ob: Fix org-babel-edit-distance for insertion/deletion
[org-mode.git] / lisp / org.el
blobc4a006ba3ad1b69545d22c3dba42482cedd5c07a
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" ())
121 (declare-function org-clock-timestamps-down "org-clock" ())
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)
4960 (require 'ob-table)
4961 (require 'ob-lob)
4962 (require 'ob-ref)
4963 (require 'ob-tangle)
4964 (require 'ob-comint)
4965 (require 'ob-keys)
4967 ;;;###autoload
4968 (define-derived-mode org-mode outline-mode "Org"
4969 "Outline-based notes management and organizer, alias
4970 \"Carsten's outline-mode for keeping track of everything.\"
4972 Org-mode develops organizational tasks around a NOTES file which
4973 contains information about projects as plain text. Org-mode is
4974 implemented on top of outline-mode, which is ideal to keep the content
4975 of large files well structured. It supports ToDo items, deadlines and
4976 time stamps, which magically appear in the diary listing of the Emacs
4977 calendar. Tables are easily created with a built-in table editor.
4978 Plain text URL-like links connect to websites, emails (VM), Usenet
4979 messages (Gnus), BBDB entries, and any files related to the project.
4980 For printing and sharing of notes, an Org-mode file (or a part of it)
4981 can be exported as a structured ASCII or HTML file.
4983 The following commands are available:
4985 \\{org-mode-map}"
4987 ;; Get rid of Outline menus, they are not needed
4988 ;; Need to do this here because define-derived-mode sets up
4989 ;; the keymap so late. Still, it is a waste to call this each time
4990 ;; we switch another buffer into org-mode.
4991 (if (featurep 'xemacs)
4992 (when (boundp 'outline-mode-menu-heading)
4993 ;; Assume this is Greg's port, it uses easymenu
4994 (easy-menu-remove outline-mode-menu-heading)
4995 (easy-menu-remove outline-mode-menu-show)
4996 (easy-menu-remove outline-mode-menu-hide))
4997 (define-key org-mode-map [menu-bar headings] 'undefined)
4998 (define-key org-mode-map [menu-bar hide] 'undefined)
4999 (define-key org-mode-map [menu-bar show] 'undefined))
5001 (org-load-modules-maybe)
5002 (easy-menu-add org-org-menu)
5003 (easy-menu-add org-tbl-menu)
5004 (org-install-agenda-files-menu)
5005 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5006 (add-to-invisibility-spec '(org-cwidth))
5007 (add-to-invisibility-spec '(org-hide-block . t))
5008 (when (featurep 'xemacs)
5009 (org-set-local 'line-move-ignore-invisible t))
5010 (org-set-local 'outline-regexp org-outline-regexp)
5011 (org-set-local 'outline-level 'org-outline-level)
5012 (setq bidi-paragraph-direction 'left-to-right)
5013 (when (and org-ellipsis
5014 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5015 (fboundp 'make-glyph-code))
5016 (unless org-display-table
5017 (setq org-display-table (make-display-table)))
5018 (set-display-table-slot
5019 org-display-table 4
5020 (vconcat (mapcar
5021 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5022 org-ellipsis)))
5023 (if (stringp org-ellipsis) org-ellipsis "..."))))
5024 (setq buffer-display-table org-display-table))
5025 (org-set-regexps-and-options)
5026 (when (and org-tag-faces (not org-tags-special-faces-re))
5027 ;; tag faces set outside customize.... force initialization.
5028 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5029 ;; Calc embedded
5030 (org-set-local 'calc-embedded-open-mode "# ")
5031 (modify-syntax-entry ?@ "w")
5032 (modify-syntax-entry ?\" "\"")
5033 (if org-startup-truncated (setq truncate-lines t))
5034 (org-set-local 'font-lock-unfontify-region-function
5035 'org-unfontify-region)
5036 ;; Activate before-change-function
5037 (org-set-local 'org-table-may-need-update t)
5038 (org-add-hook 'before-change-functions 'org-before-change-function nil
5039 'local)
5040 ;; Check for running clock before killing a buffer
5041 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5042 ;; Initialize macros templates.
5043 (org-macro-initialize-templates)
5044 ;; Initialize radio targets.
5045 (org-update-radio-target-regexp)
5046 ;; Indentation.
5047 (org-set-local 'indent-line-function 'org-indent-line)
5048 (org-set-local 'indent-region-function 'org-indent-region)
5049 ;; Filling and auto-filling.
5050 (org-setup-filling)
5051 ;; Comments.
5052 (org-setup-comments-handling)
5053 ;; Beginning/end of defun
5054 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5055 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5056 ;; Next error for sparse trees
5057 (org-set-local 'next-error-function 'org-occur-next-match)
5058 ;; Make sure dependence stuff works reliably, even for users who set it
5059 ;; too late :-(
5060 (if org-enforce-todo-dependencies
5061 (add-hook 'org-blocker-hook
5062 'org-block-todo-from-children-or-siblings-or-parent)
5063 (remove-hook 'org-blocker-hook
5064 'org-block-todo-from-children-or-siblings-or-parent))
5065 (if org-enforce-todo-checkbox-dependencies
5066 (add-hook 'org-blocker-hook
5067 'org-block-todo-from-checkboxes)
5068 (remove-hook 'org-blocker-hook
5069 'org-block-todo-from-checkboxes))
5071 ;; Align options lines
5072 (org-set-local
5073 'align-mode-rules-list
5074 '((org-in-buffer-settings
5075 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5076 (modes . '(org-mode)))))
5078 ;; Imenu
5079 (org-set-local 'imenu-create-index-function
5080 'org-imenu-get-tree)
5082 ;; Make isearch reveal context
5083 (if (or (featurep 'xemacs)
5084 (not (boundp 'outline-isearch-open-invisible-function)))
5085 ;; Emacs 21 and XEmacs make use of the hook
5086 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5087 ;; Emacs 22 deals with this through a special variable
5088 (org-set-local 'outline-isearch-open-invisible-function
5089 (lambda (&rest ignore) (org-show-context 'isearch))))
5091 ;; Turn on org-beamer-mode?
5092 (and org-startup-with-beamer-mode (org-beamer-mode))
5094 ;; Setup the pcomplete hooks
5095 (set (make-local-variable 'pcomplete-command-completion-function)
5096 'org-pcomplete-initial)
5097 (set (make-local-variable 'pcomplete-command-name-function)
5098 'org-command-at-point)
5099 (set (make-local-variable 'pcomplete-default-completion-function)
5100 'ignore)
5101 (set (make-local-variable 'pcomplete-parse-arguments-function)
5102 'org-parse-arguments)
5103 (set (make-local-variable 'pcomplete-termination-string) "")
5104 (when (>= emacs-major-version 23)
5105 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5107 ;; If empty file that did not turn on org-mode automatically, make it to.
5108 (if (and org-insert-mode-line-in-empty-file
5109 (org-called-interactively-p 'any)
5110 (= (point-min) (point-max)))
5111 (insert "# -*- mode: org -*-\n\n"))
5112 (unless org-inhibit-startup
5113 (when org-startup-align-all-tables
5114 (let ((bmp (buffer-modified-p)))
5115 (org-table-map-tables 'org-table-align 'quietly)
5116 (set-buffer-modified-p bmp)))
5117 (when org-startup-with-inline-images
5118 (org-display-inline-images))
5119 (when org-startup-indented
5120 (require 'org-indent)
5121 (org-indent-mode 1))
5122 (unless org-inhibit-startup-visibility-stuff
5123 (org-set-startup-visibility)))
5124 ;; Try to set org-hide correctly
5125 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5127 (when (fboundp 'abbrev-table-put)
5128 (abbrev-table-put org-mode-abbrev-table
5129 :parents (list text-mode-abbrev-table)))
5131 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5134 (defun org-find-invisible-foreground ()
5135 (let ((candidates (remove
5136 "unspecified-bg"
5137 (list
5138 (face-background 'default)
5139 (face-background 'org-default)
5140 (cdr (assoc 'background-color default-frame-alist))
5141 (cdr (assoc 'background-color initial-frame-alist))
5142 (cdr (assoc 'background-color window-system-default-frame-alist))
5143 (face-foreground 'org-hide)))))
5144 (car (remove nil candidates))))
5146 (defun org-current-time ()
5147 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5148 (if (> (car org-time-stamp-rounding-minutes) 1)
5149 (let ((r (car org-time-stamp-rounding-minutes))
5150 (time (decode-time)))
5151 (apply 'encode-time
5152 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5153 (nthcdr 2 time))))
5154 (current-time)))
5156 (defun org-today ()
5157 "Return today date, considering `org-extend-today-until'."
5158 (time-to-days
5159 (time-subtract (current-time)
5160 (list 0 (* 3600 org-extend-today-until) 0))))
5162 ;;;; Font-Lock stuff, including the activators
5164 (defvar org-mouse-map (make-sparse-keymap))
5165 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5166 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5167 (when org-mouse-1-follows-link
5168 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5169 (when org-tab-follows-link
5170 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5171 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5173 (require 'font-lock)
5175 (defconst org-non-link-chars "]\t\n\r<>")
5176 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5177 "shell" "elisp" "doi" "message"))
5178 (defvar org-link-types-re nil
5179 "Matches a link that has a url-like prefix like \"http:\"")
5180 (defvar org-link-re-with-space nil
5181 "Matches a link with spaces, optional angular brackets around it.")
5182 (defvar org-link-re-with-space2 nil
5183 "Matches a link with spaces, optional angular brackets around it.")
5184 (defvar org-link-re-with-space3 nil
5185 "Matches a link with spaces, only for internal part in bracket links.")
5186 (defvar org-angle-link-re nil
5187 "Matches link with angular brackets, spaces are allowed.")
5188 (defvar org-plain-link-re nil
5189 "Matches plain link, without spaces.")
5190 (defvar org-bracket-link-regexp nil
5191 "Matches a link in double brackets.")
5192 (defvar org-bracket-link-analytic-regexp nil
5193 "Regular expression used to analyze links.
5194 Here is what the match groups contain after a match:
5195 1: http:
5196 2: http
5197 3: path
5198 4: [desc]
5199 5: desc")
5200 (defvar org-bracket-link-analytic-regexp++ nil
5201 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5202 (defvar org-any-link-re nil
5203 "Regular expression matching any link.")
5205 (defcustom org-match-sexp-depth 3
5206 "Number of stacked braces for sub/superscript matching.
5207 This has to be set before loading org.el to be effective."
5208 :group 'org-export-translation ; ??????????????????????????/
5209 :type 'integer)
5211 (defun org-create-multibrace-regexp (left right n)
5212 "Create a regular expression which will match a balanced sexp.
5213 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5214 as single character strings.
5215 The regexp returned will match the entire expression including the
5216 delimiters. It will also define a single group which contains the
5217 match except for the outermost delimiters. The maximum depth of
5218 stacked delimiters is N. Escaping delimiters is not possible."
5219 (let* ((nothing (concat "[^" left right "]*?"))
5220 (or "\\|")
5221 (re nothing)
5222 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5223 (while (> n 1)
5224 (setq n (1- n)
5225 re (concat re or next)
5226 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5227 (concat left "\\(" re "\\)" right)))
5229 (defvar org-match-substring-regexp
5230 (concat
5231 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5232 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5233 "\\|"
5234 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5235 "\\|"
5236 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5237 "The regular expression matching a sub- or superscript.")
5239 (defvar org-match-substring-with-braces-regexp
5240 (concat
5241 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5242 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5243 "\\)")
5244 "The regular expression matching a sub- or superscript, forcing braces.")
5246 (defun org-make-link-regexps ()
5247 "Update the link regular expressions.
5248 This should be called after the variable `org-link-types' has changed."
5249 (setq org-link-types-re
5250 (concat
5251 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5252 org-link-re-with-space
5253 (concat
5254 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5255 "\\([^" org-non-link-chars " ]"
5256 "[^" org-non-link-chars "]*"
5257 "[^" org-non-link-chars " ]\\)>?")
5258 org-link-re-with-space2
5259 (concat
5260 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5261 "\\([^" org-non-link-chars " ]"
5262 "[^\t\n\r]*"
5263 "[^" org-non-link-chars " ]\\)>?")
5264 org-link-re-with-space3
5265 (concat
5266 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5267 "\\([^" org-non-link-chars " ]"
5268 "[^\t\n\r]*\\)")
5269 org-angle-link-re
5270 (concat
5271 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5272 "\\([^" org-non-link-chars " ]"
5273 "[^" org-non-link-chars "]*"
5274 "\\)>")
5275 org-plain-link-re
5276 (concat
5277 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5278 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5279 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5280 org-bracket-link-regexp
5281 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5282 org-bracket-link-analytic-regexp
5283 (concat
5284 "\\[\\["
5285 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5286 "\\([^]]+\\)"
5287 "\\]"
5288 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5289 "\\]")
5290 org-bracket-link-analytic-regexp++
5291 (concat
5292 "\\[\\["
5293 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5294 "\\([^]]+\\)"
5295 "\\]"
5296 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5297 "\\]")
5298 org-any-link-re
5299 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5300 org-angle-link-re "\\)\\|\\("
5301 org-plain-link-re "\\)")))
5303 (org-make-link-regexps)
5305 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5306 "Regular expression for fast time stamp matching.")
5307 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5308 "Regular expression for fast time stamp matching.")
5309 (defconst org-ts-regexp0
5310 "\\(\\([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 This one does not require the space after the date, so it can be used
5313 on a string that terminates immediately after the date.")
5314 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5315 "Regular expression matching time strings for analysis.")
5316 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5317 "Regular expression matching time stamps, with groups.")
5318 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5319 "Regular expression matching time stamps (also [..]), with groups.")
5320 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5321 "Regular expression matching a time stamp range.")
5322 (defconst org-tr-regexp-both
5323 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5324 "Regular expression matching a time stamp range.")
5325 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5326 org-ts-regexp "\\)?")
5327 "Regular expression matching a time stamp or time stamp range.")
5328 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5329 org-ts-regexp-both "\\)?")
5330 "Regular expression matching a time stamp or time stamp range.
5331 The time stamps may be either active or inactive.")
5333 (defvar org-emph-face nil)
5335 (defun org-do-emphasis-faces (limit)
5336 "Run through the buffer and add overlays to emphasized strings."
5337 (let (rtn a)
5338 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5339 (if (not (= (char-after (match-beginning 3))
5340 (char-after (match-beginning 4))))
5341 (progn
5342 (setq rtn t)
5343 (setq a (assoc (match-string 3) org-emphasis-alist))
5344 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5345 'face
5346 (nth 1 a))
5347 (and (nth 4 a)
5348 (org-remove-flyspell-overlays-in
5349 (match-beginning 0) (match-end 0)))
5350 (add-text-properties (match-beginning 2) (match-end 2)
5351 '(font-lock-multiline t org-emphasis t))
5352 (when org-hide-emphasis-markers
5353 (add-text-properties (match-end 4) (match-beginning 5)
5354 '(invisible org-link))
5355 (add-text-properties (match-beginning 3) (match-end 3)
5356 '(invisible org-link)))))
5357 (backward-char 1))
5358 rtn))
5360 (defun org-emphasize (&optional char)
5361 "Insert or change an emphasis, i.e. a font like bold or italic.
5362 If there is an active region, change that region to a new emphasis.
5363 If there is no region, just insert the marker characters and position
5364 the cursor between them.
5365 CHAR should be either the marker character, or the first character of the
5366 HTML tag associated with that emphasis. If CHAR is a space, the means
5367 to remove the emphasis of the selected region.
5368 If char is not given (for example in an interactive call) it
5369 will be prompted for."
5370 (interactive)
5371 (let ((eal org-emphasis-alist) e det
5372 (erc org-emphasis-regexp-components)
5373 (prompt "")
5374 (string "") beg end move tag c s)
5375 (if (org-region-active-p)
5376 (setq beg (region-beginning) end (region-end)
5377 string (buffer-substring beg end))
5378 (setq move t))
5380 (while (setq e (pop eal))
5381 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5382 c (aref tag 0))
5383 (push (cons c (string-to-char (car e))) det)
5384 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5385 (substring tag 1)))))
5386 (setq det (nreverse det))
5387 (unless char
5388 (message "%s" (concat "Emphasis marker or tag:" prompt))
5389 (setq char (read-char-exclusive)))
5390 (setq char (or (cdr (assoc char det)) char))
5391 (if (equal char ?\ )
5392 (setq s "" move nil)
5393 (unless (assoc (char-to-string char) org-emphasis-alist)
5394 (error "No such emphasis marker: \"%c\"" char))
5395 (setq s (char-to-string char)))
5396 (while (and (> (length string) 1)
5397 (equal (substring string 0 1) (substring string -1))
5398 (assoc (substring string 0 1) org-emphasis-alist))
5399 (setq string (substring string 1 -1)))
5400 (setq string (concat s string s))
5401 (if beg (delete-region beg end))
5402 (unless (or (bolp)
5403 (string-match (concat "[" (nth 0 erc) "\n]")
5404 (char-to-string (char-before (point)))))
5405 (insert " "))
5406 (unless (or (eobp)
5407 (string-match (concat "[" (nth 1 erc) "\n]")
5408 (char-to-string (char-after (point)))))
5409 (insert " ") (backward-char 1))
5410 (insert string)
5411 (and move (backward-char 1))))
5413 (defconst org-nonsticky-props
5414 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5416 (defsubst org-rear-nonsticky-at (pos)
5417 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5419 (defun org-activate-plain-links (limit)
5420 "Run through the buffer and add overlays to links."
5421 (catch 'exit
5422 (let (f hl)
5423 (when (re-search-forward (concat org-plain-link-re) limit t)
5424 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5425 (setq f (get-text-property (match-beginning 0) 'face))
5426 (setq hl (org-match-string-no-properties 0))
5427 (if (or (eq f 'org-tag)
5428 (and (listp f) (memq 'org-tag f)))
5430 (add-text-properties (match-beginning 0) (match-end 0)
5431 (list 'mouse-face 'highlight
5432 'face 'org-link
5433 'htmlize-link `(:uri ,hl)
5434 'keymap org-mouse-map))
5435 (org-rear-nonsticky-at (match-end 0)))
5436 t))))
5438 (defun org-activate-code (limit)
5439 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5440 (progn
5441 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5442 (remove-text-properties (match-beginning 0) (match-end 0)
5443 '(display t invisible t intangible t))
5444 t)))
5446 (defcustom org-src-fontify-natively nil
5447 "When non-nil, fontify code in code blocks."
5448 :type 'boolean
5449 :version "24.1"
5450 :group 'org-appearance
5451 :group 'org-babel)
5453 (defcustom org-allow-promoting-top-level-subtree nil
5454 "When non-nil, allow promoting a top level subtree.
5455 The leading star of the top level headline will be replaced
5456 by a #."
5457 :type 'boolean
5458 :version "24.1"
5459 :group 'org-appearance)
5461 (defun org-fontify-meta-lines-and-blocks (limit)
5462 (condition-case nil
5463 (org-fontify-meta-lines-and-blocks-1 limit)
5464 (error (message "org-mode fontification error"))))
5466 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5467 "Fontify #+ lines and blocks, in the correct ways."
5468 (let ((case-fold-search t))
5469 (if (re-search-forward
5470 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5471 limit t)
5472 (let ((beg (match-beginning 0))
5473 (block-start (match-end 0))
5474 (block-end nil)
5475 (lang (match-string 7))
5476 (beg1 (line-beginning-position 2))
5477 (dc1 (downcase (match-string 2)))
5478 (dc3 (downcase (match-string 3)))
5479 end end1 quoting block-type ovl)
5480 (cond
5481 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5482 ;; a single line of backend-specific content
5483 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5484 (remove-text-properties (match-beginning 0) (match-end 0)
5485 '(display t invisible t intangible t))
5486 (add-text-properties (match-beginning 1) (match-end 3)
5487 '(font-lock-fontified t face org-meta-line))
5488 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5489 '(font-lock-fontified t face org-block))
5490 ; for backend-specific code
5492 ((and (match-end 4) (equal dc3 "+begin"))
5493 ;; Truly a block
5494 (setq block-type (downcase (match-string 5))
5495 quoting (member block-type org-protecting-blocks))
5496 (when (re-search-forward
5497 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5498 nil t) ;; on purpose, we look further than LIMIT
5499 (setq end (min (point-max) (match-end 0))
5500 end1 (min (point-max) (1- (match-beginning 0))))
5501 (setq block-end (match-beginning 0))
5502 (when quoting
5503 (remove-text-properties beg end
5504 '(display t invisible t intangible t)))
5505 (add-text-properties
5506 beg end
5507 '(font-lock-fontified t font-lock-multiline t))
5508 (add-text-properties beg beg1 '(face org-meta-line))
5509 (add-text-properties end1 (min (point-max) (1+ end))
5510 '(face org-meta-line)) ; for end_src
5511 (cond
5512 ((and lang (not (string= lang "")) org-src-fontify-natively)
5513 (org-src-font-lock-fontify-block lang block-start block-end)
5514 ;; remove old background overlays
5515 (mapc (lambda (ov)
5516 (if (eq (overlay-get ov 'face) 'org-block-background)
5517 (delete-overlay ov)))
5518 (overlays-at (/ (+ beg1 block-end) 2)))
5519 ;; add a background overlay
5520 (setq ovl (make-overlay beg1 block-end))
5521 (overlay-put ovl 'face 'org-block-background)
5522 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5523 (quoting
5524 (add-text-properties beg1 (min (point-max) (1+ end1))
5525 '(face org-block))) ; end of source block
5526 ((not org-fontify-quote-and-verse-blocks))
5527 ((string= block-type "quote")
5528 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5529 ((string= block-type "verse")
5530 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5531 (add-text-properties beg beg1 '(face org-block-begin-line))
5532 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5533 '(face org-block-end-line))
5535 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5536 (add-text-properties
5537 beg (match-end 3)
5538 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5539 '(font-lock-fontified t invisible t)
5540 '(font-lock-fontified t face org-document-info-keyword)))
5541 (add-text-properties
5542 (match-beginning 6) (match-end 6)
5543 (if (string-equal dc1 "+title:")
5544 '(font-lock-fontified t face org-document-title)
5545 '(font-lock-fontified t face org-document-info))))
5546 ((or (equal dc1 "+results")
5547 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5548 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5549 "+call:" "+header:" "+headers:" "+name:"))
5550 (and (match-end 4) (equal dc3 "+attr")))
5551 (add-text-properties
5552 beg (match-end 0)
5553 '(font-lock-fontified t face org-meta-line))
5555 ((member dc3 '(" " ""))
5556 (add-text-properties
5557 beg (match-end 0)
5558 '(font-lock-fontified t face font-lock-comment-face)))
5559 ((not (member (char-after beg) '(?\ ?\t)))
5560 ;; just any other in-buffer setting, but not indented
5561 (add-text-properties
5562 beg (match-end 0)
5563 '(font-lock-fontified t face org-meta-line))
5565 (t nil))))))
5567 (defun org-activate-angle-links (limit)
5568 "Run through the buffer and add overlays to links."
5569 (if (re-search-forward org-angle-link-re limit t)
5570 (progn
5571 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5572 (add-text-properties (match-beginning 0) (match-end 0)
5573 (list 'mouse-face 'highlight
5574 'keymap org-mouse-map))
5575 (org-rear-nonsticky-at (match-end 0))
5576 t)))
5578 (defun org-activate-footnote-links (limit)
5579 "Run through the buffer and add overlays to footnotes."
5580 (let ((fn (org-footnote-next-reference-or-definition limit)))
5581 (when fn
5582 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5583 (org-remove-flyspell-overlays-in beg end)
5584 (add-text-properties beg end
5585 (list 'mouse-face 'highlight
5586 'keymap org-mouse-map
5587 'help-echo
5588 (if (= (point-at-bol) beg)
5589 "Footnote definition"
5590 "Footnote reference")
5591 'font-lock-fontified t
5592 'font-lock-multiline t
5593 'face 'org-footnote))))))
5595 (defun org-activate-bracket-links (limit)
5596 "Run through the buffer and add overlays to bracketed links."
5597 (if (re-search-forward org-bracket-link-regexp limit t)
5598 (let* ((hl (org-match-string-no-properties 1))
5599 (help (concat "LINK: " hl))
5600 ;; FIXME: Above we should remove the escapes. But that
5601 ;; requires another match, protecting match data, a lot
5602 ;; of overhead for font-lock.
5603 (ip (org-maybe-intangible
5604 (list 'invisible 'org-link
5605 'keymap org-mouse-map 'mouse-face 'highlight
5606 'font-lock-multiline t 'help-echo help
5607 'htmlize-link `(:uri ,hl))))
5608 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5609 'font-lock-multiline t 'help-echo help
5610 'htmlize-link `(:uri ,hl))))
5611 ;; We need to remove the invisible property here. Table narrowing
5612 ;; may have made some of this invisible.
5613 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5614 (remove-text-properties (match-beginning 0) (match-end 0)
5615 '(invisible nil))
5616 (if (match-end 3)
5617 (progn
5618 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5619 (org-rear-nonsticky-at (match-beginning 3))
5620 (add-text-properties (match-beginning 3) (match-end 3) vp)
5621 (org-rear-nonsticky-at (match-end 3))
5622 (add-text-properties (match-end 3) (match-end 0) ip)
5623 (org-rear-nonsticky-at (match-end 0)))
5624 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5625 (org-rear-nonsticky-at (match-beginning 1))
5626 (add-text-properties (match-beginning 1) (match-end 1) vp)
5627 (org-rear-nonsticky-at (match-end 1))
5628 (add-text-properties (match-end 1) (match-end 0) ip)
5629 (org-rear-nonsticky-at (match-end 0)))
5630 t)))
5632 (defun org-activate-dates (limit)
5633 "Run through the buffer and add overlays to dates."
5634 (if (re-search-forward org-tsr-regexp-both limit t)
5635 (progn
5636 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5637 (add-text-properties (match-beginning 0) (match-end 0)
5638 (list 'mouse-face 'highlight
5639 'keymap org-mouse-map))
5640 (org-rear-nonsticky-at (match-end 0))
5641 (when org-display-custom-times
5642 (if (match-end 3)
5643 (org-display-custom-time (match-beginning 3) (match-end 3)))
5644 (org-display-custom-time (match-beginning 1) (match-end 1)))
5645 t)))
5647 (defvar org-target-link-regexp nil
5648 "Regular expression matching radio targets in plain text.")
5649 (make-variable-buffer-local 'org-target-link-regexp)
5650 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5651 "Regular expression matching a link target.")
5652 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5653 "Regular expression matching a radio target.")
5654 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5655 "Regular expression matching any target.")
5657 (defun org-activate-target-links (limit)
5658 "Run through the buffer and add overlays to target matches."
5659 (when org-target-link-regexp
5660 (let ((case-fold-search t))
5661 (if (re-search-forward org-target-link-regexp limit t)
5662 (progn
5663 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5664 (add-text-properties (match-beginning 0) (match-end 0)
5665 (list 'mouse-face 'highlight
5666 'keymap org-mouse-map
5667 'help-echo "Radio target link"
5668 'org-linked-text t))
5669 (org-rear-nonsticky-at (match-end 0))
5670 t)))))
5672 (defun org-update-radio-target-regexp ()
5673 "Find all radio targets in this file and update the regular expression."
5674 (interactive)
5675 (when (memq 'radio org-activate-links)
5676 (setq org-target-link-regexp
5677 (org-make-target-link-regexp (org-all-targets 'radio)))
5678 (org-restart-font-lock)))
5680 (defun org-hide-wide-columns (limit)
5681 (let (s e)
5682 (setq s (text-property-any (point) (or limit (point-max))
5683 'org-cwidth t))
5684 (when s
5685 (setq e (next-single-property-change s 'org-cwidth))
5686 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5687 (goto-char e)
5688 t)))
5690 (defvar org-latex-and-specials-regexp nil
5691 "Regular expression for highlighting export special stuff.")
5692 (defvar org-match-substring-regexp)
5693 (defvar org-match-substring-with-braces-regexp)
5695 ;; This should be with the exporter code, but we also use if for font-locking
5696 (defconst org-export-html-special-string-regexps
5697 '(("\\\\-" . "&shy;")
5698 ("---\\([^-]\\)" . "&mdash;\\1")
5699 ("--\\([^-]\\)" . "&ndash;\\1")
5700 ("\\.\\.\\." . "&hellip;"))
5701 "Regular expressions for special string conversion.")
5704 (defun org-compute-latex-and-specials-regexp ()
5705 "Compute regular expression for stuff treated specially by exporters."
5706 (if (not org-highlight-latex-fragments-and-specials)
5707 (org-set-local 'org-latex-and-specials-regexp nil)
5708 (require 'org-exp)
5709 (let*
5710 ((matchers (plist-get org-format-latex-options :matchers))
5711 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5712 org-latex-regexps)))
5713 (org-export-allow-BIND nil)
5714 (options (org-combine-plists (org-default-export-plist)
5715 (org-infile-export-plist)))
5716 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5717 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5718 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5719 (org-export-html-expand (plist-get options :expand-quoted-html))
5720 (org-export-with-special-strings (plist-get options :special-strings))
5721 (re-sub
5722 (cond
5723 ((equal org-export-with-sub-superscripts '{})
5724 (list org-match-substring-with-braces-regexp))
5725 (org-export-with-sub-superscripts
5726 (list org-match-substring-regexp))))
5727 (re-latex
5728 (if org-export-with-LaTeX-fragments
5729 (mapcar (lambda (x) (nth 1 x)) latexs)))
5730 (re-macros
5731 (if org-export-with-TeX-macros
5732 (list (concat "\\\\"
5733 (regexp-opt
5734 (append
5736 (delq nil
5737 (mapcar 'car-safe
5738 (append org-entities-user
5739 org-entities)))
5740 (if (boundp 'org-latex-entities)
5741 (mapcar (lambda (x)
5742 (or (car-safe x) x))
5743 org-latex-entities)
5744 nil))
5745 'words))) ; FIXME
5747 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5748 (re-special (if org-export-with-special-strings
5749 (mapcar (lambda (x) (car x))
5750 org-export-html-special-string-regexps)))
5751 (re-rest
5752 (delq nil
5753 (list
5754 (if org-export-html-expand "@<[^>\n]+>")
5755 ))))
5756 (org-set-local
5757 'org-latex-and-specials-regexp
5758 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5759 re-rest) "\\|")))))
5761 (defun org-do-latex-and-special-faces (limit)
5762 "Run through the buffer and add overlays to links."
5763 (when org-latex-and-specials-regexp
5764 (let (rtn d)
5765 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5766 limit t))
5767 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5768 'face))
5769 '(org-code org-verbatim underline)))
5770 (progn
5771 (setq rtn t
5772 d (cond ((member (char-after (1+ (match-beginning 0)))
5773 '(?_ ?^)) 1)
5774 (t 0)))
5775 (font-lock-prepend-text-property
5776 (+ d (match-beginning 0)) (match-end 0)
5777 'face 'org-latex-and-export-specials)
5778 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5779 '(font-lock-multiline t)))))
5780 rtn)))
5782 (defun org-restart-font-lock ()
5783 "Restart `font-lock-mode', to force refontification."
5784 (when (and (boundp 'font-lock-mode) font-lock-mode)
5785 (font-lock-mode -1)
5786 (font-lock-mode 1)))
5788 (defun org-all-targets (&optional radio)
5789 "Return a list of all targets in this file.
5790 When optional argument RADIO is non-nil, only find radio
5791 targets."
5792 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5793 (save-excursion
5794 (goto-char (point-min))
5795 (while (re-search-forward re nil t)
5796 ;; Make sure point is really within the object.
5797 (backward-char)
5798 (let ((obj (org-element-context)))
5799 (when (memq (org-element-type obj) '(radio-target target))
5800 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5801 rtn)))
5803 (defun org-make-target-link-regexp (targets)
5804 "Make regular expression matching all strings in TARGETS.
5805 The regular expression finds the targets also if there is a line break
5806 between words."
5807 (and targets
5808 (concat
5809 "\\<\\("
5810 (mapconcat
5811 (lambda (x)
5812 (setq x (regexp-quote x))
5813 (while (string-match " +" x)
5814 (setq x (replace-match "\\s-+" t t x)))
5816 targets
5817 "\\|")
5818 "\\)\\>")))
5820 (defun org-activate-tags (limit)
5821 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5822 (progn
5823 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5824 (add-text-properties (match-beginning 1) (match-end 1)
5825 (list 'mouse-face 'highlight
5826 'keymap org-mouse-map))
5827 (org-rear-nonsticky-at (match-end 1))
5828 t)))
5830 (defun org-outline-level ()
5831 "Compute the outline level of the heading at point.
5832 If this is called at a normal headline, the level is the number of stars.
5833 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5834 (save-excursion
5835 (if (not (condition-case nil
5836 (org-back-to-heading t)
5837 (error nil)))
5839 (looking-at org-outline-regexp)
5840 (1- (- (match-end 0) (match-beginning 0))))))
5842 (defvar org-font-lock-keywords nil)
5844 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5845 "Regular expression matching a property line.")
5847 (defvar org-font-lock-hook nil
5848 "Functions to be called for special font lock stuff.")
5850 (defvar org-font-lock-set-keywords-hook nil
5851 "Functions that can manipulate `org-font-lock-extra-keywords'.
5852 This is called after `org-font-lock-extra-keywords' is defined, but before
5853 it is installed to be used by font lock. This can be useful if something
5854 needs to be inserted at a specific position in the font-lock sequence.")
5856 (defun org-font-lock-hook (limit)
5857 "Run `org-font-lock-hook' within LIMIT."
5858 (run-hook-with-args 'org-font-lock-hook limit))
5860 (defun org-set-font-lock-defaults ()
5861 "Set font lock defaults for the current buffer."
5862 (let* ((em org-fontify-emphasized-text)
5863 (lk org-activate-links)
5864 (org-font-lock-extra-keywords
5865 (list
5866 ;; Call the hook
5867 '(org-font-lock-hook)
5868 ;; Headlines
5869 `(,(if org-fontify-whole-heading-line
5870 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5871 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5872 (1 (org-get-level-face 1))
5873 (2 (org-get-level-face 2))
5874 (3 (org-get-level-face 3)))
5875 ;; Table lines
5876 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5877 (1 'org-table t))
5878 ;; Table internals
5879 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5880 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5881 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5882 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5883 ;; Drawers
5884 (list org-drawer-regexp '(0 'org-special-keyword t))
5885 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5886 ;; Properties
5887 (list org-property-re
5888 '(1 'org-special-keyword t)
5889 '(3 'org-property-value t))
5890 ;; Links
5891 (if (memq 'footnote lk) '(org-activate-footnote-links))
5892 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5893 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5894 (if (memq 'plain lk) '(org-activate-plain-links))
5895 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5896 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5897 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5898 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5899 '(org-hide-wide-columns (0 nil append))
5900 ;; TODO keyword
5901 (list (format org-heading-keyword-regexp-format
5902 org-todo-regexp)
5903 '(2 (org-get-todo-face 2) t))
5904 ;; DONE
5905 (if org-fontify-done-headline
5906 (list (format org-heading-keyword-regexp-format
5907 (concat
5908 "\\(?:"
5909 (mapconcat 'regexp-quote org-done-keywords "\\|")
5910 "\\)"))
5911 '(2 'org-headline-done t))
5912 nil)
5913 ;; Priorities
5914 '(org-font-lock-add-priority-faces)
5915 ;; Tags
5916 '(org-font-lock-add-tag-faces)
5917 ;; Special keywords
5918 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5919 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5920 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5921 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5922 ;; Emphasis
5923 (if em
5924 (if (featurep 'xemacs)
5925 '(org-do-emphasis-faces (0 nil append))
5926 '(org-do-emphasis-faces)))
5927 ;; Checkboxes
5928 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5929 1 'org-checkbox prepend)
5930 (if (cdr (assq 'checkbox org-list-automatic-rules))
5931 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5932 (0 (org-get-checkbox-statistics-face) t)))
5933 ;; Description list items
5934 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5935 1 'org-list-dt prepend)
5936 ;; ARCHIVEd headings
5937 (list (concat
5938 org-outline-regexp-bol
5939 "\\(.*:" org-archive-tag ":.*\\)")
5940 '(1 'org-archived prepend))
5941 ;; Specials
5942 '(org-do-latex-and-special-faces)
5943 '(org-fontify-entities)
5944 '(org-raise-scripts)
5945 ;; Code
5946 '(org-activate-code (1 'org-code t))
5947 ;; COMMENT
5948 (list (format org-heading-keyword-regexp-format
5949 (concat "\\("
5950 org-comment-string "\\|" org-quote-string
5951 "\\)"))
5952 '(2 'org-special-keyword t))
5953 ;; Blocks and meta lines
5954 '(org-fontify-meta-lines-and-blocks)
5956 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5957 (run-hooks 'org-font-lock-set-keywords-hook)
5958 ;; Now set the full font-lock-keywords
5959 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5960 (org-set-local 'font-lock-defaults
5961 '(org-font-lock-keywords t nil nil backward-paragraph))
5962 (kill-local-variable 'font-lock-keywords) nil))
5964 (defun org-toggle-pretty-entities ()
5965 "Toggle the composition display of entities as UTF8 characters."
5966 (interactive)
5967 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5968 (org-restart-font-lock)
5969 (if org-pretty-entities
5970 (message "Entities are displayed as UTF8 characters")
5971 (save-restriction
5972 (widen)
5973 (org-decompose-region (point-min) (point-max))
5974 (message "Entities are displayed plain"))))
5976 (defvar org-custom-properties-overlays nil
5977 "List of overlays used for custom properties.")
5978 (make-variable-buffer-local 'org-custom-properties-overlays)
5980 (defun org-toggle-custom-properties-visibility ()
5981 "Display or hide properties in `org-custom-properties'."
5982 (interactive)
5983 (if org-custom-properties-overlays
5984 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5985 (setq org-custom-properties-overlays nil))
5986 (unless (not org-custom-properties)
5987 (save-excursion
5988 (save-restriction
5989 (widen)
5990 (goto-char (point-min))
5991 (while (re-search-forward org-property-re nil t)
5992 (mapc (lambda(p)
5993 (when (equal p (substring (match-string 1) 1 -1))
5994 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5995 (overlay-put o 'invisible t)
5996 (overlay-put o 'org-custom-property t)
5997 (push o org-custom-properties-overlays))))
5998 org-custom-properties)))))))
6000 (defun org-fontify-entities (limit)
6001 "Find an entity to fontify."
6002 (let (ee)
6003 (when org-pretty-entities
6004 (catch 'match
6005 (while (re-search-forward
6006 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6007 limit t)
6008 (if (and (not (org-in-indented-comment-line))
6009 (setq ee (org-entity-get (match-string 1)))
6010 (= (length (nth 6 ee)) 1))
6011 (let*
6012 ((end (if (equal (match-string 2) "{}")
6013 (match-end 2)
6014 (match-end 1))))
6015 (add-text-properties
6016 (match-beginning 0) end
6017 (list 'font-lock-fontified t))
6018 (compose-region (match-beginning 0) end
6019 (nth 6 ee) nil)
6020 (backward-char 1)
6021 (throw 'match t))))
6022 nil))))
6024 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6025 "Fontify string S like in Org-mode."
6026 (with-temp-buffer
6027 (insert s)
6028 (let ((org-odd-levels-only odd-levels))
6029 (org-mode)
6030 (font-lock-fontify-buffer)
6031 (buffer-string))))
6033 (defvar org-m nil)
6034 (defvar org-l nil)
6035 (defvar org-f nil)
6036 (defun org-get-level-face (n)
6037 "Get the right face for match N in font-lock matching of headlines."
6038 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6039 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6040 (if org-cycle-level-faces
6041 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6042 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6043 (cond
6044 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6045 ((eq n 2) org-f)
6046 (t (if org-level-color-stars-only nil org-f))))
6049 (defun org-get-todo-face (kwd)
6050 "Get the right face for a TODO keyword KWD.
6051 If KWD is a number, get the corresponding match group."
6052 (if (numberp kwd) (setq kwd (match-string kwd)))
6053 (or (org-face-from-face-or-color
6054 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6055 (and (member kwd org-done-keywords) 'org-done)
6056 'org-todo))
6058 (defun org-face-from-face-or-color (context inherit face-or-color)
6059 "Create a face list that inherits INHERIT, but sets the foreground color.
6060 When FACE-OR-COLOR is not a string, just return it."
6061 (if (stringp face-or-color)
6062 (list :inherit inherit
6063 (cdr (assoc context org-faces-easy-properties))
6064 face-or-color)
6065 face-or-color))
6067 (defun org-font-lock-add-tag-faces (limit)
6068 "Add the special tag faces."
6069 (when (and org-tag-faces org-tags-special-faces-re)
6070 (while (re-search-forward org-tags-special-faces-re limit t)
6071 (add-text-properties (match-beginning 1) (match-end 1)
6072 (list 'face (org-get-tag-face 1)
6073 'font-lock-fontified t))
6074 (backward-char 1))))
6076 (defun org-font-lock-add-priority-faces (limit)
6077 "Add the special priority faces."
6078 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6079 (when (save-match-data (org-at-heading-p))
6080 (add-text-properties
6081 (match-beginning 0) (match-end 0)
6082 (list 'face (or (org-face-from-face-or-color
6083 'priority 'org-special-keyword
6084 (cdr (assoc (char-after (match-beginning 1))
6085 org-priority-faces)))
6086 'org-special-keyword)
6087 'font-lock-fontified t)))))
6089 (defun org-get-tag-face (kwd)
6090 "Get the right face for a TODO keyword KWD.
6091 If KWD is a number, get the corresponding match group."
6092 (if (numberp kwd) (setq kwd (match-string kwd)))
6093 (or (org-face-from-face-or-color
6094 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6095 'org-tag))
6097 (defun org-unfontify-region (beg end &optional maybe_loudly)
6098 "Remove fontification and activation overlays from links."
6099 (font-lock-default-unfontify-region beg end)
6100 (let* ((buffer-undo-list t)
6101 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6102 (inhibit-modification-hooks t)
6103 deactivate-mark buffer-file-name buffer-file-truename)
6104 (org-decompose-region beg end)
6105 (remove-text-properties beg end
6106 '(mouse-face t keymap t org-linked-text t
6107 invisible t intangible t
6108 org-no-flyspell t org-emphasis t))
6109 (org-remove-font-lock-display-properties beg end)))
6111 (defconst org-script-display '(((raise -0.3) (height 0.7))
6112 ((raise 0.3) (height 0.7))
6113 ((raise -0.5))
6114 ((raise 0.5)))
6115 "Display properties for showing superscripts and subscripts.")
6117 (defun org-remove-font-lock-display-properties (beg end)
6118 "Remove specific display properties that have been added by font lock.
6119 The will remove the raise properties that are used to show superscripts
6120 and subscripts."
6121 (let (next prop)
6122 (while (< beg end)
6123 (setq next (next-single-property-change beg 'display nil end)
6124 prop (get-text-property beg 'display))
6125 (if (member prop org-script-display)
6126 (put-text-property beg next 'display nil))
6127 (setq beg next))))
6129 (defun org-raise-scripts (limit)
6130 "Add raise properties to sub/superscripts."
6131 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6132 (if (re-search-forward
6133 (if (eq org-use-sub-superscripts t)
6134 org-match-substring-regexp
6135 org-match-substring-with-braces-regexp)
6136 limit t)
6137 (let* ((pos (point)) table-p comment-p
6138 (mpos (match-beginning 3))
6139 (emph-p (get-text-property mpos 'org-emphasis))
6140 (link-p (get-text-property mpos 'mouse-face))
6141 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6142 (goto-char (point-at-bol))
6143 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6144 comment-p (org-looking-at-p "[ \t]*#"))
6145 (goto-char pos)
6146 ;; FIXME: Should we go back one character here, for a_b^c
6147 ;; (goto-char (1- pos)) ;????????????????????
6148 (if (or comment-p emph-p link-p keyw-p)
6150 (put-text-property (match-beginning 3) (match-end 0)
6151 'display
6152 (if (equal (char-after (match-beginning 2)) ?^)
6153 (nth (if table-p 3 1) org-script-display)
6154 (nth (if table-p 2 0) org-script-display)))
6155 (add-text-properties (match-beginning 2) (match-end 2)
6156 (list 'invisible t
6157 'org-dwidth t 'org-dwidth-n 1))
6158 (if (and (eq (char-after (match-beginning 3)) ?{)
6159 (eq (char-before (match-end 3)) ?}))
6160 (progn
6161 (add-text-properties
6162 (match-beginning 3) (1+ (match-beginning 3))
6163 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6164 (add-text-properties
6165 (1- (match-end 3)) (match-end 3)
6166 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6167 t)))))
6169 ;;;; Visibility cycling, including org-goto and indirect buffer
6171 ;;; Cycling
6173 (defvar org-cycle-global-status nil)
6174 (make-variable-buffer-local 'org-cycle-global-status)
6175 (defvar org-cycle-subtree-status nil)
6176 (make-variable-buffer-local 'org-cycle-subtree-status)
6178 (defvar org-inlinetask-min-level)
6180 ;;;###autoload
6181 (defun org-cycle (&optional arg)
6182 "TAB-action and visibility cycling for Org-mode.
6184 This is the command invoked in Org-mode by the TAB key. Its main purpose
6185 is outline visibility cycling, but it also invokes other actions
6186 in special contexts.
6188 - When this function is called with a prefix argument, rotate the entire
6189 buffer through 3 states (global cycling)
6190 1. OVERVIEW: Show only top-level headlines.
6191 2. CONTENTS: Show all headlines of all levels, but no body text.
6192 3. SHOW ALL: Show everything.
6193 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6194 determined by the variable `org-startup-folded', and by any VISIBILITY
6195 properties in the buffer.
6196 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6197 including any drawers.
6199 - When inside a table, re-align the table and move to the next field.
6201 - When point is at the beginning of a headline, rotate the subtree started
6202 by this line through 3 different states (local cycling)
6203 1. FOLDED: Only the main headline is shown.
6204 2. CHILDREN: The main headline and the direct children are shown.
6205 From this state, you can move to one of the children
6206 and zoom in further.
6207 3. SUBTREE: Show the entire subtree, including body text.
6208 If there is no subtree, switch directly from CHILDREN to FOLDED.
6210 - When point is at the beginning of an empty headline and the variable
6211 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6212 of the headline by demoting and promoting it to likely levels. This
6213 speeds up creation document structure by pressing TAB once or several
6214 times right after creating a new headline.
6216 - When there is a numeric prefix, go up to a heading with level ARG, do
6217 a `show-subtree' and return to the previous cursor position. If ARG
6218 is negative, go up that many levels.
6220 - When point is not at the beginning of a headline, execute the global
6221 binding for TAB, which is re-indenting the line. See the option
6222 `org-cycle-emulate-tab' for details.
6224 - Special case: if point is at the beginning of the buffer and there is
6225 no headline in line 1, this function will act as if called with prefix arg
6226 (C-u TAB, same as S-TAB) also when called without prefix arg.
6227 But only if also the variable `org-cycle-global-at-bob' is t."
6228 (interactive "P")
6229 (org-load-modules-maybe)
6230 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6231 (and org-cycle-level-after-item/entry-creation
6232 (or (org-cycle-level)
6233 (org-cycle-item-indentation))))
6234 (let* ((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 ((ga (string-match "\\*fontification" (buffer-name))))
6350 (cond
6351 ((and (eq last-command this-command)
6352 (eq org-cycle-global-status 'overview))
6353 ;; We just created the overview - now do table of contents
6354 ;; This can be slow in very large buffers, so indicate action
6355 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6356 (unless ga (message "CONTENTS..."))
6357 (org-content)
6358 (unless ga (message "CONTENTS...done"))
6359 (setq org-cycle-global-status 'contents)
6360 (run-hook-with-args 'org-cycle-hook 'contents))
6362 ((and (eq last-command this-command)
6363 (eq org-cycle-global-status 'contents))
6364 ;; We just showed the table of contents - now show everything
6365 (run-hook-with-args 'org-pre-cycle-hook 'all)
6366 (show-all)
6367 (unless ga (message "SHOW ALL"))
6368 (setq org-cycle-global-status 'all)
6369 (run-hook-with-args 'org-cycle-hook 'all))
6372 ;; Default action: go to overview
6373 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6374 (org-overview)
6375 (unless ga (message "OVERVIEW"))
6376 (setq org-cycle-global-status 'overview)
6377 (run-hook-with-args 'org-cycle-hook 'overview)))))
6379 (defun org-cycle-internal-local ()
6380 "Do the local cycling action."
6381 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6382 ;; First, determine end of headline (EOH), end of subtree or item
6383 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6384 (save-excursion
6385 (if (org-at-item-p)
6386 (progn
6387 (beginning-of-line)
6388 (setq struct (org-list-struct))
6389 (setq eoh (point-at-eol))
6390 (setq eos (org-list-get-item-end-before-blank (point) struct))
6391 (setq has-children (org-list-has-child-p (point) struct)))
6392 (org-back-to-heading)
6393 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6394 (setq eos (save-excursion
6395 (org-end-of-subtree t)
6396 (unless (eobp)
6397 (skip-chars-forward " \t\n"))
6398 (if (eobp) (point) (1- (point)))))
6399 (setq has-children
6400 (or (save-excursion
6401 (let ((level (funcall outline-level)))
6402 (outline-next-heading)
6403 (and (org-at-heading-p t)
6404 (> (funcall outline-level) level))))
6405 (save-excursion
6406 (org-list-search-forward (org-item-beginning-re) eos t)))))
6407 ;; Determine end invisible part of buffer (EOL)
6408 (beginning-of-line 2)
6409 ;; XEmacs doesn't have `next-single-char-property-change'
6410 (if (featurep 'xemacs)
6411 (while (and (not (eobp)) ;; this is like `next-line'
6412 (get-char-property (1- (point)) 'invisible))
6413 (beginning-of-line 2))
6414 (while (and (not (eobp)) ;; this is like `next-line'
6415 (get-char-property (1- (point)) 'invisible))
6416 (goto-char (next-single-char-property-change (point) 'invisible))
6417 (and (eolp) (beginning-of-line 2))))
6418 (setq eol (point)))
6419 ;; Find out what to do next and set `this-command'
6420 (cond
6421 ((= eos eoh)
6422 ;; Nothing is hidden behind this heading
6423 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6424 (message "EMPTY ENTRY")
6425 (setq org-cycle-subtree-status nil)
6426 (save-excursion
6427 (goto-char eos)
6428 (outline-next-heading)
6429 (if (outline-invisible-p) (org-flag-heading nil))))
6430 ((and (or (>= eol eos)
6431 (not (string-match "\\S-" (buffer-substring eol eos))))
6432 (or has-children
6433 (not (setq children-skipped
6434 org-cycle-skip-children-state-if-no-children))))
6435 ;; Entire subtree is hidden in one line: children view
6436 (run-hook-with-args 'org-pre-cycle-hook 'children)
6437 (if (org-at-item-p)
6438 (org-list-set-item-visibility (point-at-bol) struct 'children)
6439 (org-show-entry)
6440 (org-with-limited-levels (show-children))
6441 ;; FIXME: This slows down the func way too much.
6442 ;; How keep drawers hidden in subtree anyway?
6443 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6444 ;; (org-cycle-hide-drawers 'subtree))
6446 ;; Fold every list in subtree to top-level items.
6447 (when (eq org-cycle-include-plain-lists 'integrate)
6448 (save-excursion
6449 (org-back-to-heading)
6450 (while (org-list-search-forward (org-item-beginning-re) eos t)
6451 (beginning-of-line 1)
6452 (let* ((struct (org-list-struct))
6453 (prevs (org-list-prevs-alist struct))
6454 (end (org-list-get-bottom-point struct)))
6455 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6456 (org-list-get-all-items (point) struct prevs))
6457 (goto-char end))))))
6458 (message "CHILDREN")
6459 (save-excursion
6460 (goto-char eos)
6461 (outline-next-heading)
6462 (if (outline-invisible-p) (org-flag-heading nil)))
6463 (setq org-cycle-subtree-status 'children)
6464 (run-hook-with-args 'org-cycle-hook 'children))
6465 ((or children-skipped
6466 (and (eq last-command this-command)
6467 (eq org-cycle-subtree-status 'children)))
6468 ;; We just showed the children, or no children are there,
6469 ;; now show everything.
6470 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6471 (outline-flag-region eoh eos nil)
6472 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6473 (setq org-cycle-subtree-status 'subtree)
6474 (run-hook-with-args 'org-cycle-hook 'subtree))
6476 ;; Default action: hide the subtree.
6477 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6478 (outline-flag-region eoh eos t)
6479 (message "FOLDED")
6480 (setq org-cycle-subtree-status 'folded)
6481 (run-hook-with-args 'org-cycle-hook 'folded)))))
6483 ;;;###autoload
6484 (defun org-global-cycle (&optional arg)
6485 "Cycle the global visibility. For details see `org-cycle'.
6486 With \\[universal-argument] prefix arg, switch to startup visibility.
6487 With a numeric prefix, show all headlines up to that level."
6488 (interactive "P")
6489 (let ((org-cycle-include-plain-lists
6490 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6491 (cond
6492 ((integerp arg)
6493 (show-all)
6494 (hide-sublevels arg)
6495 (setq org-cycle-global-status 'contents))
6496 ((equal arg '(4))
6497 (org-set-startup-visibility)
6498 (message "Startup visibility, plus VISIBILITY properties."))
6500 (org-cycle '(4))))))
6502 (defun org-set-startup-visibility ()
6503 "Set the visibility required by startup options and properties."
6504 (cond
6505 ((eq org-startup-folded t)
6506 (org-cycle '(4)))
6507 ((eq org-startup-folded 'content)
6508 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6509 (org-cycle '(4)) (org-cycle '(4)))))
6510 (unless (eq org-startup-folded 'showeverything)
6511 (if org-hide-block-startup (org-hide-block-all))
6512 (org-set-visibility-according-to-property 'no-cleanup)
6513 (org-cycle-hide-archived-subtrees 'all)
6514 (org-cycle-hide-drawers 'all)
6515 (org-cycle-show-empty-lines t)))
6517 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6518 "Switch subtree visibilities according to :VISIBILITY: property."
6519 (interactive)
6520 (let (org-show-entry-below state)
6521 (save-excursion
6522 (goto-char (point-min))
6523 (while (re-search-forward
6524 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6525 nil t)
6526 (setq state (match-string 1))
6527 (save-excursion
6528 (org-back-to-heading t)
6529 (hide-subtree)
6530 (org-reveal)
6531 (cond
6532 ((equal state '("fold" "folded"))
6533 (hide-subtree))
6534 ((equal state "children")
6535 (org-show-hidden-entry)
6536 (show-children))
6537 ((equal state "content")
6538 (save-excursion
6539 (save-restriction
6540 (org-narrow-to-subtree)
6541 (org-content))))
6542 ((member state '("all" "showall"))
6543 (show-subtree)))))
6544 (unless no-cleanup
6545 (org-cycle-hide-archived-subtrees 'all)
6546 (org-cycle-hide-drawers 'all)
6547 (org-cycle-show-empty-lines 'all)))))
6549 ;; This function uses outline-regexp instead of the more fundamental
6550 ;; org-outline-regexp so that org-cycle-global works outside of Org
6551 ;; buffers, where outline-regexp is needed.
6552 (defun org-overview ()
6553 "Switch to overview mode, showing only top-level headlines.
6554 Really, this shows all headlines with level equal or greater than the level
6555 of the first headline in the buffer. This is important, because if the
6556 first headline is not level one, then (hide-sublevels 1) gives confusing
6557 results."
6558 (interactive)
6559 (let ((level (save-excursion
6560 (goto-char (point-min))
6561 (if (re-search-forward (concat "^" outline-regexp) nil t)
6562 (progn
6563 (goto-char (match-beginning 0))
6564 (funcall outline-level))))))
6565 (and level (hide-sublevels level))))
6567 (defun org-content (&optional arg)
6568 "Show all headlines in the buffer, like a table of contents.
6569 With numerical argument N, show content up to level N."
6570 (interactive "P")
6571 (save-excursion
6572 ;; Visit all headings and show their offspring
6573 (and (integerp arg) (org-overview))
6574 (goto-char (point-max))
6575 (catch 'exit
6576 (while (and (progn (condition-case nil
6577 (outline-previous-visible-heading 1)
6578 (error (goto-char (point-min))))
6580 (looking-at org-outline-regexp))
6581 (if (integerp arg)
6582 (show-children (1- arg))
6583 (show-branches))
6584 (if (bobp) (throw 'exit nil))))))
6587 (defun org-optimize-window-after-visibility-change (state)
6588 "Adjust the window after a change in outline visibility.
6589 This function is the default value of the hook `org-cycle-hook'."
6590 (when (get-buffer-window (current-buffer))
6591 (cond
6592 ((eq state 'content) nil)
6593 ((eq state 'all) nil)
6594 ((eq state 'folded) nil)
6595 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6596 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6598 (defun org-remove-empty-overlays-at (pos)
6599 "Remove outline overlays that do not contain non-white stuff."
6600 (mapc
6601 (lambda (o)
6602 (and (eq 'outline (overlay-get o 'invisible))
6603 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6604 (overlay-end o))))
6605 (delete-overlay o)))
6606 (overlays-at pos)))
6608 (defun org-clean-visibility-after-subtree-move ()
6609 "Fix visibility issues after moving a subtree."
6610 ;; First, find a reasonable region to look at:
6611 ;; Start two siblings above, end three below
6612 (let* ((beg (save-excursion
6613 (and (org-get-last-sibling)
6614 (org-get-last-sibling))
6615 (point)))
6616 (end (save-excursion
6617 (and (org-get-next-sibling)
6618 (org-get-next-sibling)
6619 (org-get-next-sibling))
6620 (if (org-at-heading-p)
6621 (point-at-eol)
6622 (point))))
6623 (level (looking-at "\\*+"))
6624 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6625 (save-excursion
6626 (save-restriction
6627 (narrow-to-region beg end)
6628 (when re
6629 ;; Properly fold already folded siblings
6630 (goto-char (point-min))
6631 (while (re-search-forward re nil t)
6632 (if (and (not (outline-invisible-p))
6633 (save-excursion
6634 (goto-char (point-at-eol)) (outline-invisible-p)))
6635 (hide-entry))))
6636 (org-cycle-show-empty-lines 'overview)
6637 (org-cycle-hide-drawers 'overview)))))
6639 (defun org-cycle-show-empty-lines (state)
6640 "Show empty lines above all visible headlines.
6641 The region to be covered depends on STATE when called through
6642 `org-cycle-hook'. Lisp program can use t for STATE to get the
6643 entire buffer covered. Note that an empty line is only shown if there
6644 are at least `org-cycle-separator-lines' empty lines before the headline."
6645 (when (not (= org-cycle-separator-lines 0))
6646 (save-excursion
6647 (let* ((n (abs org-cycle-separator-lines))
6648 (re (cond
6649 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6650 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6651 (t (let ((ns (number-to-string (- n 2))))
6652 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6653 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6654 beg end b e)
6655 (cond
6656 ((memq state '(overview contents t))
6657 (setq beg (point-min) end (point-max)))
6658 ((memq state '(children folded))
6659 (setq beg (point) end (progn (org-end-of-subtree t t)
6660 (beginning-of-line 2)
6661 (point)))))
6662 (when beg
6663 (goto-char beg)
6664 (while (re-search-forward re end t)
6665 (unless (get-char-property (match-end 1) 'invisible)
6666 (setq e (match-end 1))
6667 (if (< org-cycle-separator-lines 0)
6668 (setq b (save-excursion
6669 (goto-char (match-beginning 0))
6670 (org-back-over-empty-lines)
6671 (if (save-excursion
6672 (goto-char (max (point-min) (1- (point))))
6673 (org-at-heading-p))
6674 (1- (point))
6675 (point))))
6676 (setq b (match-beginning 1)))
6677 (outline-flag-region b e nil)))))))
6678 ;; Never hide empty lines at the end of the file.
6679 (save-excursion
6680 (goto-char (point-max))
6681 (outline-previous-heading)
6682 (outline-end-of-heading)
6683 (if (and (looking-at "[ \t\n]+")
6684 (= (match-end 0) (point-max)))
6685 (outline-flag-region (point) (match-end 0) nil))))
6687 (defun org-show-empty-lines-in-parent ()
6688 "Move to the parent and re-show empty lines before visible headlines."
6689 (save-excursion
6690 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6691 (org-cycle-show-empty-lines context))))
6693 (defun org-files-list ()
6694 "Return `org-agenda-files' list, plus all open org-mode files.
6695 This is useful for operations that need to scan all of a user's
6696 open and agenda-wise Org files."
6697 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6698 (dolist (buf (buffer-list))
6699 (with-current-buffer buf
6700 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6701 (let ((file (expand-file-name (buffer-file-name))))
6702 (unless (member file files)
6703 (push file files))))))
6704 files))
6706 (defsubst org-entry-beginning-position ()
6707 "Return the beginning position of the current entry."
6708 (save-excursion (outline-back-to-heading t) (point)))
6710 (defsubst org-entry-end-position ()
6711 "Return the end position of the current entry."
6712 (save-excursion (outline-next-heading) (point)))
6714 (defun org-cycle-hide-drawers (state)
6715 "Re-hide all drawers after a visibility state change."
6716 (when (and (derived-mode-p 'org-mode)
6717 (not (memq state '(overview folded contents))))
6718 (save-excursion
6719 (let* ((globalp (memq state '(contents all)))
6720 (beg (if globalp (point-min) (point)))
6721 (end (if globalp (point-max)
6722 (if (eq state 'children)
6723 (save-excursion (outline-next-heading) (point))
6724 (org-end-of-subtree t)))))
6725 (goto-char beg)
6726 (while (re-search-forward org-drawer-regexp end t)
6727 (org-flag-drawer t))))))
6729 (defun org-cycle-hide-inline-tasks (state)
6730 "Re-hide inline task when switching to 'contents visibility state."
6731 (when (and (eq state 'contents)
6732 (boundp 'org-inlinetask-min-level)
6733 org-inlinetask-min-level)
6734 (hide-sublevels (1- org-inlinetask-min-level))))
6736 (defun org-flag-drawer (flag)
6737 "When FLAG is non-nil, hide the drawer we are within.
6738 Otherwise make it visible."
6739 (save-excursion
6740 (beginning-of-line 1)
6741 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6742 (let ((b (match-end 0)))
6743 (if (re-search-forward
6744 "^[ \t]*:END:"
6745 (save-excursion (outline-next-heading) (point)) t)
6746 (outline-flag-region b (point-at-eol) flag)
6747 (error ":END: line missing at position %s" b))))))
6749 (defun org-subtree-end-visible-p ()
6750 "Is the end of the current subtree visible?"
6751 (pos-visible-in-window-p
6752 (save-excursion (org-end-of-subtree t) (point))))
6754 (defun org-first-headline-recenter (&optional N)
6755 "Move cursor to the first headline and recenter the headline.
6756 Optional argument N means put the headline into the Nth line of the window."
6757 (goto-char (point-min))
6758 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6759 (beginning-of-line)
6760 (recenter (prefix-numeric-value N))))
6762 ;;; Saving and restoring visibility
6764 (defun org-outline-overlay-data (&optional use-markers)
6765 "Return a list of the locations of all outline overlays.
6766 These are overlays with the `invisible' property value `outline'.
6767 The return value is a list of cons cells, with start and stop
6768 positions for each overlay.
6769 If USE-MARKERS is set, return the positions as markers."
6770 (let (beg end)
6771 (save-excursion
6772 (save-restriction
6773 (widen)
6774 (delq nil
6775 (mapcar (lambda (o)
6776 (when (eq (overlay-get o 'invisible) 'outline)
6777 (setq beg (overlay-start o)
6778 end (overlay-end o))
6779 (and beg end (> end beg)
6780 (if use-markers
6781 (cons (move-marker (make-marker) beg)
6782 (move-marker (make-marker) end))
6783 (cons beg end)))))
6784 (overlays-in (point-min) (point-max))))))))
6786 (defun org-set-outline-overlay-data (data)
6787 "Create visibility overlays for all positions in DATA.
6788 DATA should have been made by `org-outline-overlay-data'."
6789 (let (o)
6790 (save-excursion
6791 (save-restriction
6792 (widen)
6793 (show-all)
6794 (mapc (lambda (c)
6795 (outline-flag-region (car c) (cdr c) t))
6796 data)))))
6798 ;;; Folding of blocks
6800 (defvar org-hide-block-overlays nil
6801 "Overlays hiding blocks.")
6802 (make-variable-buffer-local 'org-hide-block-overlays)
6804 (defun org-block-map (function &optional start end)
6805 "Call FUNCTION at the head of all source blocks in the current buffer.
6806 Optional arguments START and END can be used to limit the range."
6807 (let ((start (or start (point-min)))
6808 (end (or end (point-max))))
6809 (save-excursion
6810 (goto-char start)
6811 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6812 (save-excursion
6813 (save-match-data
6814 (goto-char (match-beginning 0))
6815 (funcall function)))))))
6817 (defun org-hide-block-toggle-all ()
6818 "Toggle the visibility of all blocks in the current buffer."
6819 (org-block-map #'org-hide-block-toggle))
6821 (defun org-hide-block-all ()
6822 "Fold all blocks in the current buffer."
6823 (interactive)
6824 (org-show-block-all)
6825 (org-block-map #'org-hide-block-toggle-maybe))
6827 (defun org-show-block-all ()
6828 "Unfold all blocks in the current buffer."
6829 (interactive)
6830 (mapc 'delete-overlay org-hide-block-overlays)
6831 (setq org-hide-block-overlays nil))
6833 (defun org-hide-block-toggle-maybe ()
6834 "Toggle visibility of block at point."
6835 (interactive)
6836 (let ((case-fold-search t))
6837 (if (save-excursion
6838 (beginning-of-line 1)
6839 (looking-at org-block-regexp))
6840 (progn (org-hide-block-toggle)
6841 t) ;; to signal that we took action
6842 nil))) ;; to signal that we did not
6844 (defun org-hide-block-toggle (&optional force)
6845 "Toggle the visibility of the current block."
6846 (interactive)
6847 (save-excursion
6848 (beginning-of-line)
6849 (if (re-search-forward org-block-regexp nil t)
6850 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6851 (end (match-end 0)) ;; end of entire body
6853 (if (memq t (mapcar (lambda (overlay)
6854 (eq (overlay-get overlay 'invisible)
6855 'org-hide-block))
6856 (overlays-at start)))
6857 (if (or (not force) (eq force 'off))
6858 (mapc (lambda (ov)
6859 (when (member ov org-hide-block-overlays)
6860 (setq org-hide-block-overlays
6861 (delq ov org-hide-block-overlays)))
6862 (when (eq (overlay-get ov 'invisible)
6863 'org-hide-block)
6864 (delete-overlay ov)))
6865 (overlays-at start)))
6866 (setq ov (make-overlay start end))
6867 (overlay-put ov 'invisible 'org-hide-block)
6868 ;; make the block accessible to isearch
6869 (overlay-put
6870 ov 'isearch-open-invisible
6871 (lambda (ov)
6872 (when (member ov org-hide-block-overlays)
6873 (setq org-hide-block-overlays
6874 (delq ov org-hide-block-overlays)))
6875 (when (eq (overlay-get ov 'invisible)
6876 'org-hide-block)
6877 (delete-overlay ov))))
6878 (push ov org-hide-block-overlays)))
6879 (error "Not looking at a source block"))))
6881 ;; org-tab-after-check-for-cycling-hook
6882 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6883 ;; Remove overlays when changing major mode
6884 (add-hook 'org-mode-hook
6885 (lambda () (org-add-hook 'change-major-mode-hook
6886 'org-show-block-all 'append 'local)))
6888 ;;; Org-goto
6890 (defvar org-goto-window-configuration nil)
6891 (defvar org-goto-marker nil)
6892 (defvar org-goto-map
6893 (let ((map (make-sparse-keymap)))
6894 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6895 (while (setq cmd (pop cmds))
6896 (substitute-key-definition cmd cmd map global-map)))
6897 (suppress-keymap map)
6898 (org-defkey map "\C-m" 'org-goto-ret)
6899 (org-defkey map [(return)] 'org-goto-ret)
6900 (org-defkey map [(left)] 'org-goto-left)
6901 (org-defkey map [(right)] 'org-goto-right)
6902 (org-defkey map [(control ?g)] 'org-goto-quit)
6903 (org-defkey map "\C-i" 'org-cycle)
6904 (org-defkey map [(tab)] 'org-cycle)
6905 (org-defkey map [(down)] 'outline-next-visible-heading)
6906 (org-defkey map [(up)] 'outline-previous-visible-heading)
6907 (if org-goto-auto-isearch
6908 (if (fboundp 'define-key-after)
6909 (define-key-after map [t] 'org-goto-local-auto-isearch)
6910 nil)
6911 (org-defkey map "q" 'org-goto-quit)
6912 (org-defkey map "n" 'outline-next-visible-heading)
6913 (org-defkey map "p" 'outline-previous-visible-heading)
6914 (org-defkey map "f" 'outline-forward-same-level)
6915 (org-defkey map "b" 'outline-backward-same-level)
6916 (org-defkey map "u" 'outline-up-heading))
6917 (org-defkey map "/" 'org-occur)
6918 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6919 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6920 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6921 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6922 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6923 map))
6925 (defconst org-goto-help
6926 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6927 RET=jump to location [Q]uit and return to previous location
6928 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6930 (defvar org-goto-start-pos) ; dynamically scoped parameter
6932 ;; FIXME: Docstring does not mention both interfaces
6933 (defun org-goto (&optional alternative-interface)
6934 "Look up a different location in the current file, keeping current visibility.
6936 When you want look-up or go to a different location in a
6937 document, the fastest way is often to fold the entire buffer and
6938 then dive into the tree. This method has the disadvantage, that
6939 the previous location will be folded, which may not be what you
6940 want.
6942 This command works around this by showing a copy of the current
6943 buffer in an indirect buffer, in overview mode. You can dive
6944 into the tree in that copy, use org-occur and incremental search
6945 to find a location. When pressing RET or `Q', the command
6946 returns to the original buffer in which the visibility is still
6947 unchanged. After RET it will also jump to the location selected
6948 in the indirect buffer and expose the headline hierarchy above.
6950 With a prefix argument, use the alternative interface: e.g. if
6951 `org-goto-interface' is 'outline use 'outline-path-completion."
6952 (interactive "P")
6953 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6954 (org-refile-use-outline-path t)
6955 (org-refile-target-verify-function nil)
6956 (interface
6957 (if (not alternative-interface)
6958 org-goto-interface
6959 (if (eq org-goto-interface 'outline)
6960 'outline-path-completion
6961 'outline)))
6962 (org-goto-start-pos (point))
6963 (selected-point
6964 (if (eq interface 'outline)
6965 (car (org-get-location (current-buffer) org-goto-help))
6966 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6967 (org-refile-check-position pa)
6968 (nth 3 pa)))))
6969 (if selected-point
6970 (progn
6971 (org-mark-ring-push org-goto-start-pos)
6972 (goto-char selected-point)
6973 (if (or (outline-invisible-p) (org-invisible-p2))
6974 (org-show-context 'org-goto)))
6975 (message "Quit"))))
6977 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6978 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6979 (defvar org-goto-local-auto-isearch-map) ; defined below
6981 (defun org-get-location (buf help)
6982 "Let the user select a location in the Org-mode buffer BUF.
6983 This function uses a recursive edit. It returns the selected position
6984 or nil."
6985 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6986 (isearch-hide-immediately nil)
6987 (isearch-search-fun-function
6988 (lambda () 'org-goto-local-search-headings))
6989 (org-goto-selected-point org-goto-exit-command)
6990 (pop-up-frames nil)
6991 (special-display-buffer-names nil)
6992 (special-display-regexps nil)
6993 (special-display-function nil))
6994 (save-excursion
6995 (save-window-excursion
6996 (delete-other-windows)
6997 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6998 (org-pop-to-buffer-same-window
6999 (condition-case nil
7000 (make-indirect-buffer (current-buffer) "*org-goto*")
7001 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7002 (with-output-to-temp-buffer "*Help*"
7003 (princ help))
7004 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7005 (setq buffer-read-only nil)
7006 (let ((org-startup-truncated t)
7007 (org-startup-folded nil)
7008 (org-startup-align-all-tables nil))
7009 (org-mode)
7010 (org-overview))
7011 (setq buffer-read-only t)
7012 (if (and (boundp 'org-goto-start-pos)
7013 (integer-or-marker-p org-goto-start-pos))
7014 (let ((org-show-hierarchy-above t)
7015 (org-show-siblings t)
7016 (org-show-following-heading t))
7017 (goto-char org-goto-start-pos)
7018 (and (outline-invisible-p) (org-show-context)))
7019 (goto-char (point-min)))
7020 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7021 (message "Select location and press RET")
7022 (use-local-map org-goto-map)
7023 (recursive-edit)
7025 (kill-buffer "*org-goto*")
7026 (cons org-goto-selected-point org-goto-exit-command)))
7028 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7029 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7030 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7031 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7033 (defun org-goto-local-search-headings (string bound noerror)
7034 "Search and make sure that any matches are in headlines."
7035 (catch 'return
7036 (while (if isearch-forward
7037 (search-forward string bound noerror)
7038 (search-backward string bound noerror))
7039 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7040 (and (member :headline context)
7041 (not (member :tags context))))
7042 (throw 'return (point))))))
7044 (defun org-goto-local-auto-isearch ()
7045 "Start isearch."
7046 (interactive)
7047 (goto-char (point-min))
7048 (let ((keys (this-command-keys)))
7049 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7050 (isearch-mode t)
7051 (isearch-process-search-char (string-to-char keys)))))
7053 (defun org-goto-ret (&optional arg)
7054 "Finish `org-goto' by going to the new location."
7055 (interactive "P")
7056 (setq org-goto-selected-point (point)
7057 org-goto-exit-command 'return)
7058 (throw 'exit nil))
7060 (defun org-goto-left ()
7061 "Finish `org-goto' by going to the new location."
7062 (interactive)
7063 (if (org-at-heading-p)
7064 (progn
7065 (beginning-of-line 1)
7066 (setq org-goto-selected-point (point)
7067 org-goto-exit-command 'left)
7068 (throw 'exit nil))
7069 (error "Not on a heading")))
7071 (defun org-goto-right ()
7072 "Finish `org-goto' by going to the new location."
7073 (interactive)
7074 (if (org-at-heading-p)
7075 (progn
7076 (setq org-goto-selected-point (point)
7077 org-goto-exit-command 'right)
7078 (throw 'exit nil))
7079 (error "Not on a heading")))
7081 (defun org-goto-quit ()
7082 "Finish `org-goto' without cursor motion."
7083 (interactive)
7084 (setq org-goto-selected-point nil)
7085 (setq org-goto-exit-command 'quit)
7086 (throw 'exit nil))
7088 ;;; Indirect buffer display of subtrees
7090 (defvar org-indirect-dedicated-frame nil
7091 "This is the frame being used for indirect tree display.")
7092 (defvar org-last-indirect-buffer nil)
7094 (defun org-tree-to-indirect-buffer (&optional arg)
7095 "Create indirect buffer and narrow it to current subtree.
7096 With a numerical prefix ARG, go up to this level and then take that tree.
7097 If ARG is negative, go up that many levels.
7099 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7100 indirect buffer previously made with this command, to avoid proliferation of
7101 indirect buffers. However, when you call the command with a \
7102 \\[universal-argument] prefix, or
7103 when `org-indirect-buffer-display' is `new-frame', the last buffer
7104 is kept so that you can work with several indirect buffers at the same time.
7105 If `org-indirect-buffer-display' is `dedicated-frame', the \
7106 \\[universal-argument] prefix also
7107 requests that a new frame be made for the new buffer, so that the dedicated
7108 frame is not changed."
7109 (interactive "P")
7110 (let ((cbuf (current-buffer))
7111 (cwin (selected-window))
7112 (pos (point))
7113 beg end level heading ibuf)
7114 (save-excursion
7115 (org-back-to-heading t)
7116 (when (numberp arg)
7117 (setq level (org-outline-level))
7118 (if (< arg 0) (setq arg (+ level arg)))
7119 (while (> (setq level (org-outline-level)) arg)
7120 (org-up-heading-safe)))
7121 (setq beg (point)
7122 heading (org-get-heading))
7123 (org-end-of-subtree t t)
7124 (if (org-at-heading-p) (backward-char 1))
7125 (setq end (point)))
7126 (if (and (buffer-live-p org-last-indirect-buffer)
7127 (not (eq org-indirect-buffer-display 'new-frame))
7128 (not arg))
7129 (kill-buffer org-last-indirect-buffer))
7130 (setq ibuf (org-get-indirect-buffer cbuf)
7131 org-last-indirect-buffer ibuf)
7132 (cond
7133 ((or (eq org-indirect-buffer-display 'new-frame)
7134 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7135 (select-frame (make-frame))
7136 (delete-other-windows)
7137 (org-pop-to-buffer-same-window ibuf)
7138 (org-set-frame-title heading))
7139 ((eq org-indirect-buffer-display 'dedicated-frame)
7140 (raise-frame
7141 (select-frame (or (and org-indirect-dedicated-frame
7142 (frame-live-p org-indirect-dedicated-frame)
7143 org-indirect-dedicated-frame)
7144 (setq org-indirect-dedicated-frame (make-frame)))))
7145 (delete-other-windows)
7146 (org-pop-to-buffer-same-window ibuf)
7147 (org-set-frame-title (concat "Indirect: " heading)))
7148 ((eq org-indirect-buffer-display 'current-window)
7149 (org-pop-to-buffer-same-window ibuf))
7150 ((eq org-indirect-buffer-display 'other-window)
7151 (pop-to-buffer ibuf))
7152 (t (error "Invalid value")))
7153 (if (featurep 'xemacs)
7154 (save-excursion (org-mode) (turn-on-font-lock)))
7155 (narrow-to-region beg end)
7156 (show-all)
7157 (goto-char pos)
7158 (run-hook-with-args 'org-cycle-hook 'all)
7159 (and (window-live-p cwin) (select-window cwin))))
7161 (defun org-get-indirect-buffer (&optional buffer)
7162 (setq buffer (or buffer (current-buffer)))
7163 (let ((n 1) (base (buffer-name buffer)) bname)
7164 (while (buffer-live-p
7165 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7166 (setq n (1+ n)))
7167 (condition-case nil
7168 (make-indirect-buffer buffer bname 'clone)
7169 (error (make-indirect-buffer buffer bname)))))
7171 (defun org-set-frame-title (title)
7172 "Set the title of the current frame to the string TITLE."
7173 ;; FIXME: how to name a single frame in XEmacs???
7174 (unless (featurep 'xemacs)
7175 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7177 ;;;; Structure editing
7179 ;;; Inserting headlines
7181 (defun org-previous-line-empty-p ()
7182 (save-excursion
7183 (and (not (bobp))
7184 (or (beginning-of-line 0) t)
7185 (save-match-data
7186 (looking-at "[ \t]*$")))))
7188 (defun org-insert-heading (&optional force-heading invisible-ok)
7189 "Insert a new heading or item with same depth at point.
7190 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7191 If point is at the beginning of a headline, insert a sibling before the
7192 current headline. If point is not at the beginning, split the line,
7193 create the new headline with the text in the current line after point
7194 \(but see also the variable `org-M-RET-may-split-line').
7196 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7197 This is important for non-interactive uses of the command."
7198 (interactive "P")
7199 (if (or (= (buffer-size) 0)
7200 (and (not (save-excursion
7201 (and (ignore-errors (org-back-to-heading invisible-ok))
7202 (org-at-heading-p))))
7203 (or force-heading (not (org-in-item-p)))))
7204 (progn
7205 (insert "\n* ")
7206 (run-hooks 'org-insert-heading-hook))
7207 (when (or force-heading (not (org-insert-item)))
7208 (let* ((empty-line-p nil)
7209 (level nil)
7210 (on-heading (org-at-heading-p))
7211 (head (save-excursion
7212 (condition-case nil
7213 (progn
7214 (org-back-to-heading invisible-ok)
7215 (when (and (not on-heading)
7216 (featurep 'org-inlinetask)
7217 (integerp org-inlinetask-min-level)
7218 (>= (length (match-string 0))
7219 org-inlinetask-min-level))
7220 ;; Find a heading level before the inline task
7221 (while (and (setq level (org-up-heading-safe))
7222 (>= level org-inlinetask-min-level)))
7223 (if (org-at-heading-p)
7224 (org-back-to-heading invisible-ok)
7225 (error "This should not happen")))
7226 (setq empty-line-p (org-previous-line-empty-p))
7227 (match-string 0))
7228 (error "*"))))
7229 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7230 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7231 pos hide-previous previous-pos)
7232 (cond
7233 ((and (org-at-heading-p) (bolp)
7234 (or (bobp)
7235 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7236 ;; insert before the current line
7237 (open-line (if blank 2 1)))
7238 ((and (bolp)
7239 (not org-insert-heading-respect-content)
7240 (or (bobp)
7241 (save-excursion
7242 (backward-char 1) (not (outline-invisible-p)))))
7243 ;; insert right here
7244 nil)
7246 ;; somewhere in the line
7247 (save-excursion
7248 (setq previous-pos (point-at-bol))
7249 (end-of-line)
7250 (setq hide-previous (outline-invisible-p)))
7251 (and org-insert-heading-respect-content (org-show-subtree))
7252 (let ((split
7253 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7254 (save-excursion
7255 (let ((p (point)))
7256 (goto-char (point-at-bol))
7257 (and (looking-at org-complex-heading-regexp)
7258 (match-beginning 4)
7259 (> p (match-beginning 4)))))))
7260 tags pos)
7261 (cond
7262 (org-insert-heading-respect-content
7263 (org-end-of-subtree nil t)
7264 (when (featurep 'org-inlinetask)
7265 (while (and (not (eobp))
7266 (looking-at "\\(\\*+\\)[ \t]+")
7267 (>= (length (match-string 1))
7268 org-inlinetask-min-level))
7269 (org-end-of-subtree nil t)))
7270 (or (bolp) (newline))
7271 (or (org-previous-line-empty-p)
7272 (and blank (newline)))
7273 (open-line 1))
7274 ((org-at-heading-p)
7275 (when hide-previous
7276 (show-children)
7277 (org-show-entry))
7278 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7279 (setq tags (and (match-end 2) (match-string 2)))
7280 (and (match-end 1)
7281 (delete-region (match-beginning 1) (match-end 1)))
7282 (setq pos (point-at-bol))
7283 (or split (end-of-line 1))
7284 (delete-horizontal-space)
7285 (if (string-match "\\`\\*+\\'"
7286 (buffer-substring (point-at-bol) (point)))
7287 (insert " "))
7288 (newline (if blank 2 1))
7289 (when tags
7290 (save-excursion
7291 (goto-char pos)
7292 (end-of-line 1)
7293 (insert " " tags)
7294 (org-set-tags nil 'align))))
7296 (or split (end-of-line 1))
7297 (newline (if blank 2 1)))))))
7298 (insert head) (just-one-space)
7299 (setq pos (point))
7300 (end-of-line 1)
7301 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7302 (when (and org-insert-heading-respect-content hide-previous)
7303 (save-excursion
7304 (goto-char previous-pos)
7305 (hide-subtree)))
7306 (run-hooks 'org-insert-heading-hook)))))
7308 (defun org-get-heading (&optional no-tags no-todo)
7309 "Return the heading of the current entry, without the stars.
7310 When NO-TAGS is non-nil, don't include tags.
7311 When NO-TODO is non-nil, don't include TODO keywords."
7312 (save-excursion
7313 (org-back-to-heading t)
7314 (cond
7315 ((and no-tags no-todo)
7316 (looking-at org-complex-heading-regexp)
7317 (match-string 4))
7318 (no-tags
7319 (looking-at (concat org-outline-regexp
7320 "\\(.*?\\)"
7321 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7322 (match-string 1))
7323 (no-todo
7324 (looking-at org-todo-line-regexp)
7325 (match-string 3))
7326 (t (looking-at org-heading-regexp)
7327 (match-string 2)))))
7329 (defun org-heading-components ()
7330 "Return the components of the current heading.
7331 This is a list with the following elements:
7332 - the level as an integer
7333 - the reduced level, different if `org-odd-levels-only' is set.
7334 - the TODO keyword, or nil
7335 - the priority character, like ?A, or nil if no priority is given
7336 - the headline text itself, or the tags string if no headline text
7337 - the tags string, or nil."
7338 (save-excursion
7339 (org-back-to-heading t)
7340 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7341 (list (length (match-string 1))
7342 (org-reduced-level (length (match-string 1)))
7343 (org-match-string-no-properties 2)
7344 (and (match-end 3) (aref (match-string 3) 2))
7345 (org-match-string-no-properties 4)
7346 (org-match-string-no-properties 5)))))
7348 (defun org-get-entry ()
7349 "Get the entry text, after heading, entire subtree."
7350 (save-excursion
7351 (org-back-to-heading t)
7352 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7354 (defun org-insert-heading-after-current ()
7355 "Insert a new heading with same level as current, after current subtree."
7356 (interactive)
7357 (org-back-to-heading)
7358 (org-insert-heading)
7359 (org-move-subtree-down)
7360 (end-of-line 1))
7362 (defun org-insert-heading-respect-content ()
7363 (interactive)
7364 (let ((org-insert-heading-respect-content t))
7365 (org-insert-heading t)))
7367 (defun org-insert-todo-heading-respect-content (&optional force-state)
7368 (interactive "P")
7369 (let ((org-insert-heading-respect-content t))
7370 (org-insert-todo-heading force-state t)))
7372 (defun org-insert-todo-heading (arg &optional force-heading)
7373 "Insert a new heading with the same level and TODO state as current heading.
7374 If the heading has no TODO state, or if the state is DONE, use the first
7375 state (TODO by default). Also with prefix arg, force first state."
7376 (interactive "P")
7377 (when (or force-heading (not (org-insert-item 'checkbox)))
7378 (org-insert-heading force-heading)
7379 (save-excursion
7380 (org-back-to-heading)
7381 (outline-previous-heading)
7382 (looking-at org-todo-line-regexp))
7383 (let*
7384 ((new-mark-x
7385 (if (or arg
7386 (not (match-beginning 2))
7387 (member (match-string 2) org-done-keywords))
7388 (car org-todo-keywords-1)
7389 (match-string 2)))
7390 (new-mark
7392 (run-hook-with-args-until-success
7393 'org-todo-get-default-hook new-mark-x nil)
7394 new-mark-x)))
7395 (beginning-of-line 1)
7396 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7397 (if org-treat-insert-todo-heading-as-state-change
7398 (org-todo new-mark)
7399 (insert new-mark " "))))
7400 (when org-provide-todo-statistics
7401 (org-update-parent-todo-statistics))))
7403 (defun org-insert-subheading (arg)
7404 "Insert a new subheading and demote it.
7405 Works for outline headings and for plain lists alike."
7406 (interactive "P")
7407 (org-insert-heading arg)
7408 (cond
7409 ((org-at-heading-p) (org-do-demote))
7410 ((org-at-item-p) (org-indent-item))))
7412 (defun org-insert-todo-subheading (arg)
7413 "Insert a new subheading with TODO keyword or checkbox and demote it.
7414 Works for outline headings and for plain lists alike."
7415 (interactive "P")
7416 (org-insert-todo-heading arg)
7417 (cond
7418 ((org-at-heading-p) (org-do-demote))
7419 ((org-at-item-p) (org-indent-item))))
7421 ;;; Promotion and Demotion
7423 (defvar org-after-demote-entry-hook nil
7424 "Hook run after an entry has been demoted.
7425 The cursor will be at the beginning of the entry.
7426 When a subtree is being demoted, the hook will be called for each node.")
7428 (defvar org-after-promote-entry-hook nil
7429 "Hook run after an entry has been promoted.
7430 The cursor will be at the beginning of the entry.
7431 When a subtree is being promoted, the hook will be called for each node.")
7433 (defun org-promote-subtree ()
7434 "Promote the entire subtree.
7435 See also `org-promote'."
7436 (interactive)
7437 (save-excursion
7438 (org-with-limited-levels (org-map-tree 'org-promote)))
7439 (org-fix-position-after-promote))
7441 (defun org-demote-subtree ()
7442 "Demote the entire subtree. See `org-demote'.
7443 See also `org-promote'."
7444 (interactive)
7445 (save-excursion
7446 (org-with-limited-levels (org-map-tree 'org-demote)))
7447 (org-fix-position-after-promote))
7450 (defun org-do-promote ()
7451 "Promote the current heading higher up the tree.
7452 If the region is active in `transient-mark-mode', promote all headings
7453 in the region."
7454 (interactive)
7455 (save-excursion
7456 (if (org-region-active-p)
7457 (org-map-region 'org-promote (region-beginning) (region-end))
7458 (org-promote)))
7459 (org-fix-position-after-promote))
7461 (defun org-do-demote ()
7462 "Demote the current heading lower down the tree.
7463 If the region is active in `transient-mark-mode', demote all headings
7464 in the region."
7465 (interactive)
7466 (save-excursion
7467 (if (org-region-active-p)
7468 (org-map-region 'org-demote (region-beginning) (region-end))
7469 (org-demote)))
7470 (org-fix-position-after-promote))
7472 (defun org-fix-position-after-promote ()
7473 "Make sure that after pro/demotion cursor position is right."
7474 (let ((pos (point)))
7475 (when (save-excursion
7476 (beginning-of-line 1)
7477 (looking-at org-todo-line-regexp)
7478 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7479 (cond ((eobp) (insert " "))
7480 ((eolp) (insert " "))
7481 ((equal (char-after) ?\ ) (forward-char 1))))))
7483 (defun org-current-level ()
7484 "Return the level of the current entry, or nil if before the first headline.
7485 The level is the number of stars at the beginning of the headline."
7486 (save-excursion
7487 (org-with-limited-levels
7488 (if (ignore-errors (org-back-to-heading t))
7489 (funcall outline-level)))))
7491 (defun org-get-previous-line-level ()
7492 "Return the outline depth of the last headline before the current line.
7493 Returns 0 for the first headline in the buffer, and nil if before the
7494 first headline."
7495 (let ((current-level (org-current-level))
7496 (prev-level (when (> (line-number-at-pos) 1)
7497 (save-excursion
7498 (beginning-of-line 0)
7499 (org-current-level)))))
7500 (cond ((null current-level) nil) ; Before first headline
7501 ((null prev-level) 0) ; At first headline
7502 (prev-level))))
7504 (defun org-reduced-level (l)
7505 "Compute the effective level of a heading.
7506 This takes into account the setting of `org-odd-levels-only'."
7507 (cond
7508 ((zerop l) 0)
7509 (org-odd-levels-only (1+ (floor (/ l 2))))
7510 (t l)))
7512 (defun org-level-increment ()
7513 "Return the number of stars that will be added or removed at a
7514 time to headlines when structure editing, based on the value of
7515 `org-odd-levels-only'."
7516 (if org-odd-levels-only 2 1))
7518 (defun org-get-valid-level (level &optional change)
7519 "Rectify a level change under the influence of `org-odd-levels-only'
7520 LEVEL is a current level, CHANGE is by how much the level should be
7521 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7522 even level numbers will become the next higher odd number."
7523 (if org-odd-levels-only
7524 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7525 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7526 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7527 (max 1 (+ level (or change 0)))))
7529 (if (boundp 'define-obsolete-function-alias)
7530 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7531 (define-obsolete-function-alias 'org-get-legal-level
7532 'org-get-valid-level)
7533 (define-obsolete-function-alias 'org-get-legal-level
7534 'org-get-valid-level "23.1")))
7536 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7537 ;; ̀org-with-limited-levels'
7538 (defun org-promote ()
7539 "Promote the current heading higher up the tree.
7540 If the region is active in `transient-mark-mode', promote all headings
7541 in the region."
7542 (org-back-to-heading t)
7543 (let* ((level (save-match-data (funcall outline-level)))
7544 (after-change-functions (remove 'flyspell-after-change-function
7545 after-change-functions))
7546 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7547 (diff (abs (- level (length up-head) -1))))
7548 (cond ((and (= level 1) org-called-with-limited-levels
7549 org-allow-promoting-top-level-subtree)
7550 (replace-match "# " nil t))
7551 ((= level 1)
7552 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7553 (t (replace-match up-head nil t)))
7554 ;; Fixup tag positioning
7555 (unless (= level 1)
7556 (and org-auto-align-tags (org-set-tags nil t))
7557 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7558 (run-hooks 'org-after-promote-entry-hook)))
7560 (defun org-demote ()
7561 "Demote the current heading lower down the tree.
7562 If the region is active in `transient-mark-mode', demote all headings
7563 in the region."
7564 (org-back-to-heading t)
7565 (let* ((level (save-match-data (funcall outline-level)))
7566 (after-change-functions (remove 'flyspell-after-change-function
7567 after-change-functions))
7568 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7569 (diff (abs (- level (length down-head) -1))))
7570 (replace-match down-head nil t)
7571 ;; Fixup tag positioning
7572 (and org-auto-align-tags (org-set-tags nil t))
7573 (if org-adapt-indentation (org-fixup-indentation diff))
7574 (run-hooks 'org-after-demote-entry-hook)))
7576 (defun org-cycle-level ()
7577 "Cycle the level of an empty headline through possible states.
7578 This goes first to child, then to parent, level, then up the hierarchy.
7579 After top level, it switches back to sibling level."
7580 (interactive)
7581 (let ((org-adapt-indentation nil))
7582 (when (org-point-at-end-of-empty-headline)
7583 (setq this-command 'org-cycle-level) ; Only needed for caching
7584 (let ((cur-level (org-current-level))
7585 (prev-level (org-get-previous-line-level)))
7586 (cond
7587 ;; If first headline in file, promote to top-level.
7588 ((= prev-level 0)
7589 (loop repeat (/ (- cur-level 1) (org-level-increment))
7590 do (org-do-promote)))
7591 ;; If same level as prev, demote one.
7592 ((= prev-level cur-level)
7593 (org-do-demote))
7594 ;; If parent is top-level, promote to top level if not already.
7595 ((= prev-level 1)
7596 (loop repeat (/ (- cur-level 1) (org-level-increment))
7597 do (org-do-promote)))
7598 ;; If top-level, return to prev-level.
7599 ((= cur-level 1)
7600 (loop repeat (/ (- prev-level 1) (org-level-increment))
7601 do (org-do-demote)))
7602 ;; If less than prev-level, promote one.
7603 ((< cur-level prev-level)
7604 (org-do-promote))
7605 ;; If deeper than prev-level, promote until higher than
7606 ;; prev-level.
7607 ((> cur-level prev-level)
7608 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7609 do (org-do-promote))))
7610 t))))
7612 (defun org-map-tree (fun)
7613 "Call FUN for every heading underneath the current one."
7614 (org-back-to-heading)
7615 (let ((level (funcall outline-level)))
7616 (save-excursion
7617 (funcall fun)
7618 (while (and (progn
7619 (outline-next-heading)
7620 (> (funcall outline-level) level))
7621 (not (eobp)))
7622 (funcall fun)))))
7624 (defun org-map-region (fun beg end)
7625 "Call FUN for every heading between BEG and END."
7626 (let ((org-ignore-region t))
7627 (save-excursion
7628 (setq end (copy-marker end))
7629 (goto-char beg)
7630 (if (and (re-search-forward org-outline-regexp-bol nil t)
7631 (< (point) end))
7632 (funcall fun))
7633 (while (and (progn
7634 (outline-next-heading)
7635 (< (point) end))
7636 (not (eobp)))
7637 (funcall fun)))))
7639 (defvar org-property-end-re) ; silence byte-compiler
7640 (defun org-fixup-indentation (diff)
7641 "Change the indentation in the current entry by DIFF.
7642 However, if any line in the current entry has no indentation, or if it
7643 would end up with no indentation after the change, nothing at all is done."
7644 (save-excursion
7645 (let ((end (save-excursion (outline-next-heading)
7646 (point-marker)))
7647 (prohibit (if (> diff 0)
7648 "^\\S-"
7649 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7650 col)
7651 (unless (save-excursion (end-of-line 1)
7652 (re-search-forward prohibit end t))
7653 (while (and (< (point) end)
7654 (re-search-forward "^[ \t]+" end t))
7655 (goto-char (match-end 0))
7656 (setq col (current-column))
7657 (if (< diff 0) (replace-match ""))
7658 (org-indent-to-column (+ diff col))))
7659 (move-marker end nil))))
7661 (defun org-convert-to-odd-levels ()
7662 "Convert an org-mode file with all levels allowed to one with odd levels.
7663 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7664 level 5 etc."
7665 (interactive)
7666 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7667 (let ((outline-level 'org-outline-level)
7668 (org-odd-levels-only nil) n)
7669 (save-excursion
7670 (goto-char (point-min))
7671 (while (re-search-forward "^\\*\\*+ " nil t)
7672 (setq n (- (length (match-string 0)) 2))
7673 (while (>= (setq n (1- n)) 0)
7674 (org-demote))
7675 (end-of-line 1))))))
7677 (defun org-convert-to-oddeven-levels ()
7678 "Convert an org-mode file with only odd levels to one with odd/even levels.
7679 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7680 file contains a section with an even level, conversion would
7681 destroy the structure of the file. An error is signaled in this
7682 case."
7683 (interactive)
7684 (goto-char (point-min))
7685 ;; First check if there are no even levels
7686 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7687 (org-show-context t)
7688 (error "Not all levels are odd in this file. Conversion not possible"))
7689 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7690 (let ((outline-regexp org-outline-regexp)
7691 (outline-level 'org-outline-level)
7692 (org-odd-levels-only nil) n)
7693 (save-excursion
7694 (goto-char (point-min))
7695 (while (re-search-forward "^\\*\\*+ " nil t)
7696 (setq n (/ (1- (length (match-string 0))) 2))
7697 (while (>= (setq n (1- n)) 0)
7698 (org-promote))
7699 (end-of-line 1))))))
7701 (defun org-tr-level (n)
7702 "Make N odd if required."
7703 (if org-odd-levels-only (1+ (/ n 2)) n))
7705 ;;; Vertical tree motion, cutting and pasting of subtrees
7707 (defun org-move-subtree-up (&optional arg)
7708 "Move the current subtree up past ARG headlines of the same level."
7709 (interactive "p")
7710 (org-move-subtree-down (- (prefix-numeric-value arg))))
7712 (defun org-move-subtree-down (&optional arg)
7713 "Move the current subtree down past ARG headlines of the same level."
7714 (interactive "p")
7715 (setq arg (prefix-numeric-value arg))
7716 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7717 'org-get-last-sibling))
7718 (ins-point (make-marker))
7719 (cnt (abs arg))
7720 (col (current-column))
7721 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7722 ;; Select the tree
7723 (org-back-to-heading)
7724 (setq beg0 (point))
7725 (save-excursion
7726 (setq ne-beg (org-back-over-empty-lines))
7727 (setq beg (point)))
7728 (save-match-data
7729 (save-excursion (outline-end-of-heading)
7730 (setq folded (outline-invisible-p)))
7731 (outline-end-of-subtree))
7732 (outline-next-heading)
7733 (setq ne-end (org-back-over-empty-lines))
7734 (setq end (point))
7735 (goto-char beg0)
7736 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7737 ;; include less whitespace
7738 (save-excursion
7739 (goto-char beg)
7740 (forward-line (- ne-beg ne-end))
7741 (setq beg (point))))
7742 ;; Find insertion point, with error handling
7743 (while (> cnt 0)
7744 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7745 (progn (goto-char beg0)
7746 (error "Cannot move past superior level or buffer limit")))
7747 (setq cnt (1- cnt)))
7748 (if (> arg 0)
7749 ;; Moving forward - still need to move over subtree
7750 (progn (org-end-of-subtree t t)
7751 (save-excursion
7752 (org-back-over-empty-lines)
7753 (or (bolp) (newline)))))
7754 (setq ne-ins (org-back-over-empty-lines))
7755 (move-marker ins-point (point))
7756 (setq txt (buffer-substring beg end))
7757 (org-save-markers-in-region beg end)
7758 (delete-region beg end)
7759 (org-remove-empty-overlays-at beg)
7760 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7761 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7762 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7763 (let ((bbb (point)))
7764 (insert-before-markers txt)
7765 (org-reinstall-markers-in-region bbb)
7766 (move-marker ins-point bbb))
7767 (or (bolp) (insert "\n"))
7768 (setq ins-end (point))
7769 (goto-char ins-point)
7770 (org-skip-whitespace)
7771 (when (and (< arg 0)
7772 (org-first-sibling-p)
7773 (> ne-ins ne-beg))
7774 ;; Move whitespace back to beginning
7775 (save-excursion
7776 (goto-char ins-end)
7777 (let ((kill-whole-line t))
7778 (kill-line (- ne-ins ne-beg)) (point)))
7779 (insert (make-string (- ne-ins ne-beg) ?\n)))
7780 (move-marker ins-point nil)
7781 (if folded
7782 (hide-subtree)
7783 (org-show-entry)
7784 (show-children)
7785 (org-cycle-hide-drawers 'children))
7786 (org-clean-visibility-after-subtree-move)
7787 ;; move back to the initial column we were at
7788 (move-to-column col)))
7790 (defvar org-subtree-clip ""
7791 "Clipboard for cut and paste of subtrees.
7792 This is actually only a copy of the kill, because we use the normal kill
7793 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7795 (defvar org-subtree-clip-folded nil
7796 "Was the last copied subtree folded?
7797 This is used to fold the tree back after pasting.")
7799 (defun org-cut-subtree (&optional n)
7800 "Cut the current subtree into the clipboard.
7801 With prefix arg N, cut this many sequential subtrees.
7802 This is a short-hand for marking the subtree and then cutting it."
7803 (interactive "p")
7804 (org-copy-subtree n 'cut))
7806 (defun org-copy-subtree (&optional n cut force-store-markers)
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 copying it.
7810 If CUT is non-nil, actually cut the subtree.
7811 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7812 of some markers in the region, even if CUT is non-nil. This is
7813 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7814 (interactive "p")
7815 (let (beg end folded (beg0 (point)))
7816 (if (org-called-interactively-p 'any)
7817 (org-back-to-heading nil) ; take what looks like a subtree
7818 (org-back-to-heading t)) ; take what is really there
7819 (org-back-over-empty-lines)
7820 (setq beg (point))
7821 (skip-chars-forward " \t\r\n")
7822 (save-match-data
7823 (save-excursion (outline-end-of-heading)
7824 (setq folded (outline-invisible-p)))
7825 (condition-case nil
7826 (org-forward-heading-same-level (1- n) t)
7827 (error nil))
7828 (org-end-of-subtree t t))
7829 (org-back-over-empty-lines)
7830 (setq end (point))
7831 (goto-char beg0)
7832 (when (> end beg)
7833 (setq org-subtree-clip-folded folded)
7834 (when (or cut force-store-markers)
7835 (org-save-markers-in-region beg end))
7836 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7837 (setq org-subtree-clip (current-kill 0))
7838 (message "%s: Subtree(s) with %d characters"
7839 (if cut "Cut" "Copied")
7840 (length org-subtree-clip)))))
7842 (defun org-paste-subtree (&optional level tree for-yank)
7843 "Paste the clipboard as a subtree, with modification of headline level.
7844 The entire subtree is promoted or demoted in order to match a new headline
7845 level.
7847 If the cursor is at the beginning of a headline, the same level as
7848 that headline is used to paste the tree
7850 If not, the new level is derived from the *visible* headings
7851 before and after the insertion point, and taken to be the inferior headline
7852 level of the two. So if the previous visible heading is level 3 and the
7853 next is level 4 (or vice versa), level 4 will be used for insertion.
7854 This makes sure that the subtree remains an independent subtree and does
7855 not swallow low level entries.
7857 You can also force a different level, either by using a numeric prefix
7858 argument, or by inserting the heading marker by hand. For example, if the
7859 cursor is after \"*****\", then the tree will be shifted to level 5.
7861 If optional TREE is given, use this text instead of the kill ring.
7863 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7864 move back over whitespace before inserting, and move point to the end of
7865 the inserted text when done."
7866 (interactive "P")
7867 (setq tree (or tree (and kill-ring (current-kill 0))))
7868 (unless (org-kill-is-subtree-p tree)
7869 (error "%s"
7870 (substitute-command-keys
7871 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7872 (org-with-limited-levels
7873 (let* ((visp (not (outline-invisible-p)))
7874 (txt tree)
7875 (^re_ "\\(\\*+\\)[ \t]*")
7876 (old-level (if (string-match org-outline-regexp-bol txt)
7877 (- (match-end 0) (match-beginning 0) 1)
7878 -1))
7879 (force-level (cond (level (prefix-numeric-value level))
7880 ((and (looking-at "[ \t]*$")
7881 (string-match
7882 "^\\*+$" (buffer-substring
7883 (point-at-bol) (point))))
7884 (- (match-end 1) (match-beginning 1)))
7885 ((and (bolp)
7886 (looking-at org-outline-regexp))
7887 (- (match-end 0) (point) 1))))
7888 (previous-level (save-excursion
7889 (condition-case nil
7890 (progn
7891 (outline-previous-visible-heading 1)
7892 (if (looking-at ^re_)
7893 (- (match-end 0) (match-beginning 0) 1)
7895 (error 1))))
7896 (next-level (save-excursion
7897 (condition-case nil
7898 (progn
7899 (or (looking-at org-outline-regexp)
7900 (outline-next-visible-heading 1))
7901 (if (looking-at ^re_)
7902 (- (match-end 0) (match-beginning 0) 1)
7904 (error 1))))
7905 (new-level (or force-level (max previous-level next-level)))
7906 (shift (if (or (= old-level -1)
7907 (= new-level -1)
7908 (= old-level new-level))
7910 (- new-level old-level)))
7911 (delta (if (> shift 0) -1 1))
7912 (func (if (> shift 0) 'org-demote 'org-promote))
7913 (org-odd-levels-only nil)
7914 beg end newend)
7915 ;; Remove the forced level indicator
7916 (if force-level
7917 (delete-region (point-at-bol) (point)))
7918 ;; Paste
7919 (beginning-of-line (if (bolp) 1 2))
7920 (unless for-yank (org-back-over-empty-lines))
7921 (setq beg (point))
7922 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7923 (insert-before-markers txt)
7924 (unless (string-match "\n\\'" txt) (insert "\n"))
7925 (setq newend (point))
7926 (org-reinstall-markers-in-region beg)
7927 (setq end (point))
7928 (goto-char beg)
7929 (skip-chars-forward " \t\n\r")
7930 (setq beg (point))
7931 (if (and (outline-invisible-p) visp)
7932 (save-excursion (outline-show-heading)))
7933 ;; Shift if necessary
7934 (unless (= shift 0)
7935 (save-restriction
7936 (narrow-to-region beg end)
7937 (while (not (= shift 0))
7938 (org-map-region func (point-min) (point-max))
7939 (setq shift (+ delta shift)))
7940 (goto-char (point-min))
7941 (setq newend (point-max))))
7942 (when (or (org-called-interactively-p 'interactive) for-yank)
7943 (message "Clipboard pasted as level %d subtree" new-level))
7944 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7945 kill-ring
7946 (eq org-subtree-clip (current-kill 0))
7947 org-subtree-clip-folded)
7948 ;; The tree was folded before it was killed/copied
7949 (hide-subtree))
7950 (and for-yank (goto-char newend)))))
7952 (defun org-kill-is-subtree-p (&optional txt)
7953 "Check if the current kill is an outline subtree, or a set of trees.
7954 Returns nil if kill does not start with a headline, or if the first
7955 headline level is not the largest headline level in the tree.
7956 So this will actually accept several entries of equal levels as well,
7957 which is OK for `org-paste-subtree'.
7958 If optional TXT is given, check this string instead of the current kill."
7959 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7960 (re (org-get-limited-outline-regexp))
7961 (^re (concat "^" re))
7962 (start-level (and kill
7963 (string-match
7964 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7965 kill)
7966 (- (match-end 2) (match-beginning 2) 1)))
7967 (start (1+ (or (match-beginning 2) -1))))
7968 (if (not start-level)
7969 (progn
7970 nil) ;; does not even start with a heading
7971 (catch 'exit
7972 (while (setq start (string-match ^re kill (1+ start)))
7973 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7974 (throw 'exit nil)))
7975 t))))
7977 (defvar org-markers-to-move nil
7978 "Markers that should be moved with a cut-and-paste operation.
7979 Those markers are stored together with their positions relative to
7980 the start of the region.")
7982 (defun org-save-markers-in-region (beg end)
7983 "Check markers in region.
7984 If these markers are between BEG and END, record their position relative
7985 to BEG, so that after moving the block of text, we can put the markers back
7986 into place.
7987 This function gets called just before an entry or tree gets cut from the
7988 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7989 called immediately, to move the markers with the entries."
7990 (setq org-markers-to-move nil)
7991 (when (featurep 'org-clock)
7992 (org-clock-save-markers-for-cut-and-paste beg end))
7993 (when (featurep 'org-agenda)
7994 (org-agenda-save-markers-for-cut-and-paste beg end)))
7996 (defun org-check-and-save-marker (marker beg end)
7997 "Check if MARKER is between BEG and END.
7998 If yes, remember the marker and the distance to BEG."
7999 (when (and (marker-buffer marker)
8000 (equal (marker-buffer marker) (current-buffer)))
8001 (if (and (>= marker beg) (< marker end))
8002 (push (cons marker (- marker beg)) org-markers-to-move))))
8004 (defun org-reinstall-markers-in-region (beg)
8005 "Move all remembered markers to their position relative to BEG."
8006 (mapc (lambda (x)
8007 (move-marker (car x) (+ beg (cdr x))))
8008 org-markers-to-move)
8009 (setq org-markers-to-move nil))
8011 (defun org-narrow-to-subtree ()
8012 "Narrow buffer to the current subtree."
8013 (interactive)
8014 (save-excursion
8015 (save-match-data
8016 (org-with-limited-levels
8017 (narrow-to-region
8018 (progn (org-back-to-heading t) (point))
8019 (progn (org-end-of-subtree t t)
8020 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8021 (point)))))))
8023 (defun org-narrow-to-block ()
8024 "Narrow buffer to the current block."
8025 (interactive)
8026 (let* ((case-fold-search t)
8027 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8028 "^[ \t]*#\\+end_.*")))
8029 (if blockp
8030 (narrow-to-region (car blockp) (cdr blockp))
8031 (error "Not in a block"))))
8033 (eval-when-compile
8034 (defvar org-property-drawer-re))
8036 (defvar org-property-start-re) ;; defined below
8037 (defun org-clone-subtree-with-time-shift (n &optional shift)
8038 "Clone the task (subtree) at point N times.
8039 The clones will be inserted as siblings.
8041 In interactive use, the user will be prompted for the number of
8042 clones to be produced, and for a time SHIFT, which may be a
8043 repeater as used in time stamps, for example `+3d'.
8045 When a valid repeater is given and the entry contains any time
8046 stamps, the clones will become a sequence in time, with time
8047 stamps in the subtree shifted for each clone produced. If SHIFT
8048 is nil or the empty string, time stamps will be left alone. The
8049 ID property of the original subtree is removed.
8051 If the original subtree did contain time stamps with a repeater,
8052 the following will happen:
8053 - the repeater will be removed in each clone
8054 - an additional clone will be produced, with the current, unshifted
8055 date(s) in the entry.
8056 - the original entry will be placed *after* all the clones, with
8057 repeater intact.
8058 - the start days in the repeater in the original entry will be shifted
8059 to past the last clone.
8060 In this way you can spell out a number of instances of a repeating task,
8061 and still retain the repeater to cover future instances of the task."
8062 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8063 (let (beg end template task idprop
8064 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8065 (drawer-re org-drawer-regexp))
8066 (if (not (and (integerp n) (> n 0)))
8067 (error "Invalid number of replications %s" n))
8068 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8069 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8070 shift)))
8071 (error "Invalid shift specification %s" shift))
8072 (when doshift
8073 (setq shift-n (string-to-number (match-string 1 shift))
8074 shift-what (cdr (assoc (match-string 2 shift)
8075 '(("d" . day) ("w" . week)
8076 ("m" . month) ("y" . year))))))
8077 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8078 (setq nmin 1 nmax n)
8079 (org-back-to-heading t)
8080 (setq beg (point))
8081 (setq idprop (org-entry-get nil "ID"))
8082 (org-end-of-subtree t t)
8083 (or (bolp) (insert "\n"))
8084 (setq end (point))
8085 (setq template (buffer-substring beg end))
8086 (when (and doshift
8087 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8088 (delete-region beg end)
8089 (setq end beg)
8090 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8091 (goto-char end)
8092 (loop for n from nmin to nmax do
8093 ;; prepare clone
8094 (with-temp-buffer
8095 (insert template)
8096 (org-mode)
8097 (goto-char (point-min))
8098 (org-show-subtree)
8099 (and idprop (if org-clone-delete-id
8100 (org-entry-delete nil "ID")
8101 (org-id-get-create t)))
8102 (unless (= n 0)
8103 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8104 (kill-whole-line))
8105 (goto-char (point-min))
8106 (while (re-search-forward drawer-re nil t)
8107 (mapc (lambda (d)
8108 (org-remove-empty-drawer-at d (point))) org-drawers)))
8109 (goto-char (point-min))
8110 (when doshift
8111 (while (re-search-forward org-ts-regexp-both nil t)
8112 (org-timestamp-change (* n shift-n) shift-what))
8113 (unless (= n n-no-remove)
8114 (goto-char (point-min))
8115 (while (re-search-forward org-ts-regexp nil t)
8116 (save-excursion
8117 (goto-char (match-beginning 0))
8118 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8119 (delete-region (match-beginning 1) (match-end 1)))))))
8120 (setq task (buffer-string)))
8121 (insert task))
8122 (goto-char beg)))
8124 ;;; Outline Sorting
8126 (defun org-sort (with-case)
8127 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8128 Optional argument WITH-CASE means sort case-sensitively."
8129 (interactive "P")
8130 (cond
8131 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8132 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8134 (org-call-with-arg 'org-sort-entries with-case))))
8136 (defun org-sort-remove-invisible (s)
8137 (remove-text-properties 0 (length s) org-rm-props s)
8138 (while (string-match org-bracket-link-regexp s)
8139 (setq s (replace-match (if (match-end 2)
8140 (match-string 3 s)
8141 (match-string 1 s)) t t s)))
8144 (defvar org-priority-regexp) ; defined later in the file
8146 (defvar org-after-sorting-entries-or-items-hook nil
8147 "Hook that is run after a bunch of entries or items have been sorted.
8148 When children are sorted, the cursor is in the parent line when this
8149 hook gets called. When a region or a plain list is sorted, the cursor
8150 will be in the first entry of the sorted region/list.")
8152 (defun org-sort-entries
8153 (&optional with-case sorting-type getkey-func compare-func property)
8154 "Sort entries on a certain level of an outline tree.
8155 If there is an active region, the entries in the region are sorted.
8156 Else, if the cursor is before the first entry, sort the top-level items.
8157 Else, the children of the entry at point are sorted.
8159 Sorting can be alphabetically, numerically, by date/time as given by
8160 a time stamp, by a property or by priority.
8162 The command prompts for the sorting type unless it has been given to the
8163 function through the SORTING-TYPE argument, which needs to be a character,
8164 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8165 precise meaning of each character:
8167 n Numerically, by converting the beginning of the entry/item to a number.
8168 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8169 t By date/time, either the first active time stamp in the entry, or, if
8170 none exist, by the first inactive one.
8171 s By the scheduled date/time.
8172 d By deadline date/time.
8173 c By creation time, which is assumed to be the first inactive time stamp
8174 at the beginning of a line.
8175 p By priority according to the cookie.
8176 r By the value of a property.
8178 Capital letters will reverse the sort order.
8180 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8181 called with point at the beginning of the record. It must return either
8182 a string or a number that should serve as the sorting key for that record.
8184 Comparing entries ignores case by default. However, with an optional argument
8185 WITH-CASE, the sorting considers case as well."
8186 (interactive "P")
8187 (let ((case-func (if with-case 'identity 'downcase))
8188 start beg end stars re re2
8189 txt what tmp)
8190 ;; Find beginning and end of region to sort
8191 (cond
8192 ((org-region-active-p)
8193 ;; we will sort the region
8194 (setq end (region-end)
8195 what "region")
8196 (goto-char (region-beginning))
8197 (if (not (org-at-heading-p)) (outline-next-heading))
8198 (setq start (point)))
8199 ((or (org-at-heading-p)
8200 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8201 ;; we will sort the children of the current headline
8202 (org-back-to-heading)
8203 (setq start (point)
8204 end (progn (org-end-of-subtree t t)
8205 (or (bolp) (insert "\n"))
8206 (org-back-over-empty-lines)
8207 (point))
8208 what "children")
8209 (goto-char start)
8210 (show-subtree)
8211 (outline-next-heading))
8213 ;; we will sort the top-level entries in this file
8214 (goto-char (point-min))
8215 (or (org-at-heading-p) (outline-next-heading))
8216 (setq start (point))
8217 (goto-char (point-max))
8218 (beginning-of-line 1)
8219 (when (looking-at ".*?\\S-")
8220 ;; File ends in a non-white line
8221 (end-of-line 1)
8222 (insert "\n"))
8223 (setq end (point-max))
8224 (setq what "top-level")
8225 (goto-char start)
8226 (show-all)))
8228 (setq beg (point))
8229 (if (>= beg end) (error "Nothing to sort"))
8231 (looking-at "\\(\\*+\\)")
8232 (setq stars (match-string 1)
8233 re (concat "^" (regexp-quote stars) " +")
8234 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8235 txt (buffer-substring beg end))
8236 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8237 (if (and (not (equal stars "*")) (string-match re2 txt))
8238 (error "Region to sort contains a level above the first entry"))
8240 (unless sorting-type
8241 (message
8242 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8243 [t]ime [s]cheduled [d]eadline [c]reated
8244 A/N/T/S/D/C/P/O/F means reversed:"
8245 what)
8246 (setq sorting-type (read-char-exclusive))
8248 (unless getkey-func
8249 (and (= (downcase sorting-type) ?f)
8250 (setq getkey-func
8251 (org-icompleting-read "Sort using function: "
8252 obarray 'fboundp t nil nil))
8253 (setq getkey-func (intern getkey-func))))
8255 (and (= (downcase sorting-type) ?r)
8256 (not property)
8257 (setq property
8258 (org-icompleting-read "Property: "
8259 (mapcar 'list (org-buffer-property-keys t))
8260 nil t))))
8262 (message "Sorting entries...")
8264 (save-restriction
8265 (narrow-to-region start end)
8266 (let ((dcst (downcase sorting-type))
8267 (case-fold-search nil)
8268 (now (current-time)))
8269 (sort-subr
8270 (/= dcst sorting-type)
8271 ;; This function moves to the beginning character of the "record" to
8272 ;; be sorted.
8273 (lambda nil
8274 (if (re-search-forward re nil t)
8275 (goto-char (match-beginning 0))
8276 (goto-char (point-max))))
8277 ;; This function moves to the last character of the "record" being
8278 ;; sorted.
8279 (lambda nil
8280 (save-match-data
8281 (condition-case nil
8282 (outline-forward-same-level 1)
8283 (error
8284 (goto-char (point-max))))))
8285 ;; This function returns the value that gets sorted against.
8286 (lambda nil
8287 (cond
8288 ((= dcst ?n)
8289 (if (looking-at org-complex-heading-regexp)
8290 (string-to-number (match-string 4))
8291 nil))
8292 ((= dcst ?a)
8293 (if (looking-at org-complex-heading-regexp)
8294 (funcall case-func (match-string 4))
8295 nil))
8296 ((= dcst ?t)
8297 (let ((end (save-excursion (outline-next-heading) (point))))
8298 (if (or (re-search-forward org-ts-regexp end t)
8299 (re-search-forward org-ts-regexp-both end t))
8300 (org-time-string-to-seconds (match-string 0))
8301 (org-float-time now))))
8302 ((= dcst ?c)
8303 (let ((end (save-excursion (outline-next-heading) (point))))
8304 (if (re-search-forward
8305 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8306 end t)
8307 (org-time-string-to-seconds (match-string 0))
8308 (org-float-time now))))
8309 ((= dcst ?s)
8310 (let ((end (save-excursion (outline-next-heading) (point))))
8311 (if (re-search-forward org-scheduled-time-regexp end t)
8312 (org-time-string-to-seconds (match-string 1))
8313 (org-float-time now))))
8314 ((= dcst ?d)
8315 (let ((end (save-excursion (outline-next-heading) (point))))
8316 (if (re-search-forward org-deadline-time-regexp end t)
8317 (org-time-string-to-seconds (match-string 1))
8318 (org-float-time now))))
8319 ((= dcst ?p)
8320 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8321 (string-to-char (match-string 2))
8322 org-default-priority))
8323 ((= dcst ?r)
8324 (or (org-entry-get nil property) ""))
8325 ((= dcst ?o)
8326 (if (looking-at org-complex-heading-regexp)
8327 (- 9999 (length (member (match-string 2)
8328 org-todo-keywords-1)))))
8329 ((= dcst ?f)
8330 (if getkey-func
8331 (progn
8332 (setq tmp (funcall getkey-func))
8333 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8334 tmp)
8335 (error "Invalid key function `%s'" getkey-func)))
8336 (t (error "Invalid sorting type `%c'" sorting-type))))
8338 (cond
8339 ((= dcst ?a) 'string<)
8340 ((= dcst ?f) compare-func)
8341 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8342 (run-hooks 'org-after-sorting-entries-or-items-hook)
8343 (message "Sorting entries...done")))
8345 (defun org-do-sort (table what &optional with-case sorting-type)
8346 "Sort TABLE of WHAT according to SORTING-TYPE.
8347 The user will be prompted for the SORTING-TYPE if the call to this
8348 function does not specify it. WHAT is only for the prompt, to indicate
8349 what is being sorted. The sorting key will be extracted from
8350 the car of the elements of the table.
8351 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8352 (unless sorting-type
8353 (message
8354 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8355 what)
8356 (setq sorting-type (read-char-exclusive)))
8357 (let ((dcst (downcase sorting-type))
8358 extractfun comparefun)
8359 ;; Define the appropriate functions
8360 (cond
8361 ((= dcst ?n)
8362 (setq extractfun 'string-to-number
8363 comparefun (if (= dcst sorting-type) '< '>)))
8364 ((= dcst ?a)
8365 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8366 (lambda(x) (downcase (org-sort-remove-invisible x))))
8367 comparefun (if (= dcst sorting-type)
8368 'string<
8369 (lambda (a b) (and (not (string< a b))
8370 (not (string= a b)))))))
8371 ((= dcst ?t)
8372 (setq extractfun
8373 (lambda (x)
8374 (if (or (string-match org-ts-regexp x)
8375 (string-match org-ts-regexp-both x))
8376 (org-float-time
8377 (org-time-string-to-time (match-string 0 x)))
8379 comparefun (if (= dcst sorting-type) '< '>)))
8380 (t (error "Invalid sorting type `%c'" sorting-type)))
8382 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8383 table)
8384 (lambda (a b) (funcall comparefun (car a) (car b))))))
8387 ;;; The orgstruct minor mode
8389 ;; Define a minor mode which can be used in other modes in order to
8390 ;; integrate the org-mode structure editing commands.
8392 ;; This is really a hack, because the org-mode structure commands use
8393 ;; keys which normally belong to the major mode. Here is how it
8394 ;; works: The minor mode defines all the keys necessary to operate the
8395 ;; structure commands, but wraps the commands into a function which
8396 ;; tests if the cursor is currently at a headline or a plain list
8397 ;; item. If that is the case, the structure command is used,
8398 ;; temporarily setting many Org-mode variables like regular
8399 ;; expressions for filling etc. However, when any of those keys is
8400 ;; used at a different location, function uses `key-binding' to look
8401 ;; up if the key has an associated command in another currently active
8402 ;; keymap (minor modes, major mode, global), and executes that
8403 ;; command. There might be problems if any of the keys is otherwise
8404 ;; used as a prefix key.
8406 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8407 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8408 ;; addresses this by checking explicitly for both bindings.
8410 (defvar orgstruct-mode-map (make-sparse-keymap)
8411 "Keymap for the minor `orgstruct-mode'.")
8413 (defvar org-local-vars nil
8414 "List of local variables, for use by `orgstruct-mode'.")
8416 ;;;###autoload
8417 (define-minor-mode orgstruct-mode
8418 "Toggle the minor mode `orgstruct-mode'.
8419 This mode is for using Org-mode structure commands in other
8420 modes. The following keys behave as if Org-mode were active, if
8421 the cursor is on a headline, or on a plain list item (both as
8422 defined by Org-mode).
8424 M-up Move entry/item up
8425 M-down Move entry/item down
8426 M-left Promote
8427 M-right Demote
8428 M-S-up Move entry/item up
8429 M-S-down Move entry/item down
8430 M-S-left Promote subtree
8431 M-S-right Demote subtree
8432 M-q Fill paragraph and items like in Org-mode
8433 C-c ^ Sort entries
8434 C-c - Cycle list bullet
8435 TAB Cycle item visibility
8436 M-RET Insert new heading/item
8437 S-M-RET Insert new TODO heading / Checkbox item
8438 C-c C-c Set tags / toggle checkbox"
8439 nil " OrgStruct" nil
8440 (org-load-modules-maybe)
8441 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8443 ;;;###autoload
8444 (defun turn-on-orgstruct ()
8445 "Unconditionally turn on `orgstruct-mode'."
8446 (orgstruct-mode 1))
8448 (defvar org-fb-vars nil)
8449 (make-variable-buffer-local 'org-fb-vars)
8450 (defun orgstruct++-mode (&optional arg)
8451 "Toggle `orgstruct-mode', the enhanced version of it.
8452 In addition to setting orgstruct-mode, this also exports all
8453 indentation and autofilling variables from org-mode into the
8454 buffer. It will also recognize item context in multiline items."
8455 (interactive "P")
8456 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8457 (if (< arg 1)
8458 (progn (orgstruct-mode -1)
8459 (mapc (lambda(v)
8460 (org-set-local (car v)
8461 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8462 org-fb-vars))
8463 (orgstruct-mode 1)
8464 (setq org-fb-vars nil)
8465 (let (var val)
8466 (mapc
8467 (lambda (x)
8468 (when (string-match
8469 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8470 (symbol-name (car x)))
8471 (setq var (car x) val (nth 1 x))
8472 (push (list var `(quote ,(eval var))) org-fb-vars)
8473 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8474 org-local-vars)
8475 (org-set-local 'orgstruct-is-++ t))))
8477 (defvar orgstruct-is-++ nil
8478 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8479 (make-variable-buffer-local 'orgstruct-is-++)
8481 ;;;###autoload
8482 (defun turn-on-orgstruct++ ()
8483 "Unconditionally turn on `orgstruct++-mode'."
8484 (orgstruct++-mode 1))
8486 (defun orgstruct-error ()
8487 "Error when there is no default binding for a structure key."
8488 (interactive)
8489 (error "This key has no function outside structure elements"))
8491 (defun orgstruct-setup ()
8492 "Setup orgstruct keymaps."
8493 (let ((nfunc 0)
8494 (bindings
8495 (list
8496 '([(meta up)] org-metaup)
8497 '([(meta down)] org-metadown)
8498 '([(meta left)] org-metaleft)
8499 '([(meta right)] org-metaright)
8500 '([(meta shift up)] org-shiftmetaup)
8501 '([(meta shift down)] org-shiftmetadown)
8502 '([(meta shift left)] org-shiftmetaleft)
8503 '([(meta shift right)] org-shiftmetaright)
8504 '([?\e (up)] org-metaup)
8505 '([?\e (down)] org-metadown)
8506 '([?\e (left)] org-metaleft)
8507 '([?\e (right)] org-metaright)
8508 '([?\e (shift up)] org-shiftmetaup)
8509 '([?\e (shift down)] org-shiftmetadown)
8510 '([?\e (shift left)] org-shiftmetaleft)
8511 '([?\e (shift right)] org-shiftmetaright)
8512 '([(shift up)] org-shiftup)
8513 '([(shift down)] org-shiftdown)
8514 '([(shift left)] org-shiftleft)
8515 '([(shift right)] org-shiftright)
8516 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8517 '("\M-q" fill-paragraph)
8518 '("\C-c^" org-sort)
8519 '("\C-c-" org-cycle-list-bullet)))
8520 elt key fun cmd)
8521 (while (setq elt (pop bindings))
8522 (setq nfunc (1+ nfunc))
8523 (setq key (org-key (car elt))
8524 fun (nth 1 elt)
8525 cmd (orgstruct-make-binding fun nfunc key))
8526 (org-defkey orgstruct-mode-map key cmd))
8528 ;; Prevent an error for users who forgot to make autoloads
8529 (require 'org-element)
8531 ;; Special treatment needed for TAB and RET
8532 (org-defkey orgstruct-mode-map [(tab)]
8533 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8534 (org-defkey orgstruct-mode-map "\C-i"
8535 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8537 (org-defkey orgstruct-mode-map "\M-\C-m"
8538 (orgstruct-make-binding 'org-insert-heading 105
8539 "\M-\C-m" [(meta return)]))
8540 (org-defkey orgstruct-mode-map [(meta return)]
8541 (orgstruct-make-binding 'org-insert-heading 106
8542 [(meta return)] "\M-\C-m"))
8544 (org-defkey orgstruct-mode-map [(shift meta return)]
8545 (orgstruct-make-binding 'org-insert-todo-heading 107
8546 [(meta return)] "\M-\C-m"))
8548 (org-defkey orgstruct-mode-map "\e\C-m"
8549 (orgstruct-make-binding 'org-insert-heading 108
8550 "\e\C-m" [?\e (return)]))
8551 (org-defkey orgstruct-mode-map [?\e (return)]
8552 (orgstruct-make-binding 'org-insert-heading 109
8553 [?\e (return)] "\e\C-m"))
8554 (org-defkey orgstruct-mode-map [?\e (shift return)]
8555 (orgstruct-make-binding 'org-insert-todo-heading 110
8556 [?\e (return)] "\e\C-m"))
8558 (unless org-local-vars
8559 (setq org-local-vars (org-get-local-variables)))
8563 (defun orgstruct-make-binding (fun n &rest keys)
8564 "Create a function for binding in the structure minor mode.
8565 FUN is the command to call inside a table. N is used to create a unique
8566 command name. KEYS are keys that should be checked in for a command
8567 to execute outside of tables."
8568 (eval
8569 (list 'defun
8570 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8571 '(arg)
8572 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8573 "Outside of structure, run the binding of `"
8574 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8575 "'.")
8576 '(interactive "p")
8577 (list 'if
8578 `(org-context-p 'headline 'item
8579 (and orgstruct-is-++
8580 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8581 'item-body))
8582 (list 'org-run-like-in-org-mode (list 'quote fun))
8583 (list 'let '(orgstruct-mode)
8584 (list 'call-interactively
8585 (append '(or)
8586 (mapcar (lambda (k)
8587 (list 'key-binding k))
8588 keys)
8589 '('orgstruct-error))))))))
8591 (defun org-contextualize-keys (alist contexts)
8592 "Return valid elements in ALIST depending on CONTEXTS.
8594 `org-agenda-custom-commands' or `org-capture-templates' are the
8595 values used for ALIST, and `org-agenda-custom-commands-contexts'
8596 or `org-capture-templates-contexts' are the associated contexts
8597 definitions."
8598 (let ((contexts
8599 ;; normalize contexts
8600 (mapcar
8601 (lambda(c) (cond ((listp (cadr c))
8602 (list (car c) (car c) (cadr c)))
8603 ((string= "" (cadr c))
8604 (list (car c) (car c) (caddr c)))
8605 (t c))) contexts))
8606 (a alist) c r s)
8607 ;; loop over all commands or templates
8608 (while (setq c (pop a))
8609 (let (vrules repl)
8610 (cond
8611 ((not (assoc (car c) contexts))
8612 (push c r))
8613 ((and (assoc (car c) contexts)
8614 (setq vrules (org-contextualize-validate-key
8615 (car c) contexts)))
8616 (mapc (lambda (vr)
8617 (when (not (equal (car vr) (cadr vr)))
8618 (setq repl vr))) vrules)
8619 (if (not repl) (push c r)
8620 (push (cadr repl) s)
8621 (push
8622 (cons (car c)
8623 (cdr (or (assoc (cadr repl) alist)
8624 (error "Undefined key `%s' as contextual replacement for `%s'"
8625 (cadr repl) (car c)))))
8626 r))))))
8627 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8628 (delq
8630 (delete-dups
8631 (mapcar (lambda (x)
8632 (let ((tpl (car x)))
8633 (when (not (delq
8635 (mapcar (lambda(y)
8636 (equal y tpl)) s))) x)))
8637 (reverse r))))))
8639 (defun org-contextualize-validate-key (key contexts)
8640 "Check CONTEXTS for agenda or capture KEY."
8641 (let (r rr res)
8642 (while (setq r (pop contexts))
8643 (mapc
8644 (lambda (rr)
8645 (when
8646 (and (equal key (car r))
8647 (if (functionp rr) (funcall rr)
8648 (or (and (eq (car rr) 'in-file)
8649 (buffer-file-name)
8650 (string-match (cdr rr) (buffer-file-name)))
8651 (and (eq (car rr) 'in-mode)
8652 (string-match (cdr rr) (symbol-name major-mode)))
8653 (when (and (eq (car rr) 'not-in-file)
8654 (buffer-file-name))
8655 (not (string-match (cdr rr) (buffer-file-name))))
8656 (when (eq (car rr) 'not-in-mode)
8657 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8658 (push r res)))
8659 (car (last r))))
8660 (delete-dups (delq nil res))))
8662 (defun org-context-p (&rest contexts)
8663 "Check if local context is any of CONTEXTS.
8664 Possible values in the list of contexts are `table', `headline', and `item'."
8665 (let ((pos (point)))
8666 (goto-char (point-at-bol))
8667 (prog1 (or (and (memq 'table contexts)
8668 (looking-at "[ \t]*|"))
8669 (and (memq 'headline contexts)
8670 (looking-at org-outline-regexp))
8671 (and (memq 'item contexts)
8672 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8673 (and (memq 'item-body contexts)
8674 (org-in-item-p)))
8675 (goto-char pos))))
8677 (defun org-get-local-variables ()
8678 "Return a list of all local variables in an Org mode buffer."
8679 (let (varlist)
8680 (with-current-buffer (get-buffer-create "*Org tmp*")
8681 (erase-buffer)
8682 (org-mode)
8683 (setq varlist (buffer-local-variables)))
8684 (kill-buffer "*Org tmp*")
8685 (delq nil
8686 (mapcar
8687 (lambda (x)
8688 (setq x
8689 (if (symbolp x)
8690 (list x)
8691 (list (car x) (list 'quote (cdr x)))))
8692 (if (string-match
8693 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8694 (symbol-name (car x)))
8695 x nil))
8696 varlist))))
8698 (defun org-clone-local-variables (from-buffer &optional regexp)
8699 "Clone local variables from FROM-BUFFER.
8700 Optional argument REGEXP selects variables to clone."
8701 (mapc
8702 (lambda (pair)
8703 (and (symbolp (car pair))
8704 (or (null regexp)
8705 (string-match regexp (symbol-name (car pair))))
8706 (set (make-local-variable (car pair))
8707 (cdr pair))))
8708 (buffer-local-variables from-buffer)))
8710 ;;;###autoload
8711 (defun org-run-like-in-org-mode (cmd)
8712 "Run a command, pretending that the current buffer is in Org-mode.
8713 This will temporarily bind local variables that are typically bound in
8714 Org-mode to the values they have in Org-mode, and then interactively
8715 call CMD."
8716 (org-load-modules-maybe)
8717 (unless org-local-vars
8718 (setq org-local-vars (org-get-local-variables)))
8719 (eval (list 'let org-local-vars
8720 (list 'call-interactively (list 'quote cmd)))))
8722 ;;;; Archiving
8724 (defun org-get-category (&optional pos force-refresh)
8725 "Get the category applying to position POS."
8726 (save-match-data
8727 (if force-refresh (org-refresh-category-properties))
8728 (let ((pos (or pos (point))))
8729 (or (get-text-property pos 'org-category)
8730 (progn (org-refresh-category-properties)
8731 (get-text-property pos 'org-category))))))
8733 (defun org-refresh-category-properties ()
8734 "Refresh category text properties in the buffer."
8735 (let ((case-fold-search t)
8736 (inhibit-read-only t)
8737 (def-cat (cond
8738 ((null org-category)
8739 (if buffer-file-name
8740 (file-name-sans-extension
8741 (file-name-nondirectory buffer-file-name))
8742 "???"))
8743 ((symbolp org-category) (symbol-name org-category))
8744 (t org-category)))
8745 beg end cat pos optionp)
8746 (org-unmodified
8747 (save-excursion
8748 (save-restriction
8749 (widen)
8750 (goto-char (point-min))
8751 (put-text-property (point) (point-max) 'org-category def-cat)
8752 (while (re-search-forward
8753 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8754 (setq pos (match-end 0)
8755 optionp (equal (char-after (match-beginning 0)) ?#)
8756 cat (org-trim (match-string 2)))
8757 (if optionp
8758 (setq beg (point-at-bol) end (point-max))
8759 (org-back-to-heading t)
8760 (setq beg (point) end (org-end-of-subtree t t)))
8761 (put-text-property beg end 'org-category cat)
8762 (put-text-property beg end 'org-category-position beg)
8763 (goto-char pos)))))))
8766 ;;;; Link Stuff
8768 ;;; Link abbreviations
8770 (defun org-link-expand-abbrev (link)
8771 "Apply replacements as defined in `org-link-abbrev-alist'."
8772 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8773 (let* ((key (match-string 1 link))
8774 (as (or (assoc key org-link-abbrev-alist-local)
8775 (assoc key org-link-abbrev-alist)))
8776 (tag (and (match-end 2) (match-string 3 link)))
8777 rpl)
8778 (if (not as)
8779 link
8780 (setq rpl (cdr as))
8781 (cond
8782 ((symbolp rpl) (funcall rpl tag))
8783 ((string-match "%(\\([^)]+\\))" rpl)
8784 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8785 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8786 ((string-match "%h" rpl)
8787 (replace-match (url-hexify-string (or tag "")) t t rpl))
8788 (t (concat rpl tag)))))
8789 link))
8791 ;;; Storing and inserting links
8793 (defvar org-insert-link-history nil
8794 "Minibuffer history for links inserted with `org-insert-link'.")
8796 (defvar org-stored-links nil
8797 "Contains the links stored with `org-store-link'.")
8799 (defvar org-store-link-plist nil
8800 "Plist with info about the most recently link created with `org-store-link'.")
8802 (defvar org-link-protocols nil
8803 "Link protocols added to Org-mode using `org-add-link-type'.")
8805 (defvar org-store-link-functions nil
8806 "List of functions that are called to create and store a link.
8807 Each function will be called in turn until one returns a non-nil
8808 value. Each function should check if it is responsible for creating
8809 this link (for example by looking at the major mode).
8810 If not, it must exit and return nil.
8811 If yes, it should return a non-nil value after a calling
8812 `org-store-link-props' with a list of properties and values.
8813 Special properties are:
8815 :type The link prefix, like \"http\". This must be given.
8816 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8817 This is obligatory as well.
8818 :description Optional default description for the second pair
8819 of brackets in an Org-mode link. The user can still change
8820 this when inserting this link into an Org-mode buffer.
8822 In addition to these, any additional properties can be specified
8823 and then used in capture templates.")
8825 (defun org-add-link-type (type &optional follow export)
8826 "Add TYPE to the list of `org-link-types'.
8827 Re-compute all regular expressions depending on `org-link-types'
8829 FOLLOW and EXPORT are two functions.
8831 FOLLOW should take the link path as the single argument and do whatever
8832 is necessary to follow the link, for example find a file or display
8833 a mail message.
8835 EXPORT should format the link path for export to one of the export formats.
8836 It should be a function accepting three arguments:
8838 path the path of the link, the text after the prefix (like \"http:\")
8839 desc the description of the link, if any, or a description added by
8840 org-export-normalize-links if there is none
8841 format the export format, a symbol like `html' or `latex' or `ascii'..
8843 The function may use the FORMAT information to return different values
8844 depending on the format. The return value will be put literally into
8845 the exported file. If the return value is nil, this means Org should
8846 do what it normally does with links which do not have EXPORT defined.
8848 Org-mode has a built-in default for exporting links. If you are happy with
8849 this default, there is no need to define an export function for the link
8850 type. For a simple example of an export function, see `org-bbdb.el'."
8851 (add-to-list 'org-link-types type t)
8852 (org-make-link-regexps)
8853 (if (assoc type org-link-protocols)
8854 (setcdr (assoc type org-link-protocols) (list follow export))
8855 (push (list type follow export) org-link-protocols)))
8857 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8858 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8860 ;;;###autoload
8861 (defun org-store-link (arg)
8862 "\\<org-mode-map>Store an org-link to the current location.
8863 This link is added to `org-stored-links' and can later be inserted
8864 into an org-buffer with \\[org-insert-link].
8866 For some link types, a prefix arg is interpreted:
8867 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8868 For file links, arg negates `org-context-in-file-links'."
8869 (interactive "P")
8870 (org-load-modules-maybe)
8871 (setq org-store-link-plist nil) ; reset
8872 (org-with-limited-levels
8873 (let (link cpltxt desc description search txt custom-id agenda-link)
8874 (cond
8876 ((run-hook-with-args-until-success 'org-store-link-functions)
8877 (setq link (plist-get org-store-link-plist :link)
8878 desc (or (plist-get org-store-link-plist :description) link)))
8880 ((org-src-edit-buffer-p)
8881 (let (label gc)
8882 (while (or (not label)
8883 (save-excursion
8884 (save-restriction
8885 (widen)
8886 (goto-char (point-min))
8887 (re-search-forward
8888 (regexp-quote (format org-coderef-label-format label))
8889 nil t))))
8890 (when label (message "Label exists already") (sit-for 2))
8891 (setq label (read-string "Code line label: " label)))
8892 (end-of-line 1)
8893 (setq link (format org-coderef-label-format label))
8894 (setq gc (- 79 (length link)))
8895 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8896 (insert link)
8897 (setq link (concat "(" label ")") desc nil)))
8899 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8900 ;; We are in the agenda, link to referenced location
8901 (let ((m (or (get-text-property (point) 'org-hd-marker)
8902 (get-text-property (point) 'org-marker))))
8903 (when m
8904 (org-with-point-at m
8905 (setq agenda-link
8906 (if (org-called-interactively-p 'any)
8907 (call-interactively 'org-store-link)
8908 (org-store-link nil)))))))
8910 ((eq major-mode 'calendar-mode)
8911 (let ((cd (calendar-cursor-to-date)))
8912 (setq link
8913 (format-time-string
8914 (car org-time-stamp-formats)
8915 (apply 'encode-time
8916 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8917 nil nil nil))))
8918 (org-store-link-props :type "calendar" :date cd)))
8920 ((eq major-mode 'help-mode)
8921 (setq link (concat "help:" (save-excursion
8922 (goto-char (point-min))
8923 (looking-at "^[^ ]+")
8924 (match-string 0))))
8925 (org-store-link-props :type "help"))
8927 ((eq major-mode 'w3-mode)
8928 (setq cpltxt (if (and (buffer-name)
8929 (not (string-match "Untitled" (buffer-name))))
8930 (buffer-name)
8931 (url-view-url t))
8932 link (url-view-url t))
8933 (org-store-link-props :type "w3" :url (url-view-url t)))
8935 ((eq major-mode 'w3m-mode)
8936 (setq cpltxt (or w3m-current-title w3m-current-url)
8937 link w3m-current-url)
8938 (org-store-link-props :type "w3m" :url (url-view-url t)))
8940 ((setq search (run-hook-with-args-until-success
8941 'org-create-file-search-functions))
8942 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8943 "::" search))
8944 (setq cpltxt (or description link)))
8946 ((eq major-mode 'image-mode)
8947 (setq cpltxt (concat "file:"
8948 (abbreviate-file-name buffer-file-name))
8949 link cpltxt)
8950 (org-store-link-props :type "image" :file buffer-file-name))
8952 ((eq major-mode 'dired-mode)
8953 ;; link to the file in the current line
8954 (let ((file (dired-get-filename nil t)))
8955 (setq file (if file
8956 (abbreviate-file-name
8957 (expand-file-name (dired-get-filename nil t)))
8958 ;; otherwise, no file so use current directory.
8959 default-directory))
8960 (setq cpltxt (concat "file:" file)
8961 link cpltxt)))
8963 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8964 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8965 (cond
8966 ((org-in-regexp "<<\\(.*?\\)>>")
8967 (setq cpltxt
8968 (concat "file:"
8969 (abbreviate-file-name
8970 (buffer-file-name (buffer-base-buffer)))
8971 "::" (match-string 1))
8972 link cpltxt))
8973 ((and (featurep 'org-id)
8974 (or (eq org-link-to-org-use-id t)
8975 (and (org-called-interactively-p 'any)
8976 (or (eq org-link-to-org-use-id 'create-if-interactive)
8977 (and (eq org-link-to-org-use-id
8978 'create-if-interactive-and-no-custom-id)
8979 (not custom-id))))
8980 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8981 ;; We can make a link using the ID.
8982 (setq link (condition-case nil
8983 (prog1 (org-id-store-link)
8984 (setq desc (plist-get org-store-link-plist :description)))
8985 (error
8986 ;; probably before first headline, link to file only
8987 (concat "file:"
8988 (abbreviate-file-name
8989 (buffer-file-name (buffer-base-buffer))))))))
8991 ;; Just link to current headline
8992 (setq cpltxt (concat "file:"
8993 (abbreviate-file-name
8994 (buffer-file-name (buffer-base-buffer)))))
8995 ;; Add a context search string
8996 (when (org-xor org-context-in-file-links arg)
8997 (setq txt (cond
8998 ((org-at-heading-p) nil)
8999 ((org-region-active-p)
9000 (buffer-substring (region-beginning) (region-end)))))
9001 (when (or (null txt) (string-match "\\S-" txt))
9002 (setq cpltxt
9003 (concat cpltxt "::"
9004 (condition-case nil
9005 (org-make-org-heading-search-string txt)
9006 (error "")))
9007 desc (or (nth 4 (ignore-errors
9008 (org-heading-components))) "NONE"))))
9009 (if (string-match "::\\'" cpltxt)
9010 (setq cpltxt (substring cpltxt 0 -2)))
9011 (setq link cpltxt))))
9013 ((buffer-file-name (buffer-base-buffer))
9014 ;; Just link to this file here.
9015 (setq cpltxt (concat "file:"
9016 (abbreviate-file-name
9017 (buffer-file-name (buffer-base-buffer)))))
9018 ;; Add a context string
9019 (when (org-xor org-context-in-file-links arg)
9020 (setq txt (if (org-region-active-p)
9021 (buffer-substring (region-beginning) (region-end))
9022 (buffer-substring (point-at-bol) (point-at-eol))))
9023 ;; Only use search option if there is some text.
9024 (when (string-match "\\S-" txt)
9025 (setq cpltxt
9026 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9027 desc "NONE")))
9028 (setq link cpltxt))
9030 ((org-called-interactively-p 'interactive)
9031 (error "Cannot link to a buffer which is not visiting a file"))
9033 (t (setq link nil)))
9035 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9036 (setq link (or link cpltxt)
9037 desc (or desc cpltxt))
9038 (if (equal desc "NONE") (setq desc nil))
9040 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9041 (progn
9042 (setq org-stored-links
9043 (cons (list link desc) org-stored-links))
9044 (message "Stored: %s" (or desc link))
9045 (when custom-id
9046 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9047 "::#" custom-id))
9048 (setq org-stored-links
9049 (cons (list link desc) org-stored-links))))
9050 (or agenda-link (and link (org-make-link-string link desc)))))))
9052 (defun org-store-link-props (&rest plist)
9053 "Store link properties, extract names and addresses."
9054 (let (x adr)
9055 (when (setq x (plist-get plist :from))
9056 (setq adr (mail-extract-address-components x))
9057 (setq plist (plist-put plist :fromname (car adr)))
9058 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9059 (when (setq x (plist-get plist :to))
9060 (setq adr (mail-extract-address-components x))
9061 (setq plist (plist-put plist :toname (car adr)))
9062 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9063 (let ((from (plist-get plist :from))
9064 (to (plist-get plist :to)))
9065 (when (and from to org-from-is-user-regexp)
9066 (setq plist
9067 (plist-put plist :fromto
9068 (if (string-match org-from-is-user-regexp from)
9069 (concat "to %t")
9070 (concat "from %f"))))))
9071 (setq org-store-link-plist plist))
9073 (defun org-add-link-props (&rest plist)
9074 "Add these properties to the link property list."
9075 (let (key value)
9076 (while plist
9077 (setq key (pop plist) value (pop plist))
9078 (setq org-store-link-plist
9079 (plist-put org-store-link-plist key value)))))
9081 (defun org-email-link-description (&optional fmt)
9082 "Return the description part of an email link.
9083 This takes information from `org-store-link-plist' and formats it
9084 according to FMT (default from `org-email-link-description-format')."
9085 (setq fmt (or fmt org-email-link-description-format))
9086 (let* ((p org-store-link-plist)
9087 (to (plist-get p :toaddress))
9088 (from (plist-get p :fromaddress))
9089 (table
9090 (list
9091 (cons "%c" (plist-get p :fromto))
9092 (cons "%F" (plist-get p :from))
9093 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9094 (cons "%T" (plist-get p :to))
9095 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9096 (cons "%s" (plist-get p :subject))
9097 (cons "%d" (plist-get p :date))
9098 (cons "%m" (plist-get p :message-id)))))
9099 (when (string-match "%c" fmt)
9100 ;; Check if the user wrote this message
9101 (if (and org-from-is-user-regexp from to
9102 (save-match-data (string-match org-from-is-user-regexp from)))
9103 (setq fmt (replace-match "to %t" t t fmt))
9104 (setq fmt (replace-match "from %f" t t fmt))))
9105 (org-replace-escapes fmt table)))
9107 (defun org-make-org-heading-search-string (&optional string heading)
9108 "Make search string for STRING or current headline."
9109 (interactive)
9110 (let ((s (or string (org-get-heading)))
9111 (lines org-context-in-file-links))
9112 (unless (and string (not heading))
9113 ;; We are using a headline, clean up garbage in there.
9114 (if (string-match org-todo-regexp s)
9115 (setq s (replace-match "" t t s)))
9116 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9117 (setq s (replace-match "" t t s)))
9118 (setq s (org-trim s))
9119 (if (string-match (concat "^\\(" org-quote-string "\\|"
9120 org-comment-string "\\)") s)
9121 (setq s (replace-match "" t t s)))
9122 (while (string-match org-ts-regexp s)
9123 (setq s (replace-match "" t t s))))
9124 (or string (setq s (concat "*" s))) ; Add * for headlines
9125 (when (and string (integerp lines) (> lines 0))
9126 (let ((slines (org-split-string s "\n")))
9127 (when (< lines (length slines))
9128 (setq s (mapconcat
9129 'identity
9130 (reverse (nthcdr (- (length slines) lines)
9131 (reverse slines))) "\n")))))
9132 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9134 (defun org-make-link-string (link &optional description)
9135 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9136 (unless (string-match "\\S-" link)
9137 (error "Empty link"))
9138 (when (and description
9139 (stringp description)
9140 (not (string-match "\\S-" description)))
9141 (setq description nil))
9142 (when (stringp description)
9143 ;; Remove brackets from the description, they are fatal.
9144 (while (string-match "\\[" description)
9145 (setq description (replace-match "{" t t description)))
9146 (while (string-match "\\]" description)
9147 (setq description (replace-match "}" t t description))))
9148 (when (equal link description)
9149 ;; No description needed, it is identical
9150 (setq description nil))
9151 (when (and (not description)
9152 (not (string-match (org-image-file-name-regexp) link))
9153 (not (equal link (org-link-escape link))))
9154 (setq description (org-extract-attributes link)))
9155 (setq link
9156 (cond ((string-match (org-image-file-name-regexp) link) link)
9157 ((string-match org-link-types-re link)
9158 (concat (match-string 1 link)
9159 (org-link-escape (substring link (match-end 1)))))
9160 (t (org-link-escape link))))
9161 (concat "[[" link "]"
9162 (if description (concat "[" description "]") "")
9163 "]"))
9165 (defconst org-link-escape-chars
9166 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9167 "List of characters that should be escaped in link.
9168 This is the list that is used for internal purposes.")
9170 (defconst org-link-escape-chars-browser
9171 '(?\ )
9172 "List of escapes for characters that are problematic in links.
9173 This is the list that is used before handing over to the browser.")
9175 (defun org-link-escape (text &optional table merge)
9176 "Return percent escaped representation of TEXT.
9177 TEXT is a string with the text to escape.
9178 Optional argument TABLE is a list with characters that should be
9179 escaped. When nil, `org-link-escape-chars' is used.
9180 If optional argument MERGE is set, merge TABLE into
9181 `org-link-escape-chars'."
9182 (cond
9183 ((and table merge)
9184 (mapc (lambda (defchr)
9185 (unless (member defchr table)
9186 (setq table (cons defchr table)))) org-link-escape-chars))
9187 ((null table)
9188 (setq table org-link-escape-chars)))
9189 (mapconcat
9190 (lambda (char)
9191 (if (or (member char table)
9192 (and (or (< char 32) (= char 37) (> char 126))
9193 org-url-hexify-p))
9194 (mapconcat (lambda (sequence-element)
9195 (format "%%%.2X" sequence-element))
9196 (or (encode-coding-char char 'utf-8)
9197 (error "Unable to percent escape character: %s"
9198 (char-to-string char))) "")
9199 (char-to-string char))) text ""))
9201 (defun org-link-unescape (str)
9202 "Unhex hexified Unicode strings as returned from the JavaScript function
9203 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9204 (unless (and (null str) (string= "" str))
9205 (let ((pos 0) (case-fold-search t) unhexed)
9206 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9207 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9208 (setq str (replace-match unhexed t t str))
9209 (setq pos (+ pos (length unhexed))))))
9210 str)
9212 (defun org-link-unescape-compound (hex)
9213 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9214 Note: this function also decodes single byte encodings like
9215 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9216 (save-match-data
9217 (let* ((bytes (cdr (split-string hex "%")))
9218 (ret "")
9219 (eat 0)
9220 (sum 0))
9221 (while bytes
9222 (let* ((val (string-to-number (pop bytes) 16))
9223 (shift-xor
9224 (if (= 0 eat)
9225 (cond
9226 ((>= val 252) (cons 6 252))
9227 ((>= val 248) (cons 5 248))
9228 ((>= val 240) (cons 4 240))
9229 ((>= val 224) (cons 3 224))
9230 ((>= val 192) (cons 2 192))
9231 (t (cons 0 0)))
9232 (cons 6 128))))
9233 (if (>= val 192) (setq eat (car shift-xor)))
9234 (setq val (logxor val (cdr shift-xor)))
9235 (setq sum (+ (lsh sum (car shift-xor)) val))
9236 (if (> eat 0) (setq eat (- eat 1)))
9237 (cond
9238 ((= 0 eat) ;multi byte
9239 (setq ret (concat ret (org-char-to-string sum)))
9240 (setq sum 0))
9241 ((not bytes) ; single byte(s)
9242 (setq ret (org-link-unescape-single-byte-sequence hex))))
9243 )) ;; end (while bytes
9244 ret )))
9246 (defun org-link-unescape-single-byte-sequence (hex)
9247 "Unhexify hex-encoded single byte character sequences."
9248 (mapconcat (lambda (byte)
9249 (char-to-string (string-to-number byte 16)))
9250 (cdr (split-string hex "%")) ""))
9252 (defun org-xor (a b)
9253 "Exclusive or."
9254 (if a (not b) b))
9256 (defun org-fixup-message-id-for-http (s)
9257 "Replace special characters in a message id, so it can be used in an http query."
9258 (when (string-match "%" s)
9259 (setq s (mapconcat (lambda (c)
9260 (if (eq c ?%)
9261 "%25"
9262 (char-to-string c)))
9263 s "")))
9264 (while (string-match "<" s)
9265 (setq s (replace-match "%3C" t t s)))
9266 (while (string-match ">" s)
9267 (setq s (replace-match "%3E" t t s)))
9268 (while (string-match "@" s)
9269 (setq s (replace-match "%40" t t s)))
9272 (defun org-link-prettify (link)
9273 "Return a human-readable representation of LINK.
9274 The car of LINK must be a raw link the cdr of LINK must be either
9275 a link description or nil."
9276 (let ((desc (or (cadr link) "<no description>")))
9277 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9278 "<" (car link) ">")))
9280 ;;;###autoload
9281 (defun org-insert-link-global ()
9282 "Insert a link like Org-mode does.
9283 This command can be called in any mode to insert a link in Org-mode syntax."
9284 (interactive)
9285 (org-load-modules-maybe)
9286 (org-run-like-in-org-mode 'org-insert-link))
9288 (defun org-insert-all-links (&optional keep)
9289 "Insert all links in `org-stored-links'."
9290 (interactive "P")
9291 (let ((links (copy-sequence org-stored-links)) l)
9292 (while (setq l (if keep (pop links) (pop org-stored-links)))
9293 (insert "- ")
9294 (org-insert-link nil (car l) (cadr l))
9295 (insert "\n"))))
9297 (defun org-link-fontify-links-to-this-file ()
9298 "Fontify links to the current file in `org-stored-links'."
9299 (let ((f (buffer-file-name)) a b)
9300 (setq a (mapcar (lambda(l)
9301 (let ((ll (car l)))
9302 (when (and (string-match "^file:\\(.+\\)::" ll)
9303 (equal f (expand-file-name (match-string 1 ll))))
9304 ll)))
9305 org-stored-links))
9306 (when (featurep 'org-id)
9307 (setq b (mapcar (lambda(l)
9308 (let ((ll (car l)))
9309 (when (and (string-match "^id:\\(.+\\)$" ll)
9310 (equal f (expand-file-name
9311 (or (org-id-find-id-file
9312 (match-string 1 ll)) ""))))
9313 ll)))
9314 org-stored-links)))
9315 (mapcar (lambda(l)
9316 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9317 (delq nil (append a b)))))
9319 (defvar org-link-links-in-this-file nil)
9320 (defun org-insert-link (&optional complete-file link-location default-description)
9321 "Insert a link. At the prompt, enter the link.
9323 Completion can be used to insert any of the link protocol prefixes like
9324 http or ftp in use.
9326 The history can be used to select a link previously stored with
9327 `org-store-link'. When the empty string is entered (i.e. if you just
9328 press RET at the prompt), the link defaults to the most recently
9329 stored link. As SPC triggers completion in the minibuffer, you need to
9330 use M-SPC or C-q SPC to force the insertion of a space character.
9332 You will also be prompted for a description, and if one is given, it will
9333 be displayed in the buffer instead of the link.
9335 If there is already a link at point, this command will allow you to edit link
9336 and description parts.
9338 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9339 be selected using completion. The path to the file will be relative to the
9340 current directory if the file is in the current directory or a subdirectory.
9341 Otherwise, the link will be the absolute path as completed in the minibuffer
9342 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9343 option `org-link-file-path-type'.
9345 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9346 the current directory or below.
9348 With three \\[universal-argument] prefixes, negate the meaning of
9349 `org-keep-stored-link-after-insertion'.
9351 If `org-make-link-description-function' is non-nil, this function will be
9352 called with the link target, and the result will be the default
9353 link description.
9355 If the LINK-LOCATION parameter is non-nil, this value will be
9356 used as the link location instead of reading one interactively.
9358 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9359 be used as the default description."
9360 (interactive "P")
9361 (let* ((wcf (current-window-configuration))
9362 (origbuf (current-buffer))
9363 (region (if (org-region-active-p)
9364 (buffer-substring (region-beginning) (region-end))))
9365 (remove (and region (list (region-beginning) (region-end))))
9366 (desc region)
9367 tmphist ; byte-compile incorrectly complains about this
9368 (link link-location)
9369 (abbrevs org-link-abbrev-alist-local)
9370 entry file all-prefixes auto-desc)
9371 (cond
9372 (link-location) ; specified by arg, just use it.
9373 ((org-in-regexp org-bracket-link-regexp 1)
9374 ;; We do have a link at point, and we are going to edit it.
9375 (setq remove (list (match-beginning 0) (match-end 0)))
9376 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9377 (setq link (read-string "Link: "
9378 (org-link-unescape
9379 (org-match-string-no-properties 1)))))
9380 ((or (org-in-regexp org-angle-link-re)
9381 (org-in-regexp org-plain-link-re))
9382 ;; Convert to bracket link
9383 (setq remove (list (match-beginning 0) (match-end 0))
9384 link (read-string "Link: "
9385 (org-remove-angle-brackets (match-string 0)))))
9386 ((member complete-file '((4) (16)))
9387 ;; Completing read for file names.
9388 (setq link (org-file-complete-link complete-file)))
9390 ;; Read link, with completion for stored links.
9391 (org-link-fontify-links-to-this-file)
9392 (org-switch-to-buffer-other-window "*Org Links*")
9393 (with-current-buffer "*Org Links*"
9394 (erase-buffer)
9395 (insert "Insert a link.
9396 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9397 (when org-stored-links
9398 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9399 (insert (mapconcat 'org-link-prettify
9400 (reverse org-stored-links) "\n")))
9401 (goto-char (point-min)))
9402 (let ((cw (selected-window)))
9403 (select-window (get-buffer-window "*Org Links*" 'visible))
9404 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9405 (unless (pos-visible-in-window-p (point-max))
9406 (org-fit-window-to-buffer))
9407 (and (window-live-p cw) (select-window cw)))
9408 ;; Fake a link history, containing the stored links.
9409 (setq tmphist (append (mapcar 'car org-stored-links)
9410 org-insert-link-history))
9411 (setq all-prefixes (append (mapcar 'car abbrevs)
9412 (mapcar 'car org-link-abbrev-alist)
9413 org-link-types))
9414 (unwind-protect
9415 (progn
9416 (setq link
9417 (org-completing-read
9418 "Link: "
9419 (append
9420 (mapcar (lambda (x) (concat x ":"))
9421 all-prefixes)
9422 (mapcar 'car org-stored-links))
9423 nil nil nil
9424 'tmphist
9425 (caar org-stored-links)))
9426 (if (not (string-match "\\S-" link))
9427 (error "No link selected"))
9428 (mapc (lambda(l)
9429 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9430 org-stored-links)
9431 (if (or (member link all-prefixes)
9432 (and (equal ":" (substring link -1))
9433 (member (substring link 0 -1) all-prefixes)
9434 (setq link (substring link 0 -1))))
9435 (setq link (with-current-buffer origbuf
9436 (org-link-try-special-completion link)))))
9437 (set-window-configuration wcf)
9438 (kill-buffer "*Org Links*"))
9439 (setq entry (assoc link org-stored-links))
9440 (or entry (push link org-insert-link-history))
9441 (setq desc (or desc (nth 1 entry)))))
9443 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9444 (not org-keep-stored-link-after-insertion))
9445 (setq org-stored-links (delq (assoc link org-stored-links)
9446 org-stored-links)))
9448 (if (string-match org-plain-link-re link)
9449 ;; URL-like link, normalize the use of angular brackets.
9450 (setq link (org-remove-angle-brackets link)))
9452 ;; Check if we are linking to the current file with a search option
9453 ;; If yes, simplify the link by using only the search option.
9454 (when (and buffer-file-name
9455 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9456 (let* ((path (match-string 1 link))
9457 (case-fold-search nil)
9458 (search (match-string 2 link)))
9459 (save-match-data
9460 (if (equal (file-truename buffer-file-name) (file-truename path))
9461 ;; We are linking to this same file, with a search option
9462 (setq link search)))))
9464 ;; Check if we can/should use a relative path. If yes, simplify the link
9465 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9466 (let* ((type (match-string 1 link))
9467 (path (match-string 2 link))
9468 (origpath path)
9469 (case-fold-search nil))
9470 (cond
9471 ((or (eq org-link-file-path-type 'absolute)
9472 (equal complete-file '(16)))
9473 (setq path (abbreviate-file-name (expand-file-name path))))
9474 ((eq org-link-file-path-type 'noabbrev)
9475 (setq path (expand-file-name path)))
9476 ((eq org-link-file-path-type 'relative)
9477 (setq path (file-relative-name path)))
9479 (save-match-data
9480 (if (string-match (concat "^" (regexp-quote
9481 (expand-file-name
9482 (file-name-as-directory
9483 default-directory))))
9484 (expand-file-name path))
9485 ;; We are linking a file with relative path name.
9486 (setq path (substring (expand-file-name path)
9487 (match-end 0)))
9488 (setq path (abbreviate-file-name (expand-file-name path)))))))
9489 (setq link (concat type path))
9490 (if (equal desc origpath)
9491 (setq desc path))))
9493 (if org-make-link-description-function
9494 (setq desc
9495 (or (condition-case nil
9496 (funcall org-make-link-description-function link desc)
9497 (error (progn (message "Can't get link description from `%s'"
9498 (symbol-name org-make-link-description-function))
9499 (sit-for 2) nil)))
9500 (read-string "Description: " default-description)))
9501 (if default-description (setq desc default-description)
9502 (setq desc (or (and auto-desc desc)
9503 (read-string "Description: " desc)))))
9505 (unless (string-match "\\S-" desc) (setq desc nil))
9506 (if remove (apply 'delete-region remove))
9507 (insert (org-make-link-string link desc))))
9509 (defun org-link-try-special-completion (type)
9510 "If there is completion support for link type TYPE, offer it."
9511 (let ((fun (intern (concat "org-" type "-complete-link"))))
9512 (if (functionp fun)
9513 (funcall fun)
9514 (read-string "Link (no completion support): " (concat type ":")))))
9516 (defun org-file-complete-link (&optional arg)
9517 "Create a file link using completion."
9518 (let (file link)
9519 (setq file (org-iread-file-name "File: "))
9520 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9521 (pwd1 (file-name-as-directory (abbreviate-file-name
9522 (expand-file-name ".")))))
9523 (cond
9524 ((equal arg '(16))
9525 (setq link (concat
9526 "file:"
9527 (abbreviate-file-name (expand-file-name file)))))
9528 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9529 (setq link (concat "file:" (match-string 1 file))))
9530 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9531 (expand-file-name file))
9532 (setq link (concat
9533 "file:" (match-string 1 (expand-file-name file)))))
9534 (t (setq link (concat "file:" file)))))
9535 link))
9537 (defun org-iread-file-name (&rest args)
9538 "Read-file-name using `ido-mode' speedup if available.
9539 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9540 See `read-file-name' for a description of parameters."
9541 (org-without-partial-completion
9542 (if (and org-completion-use-ido
9543 (fboundp 'ido-read-file-name)
9544 (boundp 'ido-mode) ido-mode
9545 (listp (second args)))
9546 (let ((ido-enter-matching-directory nil))
9547 (apply 'ido-read-file-name args))
9548 (apply 'read-file-name args))))
9550 (defun org-completing-read (&rest args)
9551 "Completing-read with SPACE being a normal character."
9552 (let ((enable-recursive-minibuffers t)
9553 (minibuffer-local-completion-map
9554 (copy-keymap minibuffer-local-completion-map)))
9555 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9556 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9557 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9558 (apply 'org-icompleting-read args)))
9560 (defun org-completing-read-no-i (&rest args)
9561 (let (org-completion-use-ido org-completion-use-iswitchb)
9562 (apply 'org-completing-read args)))
9564 (defun org-iswitchb-completing-read (prompt choices &rest args)
9565 "Use iswitch as a completing-read replacement to choose from choices.
9566 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9567 from."
9568 (let* ((iswitchb-use-virtual-buffers nil)
9569 (iswitchb-make-buflist-hook
9570 (lambda ()
9571 (setq iswitchb-temp-buflist choices))))
9572 (iswitchb-read-buffer prompt)))
9574 (defun org-icompleting-read (&rest args)
9575 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9576 (org-without-partial-completion
9577 (if (and org-completion-use-ido
9578 (fboundp 'ido-completing-read)
9579 (boundp 'ido-mode) ido-mode
9580 (listp (second args)))
9581 (let ((ido-enter-matching-directory nil))
9582 (apply 'ido-completing-read (concat (car args))
9583 (if (consp (car (nth 1 args)))
9584 (mapcar 'car (nth 1 args))
9585 (nth 1 args))
9586 (cddr args)))
9587 (if (and org-completion-use-iswitchb
9588 (boundp 'iswitchb-mode) iswitchb-mode
9589 (listp (second args)))
9590 (apply 'org-iswitchb-completing-read (concat (car args))
9591 (if (consp (car (nth 1 args)))
9592 (mapcar 'car (nth 1 args))
9593 (nth 1 args))
9594 (cddr args))
9595 (apply 'completing-read args)))))
9597 (defun org-extract-attributes (s)
9598 "Extract the attributes cookie from a string and set as text property."
9599 (let (a attr (start 0) key value)
9600 (save-match-data
9601 (when (string-match "{{\\([^}]+\\)}}$" s)
9602 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9603 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9604 (setq key (match-string 1 a) value (match-string 2 a)
9605 start (match-end 0)
9606 attr (plist-put attr (intern key) value))))
9607 (org-add-props s nil 'org-attr attr))
9610 (defun org-extract-attributes-from-string (tag)
9611 (let (key value attr)
9612 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9613 (setq key (match-string 1 tag) value (match-string 2 tag)
9614 tag (replace-match "" t t tag)
9615 attr (plist-put attr (intern key) value)))
9616 (cons tag attr)))
9618 (defun org-attributes-to-string (plist)
9619 "Format a property list into an HTML attribute list."
9620 (let ((s "") key value)
9621 (while plist
9622 (setq key (pop plist) value (pop plist))
9623 (and value
9624 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9627 ;;; Opening/following a link
9629 (defvar org-link-search-failed nil)
9631 (defvar org-open-link-functions nil
9632 "Hook for functions finding a plain text link.
9633 These functions must take a single argument, the link content.
9634 They will be called for links that look like [[link text][description]]
9635 when LINK TEXT does not have a protocol like \"http:\" and does not look
9636 like a filename (e.g. \"./blue.png\").
9638 These functions will be called *before* Org attempts to resolve the
9639 link by doing text searches in the current buffer - so if you want a
9640 link \"[[target]]\" to still find \"<<target>>\", your function should
9641 handle this as a special case.
9643 When the function does handle the link, it must return a non-nil value.
9644 If it decides that it is not responsible for this link, it must return
9645 nil to indicate that that Org-mode can continue with other options
9646 like exact and fuzzy text search.")
9648 (defun org-next-link ()
9649 "Move forward to the next link.
9650 If the link is in hidden text, expose it."
9651 (interactive)
9652 (when (and org-link-search-failed (eq this-command last-command))
9653 (goto-char (point-min))
9654 (message "Link search wrapped back to beginning of buffer"))
9655 (setq org-link-search-failed nil)
9656 (let* ((pos (point))
9657 (ct (org-context))
9658 (a (assoc :link ct)))
9659 (if a (goto-char (nth 2 a)))
9660 (if (re-search-forward org-any-link-re nil t)
9661 (progn
9662 (goto-char (match-beginning 0))
9663 (if (outline-invisible-p) (org-show-context)))
9664 (goto-char pos)
9665 (setq org-link-search-failed t)
9666 (error "No further link found"))))
9668 (defun org-previous-link ()
9669 "Move backward to the previous link.
9670 If the link is in hidden text, expose it."
9671 (interactive)
9672 (when (and org-link-search-failed (eq this-command last-command))
9673 (goto-char (point-max))
9674 (message "Link search wrapped back to end of buffer"))
9675 (setq org-link-search-failed nil)
9676 (let* ((pos (point))
9677 (ct (org-context))
9678 (a (assoc :link ct)))
9679 (if a (goto-char (nth 1 a)))
9680 (if (re-search-backward org-any-link-re nil t)
9681 (progn
9682 (goto-char (match-beginning 0))
9683 (if (outline-invisible-p) (org-show-context)))
9684 (goto-char pos)
9685 (setq org-link-search-failed t)
9686 (error "No further link found"))))
9688 (defun org-translate-link (s)
9689 "Translate a link string if a translation function has been defined."
9690 (if (and org-link-translation-function
9691 (fboundp org-link-translation-function)
9692 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9693 (progn
9694 (setq s (funcall org-link-translation-function
9695 (match-string 1 s) (match-string 2 s)))
9696 (concat (car s) ":" (cdr s)))
9699 (defun org-translate-link-from-planner (type path)
9700 "Translate a link from Emacs Planner syntax so that Org can follow it.
9701 This is still an experimental function, your mileage may vary."
9702 (cond
9703 ((member type '("http" "https" "news" "ftp"))
9704 ;; standard Internet links are the same.
9705 nil)
9706 ((and (equal type "irc") (string-match "^//" path))
9707 ;; Planner has two / at the beginning of an irc link, we have 1.
9708 ;; We should have zero, actually....
9709 (setq path (substring path 1)))
9710 ((and (equal type "lisp") (string-match "^/" path))
9711 ;; Planner has a slash, we do not.
9712 (setq type "elisp" path (substring path 1)))
9713 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9714 ;; A typical message link. Planner has the id after the final slash,
9715 ;; we separate it with a hash mark
9716 (setq path (concat (match-string 1 path) "#"
9717 (org-remove-angle-brackets (match-string 2 path)))))
9719 (cons type path))
9721 (defun org-find-file-at-mouse (ev)
9722 "Open file link or URL at mouse."
9723 (interactive "e")
9724 (mouse-set-point ev)
9725 (org-open-at-point 'in-emacs))
9727 (defun org-open-at-mouse (ev)
9728 "Open file link or URL at mouse.
9729 See the docstring of `org-open-file' for details."
9730 (interactive "e")
9731 (mouse-set-point ev)
9732 (if (eq major-mode 'org-agenda-mode)
9733 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9734 (org-open-at-point))
9736 (defvar org-window-config-before-follow-link nil
9737 "The window configuration before following a link.
9738 This is saved in case the need arises to restore it.")
9740 (defvar org-open-link-marker (make-marker)
9741 "Marker pointing to the location where `org-open-at-point; was called.")
9743 ;;;###autoload
9744 (defun org-open-at-point-global ()
9745 "Follow a link like Org-mode does.
9746 This command can be called in any mode to follow a link that has
9747 Org-mode syntax."
9748 (interactive)
9749 (org-run-like-in-org-mode 'org-open-at-point))
9751 ;;;###autoload
9752 (defun org-open-link-from-string (s &optional arg reference-buffer)
9753 "Open a link in the string S, as if it was in Org-mode."
9754 (interactive "sLink: \nP")
9755 (let ((reference-buffer (or reference-buffer (current-buffer))))
9756 (with-temp-buffer
9757 (let ((org-inhibit-startup (not reference-buffer)))
9758 (org-mode)
9759 (insert s)
9760 (goto-char (point-min))
9761 (when reference-buffer
9762 (setq org-link-abbrev-alist-local
9763 (with-current-buffer reference-buffer
9764 org-link-abbrev-alist-local)))
9765 (org-open-at-point arg reference-buffer)))))
9767 (defvar org-open-at-point-functions nil
9768 "Hook that is run when following a link at point.
9770 Functions in this hook must return t if they identify and follow
9771 a link at point. If they don't find anything interesting at point,
9772 they must return nil.")
9774 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9775 (defun org-open-at-point (&optional arg reference-buffer)
9776 "Open link at or after point.
9777 If there is no link at point, this function will search forward up to
9778 the end of the current line.
9779 Normally, files will be opened by an appropriate application. If the
9780 optional prefix argument ARG is non-nil, Emacs will visit the file.
9781 With a double prefix argument, try to open outside of Emacs, in the
9782 application the system uses for this file type."
9783 (interactive "P")
9784 ;; if in a code block, then open the block's results
9785 (unless (call-interactively #'org-babel-open-src-block-result)
9786 (org-load-modules-maybe)
9787 (move-marker org-open-link-marker (point))
9788 (setq org-window-config-before-follow-link (current-window-configuration))
9789 (org-remove-occur-highlights nil nil t)
9790 (cond
9791 ((and (org-at-heading-p)
9792 (not (org-at-timestamp-p t))
9793 (not (org-in-regexp
9794 (concat org-plain-link-re "\\|"
9795 org-bracket-link-regexp "\\|"
9796 org-angle-link-re "\\|"
9797 "[ \t]:[^ \t\n]+:[ \t]*$")))
9798 (not (get-text-property (point) 'org-linked-text)))
9799 (or (org-offer-links-in-entry arg)
9800 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9801 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9802 ((and (org-at-timestamp-p t)
9803 (not (org-in-regexp org-bracket-link-regexp)))
9804 (org-follow-timestamp-link))
9805 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9806 (not (org-in-regexp org-bracket-link-regexp)))
9807 (org-footnote-action))
9809 (let (type path link line search (pos (point)))
9810 (catch 'match
9811 (save-excursion
9812 (skip-chars-forward "^]\n\r")
9813 (when (org-in-regexp org-bracket-link-regexp 1)
9814 (setq link (org-extract-attributes
9815 (org-link-unescape (org-match-string-no-properties 1))))
9816 (while (string-match " *\n *" link)
9817 (setq link (replace-match " " t t link)))
9818 (setq link (org-link-expand-abbrev link))
9819 (cond
9820 ((or (file-name-absolute-p link)
9821 (string-match "^\\.\\.?/" link))
9822 (setq type "file" path link))
9823 ((string-match org-link-re-with-space3 link)
9824 (setq type (match-string 1 link) path (match-string 2 link)))
9825 ((string-match "^help:+\\(.+\\)" link)
9826 (setq type "help" path (match-string 1 link)))
9827 (t (setq type "thisfile" path link)))
9828 (throw 'match t)))
9830 (when (get-text-property (point) 'org-linked-text)
9831 (setq type "thisfile"
9832 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9833 (1+ (point)) (point))
9834 path (buffer-substring
9835 (or (previous-single-property-change pos 'org-linked-text)
9836 (point-min))
9837 (or (next-single-property-change pos 'org-linked-text)
9838 (point-max))))
9839 (throw 'match t))
9841 (save-excursion
9842 (when (or (org-in-regexp org-angle-link-re)
9843 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9844 (save-match-data (not (looking-back "\\[\\[")))))
9845 (setq type (match-string 1)
9846 path (org-link-unescape (match-string 2)))
9847 (throw 'match t)))
9848 (save-excursion
9849 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9850 (setq type "tags"
9851 path (match-string 1))
9852 (while (string-match ":" path)
9853 (setq path (replace-match "+" t t path)))
9854 (throw 'match t)))
9855 (when (org-in-regexp "<\\([^><\n]+\\)>")
9856 (setq type "tree-match"
9857 path (match-string 1))
9858 (throw 'match t)))
9859 (unless path
9860 (error "No link found"))
9862 ;; switch back to reference buffer
9863 ;; needed when if called in a temporary buffer through
9864 ;; org-open-link-from-string
9865 (with-current-buffer (or reference-buffer (current-buffer))
9867 ;; Remove any trailing spaces in path
9868 (if (string-match " +\\'" path)
9869 (setq path (replace-match "" t t path)))
9870 (if (and org-link-translation-function
9871 (fboundp org-link-translation-function))
9872 ;; Check if we need to translate the link
9873 (let ((tmp (funcall org-link-translation-function type path)))
9874 (setq type (car tmp) path (cdr tmp))))
9876 (cond
9878 ((assoc type org-link-protocols)
9879 (funcall (nth 1 (assoc type org-link-protocols)) path))
9881 ((equal type "help")
9882 (let ((f-or-v (intern path)))
9883 (cond ((fboundp f-or-v)
9884 (describe-function f-or-v))
9885 ((boundp f-or-v)
9886 (describe-variable f-or-v))
9887 (t (error "Not a known function or variable")))))
9889 ((equal type "mailto")
9890 (let ((cmd (car org-link-mailto-program))
9891 (args (cdr org-link-mailto-program)) args1
9892 (address path) (subject "") a)
9893 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9894 (setq address (match-string 1 path)
9895 subject (org-link-escape (match-string 2 path))))
9896 (while args
9897 (cond
9898 ((not (stringp (car args))) (push (pop args) args1))
9899 (t (setq a (pop args))
9900 (if (string-match "%a" a)
9901 (setq a (replace-match address t t a)))
9902 (if (string-match "%s" a)
9903 (setq a (replace-match subject t t a)))
9904 (push a args1))))
9905 (apply cmd (nreverse args1))))
9907 ((member type '("http" "https" "ftp" "news"))
9908 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9909 (org-link-escape
9910 path org-link-escape-chars-browser)
9911 path))))
9913 ((string= type "doi")
9914 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9915 (org-link-escape
9916 path org-link-escape-chars-browser)
9917 path))))
9919 ((member type '("message"))
9920 (browse-url (concat type ":" path)))
9922 ((string= type "tags")
9923 (org-tags-view arg path))
9925 ((string= type "tree-match")
9926 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9928 ((string= type "file")
9929 (if (string-match "::\\([0-9]+\\)\\'" path)
9930 (setq line (string-to-number (match-string 1 path))
9931 path (substring path 0 (match-beginning 0)))
9932 (if (string-match "::\\(.+\\)\\'" path)
9933 (setq search (match-string 1 path)
9934 path (substring path 0 (match-beginning 0)))))
9935 (if (string-match "[*?{]" (file-name-nondirectory path))
9936 (dired path)
9937 (org-open-file path arg line search)))
9939 ((string= type "shell")
9940 (let ((buf (generate-new-buffer "*Org Shell Output"))
9941 (cmd path))
9942 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9943 (string-match org-confirm-shell-link-not-regexp cmd))
9944 (not org-confirm-shell-link-function)
9945 (funcall org-confirm-shell-link-function
9946 (format "Execute \"%s\" in shell? "
9947 (org-add-props cmd nil
9948 'face 'org-warning))))
9949 (progn
9950 (message "Executing %s" cmd)
9951 (shell-command cmd buf)
9952 (if (featurep 'midnight)
9953 (setq clean-buffer-list-kill-buffer-names
9954 (cons buf clean-buffer-list-kill-buffer-names))))
9955 (error "Abort"))))
9957 ((string= type "elisp")
9958 (let ((cmd path))
9959 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9960 (string-match org-confirm-elisp-link-not-regexp cmd))
9961 (not org-confirm-elisp-link-function)
9962 (funcall org-confirm-elisp-link-function
9963 (format "Execute \"%s\" as elisp? "
9964 (org-add-props cmd nil
9965 'face 'org-warning))))
9966 (message "%s => %s" cmd
9967 (if (equal (string-to-char cmd) ?\()
9968 (eval (read cmd))
9969 (call-interactively (read cmd))))
9970 (error "Abort"))))
9972 ((and (string= type "thisfile")
9973 (run-hook-with-args-until-success
9974 'org-open-link-functions path)))
9976 ((string= type "thisfile")
9977 (if arg
9978 (switch-to-buffer-other-window
9979 (org-get-buffer-for-internal-link (current-buffer)))
9980 (org-mark-ring-push))
9981 (let ((cmd `(org-link-search
9982 ,path
9983 ,(cond ((equal arg '(4)) ''occur)
9984 ((equal arg '(16)) ''org-occur))
9985 ,pos)))
9986 (condition-case nil (let ((org-link-search-inhibit-query t))
9987 (eval cmd))
9988 (error (progn (widen) (eval cmd))))))
9990 (t (browse-url-at-point)))))))
9991 (move-marker org-open-link-marker nil)
9992 (run-hook-with-args 'org-follow-link-hook)))
9994 (defun org-offer-links-in-entry (&optional nth zero)
9995 "Offer links in the current entry and follow the selected link.
9996 If there is only one link, follow it immediately as well.
9997 If NTH is an integer, immediately pick the NTH link found.
9998 If ZERO is a string, check also this string for a link, and if
9999 there is one, offer it as link number zero."
10000 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10001 "\\(" org-angle-link-re "\\)\\|"
10002 "\\(" org-plain-link-re "\\)"))
10003 (cnt ?0)
10004 (in-emacs (if (integerp nth) nil nth))
10005 have-zero end links link c)
10006 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10007 (push (match-string 0 zero) links)
10008 (setq cnt (1- cnt) have-zero t))
10009 (save-excursion
10010 (org-back-to-heading t)
10011 (setq end (save-excursion (outline-next-heading) (point)))
10012 (while (re-search-forward re end t)
10013 (push (match-string 0) links))
10014 (setq links (org-uniquify (reverse links))))
10016 (cond
10017 ((null links)
10018 (message "No links"))
10019 ((equal (length links) 1)
10020 (setq link (list (car links))))
10021 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10022 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10023 (t ; we have to select a link
10024 (save-excursion
10025 (save-window-excursion
10026 (delete-other-windows)
10027 (with-output-to-temp-buffer "*Select Link*"
10028 (mapc (lambda (l)
10029 (if (not (string-match org-bracket-link-regexp l))
10030 (princ (format "[%c] %s\n" (incf cnt)
10031 (org-remove-angle-brackets l)))
10032 (if (match-end 3)
10033 (princ (format "[%c] %s (%s)\n" (incf cnt)
10034 (match-string 3 l) (match-string 1 l)))
10035 (princ (format "[%c] %s\n" (incf cnt)
10036 (match-string 1 l))))))
10037 links))
10038 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10039 (message "Select link to open, RET to open all:")
10040 (setq c (read-char-exclusive))
10041 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10042 (when (equal c ?q) (error "Abort"))
10043 (if (equal c ?\C-m)
10044 (setq link links)
10045 (setq nth (- c ?0))
10046 (if have-zero (setq nth (1+ nth)))
10047 (unless (and (integerp nth) (>= (length links) nth))
10048 (error "Invalid link selection"))
10049 (setq link (list (nth (1- nth) links))))))
10050 (if link
10051 (let ((buf (current-buffer)))
10052 (dolist (l link)
10053 (org-open-link-from-string l in-emacs buf))
10055 nil)))
10057 ;; Add special file links that specify the way of opening
10059 (org-add-link-type "file+sys" 'org-open-file-with-system)
10060 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10061 (defun org-open-file-with-system (path)
10062 "Open file at PATH using the system way of opening it."
10063 (org-open-file path 'system))
10064 (defun org-open-file-with-emacs (path)
10065 "Open file at PATH in Emacs."
10066 (org-open-file path 'emacs))
10067 (defun org-remove-file-link-modifiers ()
10068 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10069 (goto-char (point-min))
10070 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10071 (org-if-unprotected
10072 (replace-match "file:" t t))))
10073 (eval-after-load "org-exp"
10074 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10075 'org-remove-file-link-modifiers))
10077 ;;;; Time estimates
10079 (defun org-get-effort (&optional pom)
10080 "Get the effort estimate for the current entry."
10081 (org-entry-get pom org-effort-property))
10083 ;;; File search
10085 (defvar org-create-file-search-functions nil
10086 "List of functions to construct the right search string for a file link.
10087 These functions are called in turn with point at the location to
10088 which the link should point.
10090 A function in the hook should first test if it would like to
10091 handle this file type, for example by checking the `major-mode'
10092 or the file extension. If it decides not to handle this file, it
10093 should just return nil to give other functions a chance. If it
10094 does handle the file, it must return the search string to be used
10095 when following the link. The search string will be part of the
10096 file link, given after a double colon, and `org-open-at-point'
10097 will automatically search for it. If special measures must be
10098 taken to make the search successful, another function should be
10099 added to the companion hook `org-execute-file-search-functions',
10100 which see.
10102 A function in this hook may also use `setq' to set the variable
10103 `description' to provide a suggestion for the descriptive text to
10104 be used for this link when it gets inserted into an Org-mode
10105 buffer with \\[org-insert-link].")
10107 (defvar org-execute-file-search-functions nil
10108 "List of functions to execute a file search triggered by a link.
10110 Functions added to this hook must accept a single argument, the
10111 search string that was part of the file link, the part after the
10112 double colon. The function must first check if it would like to
10113 handle this search, for example by checking the `major-mode' or
10114 the file extension. If it decides not to handle this search, it
10115 should just return nil to give other functions a chance. If it
10116 does handle the search, it must return a non-nil value to keep
10117 other functions from trying.
10119 Each function can access the current prefix argument through the
10120 variable `current-prefix-argument'. Note that a single prefix is
10121 used to force opening a link in Emacs, so it may be good to only
10122 use a numeric or double prefix to guide the search function.
10124 In case this is needed, a function in this hook can also restore
10125 the window configuration before `org-open-at-point' was called using:
10127 (set-window-configuration org-window-config-before-follow-link)")
10129 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10130 (defun org-link-search (s &optional type avoid-pos stealth)
10131 "Search for a link search option.
10132 If S is surrounded by forward slashes, it is interpreted as a
10133 regular expression. In org-mode files, this will create an `org-occur'
10134 sparse tree. In ordinary files, `occur' will be used to list matches.
10135 If the current buffer is in `dired-mode', grep will be used to search
10136 in all files. If AVOID-POS is given, ignore matches near that position.
10138 When optional argument STEALTH is non-nil, do not modify
10139 visibility around point, thus ignoring
10140 `org-show-hierarchy-above', `org-show-following-heading' and
10141 `org-show-siblings' variables."
10142 (let ((case-fold-search t)
10143 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10144 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10145 (append '(("") (" ") ("\t") ("\n"))
10146 org-emphasis-alist)
10147 "\\|") "\\)"))
10148 (pos (point))
10149 (pre nil) (post nil)
10150 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10151 (cond
10152 ;; First check if there are any special search functions
10153 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10154 ;; Now try the builtin stuff
10155 ((and (equal (string-to-char s0) ?#)
10156 (> (length s0) 1)
10157 (save-excursion
10158 (goto-char (point-min))
10159 (and
10160 (re-search-forward
10161 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10162 (setq type 'dedicated
10163 pos (match-beginning 0))))
10164 ;; There is an exact target for this
10165 (goto-char pos)
10166 (org-back-to-heading t)))
10167 ((save-excursion
10168 (goto-char (point-min))
10169 (and
10170 (re-search-forward
10171 (concat "<<" (regexp-quote s0) ">>") nil t)
10172 (setq type 'dedicated
10173 pos (match-beginning 0))))
10174 ;; There is an exact target for this
10175 (goto-char pos))
10176 ((save-excursion
10177 (goto-char (point-min))
10178 (and
10179 (re-search-forward
10180 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10181 (setq type 'dedicated pos (match-beginning 0))))
10182 ;; Found an invisible target.
10183 (goto-char pos))
10184 ((save-excursion
10185 (goto-char (point-min))
10186 (and
10187 (re-search-forward
10188 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10189 (setq type 'dedicated pos (match-beginning 0))))
10190 ;; Found an element with a matching #+name affiliated keyword.
10191 (goto-char pos))
10192 ((and (string-match "^(\\(.*\\))$" s0)
10193 (save-excursion
10194 (goto-char (point-min))
10195 (and
10196 (re-search-forward
10197 (concat "[^[]" (regexp-quote
10198 (format org-coderef-label-format
10199 (match-string 1 s0))))
10200 nil t)
10201 (setq type 'dedicated
10202 pos (1+ (match-beginning 0))))))
10203 ;; There is a coderef target for this
10204 (goto-char pos))
10205 ((string-match "^/\\(.*\\)/$" s)
10206 ;; A regular expression
10207 (cond
10208 ((derived-mode-p 'org-mode)
10209 (org-occur (match-string 1 s)))
10210 ;;((eq major-mode 'dired-mode)
10211 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10212 (t (org-do-occur (match-string 1 s)))))
10213 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10214 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10215 (goto-char (point-min))
10216 (cond
10217 ((let (case-fold-search)
10218 (re-search-forward (format org-complex-heading-regexp-format
10219 (regexp-quote s))
10220 nil t))
10221 ;; OK, found a match
10222 (setq type 'dedicated)
10223 (goto-char (match-beginning 0)))
10224 ((and (not org-link-search-inhibit-query)
10225 (eq org-link-search-must-match-exact-headline 'query-to-create)
10226 (y-or-n-p "No match - create this as a new heading? "))
10227 (goto-char (point-max))
10228 (or (bolp) (newline))
10229 (insert "* " s "\n")
10230 (beginning-of-line 0))
10232 (goto-char pos)
10233 (error "No match"))))
10235 ;; A normal search string
10236 (when (equal (string-to-char s) ?*)
10237 ;; Anchor on headlines, post may include tags.
10238 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10239 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10240 s (substring s 1)))
10241 (remove-text-properties
10242 0 (length s)
10243 '(face nil mouse-face nil keymap nil fontified nil) s)
10244 ;; Make a series of regular expressions to find a match
10245 (setq words (org-split-string s "[ \n\r\t]+")
10247 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10248 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10249 "\\)" markers)
10250 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10251 re2a (concat "[ \t\r\n]" re2a_)
10252 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10253 re4 (concat "[^a-zA-Z_]" re4_)
10255 re1 (concat pre re2 post)
10256 re3 (concat pre (if pre re4_ re4) post)
10257 re5 (concat pre ".*" re4)
10258 re2 (concat pre re2)
10259 re2a (concat pre (if pre re2a_ re2a))
10260 re4 (concat pre (if pre re4_ re4))
10261 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10262 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10263 re5 "\\)"
10265 (cond
10266 ((eq type 'org-occur) (org-occur reall))
10267 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10268 (t (goto-char (point-min))
10269 (setq type 'fuzzy)
10270 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10271 (org-search-not-self 1 re1 nil t)
10272 (org-search-not-self 1 re2 nil t)
10273 (org-search-not-self 1 re2a nil t)
10274 (org-search-not-self 1 re3 nil t)
10275 (org-search-not-self 1 re4 nil t)
10276 (org-search-not-self 1 re5 nil t)
10278 (goto-char (match-beginning 1))
10279 (goto-char pos)
10280 (error "No match"))))))
10281 (and (derived-mode-p 'org-mode)
10282 (not stealth)
10283 (org-show-context 'link-search))
10284 type))
10286 (defun org-search-not-self (group &rest args)
10287 "Execute `re-search-forward', but only accept matches that do not
10288 enclose the position of `org-open-link-marker'."
10289 (let ((m org-open-link-marker))
10290 (catch 'exit
10291 (while (apply 're-search-forward args)
10292 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10293 (goto-char (match-end group))
10294 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10295 (> (match-beginning 0) (marker-position m))
10296 (< (match-end 0) (marker-position m)))
10297 (save-match-data
10298 (or (not (org-in-regexp
10299 org-bracket-link-analytic-regexp 1))
10300 (not (match-end 4)) ; no description
10301 (and (<= (match-beginning 4) (point))
10302 (>= (match-end 4) (point))))))
10303 (throw 'exit (point))))))))
10305 (defun org-get-buffer-for-internal-link (buffer)
10306 "Return a buffer to be used for displaying the link target of internal links."
10307 (cond
10308 ((not org-display-internal-link-with-indirect-buffer)
10309 buffer)
10310 ((string-match "(Clone)$" (buffer-name buffer))
10311 (message "Buffer is already a clone, not making another one")
10312 ;; we also do not modify visibility in this case
10313 buffer)
10314 (t ; make a new indirect buffer for displaying the link
10315 (let* ((bn (buffer-name buffer))
10316 (ibn (concat bn "(Clone)"))
10317 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10318 (with-current-buffer ib (org-overview))
10319 ib))))
10321 (defun org-do-occur (regexp &optional cleanup)
10322 "Call the Emacs command `occur'.
10323 If CLEANUP is non-nil, remove the printout of the regular expression
10324 in the *Occur* buffer. This is useful if the regex is long and not useful
10325 to read."
10326 (occur regexp)
10327 (when cleanup
10328 (let ((cwin (selected-window)) win beg end)
10329 (when (setq win (get-buffer-window "*Occur*"))
10330 (select-window win))
10331 (goto-char (point-min))
10332 (when (re-search-forward "match[a-z]+" nil t)
10333 (setq beg (match-end 0))
10334 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10335 (setq end (1- (match-beginning 0)))))
10336 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10337 (goto-char (point-min))
10338 (select-window cwin))))
10340 ;;; The mark ring for links jumps
10342 (defvar org-mark-ring nil
10343 "Mark ring for positions before jumps in Org-mode.")
10344 (defvar org-mark-ring-last-goto nil
10345 "Last position in the mark ring used to go back.")
10346 ;; Fill and close the ring
10347 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10348 (loop for i from 1 to org-mark-ring-length do
10349 (push (make-marker) org-mark-ring))
10350 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10351 org-mark-ring)
10353 (defun org-mark-ring-push (&optional pos buffer)
10354 "Put the current position or POS into the mark ring and rotate it."
10355 (interactive)
10356 (setq pos (or pos (point)))
10357 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10358 (move-marker (car org-mark-ring)
10359 (or pos (point))
10360 (or buffer (current-buffer)))
10361 (message "%s"
10362 (substitute-command-keys
10363 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10365 (defun org-mark-ring-goto (&optional n)
10366 "Jump to the previous position in the mark ring.
10367 With prefix arg N, jump back that many stored positions. When
10368 called several times in succession, walk through the entire ring.
10369 Org-mode commands jumping to a different position in the current file,
10370 or to another Org-mode file, automatically push the old position
10371 onto the ring."
10372 (interactive "p")
10373 (let (p m)
10374 (if (eq last-command this-command)
10375 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10376 (setq p org-mark-ring))
10377 (setq org-mark-ring-last-goto p)
10378 (setq m (car p))
10379 (org-pop-to-buffer-same-window (marker-buffer m))
10380 (goto-char m)
10381 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10383 (defun org-remove-angle-brackets (s)
10384 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10385 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10387 (defun org-add-angle-brackets (s)
10388 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10389 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10391 (defun org-remove-double-quotes (s)
10392 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10393 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10396 ;;; Following specific links
10398 (defun org-follow-timestamp-link ()
10399 "Open an agenda view for the time-stamp date/range at point."
10400 (cond
10401 ((org-at-date-range-p t)
10402 (let ((org-agenda-start-on-weekday)
10403 (t1 (match-string 1))
10404 (t2 (match-string 2)) tt1 tt2)
10405 (setq tt1 (time-to-days (org-time-string-to-time t1))
10406 tt2 (time-to-days (org-time-string-to-time t2)))
10407 (let ((org-agenda-buffer-tmp-name
10408 (format "*Org Agenda(a:%s)"
10409 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10410 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10411 ((org-at-timestamp-p t)
10412 (let ((org-agenda-buffer-tmp-name
10413 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10414 (org-agenda-list nil (time-to-days (org-time-string-to-time
10415 (substring (match-string 1) 0 10)))
10416 1)))
10417 (t (error "This should not happen"))))
10420 ;;; Following file links
10421 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10422 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10423 (declare-function mailcap-mime-info
10424 "mailcap" (string &optional request no-decode))
10425 (defvar org-wait nil)
10426 (defun org-open-file (path &optional in-emacs line search)
10427 "Open the file at PATH.
10428 First, this expands any special file name abbreviations. Then the
10429 configuration variable `org-file-apps' is checked if it contains an
10430 entry for this file type, and if yes, the corresponding command is launched.
10432 If no application is found, Emacs simply visits the file.
10434 With optional prefix argument IN-EMACS, Emacs will visit the file.
10435 With a double \\[universal-argument] \\[universal-argument] \
10436 prefix arg, Org tries to avoid opening in Emacs
10437 and to use an external application to visit the file.
10439 Optional LINE specifies a line to go to, optional SEARCH a string
10440 to search for. If LINE or SEARCH is given, the file will be
10441 opened in Emacs, unless an entry from org-file-apps that makes
10442 use of groups in a regexp matches.
10444 If you want to change the way frames are used when following a
10445 link, please customize `org-link-frame-setup'.
10447 If the file does not exist, an error is thrown."
10448 (let* ((file (if (equal path "")
10449 buffer-file-name
10450 (substitute-in-file-name (expand-file-name path))))
10451 (file-apps (append org-file-apps (org-default-apps)))
10452 (apps (org-remove-if
10453 'org-file-apps-entry-match-against-dlink-p file-apps))
10454 (apps-dlink (org-remove-if-not
10455 'org-file-apps-entry-match-against-dlink-p file-apps))
10456 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10457 (dirp (if remp nil (file-directory-p file)))
10458 (file (if (and dirp org-open-directory-means-index-dot-org)
10459 (concat (file-name-as-directory file) "index.org")
10460 file))
10461 (a-m-a-p (assq 'auto-mode apps))
10462 (dfile (downcase file))
10463 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10464 (link (cond ((and (eq line nil)
10465 (eq search nil))
10466 file)
10467 (line
10468 (concat file "::" (number-to-string line)))
10469 (search
10470 (concat file "::" search))))
10471 (dlink (downcase link))
10472 (old-buffer (current-buffer))
10473 (old-pos (point))
10474 (old-mode major-mode)
10475 ext cmd link-match-data)
10476 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10477 (setq ext (match-string 1 dfile))
10478 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10479 (setq ext (match-string 1 dfile))))
10480 (cond
10481 ((member in-emacs '((16) system))
10482 (setq cmd (cdr (assoc 'system apps))))
10483 (in-emacs (setq cmd 'emacs))
10485 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10486 (and dirp (cdr (assoc 'directory apps)))
10487 ; first, try matching against apps-dlink
10488 ; if we get a match here, store the match data for later
10489 (let ((match (assoc-default dlink apps-dlink
10490 'string-match)))
10491 (if match
10492 (progn (setq link-match-data (match-data))
10493 match)
10494 (progn (setq in-emacs (or in-emacs line search))
10495 nil))) ; if we have no match in apps-dlink,
10496 ; always open the file in emacs if line or search
10497 ; is given (for backwards compatibility)
10498 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10499 'string-match)
10500 (cdr (assoc ext apps))
10501 (cdr (assoc t apps))))))
10502 (when (eq cmd 'system)
10503 (setq cmd (cdr (assoc 'system apps))))
10504 (when (eq cmd 'default)
10505 (setq cmd (cdr (assoc t apps))))
10506 (when (eq cmd 'mailcap)
10507 (require 'mailcap)
10508 (mailcap-parse-mailcaps)
10509 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10510 (command (mailcap-mime-info mime-type)))
10511 (if (stringp command)
10512 (setq cmd command)
10513 (setq cmd 'emacs))))
10514 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10515 (not (file-exists-p file))
10516 (not org-open-non-existing-files))
10517 (error "No such file: %s" file))
10518 (cond
10519 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10520 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10521 (while (string-match "['\"]%s['\"]" cmd)
10522 (setq cmd (replace-match "%s" t t cmd)))
10523 (while (string-match "%s" cmd)
10524 (setq cmd (replace-match
10525 (save-match-data
10526 (shell-quote-argument
10527 (convert-standard-filename file)))
10528 t t cmd)))
10530 ;; Replace "%1", "%2" etc. in command with group matches from regex
10531 (save-match-data
10532 (let ((match-index 1)
10533 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10534 (set-match-data link-match-data)
10535 (while (<= match-index number-of-groups)
10536 (let ((regex (concat "%" (number-to-string match-index)))
10537 (replace-with (match-string match-index dlink)))
10538 (while (string-match regex cmd)
10539 (setq cmd (replace-match replace-with t t cmd))))
10540 (setq match-index (+ match-index 1)))))
10542 (save-window-excursion
10543 (message "Running %s...done" cmd)
10544 (start-process-shell-command cmd nil cmd)
10545 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10546 ((or (stringp cmd)
10547 (eq cmd 'emacs))
10548 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10549 (widen)
10550 (if line (org-goto-line line)
10551 (if search (org-link-search search))))
10552 ((consp cmd)
10553 (let ((file (convert-standard-filename file)))
10554 (save-match-data
10555 (set-match-data link-match-data)
10556 (eval cmd))))
10557 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10558 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10559 (or (not (equal old-buffer (current-buffer)))
10560 (not (equal old-pos (point))))
10561 (org-mark-ring-push old-pos old-buffer))))
10563 (defun org-file-apps-entry-match-against-dlink-p (entry)
10564 "This function returns non-nil if `entry' uses a regular
10565 expression which should be matched against the whole link by
10566 org-open-file.
10568 It assumes that is the case when the entry uses a regular
10569 expression which has at least one grouping construct and the
10570 action is either a lisp form or a command string containing
10571 '%1', i.e. using at least one subexpression match as a
10572 parameter."
10573 (let ((selector (car entry))
10574 (action (cdr entry)))
10575 (if (stringp selector)
10576 (and (> (regexp-opt-depth selector) 0)
10577 (or (and (stringp action)
10578 (string-match "%[0-9]" action))
10579 (consp action)))
10580 nil)))
10582 (defun org-default-apps ()
10583 "Return the default applications for this operating system."
10584 (cond
10585 ((eq system-type 'darwin)
10586 org-file-apps-defaults-macosx)
10587 ((eq system-type 'windows-nt)
10588 org-file-apps-defaults-windowsnt)
10589 (t org-file-apps-defaults-gnu)))
10591 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10592 "Convert extensions to regular expressions in the cars of LIST.
10593 Also, weed out any non-string entries, because the return value is used
10594 only for regexp matching.
10595 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10596 point to the symbol `emacs', indicating that the file should
10597 be opened in Emacs."
10598 (append
10599 (delq nil
10600 (mapcar (lambda (x)
10601 (if (not (stringp (car x)))
10603 (if (string-match "\\W" (car x))
10605 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10606 list))
10607 (if add-auto-mode
10608 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10610 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10611 (defun org-file-remote-p (file)
10612 "Test whether FILE specifies a location on a remote system.
10613 Return non-nil if the location is indeed remote.
10615 For example, the filename \"/user@host:/foo\" specifies a location
10616 on the system \"/user@host:\"."
10617 (cond ((fboundp 'file-remote-p)
10618 (file-remote-p file))
10619 ((fboundp 'tramp-handle-file-remote-p)
10620 (tramp-handle-file-remote-p file))
10621 ((and (boundp 'ange-ftp-name-format)
10622 (string-match (car ange-ftp-name-format) file))
10623 t)))
10626 ;;;; Refiling
10628 (defun org-get-org-file ()
10629 "Read a filename, with default directory `org-directory'."
10630 (let ((default (or org-default-notes-file remember-data-file)))
10631 (read-file-name (format "File name [%s]: " default)
10632 (file-name-as-directory org-directory)
10633 default)))
10635 (defun org-notes-order-reversed-p ()
10636 "Check if the current file should receive notes in reversed order."
10637 (cond
10638 ((not org-reverse-note-order) nil)
10639 ((eq t org-reverse-note-order) t)
10640 ((not (listp org-reverse-note-order)) nil)
10641 (t (catch 'exit
10642 (let ((all org-reverse-note-order)
10643 entry)
10644 (while (setq entry (pop all))
10645 (if (string-match (car entry) buffer-file-name)
10646 (throw 'exit (cdr entry))))
10647 nil)))))
10649 (defvar org-refile-target-table nil
10650 "The list of refile targets, created by `org-refile'.")
10652 (defvar org-agenda-new-buffers nil
10653 "Buffers created to visit agenda files.")
10655 (defvar org-refile-cache nil
10656 "Cache for refile targets.")
10658 (defvar org-refile-markers nil
10659 "All the markers used for caching refile locations.")
10661 (defun org-refile-marker (pos)
10662 "Get a new refile marker, but only if caching is in use."
10663 (if (not org-refile-use-cache)
10665 (let ((m (make-marker)))
10666 (move-marker m pos)
10667 (push m org-refile-markers)
10668 m)))
10670 (defun org-refile-cache-clear ()
10671 "Clear the refile cache and disable all the markers."
10672 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10673 (setq org-refile-markers nil)
10674 (setq org-refile-cache nil)
10675 (message "Refile cache has been cleared"))
10677 (defun org-refile-cache-check-set (set)
10678 "Check if all the markers in the cache still have live buffers."
10679 (let (marker)
10680 (catch 'exit
10681 (while (and set (setq marker (nth 3 (pop set))))
10682 ;; if org-refile-use-outline-path is 'file, marker may be nil
10683 (when (and marker (null (marker-buffer marker)))
10684 (message "not found") (sit-for 3)
10685 (throw 'exit nil)))
10686 t)))
10688 (defun org-refile-cache-put (set &rest identifiers)
10689 "Push the refile targets SET into the cache, under IDENTIFIERS."
10690 (let* ((key (sha1 (prin1-to-string identifiers)))
10691 (entry (assoc key org-refile-cache)))
10692 (if entry
10693 (setcdr entry set)
10694 (push (cons key set) org-refile-cache))))
10696 (defun org-refile-cache-get (&rest identifiers)
10697 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10698 (cond
10699 ((not org-refile-cache) nil)
10700 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10702 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10703 org-refile-cache))))
10704 (and set (org-refile-cache-check-set set) set)))))
10706 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10707 "Produce a table with refile targets."
10708 (let ((case-fold-search nil)
10709 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10710 (entries (or org-refile-targets '((nil . (:level . 1)))))
10711 targets tgs txt re files f desc descre fast-path-p level pos0)
10712 (message "Getting targets...")
10713 (with-current-buffer (or default-buffer (current-buffer))
10714 (while (setq entry (pop entries))
10715 (setq files (car entry) desc (cdr entry))
10716 (setq fast-path-p nil)
10717 (cond
10718 ((null files) (setq files (list (current-buffer))))
10719 ((eq files 'org-agenda-files)
10720 (setq files (org-agenda-files 'unrestricted)))
10721 ((and (symbolp files) (fboundp files))
10722 (setq files (funcall files)))
10723 ((and (symbolp files) (boundp files))
10724 (setq files (symbol-value files))))
10725 (if (stringp files) (setq files (list files)))
10726 (cond
10727 ((eq (car desc) :tag)
10728 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10729 ((eq (car desc) :todo)
10730 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10731 ((eq (car desc) :regexp)
10732 (setq descre (cdr desc)))
10733 ((eq (car desc) :level)
10734 (setq descre (concat "^\\*\\{" (number-to-string
10735 (if org-odd-levels-only
10736 (1- (* 2 (cdr desc)))
10737 (cdr desc)))
10738 "\\}[ \t]")))
10739 ((eq (car desc) :maxlevel)
10740 (setq fast-path-p t)
10741 (setq descre (concat "^\\*\\{1," (number-to-string
10742 (if org-odd-levels-only
10743 (1- (* 2 (cdr desc)))
10744 (cdr desc)))
10745 "\\}[ \t]")))
10746 (t (error "Bad refiling target description %s" desc)))
10747 (while (setq f (pop files))
10748 (with-current-buffer
10749 (if (bufferp f) f (org-get-agenda-file-buffer f))
10751 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10752 (progn
10753 (if (bufferp f) (setq f (buffer-file-name
10754 (buffer-base-buffer f))))
10755 (setq f (and f (expand-file-name f)))
10756 (if (eq org-refile-use-outline-path 'file)
10757 (push (list (file-name-nondirectory f) f nil nil) tgs))
10758 (save-excursion
10759 (save-restriction
10760 (widen)
10761 (goto-char (point-min))
10762 (while (re-search-forward descre nil t)
10763 (goto-char (setq pos0 (point-at-bol)))
10764 (catch 'next
10765 (when org-refile-target-verify-function
10766 (save-match-data
10767 (or (funcall org-refile-target-verify-function)
10768 (throw 'next t))))
10769 (when (and (looking-at org-complex-heading-regexp)
10770 (not (member (match-string 4) excluded-entries))
10771 (match-string 4))
10772 (setq level (org-reduced-level
10773 (- (match-end 1) (match-beginning 1)))
10774 txt (org-link-display-format (match-string 4))
10775 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10776 re (format org-complex-heading-regexp-format
10777 (regexp-quote (match-string 4))))
10778 (when org-refile-use-outline-path
10779 (setq txt (mapconcat
10780 'org-protect-slash
10781 (append
10782 (if (eq org-refile-use-outline-path
10783 'file)
10784 (list (file-name-nondirectory
10785 (buffer-file-name
10786 (buffer-base-buffer))))
10787 (if (eq org-refile-use-outline-path
10788 'full-file-path)
10789 (list (buffer-file-name
10790 (buffer-base-buffer)))))
10791 (org-get-outline-path fast-path-p
10792 level txt)
10793 (list txt))
10794 "/")))
10795 (push (list txt f re (org-refile-marker (point)))
10796 tgs)))
10797 (when (= (point) pos0)
10798 ;; verification function has not moved point
10799 (goto-char (point-at-eol))))))))
10800 (when org-refile-use-cache
10801 (org-refile-cache-put tgs (buffer-file-name) descre))
10802 (setq targets (append tgs targets))
10803 ))))
10804 (message "Getting targets...done")
10805 (nreverse targets)))
10807 (defun org-protect-slash (s)
10808 (while (string-match "/" s)
10809 (setq s (replace-match "\\" t t s)))
10812 (defvar org-olpa (make-vector 20 nil))
10814 (defun org-get-outline-path (&optional fastp level heading)
10815 "Return the outline path to the current entry, as a list.
10817 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10818 routine which makes outline path derivations for an entire file,
10819 avoiding backtracing. Refile target collection makes use of that."
10820 (if fastp
10821 (progn
10822 (if (> level 19)
10823 (error "Outline path failure, more than 19 levels"))
10824 (loop for i from level upto 19 do
10825 (aset org-olpa i nil))
10826 (prog1
10827 (delq nil (append org-olpa nil))
10828 (aset org-olpa level heading)))
10829 (let (rtn case-fold-search)
10830 (save-excursion
10831 (save-restriction
10832 (widen)
10833 (while (org-up-heading-safe)
10834 (when (looking-at org-complex-heading-regexp)
10835 (push (org-match-string-no-properties 4) rtn)))
10836 rtn)))))
10838 (defun org-format-outline-path (path &optional width prefix separator)
10839 "Format the outline path PATH for display.
10840 WIDTH is the maximum number of characters that is available.
10841 PREFIX is a prefix to be included in the returned string,
10842 such as the file name.
10843 SEPARATOR is inserted between the different parts of the path,
10844 the default is \"/\"."
10845 (setq width (or width 79))
10846 (if prefix (setq width (- width (length prefix))))
10847 (if (not path)
10848 (or prefix "")
10849 (let* ((nsteps (length path))
10850 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10851 (maxwidth (if (<= total-width width)
10852 10000 ;; everything fits
10853 ;; we need to shorten the level headings
10854 (/ (- width nsteps) nsteps)))
10855 (org-odd-levels-only nil)
10856 (n 0)
10857 (total (1+ (length prefix))))
10858 (setq maxwidth (max maxwidth 10))
10859 (concat prefix
10860 (if prefix (or separator "/"))
10861 (mapconcat
10862 (lambda (h)
10863 (setq n (1+ n))
10864 (if (and (= n nsteps) (< maxwidth 10000))
10865 (setq maxwidth (- total-width total)))
10866 (if (< (length h) maxwidth)
10867 (progn (setq total (+ total (length h) 1)) h)
10868 (setq h (substring h 0 (- maxwidth 2))
10869 total (+ total maxwidth 1))
10870 (if (string-match "[ \t]+\\'" h)
10871 (setq h (substring h 0 (match-beginning 0))))
10872 (setq h (concat h "..")))
10873 (org-add-props h nil 'face
10874 (nth (% (1- n) org-n-level-faces)
10875 org-level-faces))
10877 path (or separator "/"))))))
10879 (defun org-display-outline-path (&optional file current separator just-return-string)
10880 "Display the current outline path in the echo area.
10882 If FILE is non-nil, prepend the output with the file name.
10883 If CURRENT is non-nil, append the current heading to the output.
10884 SEPARATOR is passed through to `org-format-outline-path'. It separates
10885 the different parts of the path and defaults to \"/\".
10886 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10887 (interactive "P")
10888 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10889 (case-fold-search nil)
10890 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10891 res)
10892 (if current (setq path (append path
10893 (save-excursion
10894 (org-back-to-heading t)
10895 (if (looking-at org-complex-heading-regexp)
10896 (list (match-string 4)))))))
10897 (setq res
10898 (org-format-outline-path
10899 path
10900 (1- (frame-width))
10901 (and file bfn (concat (file-name-nondirectory bfn) separator))
10902 separator))
10903 (if just-return-string
10904 (org-no-properties res)
10905 (message "%s" res))))
10907 (defvar org-refile-history nil
10908 "History for refiling operations.")
10910 (defvar org-after-refile-insert-hook nil
10911 "Hook run after `org-refile' has inserted its stuff at the new location.
10912 Note that this is still *before* the stuff will be removed from
10913 the *old* location.")
10915 (defvar org-capture-last-stored-marker)
10916 (defvar org-refile-keep nil
10917 "Non-nil means `org-refile' will copy instead of refile.")
10919 (defun org-copy ()
10920 "Like `org-refile', but copy."
10921 (interactive)
10922 (let ((org-refile-keep t))
10923 (funcall 'org-refile nil nil nil "Copy")))
10925 (defun org-refile (&optional goto default-buffer rfloc msg)
10926 "Move the entry or entries at point to another heading.
10927 The list of target headings is compiled using the information in
10928 `org-refile-targets', which see.
10930 At the target location, the entry is filed as a subitem of the target
10931 heading. Depending on `org-reverse-note-order', the new subitem will
10932 either be the first or the last subitem.
10934 If there is an active region, all entries in that region will be moved.
10935 However, the region must fulfill the requirement that the first heading
10936 is the first one sets the top-level of the moved text - at most siblings
10937 below it are allowed.
10939 With prefix arg GOTO, the command will only visit the target location
10940 and not actually move anything.
10942 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10943 go to the location where the last refiling operation has put the subtree.
10944 With a prefix argument of `2', refile to the running clock.
10946 RFLOC can be a refile location obtained in a different way.
10948 MSG is a string to replace \"Refile\" in the default prompt with
10949 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10951 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10953 If you are using target caching (see `org-refile-use-cache'),
10954 you have to clear the target cache in order to find new targets.
10955 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10956 prefix argument (`C-u C-u C-u C-c C-w')."
10958 (interactive "P")
10959 (if (member goto '(0 (64)))
10960 (org-refile-cache-clear)
10961 (let* ((actionmsg (or msg "Refile"))
10962 (cbuf (current-buffer))
10963 (regionp (org-region-active-p))
10964 (region-start (and regionp (region-beginning)))
10965 (region-end (and regionp (region-end)))
10966 (region-length (and regionp (- region-end region-start)))
10967 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10968 pos it nbuf file re level reversed)
10969 (setq last-command nil)
10970 (when regionp
10971 (goto-char region-start)
10972 (or (bolp) (goto-char (point-at-bol)))
10973 (setq region-start (point))
10974 (unless (or (org-kill-is-subtree-p
10975 (buffer-substring region-start region-end))
10976 (prog1 org-refile-active-region-within-subtree
10977 (org-toggle-heading)))
10978 (error "The region is not a (sequence of) subtree(s)")))
10979 (if (equal goto '(16))
10980 (org-refile-goto-last-stored)
10981 (when (or
10982 (and (equal goto 2)
10983 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10984 (prog1
10985 (setq it (list (or org-clock-heading "running clock")
10986 (buffer-file-name
10987 (marker-buffer org-clock-hd-marker))
10989 (marker-position org-clock-hd-marker)))
10990 (setq goto nil)))
10991 (setq it (or rfloc
10992 (let (heading-text)
10993 (save-excursion
10994 (unless goto
10995 (org-back-to-heading t)
10996 (setq heading-text
10997 (nth 4 (org-heading-components))))
10999 (org-refile-get-location
11000 (cond (goto "Goto")
11001 (regionp (concat actionmsg " region to"))
11002 (t (concat actionmsg " subtree \""
11003 heading-text "\" to")))
11004 default-buffer
11005 (and (not (equal '(4) goto))
11006 org-refile-allow-creating-parent-nodes)
11007 goto))))))
11008 (setq file (nth 1 it)
11009 re (nth 2 it)
11010 pos (nth 3 it))
11011 (if (and (not goto)
11013 (equal (buffer-file-name) file)
11014 (if regionp
11015 (and (>= pos region-start)
11016 (<= pos region-end))
11017 (and (>= pos (point))
11018 (< pos (save-excursion
11019 (org-end-of-subtree t t))))))
11020 (error "Cannot refile to position inside the tree or region"))
11022 (setq nbuf (or (find-buffer-visiting file)
11023 (find-file-noselect file)))
11024 (if goto
11025 (progn
11026 (org-pop-to-buffer-same-window nbuf)
11027 (goto-char pos)
11028 (org-show-context 'org-goto))
11029 (if regionp
11030 (progn
11031 (org-kill-new (buffer-substring region-start region-end))
11032 (org-save-markers-in-region region-start region-end))
11033 (org-copy-subtree 1 nil t))
11034 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11035 (find-file-noselect file)))
11036 (setq reversed (org-notes-order-reversed-p))
11037 (save-excursion
11038 (save-restriction
11039 (widen)
11040 (if pos
11041 (progn
11042 (goto-char pos)
11043 (looking-at org-outline-regexp)
11044 (setq level (org-get-valid-level (funcall outline-level) 1))
11045 (goto-char
11046 (if reversed
11047 (or (outline-next-heading) (point-max))
11048 (or (save-excursion (org-get-next-sibling))
11049 (org-end-of-subtree t t)
11050 (point-max)))))
11051 (setq level 1)
11052 (if (not reversed)
11053 (goto-char (point-max))
11054 (goto-char (point-min))
11055 (or (outline-next-heading) (goto-char (point-max)))))
11056 (if (not (bolp)) (newline))
11057 (org-paste-subtree level)
11058 (when org-log-refile
11059 (org-add-log-setup 'refile nil nil 'findpos
11060 org-log-refile)
11061 (unless (eq org-log-refile 'note)
11062 (save-excursion (org-add-log-note))))
11063 (and org-auto-align-tags
11064 (let ((org-loop-over-headlines-in-active-region nil))
11065 (org-set-tags nil t)))
11066 (with-demoted-errors
11067 (bookmark-set "org-refile-last-stored"))
11068 ;; If we are refiling for capture, make sure that the
11069 ;; last-capture pointers point here
11070 (when (org-bound-and-true-p org-refile-for-capture)
11071 (with-demoted-errors
11072 (bookmark-set "org-capture-last-stored-marker"))
11073 (move-marker org-capture-last-stored-marker (point)))
11074 (if (fboundp 'deactivate-mark) (deactivate-mark))
11075 (run-hooks 'org-after-refile-insert-hook))))
11076 (unless org-refile-keep
11077 (if regionp
11078 (delete-region (point) (+ (point) region-length))
11079 (org-cut-subtree)))
11080 (when (featurep 'org-inlinetask)
11081 (org-inlinetask-remove-END-maybe))
11082 (setq org-markers-to-move nil)
11083 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11085 (defun org-refile-goto-last-stored ()
11086 "Go to the location where the last refile was stored."
11087 (interactive)
11088 (bookmark-jump "org-refile-last-stored")
11089 (message "This is the location of the last refile"))
11091 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11092 no-exclude)
11093 "Prompt the user for a refile location, using PROMPT.
11094 PROMPT should not be suffixed with a colon and a space, because
11095 this function appends the default value from
11096 `org-refile-history' automatically, if that is not empty.
11097 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11098 this is used for the GOTO interface."
11099 (let ((org-refile-targets org-refile-targets)
11100 (org-refile-use-outline-path org-refile-use-outline-path)
11101 excluded-entries)
11102 (when (and (derived-mode-p 'org-mode)
11103 (not org-refile-use-cache)
11104 (not no-exclude))
11105 (org-map-tree
11106 (lambda()
11107 (setq excluded-entries
11108 (append excluded-entries (list (org-get-heading t t)))))))
11109 (setq org-refile-target-table
11110 (org-refile-get-targets default-buffer excluded-entries)))
11111 (unless org-refile-target-table
11112 (error "No refile targets"))
11113 (let* ((cbuf (current-buffer))
11114 (partial-completion-mode nil)
11115 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11116 (cfunc (if (and org-refile-use-outline-path
11117 org-outline-path-complete-in-steps)
11118 'org-olpath-completing-read
11119 'org-icompleting-read))
11120 (extra (if org-refile-use-outline-path "/" ""))
11121 (cbnex (concat (buffer-name) extra))
11122 (filename (and cfn (expand-file-name cfn)))
11123 (tbl (mapcar
11124 (lambda (x)
11125 (if (and (not (member org-refile-use-outline-path
11126 '(file full-file-path)))
11127 (not (equal filename (nth 1 x))))
11128 (cons (concat (car x) extra " ("
11129 (file-name-nondirectory (nth 1 x)) ")")
11130 (cdr x))
11131 (cons (concat (car x) extra) (cdr x))))
11132 org-refile-target-table))
11133 (completion-ignore-case t)
11134 cdef
11135 (prompt (concat prompt
11136 (or (and (car org-refile-history)
11137 (concat " (default " (car org-refile-history) ")"))
11138 (and (assoc cbnex tbl) (setq cdef cbnex)
11139 (concat " (default " cbnex ")"))) ": "))
11140 pa answ parent-target child parent old-hist)
11141 (setq old-hist org-refile-history)
11142 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11143 nil 'org-refile-history (or cdef (car org-refile-history))))
11144 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11145 (org-refile-check-position pa)
11146 (if pa
11147 (progn
11148 (when (or (not org-refile-history)
11149 (not (eq old-hist org-refile-history))
11150 (not (equal (car pa) (car org-refile-history))))
11151 (setq org-refile-history
11152 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11153 org-refile-history
11154 (cdr org-refile-history))))
11155 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11156 (pop org-refile-history)))
11158 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11159 (progn
11160 (setq parent (match-string 1 answ)
11161 child (match-string 2 answ))
11162 (setq parent-target (or (assoc parent tbl)
11163 (assoc (concat parent "/") tbl)))
11164 (when (and parent-target
11165 (or (eq new-nodes t)
11166 (and (eq new-nodes 'confirm)
11167 (y-or-n-p (format "Create new node \"%s\"? "
11168 child)))))
11169 (org-refile-new-child parent-target child)))
11170 (error "Invalid target location")))))
11172 (declare-function org-string-nw-p "org-macs" (s))
11173 (defun org-refile-check-position (refile-pointer)
11174 "Check if the refile pointer matches the headline to which it points."
11175 (let* ((file (nth 1 refile-pointer))
11176 (re (nth 2 refile-pointer))
11177 (pos (nth 3 refile-pointer))
11178 buffer)
11179 (if (and (not (markerp pos)) (not file))
11180 (error "Please save the buffer to a file before refiling")
11181 (when (org-string-nw-p re)
11182 (setq buffer (if (markerp pos)
11183 (marker-buffer pos)
11184 (or (find-buffer-visiting file)
11185 (find-file-noselect file))))
11186 (with-current-buffer buffer
11187 (save-excursion
11188 (save-restriction
11189 (widen)
11190 (goto-char pos)
11191 (beginning-of-line 1)
11192 (unless (org-looking-at-p re)
11193 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11195 (defun org-refile-new-child (parent-target child)
11196 "Use refile target PARENT-TARGET to add new CHILD below it."
11197 (unless parent-target
11198 (error "Cannot find parent for new node"))
11199 (let ((file (nth 1 parent-target))
11200 (pos (nth 3 parent-target))
11201 level)
11202 (with-current-buffer (or (find-buffer-visiting file)
11203 (find-file-noselect file))
11204 (save-excursion
11205 (save-restriction
11206 (widen)
11207 (if pos
11208 (goto-char pos)
11209 (goto-char (point-max))
11210 (if (not (bolp)) (newline)))
11211 (when (looking-at org-outline-regexp)
11212 (setq level (funcall outline-level))
11213 (org-end-of-subtree t t))
11214 (org-back-over-empty-lines)
11215 (insert "\n" (make-string
11216 (if pos (org-get-valid-level level 1) 1) ?*)
11217 " " child "\n")
11218 (beginning-of-line 0)
11219 (list (concat (car parent-target) "/" child) file "" (point)))))))
11221 (defun org-olpath-completing-read (prompt collection &rest args)
11222 "Read an outline path like a file name."
11223 (let ((thetable collection)
11224 (org-completion-use-ido nil) ; does not work with ido.
11225 (org-completion-use-iswitchb nil)) ; or iswitchb
11226 (apply
11227 'org-icompleting-read prompt
11228 (lambda (string predicate &optional flag)
11229 (let (rtn r f (l (length string)))
11230 (cond
11231 ((eq flag nil)
11232 ;; try completion
11233 (try-completion string thetable))
11234 ((eq flag t)
11235 ;; all-completions
11236 (setq rtn (all-completions string thetable predicate))
11237 (mapcar
11238 (lambda (x)
11239 (setq r (substring x l))
11240 (if (string-match " ([^)]*)$" x)
11241 (setq f (match-string 0 x))
11242 (setq f ""))
11243 (if (string-match "/" r)
11244 (concat string (substring r 0 (match-end 0)) f)
11246 rtn))
11247 ((eq flag 'lambda)
11248 ;; exact match?
11249 (assoc string thetable)))))
11250 args)))
11252 ;;;; Dynamic blocks
11254 (defun org-find-dblock (name)
11255 "Find the first dynamic block with name NAME in the buffer.
11256 If not found, stay at current position and return nil."
11257 (let ((case-fold-search t) pos)
11258 (save-excursion
11259 (goto-char (point-min))
11260 (setq pos (and (re-search-forward
11261 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11262 (match-beginning 0))))
11263 (if pos (goto-char pos))
11264 pos))
11266 (defconst org-dblock-start-re
11267 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11268 "Matches the start line of a dynamic block, with parameters.")
11270 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11271 "Matches the end of a dynamic block.")
11273 (defun org-create-dblock (plist)
11274 "Create a dynamic block section, with parameters taken from PLIST.
11275 PLIST must contain a :name entry which is used as name of the block."
11276 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11277 (end-of-line 1)
11278 (newline))
11279 (let ((col (current-column))
11280 (name (plist-get plist :name)))
11281 (insert "#+BEGIN: " name)
11282 (while plist
11283 (if (eq (car plist) :name)
11284 (setq plist (cddr plist))
11285 (insert " " (prin1-to-string (pop plist)))))
11286 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11287 (beginning-of-line -2)))
11289 (defun org-prepare-dblock ()
11290 "Prepare dynamic block for refresh.
11291 This empties the block, puts the cursor at the insert position and returns
11292 the property list including an extra property :name with the block name."
11293 (unless (looking-at org-dblock-start-re)
11294 (error "Not at a dynamic block"))
11295 (let* ((begdel (1+ (match-end 0)))
11296 (name (org-no-properties (match-string 1)))
11297 (params (append (list :name name)
11298 (read (concat "(" (match-string 3) ")")))))
11299 (save-excursion
11300 (beginning-of-line 1)
11301 (skip-chars-forward " \t")
11302 (setq params (plist-put params :indentation-column (current-column))))
11303 (unless (re-search-forward org-dblock-end-re nil t)
11304 (error "Dynamic block not terminated"))
11305 (setq params
11306 (append params
11307 (list :content (buffer-substring
11308 begdel (match-beginning 0)))))
11309 (delete-region begdel (match-beginning 0))
11310 (goto-char begdel)
11311 (open-line 1)
11312 params))
11314 (defun org-map-dblocks (&optional command)
11315 "Apply COMMAND to all dynamic blocks in the current buffer.
11316 If COMMAND is not given, use `org-update-dblock'."
11317 (let ((cmd (or command 'org-update-dblock)))
11318 (save-excursion
11319 (goto-char (point-min))
11320 (while (re-search-forward org-dblock-start-re nil t)
11321 (goto-char (match-beginning 0))
11322 (save-excursion
11323 (condition-case nil
11324 (funcall cmd)
11325 (error (message "Error during update of dynamic block"))))
11326 (unless (re-search-forward org-dblock-end-re nil t)
11327 (error "Dynamic block not terminated"))))))
11329 (defun org-dblock-update (&optional arg)
11330 "User command for updating dynamic blocks.
11331 Update the dynamic block at point. With prefix ARG, update all dynamic
11332 blocks in the buffer."
11333 (interactive "P")
11334 (if arg
11335 (org-update-all-dblocks)
11336 (or (looking-at org-dblock-start-re)
11337 (org-beginning-of-dblock))
11338 (org-update-dblock)))
11340 (defun org-update-dblock ()
11341 "Update the dynamic block at point.
11342 This means to empty the block, parse for parameters and then call
11343 the correct writing function."
11344 (interactive)
11345 (save-window-excursion
11346 (let* ((pos (point))
11347 (line (org-current-line))
11348 (params (org-prepare-dblock))
11349 (name (plist-get params :name))
11350 (indent (plist-get params :indentation-column))
11351 (cmd (intern (concat "org-dblock-write:" name))))
11352 (message "Updating dynamic block `%s' at line %d..." name line)
11353 (funcall cmd params)
11354 (message "Updating dynamic block `%s' at line %d...done" name line)
11355 (goto-char pos)
11356 (when (and indent (> indent 0))
11357 (setq indent (make-string indent ?\ ))
11358 (save-excursion
11359 (org-beginning-of-dblock)
11360 (forward-line 1)
11361 (while (not (looking-at org-dblock-end-re))
11362 (insert indent)
11363 (beginning-of-line 2))
11364 (when (looking-at org-dblock-end-re)
11365 (and (looking-at "[ \t]+")
11366 (replace-match ""))
11367 (insert indent)))))))
11369 (defun org-beginning-of-dblock ()
11370 "Find the beginning of the dynamic block at point.
11371 Error if there is no such block at point."
11372 (let ((pos (point))
11373 beg)
11374 (end-of-line 1)
11375 (if (and (re-search-backward org-dblock-start-re nil t)
11376 (setq beg (match-beginning 0))
11377 (re-search-forward org-dblock-end-re nil t)
11378 (> (match-end 0) pos))
11379 (goto-char beg)
11380 (goto-char pos)
11381 (error "Not in a dynamic block"))))
11383 (defun org-update-all-dblocks ()
11384 "Update all dynamic blocks in the buffer.
11385 This function can be used in a hook."
11386 (interactive)
11387 (when (derived-mode-p 'org-mode)
11388 (org-map-dblocks 'org-update-dblock)))
11391 ;;;; Completion
11393 (defconst org-additional-option-like-keywords
11394 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11395 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11396 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11397 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11398 "BEGIN:" "END:"
11399 "ORGTBL" "TBLFM:" "TBLNAME:"
11400 "BEGIN_EXAMPLE" "END_EXAMPLE"
11401 "BEGIN_VERBATIM" "END_VERBATIM"
11402 "BEGIN_QUOTE" "END_QUOTE"
11403 "BEGIN_VERSE" "END_VERSE"
11404 "BEGIN_CENTER" "END_CENTER"
11405 "BEGIN_SRC" "END_SRC"
11406 "BEGIN_RESULT" "END_RESULT"
11407 "BEGIN_lstlisting" "END_lstlisting"
11408 "NAME:" "RESULTS:"
11409 "HEADER:" "HEADERS:"
11410 "COLUMNS:" "PROPERTY:"
11411 "CAPTION:" "LABEL:"
11412 "SETUPFILE:"
11413 "INCLUDE:" "INDEX:"
11414 "BIND:"
11415 "MACRO:"))
11417 (defconst org-options-keywords
11418 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11419 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11420 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11421 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11422 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11423 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11424 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11426 (defconst org-additional-option-like-keywords-for-flyspell
11427 (delete-dups
11428 (split-string
11429 (mapconcat (lambda(k)
11430 (replace-regexp-in-string
11431 "_\\|:" " "
11432 (concat k " " (downcase k) " " (upcase k))))
11433 (append org-options-keywords org-additional-option-like-keywords)
11434 " ")
11435 " +" t)))
11437 (defcustom org-structure-template-alist
11439 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11440 "<src lang=\"?\">\n\n</src>")
11441 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11442 "<example>\n?\n</example>")
11443 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11444 "<quote>\n?\n</quote>")
11445 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11446 "<verse>\n?\n</verse>")
11447 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11448 "<center>\n?\n</center>")
11449 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11450 "<literal style=\"latex\">\n?\n</literal>")
11451 ("L" "#+LaTeX: "
11452 "<literal style=\"latex\">?</literal>")
11453 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11454 "<literal style=\"html\">\n?\n</literal>")
11455 ("H" "#+HTML: "
11456 "<literal style=\"html\">?</literal>")
11457 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11458 ("A" "#+ASCII: ")
11459 ("i" "#+INDEX: ?"
11460 "#+INDEX: ?")
11461 ("I" "#+INCLUDE: %file ?"
11462 "<include file=%file markup=\"?\">")
11464 "Structure completion elements.
11465 This is a list of abbreviation keys and values. The value gets inserted
11466 if you type `<' followed by the key and then press the completion key,
11467 usually `M-TAB'. %file will be replaced by a file name after prompting
11468 for the file using completion. The cursor will be placed at the position
11469 of the `?` in the template.
11470 There are two templates for each key, the first uses the original Org syntax,
11471 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11472 the default when the /org-mtags.el/ module has been loaded. See also the
11473 variable `org-mtags-prefer-muse-templates'."
11474 :group 'org-completion
11475 :type '(repeat
11476 (string :tag "Key")
11477 (string :tag "Template")
11478 (string :tag "Muse Template")))
11480 (defun org-try-structure-completion ()
11481 "Try to complete a structure template before point.
11482 This looks for strings like \"<e\" on an otherwise empty line and
11483 expands them."
11484 (let ((l (buffer-substring (point-at-bol) (point)))
11486 (when (and (looking-at "[ \t]*$")
11487 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11488 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11489 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11490 (match-beginning 1)) a)
11491 t)))
11493 (defun org-complete-expand-structure-template (start cell)
11494 "Expand a structure template."
11495 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11496 (rpl (nth (if musep 2 1) cell))
11497 (ind ""))
11498 (delete-region start (point))
11499 (when (string-match "\\`#\\+" rpl)
11500 (cond
11501 ((bolp))
11502 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11503 (setq ind (buffer-substring (point-at-bol) (point))))
11504 (t (newline))))
11505 (setq start (point))
11506 (if (string-match "%file" rpl)
11507 (setq rpl (replace-match
11508 (concat
11509 "\""
11510 (save-match-data
11511 (abbreviate-file-name (read-file-name "Include file: ")))
11512 "\"")
11513 t t rpl)))
11514 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11515 (concat "\n" ind)))
11516 (insert rpl)
11517 (if (re-search-backward "\\?" start t) (delete-char 1))))
11519 ;;;; TODO, DEADLINE, Comments
11521 (defun org-toggle-comment ()
11522 "Change the COMMENT state of an entry."
11523 (interactive)
11524 (save-excursion
11525 (org-back-to-heading)
11526 (let (case-fold-search)
11527 (cond
11528 ((looking-at (format org-heading-keyword-regexp-format
11529 org-comment-string))
11530 (goto-char (match-end 1))
11531 (looking-at (concat " +" org-comment-string))
11532 (replace-match "" t t)
11533 (when (eolp) (insert " ")))
11534 ((looking-at org-outline-regexp)
11535 (goto-char (match-end 0))
11536 (insert org-comment-string " "))))))
11538 (defvar org-last-todo-state-is-todo nil
11539 "This is non-nil when the last TODO state change led to a TODO state.
11540 If the last change removed the TODO tag or switched to DONE, then
11541 this is nil.")
11543 (defvar org-setting-tags nil) ; dynamically skipped
11545 (defvar org-todo-setup-filter-hook nil
11546 "Hook for functions that pre-filter todo specs.
11547 Each function takes a todo spec and returns either nil or the spec
11548 transformed into canonical form." )
11550 (defvar org-todo-get-default-hook nil
11551 "Hook for functions that get a default item for todo.
11552 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11553 nil or a string to be used for the todo mark." )
11555 (defvar org-agenda-headline-snapshot-before-repeat)
11557 (defun org-current-effective-time ()
11558 "Return current time adjusted for `org-extend-today-until' variable."
11559 (let* ((ct (org-current-time))
11560 (dct (decode-time ct))
11561 (ct1
11562 (cond
11563 (org-use-last-clock-out-time-as-effective-time
11564 (or (org-clock-get-last-clock-out-time) ct))
11565 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11566 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11567 (t ct))))
11568 ct1))
11570 (defun org-todo-yesterday (&optional arg)
11571 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11572 (interactive "P")
11573 (if (eq major-mode 'org-agenda-mode)
11574 (apply 'org-agenda-todo-yesterday arg)
11575 (let* ((hour (third (decode-time
11576 (org-current-time))))
11577 (org-extend-today-until (1+ hour)))
11578 (org-todo arg))))
11580 (defun org-todo (&optional arg)
11581 "Change the TODO state of an item.
11582 The state of an item is given by a keyword at the start of the heading,
11583 like
11584 *** TODO Write paper
11585 *** DONE Call mom
11587 The different keywords are specified in the variable `org-todo-keywords'.
11588 By default the available states are \"TODO\" and \"DONE\".
11589 So for this example: when the item starts with TODO, it is changed to DONE.
11590 When it starts with DONE, the DONE is removed. And when neither TODO nor
11591 DONE are present, add TODO at the beginning of the heading.
11593 With \\[universal-argument] prefix arg, use completion to determine the new \
11594 state.
11595 With numeric prefix arg, switch to that state.
11596 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11597 keywords (nextset).
11598 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11599 With a numeric prefix arg of 0, inhibit note taking for the change.
11601 For calling through lisp, arg is also interpreted in the following way:
11602 'none -> empty state
11603 \"\"(empty string) -> switch to empty state
11604 'done -> switch to DONE
11605 'nextset -> switch to the next set of keywords
11606 'previousset -> switch to the previous set of keywords
11607 \"WAITING\" -> switch to the specified keyword, but only if it
11608 really is a member of `org-todo-keywords'."
11609 (interactive "P")
11610 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11611 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11612 'region-start-level 'region))
11613 org-loop-over-headlines-in-active-region)
11614 (org-map-entries
11615 `(org-todo ,arg)
11616 org-loop-over-headlines-in-active-region
11617 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11618 (if (equal arg '(16)) (setq arg 'nextset))
11619 (let ((org-blocker-hook org-blocker-hook)
11620 (case-fold-search nil))
11621 (when (equal arg '(64))
11622 (setq arg nil org-blocker-hook nil))
11623 (when (and org-blocker-hook
11624 (or org-inhibit-blocking
11625 (org-entry-get nil "NOBLOCKING")))
11626 (setq org-blocker-hook nil))
11627 (save-excursion
11628 (catch 'exit
11629 (org-back-to-heading t)
11630 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11631 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11632 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11633 (let* ((match-data (match-data))
11634 (startpos (point-at-bol))
11635 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11636 (org-log-done org-log-done)
11637 (org-log-repeat org-log-repeat)
11638 (org-todo-log-states org-todo-log-states)
11639 (org-inhibit-logging
11640 (if (equal arg 0)
11641 (progn (setq arg nil) 'note) org-inhibit-logging))
11642 (this (match-string 1))
11643 (hl-pos (match-beginning 0))
11644 (head (org-get-todo-sequence-head this))
11645 (ass (assoc head org-todo-kwd-alist))
11646 (interpret (nth 1 ass))
11647 (done-word (nth 3 ass))
11648 (final-done-word (nth 4 ass))
11649 (org-last-state (or this ""))
11650 (completion-ignore-case t)
11651 (member (member this org-todo-keywords-1))
11652 (tail (cdr member))
11653 (org-state (cond
11654 ((and org-todo-key-trigger
11655 (or (and (equal arg '(4))
11656 (eq org-use-fast-todo-selection 'prefix))
11657 (and (not arg) org-use-fast-todo-selection
11658 (not (eq org-use-fast-todo-selection
11659 'prefix)))))
11660 ;; Use fast selection
11661 (org-fast-todo-selection))
11662 ((and (equal arg '(4))
11663 (or (not org-use-fast-todo-selection)
11664 (not org-todo-key-trigger)))
11665 ;; Read a state with completion
11666 (org-icompleting-read
11667 "State: " (mapcar (lambda(x) (list x))
11668 org-todo-keywords-1)
11669 nil t))
11670 ((eq arg 'right)
11671 (if this
11672 (if tail (car tail) nil)
11673 (car org-todo-keywords-1)))
11674 ((eq arg 'left)
11675 (if (equal member org-todo-keywords-1)
11677 (if this
11678 (nth (- (length org-todo-keywords-1)
11679 (length tail) 2)
11680 org-todo-keywords-1)
11681 (org-last org-todo-keywords-1))))
11682 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11683 (setq arg nil))) ; hack to fall back to cycling
11684 (arg
11685 ;; user or caller requests a specific state
11686 (cond
11687 ((equal arg "") nil)
11688 ((eq arg 'none) nil)
11689 ((eq arg 'done) (or done-word (car org-done-keywords)))
11690 ((eq arg 'nextset)
11691 (or (car (cdr (member head org-todo-heads)))
11692 (car org-todo-heads)))
11693 ((eq arg 'previousset)
11694 (let ((org-todo-heads (reverse org-todo-heads)))
11695 (or (car (cdr (member head org-todo-heads)))
11696 (car org-todo-heads))))
11697 ((car (member arg org-todo-keywords-1)))
11698 ((stringp arg)
11699 (error "State `%s' not valid in this file" arg))
11700 ((nth (1- (prefix-numeric-value arg))
11701 org-todo-keywords-1))))
11702 ((null member) (or head (car org-todo-keywords-1)))
11703 ((equal this final-done-word) nil) ;; -> make empty
11704 ((null tail) nil) ;; -> first entry
11705 ((memq interpret '(type priority))
11706 (if (eq this-command last-command)
11707 (car tail)
11708 (if (> (length tail) 0)
11709 (or done-word (car org-done-keywords))
11710 nil)))
11712 (car tail))))
11713 (org-state (or
11714 (run-hook-with-args-until-success
11715 'org-todo-get-default-hook org-state org-last-state)
11716 org-state))
11717 (next (if org-state (concat " " org-state " ") " "))
11718 (change-plist (list :type 'todo-state-change :from this :to org-state
11719 :position startpos))
11720 dolog now-done-p)
11721 (when org-blocker-hook
11722 (setq org-last-todo-state-is-todo
11723 (not (member this org-done-keywords)))
11724 (unless (save-excursion
11725 (save-match-data
11726 (org-with-wide-buffer
11727 (run-hook-with-args-until-failure
11728 'org-blocker-hook change-plist))))
11729 (if (org-called-interactively-p 'interactive)
11730 (error "TODO state change from %s to %s blocked" this org-state)
11731 ;; fail silently
11732 (message "TODO state change from %s to %s blocked" this org-state)
11733 (throw 'exit nil))))
11734 (store-match-data match-data)
11735 (replace-match next t t)
11736 (unless (pos-visible-in-window-p hl-pos)
11737 (message "TODO state changed to %s" (org-trim next)))
11738 (unless head
11739 (setq head (org-get-todo-sequence-head org-state)
11740 ass (assoc head org-todo-kwd-alist)
11741 interpret (nth 1 ass)
11742 done-word (nth 3 ass)
11743 final-done-word (nth 4 ass)))
11744 (when (memq arg '(nextset previousset))
11745 (message "Keyword-Set %d/%d: %s"
11746 (- (length org-todo-sets) -1
11747 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11748 (length org-todo-sets)
11749 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11750 (setq org-last-todo-state-is-todo
11751 (not (member org-state org-done-keywords)))
11752 (setq now-done-p (and (member org-state org-done-keywords)
11753 (not (member this org-done-keywords))))
11754 (and logging (org-local-logging logging))
11755 (when (and (or org-todo-log-states org-log-done)
11756 (not (eq org-inhibit-logging t))
11757 (not (memq arg '(nextset previousset))))
11758 ;; we need to look at recording a time and note
11759 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11760 (nth 2 (assoc this org-todo-log-states))))
11761 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11762 (setq dolog 'time))
11763 (when (and org-state
11764 (member org-state org-not-done-keywords)
11765 (not (member this org-not-done-keywords)))
11766 ;; This is now a todo state and was not one before
11767 ;; If there was a CLOSED time stamp, get rid of it.
11768 (org-add-planning-info nil nil 'closed))
11769 (when (and now-done-p org-log-done)
11770 ;; It is now done, and it was not done before
11771 (org-add-planning-info 'closed (org-current-effective-time))
11772 (if (and (not dolog) (eq 'note org-log-done))
11773 (org-add-log-setup 'done org-state this 'findpos 'note)))
11774 (when (and org-state dolog)
11775 ;; This is a non-nil state, and we need to log it
11776 (org-add-log-setup 'state org-state this 'findpos dolog)))
11777 ;; Fixup tag positioning
11778 (org-todo-trigger-tag-changes org-state)
11779 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11780 (when org-provide-todo-statistics
11781 (org-update-parent-todo-statistics))
11782 (run-hooks 'org-after-todo-state-change-hook)
11783 (if (and arg (not (member org-state org-done-keywords)))
11784 (setq head (org-get-todo-sequence-head org-state)))
11785 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11786 ;; Do we need to trigger a repeat?
11787 (when now-done-p
11788 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11789 ;; This is for the agenda, take a snapshot of the headline.
11790 (save-match-data
11791 (setq org-agenda-headline-snapshot-before-repeat
11792 (org-get-heading))))
11793 (org-auto-repeat-maybe org-state))
11794 ;; Fixup cursor location if close to the keyword
11795 (if (and (outline-on-heading-p)
11796 (not (bolp))
11797 (save-excursion (beginning-of-line 1)
11798 (looking-at org-todo-line-regexp))
11799 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11800 (progn
11801 (goto-char (or (match-end 2) (match-end 1)))
11802 (and (looking-at " ") (just-one-space))))
11803 (when org-trigger-hook
11804 (save-excursion
11805 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11807 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11808 "Block turning an entry into a TODO, using the hierarchy.
11809 This checks whether the current task should be blocked from state
11810 changes. Such blocking occurs when:
11812 1. The task has children which are not all in a completed state.
11814 2. A task has a parent with the property :ORDERED:, and there
11815 are siblings prior to the current task with incomplete
11816 status.
11818 3. The parent of the task is blocked because it has siblings that should
11819 be done first, or is child of a block grandparent TODO entry."
11821 (if (not org-enforce-todo-dependencies)
11822 t ; if locally turned off don't block
11823 (catch 'dont-block
11824 ;; If this is not a todo state change, or if this entry is already DONE,
11825 ;; do not block
11826 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11827 (member (plist-get change-plist :from)
11828 (cons 'done org-done-keywords))
11829 (member (plist-get change-plist :to)
11830 (cons 'todo org-not-done-keywords))
11831 (not (plist-get change-plist :to)))
11832 (throw 'dont-block t))
11833 ;; If this task has children, and any are undone, it's blocked
11834 (save-excursion
11835 (org-back-to-heading t)
11836 (let ((this-level (funcall outline-level)))
11837 (outline-next-heading)
11838 (let ((child-level (funcall outline-level)))
11839 (while (and (not (eobp))
11840 (> child-level this-level))
11841 ;; this todo has children, check whether they are all
11842 ;; completed
11843 (if (and (not (org-entry-is-done-p))
11844 (org-entry-is-todo-p))
11845 (throw 'dont-block nil))
11846 (outline-next-heading)
11847 (setq child-level (funcall outline-level))))))
11848 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11849 ;; any previous siblings are undone, it's blocked
11850 (save-excursion
11851 (org-back-to-heading t)
11852 (let* ((pos (point))
11853 (parent-pos (and (org-up-heading-safe) (point))))
11854 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11855 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11856 (forward-line 1)
11857 (re-search-forward org-not-done-heading-regexp pos t))
11858 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11859 ;; Search further up the hierarchy, to see if an ancestor is blocked
11860 (while t
11861 (goto-char parent-pos)
11862 (if (not (looking-at org-not-done-heading-regexp))
11863 (throw 'dont-block t)) ; do not block, parent is not a TODO
11864 (setq pos (point))
11865 (setq parent-pos (and (org-up-heading-safe) (point)))
11866 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11867 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11868 (forward-line 1)
11869 (re-search-forward org-not-done-heading-regexp pos t))
11870 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11872 (defcustom org-track-ordered-property-with-tag nil
11873 "Should the ORDERED property also be shown as a tag?
11874 The ORDERED property decides if an entry should require subtasks to be
11875 completed in sequence. Since a property is not very visible, setting
11876 this option means that toggling the ORDERED property with the command
11877 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11878 not relevant for the behavior, but it makes things more visible.
11880 Note that toggling the tag with tags commands will not change the property
11881 and therefore not influence behavior!
11883 This can be t, meaning the tag ORDERED should be used, It can also be a
11884 string to select a different tag for this task."
11885 :group 'org-todo
11886 :type '(choice
11887 (const :tag "No tracking" nil)
11888 (const :tag "Track with ORDERED tag" t)
11889 (string :tag "Use other tag")))
11891 (defun org-toggle-ordered-property ()
11892 "Toggle the ORDERED property of the current entry.
11893 For better visibility, you can track the value of this property with a tag.
11894 See variable `org-track-ordered-property-with-tag'."
11895 (interactive)
11896 (let* ((t1 org-track-ordered-property-with-tag)
11897 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11898 (save-excursion
11899 (org-back-to-heading)
11900 (if (org-entry-get nil "ORDERED")
11901 (progn
11902 (org-delete-property "ORDERED")
11903 (and tag (org-toggle-tag tag 'off))
11904 (message "Subtasks can be completed in arbitrary order"))
11905 (org-entry-put nil "ORDERED" "t")
11906 (and tag (org-toggle-tag tag 'on))
11907 (message "Subtasks must be completed in sequence")))))
11909 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11910 (defun org-block-todo-from-checkboxes (change-plist)
11911 "Block turning an entry into a TODO, using checkboxes.
11912 This checks whether the current task should be blocked from state
11913 changes because there are unchecked boxes in this entry."
11914 (if (not org-enforce-todo-checkbox-dependencies)
11915 t ; if locally turned off don't block
11916 (catch 'dont-block
11917 ;; If this is not a todo state change, or if this entry is already DONE,
11918 ;; do not block
11919 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11920 (member (plist-get change-plist :from)
11921 (cons 'done org-done-keywords))
11922 (member (plist-get change-plist :to)
11923 (cons 'todo org-not-done-keywords))
11924 (not (plist-get change-plist :to)))
11925 (throw 'dont-block t))
11926 ;; If this task has checkboxes that are not checked, it's blocked
11927 (save-excursion
11928 (org-back-to-heading t)
11929 (let ((beg (point)) end)
11930 (outline-next-heading)
11931 (setq end (point))
11932 (goto-char beg)
11933 (if (org-list-search-forward
11934 (concat (org-item-beginning-re)
11935 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11936 "\\[[- ]\\]")
11937 end t)
11938 (progn
11939 (if (boundp 'org-blocked-by-checkboxes)
11940 (setq org-blocked-by-checkboxes t))
11941 (throw 'dont-block nil)))))
11942 t))) ; do not block
11944 (defun org-entry-blocked-p ()
11945 "Is the current entry blocked?"
11946 (if (org-entry-get nil "NOBLOCKING")
11947 nil ;; Never block this entry
11948 (not
11949 (run-hook-with-args-until-failure
11950 'org-blocker-hook
11951 (list :type 'todo-state-change
11952 :position (point)
11953 :from 'todo
11954 :to 'done)))))
11956 (defun org-update-statistics-cookies (all)
11957 "Update the statistics cookie, either from TODO or from checkboxes.
11958 This should be called with the cursor in a line with a statistics cookie."
11959 (interactive "P")
11960 (if all
11961 (progn
11962 (org-update-checkbox-count 'all)
11963 (org-map-entries 'org-update-parent-todo-statistics))
11964 (if (not (org-at-heading-p))
11965 (org-update-checkbox-count)
11966 (let ((pos (move-marker (make-marker) (point)))
11967 end l1 l2)
11968 (ignore-errors (org-back-to-heading t))
11969 (if (not (org-at-heading-p))
11970 (org-update-checkbox-count)
11971 (setq l1 (org-outline-level))
11972 (setq end (save-excursion
11973 (outline-next-heading)
11974 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11975 (point)))
11976 (if (and (save-excursion
11977 (re-search-forward
11978 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11979 (not (save-excursion (re-search-forward
11980 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11981 (org-update-checkbox-count)
11982 (if (and l2 (> l2 l1))
11983 (progn
11984 (goto-char end)
11985 (org-update-parent-todo-statistics))
11986 (goto-char pos)
11987 (beginning-of-line 1)
11988 (while (re-search-forward
11989 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11990 (point-at-eol) t)
11991 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11992 (goto-char pos)
11993 (move-marker pos nil)))))
11995 (defvar org-entry-property-inherited-from) ;; defined below
11996 (defun org-update-parent-todo-statistics ()
11997 "Update any statistics cookie in the parent of the current headline.
11998 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11999 the entire subtree and this will travel up the hierarchy and update
12000 statistics everywhere."
12001 (let* ((prop (save-excursion (org-up-heading-safe)
12002 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12003 (recursive (or (not org-hierarchical-todo-statistics)
12004 (and prop (string-match "\\<recursive\\>" prop))))
12005 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12007 (first t)
12008 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12009 level ltoggle l1 new ndel
12010 (cnt-all 0) (cnt-done 0) is-percent kwd
12011 checkbox-beg ov ovs ove cookie-present)
12012 (catch 'exit
12013 (save-excursion
12014 (beginning-of-line 1)
12015 (setq ltoggle (funcall outline-level))
12016 ;; Three situations are to consider:
12018 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12019 ;; to the top-level ancestor on the headline;
12021 ;; 2. If parent has "recursive" property, repeat up to the
12022 ;; headline setting that property, taking inheritance into
12023 ;; account;
12025 ;; 3. Else, move up to direct parent and proceed only once.
12026 (while (and (setq level (org-up-heading-safe))
12027 (or recursive first)
12028 (>= (point) lim))
12029 (setq first nil cookie-present nil)
12030 (unless (and level
12031 (not (string-match
12032 "\\<checkbox\\>"
12033 (downcase (or (org-entry-get nil "COOKIE_DATA")
12034 "")))))
12035 (throw 'exit nil))
12036 (while (re-search-forward box-re (point-at-eol) t)
12037 (setq cnt-all 0 cnt-done 0 cookie-present t)
12038 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12039 (save-match-data
12040 (unless (outline-next-heading) (throw 'exit nil))
12041 (while (and (looking-at org-complex-heading-regexp)
12042 (> (setq l1 (length (match-string 1))) level))
12043 (setq kwd (and (or recursive (= l1 ltoggle))
12044 (match-string 2)))
12045 (if (or (eq org-provide-todo-statistics 'all-headlines)
12046 (and (listp org-provide-todo-statistics)
12047 (or (member kwd org-provide-todo-statistics)
12048 (member kwd org-done-keywords))))
12049 (setq cnt-all (1+ cnt-all))
12050 (if (eq org-provide-todo-statistics t)
12051 (and kwd (setq cnt-all (1+ cnt-all)))))
12052 (and (member kwd org-done-keywords)
12053 (setq cnt-done (1+ cnt-done)))
12054 (outline-next-heading)))
12055 (setq new
12056 (if is-percent
12057 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12058 (format "[%d/%d]" cnt-done cnt-all))
12059 ndel (- (match-end 0) checkbox-beg))
12060 ;; handle overlays when updating cookie from column view
12061 (when (setq ov (car (overlays-at checkbox-beg)))
12062 (setq ovs (overlay-start ov) ove (overlay-end ov))
12063 (delete-overlay ov))
12064 (goto-char checkbox-beg)
12065 (insert new)
12066 (delete-region (point) (+ (point) ndel))
12067 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12068 (when ov (move-overlay ov ovs ove)))
12069 (when cookie-present
12070 (run-hook-with-args 'org-after-todo-statistics-hook
12071 cnt-done (- cnt-all cnt-done))))))
12072 (run-hooks 'org-todo-statistics-hook)))
12074 (defvar org-after-todo-statistics-hook nil
12075 "Hook that is called after a TODO statistics cookie has been updated.
12076 Each function is called with two arguments: the number of not-done entries
12077 and the number of done entries.
12079 For example, the following function, when added to this hook, will switch
12080 an entry to DONE when all children are done, and back to TODO when new
12081 entries are set to a TODO status. Note that this hook is only called
12082 when there is a statistics cookie in the headline!
12084 (defun org-summary-todo (n-done n-not-done)
12085 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12086 (let (org-log-done org-log-states) ; turn off logging
12087 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12090 (defvar org-todo-statistics-hook nil
12091 "Hook that is run whenever Org thinks TODO statistics should be updated.
12092 This hook runs even if there is no statistics cookie present, in which case
12093 `org-after-todo-statistics-hook' would not run.")
12095 (defun org-todo-trigger-tag-changes (state)
12096 "Apply the changes defined in `org-todo-state-tags-triggers'."
12097 (let ((l org-todo-state-tags-triggers)
12098 changes)
12099 (when (or (not state) (equal state ""))
12100 (setq changes (append changes (cdr (assoc "" l)))))
12101 (when (and (stringp state) (> (length state) 0))
12102 (setq changes (append changes (cdr (assoc state l)))))
12103 (when (member state org-not-done-keywords)
12104 (setq changes (append changes (cdr (assoc 'todo l)))))
12105 (when (member state org-done-keywords)
12106 (setq changes (append changes (cdr (assoc 'done l)))))
12107 (dolist (c changes)
12108 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12110 (defun org-local-logging (value)
12111 "Get logging settings from a property VALUE."
12112 (let* (words w a)
12113 ;; directly set the variables, they are already local.
12114 (setq org-log-done nil
12115 org-log-repeat nil
12116 org-todo-log-states nil)
12117 (setq words (org-split-string value))
12118 (while (setq w (pop words))
12119 (cond
12120 ((setq a (assoc w org-startup-options))
12121 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12122 (set (nth 1 a) (nth 2 a))))
12123 ((setq a (org-extract-log-state-settings w))
12124 (and (member (car a) org-todo-keywords-1)
12125 (push a org-todo-log-states)))))))
12127 (defun org-get-todo-sequence-head (kwd)
12128 "Return the head of the TODO sequence to which KWD belongs.
12129 If KWD is not set, check if there is a text property remembering the
12130 right sequence."
12131 (let (p)
12132 (cond
12133 ((not kwd)
12134 (or (get-text-property (point-at-bol) 'org-todo-head)
12135 (progn
12136 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12137 nil (point-at-eol)))
12138 (get-text-property p 'org-todo-head))))
12139 ((not (member kwd org-todo-keywords-1))
12140 (car org-todo-keywords-1))
12141 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12143 (defun org-fast-todo-selection ()
12144 "Fast TODO keyword selection with single keys.
12145 Returns the new TODO keyword, or nil if no state change should occur."
12146 (let* ((fulltable org-todo-key-alist)
12147 (done-keywords org-done-keywords) ;; needed for the faces.
12148 (maxlen (apply 'max (mapcar
12149 (lambda (x)
12150 (if (stringp (car x)) (string-width (car x)) 0))
12151 fulltable)))
12152 (expert nil)
12153 (fwidth (+ maxlen 3 1 3))
12154 (ncol (/ (- (window-width) 4) fwidth))
12155 tg cnt e c tbl
12156 groups ingroup)
12157 (save-excursion
12158 (save-window-excursion
12159 (if expert
12160 (set-buffer (get-buffer-create " *Org todo*"))
12161 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12162 (erase-buffer)
12163 (org-set-local 'org-done-keywords done-keywords)
12164 (setq tbl fulltable cnt 0)
12165 (while (setq e (pop tbl))
12166 (cond
12167 ((equal e '(:startgroup))
12168 (push '() groups) (setq ingroup t)
12169 (when (not (= cnt 0))
12170 (setq cnt 0)
12171 (insert "\n"))
12172 (insert "{ "))
12173 ((equal e '(:endgroup))
12174 (setq ingroup nil cnt 0)
12175 (insert "}\n"))
12176 ((equal e '(:newline))
12177 (when (not (= cnt 0))
12178 (setq cnt 0)
12179 (insert "\n")
12180 (setq e (car tbl))
12181 (while (equal (car tbl) '(:newline))
12182 (insert "\n")
12183 (setq tbl (cdr tbl)))))
12185 (setq tg (car e) c (cdr e))
12186 (if ingroup (push tg (car groups)))
12187 (setq tg (org-add-props tg nil 'face
12188 (org-get-todo-face tg)))
12189 (if (and (= cnt 0) (not ingroup)) (insert " "))
12190 (insert "[" c "] " tg (make-string
12191 (- fwidth 4 (length tg)) ?\ ))
12192 (when (= (setq cnt (1+ cnt)) ncol)
12193 (insert "\n")
12194 (if ingroup (insert " "))
12195 (setq cnt 0)))))
12196 (insert "\n")
12197 (goto-char (point-min))
12198 (if (not expert) (org-fit-window-to-buffer))
12199 (message "[a-z..]:Set [SPC]:clear")
12200 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12201 (cond
12202 ((or (= c ?\C-g)
12203 (and (= c ?q) (not (rassoc c fulltable))))
12204 (setq quit-flag t))
12205 ((= c ?\ ) nil)
12206 ((setq e (rassoc c fulltable) tg (car e))
12208 (t (setq quit-flag t)))))))
12210 (defun org-entry-is-todo-p ()
12211 (member (org-get-todo-state) org-not-done-keywords))
12213 (defun org-entry-is-done-p ()
12214 (member (org-get-todo-state) org-done-keywords))
12216 (defun org-get-todo-state ()
12217 (save-excursion
12218 (org-back-to-heading t)
12219 (and (looking-at org-todo-line-regexp)
12220 (match-end 2)
12221 (match-string 2))))
12223 (defun org-at-date-range-p (&optional inactive-ok)
12224 "Is the cursor inside a date range?"
12225 (interactive)
12226 (save-excursion
12227 (catch 'exit
12228 (let ((pos (point)))
12229 (skip-chars-backward "^[<\r\n")
12230 (skip-chars-backward "<[")
12231 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12232 (>= (match-end 0) pos)
12233 (throw 'exit t))
12234 (skip-chars-backward "^<[\r\n")
12235 (skip-chars-backward "<[")
12236 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12237 (>= (match-end 0) pos)
12238 (throw 'exit t)))
12239 nil)))
12241 (defun org-get-repeat (&optional tagline)
12242 "Check if there is a deadline/schedule with repeater in this entry."
12243 (save-match-data
12244 (save-excursion
12245 (org-back-to-heading t)
12246 (and (re-search-forward (if tagline
12247 (concat tagline "\\s-*" org-repeat-re)
12248 org-repeat-re)
12249 (org-entry-end-position) t)
12250 (match-string-no-properties 1)))))
12252 (defvar org-last-changed-timestamp)
12253 (defvar org-last-inserted-timestamp)
12254 (defvar org-log-post-message)
12255 (defvar org-log-note-purpose)
12256 (defvar org-log-note-how)
12257 (defvar org-log-note-extra)
12258 (defun org-auto-repeat-maybe (done-word)
12259 "Check if the current headline contains a repeated deadline/schedule.
12260 If yes, set TODO state back to what it was and change the base date
12261 of repeating deadline/scheduled time stamps to new date.
12262 This function is run automatically after each state change to a DONE state."
12263 ;; last-state is dynamically scoped into this function
12264 (let* ((repeat (org-get-repeat))
12265 (aa (assoc org-last-state org-todo-kwd-alist))
12266 (interpret (nth 1 aa))
12267 (head (nth 2 aa))
12268 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12269 (msg "Entry repeats: ")
12270 (org-log-done nil)
12271 (org-todo-log-states nil)
12272 re type n what ts time to-state)
12273 (when repeat
12274 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12275 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12276 org-todo-repeat-to-state))
12277 (unless (and to-state (member to-state org-todo-keywords-1))
12278 (setq to-state (if (eq interpret 'type) org-last-state head)))
12279 (org-todo to-state)
12280 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12281 (org-entry-put nil "LAST_REPEAT" (format-time-string
12282 (org-time-stamp-format t t))))
12283 (when org-log-repeat
12284 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12285 (memq 'org-add-log-note post-command-hook))
12286 ;; OK, we are already setup for some record
12287 (if (eq org-log-repeat 'note)
12288 ;; make sure we take a note, not only a time stamp
12289 (setq org-log-note-how 'note))
12290 ;; Set up for taking a record
12291 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12292 org-last-state
12293 'findpos org-log-repeat)))
12294 (org-back-to-heading t)
12295 (org-add-planning-info nil nil 'closed)
12296 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12297 org-deadline-time-regexp "\\)\\|\\("
12298 org-ts-regexp "\\)"))
12299 (while (re-search-forward
12300 re (save-excursion (outline-next-heading) (point)) t)
12301 (setq type (if (match-end 1) org-scheduled-string
12302 (if (match-end 3) org-deadline-string "Plain:"))
12303 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12304 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12305 (setq n (string-to-number (match-string 2 ts))
12306 what (match-string 3 ts))
12307 (if (equal what "w") (setq n (* n 7) what "d"))
12308 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12309 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12310 ;; Preparation, see if we need to modify the start date for the change
12311 (when (match-end 1)
12312 (setq time (save-match-data (org-time-string-to-time ts)))
12313 (cond
12314 ((equal (match-string 1 ts) ".")
12315 ;; Shift starting date to today
12316 (org-timestamp-change
12317 (- (org-today) (time-to-days time))
12318 'day))
12319 ((equal (match-string 1 ts) "+")
12320 (let ((nshiftmax 10) (nshift 0))
12321 (while (or (= nshift 0)
12322 (<= (time-to-days time)
12323 (time-to-days (current-time))))
12324 (when (= (incf nshift) nshiftmax)
12325 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12326 (error "Abort")))
12327 (org-timestamp-change n (cdr (assoc what whata)))
12328 (org-at-timestamp-p t)
12329 (setq ts (match-string 1))
12330 (setq time (save-match-data (org-time-string-to-time ts)))))
12331 (org-timestamp-change (- n) (cdr (assoc what whata)))
12332 ;; rematch, so that we have everything in place for the real shift
12333 (org-at-timestamp-p t)
12334 (setq ts (match-string 1))
12335 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12336 (org-timestamp-change n (cdr (assoc what whata)))
12337 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12338 (setq org-log-post-message msg)
12339 (message "%s" msg))))
12341 (defun org-show-todo-tree (arg)
12342 "Make a compact tree which shows all headlines marked with TODO.
12343 The tree will show the lines where the regexp matches, and all higher
12344 headlines above the match.
12345 With a \\[universal-argument] prefix, prompt for a regexp to match.
12346 With a numeric prefix N, construct a sparse tree for the Nth element
12347 of `org-todo-keywords-1'."
12348 (interactive "P")
12349 (let ((case-fold-search nil)
12350 (kwd-re
12351 (cond ((null arg) org-not-done-regexp)
12352 ((equal arg '(4))
12353 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12354 (mapcar 'list org-todo-keywords-1))))
12355 (concat "\\("
12356 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12357 "\\)\\>")))
12358 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12359 (regexp-quote (nth (1- (prefix-numeric-value arg))
12360 org-todo-keywords-1)))
12361 (t (error "Invalid prefix argument: %s" arg)))))
12362 (message "%d TODO entries found"
12363 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12365 (defun org-deadline (&optional remove time)
12366 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12367 With argument REMOVE, remove any deadline from the item.
12368 With argument TIME, set the deadline at the corresponding date. TIME
12369 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12370 (interactive "P")
12371 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12372 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12373 'region-start-level 'region))
12374 org-loop-over-headlines-in-active-region)
12375 (org-map-entries
12376 `(org-deadline ',remove ,time)
12377 org-loop-over-headlines-in-active-region
12378 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12379 (let* ((old-date (org-entry-get nil "DEADLINE"))
12380 (repeater (and old-date
12381 (string-match
12382 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12383 old-date)
12384 (match-string 1 old-date))))
12385 (if remove
12386 (progn
12387 (when (and old-date org-log-redeadline)
12388 (org-add-log-setup 'deldeadline nil old-date 'findpos
12389 org-log-redeadline))
12390 (org-remove-timestamp-with-keyword org-deadline-string)
12391 (message "Item no longer has a deadline."))
12392 (org-add-planning-info 'deadline time 'closed)
12393 (when (and old-date org-log-redeadline
12394 (not (equal old-date
12395 (substring org-last-inserted-timestamp 1 -1))))
12396 (org-add-log-setup 'redeadline nil old-date 'findpos
12397 org-log-redeadline))
12398 (when repeater
12399 (save-excursion
12400 (org-back-to-heading t)
12401 (when (re-search-forward (concat org-deadline-string " "
12402 org-last-inserted-timestamp)
12403 (save-excursion
12404 (outline-next-heading) (point)) t)
12405 (goto-char (1- (match-end 0)))
12406 (insert " " repeater)
12407 (setq org-last-inserted-timestamp
12408 (concat (substring org-last-inserted-timestamp 0 -1)
12409 " " repeater
12410 (substring org-last-inserted-timestamp -1))))))
12411 (message "Deadline on %s" org-last-inserted-timestamp)))))
12413 (defun org-schedule (&optional remove time)
12414 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12415 With argument REMOVE, remove any scheduling date from the item.
12416 With argument TIME, scheduled at the corresponding date. TIME can
12417 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12418 (interactive "P")
12419 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12420 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12421 'region-start-level 'region))
12422 org-loop-over-headlines-in-active-region)
12423 (org-map-entries
12424 `(org-schedule ',remove ,time)
12425 org-loop-over-headlines-in-active-region
12426 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12427 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12428 (repeater (and old-date
12429 (string-match
12430 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12431 old-date)
12432 (match-string 1 old-date))))
12433 (if remove
12434 (progn
12435 (when (and old-date org-log-reschedule)
12436 (org-add-log-setup 'delschedule nil old-date 'findpos
12437 org-log-reschedule))
12438 (org-remove-timestamp-with-keyword org-scheduled-string)
12439 (message "Item is no longer scheduled."))
12440 (org-add-planning-info 'scheduled time 'closed)
12441 (when (and old-date org-log-reschedule
12442 (not (equal old-date
12443 (substring org-last-inserted-timestamp 1 -1))))
12444 (org-add-log-setup 'reschedule nil old-date 'findpos
12445 org-log-reschedule))
12446 (when repeater
12447 (save-excursion
12448 (org-back-to-heading t)
12449 (when (re-search-forward (concat org-scheduled-string " "
12450 org-last-inserted-timestamp)
12451 (save-excursion
12452 (outline-next-heading) (point)) t)
12453 (goto-char (1- (match-end 0)))
12454 (insert " " repeater)
12455 (setq org-last-inserted-timestamp
12456 (concat (substring org-last-inserted-timestamp 0 -1)
12457 " " repeater
12458 (substring org-last-inserted-timestamp -1))))))
12459 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12461 (defun org-get-scheduled-time (pom &optional inherit)
12462 "Get the scheduled time as a time tuple, of a format suitable
12463 for calling org-schedule with, or if there is no scheduling,
12464 returns nil."
12465 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12466 (when time
12467 (apply 'encode-time (org-parse-time-string time)))))
12469 (defun org-get-deadline-time (pom &optional inherit)
12470 "Get the deadline as a time tuple, of a format suitable for
12471 calling org-deadline with, or if there is no scheduling, returns
12472 nil."
12473 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12474 (when time
12475 (apply 'encode-time (org-parse-time-string time)))))
12477 (defun org-remove-timestamp-with-keyword (keyword)
12478 "Remove all time stamps with KEYWORD in the current entry."
12479 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12480 beg)
12481 (save-excursion
12482 (org-back-to-heading t)
12483 (setq beg (point))
12484 (outline-next-heading)
12485 (while (re-search-backward re beg t)
12486 (replace-match "")
12487 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12488 (equal (char-before) ?\ ))
12489 (backward-delete-char 1)
12490 (if (string-match "^[ \t]*$" (buffer-substring
12491 (point-at-bol) (point-at-eol)))
12492 (delete-region (point-at-bol)
12493 (min (point-max) (1+ (point-at-eol))))))))))
12495 (defun org-add-planning-info (what &optional time &rest remove)
12496 "Insert new timestamp with keyword in the line directly after the headline.
12497 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12498 If non is given, the user is prompted for a date.
12499 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12500 be removed."
12501 (interactive)
12502 (let (org-time-was-given org-end-time-was-given ts
12503 end default-time default-input)
12505 (catch 'exit
12506 (when (and (memq what '(scheduled deadline))
12507 (or (not time)
12508 (and (stringp time)
12509 (string-match "^[-+]+[0-9]" time))))
12510 ;; Try to get a default date/time from existing timestamp
12511 (save-excursion
12512 (org-back-to-heading t)
12513 (setq end (save-excursion (outline-next-heading) (point)))
12514 (when (re-search-forward (if (eq what 'scheduled)
12515 org-scheduled-time-regexp
12516 org-deadline-time-regexp)
12517 end t)
12518 (setq ts (match-string 1)
12519 default-time
12520 (apply 'encode-time (org-parse-time-string ts))
12521 default-input (and ts (org-get-compact-tod ts))))))
12522 (when what
12523 (setq time
12524 (if (stringp time)
12525 ;; This is a string (relative or absolute), set proper date
12526 (apply 'encode-time
12527 (org-read-date-analyze
12528 time default-time (decode-time default-time)))
12529 ;; If necessary, get the time from the user
12530 (or time (org-read-date nil 'to-time nil nil
12531 default-time default-input)))))
12533 (when (and org-insert-labeled-timestamps-at-point
12534 (member what '(scheduled deadline)))
12535 (insert
12536 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12537 (org-insert-time-stamp time org-time-was-given
12538 nil nil nil (list org-end-time-was-given))
12539 (setq what nil))
12540 (save-excursion
12541 (save-restriction
12542 (let (col list elt ts buffer-invisibility-spec)
12543 (org-back-to-heading t)
12544 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12545 (goto-char (match-end 1))
12546 (setq col (current-column))
12547 (goto-char (match-end 0))
12548 (if (eobp) (insert "\n") (forward-char 1))
12549 (when (and (not what)
12550 (not (looking-at
12551 (concat "[ \t]*"
12552 org-keyword-time-not-clock-regexp))))
12553 ;; Nothing to add, nothing to remove...... :-)
12554 (throw 'exit nil))
12555 (if (and (not (looking-at org-outline-regexp))
12556 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12557 "[^\r\n]*"))
12558 (not (equal (match-string 1) org-clock-string)))
12559 (narrow-to-region (match-beginning 0) (match-end 0))
12560 (insert-before-markers "\n")
12561 (backward-char 1)
12562 (narrow-to-region (point) (point))
12563 (and org-adapt-indentation (org-indent-to-column col)))
12564 ;; Check if we have to remove something.
12565 (setq list (cons what remove))
12566 (while list
12567 (setq elt (pop list))
12568 (when (or (and (eq elt 'scheduled)
12569 (re-search-forward org-scheduled-time-regexp nil t))
12570 (and (eq elt 'deadline)
12571 (re-search-forward org-deadline-time-regexp nil t))
12572 (and (eq elt 'closed)
12573 (re-search-forward org-closed-time-regexp nil t)))
12574 (replace-match "")
12575 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12576 (and (looking-at "[ \t]+") (replace-match ""))
12577 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12578 (when what
12579 (insert
12580 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12581 (cond ((eq what 'scheduled) org-scheduled-string)
12582 ((eq what 'deadline) org-deadline-string)
12583 ((eq what 'closed) org-closed-string))
12584 " ")
12585 (setq ts (org-insert-time-stamp
12586 time
12587 (or org-time-was-given
12588 (and (eq what 'closed) org-log-done-with-time))
12589 (eq what 'closed)
12590 nil nil (list org-end-time-was-given)))
12591 (insert
12592 (if (not (or (bolp) (eq (char-before) ?\ )
12593 (memq (char-after) '(32 10))
12594 (eobp))) " " ""))
12595 (end-of-line 1))
12596 (goto-char (point-min))
12597 (widen)
12598 (if (and (looking-at "[ \t]*\n")
12599 (equal (char-before) ?\n))
12600 (delete-region (1- (point)) (point-at-eol)))
12601 ts))))))
12603 (defvar org-log-note-marker (make-marker))
12604 (defvar org-log-note-purpose nil)
12605 (defvar org-log-note-state nil)
12606 (defvar org-log-note-previous-state nil)
12607 (defvar org-log-note-how nil)
12608 (defvar org-log-note-extra nil)
12609 (defvar org-log-note-window-configuration nil)
12610 (defvar org-log-note-return-to (make-marker))
12611 (defvar org-log-note-effective-time nil
12612 "Remembered current time so that dynamically scoped
12613 `org-extend-today-until' affects tha timestamps in state change
12614 log")
12616 (defvar org-log-post-message nil
12617 "Message to be displayed after a log note has been stored.
12618 The auto-repeater uses this.")
12620 (defun org-add-note ()
12621 "Add a note to the current entry.
12622 This is done in the same way as adding a state change note."
12623 (interactive)
12624 (org-add-log-setup 'note nil nil 'findpos nil))
12626 (defvar org-property-end-re)
12627 (defun org-add-log-setup (&optional purpose state prev-state
12628 findpos how extra)
12629 "Set up the post command hook to take a note.
12630 If this is about to TODO state change, the new state is expected in STATE.
12631 When FINDPOS is non-nil, find the correct position for the note in
12632 the current entry. If not, assume that it can be inserted at point.
12633 HOW is an indicator what kind of note should be created.
12634 EXTRA is additional text that will be inserted into the notes buffer."
12635 (let* ((org-log-into-drawer (org-log-into-drawer))
12636 (drawer (cond ((stringp org-log-into-drawer)
12637 org-log-into-drawer)
12638 (org-log-into-drawer "LOGBOOK"))))
12639 (save-restriction
12640 (save-excursion
12641 (when findpos
12642 (org-back-to-heading t)
12643 (narrow-to-region (point) (save-excursion
12644 (outline-next-heading) (point)))
12645 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12646 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12647 "[^\r\n]*\\)?"))
12648 (goto-char (match-end 0))
12649 (cond
12650 (drawer
12651 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12652 nil t)
12653 (progn
12654 (goto-char (match-end 0))
12655 (or org-log-states-order-reversed
12656 (and (re-search-forward org-property-end-re nil t)
12657 (goto-char (1- (match-beginning 0))))))
12658 (insert "\n:" drawer ":\n:END:")
12659 (beginning-of-line 0)
12660 (org-indent-line)
12661 (beginning-of-line 2)
12662 (org-indent-line)
12663 (end-of-line 0)))
12664 ((and org-log-state-notes-insert-after-drawers
12665 (save-excursion
12666 (forward-line) (looking-at org-drawer-regexp)))
12667 (forward-line)
12668 (while (looking-at org-drawer-regexp)
12669 (goto-char (match-end 0))
12670 (re-search-forward org-property-end-re (point-max) t)
12671 (forward-line))
12672 (forward-line -1)))
12673 (unless org-log-states-order-reversed
12674 (and (= (char-after) ?\n) (forward-char 1))
12675 (org-skip-over-state-notes)
12676 (skip-chars-backward " \t\n\r")))
12677 (move-marker org-log-note-marker (point))
12678 (setq org-log-note-purpose purpose
12679 org-log-note-state state
12680 org-log-note-previous-state prev-state
12681 org-log-note-how how
12682 org-log-note-extra extra
12683 org-log-note-effective-time (org-current-effective-time))
12684 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12686 (defun org-skip-over-state-notes ()
12687 "Skip past the list of State notes in an entry."
12688 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12689 (when (ignore-errors (goto-char (org-in-item-p)))
12690 (let* ((struct (org-list-struct))
12691 (prevs (org-list-prevs-alist struct)))
12692 (while (looking-at "[ \t]*- State")
12693 (goto-char (or (org-list-get-next-item (point) struct prevs)
12694 (org-list-get-item-end (point) struct)))))))
12696 (defun org-add-log-note (&optional purpose)
12697 "Pop up a window for taking a note, and add this note later at point."
12698 (remove-hook 'post-command-hook 'org-add-log-note)
12699 (setq org-log-note-window-configuration (current-window-configuration))
12700 (delete-other-windows)
12701 (move-marker org-log-note-return-to (point))
12702 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12703 (goto-char org-log-note-marker)
12704 (org-switch-to-buffer-other-window "*Org Note*")
12705 (erase-buffer)
12706 (if (memq org-log-note-how '(time state))
12707 (let (current-prefix-arg) (org-store-log-note))
12708 (let ((org-inhibit-startup t)) (org-mode))
12709 (insert (format "# Insert note for %s.
12710 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12711 (cond
12712 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12713 ((eq org-log-note-purpose 'done) "closed todo item")
12714 ((eq org-log-note-purpose 'state)
12715 (format "state change from \"%s\" to \"%s\""
12716 (or org-log-note-previous-state "")
12717 (or org-log-note-state "")))
12718 ((eq org-log-note-purpose 'reschedule)
12719 "rescheduling")
12720 ((eq org-log-note-purpose 'delschedule)
12721 "no longer scheduled")
12722 ((eq org-log-note-purpose 'redeadline)
12723 "changing deadline")
12724 ((eq org-log-note-purpose 'deldeadline)
12725 "removing deadline")
12726 ((eq org-log-note-purpose 'refile)
12727 "refiling")
12728 ((eq org-log-note-purpose 'note)
12729 "this entry")
12730 (t (error "This should not happen")))))
12731 (if org-log-note-extra (insert org-log-note-extra))
12732 (org-set-local 'org-finish-function 'org-store-log-note)
12733 (run-hooks 'org-log-buffer-setup-hook)))
12735 (defvar org-note-abort nil) ; dynamically scoped
12736 (defun org-store-log-note ()
12737 "Finish taking a log note, and insert it to where it belongs."
12738 (let ((txt (buffer-string)))
12739 (kill-buffer (current-buffer))
12740 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12741 lines ind bul)
12742 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12743 (setq txt (replace-match "" t t txt)))
12744 (if (string-match "\\s-+\\'" txt)
12745 (setq txt (replace-match "" t t txt)))
12746 (setq lines (org-split-string txt "\n"))
12747 (when (and note (string-match "\\S-" note))
12748 (setq note
12749 (org-replace-escapes
12750 note
12751 (list (cons "%u" (user-login-name))
12752 (cons "%U" user-full-name)
12753 (cons "%t" (format-time-string
12754 (org-time-stamp-format 'long 'inactive)
12755 org-log-note-effective-time))
12756 (cons "%T" (format-time-string
12757 (org-time-stamp-format 'long nil)
12758 org-log-note-effective-time))
12759 (cons "%d" (format-time-string
12760 (org-time-stamp-format nil 'inactive)
12761 org-log-note-effective-time))
12762 (cons "%D" (format-time-string
12763 (org-time-stamp-format nil nil)
12764 org-log-note-effective-time))
12765 (cons "%s" (if org-log-note-state
12766 (concat "\"" org-log-note-state "\"")
12767 ""))
12768 (cons "%S" (if org-log-note-previous-state
12769 (concat "\"" org-log-note-previous-state "\"")
12770 "\"\"")))))
12771 (if lines (setq note (concat note " \\\\")))
12772 (push note lines))
12773 (when (or current-prefix-arg org-note-abort)
12774 (when org-log-into-drawer
12775 (org-remove-empty-drawer-at
12776 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12777 org-log-note-marker))
12778 (setq lines nil))
12779 (when lines
12780 (with-current-buffer (marker-buffer org-log-note-marker)
12781 (save-excursion
12782 (goto-char org-log-note-marker)
12783 (move-marker org-log-note-marker nil)
12784 (end-of-line 1)
12785 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12786 (setq ind (save-excursion
12787 (if (ignore-errors (goto-char (org-in-item-p)))
12788 (let ((struct (org-list-struct)))
12789 (org-list-get-ind
12790 (org-list-get-top-point struct) struct))
12791 (skip-chars-backward " \r\t\n")
12792 (cond
12793 ((and (org-at-heading-p)
12794 org-adapt-indentation)
12795 (1+ (org-current-level)))
12796 ((org-at-heading-p) 0)
12797 (t (org-get-indentation))))))
12798 (setq bul (org-list-bullet-string "-"))
12799 (org-indent-line-to ind)
12800 (insert bul (pop lines))
12801 (let ((ind-body (+ (length bul) ind)))
12802 (while lines
12803 (insert "\n")
12804 (org-indent-line-to ind-body)
12805 (insert (pop lines))))
12806 (message "Note stored")
12807 (org-back-to-heading t)
12808 (org-cycle-hide-drawers 'children))))))
12809 (set-window-configuration org-log-note-window-configuration)
12810 (with-current-buffer (marker-buffer org-log-note-return-to)
12811 (goto-char org-log-note-return-to))
12812 (move-marker org-log-note-return-to nil)
12813 (and org-log-post-message (message "%s" org-log-post-message)))
12815 (defun org-remove-empty-drawer-at (drawer pos)
12816 "Remove an empty drawer DRAWER at position POS.
12817 POS may also be a marker."
12818 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12819 (save-excursion
12820 (save-restriction
12821 (widen)
12822 (goto-char pos)
12823 (if (org-in-regexp
12824 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12825 (replace-match ""))))))
12827 (defvar org-ts-type nil)
12828 (defun org-sparse-tree (&optional arg type)
12829 "Create a sparse tree, prompt for the details.
12830 This command can create sparse trees. You first need to select the type
12831 of match used to create the tree:
12833 t Show all TODO entries.
12834 T Show entries with a specific TODO keyword.
12835 m Show entries selected by a tags/property match.
12836 p Enter a property name and its value (both with completion on existing
12837 names/values) and show entries with that property.
12838 r Show entries matching a regular expression (`/' can be used as well).
12839 b Show deadlines and scheduled items before a date.
12840 a Show deadlines and scheduled items after a date.
12841 d Show deadlines due within `org-deadline-warning-days'.
12842 D Show deadlines and scheduled items between a date range."
12843 (interactive "P")
12844 (let (ans kwd value ts-type)
12845 (setq type (or type org-sparse-tree-default-date-type))
12846 (setq org-ts-type type)
12847 (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"
12848 (cond ((eq type 'all) "all timestamps")
12849 ((eq type 'scheduled) "only scheduled")
12850 ((eq type 'deadline) "only deadline")
12851 ((eq type 'active) "only active timestamps")
12852 ((eq type 'inactive) "only inactive timestamps")
12853 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12854 (t "scheduled/deadline")))
12855 (setq ans (read-char-exclusive))
12856 (cond
12857 ((equal ans ?c)
12858 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12859 ((equal ans ?d)
12860 (call-interactively 'org-check-deadlines))
12861 ((equal ans ?b)
12862 (call-interactively 'org-check-before-date))
12863 ((equal ans ?a)
12864 (call-interactively 'org-check-after-date))
12865 ((equal ans ?D)
12866 (call-interactively 'org-check-dates-range))
12867 ((equal ans ?t)
12868 (call-interactively 'org-show-todo-tree))
12869 ((equal ans ?T)
12870 (org-show-todo-tree '(4)))
12871 ((member ans '(?T ?m))
12872 (call-interactively 'org-match-sparse-tree))
12873 ((member ans '(?p ?P))
12874 (setq kwd (org-icompleting-read "Property: "
12875 (mapcar 'list (org-buffer-property-keys))))
12876 (setq value (org-icompleting-read "Value: "
12877 (mapcar 'list (org-property-values kwd))))
12878 (unless (string-match "\\`{.*}\\'" value)
12879 (setq value (concat "\"" value "\"")))
12880 (org-match-sparse-tree arg (concat kwd "=" value)))
12881 ((member ans '(?r ?R ?/))
12882 (call-interactively 'org-occur))
12883 (t (error "No such sparse tree command \"%c\"" ans)))))
12885 (defvar org-occur-highlights nil
12886 "List of overlays used for occur matches.")
12887 (make-variable-buffer-local 'org-occur-highlights)
12888 (defvar org-occur-parameters nil
12889 "Parameters of the active org-occur calls.
12890 This is a list, each call to org-occur pushes as cons cell,
12891 containing the regular expression and the callback, onto the list.
12892 The list can contain several entries if `org-occur' has been called
12893 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12894 will only contain one set of parameters. When the highlights are
12895 removed (for example with `C-c C-c', or with the next edit (depending
12896 on `org-remove-highlights-with-change'), this variable is emptied
12897 as well.")
12898 (make-variable-buffer-local 'org-occur-parameters)
12900 (defun org-occur (regexp &optional keep-previous callback)
12901 "Make a compact tree which shows all matches of REGEXP.
12902 The tree will show the lines where the regexp matches, and all higher
12903 headlines above the match. It will also show the heading after the match,
12904 to make sure editing the matching entry is easy.
12905 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12906 call to `org-occur' will be kept, to allow stacking of calls to this
12907 command.
12908 If CALLBACK is non-nil, it is a function which is called to confirm
12909 that the match should indeed be shown."
12910 (interactive "sRegexp: \nP")
12911 (when (equal regexp "")
12912 (error "Regexp cannot be empty"))
12913 (unless keep-previous
12914 (org-remove-occur-highlights nil nil t))
12915 (push (cons regexp callback) org-occur-parameters)
12916 (let ((cnt 0))
12917 (save-excursion
12918 (goto-char (point-min))
12919 (if (or (not keep-previous) ; do not want to keep
12920 (not org-occur-highlights)) ; no previous matches
12921 ;; hide everything
12922 (org-overview))
12923 (while (re-search-forward regexp nil t)
12924 (when (or (not callback)
12925 (save-match-data (funcall callback)))
12926 (setq cnt (1+ cnt))
12927 (when org-highlight-sparse-tree-matches
12928 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12929 (org-show-context 'occur-tree))))
12930 (when org-remove-highlights-with-change
12931 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12932 nil 'local))
12933 (unless org-sparse-tree-open-archived-trees
12934 (org-hide-archived-subtrees (point-min) (point-max)))
12935 (run-hooks 'org-occur-hook)
12936 (if (org-called-interactively-p 'interactive)
12937 (message "%d match(es) for regexp %s" cnt regexp))
12938 cnt))
12940 (defun org-occur-next-match (&optional n reset)
12941 "Function for `next-error-function' to find sparse tree matches.
12942 N is the number of matches to move, when negative move backwards.
12943 RESET is entirely ignored - this function always goes back to the
12944 starting point when no match is found."
12945 (let* ((limit (if (< n 0) (point-min) (point-max)))
12946 (search-func (if (< n 0)
12947 'previous-single-char-property-change
12948 'next-single-char-property-change))
12949 (n (abs n))
12950 (pos (point))
12952 (catch 'exit
12953 (while (setq p1 (funcall search-func (point) 'org-type))
12954 (when (equal p1 limit)
12955 (goto-char pos)
12956 (error "No more matches"))
12957 (when (equal (get-char-property p1 'org-type) 'org-occur)
12958 (setq n (1- n))
12959 (when (= n 0)
12960 (goto-char p1)
12961 (throw 'exit (point))))
12962 (goto-char p1))
12963 (goto-char p1)
12964 (error "No more matches"))))
12966 (defun org-show-context (&optional key)
12967 "Make sure point and context are visible.
12968 How much context is shown depends upon the variables
12969 `org-show-hierarchy-above', `org-show-following-heading',
12970 `org-show-entry-below' and `org-show-siblings'."
12971 (let ((heading-p (org-at-heading-p t))
12972 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12973 (following-p (org-get-alist-option org-show-following-heading key))
12974 (entry-p (org-get-alist-option org-show-entry-below key))
12975 (siblings-p (org-get-alist-option org-show-siblings key)))
12976 (catch 'exit
12977 ;; Show heading or entry text
12978 (if (and heading-p (not entry-p))
12979 (org-flag-heading nil) ; only show the heading
12980 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12981 (org-show-hidden-entry))) ; show entire entry
12982 (when following-p
12983 ;; Show next sibling, or heading below text
12984 (save-excursion
12985 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12986 (org-flag-heading nil))))
12987 (when siblings-p (org-show-siblings))
12988 (when hierarchy-p
12989 ;; show all higher headings, possibly with siblings
12990 (save-excursion
12991 (while (and (condition-case nil
12992 (progn (org-up-heading-all 1) t)
12993 (error nil))
12994 (not (bobp)))
12995 (org-flag-heading nil)
12996 (when siblings-p (org-show-siblings))))))))
12998 (defvar org-reveal-start-hook nil
12999 "Hook run before revealing a location.")
13001 (defun org-reveal (&optional siblings)
13002 "Show current entry, hierarchy above it, and the following headline.
13003 This can be used to show a consistent set of context around locations
13004 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13005 not t for the search context.
13007 With optional argument SIBLINGS, on each level of the hierarchy all
13008 siblings are shown. This repairs the tree structure to what it would
13009 look like when opened with hierarchical calls to `org-cycle'.
13010 With double optional argument \\[universal-argument] \\[universal-argument], \
13011 go to the parent and show the
13012 entire tree."
13013 (interactive "P")
13014 (run-hooks 'org-reveal-start-hook)
13015 (let ((org-show-hierarchy-above t)
13016 (org-show-following-heading t)
13017 (org-show-siblings (if siblings t org-show-siblings)))
13018 (org-show-context nil))
13019 (when (equal siblings '(16))
13020 (save-excursion
13021 (when (org-up-heading-safe)
13022 (org-show-subtree)
13023 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13025 (defun org-highlight-new-match (beg end)
13026 "Highlight from BEG to END and mark the highlight is an occur headline."
13027 (let ((ov (make-overlay beg end)))
13028 (overlay-put ov 'face 'secondary-selection)
13029 (overlay-put ov 'org-type 'org-occur)
13030 (push ov org-occur-highlights)))
13032 (defun org-remove-occur-highlights (&optional beg end noremove)
13033 "Remove the occur highlights from the buffer.
13034 BEG and END are ignored. If NOREMOVE is nil, remove this function
13035 from the `before-change-functions' in the current buffer."
13036 (interactive)
13037 (unless org-inhibit-highlight-removal
13038 (mapc 'delete-overlay org-occur-highlights)
13039 (setq org-occur-highlights nil)
13040 (setq org-occur-parameters nil)
13041 (unless noremove
13042 (remove-hook 'before-change-functions
13043 'org-remove-occur-highlights 'local))))
13045 ;;;; Priorities
13047 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13048 "Regular expression matching the priority indicator.")
13050 (defvar org-remove-priority-next-time nil)
13052 (defun org-priority-up ()
13053 "Increase the priority of the current item."
13054 (interactive)
13055 (org-priority 'up))
13057 (defun org-priority-down ()
13058 "Decrease the priority of the current item."
13059 (interactive)
13060 (org-priority 'down))
13062 (defun org-priority (&optional action show)
13063 "Change the priority of an item.
13064 ACTION can be `set', `up', `down', or a character."
13065 (interactive "P")
13066 (if (equal action '(4))
13067 (org-show-priority)
13068 (unless org-enable-priority-commands
13069 (error "Priority commands are disabled"))
13070 (setq action (or action 'set))
13071 (let (current new news have remove)
13072 (save-excursion
13073 (org-back-to-heading t)
13074 (if (looking-at org-priority-regexp)
13075 (setq current (string-to-char (match-string 2))
13076 have t))
13077 (cond
13078 ((eq action 'remove)
13079 (setq remove t new ?\ ))
13080 ((or (eq action 'set)
13081 (if (featurep 'xemacs) (characterp action) (integerp action)))
13082 (if (not (eq action 'set))
13083 (setq new action)
13084 (message "Priority %c-%c, SPC to remove: "
13085 org-highest-priority org-lowest-priority)
13086 (save-match-data
13087 (setq new (read-char-exclusive))))
13088 (if (and (= (upcase org-highest-priority) org-highest-priority)
13089 (= (upcase org-lowest-priority) org-lowest-priority))
13090 (setq new (upcase new)))
13091 (cond ((equal new ?\ ) (setq remove t))
13092 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13093 (error "Priority must be between `%c' and `%c'"
13094 org-highest-priority org-lowest-priority))))
13095 ((eq action 'up)
13096 (setq new (if have
13097 (1- current) ; normal cycling
13098 ;; last priority was empty
13099 (if (eq last-command this-command)
13100 org-lowest-priority ; wrap around empty to lowest
13101 ;; default
13102 (if org-priority-start-cycle-with-default
13103 org-default-priority
13104 (1- org-default-priority))))))
13105 ((eq action 'down)
13106 (setq new (if have
13107 (1+ current) ; normal cycling
13108 ;; last priority was empty
13109 (if (eq last-command this-command)
13110 org-highest-priority ; wrap around empty to highest
13111 ;; default
13112 (if org-priority-start-cycle-with-default
13113 org-default-priority
13114 (1+ org-default-priority))))))
13115 (t (error "Invalid action")))
13116 (if (or (< (upcase new) org-highest-priority)
13117 (> (upcase new) org-lowest-priority))
13118 (if (and (memq action '(up down))
13119 (not have) (not (eq last-command this-command)))
13120 ;; `new' is from default priority
13121 (error
13122 "The default can not be set, see `org-default-priority' why")
13123 ;; normal cycling: `new' is beyond highest/lowest priority
13124 ;; and is wrapped around to the empty priority
13125 (setq remove t)))
13126 (setq news (format "%c" new))
13127 (if have
13128 (if remove
13129 (replace-match "" t t nil 1)
13130 (replace-match news t t nil 2))
13131 (if remove
13132 (error "No priority cookie found in line")
13133 (let ((case-fold-search nil))
13134 (looking-at org-todo-line-regexp))
13135 (if (match-end 2)
13136 (progn
13137 (goto-char (match-end 2))
13138 (insert " [#" news "]"))
13139 (goto-char (match-beginning 3))
13140 (insert "[#" news "] "))))
13141 (org-preserve-lc (org-set-tags nil 'align)))
13142 (if remove
13143 (message "Priority removed")
13144 (message "Priority of current item set to %s" news)))))
13146 (defun org-show-priority ()
13147 "Show the priority of the current item.
13148 This priority is composed of the main priority given with the [#A] cookies,
13149 and by additional input from the age of a schedules or deadline entry."
13150 (interactive)
13151 (let ((pri (if (eq major-mode 'org-agenda-mode)
13152 (org-get-at-bol 'priority)
13153 (save-excursion
13154 (save-match-data
13155 (beginning-of-line)
13156 (and (looking-at org-heading-regexp)
13157 (org-get-priority (match-string 0))))))))
13158 (message "Priority is %d" (if pri pri -1000))))
13160 (defun org-get-priority (s)
13161 "Find priority cookie and return priority."
13162 (if (functionp org-get-priority-function)
13163 (funcall org-get-priority-function)
13164 (save-match-data
13165 (if (not (string-match org-priority-regexp s))
13166 (* 1000 (- org-lowest-priority org-default-priority))
13167 (* 1000 (- org-lowest-priority
13168 (string-to-char (match-string 2 s))))))))
13170 ;;;; Tags
13172 (defvar org-agenda-archives-mode)
13173 (defvar org-map-continue-from nil
13174 "Position from where mapping should continue.
13175 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13177 (defvar org-scanner-tags nil
13178 "The current tag list while the tags scanner is running.")
13179 (defvar org-trust-scanner-tags nil
13180 "Should `org-get-tags-at' use the tags for the scanner.
13181 This is for internal dynamical scoping only.
13182 When this is non-nil, the function `org-get-tags-at' will return the value
13183 of `org-scanner-tags' instead of building the list by itself. This
13184 can lead to large speed-ups when the tags scanner is used in a file with
13185 many entries, and when the list of tags is retrieved, for example to
13186 obtain a list of properties. Building the tags list for each entry in such
13187 a file becomes an N^2 operation - but with this variable set, it scales
13188 as N.")
13190 (defun org-scan-tags (action matcher todo-only &optional start-level)
13191 "Scan headline tags with inheritance and produce output ACTION.
13193 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13194 or `agenda' to produce an entry list for an agenda view. It can also be
13195 a Lisp form or a function that should be called at each matched headline, in
13196 this case the return value is a list of all return values from these calls.
13198 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13199 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13200 only lines with a not-done TODO keyword are included in the output.
13201 This should be the same variable that was scoped into
13202 and set by `org-make-tags-matcher' when it constructed MATCHER.
13204 START-LEVEL can be a string with asterisks, reducing the scope to
13205 headlines matching this string."
13206 (require 'org-agenda)
13207 (let* ((re (concat "^"
13208 (if start-level
13209 ;; Get the correct level to match
13210 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13211 org-outline-regexp)
13212 " *\\(\\<\\("
13213 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13214 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13215 (props (list 'face 'default
13216 'done-face 'org-agenda-done
13217 'undone-face 'default
13218 'mouse-face 'highlight
13219 'org-not-done-regexp org-not-done-regexp
13220 'org-todo-regexp org-todo-regexp
13221 'org-complex-heading-regexp org-complex-heading-regexp
13222 'help-echo
13223 (format "mouse-2 or RET jump to org file %s"
13224 (abbreviate-file-name
13225 (or (buffer-file-name (buffer-base-buffer))
13226 (buffer-name (buffer-base-buffer)))))))
13227 (case-fold-search nil)
13228 (org-map-continue-from nil)
13229 lspos tags tags-list
13230 (tags-alist (list (cons 0 org-file-tags)))
13231 (llast 0) rtn rtn1 level category i txt
13232 todo marker entry priority)
13233 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13234 (setq action (list 'lambda nil action)))
13235 (save-excursion
13236 (goto-char (point-min))
13237 (when (eq action 'sparse-tree)
13238 (org-overview)
13239 (org-remove-occur-highlights))
13240 (while (re-search-forward re nil t)
13241 (setq org-map-continue-from nil)
13242 (catch :skip
13243 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13244 tags (if (match-end 4) (org-match-string-no-properties 4)))
13245 (goto-char (setq lspos (match-beginning 0)))
13246 (setq level (org-reduced-level (org-outline-level))
13247 category (org-get-category))
13248 (setq i llast llast level)
13249 ;; remove tag lists from same and sublevels
13250 (while (>= i level)
13251 (when (setq entry (assoc i tags-alist))
13252 (setq tags-alist (delete entry tags-alist)))
13253 (setq i (1- i)))
13254 ;; add the next tags
13255 (when tags
13256 (setq tags (org-split-string tags ":")
13257 tags-alist
13258 (cons (cons level tags) tags-alist)))
13259 ;; compile tags for current headline
13260 (setq tags-list
13261 (if org-use-tag-inheritance
13262 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13263 tags)
13264 org-scanner-tags tags-list)
13265 (when org-use-tag-inheritance
13266 (setcdr (car tags-alist)
13267 (mapcar (lambda (x)
13268 (setq x (copy-sequence x))
13269 (org-add-prop-inherited x))
13270 (cdar tags-alist))))
13271 (when (and tags org-use-tag-inheritance
13272 (or (not (eq t org-use-tag-inheritance))
13273 org-tags-exclude-from-inheritance))
13274 ;; selective inheritance, remove uninherited ones
13275 (setcdr (car tags-alist)
13276 (org-remove-uninherited-tags (cdar tags-alist))))
13277 (when (and
13279 ;; eval matcher only when the todo condition is OK
13280 (and (or (not todo-only) (member todo org-not-done-keywords))
13281 (let ((case-fold-search t) (org-trust-scanner-tags t))
13282 (eval matcher)))
13284 ;; Call the skipper, but return t if it does not skip,
13285 ;; so that the `and' form continues evaluating
13286 (progn
13287 (unless (eq action 'sparse-tree) (org-agenda-skip))
13290 ;; Check if timestamps are deselecting this entry
13291 (or (not todo-only)
13292 (and (member todo org-not-done-keywords)
13293 (or (not org-agenda-tags-todo-honor-ignore-options)
13294 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13296 ;; Extra check for the archive tag
13297 ;; FIXME: Does the skipper already do this????
13299 (not (member org-archive-tag tags-list))
13300 ;; we have an archive tag, should we use this anyway?
13301 (or (not org-agenda-skip-archived-trees)
13302 (and (eq action 'agenda) org-agenda-archives-mode))))
13304 ;; select this headline
13305 (cond
13306 ((eq action 'sparse-tree)
13307 (and org-highlight-sparse-tree-matches
13308 (org-get-heading) (match-end 0)
13309 (org-highlight-new-match
13310 (match-beginning 1) (match-end 1)))
13311 (org-show-context 'tags-tree))
13312 ((eq action 'agenda)
13313 (setq txt (org-agenda-format-item
13315 (concat
13316 (if (eq org-tags-match-list-sublevels 'indented)
13317 (make-string (1- level) ?.) "")
13318 (org-get-heading))
13319 level category
13320 tags-list)
13321 priority (org-get-priority txt))
13322 (goto-char lspos)
13323 (setq marker (org-agenda-new-marker))
13324 (org-add-props txt props
13325 'org-marker marker 'org-hd-marker marker 'org-category category
13326 'todo-state todo
13327 'priority priority 'type "tagsmatch")
13328 (push txt rtn))
13329 ((functionp action)
13330 (setq org-map-continue-from nil)
13331 (save-excursion
13332 (setq rtn1 (funcall action))
13333 (push rtn1 rtn)))
13334 (t (error "Invalid action")))
13336 ;; if we are to skip sublevels, jump to end of subtree
13337 (unless org-tags-match-list-sublevels
13338 (org-end-of-subtree t)
13339 (backward-char 1))))
13340 ;; Get the correct position from where to continue
13341 (if org-map-continue-from
13342 (goto-char org-map-continue-from)
13343 (and (= (point) lspos) (end-of-line 1)))))
13344 (when (and (eq action 'sparse-tree)
13345 (not org-sparse-tree-open-archived-trees))
13346 (org-hide-archived-subtrees (point-min) (point-max)))
13347 (nreverse rtn)))
13349 (defun org-remove-uninherited-tags (tags)
13350 "Remove all tags that are not inherited from the list TAGS."
13351 (cond
13352 ((eq org-use-tag-inheritance t)
13353 (if org-tags-exclude-from-inheritance
13354 (org-delete-all org-tags-exclude-from-inheritance tags)
13355 tags))
13356 ((not org-use-tag-inheritance) nil)
13357 ((stringp org-use-tag-inheritance)
13358 (delq nil (mapcar
13359 (lambda (x)
13360 (if (and (string-match org-use-tag-inheritance x)
13361 (not (member x org-tags-exclude-from-inheritance)))
13362 x nil))
13363 tags)))
13364 ((listp org-use-tag-inheritance)
13365 (delq nil (mapcar
13366 (lambda (x)
13367 (if (member x org-use-tag-inheritance) x nil))
13368 tags)))))
13370 (defun org-match-sparse-tree (&optional todo-only match)
13371 "Create a sparse tree according to tags string MATCH.
13372 MATCH can contain positive and negative selection of tags, like
13373 \"+WORK+URGENT-WITHBOSS\".
13374 If optional argument TODO-ONLY is non-nil, only select lines that are
13375 also TODO lines."
13376 (interactive "P")
13377 (org-agenda-prepare-buffers (list (current-buffer)))
13378 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13380 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13382 (defvar org-cached-props nil)
13383 (defun org-cached-entry-get (pom property)
13384 (if (or (eq t org-use-property-inheritance)
13385 (and (stringp org-use-property-inheritance)
13386 (string-match org-use-property-inheritance property))
13387 (and (listp org-use-property-inheritance)
13388 (member property org-use-property-inheritance)))
13389 ;; Caching is not possible, check it directly
13390 (org-entry-get pom property 'inherit)
13391 ;; Get all properties, so that we can do complicated checks easily
13392 (cdr (assoc property (or org-cached-props
13393 (setq org-cached-props
13394 (org-entry-properties pom)))))))
13396 (defun org-global-tags-completion-table (&optional files)
13397 "Return the list of all tags in all agenda buffer/files.
13398 Optional FILES argument is a list of files which can be used
13399 instead of the agenda files."
13400 (save-excursion
13401 (org-uniquify
13402 (delq nil
13403 (apply 'append
13404 (mapcar
13405 (lambda (file)
13406 (set-buffer (find-file-noselect file))
13407 (append (org-get-buffer-tags)
13408 (mapcar (lambda (x) (if (stringp (car-safe x))
13409 (list (car-safe x)) nil))
13410 org-tag-alist)))
13411 (if (and files (car files))
13412 files
13413 (org-agenda-files))))))))
13415 (defun org-make-tags-matcher (match)
13416 "Create the TAGS/TODO matcher form for the selection string MATCH.
13418 The variable `todo-only' is scoped dynamically into this function.
13419 It will be set to t if the matcher restricts matching to TODO entries,
13420 otherwise will not be touched.
13422 Returns a cons of the selection string MATCH and the constructed
13423 lisp form implementing the matcher. The matcher is to be evaluated
13424 at an Org entry, with point on the headline, and returns t if the
13425 entry matches the selection string MATCH. The returned lisp form
13426 references two variables with information about the entry, which
13427 must be bound around the form's evaluation: todo, the TODO keyword
13428 at the entry (or nil of none); and tags-list, the list of all tags
13429 at the entry including inherited ones. Additionally, the category
13430 of the entry (if any) must be specified as the text property
13431 'org-category on the headline.
13433 See also `org-scan-tags'.
13435 (declare (special todo-only))
13436 (unless (boundp 'todo-only)
13437 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13438 (unless match
13439 ;; Get a new match request, with completion
13440 (let ((org-last-tags-completion-table
13441 (org-global-tags-completion-table)))
13442 (setq match (org-completing-read-no-i
13443 "Match: " 'org-tags-completion-function nil nil nil
13444 'org-tags-history))))
13446 ;; Parse the string and create a lisp form
13447 (let ((match0 match)
13448 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13449 minus tag mm
13450 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13451 orterms term orlist re-p str-p level-p level-op time-p
13452 prop-p pn pv po gv rest)
13453 (if (string-match "/+" match)
13454 ;; match contains also a todo-matching request
13455 (progn
13456 (setq tagsmatch (substring match 0 (match-beginning 0))
13457 todomatch (substring match (match-end 0)))
13458 (if (string-match "^!" todomatch)
13459 (setq todo-only t todomatch (substring todomatch 1)))
13460 (if (string-match "^\\s-*$" todomatch)
13461 (setq todomatch nil)))
13462 ;; only matching tags
13463 (setq tagsmatch match todomatch nil))
13465 ;; Make the tags matcher
13466 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13467 (setq tagsmatcher t)
13468 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13469 (while (setq term (pop orterms))
13470 (while (and (equal (substring term -1) "\\") orterms)
13471 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13472 (while (string-match re term)
13473 (setq rest (substring term (match-end 0))
13474 minus (and (match-end 1)
13475 (equal (match-string 1 term) "-"))
13476 tag (save-match-data (replace-regexp-in-string
13477 "\\\\-" "-"
13478 (match-string 2 term)))
13479 re-p (equal (string-to-char tag) ?{)
13480 level-p (match-end 4)
13481 prop-p (match-end 5)
13482 mm (cond
13483 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13484 (level-p
13485 (setq level-op (org-op-to-function (match-string 3 term)))
13486 `(,level-op level ,(string-to-number
13487 (match-string 4 term))))
13488 (prop-p
13489 (setq pn (match-string 5 term)
13490 po (match-string 6 term)
13491 pv (match-string 7 term)
13492 re-p (equal (string-to-char pv) ?{)
13493 str-p (equal (string-to-char pv) ?\")
13494 time-p (save-match-data
13495 (string-match "^\"[[<].*[]>]\"$" pv))
13496 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13497 (if time-p (setq pv (org-matcher-time pv)))
13498 (setq po (org-op-to-function po (if time-p 'time str-p)))
13499 (cond
13500 ((equal pn "CATEGORY")
13501 (setq gv '(get-text-property (point) 'org-category)))
13502 ((equal pn "TODO")
13503 (setq gv 'todo))
13505 (setq gv `(org-cached-entry-get nil ,pn))))
13506 (if re-p
13507 (if (eq po 'org<>)
13508 `(not (string-match ,pv (or ,gv "")))
13509 `(string-match ,pv (or ,gv "")))
13510 (if str-p
13511 `(,po (or ,gv "") ,pv)
13512 `(,po (string-to-number (or ,gv ""))
13513 ,(string-to-number pv) ))))
13514 (t `(member ,tag tags-list)))
13515 mm (if minus (list 'not mm) mm)
13516 term rest)
13517 (push mm tagsmatcher))
13518 (push (if (> (length tagsmatcher) 1)
13519 (cons 'and tagsmatcher)
13520 (car tagsmatcher))
13521 orlist)
13522 (setq tagsmatcher nil))
13523 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13524 (setq tagsmatcher
13525 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13526 ;; Make the todo matcher
13527 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13528 (setq todomatcher t)
13529 (setq orterms (org-split-string todomatch "|") orlist nil)
13530 (while (setq term (pop orterms))
13531 (while (string-match re term)
13532 (setq minus (and (match-end 1)
13533 (equal (match-string 1 term) "-"))
13534 kwd (match-string 2 term)
13535 re-p (equal (string-to-char kwd) ?{)
13536 term (substring term (match-end 0))
13537 mm (if re-p
13538 `(string-match ,(substring kwd 1 -1) todo)
13539 (list 'equal 'todo kwd))
13540 mm (if minus (list 'not mm) mm))
13541 (push mm todomatcher))
13542 (push (if (> (length todomatcher) 1)
13543 (cons 'and todomatcher)
13544 (car todomatcher))
13545 orlist)
13546 (setq todomatcher nil))
13547 (setq todomatcher (if (> (length orlist) 1)
13548 (cons 'or orlist) (car orlist))))
13550 ;; Return the string and lisp forms of the matcher
13551 (setq matcher (if todomatcher
13552 (list 'and tagsmatcher todomatcher)
13553 tagsmatcher))
13554 (when todo-only
13555 (setq matcher (list 'and '(member todo org-not-done-keywords)
13556 matcher)))
13557 (cons match0 matcher)))
13559 (defun org-op-to-function (op &optional stringp)
13560 "Turn an operator into the appropriate function."
13561 (setq op
13562 (cond
13563 ((equal op "<" ) '(< string< org-time<))
13564 ((equal op ">" ) '(> org-string> org-time>))
13565 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13566 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13567 ((member op '("=" "==")) '(= string= org-time=))
13568 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13569 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13571 (defun org<> (a b) (not (= a b)))
13572 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13573 (defun org-string>= (a b) (not (string< a b)))
13574 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13575 (defun org-string<> (a b) (not (string= a b)))
13576 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13577 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13578 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13579 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13580 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13581 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13582 (defun org-2ft (s)
13583 "Convert S to a floating point time.
13584 If S is already a number, just return it. If it is a string, parse
13585 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13586 (cond
13587 ((numberp s) s)
13588 ((stringp s)
13589 (condition-case nil
13590 (float-time (apply 'encode-time (org-parse-time-string s)))
13591 (error 0.)))
13592 (t 0.)))
13594 (defun org-time-today ()
13595 "Time in seconds today at 0:00.
13596 Returns the float number of seconds since the beginning of the
13597 epoch to the beginning of today (00:00)."
13598 (float-time (apply 'encode-time
13599 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13601 (defun org-matcher-time (s)
13602 "Interpret a time comparison value."
13603 (save-match-data
13604 (cond
13605 ((string= s "<now>") (float-time))
13606 ((string= s "<today>") (org-time-today))
13607 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13608 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13609 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13610 (+ (org-time-today)
13611 (* (string-to-number (match-string 1 s))
13612 (cdr (assoc (match-string 2 s)
13613 '(("d" . 86400.0) ("w" . 604800.0)
13614 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13615 (t (org-2ft s)))))
13617 (defun org-match-any-p (re list)
13618 "Does re match any element of list?"
13619 (setq list (mapcar (lambda (x) (string-match re x)) list))
13620 (delq nil list))
13622 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13623 (defvar org-tags-overlay (make-overlay 1 1))
13624 (org-detach-overlay org-tags-overlay)
13626 (defun org-get-local-tags-at (&optional pos)
13627 "Get a list of tags defined in the current headline."
13628 (org-get-tags-at pos 'local))
13630 (defun org-get-local-tags ()
13631 "Get a list of tags defined in the current headline."
13632 (org-get-tags-at nil 'local))
13634 (defun org-get-tags-at (&optional pos local)
13635 "Get a list of all headline tags applicable at POS.
13636 POS defaults to point. If tags are inherited, the list contains
13637 the targets in the same sequence as the headlines appear, i.e.
13638 the tags of the current headline come last.
13639 When LOCAL is non-nil, only return tags from the current headline,
13640 ignore inherited ones."
13641 (interactive)
13642 (if (and org-trust-scanner-tags
13643 (or (not pos) (equal pos (point)))
13644 (not local))
13645 org-scanner-tags
13646 (let (tags ltags lastpos parent)
13647 (save-excursion
13648 (save-restriction
13649 (widen)
13650 (goto-char (or pos (point)))
13651 (save-match-data
13652 (catch 'done
13653 (condition-case nil
13654 (progn
13655 (org-back-to-heading t)
13656 (while (not (equal lastpos (point)))
13657 (setq lastpos (point))
13658 (when (looking-at
13659 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13660 (setq ltags (org-split-string
13661 (org-match-string-no-properties 1) ":"))
13662 (when parent
13663 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13664 (setq tags (append
13665 (if parent
13666 (org-remove-uninherited-tags ltags)
13667 ltags)
13668 tags)))
13669 (or org-use-tag-inheritance (throw 'done t))
13670 (if local (throw 'done t))
13671 (or (org-up-heading-safe) (error nil))
13672 (setq parent t)))
13673 (error nil)))))
13674 (if local
13675 tags
13676 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13678 (defun org-add-prop-inherited (s)
13679 (add-text-properties 0 (length s) '(inherited t) s)
13682 (defun org-toggle-tag (tag &optional onoff)
13683 "Toggle the tag TAG for the current line.
13684 If ONOFF is `on' or `off', don't toggle but set to this state."
13685 (let (res current)
13686 (save-excursion
13687 (org-back-to-heading t)
13688 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13689 (point-at-eol) t)
13690 (progn
13691 (setq current (match-string 1))
13692 (replace-match ""))
13693 (setq current ""))
13694 (setq current (nreverse (org-split-string current ":")))
13695 (cond
13696 ((eq onoff 'on)
13697 (setq res t)
13698 (or (member tag current) (push tag current)))
13699 ((eq onoff 'off)
13700 (or (not (member tag current)) (setq current (delete tag current))))
13701 (t (if (member tag current)
13702 (setq current (delete tag current))
13703 (setq res t)
13704 (push tag current))))
13705 (end-of-line 1)
13706 (if current
13707 (progn
13708 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13709 (org-set-tags nil t))
13710 (delete-horizontal-space))
13711 (run-hooks 'org-after-tags-change-hook))
13712 res))
13714 (defun org-align-tags-here (to-col)
13715 ;; Assumes that this is a headline
13716 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13717 (beginning-of-line 1)
13718 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13719 (< pos (match-beginning 2)))
13720 (progn
13721 (setq tags-l (- (match-end 2) (match-beginning 2)))
13722 (goto-char (match-beginning 1))
13723 (insert " ")
13724 (delete-region (point) (1+ (match-beginning 2)))
13725 (setq ncol (max (current-column)
13726 (1+ col)
13727 (if (> to-col 0)
13728 to-col
13729 (- (abs to-col) tags-l))))
13730 (setq p (point))
13731 (insert (make-string (- ncol (current-column)) ?\ ))
13732 (setq ncol (current-column))
13733 (when indent-tabs-mode (tabify p (point-at-eol)))
13734 (org-move-to-column (min ncol col) t))
13735 (goto-char pos))))
13737 (defun org-set-tags-command (&optional arg just-align)
13738 "Call the set-tags command for the current entry."
13739 (interactive "P")
13740 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13741 (org-set-tags arg just-align)
13742 (save-excursion
13743 (org-back-to-heading t)
13744 (org-set-tags arg just-align))))
13746 (defun org-set-tags-to (data)
13747 "Set the tags of the current entry to DATA, replacing the current tags.
13748 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13749 If DATA is nil or the empty string, any tags will be removed."
13750 (interactive "sTags: ")
13751 (setq data
13752 (cond
13753 ((eq data nil) "")
13754 ((equal data "") "")
13755 ((stringp data)
13756 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13757 ":"))
13758 ((listp data)
13759 (concat ":" (mapconcat 'identity data ":") ":"))))
13760 (when data
13761 (save-excursion
13762 (org-back-to-heading t)
13763 (when (looking-at org-complex-heading-regexp)
13764 (if (match-end 5)
13765 (progn
13766 (goto-char (match-beginning 5))
13767 (insert data)
13768 (delete-region (point) (point-at-eol))
13769 (org-set-tags nil 'align))
13770 (goto-char (point-at-eol))
13771 (insert " " data)
13772 (org-set-tags nil 'align)))
13773 (beginning-of-line 1)
13774 (if (looking-at ".*?\\([ \t]+\\)$")
13775 (delete-region (match-beginning 1) (match-end 1))))))
13777 (defun org-align-all-tags ()
13778 "Align the tags i all headings."
13779 (interactive)
13780 (save-excursion
13781 (or (ignore-errors (org-back-to-heading t))
13782 (outline-next-heading))
13783 (if (org-at-heading-p)
13784 (org-set-tags t)
13785 (message "No headings"))))
13787 (defvar org-indent-indentation-per-level)
13788 (defun org-set-tags (&optional arg just-align)
13789 "Set the tags for the current headline.
13790 With prefix ARG, realign all tags in headings in the current buffer."
13791 (interactive "P")
13792 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13793 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13794 'region-start-level 'region))
13795 org-loop-over-headlines-in-active-region)
13796 (org-map-entries
13797 ;; We don't use ARG and JUST-ALIGN here these args are not
13798 ;; useful when looping over headlines
13799 `(org-set-tags)
13800 org-loop-over-headlines-in-active-region
13801 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13802 (let* ((re org-outline-regexp-bol)
13803 (current (unless arg (org-get-tags-string)))
13804 (col (current-column))
13805 (org-setting-tags t)
13806 table current-tags inherited-tags ; computed below when needed
13807 tags p0 c0 c1 rpl di tc level)
13808 (if arg
13809 (save-excursion
13810 (goto-char (point-min))
13811 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13812 (while (re-search-forward re nil t)
13813 (org-set-tags nil t)
13814 (end-of-line 1)))
13815 (message "All tags realigned to column %d" org-tags-column))
13816 (if just-align
13817 (setq tags current)
13818 ;; Get a new set of tags from the user
13819 (save-excursion
13820 (setq table (append org-tag-persistent-alist
13821 (or org-tag-alist (org-get-buffer-tags))
13822 (and
13823 org-complete-tags-always-offer-all-agenda-tags
13824 (org-global-tags-completion-table
13825 (org-agenda-files))))
13826 org-last-tags-completion-table table
13827 current-tags (org-split-string current ":")
13828 inherited-tags (nreverse
13829 (nthcdr (length current-tags)
13830 (nreverse (org-get-tags-at))))
13831 tags
13832 (if (or (eq t org-use-fast-tag-selection)
13833 (and org-use-fast-tag-selection
13834 (delq nil (mapcar 'cdr table))))
13835 (org-fast-tag-selection
13836 current-tags inherited-tags table
13837 (if org-fast-tag-selection-include-todo
13838 org-todo-key-alist))
13839 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13840 (org-trim
13841 (org-icompleting-read "Tags: "
13842 'org-tags-completion-function
13843 nil nil current 'org-tags-history))))))
13844 (while (string-match "[-+&]+" tags)
13845 ;; No boolean logic, just a list
13846 (setq tags (replace-match ":" t t tags))))
13848 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13850 (if org-tags-sort-function
13851 (setq tags (mapconcat 'identity
13852 (sort (org-split-string
13853 tags (org-re "[^[:alnum:]_@#%]+"))
13854 org-tags-sort-function) ":")))
13856 (if (string-match "\\`[\t ]*\\'" tags)
13857 (setq tags "")
13858 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13859 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13861 ;; Insert new tags at the correct column
13862 (beginning-of-line 1)
13863 (setq level (or (and (looking-at org-outline-regexp)
13864 (- (match-end 0) (point) 1))
13866 (cond
13867 ((and (equal current "") (equal tags "")))
13868 ((re-search-forward
13869 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13870 (point-at-eol) t)
13871 (if (equal tags "")
13872 (setq rpl "")
13873 (goto-char (match-beginning 0))
13874 (setq c0 (current-column)
13875 ;; compute offset for the case of org-indent-mode active
13876 di (if org-indent-mode
13877 (* (1- org-indent-indentation-per-level) (1- level))
13879 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13880 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13881 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13882 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13883 (replace-match rpl t t)
13884 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13885 tags)
13886 (t (error "Tags alignment failed")))
13887 (org-move-to-column col)
13888 (unless just-align
13889 (run-hooks 'org-after-tags-change-hook))))))
13891 (defun org-change-tag-in-region (beg end tag off)
13892 "Add or remove TAG for each entry in the region.
13893 This works in the agenda, and also in an org-mode buffer."
13894 (interactive
13895 (list (region-beginning) (region-end)
13896 (let ((org-last-tags-completion-table
13897 (if (derived-mode-p 'org-mode)
13898 (org-get-buffer-tags)
13899 (org-global-tags-completion-table))))
13900 (org-icompleting-read
13901 "Tag: " 'org-tags-completion-function nil nil nil
13902 'org-tags-history))
13903 (progn
13904 (message "[s]et or [r]emove? ")
13905 (equal (read-char-exclusive) ?r))))
13906 (if (fboundp 'deactivate-mark) (deactivate-mark))
13907 (let ((agendap (equal major-mode 'org-agenda-mode))
13908 l1 l2 m buf pos newhead (cnt 0))
13909 (goto-char end)
13910 (setq l2 (1- (org-current-line)))
13911 (goto-char beg)
13912 (setq l1 (org-current-line))
13913 (loop for l from l1 to l2 do
13914 (org-goto-line l)
13915 (setq m (get-text-property (point) 'org-hd-marker))
13916 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13917 (and agendap m))
13918 (setq buf (if agendap (marker-buffer m) (current-buffer))
13919 pos (if agendap m (point)))
13920 (with-current-buffer buf
13921 (save-excursion
13922 (save-restriction
13923 (goto-char pos)
13924 (setq cnt (1+ cnt))
13925 (org-toggle-tag tag (if off 'off 'on))
13926 (setq newhead (org-get-heading)))))
13927 (and agendap (org-agenda-change-all-lines newhead m))))
13928 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13930 (defun org-tags-completion-function (string predicate &optional flag)
13931 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13932 (confirm (lambda (x) (stringp (car x)))))
13933 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13934 (setq s1 (match-string 1 string)
13935 s2 (match-string 2 string))
13936 (setq s1 "" s2 string))
13937 (cond
13938 ((eq flag nil)
13939 ;; try completion
13940 (setq rtn (try-completion s2 ctable confirm))
13941 (if (stringp rtn)
13942 (setq rtn
13943 (concat s1 s2 (substring rtn (length s2))
13944 (if (and org-add-colon-after-tag-completion
13945 (assoc rtn ctable))
13946 ":" ""))))
13947 rtn)
13948 ((eq flag t)
13949 ;; all-completions
13950 (all-completions s2 ctable confirm)
13952 ((eq flag 'lambda)
13953 ;; exact match?
13954 (assoc s2 ctable)))
13957 (defun org-fast-tag-insert (kwd tags face &optional end)
13958 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13959 (insert (format "%-12s" (concat kwd ":"))
13960 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13961 (or end "")))
13963 (defun org-fast-tag-show-exit (flag)
13964 (save-excursion
13965 (org-goto-line 3)
13966 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13967 (replace-match ""))
13968 (when flag
13969 (end-of-line 1)
13970 (org-move-to-column (- (window-width) 19) t)
13971 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13973 (defun org-set-current-tags-overlay (current prefix)
13974 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13975 (if (featurep 'xemacs)
13976 (org-overlay-display org-tags-overlay (concat prefix s)
13977 'secondary-selection)
13978 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13979 (org-overlay-display org-tags-overlay (concat prefix s)))))
13981 (defvar org-last-tag-selection-key nil)
13982 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13983 "Fast tag selection with single keys.
13984 CURRENT is the current list of tags in the headline, INHERITED is the
13985 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13986 possibly with grouping information. TODO-TABLE is a similar table with
13987 TODO keywords, should these have keys assigned to them.
13988 If the keys are nil, a-z are automatically assigned.
13989 Returns the new tags string, or nil to not change the current settings."
13990 (let* ((fulltable (append table todo-table))
13991 (maxlen (apply 'max (mapcar
13992 (lambda (x)
13993 (if (stringp (car x)) (string-width (car x)) 0))
13994 fulltable)))
13995 (buf (current-buffer))
13996 (expert (eq org-fast-tag-selection-single-key 'expert))
13997 (buffer-tags nil)
13998 (fwidth (+ maxlen 3 1 3))
13999 (ncol (/ (- (window-width) 4) fwidth))
14000 (i-face 'org-done)
14001 (c-face 'org-todo)
14002 tg cnt e c char c1 c2 ntable tbl rtn
14003 ov-start ov-end ov-prefix
14004 (exit-after-next org-fast-tag-selection-single-key)
14005 (done-keywords org-done-keywords)
14006 groups ingroup)
14007 (save-excursion
14008 (beginning-of-line 1)
14009 (if (looking-at
14010 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14011 (setq ov-start (match-beginning 1)
14012 ov-end (match-end 1)
14013 ov-prefix "")
14014 (setq ov-start (1- (point-at-eol))
14015 ov-end (1+ ov-start))
14016 (skip-chars-forward "^\n\r")
14017 (setq ov-prefix
14018 (concat
14019 (buffer-substring (1- (point)) (point))
14020 (if (> (current-column) org-tags-column)
14022 (make-string (- org-tags-column (current-column)) ?\ ))))))
14023 (move-overlay org-tags-overlay ov-start ov-end)
14024 (save-window-excursion
14025 (if expert
14026 (set-buffer (get-buffer-create " *Org tags*"))
14027 (delete-other-windows)
14028 (split-window-vertically)
14029 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14030 (erase-buffer)
14031 (org-set-local 'org-done-keywords done-keywords)
14032 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14033 (org-fast-tag-insert "Current" current c-face "\n\n")
14034 (org-fast-tag-show-exit exit-after-next)
14035 (org-set-current-tags-overlay current ov-prefix)
14036 (setq tbl fulltable char ?a cnt 0)
14037 (while (setq e (pop tbl))
14038 (cond
14039 ((equal (car e) :startgroup)
14040 (push '() groups) (setq ingroup t)
14041 (when (not (= cnt 0))
14042 (setq cnt 0)
14043 (insert "\n"))
14044 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14045 ((equal (car e) :endgroup)
14046 (setq ingroup nil cnt 0)
14047 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14048 ((equal e '(:newline))
14049 (when (not (= cnt 0))
14050 (setq cnt 0)
14051 (insert "\n")
14052 (setq e (car tbl))
14053 (while (equal (car tbl) '(:newline))
14054 (insert "\n")
14055 (setq tbl (cdr tbl)))))
14057 (setq tg (copy-sequence (car e)) c2 nil)
14058 (if (cdr e)
14059 (setq c (cdr e))
14060 ;; automatically assign a character.
14061 (setq c1 (string-to-char
14062 (downcase (substring
14063 tg (if (= (string-to-char tg) ?@) 1 0)))))
14064 (if (or (rassoc c1 ntable) (rassoc c1 table))
14065 (while (or (rassoc char ntable) (rassoc char table))
14066 (setq char (1+ char)))
14067 (setq c2 c1))
14068 (setq c (or c2 char)))
14069 (if ingroup (push tg (car groups)))
14070 (setq tg (org-add-props tg nil 'face
14071 (cond
14072 ((not (assoc tg table))
14073 (org-get-todo-face tg))
14074 ((member tg current) c-face)
14075 ((member tg inherited) i-face))))
14076 (if (and (= cnt 0) (not ingroup)) (insert " "))
14077 (insert "[" c "] " tg (make-string
14078 (- fwidth 4 (length tg)) ?\ ))
14079 (push (cons tg c) ntable)
14080 (when (= (setq cnt (1+ cnt)) ncol)
14081 (insert "\n")
14082 (if ingroup (insert " "))
14083 (setq cnt 0)))))
14084 (setq ntable (nreverse ntable))
14085 (insert "\n")
14086 (goto-char (point-min))
14087 (if (not expert) (org-fit-window-to-buffer))
14088 (setq rtn
14089 (catch 'exit
14090 (while t
14091 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14092 (if (not groups) "no " "")
14093 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14094 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14095 (setq org-last-tag-selection-key c)
14096 (cond
14097 ((= c ?\r) (throw 'exit t))
14098 ((= c ?!)
14099 (setq groups (not groups))
14100 (goto-char (point-min))
14101 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14102 ((= c ?\C-c)
14103 (if (not expert)
14104 (org-fast-tag-show-exit
14105 (setq exit-after-next (not exit-after-next)))
14106 (setq expert nil)
14107 (delete-other-windows)
14108 (set-window-buffer (split-window-vertically) " *Org tags*")
14109 (org-switch-to-buffer-other-window " *Org tags*")
14110 (org-fit-window-to-buffer)))
14111 ((or (= c ?\C-g)
14112 (and (= c ?q) (not (rassoc c ntable))))
14113 (org-detach-overlay org-tags-overlay)
14114 (setq quit-flag t))
14115 ((= c ?\ )
14116 (setq current nil)
14117 (if exit-after-next (setq exit-after-next 'now)))
14118 ((= c ?\t)
14119 (condition-case nil
14120 (setq tg (org-icompleting-read
14121 "Tag: "
14122 (or buffer-tags
14123 (with-current-buffer buf
14124 (org-get-buffer-tags)))))
14125 (quit (setq tg "")))
14126 (when (string-match "\\S-" tg)
14127 (add-to-list 'buffer-tags (list tg))
14128 (if (member tg current)
14129 (setq current (delete tg current))
14130 (push tg current)))
14131 (if exit-after-next (setq exit-after-next 'now)))
14132 ((setq e (rassoc c todo-table) tg (car e))
14133 (with-current-buffer buf
14134 (save-excursion (org-todo tg)))
14135 (if exit-after-next (setq exit-after-next 'now)))
14136 ((setq e (rassoc c ntable) tg (car e))
14137 (if (member tg current)
14138 (setq current (delete tg current))
14139 (loop for g in groups do
14140 (if (member tg g)
14141 (mapc (lambda (x)
14142 (setq current (delete x current)))
14143 g)))
14144 (push tg current))
14145 (if exit-after-next (setq exit-after-next 'now))))
14147 ;; Create a sorted list
14148 (setq current
14149 (sort current
14150 (lambda (a b)
14151 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14152 (if (eq exit-after-next 'now) (throw 'exit t))
14153 (goto-char (point-min))
14154 (beginning-of-line 2)
14155 (delete-region (point) (point-at-eol))
14156 (org-fast-tag-insert "Current" current c-face)
14157 (org-set-current-tags-overlay current ov-prefix)
14158 (while (re-search-forward
14159 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14160 (setq tg (match-string 1))
14161 (add-text-properties
14162 (match-beginning 1) (match-end 1)
14163 (list 'face
14164 (cond
14165 ((member tg current) c-face)
14166 ((member tg inherited) i-face)
14167 (t (get-text-property (match-beginning 1) 'face))))))
14168 (goto-char (point-min)))))
14169 (org-detach-overlay org-tags-overlay)
14170 (if rtn
14171 (mapconcat 'identity current ":")
14172 nil))))
14174 (defun org-get-tags-string ()
14175 "Get the TAGS string in the current headline."
14176 (unless (org-at-heading-p t)
14177 (error "Not on a heading"))
14178 (save-excursion
14179 (beginning-of-line 1)
14180 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14181 (org-match-string-no-properties 1)
14182 "")))
14184 (defun org-get-tags ()
14185 "Get the list of tags specified in the current headline."
14186 (org-split-string (org-get-tags-string) ":"))
14188 (defun org-get-buffer-tags ()
14189 "Get a table of all tags used in the buffer, for completion."
14190 (let (tags)
14191 (save-excursion
14192 (goto-char (point-min))
14193 (while (re-search-forward
14194 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14195 (when (equal (char-after (point-at-bol 0)) ?*)
14196 (mapc (lambda (x) (add-to-list 'tags x))
14197 (org-split-string (org-match-string-no-properties 1) ":")))))
14198 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14199 (mapcar 'list tags)))
14201 ;;;; The mapping API
14203 (defun org-map-entries (func &optional match scope &rest skip)
14204 "Call FUNC at each headline selected by MATCH in SCOPE.
14206 FUNC is a function or a lisp form. The function will be called without
14207 arguments, with the cursor positioned at the beginning of the headline.
14208 The return values of all calls to the function will be collected and
14209 returned as a list.
14211 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14212 does not need to preserve point. After evaluation, the cursor will be
14213 moved to the end of the line (presumably of the headline of the
14214 processed entry) and search continues from there. Under some
14215 circumstances, this may not produce the wanted results. For example,
14216 if you have removed (e.g. archived) the current (sub)tree it could
14217 mean that the next entry will be skipped entirely. In such cases, you
14218 can specify the position from where search should continue by making
14219 FUNC set the variable `org-map-continue-from' to the desired buffer
14220 position.
14222 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14223 Only headlines that are matched by this query will be considered during
14224 the iteration. When MATCH is nil or t, all headlines will be
14225 visited by the iteration.
14227 SCOPE determines the scope of this command. It can be any of:
14229 nil The current buffer, respecting the restriction if any
14230 tree The subtree started with the entry at point
14231 region The entries within the active region, if any
14232 region-start-level
14233 The entries within the active region, but only those at
14234 the same level than the first one.
14235 file The current buffer, without restriction
14236 file-with-archives
14237 The current buffer, and any archives associated with it
14238 agenda All agenda files
14239 agenda-with-archives
14240 All agenda files with any archive files associated with them
14241 \(file1 file2 ...)
14242 If this is a list, all files in the list will be scanned
14244 The remaining args are treated as settings for the skipping facilities of
14245 the scanner. The following items can be given here:
14247 archive skip trees with the archive tag.
14248 comment skip trees with the COMMENT keyword
14249 function or Emacs Lisp form:
14250 will be used as value for `org-agenda-skip-function', so whenever
14251 the function returns t, FUNC will not be called for that
14252 entry and search will continue from the point where the
14253 function leaves it.
14255 If your function needs to retrieve the tags including inherited tags
14256 at the *current* entry, you can use the value of the variable
14257 `org-scanner-tags' which will be much faster than getting the value
14258 with `org-get-tags-at'. If your function gets properties with
14259 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14260 to t around the call to `org-entry-properties' to get the same speedup.
14261 Note that if your function moves around to retrieve tags and properties at
14262 a *different* entry, you cannot use these techniques."
14263 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14264 (not (org-region-active-p)))
14265 (let* ((org-agenda-archives-mode nil) ; just to make sure
14266 (org-agenda-skip-archived-trees (memq 'archive skip))
14267 (org-agenda-skip-comment-trees (memq 'comment skip))
14268 (org-agenda-skip-function
14269 (car (org-delete-all '(comment archive) skip)))
14270 (org-tags-match-list-sublevels t)
14271 (start-level (eq scope 'region-start-level))
14272 matcher file res
14273 org-todo-keywords-for-agenda
14274 org-done-keywords-for-agenda
14275 org-todo-keyword-alist-for-agenda
14276 org-drawers-for-agenda
14277 org-tag-alist-for-agenda
14278 todo-only)
14280 (cond
14281 ((eq match t) (setq matcher t))
14282 ((eq match nil) (setq matcher t))
14283 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14285 (save-excursion
14286 (save-restriction
14287 (cond ((eq scope 'tree)
14288 (org-back-to-heading t)
14289 (org-narrow-to-subtree)
14290 (setq scope nil))
14291 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14292 (org-region-active-p))
14293 ;; If needed, set start-level to a string like "2"
14294 (when start-level
14295 (save-excursion
14296 (goto-char (region-beginning))
14297 (unless (org-at-heading-p) (outline-next-heading))
14298 (setq start-level (org-current-level))))
14299 (narrow-to-region (region-beginning)
14300 (save-excursion
14301 (goto-char (region-end))
14302 (unless (and (bolp) (org-at-heading-p))
14303 (outline-next-heading))
14304 (point)))
14305 (setq scope nil)))
14307 (if (not scope)
14308 (progn
14309 (org-agenda-prepare-buffers
14310 (list (buffer-file-name (current-buffer))))
14311 (setq res (org-scan-tags func matcher todo-only start-level)))
14312 ;; Get the right scope
14313 (cond
14314 ((and scope (listp scope) (symbolp (car scope)))
14315 (setq scope (eval scope)))
14316 ((eq scope 'agenda)
14317 (setq scope (org-agenda-files t)))
14318 ((eq scope 'agenda-with-archives)
14319 (setq scope (org-agenda-files t))
14320 (setq scope (org-add-archive-files scope)))
14321 ((eq scope 'file)
14322 (setq scope (list (buffer-file-name))))
14323 ((eq scope 'file-with-archives)
14324 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14325 (org-agenda-prepare-buffers scope)
14326 (while (setq file (pop scope))
14327 (with-current-buffer (org-find-base-buffer-visiting file)
14328 (save-excursion
14329 (save-restriction
14330 (widen)
14331 (goto-char (point-min))
14332 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14333 res)))
14335 ;;;; Properties
14337 ;;; Setting and retrieving properties
14339 (defconst org-special-properties
14340 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14341 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14342 "The special properties valid in Org-mode.
14344 These are properties that are not defined in the property drawer,
14345 but in some other way.")
14347 (defconst org-default-properties
14348 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14349 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14350 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14351 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14352 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14353 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14354 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14355 "Some properties that are used by Org-mode for various purposes.
14356 Being in this list makes sure that they are offered for completion.")
14358 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14359 "Regular expression matching the first line of a property drawer.")
14361 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14362 "Regular expression matching the last line of a property drawer.")
14364 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14365 "Regular expression matching the first line of a property drawer.")
14367 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14368 "Regular expression matching the first line of a property drawer.")
14370 (defconst org-property-drawer-re
14371 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14372 org-property-end-re "\\)\n?")
14373 "Matches an entire property drawer.")
14375 (defconst org-clock-drawer-re
14376 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14377 org-property-end-re "\\)\n?")
14378 "Matches an entire clock drawer.")
14380 (defsubst org-re-property (property)
14381 "Return a regexp matching a PROPERTY line.
14382 Match group 1 will be set to the value."
14383 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14385 (defsubst org-re-property-keyword (property)
14386 "Return a regexp matching a PROPERTY line, possibly with no
14387 value for the property."
14388 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14390 (defun org-property-action ()
14391 "Do an action on properties."
14392 (interactive)
14393 (let (c)
14394 (org-at-property-p)
14395 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14396 (setq c (read-char-exclusive))
14397 (cond
14398 ((equal c ?s)
14399 (call-interactively 'org-set-property))
14400 ((equal c ?d)
14401 (call-interactively 'org-delete-property))
14402 ((equal c ?D)
14403 (call-interactively 'org-delete-property-globally))
14404 ((equal c ?c)
14405 (call-interactively 'org-compute-property-at-point))
14406 (t (error "No such property action %c" c)))))
14408 (defun org-inc-effort ()
14409 "Increment the value of the effort property in the current entry."
14410 (interactive)
14411 (org-set-effort nil t))
14413 (defun org-set-effort (&optional value increment)
14414 "Set the effort property of the current entry.
14415 With numerical prefix arg, use the nth allowed value, 0 stands for the
14416 10th allowed value.
14418 When INCREMENT is non-nil, set the property to the next allowed value."
14419 (interactive "P")
14420 (if (equal value 0) (setq value 10))
14421 (let* ((completion-ignore-case t)
14422 (prop org-effort-property)
14423 (cur (org-entry-get nil prop))
14424 (allowed (org-property-get-allowed-values nil prop 'table))
14425 (existing (mapcar 'list (org-property-values prop)))
14427 (val (cond
14428 ((stringp value) value)
14429 ((and allowed (integerp value))
14430 (or (car (nth (1- value) allowed))
14431 (car (org-last allowed))))
14432 ((and allowed increment)
14433 (or (caadr (member (list cur) allowed))
14434 (error "Allowed effort values are not set")))
14435 (allowed
14436 (message "Select 1-9,0, [RET%s]: %s"
14437 (if cur (concat "=" cur) "")
14438 (mapconcat 'car allowed " "))
14439 (setq rpl (read-char-exclusive))
14440 (if (equal rpl ?\r)
14442 (setq rpl (- rpl ?0))
14443 (if (equal rpl 0) (setq rpl 10))
14444 (if (and (> rpl 0) (<= rpl (length allowed)))
14445 (car (nth (1- rpl) allowed))
14446 (org-completing-read "Effort: " allowed nil))))
14448 (let (org-completion-use-ido org-completion-use-iswitchb)
14449 (org-completing-read
14450 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14451 (concat "[" cur "]") "")
14452 ": ")
14453 existing nil nil "" nil cur))))))
14454 (unless (equal (org-entry-get nil prop) val)
14455 (org-entry-put nil prop val))
14456 (message "%s is now %s" prop val)))
14458 (defun org-at-property-p ()
14459 "Is cursor inside a property drawer?"
14460 (save-excursion
14461 (beginning-of-line 1)
14462 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14463 (save-match-data ;; Used by calling procedures
14464 (let ((p (point))
14465 (range (unless (org-before-first-heading-p)
14466 (org-get-property-block))))
14467 (and range (<= (car range) p) (< p (cdr range))))))))
14469 (defun org-get-property-block (&optional beg end force)
14470 "Return the (beg . end) range of the body of the property drawer.
14471 BEG and END are the beginning and end of the current subtree, or of
14472 the part before the first headline. If they are not given, they will
14473 be found. If the drawer does not exist and FORCE is non-nil, create
14474 the drawer."
14475 (catch 'exit
14476 (save-excursion
14477 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14478 (progn (org-back-to-heading t) (point))))
14479 (end (or end (and (not (outline-next-heading)) (point-max))
14480 (point))))
14481 (goto-char beg)
14482 (if (re-search-forward org-property-start-re end t)
14483 (setq beg (1+ (match-end 0)))
14484 (if force
14485 (save-excursion
14486 (org-insert-property-drawer)
14487 (setq end (progn (outline-next-heading) (point))))
14488 (throw 'exit nil))
14489 (goto-char beg)
14490 (if (re-search-forward org-property-start-re end t)
14491 (setq beg (1+ (match-end 0)))))
14492 (if (re-search-forward org-property-end-re end t)
14493 (setq end (match-beginning 0))
14494 (or force (throw 'exit nil))
14495 (goto-char beg)
14496 (setq end beg)
14497 (org-indent-line)
14498 (insert ":END:\n"))
14499 (cons beg end)))))
14501 (defun org-entry-properties (&optional pom which specific)
14502 "Get all properties of the entry at point-or-marker POM.
14503 This includes the TODO keyword, the tags, time strings for deadline,
14504 scheduled, and clocking, and any additional properties defined in the
14505 entry. The return value is an alist, keys may occur multiple times
14506 if the property key was used several times.
14507 POM may also be nil, in which case the current entry is used.
14508 If WHICH is nil or `all', get all properties. If WHICH is
14509 `special' or `standard', only get that subclass. If WHICH
14510 is a string only get exactly this property. SPECIFIC can be a string, the
14511 specific property we are interested in. Specifying it can speed
14512 things up because then unnecessary parsing is avoided."
14513 (setq which (or which 'all))
14514 (org-with-point-at pom
14515 (let ((clockstr (substring org-clock-string 0 -1))
14516 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14517 (case-fold-search nil)
14518 beg end range props sum-props key key1 value string clocksum clocksumt)
14519 (save-excursion
14520 (when (condition-case nil
14521 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14522 (error nil))
14523 (setq beg (point))
14524 (setq sum-props (get-text-property (point) 'org-summaries))
14525 (setq clocksum (get-text-property (point) :org-clock-minutes)
14526 clocksumt (get-text-property (point) :org-clock-minutes-today))
14527 (outline-next-heading)
14528 (setq end (point))
14529 (when (memq which '(all special))
14530 ;; Get the special properties, like TODO and tags
14531 (goto-char beg)
14532 (when (and (or (not specific) (string= specific "TODO"))
14533 (looking-at org-todo-line-regexp) (match-end 2))
14534 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14535 (when (and (or (not specific) (string= specific "PRIORITY"))
14536 (looking-at org-priority-regexp))
14537 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14538 (when (or (not specific) (string= specific "FILE"))
14539 (push (cons "FILE" buffer-file-name) props))
14540 (when (and (or (not specific) (string= specific "TAGS"))
14541 (setq value (org-get-tags-string))
14542 (string-match "\\S-" value))
14543 (push (cons "TAGS" value) props))
14544 (when (and (or (not specific) (string= specific "ALLTAGS"))
14545 (setq value (org-get-tags-at)))
14546 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14547 ":"))
14548 props))
14549 (when (or (not specific) (string= specific "BLOCKED"))
14550 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14551 (when (or (not specific)
14552 (member specific
14553 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14554 "TIMESTAMP" "TIMESTAMP_IA")))
14555 (catch 'match
14556 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14557 (setq key (if (match-end 1)
14558 (substring (org-match-string-no-properties 1)
14559 0 -1))
14560 string (if (equal key clockstr)
14561 (org-trim
14562 (buffer-substring-no-properties
14563 (match-beginning 3) (goto-char
14564 (point-at-eol))))
14565 (substring (org-match-string-no-properties 3)
14566 1 -1)))
14567 ;; Get the correct property name from the key. This is
14568 ;; necessary if the user has configured time keywords.
14569 (setq key1 (concat key ":"))
14570 (cond
14571 ((not key)
14572 (setq key
14573 (if (= (char-after (match-beginning 3)) ?\[)
14574 "TIMESTAMP_IA" "TIMESTAMP")))
14575 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14576 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14577 ((equal key1 org-closed-string) (setq key "CLOSED"))
14578 ((equal key1 org-clock-string) (setq key "CLOCK")))
14579 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14580 (progn
14581 (push (cons key string) props)
14582 ;; no need to search further if match is found
14583 (throw 'match t))
14584 (when (or (equal key "CLOCK") (not (assoc key props)))
14585 (push (cons key string) props)))))))
14587 (when (memq which '(all standard))
14588 ;; Get the standard properties, like :PROP: ...
14589 (setq range (org-get-property-block beg end))
14590 (when range
14591 (goto-char (car range))
14592 (while (re-search-forward
14593 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14594 (cdr range) t)
14595 (setq key (org-match-string-no-properties 1)
14596 value (org-trim (or (org-match-string-no-properties 2) "")))
14597 (unless (member key excluded)
14598 (push (cons key (or value "")) props)))))
14599 (if clocksum
14600 (push (cons "CLOCKSUM"
14601 (org-columns-number-to-string (/ (float clocksum) 60.)
14602 'add_times))
14603 props))
14604 (if clocksumt
14605 (push (cons "CLOCKSUM_T"
14606 (org-columns-number-to-string (/ (float clocksumt) 60.)
14607 'add_times))
14608 props))
14609 (unless (assoc "CATEGORY" props)
14610 (push (cons "CATEGORY" (org-get-category)) props))
14611 (append sum-props (nreverse props)))))))
14613 (defun org-entry-get (pom property &optional inherit literal-nil)
14614 "Get value of PROPERTY for entry or content at point-or-marker POM.
14615 If INHERIT is non-nil and the entry does not have the property,
14616 then also check higher levels of the hierarchy.
14617 If INHERIT is the symbol `selective', use inheritance only if the setting
14618 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14619 If the property is present but empty, the return value is the empty string.
14620 If the property is not present at all, nil is returned.
14622 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14623 do not interpret it as the list atom nil. This is used for inheritance
14624 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14625 (org-with-point-at pom
14626 (if (and inherit (if (eq inherit 'selective)
14627 (org-property-inherit-p property)
14629 (org-entry-get-with-inheritance property literal-nil)
14630 (if (member property org-special-properties)
14631 ;; We need a special property. Use `org-entry-properties' to
14632 ;; retrieve it, but specify the wanted property
14633 (cdr (assoc property (org-entry-properties nil 'special property)))
14634 (let* ((range (org-get-property-block))
14635 (props (list (or (assoc property org-file-properties)
14636 (assoc property org-global-properties)
14637 (assoc property org-global-properties-fixed))))
14638 (ap (lambda (key)
14639 (when (re-search-forward
14640 (org-re-property key) (cdr range) t)
14641 (setq props
14642 (org-update-property-plist
14644 (if (match-end 1)
14645 (org-match-string-no-properties 1) "")
14646 props)))))
14647 val)
14648 (when (and range (goto-char (car range)))
14649 (funcall ap property)
14650 (goto-char (car range))
14651 (while (funcall ap (concat property "+")))
14652 (setq val (cdr (assoc property props)))
14653 (when val (if literal-nil val (org-not-nil val)))))))))
14655 (defun org-property-or-variable-value (var &optional inherit)
14656 "Check if there is a property fixing the value of VAR.
14657 If yes, return this value. If not, return the current value of the variable."
14658 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14659 (if (and prop (stringp prop) (string-match "\\S-" prop))
14660 (read prop)
14661 (symbol-value var))))
14663 (defun org-entry-delete (pom property)
14664 "Delete the property PROPERTY from entry at point-or-marker POM."
14665 (org-with-point-at pom
14666 (if (member property org-special-properties)
14667 nil ; cannot delete these properties.
14668 (let ((range (org-get-property-block)))
14669 (if (and range
14670 (goto-char (car range))
14671 (re-search-forward
14672 (org-re-property property)
14673 (cdr range) t))
14674 (progn
14675 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14677 nil)))))
14679 ;; Multi-values properties are properties that contain multiple values
14680 ;; These values are assumed to be single words, separated by whitespace.
14681 (defun org-entry-add-to-multivalued-property (pom property value)
14682 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14683 (let* ((old (org-entry-get pom property))
14684 (values (and old (org-split-string old "[ \t]"))))
14685 (setq value (org-entry-protect-space value))
14686 (unless (member value values)
14687 (setq values (cons value values))
14688 (org-entry-put pom property
14689 (mapconcat 'identity values " ")))))
14691 (defun org-entry-remove-from-multivalued-property (pom property value)
14692 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14693 (let* ((old (org-entry-get pom property))
14694 (values (and old (org-split-string old "[ \t]"))))
14695 (setq value (org-entry-protect-space value))
14696 (when (member value values)
14697 (setq values (delete value values))
14698 (org-entry-put pom property
14699 (mapconcat 'identity values " ")))))
14701 (defun org-entry-member-in-multivalued-property (pom property value)
14702 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14703 (let* ((old (org-entry-get pom property))
14704 (values (and old (org-split-string old "[ \t]"))))
14705 (setq value (org-entry-protect-space value))
14706 (member value values)))
14708 (defun org-entry-get-multivalued-property (pom property)
14709 "Return a list of values in a multivalued property."
14710 (let* ((value (org-entry-get pom property))
14711 (values (and value (org-split-string value "[ \t]"))))
14712 (mapcar 'org-entry-restore-space values)))
14714 (defun org-entry-put-multivalued-property (pom property &rest values)
14715 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14716 VALUES should be a list of strings. Spaces will be protected."
14717 (org-entry-put pom property
14718 (mapconcat 'org-entry-protect-space values " "))
14719 (let* ((value (org-entry-get pom property))
14720 (values (and value (org-split-string value "[ \t]"))))
14721 (mapcar 'org-entry-restore-space values)))
14723 (defun org-entry-protect-space (s)
14724 "Protect spaces and newline in string S."
14725 (while (string-match " " s)
14726 (setq s (replace-match "%20" t t s)))
14727 (while (string-match "\n" s)
14728 (setq s (replace-match "%0A" t t s)))
14731 (defun org-entry-restore-space (s)
14732 "Restore spaces and newline in string S."
14733 (while (string-match "%20" s)
14734 (setq s (replace-match " " t t s)))
14735 (while (string-match "%0A" s)
14736 (setq s (replace-match "\n" t t s)))
14739 (defvar org-entry-property-inherited-from (make-marker)
14740 "Marker pointing to the entry from where a property was inherited.
14741 Each call to `org-entry-get-with-inheritance' will set this marker to the
14742 location of the entry where the inheritance search matched. If there was
14743 no match, the marker will point nowhere.
14744 Note that also `org-entry-get' calls this function, if the INHERIT flag
14745 is set.")
14747 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14748 "Get PROPERTY of entry or content at point, search higher levels if needed.
14749 The search will stop at the first ancestor which has the property defined.
14750 If the value found is \"nil\", return nil to show that the property
14751 should be considered as undefined (this is the meaning of nil here).
14752 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14753 (move-marker org-entry-property-inherited-from nil)
14754 (let (tmp)
14755 (save-excursion
14756 (save-restriction
14757 (widen)
14758 (catch 'ex
14759 (while t
14760 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14761 (or (ignore-errors (org-back-to-heading t))
14762 (goto-char (point-min)))
14763 (move-marker org-entry-property-inherited-from (point))
14764 (throw 'ex tmp))
14765 (or (ignore-errors (org-up-heading-safe))
14766 (throw 'ex nil))))))
14767 (setq tmp (or tmp
14768 (cdr (assoc property org-file-properties))
14769 (cdr (assoc property org-global-properties))
14770 (cdr (assoc property org-global-properties-fixed))))
14771 (if literal-nil tmp (org-not-nil tmp))))
14773 (defvar org-property-changed-functions nil
14774 "Hook called when the value of a property has changed.
14775 Each hook function should accept two arguments, the name of the property
14776 and the new value.")
14778 (defun org-entry-put (pom property value)
14779 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14780 (org-with-point-at pom
14781 (org-back-to-heading t)
14782 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14783 range)
14784 (cond
14785 ((equal property "TODO")
14786 (when (and (stringp value) (string-match "\\S-" value)
14787 (not (member value org-todo-keywords-1)))
14788 (error "\"%s\" is not a valid TODO state" value))
14789 (if (or (not value)
14790 (not (string-match "\\S-" value)))
14791 (setq value 'none))
14792 (org-todo value)
14793 (org-set-tags nil 'align))
14794 ((equal property "PRIORITY")
14795 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14796 (string-to-char value) ?\ ))
14797 (org-set-tags nil 'align))
14798 ((equal property "CLOCKSUM")
14799 (if (not (re-search-forward
14800 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14801 (error "Cannot find a clock log")
14802 (goto-char (- (match-end 1) 2))
14803 (cond
14804 ((eq value 'earlier) (org-timestamp-down))
14805 ((eq value 'later) (org-timestamp-up)))
14806 (org-clock-sum-current-item)))
14807 ((equal property "SCHEDULED")
14808 (if (re-search-forward org-scheduled-time-regexp end t)
14809 (cond
14810 ((eq value 'earlier) (org-timestamp-change -1 'day))
14811 ((eq value 'later) (org-timestamp-change 1 'day))
14812 (t (call-interactively 'org-schedule)))
14813 (call-interactively 'org-schedule)))
14814 ((equal property "DEADLINE")
14815 (if (re-search-forward org-deadline-time-regexp end t)
14816 (cond
14817 ((eq value 'earlier) (org-timestamp-change -1 'day))
14818 ((eq value 'later) (org-timestamp-change 1 'day))
14819 (t (call-interactively 'org-deadline)))
14820 (call-interactively 'org-deadline)))
14821 ((member property org-special-properties)
14822 (error "The %s property can not yet be set with `org-entry-put'"
14823 property))
14824 (t ; a non-special property
14825 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14826 (setq range (org-get-property-block beg end 'force))
14827 (goto-char (car range))
14828 (if (re-search-forward
14829 (org-re-property-keyword property) (cdr range) t)
14830 (progn
14831 (delete-region (match-beginning 0) (match-end 0))
14832 (goto-char (match-beginning 0)))
14833 (goto-char (cdr range))
14834 (insert "\n")
14835 (backward-char 1)
14836 (org-indent-line))
14837 (insert ":" property ":")
14838 (and value (insert " " value))
14839 (org-indent-line)))))
14840 (run-hook-with-args 'org-property-changed-functions property value)))
14842 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14843 "Get all property keys in the current buffer.
14844 With INCLUDE-SPECIALS, also list the special properties that reflect things
14845 like tags and TODO state.
14846 With INCLUDE-DEFAULTS, also include properties that has special meaning
14847 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14848 and others.
14849 With INCLUDE-COLUMNS, also include property names given in COLUMN
14850 formats in the current buffer."
14851 (let (rtn range cfmt s p)
14852 (save-excursion
14853 (save-restriction
14854 (widen)
14855 (goto-char (point-min))
14856 (while (re-search-forward org-property-start-re nil t)
14857 (setq range (org-get-property-block))
14858 (goto-char (car range))
14859 (while (re-search-forward
14860 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14861 (cdr range) t)
14862 (add-to-list 'rtn (org-match-string-no-properties 1)))
14863 (outline-next-heading))))
14865 (when include-specials
14866 (setq rtn (append org-special-properties rtn)))
14868 (when include-defaults
14869 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14870 (add-to-list 'rtn org-effort-property))
14872 (when include-columns
14873 (save-excursion
14874 (save-restriction
14875 (widen)
14876 (goto-char (point-min))
14877 (while (re-search-forward
14878 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14879 nil t)
14880 (setq cfmt (match-string 2) s 0)
14881 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14882 cfmt s)
14883 (setq s (match-end 0)
14884 p (match-string 1 cfmt))
14885 (unless (or (equal p "ITEM")
14886 (member p org-special-properties))
14887 (add-to-list 'rtn (match-string 1 cfmt))))))))
14889 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14891 (defun org-property-values (key)
14892 "Return a list of all values of property KEY in the current buffer."
14893 (save-excursion
14894 (save-restriction
14895 (widen)
14896 (goto-char (point-min))
14897 (let ((re (org-re-property key))
14898 values)
14899 (while (re-search-forward re nil t)
14900 (add-to-list 'values (org-trim (match-string 1))))
14901 (delete "" values)))))
14903 (defun org-insert-property-drawer ()
14904 "Insert a property drawer into the current entry."
14905 (org-back-to-heading t)
14906 (looking-at org-outline-regexp)
14907 (let ((indent (if org-adapt-indentation
14908 (- (match-end 0) (match-beginning 0))
14910 (beg (point))
14911 (re (concat "^[ \t]*" org-keyword-time-regexp))
14912 end hiddenp)
14913 (outline-next-heading)
14914 (setq end (point))
14915 (goto-char beg)
14916 (while (re-search-forward re end t))
14917 (setq hiddenp (outline-invisible-p))
14918 (end-of-line 1)
14919 (and (equal (char-after) ?\n) (forward-char 1))
14920 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14921 (if (member (match-string 1) '("CLOCK:" ":END:"))
14922 ;; just skip this line
14923 (beginning-of-line 2)
14924 ;; Drawer start, find the end
14925 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14926 (beginning-of-line 1)))
14927 (org-skip-over-state-notes)
14928 (skip-chars-backward " \t\n\r")
14929 (if (eq (char-before) ?*) (forward-char 1))
14930 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14931 (beginning-of-line 0)
14932 (org-indent-to-column indent)
14933 (beginning-of-line 2)
14934 (org-indent-to-column indent)
14935 (beginning-of-line 0)
14936 (if hiddenp
14937 (save-excursion
14938 (org-back-to-heading t)
14939 (hide-entry))
14940 (org-flag-drawer t))))
14942 (defun org-insert-drawer (&optional arg drawer)
14943 "Insert a drawer at point.
14945 Optional argument DRAWER, when non-nil, is a string representing
14946 drawer's name. Otherwise, the user is prompted for a name.
14948 If a region is active, insert the drawer around that region
14949 instead.
14951 Point is left between drawer's boundaries."
14952 (interactive "P")
14953 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14954 "LOGBOOK"))
14955 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14956 ;; internally by Org. They are meant to be inserted
14957 ;; automatically.
14958 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14959 ;; Remove system drawers from list. Note: For some reason,
14960 ;; `org-completing-read' ignores the predicate while
14961 ;; `completing-read' handles it fine.
14962 (drawer (if arg "PROPERTIES"
14963 (or drawer
14964 (completing-read
14965 "Drawer: " org-drawers
14966 (lambda (d) (not (member d system-drawers))))))))
14967 (cond
14968 ;; With C-u, fall back on `org-insert-property-drawer'
14969 (arg (org-insert-property-drawer))
14970 ;; With an active region, insert a drawer at point.
14971 ((not (org-region-active-p))
14972 (progn
14973 (unless (bolp) (insert "\n"))
14974 (insert (format ":%s:\n\n:END:\n" drawer))
14975 (forward-line -2)))
14976 ;; Otherwise, insert the drawer at point
14978 (let ((rbeg (region-beginning))
14979 (rend (copy-marker (region-end))))
14980 (unwind-protect
14981 (progn
14982 (goto-char rbeg)
14983 (beginning-of-line)
14984 (when (save-excursion
14985 (re-search-forward org-outline-regexp-bol rend t))
14986 (error "Drawers cannot contain headlines"))
14987 ;; Position point at the beginning of the first
14988 ;; non-blank line in region. Insert drawer's opening
14989 ;; there, then indent it.
14990 (org-skip-whitespace)
14991 (beginning-of-line)
14992 (insert ":" drawer ":\n")
14993 (forward-line -1)
14994 (indent-for-tab-command)
14995 ;; Move point to the beginning of the first blank line
14996 ;; after the last non-blank line in region. Insert
14997 ;; drawer's closing, then indent it.
14998 (goto-char rend)
14999 (skip-chars-backward " \r\t\n")
15000 (insert "\n:END:")
15001 (deactivate-mark t)
15002 (indent-for-tab-command)
15003 (unless (eolp) (insert "\n")))
15004 ;; Clear marker, whatever the outcome of insertion is.
15005 (set-marker rend nil)))))))
15007 (defvar org-property-set-functions-alist nil
15008 "Property set function alist.
15009 Each entry should have the following format:
15011 (PROPERTY . READ-FUNCTION)
15013 The read function will be called with the same argument as
15014 `org-completing-read'.")
15016 (defun org-set-property-function (property)
15017 "Get the function that should be used to set PROPERTY.
15018 This is computed according to `org-property-set-functions-alist'."
15019 (or (cdr (assoc property org-property-set-functions-alist))
15020 'org-completing-read))
15022 (defun org-read-property-value (property)
15023 "Read PROPERTY value from user."
15024 (let* ((completion-ignore-case t)
15025 (allowed (org-property-get-allowed-values nil property 'table))
15026 (cur (org-entry-get nil property))
15027 (prompt (concat property " value"
15028 (if (and cur (string-match "\\S-" cur))
15029 (concat " [" cur "]") "") ": "))
15030 (set-function (org-set-property-function property))
15031 (val (if allowed
15032 (funcall set-function prompt allowed nil
15033 (not (get-text-property 0 'org-unrestricted
15034 (caar allowed))))
15035 (let (org-completion-use-ido org-completion-use-iswitchb)
15036 (funcall set-function prompt
15037 (mapcar 'list (org-property-values property))
15038 nil nil "" nil cur)))))
15039 (if (equal val "")
15041 val)))
15043 (defvar org-last-set-property nil)
15044 (defun org-read-property-name ()
15045 "Read a property name."
15046 (let* ((completion-ignore-case t)
15047 (keys (org-buffer-property-keys nil t t))
15048 (default-prop (or (save-excursion
15049 (save-match-data
15050 (beginning-of-line)
15051 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15052 (null (string= (match-string 1) "END"))
15053 (match-string 1))))
15054 org-last-set-property))
15055 (property (org-icompleting-read
15056 (concat "Property"
15057 (if default-prop (concat " [" default-prop "]") "")
15058 ": ")
15059 (mapcar 'list keys)
15060 nil nil nil nil
15061 default-prop
15063 (if (member property keys)
15064 property
15065 (or (cdr (assoc (downcase property)
15066 (mapcar (lambda (x) (cons (downcase x) x))
15067 keys)))
15068 property))))
15070 (defun org-set-property (property value)
15071 "In the current entry, set PROPERTY to VALUE.
15072 When called interactively, this will prompt for a property name, offering
15073 completion on existing and default properties. And then it will prompt
15074 for a value, offering completion either on allowed values (via an inherited
15075 xxx_ALL property) or on existing values in other instances of this property
15076 in the current file."
15077 (interactive (list nil nil))
15078 (let* ((property (or property (org-read-property-name)))
15079 (value (or value (org-read-property-value property)))
15080 (fn (cdr (assoc property org-properties-postprocess-alist))))
15081 (setq org-last-set-property property)
15082 ;; Possibly postprocess the inserted value:
15083 (when fn (setq value (funcall fn value)))
15084 (unless (equal (org-entry-get nil property) value)
15085 (org-entry-put nil property value))))
15087 (defun org-delete-property (property)
15088 "In the current entry, delete PROPERTY."
15089 (interactive
15090 (let* ((completion-ignore-case t)
15091 (prop (org-icompleting-read "Property: "
15092 (org-entry-properties nil 'standard))))
15093 (list prop)))
15094 (message "Property %s %s" property
15095 (if (org-entry-delete nil property)
15096 "deleted"
15097 "was not present in the entry")))
15099 (defun org-delete-property-globally (property)
15100 "Remove PROPERTY globally, from all entries."
15101 (interactive
15102 (let* ((completion-ignore-case t)
15103 (prop (org-icompleting-read
15104 "Globally remove property: "
15105 (mapcar 'list (org-buffer-property-keys)))))
15106 (list prop)))
15107 (save-excursion
15108 (save-restriction
15109 (widen)
15110 (goto-char (point-min))
15111 (let ((cnt 0))
15112 (while (re-search-forward
15113 (org-re-property property)
15114 nil t)
15115 (setq cnt (1+ cnt))
15116 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15117 (message "Property \"%s\" removed from %d entries" property cnt)))))
15119 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15121 (defun org-compute-property-at-point ()
15122 "Compute the property at point.
15123 This looks for an enclosing column format, extracts the operator and
15124 then applies it to the property in the column format's scope."
15125 (interactive)
15126 (unless (org-at-property-p)
15127 (error "Not at a property"))
15128 (let ((prop (org-match-string-no-properties 2)))
15129 (org-columns-get-format-and-top-level)
15130 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15131 (error "No operator defined for property %s" prop))
15132 (org-columns-compute prop)))
15134 (defvar org-property-allowed-value-functions nil
15135 "Hook for functions supplying allowed values for a specific property.
15136 The functions must take a single argument, the name of the property, and
15137 return a flat list of allowed values. If \":ETC\" is one of
15138 the values, this means that these values are intended as defaults for
15139 completion, but that other values should be allowed too.
15140 The functions must return nil if they are not responsible for this
15141 property.")
15143 (defun org-property-get-allowed-values (pom property &optional table)
15144 "Get allowed values for the property PROPERTY.
15145 When TABLE is non-nil, return an alist that can directly be used for
15146 completion."
15147 (let (vals)
15148 (cond
15149 ((equal property "TODO")
15150 (setq vals (org-with-point-at pom
15151 (append org-todo-keywords-1 '("")))))
15152 ((equal property "PRIORITY")
15153 (let ((n org-lowest-priority))
15154 (while (>= n org-highest-priority)
15155 (push (char-to-string n) vals)
15156 (setq n (1- n)))))
15157 ((member property org-special-properties))
15158 ((setq vals (run-hook-with-args-until-success
15159 'org-property-allowed-value-functions property)))
15161 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15162 (when (and vals (string-match "\\S-" vals))
15163 (setq vals (car (read-from-string (concat "(" vals ")"))))
15164 (setq vals (mapcar (lambda (x)
15165 (cond ((stringp x) x)
15166 ((numberp x) (number-to-string x))
15167 ((symbolp x) (symbol-name x))
15168 (t "???")))
15169 vals)))))
15170 (when (member ":ETC" vals)
15171 (setq vals (remove ":ETC" vals))
15172 (org-add-props (car vals) '(org-unrestricted t)))
15173 (if table (mapcar 'list vals) vals)))
15175 (defun org-property-previous-allowed-value (&optional previous)
15176 "Switch to the next allowed value for this property."
15177 (interactive)
15178 (org-property-next-allowed-value t))
15180 (defun org-property-next-allowed-value (&optional previous)
15181 "Switch to the next allowed value for this property."
15182 (interactive)
15183 (unless (org-at-property-p)
15184 (error "Not at a property"))
15185 (let* ((key (match-string 2))
15186 (value (match-string 3))
15187 (allowed (or (org-property-get-allowed-values (point) key)
15188 (and (member value '("[ ]" "[-]" "[X]"))
15189 '("[ ]" "[X]"))))
15190 nval)
15191 (unless allowed
15192 (error "Allowed values for this property have not been defined"))
15193 (if previous (setq allowed (reverse allowed)))
15194 (if (member value allowed)
15195 (setq nval (car (cdr (member value allowed)))))
15196 (setq nval (or nval (car allowed)))
15197 (if (equal nval value)
15198 (error "Only one allowed value for this property"))
15199 (org-at-property-p)
15200 (replace-match (concat " :" key ": " nval) t t)
15201 (org-indent-line)
15202 (beginning-of-line 1)
15203 (skip-chars-forward " \t")
15204 (run-hook-with-args 'org-property-changed-functions key nval)))
15206 (defun org-find-olp (path &optional this-buffer)
15207 "Return a marker pointing to the entry at outline path OLP.
15208 If anything goes wrong, throw an error.
15209 You can wrap this call to catch the error like this:
15211 (condition-case msg
15212 (org-mobile-locate-entry (match-string 4))
15213 (error (nth 1 msg)))
15215 The return value will then be either a string with the error message,
15216 or a marker if everything is OK.
15218 If THIS-BUFFER is set, the outline path does not contain a file,
15219 only headings."
15220 (let* ((file (if this-buffer buffer-file-name (pop path)))
15221 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15222 (level 1)
15223 (lmin 1)
15224 (lmax 1)
15225 limit re end found pos heading cnt flevel)
15226 (unless buffer (error "File not found :%s" file))
15227 (with-current-buffer buffer
15228 (save-excursion
15229 (save-restriction
15230 (widen)
15231 (setq limit (point-max))
15232 (goto-char (point-min))
15233 (while (setq heading (pop path))
15234 (setq re (format org-complex-heading-regexp-format
15235 (regexp-quote heading)))
15236 (setq cnt 0 pos (point))
15237 (while (re-search-forward re end t)
15238 (setq level (- (match-end 1) (match-beginning 1)))
15239 (if (and (>= level lmin) (<= level lmax))
15240 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15241 (when (= cnt 0) (error "Heading not found on level %d: %s"
15242 lmax heading))
15243 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15244 lmax heading))
15245 (goto-char found)
15246 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15247 (setq end (save-excursion (org-end-of-subtree t t))))
15248 (when (org-at-heading-p)
15249 (move-marker (make-marker) (point))))))))
15251 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15252 "Find node HEADING in BUFFER.
15253 Return a marker to the heading if it was found, or nil if not.
15254 If POS-ONLY is set, return just the position instead of a marker.
15256 The heading text must match exact, but it may have a TODO keyword,
15257 a priority cookie and tags in the standard locations."
15258 (with-current-buffer (or buffer (current-buffer))
15259 (save-excursion
15260 (save-restriction
15261 (widen)
15262 (goto-char (point-min))
15263 (let (case-fold-search)
15264 (if (re-search-forward
15265 (format org-complex-heading-regexp-format
15266 (regexp-quote heading)) nil t)
15267 (if pos-only
15268 (match-beginning 0)
15269 (move-marker (make-marker) (match-beginning 0)))))))))
15271 (defun org-find-exact-heading-in-directory (heading &optional dir)
15272 "Find Org node headline HEADING in all .org files in directory DIR.
15273 When the target headline is found, return a marker to this location."
15274 (let ((files (directory-files (or dir default-directory)
15275 nil "\\`[^.#].*\\.org\\'"))
15276 file visiting m buffer)
15277 (catch 'found
15278 (while (setq file (pop files))
15279 (message "trying %s" file)
15280 (setq visiting (org-find-base-buffer-visiting file))
15281 (setq buffer (or visiting (find-file-noselect file)))
15282 (setq m (org-find-exact-headline-in-buffer
15283 heading buffer))
15284 (when (and (not m) (not visiting)) (kill-buffer buffer))
15285 (and m (throw 'found m))))))
15287 (defun org-find-entry-with-id (ident)
15288 "Locate the entry that contains the ID property with exact value IDENT.
15289 IDENT can be a string, a symbol or a number, this function will search for
15290 the string representation of it.
15291 Return the position where this entry starts, or nil if there is no such entry."
15292 (interactive "sID: ")
15293 (let ((id (cond
15294 ((stringp ident) ident)
15295 ((symbol-name ident) (symbol-name ident))
15296 ((numberp ident) (number-to-string ident))
15297 (t (error "IDENT %s must be a string, symbol or number" ident))))
15298 (case-fold-search nil))
15299 (save-excursion
15300 (save-restriction
15301 (widen)
15302 (goto-char (point-min))
15303 (when (re-search-forward
15304 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15305 nil t)
15306 (org-back-to-heading t)
15307 (point))))))
15309 ;;;; Timestamps
15311 (defvar org-last-changed-timestamp nil)
15312 (defvar org-last-inserted-timestamp nil
15313 "The last time stamp inserted with `org-insert-time-stamp'.")
15314 (defvar org-time-was-given) ; dynamically scoped parameter
15315 (defvar org-end-time-was-given) ; dynamically scoped parameter
15316 (defvar org-ts-what) ; dynamically scoped parameter
15318 (defun org-time-stamp (arg &optional inactive)
15319 "Prompt for a date/time and insert a time stamp.
15320 If the user specifies a time like HH:MM or if this command is
15321 called with at least one prefix argument, the time stamp contains
15322 the date and the time. Otherwise, only the date is be included.
15324 All parts of a date not specified by the user is filled in from
15325 the current date/time. So if you just press return without
15326 typing anything, the time stamp will represent the current
15327 date/time.
15329 If there is already a timestamp at the cursor, it will be
15330 modified.
15332 With two universal prefix arguments, insert an active timestamp
15333 with the current time without prompting the user."
15334 (interactive "P")
15335 (let* ((ts nil)
15336 (default-time
15337 ;; Default time is either today, or, when entering a range,
15338 ;; the range start.
15339 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15340 (save-excursion
15341 (re-search-backward
15342 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15343 (- (point) 20) t)))
15344 (apply 'encode-time (org-parse-time-string (match-string 1)))
15345 (current-time)))
15346 (default-input (and ts (org-get-compact-tod ts)))
15347 (repeater (save-excursion
15348 (save-match-data
15349 (beginning-of-line)
15350 (when (re-search-forward
15351 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15352 (save-excursion (progn (end-of-line) (point))) t)
15353 (match-string 0)))))
15354 org-time-was-given org-end-time-was-given time)
15355 (cond
15356 ((and (org-at-timestamp-p t)
15357 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15358 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15359 (insert "--")
15360 (setq time (let ((this-command this-command))
15361 (org-read-date arg 'totime nil nil
15362 default-time default-input inactive)))
15363 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15364 ((org-at-timestamp-p t)
15365 (setq time (let ((this-command this-command))
15366 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15367 (when (org-at-timestamp-p t) ; just to get the match data
15368 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15369 (replace-match "")
15370 (setq org-last-changed-timestamp
15371 (org-insert-time-stamp
15372 time (or org-time-was-given arg)
15373 inactive nil nil (list org-end-time-was-given)))
15374 (when repeater (goto-char (1- (point))) (insert " " repeater)
15375 (setq org-last-changed-timestamp
15376 (concat (substring org-last-inserted-timestamp 0 -1)
15377 " " repeater ">"))))
15378 (message "Timestamp updated"))
15379 ((equal arg '(16))
15380 (org-insert-time-stamp (current-time) t))
15382 (setq time (let ((this-command this-command))
15383 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15384 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15385 nil nil (list org-end-time-was-given))))))
15387 ;; FIXME: can we use this for something else, like computing time differences?
15388 (defun org-get-compact-tod (s)
15389 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15390 (let* ((t1 (match-string 1 s))
15391 (h1 (string-to-number (match-string 2 s)))
15392 (m1 (string-to-number (match-string 3 s)))
15393 (t2 (and (match-end 4) (match-string 5 s)))
15394 (h2 (and t2 (string-to-number (match-string 6 s))))
15395 (m2 (and t2 (string-to-number (match-string 7 s))))
15396 dh dm)
15397 (if (not t2)
15399 (setq dh (- h2 h1) dm (- m2 m1))
15400 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15401 (concat t1 "+" (number-to-string dh)
15402 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15404 (defun org-time-stamp-inactive (&optional arg)
15405 "Insert an inactive time stamp.
15406 An inactive time stamp is enclosed in square brackets instead of angle
15407 brackets. It is inactive in the sense that it does not trigger agenda entries,
15408 does not link to the calendar and cannot be changed with the S-cursor keys.
15409 So these are more for recording a certain time/date."
15410 (interactive "P")
15411 (org-time-stamp arg 'inactive))
15413 (defvar org-date-ovl (make-overlay 1 1))
15414 (overlay-put org-date-ovl 'face 'org-date-selected)
15415 (org-detach-overlay org-date-ovl)
15417 (defvar org-ans1) ; dynamically scoped parameter
15418 (defvar org-ans2) ; dynamically scoped parameter
15420 (defvar org-plain-time-of-day-regexp) ; defined below
15422 (defvar org-overriding-default-time nil) ; dynamically scoped
15423 (defvar org-read-date-overlay nil)
15424 (defvar org-dcst nil) ; dynamically scoped
15425 (defvar org-read-date-history nil)
15426 (defvar org-read-date-final-answer nil)
15427 (defvar org-read-date-analyze-futurep nil)
15428 (defvar org-read-date-analyze-forced-year nil)
15429 (defvar org-read-date-inactive)
15431 (defun org-read-date (&optional org-with-time to-time from-string prompt
15432 default-time default-input inactive)
15433 "Read a date, possibly a time, and make things smooth for the user.
15434 The prompt will suggest to enter an ISO date, but you can also enter anything
15435 which will at least partially be understood by `parse-time-string'.
15436 Unrecognized parts of the date will default to the current day, month, year,
15437 hour and minute. If this command is called to replace a timestamp at point,
15438 or to enter the second timestamp of a range, the default time is taken
15439 from the existing stamp. Furthermore, the command prefers the future,
15440 so if you are giving a date where the year is not given, and the day-month
15441 combination is already past in the current year, it will assume you
15442 mean next year. For details, see the manual. A few examples:
15444 3-2-5 --> 2003-02-05
15445 feb 15 --> currentyear-02-15
15446 2/15 --> currentyear-02-15
15447 sep 12 9 --> 2009-09-12
15448 12:45 --> today 12:45
15449 22 sept 0:34 --> currentyear-09-22 0:34
15450 12 --> currentyear-currentmonth-12
15451 Fri --> nearest Friday (today or later)
15452 etc.
15454 Furthermore you can specify a relative date by giving, as the *first* thing
15455 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15456 change in days weeks, months, years.
15457 With a single plus or minus, the date is relative to today. With a double
15458 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15459 +4d --> four days from today
15460 +4 --> same as above
15461 +2w --> two weeks from today
15462 ++5 --> five days from default date
15464 The function understands only English month and weekday abbreviations.
15466 While prompting, a calendar is popped up - you can also select the
15467 date with the mouse (button 1). The calendar shows a period of three
15468 months. To scroll it to other months, use the keys `>' and `<'.
15469 If you don't like the calendar, turn it off with
15470 \(setq org-read-date-popup-calendar nil)
15472 With optional argument TO-TIME, the date will immediately be converted
15473 to an internal time.
15474 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15475 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15476 still enter a time, and this function will inform the calling routine
15477 about this change. The calling routine may then choose to change the
15478 format used to insert the time stamp into the buffer to include the time.
15479 With optional argument FROM-STRING, read from this string instead from
15480 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15481 the time/date that is used for everything that is not specified by the
15482 user."
15483 (require 'parse-time)
15484 (let* ((org-time-stamp-rounding-minutes
15485 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15486 (org-dcst org-display-custom-times)
15487 (ct (org-current-time))
15488 (org-def (or org-overriding-default-time default-time ct))
15489 (org-defdecode (decode-time org-def))
15490 (dummy (progn
15491 (when (< (nth 2 org-defdecode) org-extend-today-until)
15492 (setcar (nthcdr 2 org-defdecode) -1)
15493 (setcar (nthcdr 1 org-defdecode) 59)
15494 (setq org-def (apply 'encode-time org-defdecode)
15495 org-defdecode (decode-time org-def)))))
15496 (calendar-frame-setup nil)
15497 (calendar-setup nil)
15498 (calendar-move-hook nil)
15499 (calendar-view-diary-initially-flag nil)
15500 (calendar-view-holidays-initially-flag nil)
15501 (timestr (format-time-string
15502 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15503 (prompt (concat (if prompt (concat prompt " ") "")
15504 (format "Date+time [%s]: " timestr)))
15505 ans (org-ans0 "") org-ans1 org-ans2 final)
15507 (cond
15508 (from-string (setq ans from-string))
15509 (org-read-date-popup-calendar
15510 (save-excursion
15511 (save-window-excursion
15512 (calendar)
15513 (org-eval-in-calendar '(setq cursor-type nil) t)
15514 (unwind-protect
15515 (progn
15516 (calendar-forward-day (- (time-to-days org-def)
15517 (calendar-absolute-from-gregorian
15518 (calendar-current-date))))
15519 (org-eval-in-calendar nil t)
15520 (let* ((old-map (current-local-map))
15521 (map (copy-keymap calendar-mode-map))
15522 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15523 (org-defkey map (kbd "RET") 'org-calendar-select)
15524 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15525 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15526 (org-defkey minibuffer-local-map [(meta shift left)]
15527 (lambda () (interactive)
15528 (org-eval-in-calendar '(calendar-backward-month 1))))
15529 (org-defkey minibuffer-local-map [(meta shift right)]
15530 (lambda () (interactive)
15531 (org-eval-in-calendar '(calendar-forward-month 1))))
15532 (org-defkey minibuffer-local-map [(meta shift up)]
15533 (lambda () (interactive)
15534 (org-eval-in-calendar '(calendar-backward-year 1))))
15535 (org-defkey minibuffer-local-map [(meta shift down)]
15536 (lambda () (interactive)
15537 (org-eval-in-calendar '(calendar-forward-year 1))))
15538 (org-defkey minibuffer-local-map [?\e (shift left)]
15539 (lambda () (interactive)
15540 (org-eval-in-calendar '(calendar-backward-month 1))))
15541 (org-defkey minibuffer-local-map [?\e (shift right)]
15542 (lambda () (interactive)
15543 (org-eval-in-calendar '(calendar-forward-month 1))))
15544 (org-defkey minibuffer-local-map [?\e (shift up)]
15545 (lambda () (interactive)
15546 (org-eval-in-calendar '(calendar-backward-year 1))))
15547 (org-defkey minibuffer-local-map [?\e (shift down)]
15548 (lambda () (interactive)
15549 (org-eval-in-calendar '(calendar-forward-year 1))))
15550 (org-defkey minibuffer-local-map [(shift up)]
15551 (lambda () (interactive)
15552 (org-eval-in-calendar '(calendar-backward-week 1))))
15553 (org-defkey minibuffer-local-map [(shift down)]
15554 (lambda () (interactive)
15555 (org-eval-in-calendar '(calendar-forward-week 1))))
15556 (org-defkey minibuffer-local-map [(shift left)]
15557 (lambda () (interactive)
15558 (org-eval-in-calendar '(calendar-backward-day 1))))
15559 (org-defkey minibuffer-local-map [(shift right)]
15560 (lambda () (interactive)
15561 (org-eval-in-calendar '(calendar-forward-day 1))))
15562 (org-defkey minibuffer-local-map ">"
15563 (lambda () (interactive)
15564 (org-eval-in-calendar '(scroll-calendar-left 1))))
15565 (org-defkey minibuffer-local-map "<"
15566 (lambda () (interactive)
15567 (org-eval-in-calendar '(scroll-calendar-right 1))))
15568 (org-defkey minibuffer-local-map "\C-v"
15569 (lambda () (interactive)
15570 (org-eval-in-calendar
15571 '(calendar-scroll-left-three-months 1))))
15572 (org-defkey minibuffer-local-map "\M-v"
15573 (lambda () (interactive)
15574 (org-eval-in-calendar
15575 '(calendar-scroll-right-three-months 1))))
15576 (run-hooks 'org-read-date-minibuffer-setup-hook)
15577 (unwind-protect
15578 (progn
15579 (use-local-map map)
15580 (setq org-read-date-inactive inactive)
15581 (add-hook 'post-command-hook 'org-read-date-display)
15582 (setq org-ans0 (read-string prompt default-input
15583 'org-read-date-history nil))
15584 ;; org-ans0: from prompt
15585 ;; org-ans1: from mouse click
15586 ;; org-ans2: from calendar motion
15587 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15588 (remove-hook 'post-command-hook 'org-read-date-display)
15589 (use-local-map old-map)
15590 (when org-read-date-overlay
15591 (delete-overlay org-read-date-overlay)
15592 (setq org-read-date-overlay nil)))))
15593 (bury-buffer "*Calendar*")))))
15595 (t ; Naked prompt only
15596 (unwind-protect
15597 (setq ans (read-string prompt default-input
15598 'org-read-date-history timestr))
15599 (when org-read-date-overlay
15600 (delete-overlay org-read-date-overlay)
15601 (setq org-read-date-overlay nil)))))
15603 (setq final (org-read-date-analyze ans org-def org-defdecode))
15605 (when org-read-date-analyze-forced-year
15606 (message "Year was forced into %s"
15607 (if org-read-date-force-compatible-dates
15608 "compatible range (1970-2037)"
15609 "range representable on this machine"))
15610 (ding))
15612 ;; One round trip to get rid of 34th of August and stuff like that....
15613 (setq final (decode-time (apply 'encode-time final)))
15615 (setq org-read-date-final-answer ans)
15617 (if to-time
15618 (apply 'encode-time final)
15619 (if (and (boundp 'org-time-was-given) org-time-was-given)
15620 (format "%04d-%02d-%02d %02d:%02d"
15621 (nth 5 final) (nth 4 final) (nth 3 final)
15622 (nth 2 final) (nth 1 final))
15623 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15625 (defvar org-def)
15626 (defvar org-defdecode)
15627 (defvar org-with-time)
15628 (defun org-read-date-display ()
15629 "Display the current date prompt interpretation in the minibuffer."
15630 (when org-read-date-display-live
15631 (when org-read-date-overlay
15632 (delete-overlay org-read-date-overlay))
15633 (when (minibufferp (current-buffer))
15634 (save-excursion
15635 (end-of-line 1)
15636 (while (not (equal (buffer-substring
15637 (max (point-min) (- (point) 4)) (point))
15638 " "))
15639 (insert " ")))
15640 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15641 " " (or org-ans1 org-ans2)))
15642 (org-end-time-was-given nil)
15643 (f (org-read-date-analyze ans org-def org-defdecode))
15644 (fmts (if org-dcst
15645 org-time-stamp-custom-formats
15646 org-time-stamp-formats))
15647 (fmt (if (or org-with-time
15648 (and (boundp 'org-time-was-given) org-time-was-given))
15649 (cdr fmts)
15650 (car fmts)))
15651 (txt (format-time-string fmt (apply 'encode-time f)))
15652 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15653 (txt (concat "=> " txt)))
15654 (when (and org-end-time-was-given
15655 (string-match org-plain-time-of-day-regexp txt))
15656 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15657 org-end-time-was-given
15658 (substring txt (match-end 0)))))
15659 (when org-read-date-analyze-futurep
15660 (setq txt (concat txt " (=>F)")))
15661 (setq org-read-date-overlay
15662 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15663 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15665 (defun org-read-date-analyze (ans org-def org-defdecode)
15666 "Analyze the combined answer of the date prompt."
15667 ;; FIXME: cleanup and comment
15668 (let ((nowdecode (decode-time (current-time)))
15669 delta deltan deltaw deltadef year month day
15670 hour minute second wday pm h2 m2 tl wday1
15671 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15672 (setq org-read-date-analyze-futurep nil
15673 org-read-date-analyze-forced-year nil)
15674 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15675 (setq ans "+0"))
15677 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15678 (setq ans (replace-match "" t t ans)
15679 deltan (car delta)
15680 deltaw (nth 1 delta)
15681 deltadef (nth 2 delta)))
15683 ;; Check if there is an iso week date in there. If yes, store the
15684 ;; info and postpone interpreting it until the rest of the parsing
15685 ;; is done.
15686 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15687 (setq iso-year (if (match-end 1)
15688 (org-small-year-to-year
15689 (string-to-number (match-string 1 ans))))
15690 iso-weekday (if (match-end 3)
15691 (string-to-number (match-string 3 ans)))
15692 iso-week (string-to-number (match-string 2 ans)))
15693 (setq ans (replace-match "" t t ans)))
15695 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15696 (when (string-match
15697 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15698 (setq year (if (match-end 2)
15699 (string-to-number (match-string 2 ans))
15700 (progn (setq kill-year t)
15701 (string-to-number (format-time-string "%Y"))))
15702 month (string-to-number (match-string 3 ans))
15703 day (string-to-number (match-string 4 ans)))
15704 (if (< year 100) (setq year (+ 2000 year)))
15705 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15706 t nil ans)))
15708 ;; Help matching dotted european dates
15709 (when (string-match
15710 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15711 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15712 (setq kill-year t)
15713 (string-to-number (format-time-string "%Y")))
15714 day (string-to-number (match-string 1 ans))
15715 month (string-to-number (match-string 2 ans))
15716 ans (replace-match (format "%04d-%02d-%02d" year month day)
15717 t nil ans)))
15719 ;; Help matching american dates, like 5/30 or 5/30/7
15720 (when (string-match
15721 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15722 (setq year (if (match-end 4)
15723 (string-to-number (match-string 4 ans))
15724 (progn (setq kill-year t)
15725 (string-to-number (format-time-string "%Y"))))
15726 month (string-to-number (match-string 1 ans))
15727 day (string-to-number (match-string 2 ans)))
15728 (if (< year 100) (setq year (+ 2000 year)))
15729 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15730 t nil ans)))
15731 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15732 ;; If there is a time with am/pm, and *no* time without it, we convert
15733 ;; so that matching will be successful.
15734 (loop for i from 1 to 2 do ; twice, for end time as well
15735 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15736 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15737 (setq hour (string-to-number (match-string 1 ans))
15738 minute (if (match-end 3)
15739 (string-to-number (match-string 3 ans))
15741 pm (equal ?p
15742 (string-to-char (downcase (match-string 4 ans)))))
15743 (if (and (= hour 12) (not pm))
15744 (setq hour 0)
15745 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15746 (setq ans (replace-match (format "%02d:%02d" hour minute)
15747 t t ans))))
15749 ;; Check if a time range is given as a duration
15750 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15751 (setq hour (string-to-number (match-string 1 ans))
15752 h2 (+ hour (string-to-number (match-string 3 ans)))
15753 minute (string-to-number (match-string 2 ans))
15754 m2 (+ minute (if (match-end 5) (string-to-number
15755 (match-string 5 ans))0)))
15756 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15757 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15758 t t ans)))
15760 ;; Check if there is a time range
15761 (when (boundp 'org-end-time-was-given)
15762 (setq org-time-was-given nil)
15763 (when (and (string-match org-plain-time-of-day-regexp ans)
15764 (match-end 8))
15765 (setq org-end-time-was-given (match-string 8 ans))
15766 (setq ans (concat (substring ans 0 (match-beginning 7))
15767 (substring ans (match-end 7))))))
15769 (setq tl (parse-time-string ans)
15770 day (or (nth 3 tl) (nth 3 org-defdecode))
15771 month (or (nth 4 tl)
15772 (if (and org-read-date-prefer-future
15773 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15774 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15775 (nth 4 org-defdecode)))
15776 year (or (and (not kill-year) (nth 5 tl))
15777 (if (and org-read-date-prefer-future
15778 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15779 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15780 (nth 5 org-defdecode)))
15781 hour (or (nth 2 tl) (nth 2 org-defdecode))
15782 minute (or (nth 1 tl) (nth 1 org-defdecode))
15783 second (or (nth 0 tl) 0)
15784 wday (nth 6 tl))
15786 (when (and (eq org-read-date-prefer-future 'time)
15787 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15788 (equal day (nth 3 nowdecode))
15789 (equal month (nth 4 nowdecode))
15790 (equal year (nth 5 nowdecode))
15791 (nth 2 tl)
15792 (or (< (nth 2 tl) (nth 2 nowdecode))
15793 (and (= (nth 2 tl) (nth 2 nowdecode))
15794 (nth 1 tl)
15795 (< (nth 1 tl) (nth 1 nowdecode)))))
15796 (setq day (1+ day)
15797 futurep t))
15799 ;; Special date definitions below
15800 (cond
15801 (iso-week
15802 ;; There was an iso week
15803 (require 'cal-iso)
15804 (setq futurep nil)
15805 (setq year (or iso-year year)
15806 day (or iso-weekday wday 1)
15807 wday nil ; to make sure that the trigger below does not match
15808 iso-date (calendar-gregorian-from-absolute
15809 (calendar-absolute-from-iso
15810 (list iso-week day year))))
15811 ; FIXME: Should we also push ISO weeks into the future?
15812 ; (when (and org-read-date-prefer-future
15813 ; (not iso-year)
15814 ; (< (calendar-absolute-from-gregorian iso-date)
15815 ; (time-to-days (current-time))))
15816 ; (setq year (1+ year)
15817 ; iso-date (calendar-gregorian-from-absolute
15818 ; (calendar-absolute-from-iso
15819 ; (list iso-week day year)))))
15820 (setq month (car iso-date)
15821 year (nth 2 iso-date)
15822 day (nth 1 iso-date)))
15823 (deltan
15824 (setq futurep nil)
15825 (unless deltadef
15826 (let ((now (decode-time (current-time))))
15827 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15828 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15829 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15830 ((equal deltaw "m") (setq month (+ month deltan)))
15831 ((equal deltaw "y") (setq year (+ year deltan)))))
15832 ((and wday (not (nth 3 tl)))
15833 ;; Weekday was given, but no day, so pick that day in the week
15834 ;; on or after the derived date.
15835 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15836 (unless (equal wday wday1)
15837 (setq day (+ day (% (- wday wday1 -7) 7))))))
15838 (if (and (boundp 'org-time-was-given)
15839 (nth 2 tl))
15840 (setq org-time-was-given t))
15841 (if (< year 100) (setq year (+ 2000 year)))
15842 ;; Check of the date is representable
15843 (if org-read-date-force-compatible-dates
15844 (progn
15845 (if (< year 1970)
15846 (setq year 1970 org-read-date-analyze-forced-year t))
15847 (if (> year 2037)
15848 (setq year 2037 org-read-date-analyze-forced-year t)))
15849 (condition-case nil
15850 (ignore (encode-time second minute hour day month year))
15851 (error
15852 (setq year (nth 5 org-defdecode))
15853 (setq org-read-date-analyze-forced-year t))))
15854 (setq org-read-date-analyze-futurep futurep)
15855 (list second minute hour day month year)))
15857 (defvar parse-time-weekdays)
15858 (defun org-read-date-get-relative (s today default)
15859 "Check string S for special relative date string.
15860 TODAY and DEFAULT are internal times, for today and for a default.
15861 Return shift list (N what def-flag)
15862 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15863 N is the number of WHATs to shift.
15864 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15865 the DEFAULT date rather than TODAY."
15866 (require 'parse-time)
15867 (when (and
15868 (string-match
15869 (concat
15870 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15871 "\\([0-9]+\\)?"
15872 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15873 "\\([ \t]\\|$\\)") s)
15874 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15875 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15876 (string-to-char (substring (match-string 1 s) -1))
15877 ?+))
15878 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15879 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15880 (what (if (match-end 3) (match-string 3 s) "d"))
15881 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15882 (date (if rel default today))
15883 (wday (nth 6 (decode-time date)))
15884 delta)
15885 (if wday1
15886 (progn
15887 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15888 (if (= dir ?-) (setq delta (- delta 7)))
15889 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15890 (list delta "d" rel))
15891 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15893 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15894 "Turn a user-specified date into the internal representation.
15895 The internal representation needed by the calendar is (month day year).
15896 This is a wrapper to handle the brain-dead convention in calendar that
15897 user function argument order change dependent on argument order."
15898 (if (boundp 'calendar-date-style)
15899 (cond
15900 ((eq calendar-date-style 'american)
15901 (list arg1 arg2 arg3))
15902 ((eq calendar-date-style 'european)
15903 (list arg2 arg1 arg3))
15904 ((eq calendar-date-style 'iso)
15905 (list arg2 arg3 arg1)))
15906 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15907 (if (org-bound-and-true-p european-calendar-style)
15908 (list arg2 arg1 arg3)
15909 (list arg1 arg2 arg3)))))
15911 (defun org-eval-in-calendar (form &optional keepdate)
15912 "Eval FORM in the calendar window and return to current window.
15913 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15914 otherwise stick to the current value of `org-ans2'."
15915 (let ((sf (selected-frame))
15916 (sw (selected-window)))
15917 (select-window (get-buffer-window "*Calendar*" t))
15918 (eval form)
15919 (when (and (not keepdate) (calendar-cursor-to-date))
15920 (let* ((date (calendar-cursor-to-date))
15921 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15922 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15923 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15924 (select-window sw)
15925 (org-select-frame-set-input-focus sf)))
15927 (defun org-calendar-select ()
15928 "Return to `org-read-date' with the date currently selected.
15929 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15930 (interactive)
15931 (when (calendar-cursor-to-date)
15932 (let* ((date (calendar-cursor-to-date))
15933 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15934 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15935 (if (active-minibuffer-window) (exit-minibuffer))))
15937 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15938 "Insert a date stamp for the date given by the internal TIME.
15939 WITH-HM means use the stamp format that includes the time of the day.
15940 INACTIVE means use square brackets instead of angular ones, so that the
15941 stamp will not contribute to the agenda.
15942 PRE and POST are optional strings to be inserted before and after the
15943 stamp.
15944 The command returns the inserted time stamp."
15945 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15946 stamp)
15947 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15948 (insert-before-markers (or pre ""))
15949 (when (listp extra)
15950 (setq extra (car extra))
15951 (if (and (stringp extra)
15952 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15953 (setq extra (format "-%02d:%02d"
15954 (string-to-number (match-string 1 extra))
15955 (string-to-number (match-string 2 extra))))
15956 (setq extra nil)))
15957 (when extra
15958 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15959 (insert-before-markers (setq stamp (format-time-string fmt time)))
15960 (insert-before-markers (or post ""))
15961 (setq org-last-inserted-timestamp stamp)))
15963 (defun org-toggle-time-stamp-overlays ()
15964 "Toggle the use of custom time stamp formats."
15965 (interactive)
15966 (setq org-display-custom-times (not org-display-custom-times))
15967 (unless org-display-custom-times
15968 (let ((p (point-min)) (bmp (buffer-modified-p)))
15969 (while (setq p (next-single-property-change p 'display))
15970 (if (and (get-text-property p 'display)
15971 (eq (get-text-property p 'face) 'org-date))
15972 (remove-text-properties
15973 p (setq p (next-single-property-change p 'display))
15974 '(display t))))
15975 (set-buffer-modified-p bmp)))
15976 (if (featurep 'xemacs)
15977 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15978 (org-restart-font-lock)
15979 (setq org-table-may-need-update t)
15980 (if org-display-custom-times
15981 (message "Time stamps are overlaid with custom format")
15982 (message "Time stamp overlays removed")))
15984 (defun org-display-custom-time (beg end)
15985 "Overlay modified time stamp format over timestamp between BEG and END."
15986 (let* ((ts (buffer-substring beg end))
15987 t1 w1 with-hm tf time str w2 (off 0))
15988 (save-match-data
15989 (setq t1 (org-parse-time-string ts t))
15990 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15991 (setq off (- (match-end 0) (match-beginning 0)))))
15992 (setq end (- end off))
15993 (setq w1 (- end beg)
15994 with-hm (and (nth 1 t1) (nth 2 t1))
15995 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15996 time (org-fix-decoded-time t1)
15997 str (org-add-props
15998 (format-time-string
15999 (substring tf 1 -1) (apply 'encode-time time))
16000 nil 'mouse-face 'highlight)
16001 w2 (length str))
16002 (if (not (= w2 w1))
16003 (add-text-properties (1+ beg) (+ 2 beg)
16004 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16005 (if (featurep 'xemacs)
16006 (progn
16007 (put-text-property beg end 'invisible t)
16008 (put-text-property beg end 'end-glyph (make-glyph str)))
16009 (put-text-property beg end 'display str))))
16011 (defun org-translate-time (string)
16012 "Translate all timestamps in STRING to custom format.
16013 But do this only if the variable `org-display-custom-times' is set."
16014 (when org-display-custom-times
16015 (save-match-data
16016 (let* ((start 0)
16017 (re org-ts-regexp-both)
16018 t1 with-hm inactive tf time str beg end)
16019 (while (setq start (string-match re string start))
16020 (setq beg (match-beginning 0)
16021 end (match-end 0)
16022 t1 (save-match-data
16023 (org-parse-time-string (substring string beg end) t))
16024 with-hm (and (nth 1 t1) (nth 2 t1))
16025 inactive (equal (substring string beg (1+ beg)) "[")
16026 tf (funcall (if with-hm 'cdr 'car)
16027 org-time-stamp-custom-formats)
16028 time (org-fix-decoded-time t1)
16029 str (format-time-string
16030 (concat
16031 (if inactive "[" "<") (substring tf 1 -1)
16032 (if inactive "]" ">"))
16033 (apply 'encode-time time))
16034 string (replace-match str t t string)
16035 start (+ start (length str)))))))
16036 string)
16038 (defun org-fix-decoded-time (time)
16039 "Set 0 instead of nil for the first 6 elements of time.
16040 Don't touch the rest."
16041 (let ((n 0))
16042 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16044 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16046 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16047 "Difference between TIMESTAMP-STRING and now in days.
16048 If SECONDS is non-nil, return the difference in seconds."
16049 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16050 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16051 (funcall fdiff (current-time)))))
16053 (defun org-deadline-close (timestamp-string &optional ndays)
16054 "Is the time in TIMESTAMP-STRING close to the current date?"
16055 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16056 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16057 (not (org-entry-is-done-p))))
16059 (defun org-get-wdays (ts)
16060 "Get the deadline lead time appropriate for timestring TS."
16061 (cond
16062 ((<= org-deadline-warning-days 0)
16063 ;; 0 or negative, enforce this value no matter what
16064 (- org-deadline-warning-days))
16065 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16066 ;; lead time is specified.
16067 (floor (* (string-to-number (match-string 1 ts))
16068 (cdr (assoc (match-string 2 ts)
16069 '(("d" . 1) ("w" . 7)
16070 ("m" . 30.4) ("y" . 365.25)))))))
16071 ;; go for the default.
16072 (t org-deadline-warning-days)))
16074 (defun org-calendar-select-mouse (ev)
16075 "Return to `org-read-date' with the date currently selected.
16076 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16077 (interactive "e")
16078 (mouse-set-point ev)
16079 (when (calendar-cursor-to-date)
16080 (let* ((date (calendar-cursor-to-date))
16081 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16082 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16083 (if (active-minibuffer-window) (exit-minibuffer))))
16085 (defun org-check-deadlines (ndays)
16086 "Check if there are any deadlines due or past due.
16087 A deadline is considered due if it happens within `org-deadline-warning-days'
16088 days from today's date. If the deadline appears in an entry marked DONE,
16089 it is not shown. The prefix arg NDAYS can be used to test that many
16090 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16091 (interactive "P")
16092 (let* ((org-warn-days
16093 (cond
16094 ((equal ndays '(4)) 100000)
16095 (ndays (prefix-numeric-value ndays))
16096 (t (abs org-deadline-warning-days))))
16097 (case-fold-search nil)
16098 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16099 (callback
16100 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16102 (message "%d deadlines past-due or due within %d days"
16103 (org-occur regexp nil callback)
16104 org-warn-days)))
16106 (defsubst org-re-timestamp (type)
16107 "Return a regexp for timestamp TYPE.
16108 Allowed values for TYPE are:
16110 all: all timestamps
16111 active: only active timestamps (<...>)
16112 inactive: only inactive timestamps ([...])
16113 scheduled: only scheduled timestamps
16114 deadline: only deadline timestamps
16116 When TYPE is nil, fall back on returning a regexp that matches
16117 both scheduled and deadline timestamps."
16118 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16119 ((eq type 'active) org-ts-regexp)
16120 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16121 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16122 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16123 ((eq type 'scheduled-or-deadline)
16124 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16126 (defun org-check-before-date (date)
16127 "Check if there are deadlines or scheduled entries before DATE."
16128 (interactive (list (org-read-date)))
16129 (let ((case-fold-search nil)
16130 (regexp (org-re-timestamp org-ts-type))
16131 (callback
16132 (lambda () (time-less-p
16133 (org-time-string-to-time (match-string 1))
16134 (org-time-string-to-time date)))))
16135 (message "%d entries before %s"
16136 (org-occur regexp nil callback) date)))
16138 (defun org-check-after-date (date)
16139 "Check if there are deadlines or scheduled entries after DATE."
16140 (interactive (list (org-read-date)))
16141 (let ((case-fold-search nil)
16142 (regexp (org-re-timestamp org-ts-type))
16143 (callback
16144 (lambda () (not
16145 (time-less-p
16146 (org-time-string-to-time (match-string 1))
16147 (org-time-string-to-time date))))))
16148 (message "%d entries after %s"
16149 (org-occur regexp nil callback) date)))
16151 (defun org-check-dates-range (start-date end-date)
16152 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16153 (interactive (list (org-read-date nil nil nil "Range starts")
16154 (org-read-date nil nil nil "Range end")))
16155 (let ((case-fold-search nil)
16156 (regexp (org-re-timestamp org-ts-type))
16157 (callback
16158 (lambda ()
16159 (let ((match (match-string 1)))
16160 (and
16161 (not (time-less-p
16162 (org-time-string-to-time match)
16163 (org-time-string-to-time start-date)))
16164 (time-less-p
16165 (org-time-string-to-time match)
16166 (org-time-string-to-time end-date)))))))
16167 (message "%d entries between %s and %s"
16168 (org-occur regexp nil callback) start-date end-date)))
16170 (defun org-evaluate-time-range (&optional to-buffer)
16171 "Evaluate a time range by computing the difference between start and end.
16172 Normally the result is just printed in the echo area, but with prefix arg
16173 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16174 If the time range is actually in a table, the result is inserted into the
16175 next column.
16176 For time difference computation, a year is assumed to be exactly 365
16177 days in order to avoid rounding problems."
16178 (interactive "P")
16180 (org-clock-update-time-maybe)
16181 (save-excursion
16182 (unless (org-at-date-range-p t)
16183 (goto-char (point-at-bol))
16184 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16185 (if (not (org-at-date-range-p t))
16186 (error "Not at a time-stamp range, and none found in current line")))
16187 (let* ((ts1 (match-string 1))
16188 (ts2 (match-string 2))
16189 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16190 (match-end (match-end 0))
16191 (time1 (org-time-string-to-time ts1))
16192 (time2 (org-time-string-to-time ts2))
16193 (t1 (org-float-time time1))
16194 (t2 (org-float-time time2))
16195 (diff (abs (- t2 t1)))
16196 (negative (< (- t2 t1) 0))
16197 ;; (ys (floor (* 365 24 60 60)))
16198 (ds (* 24 60 60))
16199 (hs (* 60 60))
16200 (fy "%dy %dd %02d:%02d")
16201 (fy1 "%dy %dd")
16202 (fd "%dd %02d:%02d")
16203 (fd1 "%dd")
16204 (fh "%02d:%02d")
16205 y d h m align)
16206 (if havetime
16207 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16209 d (floor (/ diff ds)) diff (mod diff ds)
16210 h (floor (/ diff hs)) diff (mod diff hs)
16211 m (floor (/ diff 60)))
16212 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16214 d (floor (+ (/ diff ds) 0.5))
16215 h 0 m 0))
16216 (if (not to-buffer)
16217 (message "%s" (org-make-tdiff-string y d h m))
16218 (if (org-at-table-p)
16219 (progn
16220 (goto-char match-end)
16221 (setq align t)
16222 (and (looking-at " *|") (goto-char (match-end 0))))
16223 (goto-char match-end))
16224 (if (looking-at
16225 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16226 (replace-match ""))
16227 (if negative (insert " -"))
16228 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16229 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16230 (insert " " (format fh h m))))
16231 (if align (org-table-align))
16232 (message "Time difference inserted")))))
16234 (defun org-make-tdiff-string (y d h m)
16235 (let ((fmt "")
16236 (l nil))
16237 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16238 l (push y l)))
16239 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16240 l (push d l)))
16241 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16242 l (push h l)))
16243 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16244 l (push m l)))
16245 (apply 'format fmt (nreverse l))))
16247 (defun org-time-string-to-time (s &optional buffer pos)
16248 "Convert a timestamp string into internal time."
16249 (condition-case errdata
16250 (apply 'encode-time (org-parse-time-string s))
16251 (error (error "Bad timestamp `%s'%s\nError was: %s"
16252 s (if (not (and buffer pos))
16254 (format " at %d in buffer `%s'" pos buffer))
16255 (cdr errdata)))))
16257 (defun org-time-string-to-seconds (s)
16258 "Convert a timestamp string to a number of seconds."
16259 (org-float-time (org-time-string-to-time s)))
16261 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16262 "Convert a time stamp to an absolute day number.
16263 If there is a specifier for a cyclic time stamp, get the closest date to
16264 DAYNR.
16265 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16266 The variable date is bound by the calendar when this is called."
16267 (cond
16268 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16269 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16270 daynr
16271 (+ daynr 1000)))
16272 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16273 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16274 (time-to-days (current-time))) (match-string 0 s)
16275 prefer show-all))
16276 (t (time-to-days
16277 (condition-case errdata
16278 (apply 'encode-time (org-parse-time-string s))
16279 (error (error "Bad timestamp `%s'%s\nError was: %s"
16280 s (if (not (and buffer pos))
16282 (format " at %d in buffer `%s'" pos buffer))
16283 (cdr errdata))))))))
16285 (defun org-days-to-iso-week (days)
16286 "Return the iso week number."
16287 (require 'cal-iso)
16288 (car (calendar-iso-from-absolute days)))
16290 (defun org-small-year-to-year (year)
16291 "Convert 2-digit years into 4-digit years.
16292 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16293 The year 2000 cannot be abbreviated. Any year larger than 99
16294 is returned unchanged."
16295 (if (< year 38)
16296 (setq year (+ 2000 year))
16297 (if (< year 100)
16298 (setq year (+ 1900 year))))
16299 year)
16301 (defun org-time-from-absolute (d)
16302 "Return the time corresponding to date D.
16303 D may be an absolute day number, or a calendar-type list (month day year)."
16304 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16305 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16307 (defun org-calendar-holiday ()
16308 "List of holidays, for Diary display in Org-mode."
16309 (require 'holidays)
16310 (let ((hl (funcall
16311 (if (fboundp 'calendar-check-holidays)
16312 'calendar-check-holidays 'check-calendar-holidays) date)))
16313 (if hl (mapconcat 'identity hl "; "))))
16315 (defun org-diary-sexp-entry (sexp entry date)
16316 "Process a SEXP diary ENTRY for DATE."
16317 (require 'diary-lib)
16318 (let ((result (if calendar-debug-sexp
16319 (let ((stack-trace-on-error t))
16320 (eval (car (read-from-string sexp))))
16321 (condition-case nil
16322 (eval (car (read-from-string sexp)))
16323 (error
16324 (beep)
16325 (message "Bad sexp at line %d in %s: %s"
16326 (org-current-line)
16327 (buffer-file-name) sexp)
16328 (sleep-for 2))))))
16329 (cond ((stringp result) (split-string result "; "))
16330 ((and (consp result)
16331 (not (consp (cdr result)))
16332 (stringp (cdr result))) (cdr result))
16333 ((and (consp result)
16334 (stringp (car result))) result)
16335 (result entry))))
16337 (defun org-diary-to-ical-string (frombuf)
16338 "Get iCalendar entries from diary entries in buffer FROMBUF.
16339 This uses the icalendar.el library."
16340 (let* ((tmpdir (if (featurep 'xemacs)
16341 (temp-directory)
16342 temporary-file-directory))
16343 (tmpfile (make-temp-name
16344 (expand-file-name "orgics" tmpdir)))
16345 buf rtn b e)
16346 (with-current-buffer frombuf
16347 (icalendar-export-region (point-min) (point-max) tmpfile)
16348 (setq buf (find-buffer-visiting tmpfile))
16349 (set-buffer buf)
16350 (goto-char (point-min))
16351 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16352 (setq b (match-beginning 0)))
16353 (goto-char (point-max))
16354 (if (re-search-backward "^END:VEVENT" nil t)
16355 (setq e (match-end 0)))
16356 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16357 (kill-buffer buf)
16358 (delete-file tmpfile)
16359 rtn))
16361 (defun org-closest-date (start current change prefer show-all)
16362 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16363 When PREFER is `past', return a date that is either CURRENT or past.
16364 When PREFER is `future', return a date that is either CURRENT or future.
16365 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16366 ;; Make the proper lists from the dates
16367 (catch 'exit
16368 (let ((a1 '(("h" . hour)
16369 ("d" . day)
16370 ("w" . week)
16371 ("m" . month)
16372 ("y" . year)))
16373 (shour (nth 2 (org-parse-time-string start)))
16374 dn dw sday cday n1 n2 n0
16375 d m y y1 y2 date1 date2 nmonths nm ny m2)
16377 (setq start (org-date-to-gregorian start)
16378 current (org-date-to-gregorian
16379 (if show-all
16380 current
16381 (time-to-days (current-time))))
16382 sday (calendar-absolute-from-gregorian start)
16383 cday (calendar-absolute-from-gregorian current))
16385 (if (<= cday sday) (throw 'exit sday))
16387 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16388 (setq dn (string-to-number (match-string 1 change))
16389 dw (cdr (assoc (match-string 2 change) a1)))
16390 (error "Invalid change specifier: %s" change))
16391 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16392 (cond
16393 ((eq dw 'hour)
16394 (let ((missing-hours
16395 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16396 dn)))
16397 (setq n1 (if (zerop missing-hours) cday
16398 (- cday (1+ (floor (/ missing-hours 24)))))
16399 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16400 ((eq dw 'day)
16401 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16402 n2 (+ n1 dn)))
16403 ((eq dw 'year)
16404 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16405 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16406 (setq date1 (list m d y1)
16407 n1 (calendar-absolute-from-gregorian date1)
16408 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16409 n2 (calendar-absolute-from-gregorian date2)))
16410 ((eq dw 'month)
16411 ;; approx number of month between the two dates
16412 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16413 ;; How often does dn fit in there?
16414 (setq d (nth 1 start) m (car start) y (nth 2 start)
16415 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16416 m (+ m nm)
16417 ny (floor (/ m 12))
16418 y (+ y ny)
16419 m (- m (* ny 12)))
16420 (while (> m 12) (setq m (- m 12) y (1+ y)))
16421 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16422 (setq m2 (+ m dn) y2 y)
16423 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16424 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16425 (while (<= n2 cday)
16426 (setq n1 n2 m m2 y y2)
16427 (setq m2 (+ m dn) y2 y)
16428 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16429 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16430 ;; Make sure n1 is the earlier date
16431 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16432 (if show-all
16433 (cond
16434 ((eq prefer 'past) (if (= cday n2) n2 n1))
16435 ((eq prefer 'future) (if (= cday n1) n1 n2))
16436 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16437 (cond
16438 ((eq prefer 'past) (if (= cday n2) n2 n1))
16439 ((eq prefer 'future) (if (= cday n1) n1 n2))
16440 (t (if (= cday n1) n1 n2)))))))
16442 (defun org-date-to-gregorian (date)
16443 "Turn any specification of DATE into a Gregorian date for the calendar."
16444 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16445 ((and (listp date) (= (length date) 3)) date)
16446 ((stringp date)
16447 (setq date (org-parse-time-string date))
16448 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16449 ((listp date)
16450 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16452 (defun org-parse-time-string (s &optional nodefault)
16453 "Parse the standard Org-mode time string.
16454 This should be a lot faster than the normal `parse-time-string'.
16455 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16456 hour and minute fields will be nil if not given."
16457 (if (string-match org-ts-regexp0 s)
16458 (list 0
16459 (if (or (match-beginning 8) (not nodefault))
16460 (string-to-number (or (match-string 8 s) "0")))
16461 (if (or (match-beginning 7) (not nodefault))
16462 (string-to-number (or (match-string 7 s) "0")))
16463 (string-to-number (match-string 4 s))
16464 (string-to-number (match-string 3 s))
16465 (string-to-number (match-string 2 s))
16466 nil nil nil)
16467 (error "Not a standard Org-mode time string: %s" s)))
16469 (defun org-timestamp-up (&optional arg)
16470 "Increase the date item at the cursor by one.
16471 If the cursor is on the year, change the year. If it is on the month,
16472 the day or the time, change that.
16473 With prefix ARG, change by that many units."
16474 (interactive "p")
16475 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16477 (defun org-timestamp-down (&optional arg)
16478 "Decrease the date item at the cursor by one.
16479 If the cursor is on the year, change the year. If it is on the month,
16480 the day or the time, change that.
16481 With prefix ARG, change by that many units."
16482 (interactive "p")
16483 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16485 (defun org-timestamp-up-day (&optional arg)
16486 "Increase the date in the time stamp by one day.
16487 With prefix ARG, change that many days."
16488 (interactive "p")
16489 (if (and (not (org-at-timestamp-p t))
16490 (org-at-heading-p))
16491 (org-todo 'up)
16492 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16494 (defun org-timestamp-down-day (&optional arg)
16495 "Decrease the date in the time stamp by one day.
16496 With prefix ARG, change that many days."
16497 (interactive "p")
16498 (if (and (not (org-at-timestamp-p t))
16499 (org-at-heading-p))
16500 (org-todo 'down)
16501 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16503 (defun org-at-timestamp-p (&optional inactive-ok)
16504 "Determine if the cursor is in or at a timestamp."
16505 (interactive)
16506 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16507 (pos (point))
16508 (ans (or (looking-at tsr)
16509 (save-excursion
16510 (skip-chars-backward "^[<\n\r\t")
16511 (if (> (point) (point-min)) (backward-char 1))
16512 (and (looking-at tsr)
16513 (> (- (match-end 0) pos) -1))))))
16514 (and ans
16515 (boundp 'org-ts-what)
16516 (setq org-ts-what
16517 (cond
16518 ((= pos (match-beginning 0)) 'bracket)
16519 ;; Point is considered to be "on the bracket" whether
16520 ;; it's really on it or right after it.
16521 ((= pos (1- (match-end 0))) 'bracket)
16522 ((= pos (match-end 0)) 'after)
16523 ((org-pos-in-match-range pos 2) 'year)
16524 ((org-pos-in-match-range pos 3) 'month)
16525 ((org-pos-in-match-range pos 7) 'hour)
16526 ((org-pos-in-match-range pos 8) 'minute)
16527 ((or (org-pos-in-match-range pos 4)
16528 (org-pos-in-match-range pos 5)) 'day)
16529 ((and (> pos (or (match-end 8) (match-end 5)))
16530 (< pos (match-end 0)))
16531 (- pos (or (match-end 8) (match-end 5))))
16532 (t 'day))))
16533 ans))
16535 (defun org-toggle-timestamp-type ()
16536 "Toggle the type (<active> or [inactive]) of a time stamp."
16537 (interactive)
16538 (when (org-at-timestamp-p t)
16539 (let ((beg (match-beginning 0)) (end (match-end 0))
16540 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16541 (save-excursion
16542 (goto-char beg)
16543 (while (re-search-forward "[][<>]" end t)
16544 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16545 t t)))
16546 (message "Timestamp is now %sactive"
16547 (if (equal (char-after beg) ?<) "" "in")))))
16549 (defvar org-clock-history) ; defined in org-clock.el
16550 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16551 (defun org-timestamp-change (n &optional what updown)
16552 "Change the date in the time stamp at point.
16553 The date will be changed by N times WHAT. WHAT can be `day', `month',
16554 `year', `minute', `second'. If WHAT is not given, the cursor position
16555 in the timestamp determines what will be changed."
16556 (let ((origin (point)) origin-cat
16557 with-hm inactive
16558 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16559 org-ts-what
16560 extra rem
16561 ts time time0 fixnext clrgx)
16562 (if (not (org-at-timestamp-p t))
16563 (error "Not at a timestamp"))
16564 (if (and (not what) (eq org-ts-what 'bracket))
16565 (org-toggle-timestamp-type)
16566 ;; Point isn't on brackets. Remember the part of the time-stamp
16567 ;; the point was in. Indeed, size of time-stamps may change,
16568 ;; but point must be kept in the same category nonetheless.
16569 (setq origin-cat org-ts-what)
16570 (if (and (not what) (not (eq org-ts-what 'day))
16571 org-display-custom-times
16572 (get-text-property (point) 'display)
16573 (not (get-text-property (1- (point)) 'display)))
16574 (setq org-ts-what 'day))
16575 (setq org-ts-what (or what org-ts-what)
16576 inactive (= (char-after (match-beginning 0)) ?\[)
16577 ts (match-string 0))
16578 (replace-match "")
16579 (if (string-match
16580 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16582 (setq extra (match-string 1 ts)))
16583 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16584 (setq with-hm t))
16585 (setq time0 (org-parse-time-string ts))
16586 (when (and updown
16587 (eq org-ts-what 'minute)
16588 (not current-prefix-arg))
16589 ;; This looks like s-up and s-down. Change by one rounding step.
16590 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16591 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16592 (setcar (cdr time0) (+ (nth 1 time0)
16593 (if (> n 0) (- rem) (- dm rem))))))
16594 (setq time
16595 (encode-time (or (car time0) 0)
16596 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16597 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16598 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16599 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16600 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16601 (nthcdr 6 time0)))
16602 (when (and (member org-ts-what '(hour minute))
16603 extra
16604 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16605 (setq extra (org-modify-ts-extra
16606 extra
16607 (if (eq org-ts-what 'hour) 2 5)
16608 n dm)))
16609 (when (integerp org-ts-what)
16610 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16611 (if (eq what 'calendar)
16612 (let ((cal-date (org-get-date-from-calendar)))
16613 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16614 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16615 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16616 (setcar time0 (or (car time0) 0))
16617 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16618 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16619 (setq time (apply 'encode-time time0))))
16620 ;; Insert the new time-stamp, and ensure point stays in the same
16621 ;; category as before (i.e. not after the last position in that
16622 ;; category).
16623 (let ((pos (point)))
16624 ;; Stay before inserted string. `save-excursion' is of no use.
16625 (setq org-last-changed-timestamp
16626 (org-insert-time-stamp time with-hm inactive nil nil extra))
16627 (goto-char pos))
16628 (save-match-data
16629 (looking-at org-ts-regexp3)
16630 (goto-char (cond
16631 ;; `day' category ends before `hour' if any, or at
16632 ;; the end of the day name.
16633 ((eq origin-cat 'day)
16634 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16635 ((eq origin-cat 'hour) (min (match-end 7) origin))
16636 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16637 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16638 ;; `year' and `month' have both fixed size: point
16639 ;; couldn't have moved into another part.
16640 (t origin))))
16641 ;; Update clock if on a CLOCK line.
16642 (org-clock-update-time-maybe)
16643 ;; Maybe adjust the closest clock in `org-clock-history'
16644 (when org-clock-adjust-closest
16645 (if (not (and (org-at-clock-log-p)
16646 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16647 org-clock-history))))))
16648 (message "No clock to adjust")
16649 (cond ((save-excursion ; fix previous clock?
16650 (re-search-backward org-ts-regexp0 nil t)
16651 (org-looking-back (concat org-clock-string " \\[")))
16652 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16653 ((save-excursion ; fix next clock?
16654 (re-search-backward org-ts-regexp0 nil t)
16655 (looking-at (concat org-ts-regexp0 "\\] =>")))
16656 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16657 (save-window-excursion
16658 ;; Find closest clock to point, adjust the previous/next one in history
16659 (let* ((p (save-excursion (org-back-to-heading t)))
16660 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16661 (clfixnth
16662 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16663 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16664 (if (not clfixpos)
16665 (message "No clock to adjust")
16666 (save-excursion
16667 (org-goto-marker-or-bmk clfixpos)
16668 (org-show-subtree)
16669 (when (re-search-forward clrgx nil t)
16670 (goto-char (match-beginning 1))
16671 (let (org-clock-adjust-closest)
16672 (org-timestamp-change n org-ts-what updown))
16673 (message "Clock adjusted in %s for heading: %s"
16674 (file-name-nondirectory (buffer-file-name))
16675 (org-get-heading t t)))))))))
16676 ;; Try to recenter the calendar window, if any.
16677 (if (and org-calendar-follow-timestamp-change
16678 (get-buffer-window "*Calendar*" t)
16679 (memq org-ts-what '(day month year)))
16680 (org-recenter-calendar (time-to-days time))))))
16682 (defun org-modify-ts-extra (s pos n dm)
16683 "Change the different parts of the lead-time and repeat fields in timestamp."
16684 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16685 ng h m new rem)
16686 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16687 (cond
16688 ((or (org-pos-in-match-range pos 2)
16689 (org-pos-in-match-range pos 3))
16690 (setq m (string-to-number (match-string 3 s))
16691 h (string-to-number (match-string 2 s)))
16692 (if (org-pos-in-match-range pos 2)
16693 (setq h (+ h n))
16694 (setq n (* dm (org-no-warnings (signum n))))
16695 (when (not (= 0 (setq rem (% m dm))))
16696 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16697 (setq m (+ m n)))
16698 (if (< m 0) (setq m (+ m 60) h (1- h)))
16699 (if (> m 59) (setq m (- m 60) h (1+ h)))
16700 (setq h (min 24 (max 0 h)))
16701 (setq ng 1 new (format "-%02d:%02d" h m)))
16702 ((org-pos-in-match-range pos 6)
16703 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16704 ((org-pos-in-match-range pos 5)
16705 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16707 ((org-pos-in-match-range pos 9)
16708 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16709 ((org-pos-in-match-range pos 8)
16710 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16712 (when ng
16713 (setq s (concat
16714 (substring s 0 (match-beginning ng))
16716 (substring s (match-end ng))))))
16719 (defun org-recenter-calendar (date)
16720 "If the calendar is visible, recenter it to DATE."
16721 (let ((cwin (get-buffer-window "*Calendar*" t)))
16722 (when cwin
16723 (let ((calendar-move-hook nil))
16724 (with-selected-window cwin
16725 (calendar-goto-date (if (listp date) date
16726 (calendar-gregorian-from-absolute date))))))))
16728 (defun org-goto-calendar (&optional arg)
16729 "Go to the Emacs calendar at the current date.
16730 If there is a time stamp in the current line, go to that date.
16731 A prefix ARG can be used to force the current date."
16732 (interactive "P")
16733 (let ((tsr org-ts-regexp) diff
16734 (calendar-move-hook nil)
16735 (calendar-view-holidays-initially-flag nil)
16736 (calendar-view-diary-initially-flag nil))
16737 (if (or (org-at-timestamp-p)
16738 (save-excursion
16739 (beginning-of-line 1)
16740 (looking-at (concat ".*" tsr))))
16741 (let ((d1 (time-to-days (current-time)))
16742 (d2 (time-to-days
16743 (org-time-string-to-time (match-string 1)))))
16744 (setq diff (- d2 d1))))
16745 (calendar)
16746 (calendar-goto-today)
16747 (if (and diff (not arg)) (calendar-forward-day diff))))
16749 (defun org-get-date-from-calendar ()
16750 "Return a list (month day year) of date at point in calendar."
16751 (with-current-buffer "*Calendar*"
16752 (save-match-data
16753 (calendar-cursor-to-date))))
16755 (defun org-date-from-calendar ()
16756 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16757 If there is already a time stamp at the cursor position, update it."
16758 (interactive)
16759 (if (org-at-timestamp-p t)
16760 (org-timestamp-change 0 'calendar)
16761 (let ((cal-date (org-get-date-from-calendar)))
16762 (org-insert-time-stamp
16763 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16765 (defun org-minutes-to-clocksum-string (m)
16766 "Format number of minutes as a clocksum string.
16767 The format is determined by `org-time-clocksum-format',
16768 `org-time-clocksum-use-fractional' and
16769 `org-time-clocksum-fractional-format'."
16770 (let ((clocksum "") fmt n)
16771 ;; fractional format
16772 (if org-time-clocksum-use-fractional
16773 (cond
16774 ;; single format string
16775 ((stringp org-time-clocksum-fractional-format)
16776 (format org-time-clocksum-fractional-format (/ m 60.0)))
16777 ;; choice of fractional formats for different time units
16778 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16779 (> (/ (truncate m) (* 365 24 60)) 0))
16780 (format fmt (/ m (* 365 24 60.0))))
16781 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16782 (> (/ (truncate m) (* 30 24 60)) 0))
16783 (format fmt (/ m (* 30 24 60.0))))
16784 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16785 (> (/ (truncate m) (* 7 24 60)) 0))
16786 (format fmt (/ m (* 7 24 60.0))))
16787 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16788 (> (/ (truncate m) (* 24 60)) 0))
16789 (format fmt (/ m (* 24 60.0))))
16790 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16791 (> (/ (truncate m) 60) 0))
16792 (format fmt (/ m 60.0)))
16793 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16794 (format fmt m))
16795 ;; fall back to smallest time unit with a format
16796 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16797 (format fmt (/ m 60.0)))
16798 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16799 (format fmt (/ m (* 24 60.0))))
16800 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16801 (format fmt (/ m (* 7 24 60.0))))
16802 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16803 (format fmt (/ m (* 30 24 60.0))))
16804 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16805 (format fmt (/ m (* 365 24 60.0)))))
16806 ;; standard (non-fractional) format, with single format string
16807 (if (stringp org-time-clocksum-format)
16808 (format org-time-clocksum-format (setq n (/ m 60)) (- m (* 60 n)))
16809 ;; separate formats components
16810 (and (setq fmt (plist-get org-time-clocksum-format :years))
16811 (or (> (setq n (/ (truncate m) (* 365 24 60))) 0)
16812 (plist-get org-time-clocksum-format :require-years))
16813 (setq clocksum (concat clocksum (format fmt n))
16814 m (- m (* n 365 24 60))))
16815 (and (setq fmt (plist-get org-time-clocksum-format :months))
16816 (or (> (setq n (/ (truncate m) (* 30 24 60))) 0)
16817 (plist-get org-time-clocksum-format :require-months))
16818 (setq clocksum (concat clocksum (format fmt n))
16819 m (- m (* n 30 24 60))))
16820 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16821 (or (> (setq n (/ (truncate m) (* 7 24 60))) 0)
16822 (plist-get org-time-clocksum-format :require-weeks))
16823 (setq clocksum (concat clocksum (format fmt n))
16824 m (- m (* n 7 24 60))))
16825 (and (setq fmt (plist-get org-time-clocksum-format :days))
16826 (or (> (setq n (/ (truncate m) (* 24 60))) 0)
16827 (plist-get org-time-clocksum-format :require-days))
16828 (setq clocksum (concat clocksum (format fmt n))
16829 m (- m (* n 24 60))))
16830 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16831 (or (> (setq n (/ (truncate m) 60)) 0)
16832 (plist-get org-time-clocksum-format :require-hours))
16833 (setq clocksum (concat clocksum (format fmt n))
16834 m (- m (* n 60))))
16835 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16836 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16837 (setq clocksum (concat clocksum (format fmt m))))
16838 ;; return formatted time duration
16839 clocksum))))
16841 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16842 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16843 "Org mode version 8.0")
16845 (defun org-hours-to-clocksum-string (n)
16846 (org-minutes-to-clocksum-string (* n 60)))
16848 (defun org-hh:mm-string-to-minutes (s)
16849 "Convert a string H:MM to a number of minutes.
16850 If the string is just a number, interpret it as minutes.
16851 In fact, the first hh:mm or number in the string will be taken,
16852 there can be extra stuff in the string.
16853 If no number is found, the return value is 0."
16854 (cond
16855 ((integerp s) s)
16856 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16857 (+ (* (string-to-number (match-string 1 s)) 60)
16858 (string-to-number (match-string 2 s))))
16859 ((string-match "\\([0-9]+\\)" s)
16860 (string-to-number (match-string 1 s)))
16861 (t 0)))
16863 (defcustom org-effort-durations
16864 `(("h" . 60)
16865 ("d" . ,(* 60 8))
16866 ("w" . ,(* 60 8 5))
16867 ("m" . ,(* 60 8 5 4))
16868 ("y" . ,(* 60 8 5 40)))
16869 "Conversion factor to minutes for an effort modifier.
16871 Each entry has the form (MODIFIER . MINUTES).
16873 In an effort string, a number followed by MODIFIER is multiplied
16874 by the specified number of MINUTES to obtain an effort in
16875 minutes.
16877 For example, if the value of this variable is ((\"hours\" . 60)), then an
16878 effort string \"2hours\" is equivalent to 120 minutes."
16879 :group 'org-agenda
16880 :version "24.1"
16881 :type '(alist :key-type (string :tag "Modifier")
16882 :value-type (number :tag "Minutes")))
16884 (defcustom org-image-actual-width t
16885 "Should we use the actual width of images when inlining them?
16887 When set to `t', always use the image width.
16889 When set to a number, use imagemagick (when available) to set
16890 the image's width to this value.
16892 When set to a number in a list, try to get the width from the
16893 #+ATTR.* keyword if it matches a width specification like
16894 width=\"[0-9]+\", and fall back on that number if none is found.
16896 When set to nil, try to get the width from an #+ATTR.* keyword
16897 and fall back on the original width if none is found.
16899 This requires Emacs >= 24.1, build with imagemagick support."
16900 :group 'org-appearance
16901 :version "24.3"
16902 :type '(choice
16903 (const :tag "Use the image width" t)
16904 (integer :tag "Use a number of pixels")
16905 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16906 (const :tag "Use #+ATTR* or don't resize" nil)))
16908 (defun org-duration-string-to-minutes (s &optional output-to-string)
16909 "Convert a duration string S to minutes.
16911 A bare number is interpreted as minutes, modifiers can be set by
16912 customizing `org-effort-durations' (which see).
16914 Entries containing a colon are interpreted as H:MM by
16915 `org-hh:mm-string-to-minutes'."
16916 (let ((result 0)
16917 (re (concat "\\([0-9.]+\\) *\\("
16918 (regexp-opt (mapcar 'car org-effort-durations))
16919 "\\)")))
16920 (while (string-match re s)
16921 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16922 (string-to-number (match-string 1 s))))
16923 (setq s (replace-match "" nil t s)))
16924 (setq result (floor result))
16925 (incf result (org-hh:mm-string-to-minutes s))
16926 (if output-to-string (number-to-string result) result)))
16928 ;;;; Files
16930 (defun org-save-all-org-buffers ()
16931 "Save all Org-mode buffers without user confirmation."
16932 (interactive)
16933 (message "Saving all Org-mode buffers...")
16934 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16935 (when (featurep 'org-id) (org-id-locations-save))
16936 (message "Saving all Org-mode buffers... done"))
16938 (defun org-revert-all-org-buffers ()
16939 "Revert all Org-mode buffers.
16940 Prompt for confirmation when there are unsaved changes.
16941 Be sure you know what you are doing before letting this function
16942 overwrite your changes.
16944 This function is useful in a setup where one tracks org files
16945 with a version control system, to revert on one machine after pulling
16946 changes from another. I believe the procedure must be like this:
16948 1. M-x org-save-all-org-buffers
16949 2. Pull changes from the other machine, resolve conflicts
16950 3. M-x org-revert-all-org-buffers"
16951 (interactive)
16952 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16953 (error "Abort"))
16954 (save-excursion
16955 (save-window-excursion
16956 (mapc
16957 (lambda (b)
16958 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16959 (with-current-buffer b buffer-file-name))
16960 (org-pop-to-buffer-same-window b)
16961 (revert-buffer t 'no-confirm)))
16962 (buffer-list))
16963 (when (and (featurep 'org-id) org-id-track-globally)
16964 (org-id-locations-load)))))
16966 ;;;; Agenda files
16968 ;;;###autoload
16969 (defun org-switchb (&optional arg)
16970 "Switch between Org buffers.
16971 With one prefix argument, restrict available buffers to files.
16972 With two prefix arguments, restrict available buffers to agenda files.
16974 Defaults to `iswitchb' for buffer name completion.
16975 Set `org-completion-use-ido' to make it use ido instead."
16976 (interactive "P")
16977 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16978 ((equal arg '(16)) (org-buffer-list 'agenda))
16979 (t (org-buffer-list))))
16980 (org-completion-use-iswitchb org-completion-use-iswitchb)
16981 (org-completion-use-ido org-completion-use-ido))
16982 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16983 (setq org-completion-use-iswitchb t))
16984 (org-pop-to-buffer-same-window
16985 (org-icompleting-read "Org buffer: "
16986 (mapcar 'list (mapcar 'buffer-name blist))
16987 nil t))))
16989 ;;; Define some older names previously used for this functionality
16990 ;;;###autoload
16991 (defalias 'org-ido-switchb 'org-switchb)
16992 ;;;###autoload
16993 (defalias 'org-iswitchb 'org-switchb)
16995 (defun org-buffer-list (&optional predicate exclude-tmp)
16996 "Return a list of Org buffers.
16997 PREDICATE can be `export', `files' or `agenda'.
16999 export restrict the list to Export buffers.
17000 files restrict the list to buffers visiting Org files.
17001 agenda restrict the list to buffers visiting agenda files.
17003 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17004 (let* ((bfn nil)
17005 (agenda-files (and (eq predicate 'agenda)
17006 (mapcar 'file-truename (org-agenda-files t))))
17007 (filter
17008 (cond
17009 ((eq predicate 'files)
17010 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17011 ((eq predicate 'export)
17012 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17013 ((eq predicate 'agenda)
17014 (lambda (b)
17015 (with-current-buffer b
17016 (and (derived-mode-p 'org-mode)
17017 (setq bfn (buffer-file-name b))
17018 (member (file-truename bfn) agenda-files)))))
17019 (t (lambda (b) (with-current-buffer b
17020 (or (derived-mode-p 'org-mode)
17021 (string-match "\*Org .*Export"
17022 (buffer-name b)))))))))
17023 (delq nil
17024 (mapcar
17025 (lambda(b)
17026 (if (and (funcall filter b)
17027 (or (not exclude-tmp)
17028 (not (string-match "tmp" (buffer-name b)))))
17030 nil))
17031 (buffer-list)))))
17033 (defun org-agenda-files (&optional unrestricted archives)
17034 "Get the list of agenda files.
17035 Optional UNRESTRICTED means return the full list even if a restriction
17036 is currently in place.
17037 When ARCHIVES is t, include all archive files that are really being
17038 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17039 `org-agenda-archives-mode' is t."
17040 (let ((files
17041 (cond
17042 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17043 ((stringp org-agenda-files) (org-read-agenda-file-list))
17044 ((listp org-agenda-files) org-agenda-files)
17045 (t (error "Invalid value of `org-agenda-files'")))))
17046 (setq files (apply 'append
17047 (mapcar (lambda (f)
17048 (if (file-directory-p f)
17049 (directory-files
17050 f t org-agenda-file-regexp)
17051 (list f)))
17052 files)))
17053 (when org-agenda-skip-unavailable-files
17054 (setq files (delq nil
17055 (mapcar (function
17056 (lambda (file)
17057 (and (file-readable-p file) file)))
17058 files))))
17059 (when (or (eq archives t)
17060 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17061 (setq files (org-add-archive-files files)))
17062 files))
17064 (defun org-agenda-file-p (&optional file)
17065 "Return non-nil, if FILE is an agenda file.
17066 If FILE is omitted, use the file associated with the current
17067 buffer."
17068 (member (or file (buffer-file-name))
17069 (org-agenda-files t)))
17071 (defun org-edit-agenda-file-list ()
17072 "Edit the list of agenda files.
17073 Depending on setup, this either uses customize to edit the variable
17074 `org-agenda-files', or it visits the file that is holding the list. In the
17075 latter case, the buffer is set up in a way that saving it automatically kills
17076 the buffer and restores the previous window configuration."
17077 (interactive)
17078 (if (stringp org-agenda-files)
17079 (let ((cw (current-window-configuration)))
17080 (find-file org-agenda-files)
17081 (org-set-local 'org-window-configuration cw)
17082 (org-add-hook 'after-save-hook
17083 (lambda ()
17084 (set-window-configuration
17085 (prog1 org-window-configuration
17086 (kill-buffer (current-buffer))))
17087 (org-install-agenda-files-menu)
17088 (message "New agenda file list installed"))
17089 nil 'local)
17090 (message "%s" (substitute-command-keys
17091 "Edit list and finish with \\[save-buffer]")))
17092 (customize-variable 'org-agenda-files)))
17094 (defun org-store-new-agenda-file-list (list)
17095 "Set new value for the agenda file list and save it correctly."
17096 (if (stringp org-agenda-files)
17097 (let ((fe (org-read-agenda-file-list t)) b u)
17098 (while (setq b (find-buffer-visiting org-agenda-files))
17099 (kill-buffer b))
17100 (with-temp-file org-agenda-files
17101 (insert
17102 (mapconcat
17103 (lambda (f) ;; Keep un-expanded entries.
17104 (if (setq u (assoc f fe))
17105 (cdr u)
17107 list "\n")
17108 "\n")))
17109 (let ((org-mode-hook nil) (org-inhibit-startup t)
17110 (org-insert-mode-line-in-empty-file nil))
17111 (setq org-agenda-files list)
17112 (customize-save-variable 'org-agenda-files org-agenda-files))))
17114 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17115 "Read the list of agenda files from a file.
17116 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17117 filenames, used by `org-store-new-agenda-file-list' to write back
17118 un-expanded file names."
17119 (when (file-directory-p org-agenda-files)
17120 (error "`org-agenda-files' cannot be a single directory"))
17121 (when (stringp org-agenda-files)
17122 (with-temp-buffer
17123 (insert-file-contents org-agenda-files)
17124 (mapcar
17125 (lambda (f)
17126 (let ((e (expand-file-name (substitute-in-file-name f)
17127 org-directory)))
17128 (if pair-with-expansion
17129 (cons e f)
17130 e)))
17131 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17133 ;;;###autoload
17134 (defun org-cycle-agenda-files ()
17135 "Cycle through the files in `org-agenda-files'.
17136 If the current buffer visits an agenda file, find the next one in the list.
17137 If the current buffer does not, find the first agenda file."
17138 (interactive)
17139 (let* ((fs (org-agenda-files t))
17140 (files (append fs (list (car fs))))
17141 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17142 file)
17143 (unless files (error "No agenda files"))
17144 (catch 'exit
17145 (while (setq file (pop files))
17146 (if (equal (file-truename file) tcf)
17147 (when (car files)
17148 (find-file (car files))
17149 (throw 'exit t))))
17150 (find-file (car fs)))
17151 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17153 (defun org-agenda-file-to-front (&optional to-end)
17154 "Move/add the current file to the top of the agenda file list.
17155 If the file is not present in the list, it is added to the front. If it is
17156 present, it is moved there. With optional argument TO-END, add/move to the
17157 end of the list."
17158 (interactive "P")
17159 (let ((org-agenda-skip-unavailable-files nil)
17160 (file-alist (mapcar (lambda (x)
17161 (cons (file-truename x) x))
17162 (org-agenda-files t)))
17163 (ctf (file-truename
17164 (or buffer-file-name
17165 (error "Please save the current buffer to a file"))))
17166 x had)
17167 (setq x (assoc ctf file-alist) had x)
17169 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17170 (if to-end
17171 (setq file-alist (append (delq x file-alist) (list x)))
17172 (setq file-alist (cons x (delq x file-alist))))
17173 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17174 (org-install-agenda-files-menu)
17175 (message "File %s to %s of agenda file list"
17176 (if had "moved" "added") (if to-end "end" "front"))))
17178 (defun org-remove-file (&optional file)
17179 "Remove current file from the list of files in variable `org-agenda-files'.
17180 These are the files which are being checked for agenda entries.
17181 Optional argument FILE means use this file instead of the current."
17182 (interactive)
17183 (let* ((org-agenda-skip-unavailable-files nil)
17184 (file (or file buffer-file-name
17185 (error "Current buffer does not visit a file")))
17186 (true-file (file-truename file))
17187 (afile (abbreviate-file-name file))
17188 (files (delq nil (mapcar
17189 (lambda (x)
17190 (if (equal true-file
17191 (file-truename x))
17192 nil x))
17193 (org-agenda-files t)))))
17194 (if (not (= (length files) (length (org-agenda-files t))))
17195 (progn
17196 (org-store-new-agenda-file-list files)
17197 (org-install-agenda-files-menu)
17198 (message "Removed file: %s" afile))
17199 (message "File was not in list: %s (not removed)" afile))))
17201 (defun org-file-menu-entry (file)
17202 (vector file (list 'find-file file) t))
17204 (defun org-check-agenda-file (file)
17205 "Make sure FILE exists. If not, ask user what to do."
17206 (when (not (file-exists-p file))
17207 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17208 (abbreviate-file-name file))
17209 (let ((r (downcase (read-char-exclusive))))
17210 (cond
17211 ((equal r ?r)
17212 (org-remove-file file)
17213 (throw 'nextfile t))
17214 (t (error "Abort"))))))
17216 (defun org-get-agenda-file-buffer (file)
17217 "Get a buffer visiting FILE. If the buffer needs to be created, add
17218 it to the list of buffers which might be released later."
17219 (let ((buf (org-find-base-buffer-visiting file)))
17220 (if buf
17221 buf ; just return it
17222 ;; Make a new buffer and remember it
17223 (setq buf (find-file-noselect file))
17224 (if buf (push buf org-agenda-new-buffers))
17225 buf)))
17227 (defun org-release-buffers (blist)
17228 "Release all buffers in list, asking the user for confirmation when needed.
17229 When a buffer is unmodified, it is just killed. When modified, it is saved
17230 \(if the user agrees) and then killed."
17231 (let (buf file)
17232 (while (setq buf (pop blist))
17233 (setq file (buffer-file-name buf))
17234 (when (and (buffer-modified-p buf)
17235 file
17236 (y-or-n-p (format "Save file %s? " file)))
17237 (with-current-buffer buf (save-buffer)))
17238 (kill-buffer buf))))
17240 (defun org-agenda-prepare-buffers (files)
17241 "Create buffers for all agenda files, protect archived trees and comments."
17242 (interactive)
17243 (let ((pa '(:org-archived t))
17244 (pc '(:org-comment t))
17245 (pall '(:org-archived t :org-comment t))
17246 (inhibit-read-only t)
17247 (rea (concat ":" org-archive-tag ":"))
17248 bmp file re)
17249 (save-excursion
17250 (save-restriction
17251 (while (setq file (pop files))
17252 (catch 'nextfile
17253 (if (bufferp file)
17254 (set-buffer file)
17255 (org-check-agenda-file file)
17256 (set-buffer (org-get-agenda-file-buffer file)))
17257 (widen)
17258 (setq bmp (buffer-modified-p))
17259 (org-refresh-category-properties)
17260 (setq org-todo-keywords-for-agenda
17261 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17262 (setq org-done-keywords-for-agenda
17263 (append org-done-keywords-for-agenda org-done-keywords))
17264 (setq org-todo-keyword-alist-for-agenda
17265 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17266 (setq org-drawers-for-agenda
17267 (append org-drawers-for-agenda org-drawers))
17268 (setq org-tag-alist-for-agenda
17269 (append org-tag-alist-for-agenda org-tag-alist))
17271 (save-excursion
17272 (remove-text-properties (point-min) (point-max) pall)
17273 (when org-agenda-skip-archived-trees
17274 (goto-char (point-min))
17275 (while (re-search-forward rea nil t)
17276 (if (org-at-heading-p t)
17277 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17278 (goto-char (point-min))
17279 (setq re (format org-heading-keyword-regexp-format
17280 org-comment-string))
17281 (while (re-search-forward re nil t)
17282 (add-text-properties
17283 (match-beginning 0) (org-end-of-subtree t) pc)))
17284 (set-buffer-modified-p bmp)))))
17285 (setq org-todo-keywords-for-agenda
17286 (org-uniquify org-todo-keywords-for-agenda))
17287 (setq org-todo-keyword-alist-for-agenda
17288 (org-uniquify org-todo-keyword-alist-for-agenda)
17289 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17291 ;;;; Embedded LaTeX
17293 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17294 "Keymap for the minor `org-cdlatex-mode'.")
17296 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17297 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17298 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17299 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17300 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17302 (defvar org-cdlatex-texmathp-advice-is-done nil
17303 "Flag remembering if we have applied the advice to texmathp already.")
17305 (define-minor-mode org-cdlatex-mode
17306 "Toggle the minor `org-cdlatex-mode'.
17307 This mode supports entering LaTeX environment and math in LaTeX fragments
17308 in Org-mode.
17309 \\{org-cdlatex-mode-map}"
17310 nil " OCDL" nil
17311 (when org-cdlatex-mode
17312 (require 'cdlatex)
17313 (run-hooks 'cdlatex-mode-hook)
17314 (cdlatex-compute-tables))
17315 (unless org-cdlatex-texmathp-advice-is-done
17316 (setq org-cdlatex-texmathp-advice-is-done t)
17317 (defadvice texmathp (around org-math-always-on activate)
17318 "Always return t in org-mode buffers.
17319 This is because we want to insert math symbols without dollars even outside
17320 the LaTeX math segments. If Orgmode thinks that point is actually inside
17321 an embedded LaTeX fragment, let texmathp do its job.
17322 \\[org-cdlatex-mode-map]"
17323 (interactive)
17324 (let (p)
17325 (cond
17326 ((not (derived-mode-p 'org-mode)) ad-do-it)
17327 ((eq this-command 'cdlatex-math-symbol)
17328 (setq ad-return-value t
17329 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17331 (let ((p (org-inside-LaTeX-fragment-p)))
17332 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17333 (setq ad-return-value t
17334 texmathp-why '("Org-mode embedded math" . 0))
17335 (if p ad-do-it)))))))))
17337 (defun turn-on-org-cdlatex ()
17338 "Unconditionally turn on `org-cdlatex-mode'."
17339 (org-cdlatex-mode 1))
17341 (defun org-inside-LaTeX-fragment-p ()
17342 "Test if point is inside a LaTeX fragment.
17343 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17344 sequence appearing also before point.
17345 Even though the matchers for math are configurable, this function assumes
17346 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17347 delimiters are skipped when they have been removed by customization.
17348 The return value is nil, or a cons cell with the delimiter and the
17349 position of this delimiter.
17351 This function does a reasonably good job, but can locally be fooled by
17352 for example currency specifications. For example it will assume being in
17353 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17354 fragments that are properly closed, but during editing, we have to live
17355 with the uncertainty caused by missing closing delimiters. This function
17356 looks only before point, not after."
17357 (catch 'exit
17358 (let ((pos (point))
17359 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17360 (lim (progn
17361 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17362 (point)))
17363 dd-on str (start 0) m re)
17364 (goto-char pos)
17365 (when dodollar
17366 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17367 re (nth 1 (assoc "$" org-latex-regexps)))
17368 (while (string-match re str start)
17369 (cond
17370 ((= (match-end 0) (length str))
17371 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17372 ((= (match-end 0) (- (length str) 5))
17373 (throw 'exit nil))
17374 (t (setq start (match-end 0))))))
17375 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17376 (goto-char pos)
17377 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17378 (and (match-beginning 2) (throw 'exit nil))
17379 ;; count $$
17380 (while (re-search-backward "\\$\\$" lim t)
17381 (setq dd-on (not dd-on)))
17382 (goto-char pos)
17383 (if dd-on (cons "$$" m))))))
17385 (defun org-inside-latex-macro-p ()
17386 "Is point inside a LaTeX macro or its arguments?"
17387 (save-match-data
17388 (org-in-regexp
17389 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17391 (defun org-try-cdlatex-tab ()
17392 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17393 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17394 - inside a LaTeX fragment, or
17395 - after the first word in a line, where an abbreviation expansion could
17396 insert a LaTeX environment."
17397 (when org-cdlatex-mode
17398 (cond
17399 ;; Before any word on the line: No expansion possible.
17400 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17401 ;; Just after first word on the line: Expand it. Make sure it
17402 ;; cannot happen on headlines, though.
17403 ((save-excursion
17404 (skip-chars-backward "a-zA-Z0-9*")
17405 (skip-chars-backward " \t")
17406 (and (bolp) (not (org-at-heading-p))))
17407 (cdlatex-tab) t)
17408 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17410 (defun org-cdlatex-underscore-caret (&optional arg)
17411 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17412 Revert to the normal definition outside of these fragments."
17413 (interactive "P")
17414 (if (org-inside-LaTeX-fragment-p)
17415 (call-interactively 'cdlatex-sub-superscript)
17416 (let (org-cdlatex-mode)
17417 (call-interactively (key-binding (vector last-input-event))))))
17419 (defun org-cdlatex-math-modify (&optional arg)
17420 "Execute `cdlatex-math-modify' in LaTeX fragments.
17421 Revert to the normal definition outside of these fragments."
17422 (interactive "P")
17423 (if (org-inside-LaTeX-fragment-p)
17424 (call-interactively 'cdlatex-math-modify)
17425 (let (org-cdlatex-mode)
17426 (call-interactively (key-binding (vector last-input-event))))))
17428 (defvar org-latex-fragment-image-overlays nil
17429 "List of overlays carrying the images of latex fragments.")
17430 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17432 (defun org-remove-latex-fragment-image-overlays ()
17433 "Remove all overlays with LaTeX fragment images in current buffer."
17434 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17435 (setq org-latex-fragment-image-overlays nil))
17437 (defun org-preview-latex-fragment (&optional subtree)
17438 "Preview the LaTeX fragment at point, or all locally or globally.
17439 If the cursor is in a LaTeX fragment, create the image and overlay
17440 it over the source code. If there is no fragment at point, display
17441 all fragments in the current text, from one headline to the next. With
17442 prefix SUBTREE, display all fragments in the current subtree. With a
17443 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17444 the cursor is before the first headline,
17445 display all fragments in the buffer.
17446 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17447 (interactive "P")
17448 (unless buffer-file-name
17449 (error "Can't preview LaTeX fragment in a non-file buffer"))
17450 (org-remove-latex-fragment-image-overlays)
17451 (save-excursion
17452 (save-restriction
17453 (let (beg end at msg)
17454 (cond
17455 ((or (equal subtree '(16))
17456 (not (save-excursion
17457 (re-search-backward org-outline-regexp-bol nil t))))
17458 (setq beg (point-min) end (point-max)
17459 msg "Creating images for buffer...%s"))
17460 ((equal subtree '(4))
17461 (org-back-to-heading)
17462 (setq beg (point) end (org-end-of-subtree t)
17463 msg "Creating images for subtree...%s"))
17465 (if (setq at (org-inside-LaTeX-fragment-p))
17466 (goto-char (max (point-min) (- (cdr at) 2)))
17467 (org-back-to-heading))
17468 (setq beg (point) end (progn (outline-next-heading) (point))
17469 msg (if at "Creating image...%s"
17470 "Creating images for entry...%s"))))
17471 (message msg "")
17472 (narrow-to-region beg end)
17473 (goto-char beg)
17474 (org-format-latex
17475 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17476 (file-name-nondirectory
17477 buffer-file-name)))
17478 default-directory 'overlays msg at 'forbuffer
17479 org-latex-create-formula-image-program)
17480 (message msg "done. Use `C-c C-c' to remove images.")))))
17482 (defvar org-latex-regexps
17483 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17484 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17485 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17486 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17487 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17488 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17489 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17490 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17491 "Regular expressions for matching embedded LaTeX.")
17493 (defvar org-export-have-math nil) ;; dynamic scoping
17494 (defun org-format-latex (prefix &optional dir overlays msg at
17495 forbuffer processing-type)
17496 "Replace LaTeX fragments with links to an image, and produce images.
17497 Some of the options can be changed using the variable
17498 `org-format-latex-options'."
17499 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17500 (let* ((prefixnodir (file-name-nondirectory prefix))
17501 (absprefix (expand-file-name prefix dir))
17502 (todir (file-name-directory absprefix))
17503 (opt org-format-latex-options)
17504 (optnew org-format-latex-options)
17505 (matchers (plist-get opt :matchers))
17506 (re-list org-latex-regexps)
17507 (org-format-latex-header-extra
17508 (plist-get (org-infile-export-plist) :latex-header-extra))
17509 (cnt 0) txt hash link beg end re e checkdir
17510 string
17511 m n block-type block linkfile movefile ov)
17512 ;; Check the different regular expressions
17513 (while (setq e (pop re-list))
17514 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17515 block (if block-type "\n\n" ""))
17516 (when (member m matchers)
17517 (goto-char (point-min))
17518 (while (re-search-forward re nil t)
17519 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17520 (not (get-text-property (match-beginning n)
17521 'org-protected))
17522 (or (not overlays)
17523 (not (eq (get-char-property (match-beginning n)
17524 'org-overlay-type)
17525 'org-latex-overlay))))
17526 (setq org-export-have-math t)
17527 (cond
17528 ((eq processing-type 'verbatim)
17529 ;; Leave the text verbatim, just protect it
17530 (add-text-properties (match-beginning n) (match-end n)
17531 '(org-protected t)))
17532 ((eq processing-type 'mathjax)
17533 ;; Prepare for MathJax processing
17534 (setq string (match-string n))
17535 (if (member m '("$" "$1"))
17536 (save-excursion
17537 (delete-region (match-beginning n) (match-end n))
17538 (goto-char (match-beginning n))
17539 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17540 "\\)")
17541 '(org-protected t))))
17542 (add-text-properties (match-beginning n) (match-end n)
17543 '(org-protected t))))
17544 ((or (eq processing-type 'dvipng)
17545 (eq processing-type 'imagemagick))
17546 ;; Process to an image
17547 (setq txt (match-string n)
17548 beg (match-beginning n) end (match-end n)
17549 cnt (1+ cnt))
17550 (let ((face (face-at-point))
17551 (fg (plist-get opt :foreground))
17552 (bg (plist-get opt :background))
17553 print-length print-level) ; make sure full list is printed
17554 (when forbuffer
17555 ; Get the colors from the face at point
17556 (goto-char beg)
17557 (when (eq fg 'auto)
17558 (setq fg (face-attribute face :foreground nil 'default)))
17559 (when (eq bg 'auto)
17560 (setq bg (face-attribute face :background nil 'default)))
17561 (setq optnew (copy-sequence opt))
17562 (plist-put optnew :foreground fg)
17563 (plist-put optnew :background bg))
17564 (setq hash (sha1 (prin1-to-string
17565 (list org-format-latex-header
17566 org-format-latex-header-extra
17567 org-export-latex-default-packages-alist
17568 org-export-latex-packages-alist
17569 org-format-latex-options
17570 forbuffer txt fg bg)))
17571 linkfile (format "%s_%s.png" prefix hash)
17572 movefile (format "%s_%s.png" absprefix hash)))
17573 (setq link (concat block "[[file:" linkfile "]]" block))
17574 (if msg (message msg cnt))
17575 (goto-char beg)
17576 (unless checkdir ; make sure the directory exists
17577 (setq checkdir t)
17578 (or (file-directory-p todir) (make-directory todir t)))
17579 (org-create-formula-image
17580 txt movefile optnew forbuffer processing-type)
17581 (if overlays
17582 (progn
17583 (mapc (lambda (o)
17584 (if (eq (overlay-get o 'org-overlay-type)
17585 'org-latex-overlay)
17586 (delete-overlay o)))
17587 (overlays-in beg end))
17588 (setq ov (make-overlay beg end))
17589 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17590 (if (featurep 'xemacs)
17591 (progn
17592 (overlay-put ov 'invisible t)
17593 (overlay-put
17594 ov 'end-glyph
17595 (make-glyph (vector 'png :file movefile))))
17596 (overlay-put
17597 ov 'display
17598 (list 'image :type 'png :file movefile :ascent 'center)))
17599 (push ov org-latex-fragment-image-overlays)
17600 (goto-char end))
17601 (delete-region beg end)
17602 (insert (org-add-props link
17603 (list 'org-latex-src
17604 (replace-regexp-in-string
17605 "\"" "" txt)
17606 'org-latex-src-embed-type
17607 (if block-type 'paragraph 'character))))))
17608 ((eq processing-type 'mathml)
17609 ;; Process to MathML
17610 (unless (save-match-data (org-format-latex-mathml-available-p))
17611 (error "LaTeX to MathML converter not configured"))
17612 (setq txt (match-string n)
17613 beg (match-beginning n) end (match-end n)
17614 cnt (1+ cnt))
17615 (if msg (message msg cnt))
17616 (goto-char beg)
17617 (delete-region beg end)
17618 (insert (org-format-latex-as-mathml
17619 txt block-type prefix dir)))
17621 (error "Unknown conversion type %s for latex fragments"
17622 processing-type)))))))))
17624 (defun org-create-math-formula (latex-frag &optional mathml-file)
17625 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17626 Use `org-latex-to-mathml-convert-command'. If the conversion is
17627 sucessful, return the portion between \"<math...> </math>\"
17628 elements otherwise return nil. When MATHML-FILE is specified,
17629 write the results in to that file. When invoked as an
17630 interactive command, prompt for LATEX-FRAG, with initial value
17631 set to the current active region and echo the results for user
17632 inspection."
17633 (interactive (list (let ((frag (when (org-region-active-p)
17634 (buffer-substring-no-properties
17635 (region-beginning) (region-end)))))
17636 (read-string "LaTeX Fragment: " frag nil frag))))
17637 (unless latex-frag (error "Invalid latex-frag"))
17638 (let* ((tmp-in-file (file-relative-name
17639 (make-temp-name (expand-file-name "ltxmathml-in"))))
17640 (ignore (write-region latex-frag nil tmp-in-file))
17641 (tmp-out-file (file-relative-name
17642 (make-temp-name (expand-file-name "ltxmathml-out"))))
17643 (cmd (format-spec
17644 org-latex-to-mathml-convert-command
17645 `((?j . ,(shell-quote-argument
17646 (expand-file-name org-latex-to-mathml-jar-file)))
17647 (?I . ,(shell-quote-argument tmp-in-file))
17648 (?o . ,(shell-quote-argument tmp-out-file)))))
17649 mathml shell-command-output)
17650 (when (org-called-interactively-p 'any)
17651 (unless (org-format-latex-mathml-available-p)
17652 (error "LaTeX to MathML converter not configured")))
17653 (message "Running %s" cmd)
17654 (setq shell-command-output (shell-command-to-string cmd))
17655 (setq mathml
17656 (when (file-readable-p tmp-out-file)
17657 (with-current-buffer (find-file-noselect tmp-out-file t)
17658 (goto-char (point-min))
17659 (when (re-search-forward
17660 (concat
17661 (regexp-quote
17662 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17663 "\\(.\\|\n\\)*"
17664 (regexp-quote "</math>")) nil t)
17665 (prog1 (match-string 0) (kill-buffer))))))
17666 (cond
17667 (mathml
17668 (setq mathml
17669 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17670 (when mathml-file
17671 (write-region mathml nil mathml-file))
17672 (when (org-called-interactively-p 'any)
17673 (message mathml)))
17674 ((message "LaTeX to MathML conversion failed")
17675 (message shell-command-output)))
17676 (delete-file tmp-in-file)
17677 (when (file-exists-p tmp-out-file)
17678 (delete-file tmp-out-file))
17679 mathml))
17681 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17682 prefix &optional dir)
17683 "Use `org-create-math-formula' but check local cache first."
17684 (let* ((absprefix (expand-file-name prefix dir))
17685 (print-length nil) (print-level nil)
17686 (formula-id (concat
17687 "formula-"
17688 (sha1
17689 (prin1-to-string
17690 (list latex-frag
17691 org-latex-to-mathml-convert-command)))))
17692 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17693 (formula-cache-dir (file-name-directory formula-cache)))
17695 (unless (file-directory-p formula-cache-dir)
17696 (make-directory formula-cache-dir t))
17698 (unless (file-exists-p formula-cache)
17699 (org-create-math-formula latex-frag formula-cache))
17701 (if (file-exists-p formula-cache)
17702 ;; Successful conversion. Return the link to MathML file.
17703 (org-add-props
17704 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17705 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17706 'org-latex-src-embed-type (if latex-frag-type
17707 'paragraph 'character)))
17708 ;; Failed conversion. Return the LaTeX fragment verbatim
17709 (add-text-properties
17710 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17711 latex-frag)))
17713 (defun org-create-formula-image (string tofile options buffer &optional type)
17714 "Create an image from LaTeX source using dvipng or convert.
17715 This function calls either `org-create-formula-image-with-dvipng'
17716 or `org-create-formula-image-with-imagemagick' depending on the
17717 value of `org-latex-create-formula-image-program' or on the value
17718 of the optional TYPE variable.
17720 Note: ultimately these two function should be combined as they
17721 share a good deal of logic."
17722 (org-check-external-command
17723 "latex" "needed to convert LaTeX fragments to images")
17724 (funcall
17725 (case (or type org-latex-create-formula-image-program)
17726 ('dvipng
17727 (org-check-external-command
17728 "dvipng" "needed to convert LaTeX fragments to images")
17729 #'org-create-formula-image-with-dvipng)
17730 ('imagemagick
17731 (org-check-external-command
17732 "convert" "you need to install imagemagick")
17733 #'org-create-formula-image-with-imagemagick)
17734 (t (error
17735 "invalid value of `org-latex-create-formula-image-program'")))
17736 string tofile options buffer))
17738 ;; This function borrows from Ganesh Swami's latex2png.el
17739 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17740 "This calls dvipng."
17741 (require 'org-latex)
17742 (let* ((tmpdir (if (featurep 'xemacs)
17743 (temp-directory)
17744 temporary-file-directory))
17745 (texfilebase (make-temp-name
17746 (expand-file-name "orgtex" tmpdir)))
17747 (texfile (concat texfilebase ".tex"))
17748 (dvifile (concat texfilebase ".dvi"))
17749 (pngfile (concat texfilebase ".png"))
17750 (fnh (if (featurep 'xemacs)
17751 (font-height (face-font 'default))
17752 (face-attribute 'default :height nil)))
17753 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17754 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17755 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17756 "Black"))
17757 (bg (or (plist-get options (if buffer :background :html-background))
17758 "Transparent")))
17759 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17760 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17761 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17762 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17763 (with-temp-file texfile
17764 (insert (org-splice-latex-header
17765 org-format-latex-header
17766 org-export-latex-default-packages-alist
17767 org-export-latex-packages-alist t
17768 org-format-latex-header-extra))
17769 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17770 (require 'org-latex)
17771 (org-export-latex-fix-inputenc))
17772 (let ((dir default-directory))
17773 (condition-case nil
17774 (progn
17775 (cd tmpdir)
17776 (call-process "latex" nil nil nil texfile))
17777 (error nil))
17778 (cd dir))
17779 (if (not (file-exists-p dvifile))
17780 (progn (message "Failed to create dvi file from %s" texfile) nil)
17781 (condition-case nil
17782 (if (featurep 'xemacs)
17783 (call-process "dvipng" nil nil nil
17784 "-fg" fg "-bg" bg
17785 "-T" "tight"
17786 "-o" pngfile
17787 dvifile)
17788 (call-process "dvipng" nil nil nil
17789 "-fg" fg "-bg" bg
17790 "-D" dpi
17791 ;;"-x" scale "-y" scale
17792 "-T" "tight"
17793 "-o" pngfile
17794 dvifile))
17795 (error nil))
17796 (if (not (file-exists-p pngfile))
17797 (if org-format-latex-signal-error
17798 (error "Failed to create png file from %s" texfile)
17799 (message "Failed to create png file from %s" texfile)
17800 nil)
17801 ;; Use the requested file name and clean up
17802 (copy-file pngfile tofile 'replace)
17803 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17804 (if (file-exists-p (concat texfilebase e))
17805 (delete-file (concat texfilebase e))))
17806 pngfile))))
17808 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17809 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17810 "This calls convert, which is included into imagemagick."
17811 (require 'org-latex)
17812 (let* ((tmpdir (if (featurep 'xemacs)
17813 (temp-directory)
17814 temporary-file-directory))
17815 (texfilebase (make-temp-name
17816 (expand-file-name "orgtex" tmpdir)))
17817 (texfile (concat texfilebase ".tex"))
17818 (pdffile (concat texfilebase ".pdf"))
17819 (pngfile (concat texfilebase ".png"))
17820 (fnh (if (featurep 'xemacs)
17821 (font-height (face-font 'default))
17822 (face-attribute 'default :height nil)))
17823 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17824 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17825 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17826 "black"))
17827 (bg (or (plist-get options (if buffer :background :html-background))
17828 "white")))
17829 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17830 (setq fg (org-latex-color-format fg)))
17831 (if (eq bg 'default) (setq bg (org-latex-color :background))
17832 (setq bg (org-latex-color-format
17833 (if (string= bg "Transparent") "white" bg))))
17834 (with-temp-file texfile
17835 (insert (org-splice-latex-header
17836 org-format-latex-header
17837 org-export-latex-default-packages-alist
17838 org-export-latex-packages-alist t
17839 org-format-latex-header-extra))
17840 (insert "\n\\begin{document}\n"
17841 "\\definecolor{fg}{rgb}{" fg "}\n"
17842 "\\definecolor{bg}{rgb}{" bg "}\n"
17843 "\n\\pagecolor{bg}\n"
17844 "\n{\\color{fg}\n"
17845 string
17846 "\n}\n"
17847 "\n\\end{document}\n" )
17848 (require 'org-latex)
17849 (org-export-latex-fix-inputenc))
17850 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17851 (condition-case nil
17852 (progn
17853 (cd tmpdir)
17854 (setq cmds org-latex-to-pdf-process)
17855 (while cmds
17856 (setq latex-frags-cmds (pop cmds))
17857 (if (listp latex-frags-cmds)
17858 (setq cmds nil)
17859 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17860 (while latex-frags-cmds
17861 (setq cmd (pop latex-frags-cmds))
17862 (while (string-match "%b" cmd)
17863 (setq cmd (replace-match
17864 (save-match-data
17865 (shell-quote-argument texfile))
17866 t t cmd)))
17867 (while (string-match "%f" cmd)
17868 (setq cmd (replace-match
17869 (save-match-data
17870 (shell-quote-argument (file-name-nondirectory texfile)))
17871 t t cmd)))
17872 (while (string-match "%o" cmd)
17873 (setq cmd (replace-match
17874 (save-match-data
17875 (shell-quote-argument (file-name-directory texfile)))
17876 t t cmd)))
17877 (setq cmd (split-string cmd))
17878 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17879 (error nil))
17880 (cd dir))
17881 (if (not (file-exists-p pdffile))
17882 (progn (message "Failed to create pdf file from %s" texfile) nil)
17883 (condition-case nil
17884 (if (featurep 'xemacs)
17885 (call-process "convert" nil nil nil
17886 "-density" "96"
17887 "-trim"
17888 "-antialias"
17889 pdffile
17890 "-quality" "100"
17891 ;; "-sharpen" "0x1.0"
17892 pngfile)
17893 (call-process "convert" nil nil nil
17894 "-density" dpi
17895 "-trim"
17896 "-antialias"
17897 pdffile
17898 "-quality" "100"
17899 ; "-sharpen" "0x1.0"
17900 pngfile))
17901 (error nil))
17902 (if (not (file-exists-p pngfile))
17903 (if org-format-latex-signal-error
17904 (error "Failed to create png file from %s" texfile)
17905 (message "Failed to create png file from %s" texfile)
17906 nil)
17907 ;; Use the requested file name and clean up
17908 (copy-file pngfile tofile 'replace)
17909 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17910 (if (file-exists-p (concat texfilebase e))
17911 (delete-file (concat texfilebase e))))
17912 pngfile))))
17914 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17915 "Fill a LaTeX header template TPL.
17916 In the template, the following place holders will be recognized:
17918 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17919 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17920 [PACKAGES] \\usepackage statements for PKG
17921 [NO-PACKAGES] do not include PKG
17922 [EXTRA] the string EXTRA
17923 [NO-EXTRA] do not include EXTRA
17925 For backward compatibility, if both the positive and the negative place
17926 holder is missing, the positive one (without the \"NO-\") will be
17927 assumed to be present at the end of the template.
17928 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17929 EXTRA is a string.
17930 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17931 (let (rpl (end ""))
17932 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17933 (setq rpl (if (or (match-end 1) (not def-pkg))
17934 "" (org-latex-packages-to-string def-pkg snippets-p t))
17935 tpl (replace-match rpl t t tpl))
17936 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17938 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17939 (setq rpl (if (or (match-end 1) (not pkg))
17940 "" (org-latex-packages-to-string pkg snippets-p t))
17941 tpl (replace-match rpl t t tpl))
17942 (if pkg (setq end
17943 (concat end "\n"
17944 (org-latex-packages-to-string pkg snippets-p)))))
17946 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17947 (setq rpl (if (or (match-end 1) (not extra))
17948 "" (concat extra "\n"))
17949 tpl (replace-match rpl t t tpl))
17950 (if (and extra (string-match "\\S-" extra))
17951 (setq end (concat end "\n" extra))))
17953 (if (string-match "\\S-" end)
17954 (concat tpl "\n" end)
17955 tpl)))
17957 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17958 "Turn an alist of packages into a string with the \\usepackage macros."
17959 (setq pkg (mapconcat (lambda(p)
17960 (cond
17961 ((stringp p) p)
17962 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17963 (format "%% Package %s omitted" (cadr p)))
17964 ((equal "" (car p))
17965 (format "\\usepackage{%s}" (cadr p)))
17967 (format "\\usepackage[%s]{%s}"
17968 (car p) (cadr p)))))
17970 "\n"))
17971 (if newline (concat pkg "\n") pkg))
17973 (defun org-dvipng-color (attr)
17974 "Return a RGB color specification for dvipng."
17975 (apply 'format "rgb %s %s %s"
17976 (mapcar 'org-normalize-color
17977 (if (featurep 'xemacs)
17978 (color-rgb-components
17979 (face-property 'default
17980 (cond ((eq attr :foreground) 'foreground)
17981 ((eq attr :background) 'background))))
17982 (color-values (face-attribute 'default attr nil))))))
17984 (defun org-dvipng-color-format (color-name)
17985 "Convert COLOR-NAME to a RGB color value for dvipng."
17986 (apply 'format "rgb %s %s %s"
17987 (mapcar 'org-normalize-color
17988 (color-values color-name))))
17990 (defun org-latex-color (attr)
17991 "Return a RGB color for the LaTeX color package."
17992 (apply 'format "%s,%s,%s"
17993 (mapcar 'org-normalize-color
17994 (if (featurep 'xemacs)
17995 (color-rgb-components
17996 (face-property 'default
17997 (cond ((eq attr :foreground) 'foreground)
17998 ((eq attr :background) 'background))))
17999 (color-values (face-attribute 'default attr nil))))))
18001 (defun org-latex-color-format (color-name)
18002 "Convert COLOR-NAME to a RGB color value."
18003 (apply 'format "%s,%s,%s"
18004 (mapcar 'org-normalize-color
18005 (color-values color-name))))
18007 (defun org-normalize-color (value)
18008 "Return string to be used as color value for an RGB component."
18009 (format "%g" (/ value 65535.0)))
18011 ;; Image display
18014 (defvar org-inline-image-overlays nil)
18015 (make-variable-buffer-local 'org-inline-image-overlays)
18017 (defun org-toggle-inline-images (&optional include-linked)
18018 "Toggle the display of inline images.
18019 INCLUDE-LINKED is passed to `org-display-inline-images'."
18020 (interactive "P")
18021 (if org-inline-image-overlays
18022 (progn
18023 (org-remove-inline-images)
18024 (message "Inline image display turned off"))
18025 (org-display-inline-images include-linked)
18026 (if (and (org-called-interactively-p)
18027 org-inline-image-overlays)
18028 (message "%d images displayed inline"
18029 (length org-inline-image-overlays))
18030 (message "No images to display inline"))))
18032 (defun org-redisplay-inline-images ()
18033 "Refresh the display of inline images."
18034 (interactive)
18035 (if (not org-inline-image-overlays)
18036 (org-toggle-inline-images)
18037 (org-toggle-inline-images)
18038 (org-toggle-inline-images)))
18040 (defun org-display-inline-images (&optional include-linked refresh beg end)
18041 "Display inline images.
18042 Normally only links without a description part are inlined, because this
18043 is how it will work for export. When INCLUDE-LINKED is set, also links
18044 with a description part will be inlined. This can be nice for a quick
18045 look at those images, but it does not reflect what exported files will look
18046 like.
18047 When REFRESH is set, refresh existing images between BEG and END.
18048 This will create new image displays only if necessary.
18049 BEG and END default to the buffer boundaries."
18050 (interactive "P")
18051 (unless refresh
18052 (org-remove-inline-images)
18053 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18054 (save-excursion
18055 (save-restriction
18056 (widen)
18057 (setq beg (or beg (point-min)) end (or end (point-max)))
18058 (goto-char beg)
18059 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18060 (substring (org-image-file-name-regexp) 0 -2)
18061 "\\)\\]" (if include-linked "" "\\]")))
18062 old file ov img type attrwidth width)
18063 (while (re-search-forward re end t)
18064 (setq old (get-char-property-and-overlay (match-beginning 1)
18065 'org-image-overlay)
18066 file (expand-file-name
18067 (concat (or (match-string 3) "") (match-string 4))))
18068 (when (image-type-available-p 'imagemagick)
18069 (setq attrwidth (if (or (listp org-image-actual-width)
18070 (null org-image-actual-width))
18071 (save-excursion
18072 (save-match-data
18073 (when (re-search-backward
18074 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18075 (save-excursion
18076 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18077 (string-to-number (match-string 1))))))
18078 width (cond ((eq org-image-actual-width t) nil)
18079 ((null org-image-actual-width) attrwidth)
18080 ((numberp org-image-actual-width)
18081 org-image-actual-width)
18082 ((listp org-image-actual-width)
18083 (or attrwidth (car org-image-actual-width))))
18084 type (if width 'imagemagick)))
18085 (when (file-exists-p file)
18086 (if (and (car-safe old) refresh)
18087 (image-refresh (overlay-get (cdr old) 'display))
18088 (setq img (save-match-data (create-image file type nil :width width)))
18089 (when img
18090 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18091 (overlay-put ov 'display img)
18092 (overlay-put ov 'face 'default)
18093 (overlay-put ov 'org-image-overlay t)
18094 (overlay-put ov 'modification-hooks
18095 (list 'org-display-inline-remove-overlay))
18096 (push ov org-inline-image-overlays)))))))))
18098 (define-obsolete-function-alias
18099 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18101 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18102 "Remove inline-display overlay if a corresponding region is modified."
18103 (let ((inhibit-modification-hooks t))
18104 (when (and ov after)
18105 (delete ov org-inline-image-overlays)
18106 (delete-overlay ov))))
18108 (defun org-remove-inline-images ()
18109 "Remove inline display of images."
18110 (interactive)
18111 (mapc 'delete-overlay org-inline-image-overlays)
18112 (setq org-inline-image-overlays nil))
18114 ;;;; Key bindings
18116 ;; Outline functions from `outline-mode-prefix-map'
18117 ;; that can be remapped in Org:
18118 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18119 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18120 (define-key org-mode-map [remap outline-forward-same-level]
18121 'org-forward-heading-same-level)
18122 (define-key org-mode-map [remap outline-backward-same-level]
18123 'org-backward-heading-same-level)
18124 (define-key org-mode-map [remap show-branches]
18125 'org-kill-note-or-show-branches)
18126 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18127 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18128 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18130 ;; Outline functions from `outline-mode-prefix-map' that can not
18131 ;; be remapped in Org:
18133 ;; - the column "key binding" shows whether the Outline function is still
18134 ;; available in Org mode on the same key that it has been bound to in
18135 ;; Outline mode:
18136 ;; - "overridden": key used for a different functionality in Org mode
18137 ;; - else: key still bound to the same Outline function in Org mode
18139 ;; | Outline function | key binding | Org replacement |
18140 ;; |------------------------------------+-------------+-----------------------|
18141 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18142 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18143 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18144 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18145 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18146 ;; | `show-entry' | overridden | no replacement |
18147 ;; | `show-children' | `C-c C-i' | visibility cycling |
18148 ;; | `show-branches' | `C-c C-k' | still same function |
18149 ;; | `show-subtree' | overridden | visibility cycling |
18150 ;; | `show-all' | overridden | no replacement |
18151 ;; | `hide-subtree' | overridden | visibility cycling |
18152 ;; | `hide-body' | overridden | no replacement |
18153 ;; | `hide-entry' | overridden | visibility cycling |
18154 ;; | `hide-leaves' | overridden | no replacement |
18155 ;; | `hide-sublevels' | overridden | no replacement |
18156 ;; | `hide-other' | overridden | no replacement |
18158 ;; Make `C-c C-x' a prefix key
18159 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18161 ;; TAB key with modifiers
18162 (org-defkey org-mode-map "\C-i" 'org-cycle)
18163 (org-defkey org-mode-map [(tab)] 'org-cycle)
18164 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18165 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18166 ;; The following line is necessary under Suse GNU/Linux
18167 (unless (featurep 'xemacs)
18168 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18169 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18170 (define-key org-mode-map [backtab] 'org-shifttab)
18172 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18173 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18174 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18176 ;; Cursor keys with modifiers
18177 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18178 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18179 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18180 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18182 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18183 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18184 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18185 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18187 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18188 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18189 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18190 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18192 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18193 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18194 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18195 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18197 ;; Babel keys
18198 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18199 (mapc (lambda (pair)
18200 (define-key org-babel-map (car pair) (cdr pair)))
18201 org-babel-key-bindings)
18203 ;;; Extra keys for tty access.
18204 ;; We only set them when really needed because otherwise the
18205 ;; menus don't show the simple keys
18207 (when (or org-use-extra-keys
18208 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18209 (not window-system))
18210 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18211 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18212 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18213 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18214 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18215 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18216 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18217 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18218 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18219 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18220 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18221 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18222 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18223 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18224 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18225 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18226 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18227 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18228 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18229 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18230 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18231 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18232 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18233 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18234 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18235 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18236 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18237 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18239 ;; All the other keys
18241 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18242 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18243 (if (boundp 'narrow-map)
18244 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18245 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18246 (if (boundp 'narrow-map)
18247 (org-defkey narrow-map "b" 'org-narrow-to-block)
18248 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18249 (if (boundp 'narrow-map)
18250 (org-defkey narrow-map "e" 'org-narrow-to-element)
18251 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18252 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18253 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18254 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18255 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18256 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18257 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18258 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18259 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18260 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18261 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18262 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18263 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18264 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18265 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18266 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18267 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18268 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18269 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18270 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18271 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18272 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18273 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18274 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18275 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18276 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18277 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18278 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18279 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18280 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18281 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18282 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18283 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18284 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18285 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18286 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18287 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18288 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18289 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18290 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18291 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18292 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18293 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18294 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18295 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18296 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18297 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18298 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18299 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18300 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18301 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18302 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18303 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18304 (org-defkey org-mode-map "\C-c^" 'org-sort)
18305 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18306 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18307 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18308 (org-defkey org-mode-map "\C-m" 'org-return)
18309 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18310 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18311 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18312 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18313 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18314 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18315 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18316 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18317 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18318 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18319 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18320 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18321 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18322 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18323 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18324 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18325 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18326 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18327 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18328 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18329 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18330 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18331 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18333 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18334 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18335 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18337 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18338 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18339 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18340 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18341 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18342 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18343 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18344 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18345 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18346 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18347 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18348 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18349 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18350 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18351 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18352 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18353 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18354 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18355 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18356 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18357 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18358 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18360 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18361 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18362 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18363 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18364 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18366 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18368 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18370 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18371 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18373 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18376 (when (featurep 'xemacs)
18377 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18380 (defconst org-speed-commands-default
18382 ("Outline Navigation")
18383 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18384 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18385 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18386 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18387 ("u" . (org-speed-move-safe 'outline-up-heading))
18388 ("j" . org-goto)
18389 ("g" . (org-refile t))
18390 ("Outline Visibility")
18391 ("c" . org-cycle)
18392 ("C" . org-shifttab)
18393 (" " . org-display-outline-path)
18394 (":" . org-columns)
18395 ("Outline Structure Editing")
18396 ("U" . org-shiftmetaup)
18397 ("D" . org-shiftmetadown)
18398 ("r" . org-metaright)
18399 ("l" . org-metaleft)
18400 ("R" . org-shiftmetaright)
18401 ("L" . org-shiftmetaleft)
18402 ("i" . (progn (forward-char 1) (call-interactively
18403 'org-insert-heading-respect-content)))
18404 ("^" . org-sort)
18405 ("w" . org-refile)
18406 ("a" . org-archive-subtree-default-with-confirmation)
18407 ("." . org-mark-subtree)
18408 ("#" . org-toggle-comment)
18409 ("Clock Commands")
18410 ("I" . org-clock-in)
18411 ("O" . org-clock-out)
18412 ("Meta Data Editing")
18413 ("t" . org-todo)
18414 ("," . (org-priority))
18415 ("0" . (org-priority ?\ ))
18416 ("1" . (org-priority ?A))
18417 ("2" . (org-priority ?B))
18418 ("3" . (org-priority ?C))
18419 (";" . org-set-tags-command)
18420 ("e" . org-set-effort)
18421 ("E" . org-inc-effort)
18422 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18423 (org-entry-put (point) "APPT_WARNTIME" m)))
18424 ("Agenda Views etc")
18425 ("v" . org-agenda)
18426 ("/" . org-sparse-tree)
18427 ("Misc")
18428 ("o" . org-open-at-point)
18429 ("?" . org-speed-command-help)
18430 ("<" . (org-agenda-set-restriction-lock 'subtree))
18431 (">" . (org-agenda-remove-restriction-lock))
18433 "The default speed commands.")
18435 (defun org-print-speed-command (e)
18436 (if (> (length (car e)) 1)
18437 (progn
18438 (princ "\n")
18439 (princ (car e))
18440 (princ "\n")
18441 (princ (make-string (length (car e)) ?-))
18442 (princ "\n"))
18443 (princ (car e))
18444 (princ " ")
18445 (if (symbolp (cdr e))
18446 (princ (symbol-name (cdr e)))
18447 (prin1 (cdr e)))
18448 (princ "\n")))
18450 (defun org-speed-command-help ()
18451 "Show the available speed commands."
18452 (interactive)
18453 (if (not org-use-speed-commands)
18454 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18455 (with-output-to-temp-buffer "*Help*"
18456 (princ "User-defined Speed commands\n===========================\n")
18457 (mapc 'org-print-speed-command org-speed-commands-user)
18458 (princ "\n")
18459 (princ "Built-in Speed commands\n=======================\n")
18460 (mapc 'org-print-speed-command org-speed-commands-default))
18461 (with-current-buffer "*Help*"
18462 (setq truncate-lines t))))
18464 (defun org-speed-move-safe (cmd)
18465 "Execute CMD, but make sure that the cursor always ends up in a headline.
18466 If not, return to the original position and throw an error."
18467 (interactive)
18468 (let ((pos (point)))
18469 (call-interactively cmd)
18470 (unless (and (bolp) (org-at-heading-p))
18471 (goto-char pos)
18472 (error "Boundary reached while executing %s" cmd))))
18474 (defvar org-self-insert-command-undo-counter 0)
18476 (defvar org-table-auto-blank-field) ; defined in org-table.el
18477 (defvar org-speed-command nil)
18479 (define-obsolete-function-alias
18480 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18482 (defun org-speed-command-activate (keys)
18483 "Hook for activating single-letter speed commands.
18484 `org-speed-commands-default' specifies a minimal command set.
18485 Use `org-speed-commands-user' for further customization."
18486 (when (or (and (bolp) (looking-at org-outline-regexp))
18487 (and (functionp org-use-speed-commands)
18488 (funcall org-use-speed-commands)))
18489 (cdr (assoc keys (append org-speed-commands-user
18490 org-speed-commands-default)))))
18492 (define-obsolete-function-alias
18493 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18495 (defun org-babel-speed-command-activate (keys)
18496 "Hook for activating single-letter code block commands."
18497 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18498 (cdr (assoc keys org-babel-key-bindings))))
18500 (defcustom org-speed-command-hook
18501 '(org-speed-command-default-hook org-babel-speed-command-hook)
18502 "Hook for activating speed commands at strategic locations.
18503 Hook functions are called in sequence until a valid handler is
18504 found.
18506 Each hook takes a single argument, a user-pressed command key
18507 which is also a `self-insert-command' from the global map.
18509 Within the hook, examine the cursor position and the command key
18510 and return nil or a valid handler as appropriate. Handler could
18511 be one of an interactive command, a function, or a form.
18513 Set `org-use-speed-commands' to non-nil value to enable this
18514 hook. The default setting is `org-speed-command-activate'."
18515 :group 'org-structure
18516 :version "24.1"
18517 :type 'hook)
18519 (defun org-self-insert-command (N)
18520 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18521 If the cursor is in a table looking at whitespace, the whitespace is
18522 overwritten, and the table is not marked as requiring realignment."
18523 (interactive "p")
18524 (org-check-before-invisible-edit 'insert)
18525 (cond
18526 ((and org-use-speed-commands
18527 (setq org-speed-command
18528 (run-hook-with-args-until-success
18529 'org-speed-command-hook (this-command-keys))))
18530 (cond
18531 ((commandp org-speed-command)
18532 (setq this-command org-speed-command)
18533 (call-interactively org-speed-command))
18534 ((functionp org-speed-command)
18535 (funcall org-speed-command))
18536 ((and org-speed-command (listp org-speed-command))
18537 (eval org-speed-command))
18538 (t (let (org-use-speed-commands)
18539 (call-interactively 'org-self-insert-command)))))
18540 ((and
18541 (org-table-p)
18542 (progn
18543 ;; check if we blank the field, and if that triggers align
18544 (and (featurep 'org-table) org-table-auto-blank-field
18545 (member last-command
18546 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18547 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18548 ;; got extra space, this field does not determine column width
18549 (let (org-table-may-need-update) (org-table-blank-field))
18550 ;; no extra space, this field may determine column width
18551 (org-table-blank-field)))
18553 (eq N 1)
18554 (looking-at "[^|\n]* |"))
18555 (let (org-table-may-need-update)
18556 (goto-char (1- (match-end 0)))
18557 (backward-delete-char 1)
18558 (goto-char (match-beginning 0))
18559 (self-insert-command N)))
18561 (setq org-table-may-need-update t)
18562 (self-insert-command N)
18563 (org-fix-tags-on-the-fly)
18564 (if org-self-insert-cluster-for-undo
18565 (if (not (eq last-command 'org-self-insert-command))
18566 (setq org-self-insert-command-undo-counter 1)
18567 (if (>= org-self-insert-command-undo-counter 20)
18568 (setq org-self-insert-command-undo-counter 1)
18569 (and (> org-self-insert-command-undo-counter 0)
18570 buffer-undo-list (listp buffer-undo-list)
18571 (not (cadr buffer-undo-list)) ; remove nil entry
18572 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18573 (setq org-self-insert-command-undo-counter
18574 (1+ org-self-insert-command-undo-counter))))))))
18576 (defun org-check-before-invisible-edit (kind)
18577 "Check is editing if kind KIND would be dangerous with invisible text around.
18578 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18579 ;; First, try to get out of here as quickly as possible, to reduce overhead
18580 (if (and org-catch-invisible-edits
18581 (or (not (boundp 'visible-mode)) (not visible-mode))
18582 (or (get-char-property (point) 'invisible)
18583 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18584 ;; OK, we need to take a closer look
18585 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18586 (invisible-before-point (if (bobp) nil (get-char-property
18587 (1- (point)) 'invisible)))
18588 (border-and-ok-direction
18590 ;; Check if we are acting predictably before invisible text
18591 (and invisible-at-point (not invisible-before-point)
18592 (memq kind '(insert delete-backward)))
18593 ;; Check if we are acting predictably after invisible text
18594 ;; This works not well, and I have turned it off. It seems
18595 ;; better to always show and stop after invisible text.
18596 ;; (and (not invisible-at-point) invisible-before-point
18597 ;; (memq kind '(insert delete)))
18599 (when (or (memq invisible-at-point '(outline org-hide-block t))
18600 (memq invisible-before-point '(outline org-hide-block t)))
18601 (if (eq org-catch-invisible-edits 'error)
18602 (error "Editing in invisible areas is prohibited - make visible first"))
18603 (if (and org-custom-properties-overlays
18604 (y-or-n-p "Display invisible properties in this buffer? "))
18605 (org-toggle-custom-properties-visibility)
18606 ;; Make the area visible
18607 (save-excursion
18608 (if invisible-before-point
18609 (goto-char (previous-single-char-property-change
18610 (point) 'invisible)))
18611 (org-cycle))
18612 (cond
18613 ((eq org-catch-invisible-edits 'show)
18614 ;; That's it, we do the edit after showing
18615 (message
18616 "Unfolding invisible region around point before editing")
18617 (sit-for 1))
18618 ((and (eq org-catch-invisible-edits 'smart)
18619 border-and-ok-direction)
18620 (message "Unfolding invisible region around point before editing"))
18622 ;; Don't do the edit, make the user repeat it in full visibility
18623 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18625 (defun org-fix-tags-on-the-fly ()
18626 (when (and (equal (char-after (point-at-bol)) ?*)
18627 (org-at-heading-p))
18628 (org-align-tags-here org-tags-column)))
18630 (defun org-delete-backward-char (N)
18631 "Like `delete-backward-char', insert whitespace at field end in tables.
18632 When deleting backwards, in tables this function will insert whitespace in
18633 front of the next \"|\" separator, to keep the table aligned. The table will
18634 still be marked for re-alignment if the field did fill the entire column,
18635 because, in this case the deletion might narrow the column."
18636 (interactive "p")
18637 (org-check-before-invisible-edit 'delete-backward)
18638 (if (and (org-table-p)
18639 (eq N 1)
18640 (string-match "|" (buffer-substring (point-at-bol) (point)))
18641 (looking-at ".*?|"))
18642 (let ((pos (point))
18643 (noalign (looking-at "[^|\n\r]* |"))
18644 (c org-table-may-need-update))
18645 (backward-delete-char N)
18646 (if (not overwrite-mode)
18647 (progn
18648 (skip-chars-forward "^|")
18649 (insert " ")
18650 (goto-char (1- pos))))
18651 ;; noalign: if there were two spaces at the end, this field
18652 ;; does not determine the width of the column.
18653 (if noalign (setq org-table-may-need-update c)))
18654 (backward-delete-char N)
18655 (org-fix-tags-on-the-fly)))
18657 (defun org-delete-char (N)
18658 "Like `delete-char', but insert whitespace at field end in tables.
18659 When deleting characters, in tables this function will insert whitespace in
18660 front of the next \"|\" separator, to keep the table aligned. The table will
18661 still be marked for re-alignment if the field did fill the entire column,
18662 because, in this case the deletion might narrow the column."
18663 (interactive "p")
18664 (org-check-before-invisible-edit 'delete)
18665 (if (and (org-table-p)
18666 (not (bolp))
18667 (not (= (char-after) ?|))
18668 (eq N 1))
18669 (if (looking-at ".*?|")
18670 (let ((pos (point))
18671 (noalign (looking-at "[^|\n\r]* |"))
18672 (c org-table-may-need-update))
18673 (replace-match (concat
18674 (substring (match-string 0) 1 -1)
18675 " |"))
18676 (goto-char pos)
18677 ;; noalign: if there were two spaces at the end, this field
18678 ;; does not determine the width of the column.
18679 (if noalign (setq org-table-may-need-update c)))
18680 (delete-char N))
18681 (delete-char N)
18682 (org-fix-tags-on-the-fly)))
18684 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18685 (put 'org-self-insert-command 'delete-selection t)
18686 (put 'orgtbl-self-insert-command 'delete-selection t)
18687 (put 'org-delete-char 'delete-selection 'supersede)
18688 (put 'org-delete-backward-char 'delete-selection 'supersede)
18689 (put 'org-yank 'delete-selection 'yank)
18691 ;; Make `flyspell-mode' delay after some commands
18692 (put 'org-self-insert-command 'flyspell-delayed t)
18693 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18694 (put 'org-delete-char 'flyspell-delayed t)
18695 (put 'org-delete-backward-char 'flyspell-delayed t)
18697 ;; Make pabbrev-mode expand after org-mode commands
18698 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18699 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18701 ;; How to do this: Measure non-white length of current string
18702 ;; If equal to column width, we should realign.
18704 (defun org-remap (map &rest commands)
18705 "In MAP, remap the functions given in COMMANDS.
18706 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18707 (let (new old)
18708 (while commands
18709 (setq old (pop commands) new (pop commands))
18710 (if (fboundp 'command-remapping)
18711 (org-defkey map (vector 'remap old) new)
18712 (substitute-key-definition old new map global-map)))))
18714 (when (eq org-enable-table-editor 'optimized)
18715 ;; If the user wants maximum table support, we need to hijack
18716 ;; some standard editing functions
18717 (org-remap org-mode-map
18718 'self-insert-command 'org-self-insert-command
18719 'delete-char 'org-delete-char
18720 'delete-backward-char 'org-delete-backward-char)
18721 (org-defkey org-mode-map "|" 'org-force-self-insert))
18723 (defvar org-ctrl-c-ctrl-c-hook nil
18724 "Hook for functions attaching themselves to `C-c C-c'.
18726 This can be used to add additional functionality to the C-c C-c
18727 key which executes context-dependent commands. This hook is run
18728 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18729 run after the last test.
18731 Each function will be called with no arguments. The function
18732 must check if the context is appropriate for it to act. If yes,
18733 it should do its thing and then return a non-nil value. If the
18734 context is wrong, just do nothing and return nil.")
18736 (defvar org-ctrl-c-ctrl-c-final-hook nil
18737 "Hook for functions attaching themselves to `C-c C-c'.
18739 This can be used to add additional functionality to the C-c C-c
18740 key which executes context-dependent commands. This hook is run
18741 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18742 before the first test.
18744 Each function will be called with no arguments. The function
18745 must check if the context is appropriate for it to act. If yes,
18746 it should do its thing and then return a non-nil value. If the
18747 context is wrong, just do nothing and return nil.")
18749 (defvar org-tab-first-hook nil
18750 "Hook for functions to attach themselves to TAB.
18751 See `org-ctrl-c-ctrl-c-hook' for more information.
18752 This hook runs as the first action when TAB is pressed, even before
18753 `org-cycle' messes around with the `outline-regexp' to cater for
18754 inline tasks and plain list item folding.
18755 If any function in this hook returns t, any other actions that
18756 would have been caused by TAB (such as table field motion or visibility
18757 cycling) will not occur.")
18759 (defvar org-tab-after-check-for-table-hook nil
18760 "Hook for functions to attach themselves to TAB.
18761 See `org-ctrl-c-ctrl-c-hook' for more information.
18762 This hook runs after it has been established that the cursor is not in a
18763 table, but before checking if the cursor is in a headline or if global cycling
18764 should be done.
18765 If any function in this hook returns t, not other actions like visibility
18766 cycling will be done.")
18768 (defvar org-tab-after-check-for-cycling-hook nil
18769 "Hook for functions to attach themselves to TAB.
18770 See `org-ctrl-c-ctrl-c-hook' for more information.
18771 This hook runs after it has been established that not table field motion and
18772 not visibility should be done because of current context. This is probably
18773 the place where a package like yasnippets can hook in.")
18775 (defvar org-tab-before-tab-emulation-hook nil
18776 "Hook for functions to attach themselves to TAB.
18777 See `org-ctrl-c-ctrl-c-hook' for more information.
18778 This hook runs after every other options for TAB have been exhausted, but
18779 before indentation and \t insertion takes place.")
18781 (defvar org-metaleft-hook nil
18782 "Hook for functions attaching themselves to `M-left'.
18783 See `org-ctrl-c-ctrl-c-hook' for more information.")
18784 (defvar org-metaright-hook nil
18785 "Hook for functions attaching themselves to `M-right'.
18786 See `org-ctrl-c-ctrl-c-hook' for more information.")
18787 (defvar org-metaup-hook nil
18788 "Hook for functions attaching themselves to `M-up'.
18789 See `org-ctrl-c-ctrl-c-hook' for more information.")
18790 (defvar org-metadown-hook nil
18791 "Hook for functions attaching themselves to `M-down'.
18792 See `org-ctrl-c-ctrl-c-hook' for more information.")
18793 (defvar org-shiftmetaleft-hook nil
18794 "Hook for functions attaching themselves to `M-S-left'.
18795 See `org-ctrl-c-ctrl-c-hook' for more information.")
18796 (defvar org-shiftmetaright-hook nil
18797 "Hook for functions attaching themselves to `M-S-right'.
18798 See `org-ctrl-c-ctrl-c-hook' for more information.")
18799 (defvar org-shiftmetaup-hook nil
18800 "Hook for functions attaching themselves to `M-S-up'.
18801 See `org-ctrl-c-ctrl-c-hook' for more information.")
18802 (defvar org-shiftmetadown-hook nil
18803 "Hook for functions attaching themselves to `M-S-down'.
18804 See `org-ctrl-c-ctrl-c-hook' for more information.")
18805 (defvar org-metareturn-hook nil
18806 "Hook for functions attaching themselves to `M-RET'.
18807 See `org-ctrl-c-ctrl-c-hook' for more information.")
18808 (defvar org-shiftup-hook nil
18809 "Hook for functions attaching themselves to `S-up'.
18810 See `org-ctrl-c-ctrl-c-hook' for more information.")
18811 (defvar org-shiftup-final-hook nil
18812 "Hook for functions attaching themselves to `S-up'.
18813 This one runs after all other options except shift-select have been excluded.
18814 See `org-ctrl-c-ctrl-c-hook' for more information.")
18815 (defvar org-shiftdown-hook nil
18816 "Hook for functions attaching themselves to `S-down'.
18817 See `org-ctrl-c-ctrl-c-hook' for more information.")
18818 (defvar org-shiftdown-final-hook nil
18819 "Hook for functions attaching themselves to `S-down'.
18820 This one runs after all other options except shift-select have been excluded.
18821 See `org-ctrl-c-ctrl-c-hook' for more information.")
18822 (defvar org-shiftleft-hook nil
18823 "Hook for functions attaching themselves to `S-left'.
18824 See `org-ctrl-c-ctrl-c-hook' for more information.")
18825 (defvar org-shiftleft-final-hook nil
18826 "Hook for functions attaching themselves to `S-left'.
18827 This one runs after all other options except shift-select have been excluded.
18828 See `org-ctrl-c-ctrl-c-hook' for more information.")
18829 (defvar org-shiftright-hook nil
18830 "Hook for functions attaching themselves to `S-right'.
18831 See `org-ctrl-c-ctrl-c-hook' for more information.")
18832 (defvar org-shiftright-final-hook nil
18833 "Hook for functions attaching themselves to `S-right'.
18834 This one runs after all other options except shift-select have been excluded.
18835 See `org-ctrl-c-ctrl-c-hook' for more information.")
18837 (defun org-modifier-cursor-error ()
18838 "Throw an error, a modified cursor command was applied in wrong context."
18839 (error "This command is active in special context like tables, headlines or items"))
18841 (defun org-shiftselect-error ()
18842 "Throw an error because Shift-Cursor command was applied in wrong context."
18843 (if (and (boundp 'shift-select-mode) shift-select-mode)
18844 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18845 (error "This command works only in special context like headlines or timestamps")))
18847 (defun org-call-for-shift-select (cmd)
18848 (let ((this-command-keys-shift-translated t))
18849 (call-interactively cmd)))
18851 (defun org-shifttab (&optional arg)
18852 "Global visibility cycling or move to previous table field.
18853 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18854 on context.
18855 See the individual commands for more information."
18856 (interactive "P")
18857 (cond
18858 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18859 ((integerp arg)
18860 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18861 (message "Content view to level: %d" arg)
18862 (org-content (prefix-numeric-value arg2))
18863 (setq org-cycle-global-status 'overview)))
18864 (t (call-interactively 'org-global-cycle))))
18866 (defun org-shiftmetaleft ()
18867 "Promote subtree or delete table column.
18868 Calls `org-promote-subtree', `org-outdent-item-tree', or
18869 `org-table-delete-column', depending on context. See the
18870 individual commands for more information."
18871 (interactive)
18872 (cond
18873 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18874 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18875 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18876 ((if (not (org-region-active-p)) (org-at-item-p)
18877 (save-excursion (goto-char (region-beginning))
18878 (org-at-item-p)))
18879 (call-interactively 'org-outdent-item-tree))
18880 (t (org-modifier-cursor-error))))
18882 (defun org-shiftmetaright ()
18883 "Demote subtree or insert table column.
18884 Calls `org-demote-subtree', `org-indent-item-tree', or
18885 `org-table-insert-column', depending on context. See the
18886 individual commands for more information."
18887 (interactive)
18888 (cond
18889 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18890 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18891 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18892 ((if (not (org-region-active-p)) (org-at-item-p)
18893 (save-excursion (goto-char (region-beginning))
18894 (org-at-item-p)))
18895 (call-interactively 'org-indent-item-tree))
18896 (t (org-modifier-cursor-error))))
18898 (defun org-shiftmetaup (&optional arg)
18899 "Move subtree up or kill table row.
18900 Calls `org-move-subtree-up' or `org-table-kill-row' or
18901 `org-move-item-up' or `org-timestamp-up', depending on context.
18902 See the individual commands for more information."
18903 (interactive "P")
18904 (cond
18905 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18906 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18907 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18908 ((org-at-item-p) (call-interactively 'org-move-item-up))
18909 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18910 (call-interactively 'org-timestamp-up)))
18911 (t (org-modifier-cursor-error))))
18913 (defun org-shiftmetadown (&optional arg)
18914 "Move subtree down or insert table row.
18915 Calls `org-move-subtree-down' or `org-table-insert-row' or
18916 `org-move-item-down' or `org-timestamp-up', depending on context.
18917 See the individual commands for more information."
18918 (interactive "P")
18919 (cond
18920 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18921 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18922 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18923 ((org-at-item-p) (call-interactively 'org-move-item-down))
18924 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18925 (call-interactively 'org-timestamp-down)))
18926 (t (org-modifier-cursor-error))))
18928 (defsubst org-hidden-tree-error ()
18929 (error
18930 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18932 (defun org-metaleft (&optional arg)
18933 "Promote heading or move table column to left.
18934 Calls `org-do-promote' or `org-table-move-column', depending on context.
18935 With no specific context, calls the Emacs default `backward-word'.
18936 See the individual commands for more information."
18937 (interactive "P")
18938 (cond
18939 ((run-hook-with-args-until-success 'org-metaleft-hook))
18940 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18941 ((org-with-limited-levels
18942 (or (org-at-heading-p)
18943 (and (org-region-active-p)
18944 (save-excursion
18945 (goto-char (region-beginning))
18946 (org-at-heading-p)))))
18947 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18948 (call-interactively 'org-do-promote))
18949 ;; At an inline task.
18950 ((org-at-heading-p)
18951 (call-interactively 'org-inlinetask-promote))
18952 ((or (org-at-item-p)
18953 (and (org-region-active-p)
18954 (save-excursion
18955 (goto-char (region-beginning))
18956 (org-at-item-p))))
18957 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18958 (call-interactively 'org-outdent-item))
18959 (t (call-interactively 'backward-word))))
18961 (defun org-metaright (&optional arg)
18962 "Demote a subtree, a list item or move table column to right.
18963 In front of a drawer or a block keyword, indent it correctly.
18964 With no specific context, calls the Emacs default `forward-word'.
18965 See the individual commands for more information."
18966 (interactive "P")
18967 (cond
18968 ((run-hook-with-args-until-success 'org-metaright-hook))
18969 ((org-at-table-p) (call-interactively 'org-table-move-column))
18970 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18971 ((org-at-block-p) (call-interactively 'org-indent-block))
18972 ((org-with-limited-levels
18973 (or (org-at-heading-p)
18974 (and (org-region-active-p)
18975 (save-excursion
18976 (goto-char (region-beginning))
18977 (org-at-heading-p)))))
18978 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18979 (call-interactively 'org-do-demote))
18980 ;; At an inline task.
18981 ((org-at-heading-p)
18982 (call-interactively 'org-inlinetask-demote))
18983 ((or (org-at-item-p)
18984 (and (org-region-active-p)
18985 (save-excursion
18986 (goto-char (region-beginning))
18987 (org-at-item-p))))
18988 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18989 (call-interactively 'org-indent-item))
18990 (t (call-interactively 'forward-word))))
18992 (defun org-check-for-hidden (what)
18993 "Check if there are hidden headlines/items in the current visual line.
18994 WHAT can be either `headlines' or `items'. If the current line is
18995 an outline or item heading and it has a folded subtree below it,
18996 this function returns t, nil otherwise."
18997 (let ((re (cond
18998 ((eq what 'headlines) org-outline-regexp-bol)
18999 ((eq what 'items) (org-item-beginning-re))
19000 (t (error "This should not happen"))))
19001 beg end)
19002 (save-excursion
19003 (catch 'exit
19004 (unless (org-region-active-p)
19005 (setq beg (point-at-bol))
19006 (beginning-of-line 2)
19007 (while (and (not (eobp)) ;; this is like `next-line'
19008 (get-char-property (1- (point)) 'invisible))
19009 (beginning-of-line 2))
19010 (setq end (point))
19011 (goto-char beg)
19012 (goto-char (point-at-eol))
19013 (setq end (max end (point)))
19014 (while (re-search-forward re end t)
19015 (if (get-char-property (match-beginning 0) 'invisible)
19016 (throw 'exit t))))
19017 nil))))
19019 (defun org-metaup (&optional arg)
19020 "Move subtree up or move table row up.
19021 Calls `org-move-subtree-up' or `org-table-move-row' or
19022 `org-move-item-up', depending on context. See the individual commands
19023 for more information."
19024 (interactive "P")
19025 (cond
19026 ((run-hook-with-args-until-success 'org-metaup-hook))
19027 ((org-region-active-p)
19028 (let* ((a (min (region-beginning) (region-end)))
19029 (b (1- (max (region-beginning) (region-end))))
19030 (c (save-excursion (goto-char a)
19031 (move-beginning-of-line 0)))
19032 (d (save-excursion (goto-char a)
19033 (move-end-of-line 0) (point))))
19034 (transpose-regions a b c d)
19035 (goto-char c)))
19036 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19037 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19038 ((org-at-item-p) (call-interactively 'org-move-item-up))
19039 (t (org-drag-element-backward))))
19041 (defun org-metadown (&optional arg)
19042 "Move subtree down or move table row down.
19043 Calls `org-move-subtree-down' or `org-table-move-row' or
19044 `org-move-item-down', depending on context. See the individual
19045 commands for more information."
19046 (interactive "P")
19047 (cond
19048 ((run-hook-with-args-until-success 'org-metadown-hook))
19049 ((org-region-active-p)
19050 (let* ((a (min (region-beginning) (region-end)))
19051 (b (max (region-beginning) (region-end)))
19052 (c (save-excursion (goto-char b)
19053 (move-beginning-of-line 1)))
19054 (d (save-excursion (goto-char b)
19055 (move-end-of-line 1) (1+ (point)))))
19056 (transpose-regions a b c d)
19057 (goto-char d)))
19058 ((org-at-table-p) (call-interactively 'org-table-move-row))
19059 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19060 ((org-at-item-p) (call-interactively 'org-move-item-down))
19061 (t (org-drag-element-forward))))
19063 (defun org-shiftup (&optional arg)
19064 "Increase item in timestamp or increase priority of current headline.
19065 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19066 depending on context. See the individual commands for more information."
19067 (interactive "P")
19068 (cond
19069 ((run-hook-with-args-until-success 'org-shiftup-hook))
19070 ((and org-support-shift-select (org-region-active-p))
19071 (org-call-for-shift-select 'previous-line))
19072 ((org-at-timestamp-p t)
19073 (call-interactively (if org-edit-timestamp-down-means-later
19074 'org-timestamp-down 'org-timestamp-up)))
19075 ((and (not (eq org-support-shift-select 'always))
19076 org-enable-priority-commands
19077 (org-at-heading-p))
19078 (call-interactively 'org-priority-up))
19079 ((and (not org-support-shift-select) (org-at-item-p))
19080 (call-interactively 'org-previous-item))
19081 ((org-clocktable-try-shift 'up arg))
19082 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19083 (org-support-shift-select
19084 (org-call-for-shift-select 'previous-line))
19085 (t (org-shiftselect-error))))
19087 (defun org-shiftdown (&optional arg)
19088 "Decrease item in timestamp or decrease priority of current headline.
19089 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19090 depending on context. See the individual commands for more information."
19091 (interactive "P")
19092 (cond
19093 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19094 ((and org-support-shift-select (org-region-active-p))
19095 (org-call-for-shift-select 'next-line))
19096 ((org-at-timestamp-p t)
19097 (call-interactively (if org-edit-timestamp-down-means-later
19098 'org-timestamp-up 'org-timestamp-down)))
19099 ((and (not (eq org-support-shift-select 'always))
19100 org-enable-priority-commands
19101 (org-at-heading-p))
19102 (call-interactively 'org-priority-down))
19103 ((and (not org-support-shift-select) (org-at-item-p))
19104 (call-interactively 'org-next-item))
19105 ((org-clocktable-try-shift 'down arg))
19106 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19107 (org-support-shift-select
19108 (org-call-for-shift-select 'next-line))
19109 (t (org-shiftselect-error))))
19111 (defun org-shiftright (&optional arg)
19112 "Cycle the thing at point or in the current line, depending on context.
19113 Depending on context, this does one of the following:
19115 - switch a timestamp at point one day into the future
19116 - on a headline, switch to the next TODO keyword.
19117 - on an item, switch entire list to the next bullet type
19118 - on a property line, switch to the next allowed value
19119 - on a clocktable definition line, move time block into the future"
19120 (interactive "P")
19121 (cond
19122 ((run-hook-with-args-until-success 'org-shiftright-hook))
19123 ((and org-support-shift-select (org-region-active-p))
19124 (org-call-for-shift-select 'forward-char))
19125 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19126 ((and (not (eq org-support-shift-select 'always))
19127 (org-at-heading-p))
19128 (let ((org-inhibit-logging
19129 (not org-treat-S-cursor-todo-selection-as-state-change))
19130 (org-inhibit-blocking
19131 (not org-treat-S-cursor-todo-selection-as-state-change)))
19132 (org-call-with-arg 'org-todo 'right)))
19133 ((or (and org-support-shift-select
19134 (not (eq org-support-shift-select 'always))
19135 (org-at-item-bullet-p))
19136 (and (not org-support-shift-select) (org-at-item-p)))
19137 (org-call-with-arg 'org-cycle-list-bullet nil))
19138 ((and (not (eq org-support-shift-select 'always))
19139 (org-at-property-p))
19140 (call-interactively 'org-property-next-allowed-value))
19141 ((org-clocktable-try-shift 'right arg))
19142 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19143 (org-support-shift-select
19144 (org-call-for-shift-select 'forward-char))
19145 (t (org-shiftselect-error))))
19147 (defun org-shiftleft (&optional arg)
19148 "Cycle the thing at point or in the current line, depending on context.
19149 Depending on context, this does one of the following:
19151 - switch a timestamp at point one day into the past
19152 - on a headline, switch to the previous TODO keyword.
19153 - on an item, switch entire list to the previous bullet type
19154 - on a property line, switch to the previous allowed value
19155 - on a clocktable definition line, move time block into the past"
19156 (interactive "P")
19157 (cond
19158 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19159 ((and org-support-shift-select (org-region-active-p))
19160 (org-call-for-shift-select 'backward-char))
19161 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19162 ((and (not (eq org-support-shift-select 'always))
19163 (org-at-heading-p))
19164 (let ((org-inhibit-logging
19165 (not org-treat-S-cursor-todo-selection-as-state-change))
19166 (org-inhibit-blocking
19167 (not org-treat-S-cursor-todo-selection-as-state-change)))
19168 (org-call-with-arg 'org-todo 'left)))
19169 ((or (and org-support-shift-select
19170 (not (eq org-support-shift-select 'always))
19171 (org-at-item-bullet-p))
19172 (and (not org-support-shift-select) (org-at-item-p)))
19173 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19174 ((and (not (eq org-support-shift-select 'always))
19175 (org-at-property-p))
19176 (call-interactively 'org-property-previous-allowed-value))
19177 ((org-clocktable-try-shift 'left arg))
19178 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19179 (org-support-shift-select
19180 (org-call-for-shift-select 'backward-char))
19181 (t (org-shiftselect-error))))
19183 (defun org-shiftcontrolright ()
19184 "Switch to next TODO set."
19185 (interactive)
19186 (cond
19187 ((and org-support-shift-select (org-region-active-p))
19188 (org-call-for-shift-select 'forward-word))
19189 ((and (not (eq org-support-shift-select 'always))
19190 (org-at-heading-p))
19191 (org-call-with-arg 'org-todo 'nextset))
19192 (org-support-shift-select
19193 (org-call-for-shift-select 'forward-word))
19194 (t (org-shiftselect-error))))
19196 (defun org-shiftcontrolleft ()
19197 "Switch to previous TODO set."
19198 (interactive)
19199 (cond
19200 ((and org-support-shift-select (org-region-active-p))
19201 (org-call-for-shift-select 'backward-word))
19202 ((and (not (eq org-support-shift-select 'always))
19203 (org-at-heading-p))
19204 (org-call-with-arg 'org-todo 'previousset))
19205 (org-support-shift-select
19206 (org-call-for-shift-select 'backward-word))
19207 (t (org-shiftselect-error))))
19209 (defun org-shiftcontrolup ()
19210 "Change timestamps synchronously up in CLOCK log lines."
19211 (interactive)
19212 (cond ((and (not org-support-shift-select)
19213 (org-at-clock-log-p)
19214 (org-at-timestamp-p t))
19215 (org-clock-timestamps-up))
19216 (t (org-shiftselect-error))))
19218 (defun org-shiftcontroldown ()
19219 "Change timestamps synchronously down in CLOCK log lines."
19220 (interactive)
19221 (cond ((and (not org-support-shift-select)
19222 (org-at-clock-log-p)
19223 (org-at-timestamp-p t))
19224 (org-clock-timestamps-down))
19225 (t (org-shiftselect-error))))
19227 (defun org-ctrl-c-ret ()
19228 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19229 (interactive)
19230 (cond
19231 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19232 (t (call-interactively 'org-insert-heading))))
19234 (defun org-find-visible ()
19235 (let ((s (point)))
19236 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19237 (get-char-property s 'invisible)))
19239 (defun org-find-invisible ()
19240 (let ((s (point)))
19241 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19242 (not (get-char-property s 'invisible))))
19245 (defun org-copy-visible (beg end)
19246 "Copy the visible parts of the region."
19247 (interactive "r")
19248 (let (snippets s)
19249 (save-excursion
19250 (save-restriction
19251 (narrow-to-region beg end)
19252 (setq s (goto-char (point-min)))
19253 (while (not (= (point) (point-max)))
19254 (goto-char (org-find-invisible))
19255 (push (buffer-substring s (point)) snippets)
19256 (setq s (goto-char (org-find-visible))))))
19257 (kill-new (apply 'concat (nreverse snippets)))))
19259 (defun org-copy-special ()
19260 "Copy region in table or copy current subtree.
19261 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19262 See the individual commands for more information."
19263 (interactive)
19264 (call-interactively
19265 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19267 (defun org-cut-special ()
19268 "Cut region in table or cut current subtree.
19269 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19270 See the individual commands for more information."
19271 (interactive)
19272 (call-interactively
19273 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19275 (defun org-paste-special (arg)
19276 "Paste rectangular region into table, or past subtree relative to level.
19277 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19278 See the individual commands for more information."
19279 (interactive "P")
19280 (if (org-at-table-p)
19281 (org-table-paste-rectangle)
19282 (org-paste-subtree arg)))
19284 (defun org-edit-special (&optional arg)
19285 "Call a special editor for the stuff at point.
19286 When at a table, call the formula editor with `org-table-edit-formulas'.
19287 When at the first line of an src example, call `org-edit-src-code'.
19288 When in an #+include line, visit the include file. Otherwise call
19289 `ffap' to visit the file at point."
19290 (interactive)
19291 ;; possibly prep session before editing source
19292 (when arg
19293 (let* ((info (org-babel-get-src-block-info))
19294 (lang (nth 0 info))
19295 (params (nth 2 info))
19296 (session (cdr (assoc :session params))))
19297 (when (and info session) ;; we are in a source-code block with a session
19298 (funcall
19299 (intern (concat "org-babel-prep-session:" lang)) session params))))
19300 (cond ;; proceed with `org-edit-special'
19301 ((save-excursion
19302 (beginning-of-line 1)
19303 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19304 (find-file (org-trim (match-string 1))))
19305 ((org-edit-src-code))
19306 ((org-edit-fixed-width-region))
19307 ((org-at-table.el-p)
19308 (org-edit-src-code))
19309 ((or (org-at-table-p)
19310 (save-excursion
19311 (beginning-of-line 1)
19312 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19313 (call-interactively 'org-table-edit-formulas))
19314 (t (call-interactively 'ffap))))
19316 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19317 (defun org-ctrl-c-ctrl-c (&optional arg)
19318 "Set tags in headline, or update according to changed information at point.
19320 This command does many different things, depending on context:
19322 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19323 this is what we do.
19325 - If the cursor is on a statistics cookie, update it.
19327 - If the cursor is in a headline, prompt for tags and insert them
19328 into the current line, aligned to `org-tags-column'. When called
19329 with prefix arg, realign all tags in the current buffer.
19331 - If the cursor is in one of the special #+KEYWORD lines, this
19332 triggers scanning the buffer for these lines and updating the
19333 information.
19335 - If the cursor is inside a table, realign the table. This command
19336 works even if the automatic table editor has been turned off.
19338 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19339 the entire table.
19341 - If the cursor is at a footnote reference or definition, jump to
19342 the corresponding definition or references, respectively.
19344 - If the cursor is a the beginning of a dynamic block, update it.
19346 - If the current buffer is a capture buffer, close note and file it.
19348 - If the cursor is on a <<<target>>>, update radio targets and
19349 corresponding links in this buffer.
19351 - If the cursor is on a numbered item in a plain list, renumber the
19352 ordered list.
19354 - If the cursor is on a checkbox, toggle it.
19356 - If the cursor is on a code block, evaluate it. The variable
19357 `org-confirm-babel-evaluate' can be used to control prompting
19358 before code block evaluation, by default every code block
19359 evaluation requires confirmation. Code block evaluation can be
19360 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19361 (interactive "P")
19362 (let ((org-enable-table-editor t))
19363 (cond
19364 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19365 org-occur-highlights
19366 org-latex-fragment-image-overlays)
19367 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19368 (org-remove-occur-highlights)
19369 (org-remove-latex-fragment-image-overlays)
19370 (message "Temporary highlights/overlays removed from current buffer"))
19371 ((and (local-variable-p 'org-finish-function (current-buffer))
19372 (fboundp org-finish-function))
19373 (funcall org-finish-function))
19374 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19375 ((org-in-regexp org-ts-regexp-both)
19376 (org-timestamp-change 0 'day))
19377 ((or (looking-at org-property-start-re)
19378 (org-at-property-p))
19379 (call-interactively 'org-property-action))
19380 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19381 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19382 (or (org-at-heading-p) (org-at-item-p)))
19383 (call-interactively 'org-update-statistics-cookies))
19384 ((org-at-heading-p) (call-interactively 'org-set-tags))
19385 ((org-at-table.el-p)
19386 (message "Use C-c ' to edit table.el tables"))
19387 ((org-at-table-p)
19388 (org-table-maybe-eval-formula)
19389 (if arg
19390 (call-interactively 'org-table-recalculate)
19391 (org-table-maybe-recalculate-line))
19392 (call-interactively 'org-table-align)
19393 (orgtbl-send-table 'maybe))
19394 ((or (org-footnote-at-reference-p)
19395 (org-footnote-at-definition-p))
19396 (call-interactively 'org-footnote-action))
19397 ((org-at-item-checkbox-p)
19398 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19399 ;; list only if at top item.
19400 (let* ((cbox (match-string 1))
19401 (struct (org-list-struct))
19402 (old-struct (copy-tree struct))
19403 (parents (org-list-parents-alist struct))
19404 (orderedp (org-entry-get nil "ORDERED"))
19405 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19406 block-item)
19407 ;; Use a light version of `org-toggle-checkbox' to avoid
19408 ;; computing list structure twice.
19409 (let ((new-box (cond
19410 ((equal arg '(16)) "[-]")
19411 ((equal arg '(4)) nil)
19412 ((equal "[X]" cbox) "[ ]")
19413 (t "[X]"))))
19414 (if (and firstp arg)
19415 ;; If at first item of sub-list, remove check-box from
19416 ;; every item at the same level.
19417 (mapc
19418 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19419 (org-list-get-all-items
19420 (point-at-bol) struct (org-list-prevs-alist struct)))
19421 (org-list-set-checkbox (point-at-bol) struct new-box)))
19422 ;; Replicate `org-list-write-struct', while grabbing a return
19423 ;; value from `org-list-struct-fix-box'.
19424 (org-list-struct-fix-ind struct parents 2)
19425 (org-list-struct-fix-item-end struct)
19426 (let ((prevs (org-list-prevs-alist struct)))
19427 (org-list-struct-fix-bul struct prevs)
19428 (org-list-struct-fix-ind struct parents)
19429 (setq block-item
19430 (org-list-struct-fix-box struct parents prevs orderedp)))
19431 (org-list-struct-apply-struct struct old-struct)
19432 (org-update-checkbox-count-maybe)
19433 (when block-item
19434 (message
19435 "Checkboxes were removed due to unchecked box at line %d"
19436 (org-current-line block-item)))
19437 (when firstp (org-list-send-list 'maybe))))
19438 ((org-at-item-p)
19439 ;; Cursor at an item: repair list. Do checkbox related actions
19440 ;; only if function was called with an argument. Send list only
19441 ;; if at top item.
19442 (let* ((struct (org-list-struct))
19443 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19444 old-struct)
19445 (when arg
19446 (setq old-struct (copy-tree struct))
19447 (if firstp
19448 ;; If at first item of sub-list, add check-box to every
19449 ;; item at the same level.
19450 (mapc
19451 (lambda (pos)
19452 (unless (org-list-get-checkbox pos struct)
19453 (org-list-set-checkbox pos struct "[ ]")))
19454 (org-list-get-all-items
19455 (point-at-bol) struct (org-list-prevs-alist struct)))
19456 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19457 (org-list-write-struct
19458 struct (org-list-parents-alist struct) old-struct)
19459 (when arg (org-update-checkbox-count-maybe))
19460 (when firstp (org-list-send-list 'maybe))))
19461 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19462 ;; Dynamic block
19463 (beginning-of-line 1)
19464 (save-excursion (org-update-dblock)))
19465 ((save-excursion
19466 (let ((case-fold-search t))
19467 (beginning-of-line 1)
19468 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19469 (cond
19470 ((or (equal (match-string 1) "TBLFM")
19471 (equal (match-string 1) "tblfm"))
19472 ;; Recalculate the table before this line
19473 (save-excursion
19474 (beginning-of-line 1)
19475 (skip-chars-backward " \r\n\t")
19476 (if (org-at-table-p)
19477 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19479 (let ((org-inhibit-startup-visibility-stuff t)
19480 (org-startup-align-all-tables nil))
19481 (when (boundp 'org-table-coordinate-overlays)
19482 (mapc 'delete-overlay org-table-coordinate-overlays)
19483 (setq org-table-coordinate-overlays nil))
19484 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19485 (message "Local setup has been refreshed"))))
19486 ((org-clock-update-time-maybe))
19488 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19489 (error "C-c C-c can do nothing useful at this location"))))))
19491 (defun org-mode-restart ()
19492 "Restart Org-mode, to scan again for special lines.
19493 Also updates the keyword regular expressions."
19494 (interactive)
19495 (org-mode)
19496 (message "Org-mode restarted"))
19498 (defun org-kill-note-or-show-branches ()
19499 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19500 (interactive)
19501 (if (not org-finish-function)
19502 (progn
19503 (hide-subtree)
19504 (call-interactively 'show-branches))
19505 (let ((org-note-abort t))
19506 (funcall org-finish-function))))
19508 (defun org-return (&optional indent)
19509 "Goto next table row or insert a newline.
19510 Calls `org-table-next-row' or `newline', depending on context.
19511 See the individual commands for more information."
19512 (interactive)
19513 (let (org-ts-what)
19514 (cond
19515 ((or (bobp) (org-in-src-block-p))
19516 (if indent (newline-and-indent) (newline)))
19517 ((org-at-table-p)
19518 (org-table-justify-field-maybe)
19519 (call-interactively 'org-table-next-row))
19520 ;; when `newline-and-indent' is called within a list, make sure
19521 ;; text moved stays inside the item.
19522 ((and (org-in-item-p) indent)
19523 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19524 (progn
19525 (save-match-data (newline))
19526 (org-indent-line-to (length (match-string 0))))
19527 (let ((ind (org-get-indentation)))
19528 (newline)
19529 (if (org-looking-back org-list-end-re)
19530 (org-indent-line)
19531 (org-indent-line-to ind)))))
19532 ((and org-return-follows-link
19533 (org-at-timestamp-p t)
19534 (not (eq org-ts-what 'after)))
19535 (org-follow-timestamp-link))
19536 ((and org-return-follows-link
19537 (let ((tprop (get-text-property (point) 'face)))
19538 (or (eq tprop 'org-link)
19539 (and (listp tprop) (memq 'org-link tprop)))))
19540 (call-interactively 'org-open-at-point))
19541 ((and (org-at-heading-p)
19542 (looking-at
19543 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19544 (org-show-entry)
19545 (end-of-line 1)
19546 (newline))
19547 (t (if indent (newline-and-indent) (newline))))))
19549 (defun org-return-indent ()
19550 "Goto next table row or insert a newline and indent.
19551 Calls `org-table-next-row' or `newline-and-indent', depending on
19552 context. See the individual commands for more information."
19553 (interactive)
19554 (org-return t))
19556 (defun org-ctrl-c-star ()
19557 "Compute table, or change heading status of lines.
19558 Calls `org-table-recalculate' or `org-toggle-heading',
19559 depending on context."
19560 (interactive)
19561 (cond
19562 ((org-at-table-p)
19563 (call-interactively 'org-table-recalculate))
19565 ;; Convert all lines in region to list items
19566 (call-interactively 'org-toggle-heading))))
19568 (defun org-ctrl-c-minus ()
19569 "Insert separator line in table or modify bullet status of line.
19570 Also turns a plain line or a region of lines into list items.
19571 Calls `org-table-insert-hline', `org-toggle-item', or
19572 `org-cycle-list-bullet', depending on context."
19573 (interactive)
19574 (cond
19575 ((org-at-table-p)
19576 (call-interactively 'org-table-insert-hline))
19577 ((org-region-active-p)
19578 (call-interactively 'org-toggle-item))
19579 ((org-in-item-p)
19580 (call-interactively 'org-cycle-list-bullet))
19582 (call-interactively 'org-toggle-item))))
19584 (defun org-toggle-item (arg)
19585 "Convert headings or normal lines to items, items to normal lines.
19586 If there is no active region, only the current line is considered.
19588 If the first non blank line in the region is an headline, convert
19589 all headlines to items, shifting text accordingly.
19591 If it is an item, convert all items to normal lines.
19593 If it is normal text, change region into an item. With a prefix
19594 argument ARG, change each line in region into an item."
19595 (interactive "P")
19596 (let ((shift-text
19597 (function
19598 ;; Shift text in current section to IND, from point to END.
19599 ;; The function leaves point to END line.
19600 (lambda (ind end)
19601 (let ((min-i 1000) (end (copy-marker end)))
19602 ;; First determine the minimum indentation (MIN-I) of
19603 ;; the text.
19604 (save-excursion
19605 (catch 'exit
19606 (while (< (point) end)
19607 (let ((i (org-get-indentation)))
19608 (cond
19609 ;; Skip blank lines and inline tasks.
19610 ((looking-at "^[ \t]*$"))
19611 ((looking-at org-outline-regexp-bol))
19612 ;; We can't find less than 0 indentation.
19613 ((zerop i) (throw 'exit (setq min-i 0)))
19614 ((< i min-i) (setq min-i i))))
19615 (forward-line))))
19616 ;; Then indent each line so that a line indented to
19617 ;; MIN-I becomes indented to IND. Ignore blank lines
19618 ;; and inline tasks in the process.
19619 (let ((delta (- ind min-i)))
19620 (while (< (point) end)
19621 (unless (or (looking-at "^[ \t]*$")
19622 (looking-at org-outline-regexp-bol))
19623 (org-indent-line-to (+ (org-get-indentation) delta)))
19624 (forward-line)))))))
19625 (skip-blanks
19626 (function
19627 ;; Return beginning of first non-blank line, starting from
19628 ;; line at POS.
19629 (lambda (pos)
19630 (save-excursion
19631 (goto-char pos)
19632 (skip-chars-forward " \r\t\n")
19633 (point-at-bol)))))
19634 beg end)
19635 ;; Determine boundaries of changes.
19636 (if (org-region-active-p)
19637 (setq beg (funcall skip-blanks (region-beginning))
19638 end (copy-marker (region-end)))
19639 (setq beg (funcall skip-blanks (point-at-bol))
19640 end (copy-marker (point-at-eol))))
19641 ;; Depending on the starting line, choose an action on the text
19642 ;; between BEG and END.
19643 (org-with-limited-levels
19644 (save-excursion
19645 (goto-char beg)
19646 (cond
19647 ;; Case 1. Start at an item: de-itemize. Note that it only
19648 ;; happens when a region is active: `org-ctrl-c-minus'
19649 ;; would call `org-cycle-list-bullet' otherwise.
19650 ((org-at-item-p)
19651 (while (< (point) end)
19652 (when (org-at-item-p)
19653 (skip-chars-forward " \t")
19654 (delete-region (point) (match-end 0)))
19655 (forward-line)))
19656 ;; Case 2. Start at an heading: convert to items.
19657 ((org-at-heading-p)
19658 (let* ((bul (org-list-bullet-string "-"))
19659 (bul-len (length bul))
19660 ;; Indentation of the first heading. It should be
19661 ;; relative to the indentation of its parent, if any.
19662 (start-ind (save-excursion
19663 (cond
19664 ((not org-adapt-indentation) 0)
19665 ((not (outline-previous-heading)) 0)
19666 (t (length (match-string 0))))))
19667 ;; Level of first heading. Further headings will be
19668 ;; compared to it to determine hierarchy in the list.
19669 (ref-level (org-reduced-level (org-outline-level))))
19670 (while (< (point) end)
19671 (let* ((level (org-reduced-level (org-outline-level)))
19672 (delta (max 0 (- level ref-level))))
19673 ;; If current headline is less indented than the first
19674 ;; one, set it as reference, in order to preserve
19675 ;; subtrees.
19676 (when (< level ref-level) (setq ref-level level))
19677 (replace-match bul t t)
19678 (org-indent-line-to (+ start-ind (* delta bul-len)))
19679 ;; Ensure all text down to END (or SECTION-END) belongs
19680 ;; to the newly created item.
19681 (let ((section-end (save-excursion
19682 (or (outline-next-heading) (point)))))
19683 (forward-line)
19684 (funcall shift-text
19685 (+ start-ind (* (1+ delta) bul-len))
19686 (min end section-end)))))))
19687 ;; Case 3. Normal line with ARG: turn each non-item line into
19688 ;; an item.
19689 (arg
19690 (while (< (point) end)
19691 (unless (or (org-at-heading-p) (org-at-item-p))
19692 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19693 (replace-match
19694 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19695 (forward-line)))
19696 ;; Case 4. Normal line without ARG: make the first line of
19697 ;; region an item, and shift indentation of others
19698 ;; lines to set them as item's body.
19699 (t (let* ((bul (org-list-bullet-string "-"))
19700 (bul-len (length bul))
19701 (ref-ind (org-get-indentation)))
19702 (skip-chars-forward " \t")
19703 (insert bul)
19704 (forward-line)
19705 (while (< (point) end)
19706 ;; Ensure that lines less indented than first one
19707 ;; still get included in item body.
19708 (funcall shift-text
19709 (+ ref-ind bul-len)
19710 (min end (save-excursion (or (outline-next-heading)
19711 (point)))))
19712 (forward-line)))))))))
19714 (defun org-toggle-heading (&optional nstars)
19715 "Convert headings to normal text, or items or text to headings.
19716 If there is no active region, only the current line is considered.
19718 With a \\[universal-argument] prefix, convert the whole list at
19719 point into heading.
19721 In a region:
19723 - If the first non blank line is an headline, remove the stars
19724 from all headlines in the region.
19726 - If it is a normal line turn each and every normal line (i.e. not an
19727 heading or an item) in the region into a heading.
19729 - If it is a plain list item, turn all plain list items into headings.
19731 When converting a line into a heading, the number of stars is chosen
19732 such that the lines become children of the current entry. However,
19733 when a prefix argument is given, its value determines the number of
19734 stars to add."
19735 (interactive "P")
19736 (let ((skip-blanks
19737 (function
19738 ;; Return beginning of first non-blank line, starting from
19739 ;; line at POS.
19740 (lambda (pos)
19741 (save-excursion
19742 (goto-char pos)
19743 (while (org-at-comment-p) (forward-line))
19744 (skip-chars-forward " \r\t\n")
19745 (point-at-bol)))))
19746 beg end toggled)
19747 ;; Determine boundaries of changes. If a universal prefix has
19748 ;; been given, put the list in a region. If region ends at a bol,
19749 ;; do not consider the last line to be in the region.
19751 (when (and current-prefix-arg (org-at-item-p))
19752 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19753 (org-mark-element))
19755 (if (org-region-active-p)
19756 (setq beg (funcall skip-blanks (region-beginning))
19757 end (copy-marker (save-excursion
19758 (goto-char (region-end))
19759 (if (bolp) (point) (point-at-eol)))))
19760 (setq beg (funcall skip-blanks (point-at-bol))
19761 end (copy-marker (point-at-eol))))
19762 ;; Ensure inline tasks don't count as headings.
19763 (org-with-limited-levels
19764 (save-excursion
19765 (goto-char beg)
19766 (cond
19767 ;; Case 1. Started at an heading: de-star headings.
19768 ((org-at-heading-p)
19769 (while (< (point) end)
19770 (when (org-at-heading-p t)
19771 (looking-at org-outline-regexp) (replace-match "")
19772 (setq toggled t))
19773 (forward-line)))
19774 ;; Case 2. Started at an item: change items into headlines.
19775 ;; One star will be added by `org-list-to-subtree'.
19776 ((org-at-item-p)
19777 (let* ((stars (make-string
19778 (if nstars
19779 ;; subtract the star that will be added again by
19780 ;; `org-list-to-subtree'
19781 (1- (prefix-numeric-value current-prefix-arg))
19782 (or (org-current-level) 0))
19783 ?*))
19784 (add-stars
19785 (cond (nstars "") ; stars from prefix only
19786 ((equal stars "") "") ; before first heading
19787 (org-odd-levels-only "*") ; inside heading, odd
19788 (t "")))) ; inside heading, oddeven
19789 (while (< (point) end)
19790 (when (org-at-item-p)
19791 ;; Pay attention to cases when region ends before list.
19792 (let* ((struct (org-list-struct))
19793 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19794 (save-restriction
19795 (narrow-to-region (point) list-end)
19796 (insert
19797 (org-list-to-subtree
19798 (org-list-parse-list t)
19799 '(:istart (concat stars add-stars (funcall get-stars depth))
19800 :icount (concat stars add-stars (funcall get-stars depth)))))))
19801 (setq toggled t))
19802 (forward-line))))
19803 ;; Case 3. Started at normal text: make every line an heading,
19804 ;; skipping headlines and items.
19805 (t (let* ((stars (make-string
19806 (if nstars
19807 (prefix-numeric-value current-prefix-arg)
19808 (or (org-current-level) 0))
19809 ?*))
19810 (add-stars
19811 (cond (nstars "") ; stars from prefix only
19812 ((equal stars "") "*") ; before first heading
19813 (org-odd-levels-only "**") ; inside heading, odd
19814 (t "*"))) ; inside heading, oddeven
19815 (rpl (concat stars add-stars " ")))
19816 (while (< (point) end)
19817 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19818 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19819 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19820 (forward-line)))))))
19821 (unless toggled (message "Cannot toggle heading from here"))))
19823 (defun org-meta-return (&optional arg)
19824 "Insert a new heading or wrap a region in a table.
19825 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19826 See the individual commands for more information."
19827 (interactive "P")
19828 (cond
19829 ((run-hook-with-args-until-success 'org-metareturn-hook))
19830 ((or (org-at-drawer-p) (org-at-property-p))
19831 (newline-and-indent))
19832 ((org-at-table-p)
19833 (call-interactively 'org-table-wrap-region))
19834 (t (call-interactively 'org-insert-heading))))
19836 ;;; Menu entries
19838 (defsubst org-in-subtree-not-table-p ()
19839 "Are we in a subtree and not in a table?"
19840 (and (not (org-before-first-heading-p))
19841 (not (org-at-table-p))))
19843 ;; Define the Org-mode menus
19844 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19845 '("Tbl"
19846 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19847 ["Next Field" org-cycle (org-at-table-p)]
19848 ["Previous Field" org-shifttab (org-at-table-p)]
19849 ["Next Row" org-return (org-at-table-p)]
19850 "--"
19851 ["Blank Field" org-table-blank-field (org-at-table-p)]
19852 ["Edit Field" org-table-edit-field (org-at-table-p)]
19853 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19854 "--"
19855 ("Column"
19856 ["Move Column Left" org-metaleft (org-at-table-p)]
19857 ["Move Column Right" org-metaright (org-at-table-p)]
19858 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19859 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19860 ("Row"
19861 ["Move Row Up" org-metaup (org-at-table-p)]
19862 ["Move Row Down" org-metadown (org-at-table-p)]
19863 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19864 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19865 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19866 "--"
19867 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19868 ("Rectangle"
19869 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19870 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19871 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19872 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19873 "--"
19874 ("Calculate"
19875 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19876 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19877 ["Edit Formulas" org-edit-special (org-at-table-p)]
19878 "--"
19879 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19880 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19881 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19882 "--"
19883 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19884 "--"
19885 ["Sum Column/Rectangle" org-table-sum
19886 (or (org-at-table-p) (org-region-active-p))]
19887 ["Which Column?" org-table-current-column (org-at-table-p)])
19888 ["Debug Formulas"
19889 org-table-toggle-formula-debugger
19890 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19891 ["Show Col/Row Numbers"
19892 org-table-toggle-coordinate-overlays
19893 :style toggle
19894 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19895 "--"
19896 ["Create" org-table-create (and (not (org-at-table-p))
19897 org-enable-table-editor)]
19898 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19899 ["Import from File" org-table-import (not (org-at-table-p))]
19900 ["Export to File" org-table-export (org-at-table-p)]
19901 "--"
19902 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19904 (easy-menu-define org-org-menu org-mode-map "Org menu"
19905 '("Org"
19906 ("Show/Hide"
19907 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19908 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19909 ["Sparse Tree..." org-sparse-tree t]
19910 ["Reveal Context" org-reveal t]
19911 ["Show All" show-all t]
19912 "--"
19913 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19914 "--"
19915 ["New Heading" org-insert-heading t]
19916 ("Navigate Headings"
19917 ["Up" outline-up-heading t]
19918 ["Next" outline-next-visible-heading t]
19919 ["Previous" outline-previous-visible-heading t]
19920 ["Next Same Level" outline-forward-same-level t]
19921 ["Previous Same Level" outline-backward-same-level t]
19922 "--"
19923 ["Jump" org-goto t])
19924 ("Edit Structure"
19925 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19926 "--"
19927 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19928 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19929 "--"
19930 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19931 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19932 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19933 "--"
19934 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19935 "--"
19936 ["Copy visible text" org-copy-visible t]
19937 "--"
19938 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19939 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19940 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19941 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19942 "--"
19943 ["Sort Region/Children" org-sort t]
19944 "--"
19945 ["Convert to odd levels" org-convert-to-odd-levels t]
19946 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19947 ("Editing"
19948 ["Emphasis..." org-emphasize t]
19949 ["Edit Source Example" org-edit-special t]
19950 "--"
19951 ["Footnote new/jump" org-footnote-action t]
19952 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19953 ("Archive"
19954 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19955 "--"
19956 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19957 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19958 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19960 "--"
19961 ("Hyperlinks"
19962 ["Store Link (Global)" org-store-link t]
19963 ["Find existing link to here" org-occur-link-in-agenda-files t]
19964 ["Insert Link" org-insert-link t]
19965 ["Follow Link" org-open-at-point t]
19966 "--"
19967 ["Next link" org-next-link t]
19968 ["Previous link" org-previous-link t]
19969 "--"
19970 ["Descriptive Links"
19971 org-toggle-link-display
19972 :style radio
19973 :selected org-descriptive-links
19975 ["Literal Links"
19976 org-toggle-link-display
19977 :style radio
19978 :selected (not org-descriptive-links)])
19979 "--"
19980 ("TODO Lists"
19981 ["TODO/DONE/-" org-todo t]
19982 ("Select keyword"
19983 ["Next keyword" org-shiftright (org-at-heading-p)]
19984 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19985 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19986 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19987 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19988 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19989 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19990 "--"
19991 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19992 :selected org-enforce-todo-dependencies :style toggle :active t]
19993 "Settings for tree at point"
19994 ["Do Children sequentially" org-toggle-ordered-property :style radio
19995 :selected (org-entry-get nil "ORDERED")
19996 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19997 ["Do Children parallel" org-toggle-ordered-property :style radio
19998 :selected (not (org-entry-get nil "ORDERED"))
19999 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20000 "--"
20001 ["Set Priority" org-priority t]
20002 ["Priority Up" org-shiftup t]
20003 ["Priority Down" org-shiftdown t]
20004 "--"
20005 ["Get news from all feeds" org-feed-update-all t]
20006 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20007 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20008 ("TAGS and Properties"
20009 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20010 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20011 "--"
20012 ["Set property" org-set-property (not (org-before-first-heading-p))]
20013 ["Column view of properties" org-columns t]
20014 ["Insert Column View DBlock" org-insert-columns-dblock t])
20015 ("Dates and Scheduling"
20016 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20017 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20018 ("Change Date"
20019 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20020 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20021 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20022 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20023 ["Compute Time Range" org-evaluate-time-range t]
20024 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20025 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20026 "--"
20027 ["Custom time format" org-toggle-time-stamp-overlays
20028 :style radio :selected org-display-custom-times]
20029 "--"
20030 ["Goto Calendar" org-goto-calendar t]
20031 ["Date from Calendar" org-date-from-calendar t]
20032 "--"
20033 ["Start/Restart Timer" org-timer-start t]
20034 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20035 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20036 ["Insert Timer String" org-timer t]
20037 ["Insert Timer Item" org-timer-item t])
20038 ("Logging work"
20039 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20040 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20041 ["Clock out" org-clock-out t]
20042 ["Clock cancel" org-clock-cancel t]
20043 "--"
20044 ["Mark as default task" org-clock-mark-default-task t]
20045 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20046 ["Goto running clock" org-clock-goto t]
20047 "--"
20048 ["Display times" org-clock-display t]
20049 ["Create clock table" org-clock-report t]
20050 "--"
20051 ["Record DONE time"
20052 (progn (setq org-log-done (not org-log-done))
20053 (message "Switching to %s will %s record a timestamp"
20054 (car org-done-keywords)
20055 (if org-log-done "automatically" "not")))
20056 :style toggle :selected org-log-done])
20057 "--"
20058 ["Agenda Command..." org-agenda t]
20059 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20060 ("File List for Agenda")
20061 ("Special views current file"
20062 ["TODO Tree" org-show-todo-tree t]
20063 ["Check Deadlines" org-check-deadlines t]
20064 ["Timeline" org-timeline t]
20065 ["Tags/Property tree" org-match-sparse-tree t])
20066 "--"
20067 ["Export/Publish..." org-export t]
20068 ("LaTeX"
20069 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20070 :selected org-cdlatex-mode]
20071 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20072 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20073 ["Modify math symbol" org-cdlatex-math-modify
20074 (org-inside-LaTeX-fragment-p)]
20075 ["Insert citation" org-reftex-citation t]
20076 "--"
20077 ["Template for BEAMER" (progn (require 'org-beamer)
20078 (org-insert-beamer-options-template)) t])
20079 "--"
20080 ("MobileOrg"
20081 ["Push Files and Views" org-mobile-push t]
20082 ["Get Captured and Flagged" org-mobile-pull t]
20083 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20084 "--"
20085 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20086 "--"
20087 ("Documentation"
20088 ["Show Version" org-version t]
20089 ["Info Documentation" org-info t])
20090 ("Customize"
20091 ["Browse Org Group" org-customize t]
20092 "--"
20093 ["Expand This Menu" org-create-customize-menu
20094 (fboundp 'customize-menu-create)])
20095 ["Send bug report" org-submit-bug-report t]
20096 "--"
20097 ("Refresh/Reload"
20098 ["Refresh setup current buffer" org-mode-restart t]
20099 ["Reload Org (after update)" org-reload t]
20100 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20103 (defun org-info (&optional node)
20104 "Read documentation for Org-mode in the info system.
20105 With optional NODE, go directly to that node."
20106 (interactive)
20107 (info (format "(org)%s" (or node ""))))
20109 ;;;###autoload
20110 (defun org-submit-bug-report ()
20111 "Submit a bug report on Org-mode via mail.
20113 Don't hesitate to report any problems or inaccurate documentation.
20115 If you don't have setup sending mail from (X)Emacs, please copy the
20116 output buffer into your mail program, as it gives us important
20117 information about your Org-mode version and configuration."
20118 (interactive)
20119 (require 'reporter)
20120 (org-load-modules-maybe)
20121 (org-require-autoloaded-modules)
20122 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20123 (reporter-submit-bug-report
20124 "emacs-orgmode@gnu.org"
20125 (org-version nil 'full)
20126 (let (list)
20127 (save-window-excursion
20128 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20129 (delete-other-windows)
20130 (erase-buffer)
20131 (insert "You are about to submit a bug report to the Org-mode mailing list.
20133 We would like to add your full Org-mode and Outline configuration to the
20134 bug report. This greatly simplifies the work of the maintainer and
20135 other experts on the mailing list.
20137 HOWEVER, some variables you have customized may contain private
20138 information. The names of customers, colleagues, or friends, might
20139 appear in the form of file names, tags, todo states, or search strings.
20140 If you answer yes to the prompt, you might want to check and remove
20141 such private information before sending the email.")
20142 (add-text-properties (point-min) (point-max) '(face org-warning))
20143 (when (yes-or-no-p "Include your Org-mode configuration ")
20144 (mapatoms
20145 (lambda (v)
20146 (and (boundp v)
20147 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20148 (or (and (symbol-value v)
20149 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20150 (and
20151 (get v 'custom-type) (get v 'standard-value)
20152 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20153 (push v list)))))
20154 (kill-buffer (get-buffer "*Warn about privacy*"))
20155 list))
20156 nil nil
20157 "Remember to cover the basics, that is, what you expected to happen and
20158 what in fact did happen. You don't know how to make a good report? See
20160 http://orgmode.org/manual/Feedback.html#Feedback
20162 Your bug report will be posted to the Org-mode mailing list.
20163 ------------------------------------------------------------------------")
20164 (save-excursion
20165 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20166 (replace-match "\\1Bug: \\3 [\\2]")))))
20169 (defun org-install-agenda-files-menu ()
20170 (let ((bl (buffer-list)))
20171 (save-excursion
20172 (while bl
20173 (set-buffer (pop bl))
20174 (if (derived-mode-p 'org-mode) (setq bl nil)))
20175 (when (derived-mode-p 'org-mode)
20176 (easy-menu-change
20177 '("Org") "File List for Agenda"
20178 (append
20179 (list
20180 ["Edit File List" (org-edit-agenda-file-list) t]
20181 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20182 ["Remove Current File from List" org-remove-file t]
20183 ["Cycle through agenda files" org-cycle-agenda-files t]
20184 ["Occur in all agenda files" org-occur-in-agenda-files t]
20185 "--")
20186 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20188 ;;;; Documentation
20190 (defun org-require-autoloaded-modules ()
20191 (interactive)
20192 (mapc 'require
20193 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20194 org-docbook org-exp org-html org-icalendar
20195 org-id org-latex
20196 org-publish org-remember org-table
20197 org-timer org-xoxo)))
20199 ;;;###autoload
20200 (defun org-reload (&optional uncompiled)
20201 "Reload all org lisp files.
20202 With prefix arg UNCOMPILED, load the uncompiled versions."
20203 (interactive "P")
20204 (require 'loadhist)
20205 (let* ((org-dir (org-find-library-dir "org"))
20206 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20207 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20208 (remove-re (mapconcat 'identity
20209 (mapcar (lambda (f) (concat "^" f "$"))
20210 (list (if (featurep 'xemacs)
20211 "org-colview"
20212 "org-colview-xemacs")
20213 "org" "org-loaddefs" "org-version"))
20214 "\\|"))
20215 (feats (delete-dups
20216 (mapcar 'file-name-sans-extension
20217 (mapcar 'file-name-nondirectory
20218 (delq nil
20219 (mapcar 'feature-file
20220 features))))))
20221 (lfeat (append
20222 (sort
20223 (setq feats
20224 (delq nil (mapcar
20225 (lambda (f)
20226 (if (and (string-match feature-re f)
20227 (not (string-match remove-re f)))
20228 f nil))
20229 feats)))
20230 'string-lessp)
20231 (list "org-version" "org")))
20232 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20233 load-uncore load-misses)
20234 (setq load-misses
20235 (delq 't
20236 (mapcar (lambda (f)
20237 (or (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20238 (and (string= org-dir contrib-dir)
20239 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20240 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20241 (add-to-list 'load-uncore f 'append)
20244 lfeat)))
20245 (if load-uncore
20246 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20247 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20248 (if load-misses
20249 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20250 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20251 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20253 ;;;###autoload
20254 (defun org-customize ()
20255 "Call the customize function with org as argument."
20256 (interactive)
20257 (org-load-modules-maybe)
20258 (org-require-autoloaded-modules)
20259 (customize-browse 'org))
20261 (defun org-create-customize-menu ()
20262 "Create a full customization menu for Org-mode, insert it into the menu."
20263 (interactive)
20264 (org-load-modules-maybe)
20265 (org-require-autoloaded-modules)
20266 (if (fboundp 'customize-menu-create)
20267 (progn
20268 (easy-menu-change
20269 '("Org") "Customize"
20270 `(["Browse Org group" org-customize t]
20271 "--"
20272 ,(customize-menu-create 'org)
20273 ["Set" Custom-set t]
20274 ["Save" Custom-save t]
20275 ["Reset to Current" Custom-reset-current t]
20276 ["Reset to Saved" Custom-reset-saved t]
20277 ["Reset to Standard Settings" Custom-reset-standard t]))
20278 (message "\"Org\"-menu now contains full customization menu"))
20279 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20281 ;;;; Miscellaneous stuff
20283 ;;; Generally useful functions
20285 (defun org-get-at-bol (property)
20286 "Get text property PROPERTY at beginning of line."
20287 (get-text-property (point-at-bol) property))
20289 (defun org-find-text-property-in-string (prop s)
20290 "Return the first non-nil value of property PROP in string S."
20291 (or (get-text-property 0 prop s)
20292 (get-text-property (or (next-single-property-change 0 prop s) 0)
20293 prop s)))
20295 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20296 "Display the given MESSAGE as a warning."
20297 (if (fboundp 'display-warning)
20298 (display-warning 'org message
20299 (if (featurep 'xemacs) 'warning :warning))
20300 (let ((buf (get-buffer-create "*Org warnings*")))
20301 (with-current-buffer buf
20302 (goto-char (point-max))
20303 (insert "Warning (Org): " message)
20304 (unless (bolp)
20305 (newline)))
20306 (display-buffer buf)
20307 (sit-for 0))))
20309 (defun org-eval (form)
20310 "Eval FORM and return result."
20311 (condition-case error
20312 (eval form)
20313 (error (format "%%![Error: %s]" error))))
20315 (defun org-in-clocktable-p ()
20316 "Check if the cursor is in a clocktable."
20317 (let ((pos (point)) start)
20318 (save-excursion
20319 (end-of-line 1)
20320 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20321 (setq start (match-beginning 0))
20322 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20323 (>= (match-end 0) pos)
20324 start))))
20326 (defun org-in-commented-line ()
20327 "Is point in a line starting with `#'?"
20328 (equal (char-after (point-at-bol)) ?#))
20330 (defun org-in-indented-comment-line ()
20331 "Is point in a line starting with `#' after some white space?"
20332 (save-excursion
20333 (save-match-data
20334 (goto-char (point-at-bol))
20335 (looking-at "[ \t]*#"))))
20337 (defun org-in-verbatim-emphasis ()
20338 (save-match-data
20339 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20341 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20342 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20343 (if (and marker (marker-buffer marker)
20344 (buffer-live-p (marker-buffer marker)))
20345 (progn
20346 (org-pop-to-buffer-same-window (marker-buffer marker))
20347 (if (or (> marker (point-max)) (< marker (point-min)))
20348 (widen))
20349 (goto-char marker)
20350 (org-show-context 'org-goto))
20351 (if bookmark
20352 (bookmark-jump bookmark)
20353 (error "Cannot find location"))))
20355 (defun org-quote-csv-field (s)
20356 "Quote field for inclusion in CSV material."
20357 (if (string-match "[\",]" s)
20358 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20361 (defun org-force-self-insert (N)
20362 "Needed to enforce self-insert under remapping."
20363 (interactive "p")
20364 (self-insert-command N))
20366 (defun org-string-width (s)
20367 "Compute width of string, ignoring invisible characters.
20368 This ignores character with invisibility property `org-link', and also
20369 characters with property `org-cwidth', because these will become invisible
20370 upon the next fontification round."
20371 (let (b l)
20372 (when (or (eq t buffer-invisibility-spec)
20373 (assq 'org-link buffer-invisibility-spec))
20374 (while (setq b (text-property-any 0 (length s)
20375 'invisible 'org-link s))
20376 (setq s (concat (substring s 0 b)
20377 (substring s (or (next-single-property-change
20378 b 'invisible s) (length s)))))))
20379 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20380 (setq s (concat (substring s 0 b)
20381 (substring s (or (next-single-property-change
20382 b 'org-cwidth s) (length s))))))
20383 (setq l (string-width s) b -1)
20384 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20385 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20388 (defun org-shorten-string (s maxlength)
20389 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20390 If the string is shorter or has length MAXLENGTH, just return the
20391 original string. If it is longer, the functions finds a space in the
20392 string, breaks this string off at that locations and adds three dots
20393 as ellipsis. Including the ellipsis, the string will not be longer
20394 than MAXLENGTH. If finding a good breaking point in the string does
20395 not work, the string is just chopped off in the middle of a word
20396 if necessary."
20397 (if (<= (length s) maxlength)
20399 (let* ((n (max (- maxlength 4) 1))
20400 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20401 (if (string-match re s)
20402 (concat (match-string 1 s) "...")
20403 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20405 (defun org-get-indentation (&optional line)
20406 "Get the indentation of the current line, interpreting tabs.
20407 When LINE is given, assume it represents a line and compute its indentation."
20408 (if line
20409 (if (string-match "^ *" (org-remove-tabs line))
20410 (match-end 0))
20411 (save-excursion
20412 (beginning-of-line 1)
20413 (skip-chars-forward " \t")
20414 (current-column))))
20416 (defun org-get-string-indentation (s)
20417 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20418 (let ((n -1) (i 0) (w tab-width) c)
20419 (catch 'exit
20420 (while (< (setq n (1+ n)) (length s))
20421 (setq c (aref s n))
20422 (cond ((= c ?\ ) (setq i (1+ i)))
20423 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20424 (t (throw 'exit t)))))
20427 (defun org-remove-tabs (s &optional width)
20428 "Replace tabulators in S with spaces.
20429 Assumes that s is a single line, starting in column 0."
20430 (setq width (or width tab-width))
20431 (while (string-match "\t" s)
20432 (setq s (replace-match
20433 (make-string
20434 (- (* width (/ (+ (match-beginning 0) width) width))
20435 (match-beginning 0)) ?\ )
20436 t t s)))
20439 (defun org-fix-indentation (line ind)
20440 "Fix indentation in LINE.
20441 IND is a cons cell with target and minimum indentation.
20442 If the current indentation in LINE is smaller than the minimum,
20443 leave it alone. If it is larger than ind, set it to the target."
20444 (let* ((l (org-remove-tabs line))
20445 (i (org-get-indentation l))
20446 (i1 (car ind)) (i2 (cdr ind)))
20447 (if (>= i i2) (setq l (substring line i2)))
20448 (if (> i1 0)
20449 (concat (make-string i1 ?\ ) l)
20450 l)))
20452 (defun org-remove-indentation (code &optional n)
20453 "Remove the maximum common indentation from the lines in CODE.
20454 N may optionally be the number of spaces to remove."
20455 (with-temp-buffer
20456 (insert code)
20457 (org-do-remove-indentation n)
20458 (buffer-string)))
20460 (defun org-do-remove-indentation (&optional n)
20461 "Remove the maximum common indentation from the buffer."
20462 (untabify (point-min) (point-max))
20463 (let ((min 10000) re)
20464 (if n
20465 (setq min n)
20466 (goto-char (point-min))
20467 (while (re-search-forward "^ *[^ \n]" nil t)
20468 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20469 (unless (or (= min 0) (= min 10000))
20470 (setq re (format "^ \\{%d\\}" min))
20471 (goto-char (point-min))
20472 (while (re-search-forward re nil t)
20473 (replace-match "")
20474 (end-of-line 1))
20475 min)))
20477 (defun org-fill-template (template alist)
20478 "Find each %key of ALIST in TEMPLATE and replace it."
20479 (let ((case-fold-search nil)
20480 entry key value)
20481 (setq alist (sort (copy-sequence alist)
20482 (lambda (a b) (< (length (car a)) (length (car b))))))
20483 (while (setq entry (pop alist))
20484 (setq template
20485 (replace-regexp-in-string
20486 (concat "%" (regexp-quote (car entry)))
20487 (or (cdr entry) "") template t t)))
20488 template))
20490 (defun org-base-buffer (buffer)
20491 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20492 (if (not buffer)
20493 buffer
20494 (or (buffer-base-buffer buffer)
20495 buffer)))
20497 (defun org-trim (s)
20498 "Remove whitespace at beginning and end of string."
20499 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20500 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20503 (defun org-wrap (string &optional width lines)
20504 "Wrap string to either a number of lines, or a width in characters.
20505 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20506 that costs. If there is a word longer than WIDTH, the text is actually
20507 wrapped to the length of that word.
20508 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20509 many lines, whatever width that takes.
20510 The return value is a list of lines, without newlines at the end."
20511 (let* ((words (org-split-string string "[ \t\n]+"))
20512 (maxword (apply 'max (mapcar 'org-string-width words)))
20513 w ll)
20514 (cond (width
20515 (org-do-wrap words (max maxword width)))
20516 (lines
20517 (setq w maxword)
20518 (setq ll (org-do-wrap words maxword))
20519 (if (<= (length ll) lines)
20521 (setq ll words)
20522 (while (> (length ll) lines)
20523 (setq w (1+ w))
20524 (setq ll (org-do-wrap words w)))
20525 ll))
20526 (t (error "Cannot wrap this")))))
20528 (defun org-do-wrap (words width)
20529 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20530 (let (lines line)
20531 (while words
20532 (setq line (pop words))
20533 (while (and words (< (+ (length line) (length (car words))) width))
20534 (setq line (concat line " " (pop words))))
20535 (setq lines (push line lines)))
20536 (nreverse lines)))
20538 (defun org-split-string (string &optional separators)
20539 "Splits STRING into substrings at SEPARATORS.
20540 No empty strings are returned if there are matches at the beginning
20541 and end of string."
20542 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20543 (start 0)
20544 notfirst
20545 (list nil))
20546 (while (and (string-match rexp string
20547 (if (and notfirst
20548 (= start (match-beginning 0))
20549 (< start (length string)))
20550 (1+ start) start))
20551 (< (match-beginning 0) (length string)))
20552 (setq notfirst t)
20553 (or (eq (match-beginning 0) 0)
20554 (and (eq (match-beginning 0) (match-end 0))
20555 (eq (match-beginning 0) start))
20556 (setq list
20557 (cons (substring string start (match-beginning 0))
20558 list)))
20559 (setq start (match-end 0)))
20560 (or (eq start (length string))
20561 (setq list
20562 (cons (substring string start)
20563 list)))
20564 (nreverse list)))
20566 (defun org-quote-vert (s)
20567 "Replace \"|\" with \"\\vert\"."
20568 (while (string-match "|" s)
20569 (setq s (replace-match "\\vert" t t s)))
20572 (defun org-uuidgen-p (s)
20573 "Is S an ID created by UUIDGEN?"
20574 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20576 (defun org-in-src-block-p nil
20577 "Whether point is in a code source block."
20578 (let (ov)
20579 (when (setq ov (overlays-at (point)))
20580 (memq 'org-block-background
20581 (overlay-properties
20582 (car ov))))))
20584 (defun org-context ()
20585 "Return a list of contexts of the current cursor position.
20586 If several contexts apply, all are returned.
20587 Each context entry is a list with a symbol naming the context, and
20588 two positions indicating start and end of the context. Possible
20589 contexts are:
20591 :headline anywhere in a headline
20592 :headline-stars on the leading stars in a headline
20593 :todo-keyword on a TODO keyword (including DONE) in a headline
20594 :tags on the TAGS in a headline
20595 :priority on the priority cookie in a headline
20596 :item on the first line of a plain list item
20597 :item-bullet on the bullet/number of a plain list item
20598 :checkbox on the checkbox in a plain list item
20599 :table in an org-mode table
20600 :table-special on a special filed in a table
20601 :table-table in a table.el table
20602 :clocktable in a clocktable
20603 :src-block in a source block
20604 :link on a hyperlink
20605 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20606 :target on a <<target>>
20607 :radio-target on a <<<radio-target>>>
20608 :latex-fragment on a LaTeX fragment
20609 :latex-preview on a LaTeX fragment with overlaid preview image
20611 This function expects the position to be visible because it uses font-lock
20612 faces as a help to recognize the following contexts: :table-special, :link,
20613 and :keyword."
20614 (let* ((f (get-text-property (point) 'face))
20615 (faces (if (listp f) f (list f)))
20616 (case-fold-search t)
20617 (p (point)) clist o)
20618 ;; First the large context
20619 (cond
20620 ((org-at-heading-p t)
20621 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20622 (when (progn
20623 (beginning-of-line 1)
20624 (looking-at org-todo-line-tags-regexp))
20625 (push (org-point-in-group p 1 :headline-stars) clist)
20626 (push (org-point-in-group p 2 :todo-keyword) clist)
20627 (push (org-point-in-group p 4 :tags) clist))
20628 (goto-char p)
20629 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20630 (if (looking-at "\\[#[A-Z0-9]\\]")
20631 (push (org-point-in-group p 0 :priority) clist)))
20633 ((org-at-item-p)
20634 (push (org-point-in-group p 2 :item-bullet) clist)
20635 (push (list :item (point-at-bol)
20636 (save-excursion (org-end-of-item) (point)))
20637 clist)
20638 (and (org-at-item-checkbox-p)
20639 (push (org-point-in-group p 0 :checkbox) clist)))
20641 ((org-at-table-p)
20642 (push (list :table (org-table-begin) (org-table-end)) clist)
20643 (if (memq 'org-formula faces)
20644 (push (list :table-special
20645 (previous-single-property-change p 'face)
20646 (next-single-property-change p 'face)) clist)))
20647 ((org-at-table-p 'any)
20648 (push (list :table-table) clist)))
20649 (goto-char p)
20651 (let ((case-fold-search t))
20652 ;; New the "medium" contexts: clocktables, source blocks
20653 (cond ((org-in-clocktable-p)
20654 (push (list :clocktable
20655 (and (or (looking-at "#\\+BEGIN: clocktable")
20656 (search-backward "#+BEGIN: clocktable" nil t))
20657 (match-beginning 0))
20658 (and (re-search-forward "#\\+END:?" nil t)
20659 (match-end 0))) clist))
20660 ((org-in-src-block-p)
20661 (push (list :src-block
20662 (and (or (looking-at "#\\+BEGIN_SRC")
20663 (search-backward "#+BEGIN_SRC" nil t))
20664 (match-beginning 0))
20665 (and (search-forward "#+END_SRC" nil t)
20666 (match-beginning 0))) clist))))
20667 (goto-char p)
20669 ;; Now the small context
20670 (cond
20671 ((org-at-timestamp-p)
20672 (push (org-point-in-group p 0 :timestamp) clist))
20673 ((memq 'org-link faces)
20674 (push (list :link
20675 (previous-single-property-change p 'face)
20676 (next-single-property-change p 'face)) clist))
20677 ((memq 'org-special-keyword faces)
20678 (push (list :keyword
20679 (previous-single-property-change p 'face)
20680 (next-single-property-change p 'face)) clist))
20681 ((org-at-target-p)
20682 (push (org-point-in-group p 0 :target) clist)
20683 (goto-char (1- (match-beginning 0)))
20684 (if (looking-at org-radio-target-regexp)
20685 (push (org-point-in-group p 0 :radio-target) clist))
20686 (goto-char p))
20687 ((setq o (car (delq nil
20688 (mapcar
20689 (lambda (x)
20690 (if (memq x org-latex-fragment-image-overlays) x))
20691 (overlays-at (point))))))
20692 (push (list :latex-fragment
20693 (overlay-start o) (overlay-end o)) clist)
20694 (push (list :latex-preview
20695 (overlay-start o) (overlay-end o)) clist))
20696 ((org-inside-LaTeX-fragment-p)
20697 ;; FIXME: positions wrong.
20698 (push (list :latex-fragment (point) (point)) clist)))
20700 (setq clist (nreverse (delq nil clist)))
20701 clist))
20703 ;; FIXME: Compare with at-regexp-p Do we need both?
20704 (defun org-in-regexp (re &optional nlines visually)
20705 "Check if point is inside a match of regexp.
20706 Normally only the current line is checked, but you can include NLINES extra
20707 lines both before and after point into the search.
20708 If VISUALLY is set, require that the cursor is not after the match but
20709 really on, so that the block visually is on the match."
20710 (catch 'exit
20711 (let ((pos (point))
20712 (eol (point-at-eol (+ 1 (or nlines 0))))
20713 (inc (if visually 1 0)))
20714 (save-excursion
20715 (beginning-of-line (- 1 (or nlines 0)))
20716 (while (re-search-forward re eol t)
20717 (if (and (<= (match-beginning 0) pos)
20718 (>= (+ inc (match-end 0)) pos))
20719 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20721 (defun org-at-regexp-p (regexp)
20722 "Is point inside a match of REGEXP in the current line?"
20723 (catch 'exit
20724 (save-excursion
20725 (let ((pos (point)) (end (point-at-eol)))
20726 (beginning-of-line 1)
20727 (while (re-search-forward regexp end t)
20728 (if (and (<= (match-beginning 0) pos)
20729 (>= (match-end 0) pos))
20730 (throw 'exit t)))
20731 nil))))
20733 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20734 "Non-nil when point is between matches of START-RE and END-RE.
20736 Also return a non-nil value when point is on one of the matches.
20738 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20739 buffer positions. Default values are the positions of headlines
20740 surrounding the point.
20742 The functions returns a cons cell whose car (resp. cdr) is the
20743 position before START-RE (resp. after END-RE)."
20744 (save-match-data
20745 (let ((pos (point))
20746 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20747 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20748 beg end)
20749 (save-excursion
20750 ;; Point is on a block when on START-RE or if START-RE can be
20751 ;; found before it...
20752 (and (or (org-at-regexp-p start-re)
20753 (re-search-backward start-re limit-up t))
20754 (setq beg (match-beginning 0))
20755 ;; ... and END-RE after it...
20756 (goto-char (match-end 0))
20757 (re-search-forward end-re limit-down t)
20758 (> (setq end (match-end 0)) pos)
20759 ;; ... without another START-RE in-between.
20760 (goto-char (match-beginning 0))
20761 (not (re-search-backward start-re (1+ beg) t))
20762 ;; Return value.
20763 (cons beg end))))))
20765 (defun org-in-block-p (names)
20766 "Non-nil when point belongs to a block whose name belongs to NAMES.
20768 NAMES is a list of strings containing names of blocks.
20770 Return first block name matched, or nil. Beware that in case of
20771 nested blocks, the returned name may not belong to the closest
20772 block from point."
20773 (save-match-data
20774 (catch 'exit
20775 (let ((case-fold-search t)
20776 (lim-up (save-excursion (outline-previous-heading)))
20777 (lim-down (save-excursion (outline-next-heading))))
20778 (mapc (lambda (name)
20779 (let ((n (regexp-quote name)))
20780 (when (org-between-regexps-p
20781 (concat "^[ \t]*#\\+begin_" n)
20782 (concat "^[ \t]*#\\+end_" n)
20783 lim-up lim-down)
20784 (throw 'exit n))))
20785 names))
20786 nil)))
20788 (defun org-occur-in-agenda-files (regexp &optional nlines)
20789 "Call `multi-occur' with buffers for all agenda files."
20790 (interactive "sOrg-files matching: \np")
20791 (let* ((files (org-agenda-files))
20792 (tnames (mapcar 'file-truename files))
20793 (extra org-agenda-text-search-extra-files)
20795 (when (eq (car extra) 'agenda-archives)
20796 (setq extra (cdr extra))
20797 (setq files (org-add-archive-files files)))
20798 (while (setq f (pop extra))
20799 (unless (member (file-truename f) tnames)
20800 (add-to-list 'files f 'append)
20801 (add-to-list 'tnames (file-truename f) 'append)))
20802 (multi-occur
20803 (mapcar (lambda (x)
20804 (with-current-buffer
20805 (or (get-file-buffer x) (find-file-noselect x))
20806 (widen)
20807 (current-buffer)))
20808 files)
20809 regexp)))
20811 (if (boundp 'occur-mode-find-occurrence-hook)
20812 ;; Emacs 23
20813 (add-hook 'occur-mode-find-occurrence-hook
20814 (lambda ()
20815 (when (derived-mode-p 'org-mode)
20816 (org-reveal))))
20817 ;; Emacs 22
20818 (defadvice occur-mode-goto-occurrence
20819 (after org-occur-reveal activate)
20820 (and (derived-mode-p 'org-mode) (org-reveal)))
20821 (defadvice occur-mode-goto-occurrence-other-window
20822 (after org-occur-reveal activate)
20823 (and (derived-mode-p 'org-mode) (org-reveal)))
20824 (defadvice occur-mode-display-occurrence
20825 (after org-occur-reveal activate)
20826 (when (derived-mode-p 'org-mode)
20827 (let ((pos (occur-mode-find-occurrence)))
20828 (with-current-buffer (marker-buffer pos)
20829 (save-excursion
20830 (goto-char pos)
20831 (org-reveal)))))))
20833 (defun org-occur-link-in-agenda-files ()
20834 "Create a link and search for it in the agendas.
20835 The link is not stored in `org-stored-links', it is just created
20836 for the search purpose."
20837 (interactive)
20838 (let ((link (condition-case nil
20839 (org-store-link nil)
20840 (error "Unable to create a link to here"))))
20841 (org-occur-in-agenda-files (regexp-quote link))))
20843 (defun org-uniquify (list)
20844 "Remove duplicate elements from LIST."
20845 (let (res)
20846 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20847 res))
20849 (defun org-delete-all (elts list)
20850 "Remove all elements in ELTS from LIST."
20851 (while elts
20852 (setq list (delete (pop elts) list)))
20853 list)
20855 (defun org-count (cl-item cl-seq)
20856 "Count the number of occurrences of ITEM in SEQ.
20857 Taken from `count' in cl-seq.el with all keyword arguments removed."
20858 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20859 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20860 (while (< cl-start cl-end)
20861 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20862 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20863 (setq cl-start (1+ cl-start)))
20864 cl-count))
20866 (defun org-remove-if (predicate seq)
20867 "Remove everything from SEQ that fulfills PREDICATE."
20868 (let (res e)
20869 (while seq
20870 (setq e (pop seq))
20871 (if (not (funcall predicate e)) (push e res)))
20872 (nreverse res)))
20874 (defun org-remove-if-not (predicate seq)
20875 "Remove everything from SEQ that does not fulfill PREDICATE."
20876 (let (res e)
20877 (while seq
20878 (setq e (pop seq))
20879 (if (funcall predicate e) (push e res)))
20880 (nreverse res)))
20882 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20883 "Reduce two-argument FUNCTION across SEQ.
20884 Taken from `reduce' in cl-seq.el with all keyword arguments but
20885 \":initial-value\" removed."
20886 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20887 (cadr (memq :initial-value cl-keys)))
20888 (cl-seq (pop cl-seq))
20889 (t (funcall cl-func)))))
20890 (while cl-seq
20891 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20892 cl-accum))
20894 (defun org-back-over-empty-lines ()
20895 "Move backwards over whitespace, to the beginning of the first empty line.
20896 Returns the number of empty lines passed."
20897 (let ((pos (point)))
20898 (if (cdr (assoc 'heading org-blank-before-new-entry))
20899 (skip-chars-backward " \t\n\r")
20900 (unless (eobp)
20901 (forward-line -1)))
20902 (beginning-of-line 2)
20903 (goto-char (min (point) pos))
20904 (count-lines (point) pos)))
20906 (defun org-skip-whitespace ()
20907 (skip-chars-forward " \t\n\r"))
20909 (defun org-point-in-group (point group &optional context)
20910 "Check if POINT is in match-group GROUP.
20911 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20912 match. If the match group does not exist or point is not inside it,
20913 return nil."
20914 (and (match-beginning group)
20915 (>= point (match-beginning group))
20916 (<= point (match-end group))
20917 (if context
20918 (list context (match-beginning group) (match-end group))
20919 t)))
20921 (defun org-switch-to-buffer-other-window (&rest args)
20922 "Switch to buffer in a second window on the current frame.
20923 In particular, do not allow pop-up frames.
20924 Returns the newly created buffer."
20925 (let (pop-up-frames special-display-buffer-names special-display-regexps
20926 special-display-function)
20927 (apply 'switch-to-buffer-other-window args)))
20929 (defun org-combine-plists (&rest plists)
20930 "Create a single property list from all plists in PLISTS.
20931 The process starts by copying the first list, and then setting properties
20932 from the other lists. Settings in the last list are the most significant
20933 ones and overrule settings in the other lists."
20934 (let ((rtn (copy-sequence (pop plists)))
20935 p v ls)
20936 (while plists
20937 (setq ls (pop plists))
20938 (while ls
20939 (setq p (pop ls) v (pop ls))
20940 (setq rtn (plist-put rtn p v))))
20941 rtn))
20943 (defun org-replace-escapes (string table)
20944 "Replace %-escapes in STRING with values in TABLE.
20945 TABLE is an association list with keys like \"%a\" and string values.
20946 The sequences in STRING may contain normal field width and padding information,
20947 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20948 so values can contain further %-escapes if they are define later in TABLE."
20949 (let ((tbl (copy-alist table))
20950 (case-fold-search nil)
20951 (pchg 0)
20952 e re rpl)
20953 (while (setq e (pop tbl))
20954 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20955 (when (and (cdr e) (string-match re (cdr e)))
20956 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20957 (safe "SREF"))
20958 (add-text-properties 0 3 (list 'sref sref) safe)
20959 (setcdr e (replace-match safe t t (cdr e)))))
20960 (while (string-match re string)
20961 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20962 (cdr e)))
20963 (setq string (replace-match rpl t t string))))
20964 (while (setq pchg (next-property-change pchg string))
20965 (let ((sref (get-text-property pchg 'sref string)))
20966 (when (and sref (string-match "SREF" string pchg))
20967 (setq string (replace-match sref t t string)))))
20968 string))
20970 (defun org-sublist (list start end)
20971 "Return a section of LIST, from START to END.
20972 Counting starts at 1."
20973 (let (rtn (c start))
20974 (setq list (nthcdr (1- start) list))
20975 (while (and list (<= c end))
20976 (push (pop list) rtn)
20977 (setq c (1+ c)))
20978 (nreverse rtn)))
20980 (defun org-find-base-buffer-visiting (file)
20981 "Like `find-buffer-visiting' but always return the base buffer and
20982 not an indirect buffer."
20983 (let ((buf (or (get-file-buffer file)
20984 (find-buffer-visiting file))))
20985 (if buf
20986 (or (buffer-base-buffer buf) buf)
20987 nil)))
20989 (defun org-image-file-name-regexp (&optional extensions)
20990 "Return regexp matching the file names of images.
20991 If EXTENSIONS is given, only match these."
20992 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20993 (image-file-name-regexp)
20994 (let ((image-file-name-extensions
20995 (or extensions
20996 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20997 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20998 (concat "\\."
20999 (regexp-opt (nconc (mapcar 'upcase
21000 image-file-name-extensions)
21001 image-file-name-extensions)
21003 "\\'"))))
21005 (defun org-file-image-p (file &optional extensions)
21006 "Return non-nil if FILE is an image."
21007 (save-match-data
21008 (string-match (org-image-file-name-regexp extensions) file)))
21010 (defun org-get-cursor-date ()
21011 "Return the date at cursor in as a time.
21012 This works in the calendar and in the agenda, anywhere else it just
21013 returns the current time."
21014 (let (date day defd)
21015 (cond
21016 ((eq major-mode 'calendar-mode)
21017 (setq date (calendar-cursor-to-date)
21018 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21019 ((eq major-mode 'org-agenda-mode)
21020 (setq day (get-text-property (point) 'day))
21021 (if day
21022 (setq date (calendar-gregorian-from-absolute day)
21023 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
21024 (nth 2 date))))))
21025 (or defd (current-time))))
21027 (defun org-mark-subtree (&optional up)
21028 "Mark the current subtree.
21029 This puts point at the start of the current subtree, and mark at
21030 the end. If a numeric prefix UP is given, move up into the
21031 hierarchy of headlines by UP levels before marking the subtree."
21032 (interactive "P")
21033 (org-with-limited-levels
21034 (cond ((org-at-heading-p) (beginning-of-line))
21035 ((org-before-first-heading-p) (error "Not in a subtree"))
21036 (t (outline-previous-visible-heading 1))))
21037 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21038 (if (org-called-interactively-p 'any)
21039 (call-interactively 'org-mark-element)
21040 (org-mark-element)))
21043 ;;; Macros
21045 ;; Macros are expanded with `org-macro-replace-all', which relies
21046 ;; internally on `org-macro-expand'.
21048 ;; Default templates for expansion are stored in the buffer-local
21049 ;; variable `org-macro-templates'. This variable is updated by
21050 ;; `org-macro-initialize-templates'.
21052 ;; Along with macros defined through #+MACRO: keyword, default
21053 ;; templates include the following hard-coded macros:
21054 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21055 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21057 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21058 ;; {{{title}}} will also be provided.
21061 (defvar org-macro-templates nil
21062 "Alist containing all macro templates in current buffer.
21063 Associations are in the shape of (NAME . TEMPLATE) where NAME
21064 stands for macro's name and template for its replacement value,
21065 both as strings. This is an internal variable. Do not set it
21066 directly, use instead:
21068 #+MACRO: name template")
21069 (make-variable-buffer-local 'org-macro-templates)
21071 (defun org-macro-expand (macro templates)
21072 "Return expanded MACRO, as a string.
21073 MACRO is an object, obtained, for example, with
21074 `org-element-context'. TEMPLATES is an alist of templates used
21075 for expansion. See `org-macro-templates' for a buffer-local
21076 default value. Return nil if no template was found."
21077 (let ((template
21078 ;; Macro names are case-insensitive.
21079 (cdr (assoc-string (org-element-property :key macro) templates t))))
21080 (when template
21081 (let ((value (replace-regexp-in-string
21082 "\\$[0-9]+"
21083 (lambda (arg)
21084 (or (nth (1- (string-to-number (substring arg 1)))
21085 (org-element-property :args macro))
21086 ;; No argument provided: remove
21087 ;; place-holder.
21088 ""))
21089 template)))
21090 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21091 (when (string-match "\\`(eval\\>" value)
21092 (setq value (eval (read value))))
21093 ;; Return string.
21094 (format "%s" (or value ""))))))
21096 (defun org-macro-replace-all (templates)
21097 "Replace all macros in current buffer by their expansion.
21098 TEMPLATES is an alist of templates used for expansion. See
21099 `org-macro-templates' for a buffer-local default value."
21100 (save-excursion
21101 (goto-char (point-min))
21102 (let (record)
21103 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21104 (let ((object (org-element-context)))
21105 (when (eq (org-element-type object) 'macro)
21106 (let* ((value (org-macro-expand object templates))
21107 (begin (org-element-property :begin object))
21108 (signature (list begin
21109 object
21110 (org-element-property :args object))))
21111 ;; Avoid circular dependencies by checking if the same
21112 ;; macro with the same arguments is expanded at the same
21113 ;; position twice.
21114 (if (member signature record)
21115 (error "Circular macro expansion: %s"
21116 (org-element-property :key object))
21117 (when value
21118 (push signature record)
21119 (delete-region
21120 begin
21121 ;; Preserve white spaces after the macro.
21122 (progn (goto-char (org-element-property :end object))
21123 (skip-chars-backward " \t")
21124 (point)))
21125 ;; Leave point before replacement in case of recursive
21126 ;; expansions.
21127 (save-excursion (insert value)))))))))))
21129 (defun org-macro-initialize-templates ()
21130 "Collect macro templates defined in current buffer.
21131 Templates are stored in buffer-local variable
21132 `org-macro-templates'. In addition to buffer-defined macros, the
21133 function installs the following ones: \"property\",
21134 \"time\". and, if the buffer is associated to a file,
21135 \"input-file\" and \"modification-time\"."
21136 (let ((case-fold-search t)
21137 (set-template
21138 (lambda (cell)
21139 ;; Add CELL to `org-macro-templates' if there's no
21140 ;; association matching its name already. Otherwise,
21141 ;; replace old association with the new one in that
21142 ;; variable.
21143 (let ((old-template (assoc (car cell) org-macro-templates)))
21144 (if old-template (setcdr old-template (cdr cell))
21145 (push cell org-macro-templates))))))
21146 ;; Install buffer-local macros.
21147 (org-with-wide-buffer
21148 (goto-char (point-min))
21149 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21150 (let ((element (org-element-at-point)))
21151 (when (eq (org-element-type element) 'keyword)
21152 (let ((value (org-element-property :value element)))
21153 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21154 (funcall set-template
21155 (cons (match-string 1 value)
21156 (or (match-string 2 value) "")))))))))
21157 ;; Install hard-coded macros.
21158 (mapc (lambda (cell) (funcall set-template cell))
21159 (list
21160 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21161 (cons "time" "(eval (format-time-string \"$1\"))")))
21162 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21163 (when (and visited-file (file-exists-p visited-file))
21164 (mapc (lambda (cell) (funcall set-template cell))
21165 (list
21166 (cons "input-file" (file-name-nondirectory visited-file))
21167 (cons "modification-time"
21168 (format "(eval (format-time-string \"$1\" '%s))"
21169 (prin1-to-string
21170 (nth 5 (file-attributes visited-file)))))))))))
21173 ;;; Indentation
21175 (defun org-indent-line ()
21176 "Indent line depending on context."
21177 (interactive)
21178 (let* ((pos (point))
21179 (itemp (org-at-item-p))
21180 (case-fold-search t)
21181 (org-drawer-regexp (or org-drawer-regexp "\000"))
21182 (inline-task-p (and (featurep 'org-inlinetask)
21183 (org-inlinetask-in-task-p)))
21184 (inline-re (and inline-task-p
21185 (org-inlinetask-outline-regexp)))
21186 column)
21187 (if (and orgstruct-is-++ (eq pos (point)))
21188 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21189 (indent-according-to-mode))
21190 (beginning-of-line 1)
21191 (cond
21192 ;; Headings
21193 ((looking-at org-outline-regexp) (setq column 0))
21194 ;; Included files
21195 ((looking-at "#\\+include:") (setq column 0))
21196 ;; Footnote definition
21197 ((looking-at org-footnote-definition-re) (setq column 0))
21198 ;; Literal examples
21199 ((looking-at "[ \t]*:\\( \\|$\\)")
21200 (setq column (org-get-indentation))) ; do nothing
21201 ;; Lists
21202 ((ignore-errors (goto-char (org-in-item-p)))
21203 (setq column (if itemp
21204 (org-get-indentation)
21205 (org-list-item-body-column (point))))
21206 (goto-char pos))
21207 ;; Drawers
21208 ((and (looking-at "[ \t]*:END:")
21209 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21210 (save-excursion
21211 (goto-char (1- (match-beginning 1)))
21212 (setq column (current-column))))
21213 ;; Special blocks
21214 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21215 (save-excursion
21216 (re-search-backward
21217 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21218 (setq column (org-get-indentation (match-string 0))))
21219 ((and (not (looking-at "[ \t]*#\\+begin_"))
21220 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21221 (save-excursion
21222 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21223 (setq column
21224 (cond ((equal (downcase (match-string 1)) "src")
21225 ;; src blocks: let `org-edit-src-exit' handle them
21226 (org-get-indentation))
21227 ((equal (downcase (match-string 1)) "example")
21228 (max (org-get-indentation)
21229 (org-get-indentation (match-string 0))))
21231 (org-get-indentation (match-string 0))))))
21232 ;; This line has nothing special, look at the previous relevant
21233 ;; line to compute indentation
21235 (beginning-of-line 0)
21236 (while (and (not (bobp))
21237 (not (looking-at org-drawer-regexp))
21238 ;; When point started in an inline task, do not move
21239 ;; above task starting line.
21240 (not (and inline-task-p (looking-at inline-re)))
21241 ;; Skip drawers, blocks, empty lines, verbatim,
21242 ;; comments, tables, footnotes definitions, lists,
21243 ;; inline tasks.
21244 (or (and (looking-at "[ \t]*:END:")
21245 (re-search-backward org-drawer-regexp nil t))
21246 (and (looking-at "[ \t]*#\\+end_")
21247 (re-search-backward "[ \t]*#\\+begin_"nil t))
21248 (looking-at "[ \t]*[\n:#|]")
21249 (looking-at org-footnote-definition-re)
21250 (and (ignore-errors (goto-char (org-in-item-p)))
21251 (goto-char
21252 (org-list-get-top-point (org-list-struct))))
21253 (and (not inline-task-p)
21254 (featurep 'org-inlinetask)
21255 (org-inlinetask-in-task-p)
21256 (or (org-inlinetask-goto-beginning) t))))
21257 (beginning-of-line 0))
21258 (cond
21259 ;; There was an heading above.
21260 ((looking-at "\\*+[ \t]+")
21261 (if (not org-adapt-indentation)
21262 (setq column 0)
21263 (goto-char (match-end 0))
21264 (setq column (current-column))))
21265 ;; A drawer had started and is unfinished
21266 ((looking-at org-drawer-regexp)
21267 (goto-char (1- (match-beginning 1)))
21268 (setq column (current-column)))
21269 ;; Else, nothing noticeable found: get indentation and go on.
21270 (t (setq column (org-get-indentation))))))
21271 ;; Now apply indentation and move cursor accordingly
21272 (goto-char pos)
21273 (if (<= (current-column) (current-indentation))
21274 (org-indent-line-to column)
21275 (save-excursion (org-indent-line-to column)))
21276 ;; Special polishing for properties, see `org-property-format'
21277 (setq column (current-column))
21278 (beginning-of-line 1)
21279 (if (looking-at
21280 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21281 (replace-match (concat (match-string 1)
21282 (format org-property-format
21283 (match-string 2) (match-string 3)))
21284 t t))
21285 (org-move-to-column column))))
21287 (defun org-indent-drawer ()
21288 "Indent the drawer at point."
21289 (interactive)
21290 (let ((p (point))
21291 (e (and (save-excursion (re-search-forward ":END:" nil t))
21292 (match-end 0)))
21293 (folded
21294 (save-excursion
21295 (end-of-line)
21296 (when (overlays-at (point))
21297 (member 'invisible (overlay-properties
21298 (car (overlays-at (point)))))))))
21299 (when folded (org-cycle))
21300 (indent-for-tab-command)
21301 (while (and (move-beginning-of-line 2) (< (point) e))
21302 (indent-for-tab-command))
21303 (goto-char p)
21304 (when folded (org-cycle)))
21305 (message "Drawer at point indented"))
21307 (defun org-indent-block ()
21308 "Indent the block at point."
21309 (interactive)
21310 (let ((p (point))
21311 (case-fold-search t)
21312 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21313 (match-end 0)))
21314 (folded
21315 (save-excursion
21316 (end-of-line)
21317 (when (overlays-at (point))
21318 (member 'invisible (overlay-properties
21319 (car (overlays-at (point)))))))))
21320 (when folded (org-cycle))
21321 (indent-for-tab-command)
21322 (while (and (move-beginning-of-line 2) (< (point) e))
21323 (indent-for-tab-command))
21324 (goto-char p)
21325 (when folded (org-cycle)))
21326 (message "Block at point indented"))
21328 (defun org-indent-region (start end)
21329 "Indent region."
21330 (interactive "r")
21331 (save-excursion
21332 (let ((line-end (org-current-line end)))
21333 (goto-char start)
21334 (while (< (org-current-line) line-end)
21335 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21336 (t (call-interactively 'org-indent-line)))
21337 (move-beginning-of-line 2)))))
21340 ;;; Filling
21342 ;; We use our own fill-paragraph and auto-fill functions.
21344 ;; `org-fill-paragraph' relies on adaptive filling and context
21345 ;; checking. Appropriate `fill-prefix' is computed with
21346 ;; `org-adaptive-fill-function'.
21348 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21349 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21350 ;; `org-adaptive-fill-function' value. Internally,
21351 ;; `org-comment-line-break-function' breaks the line.
21353 ;; `org-setup-filling' installs filling and auto-filling related
21354 ;; variables during `org-mode' initialization.
21356 (defun org-setup-filling ()
21357 (interactive)
21358 ;; Prevent auto-fill from inserting unwanted new items.
21359 (when (boundp 'fill-nobreak-predicate)
21360 (org-set-local
21361 'fill-nobreak-predicate
21362 (org-uniquify
21363 (append fill-nobreak-predicate
21364 '(org-fill-paragraph-separate-nobreak-p
21365 org-fill-line-break-nobreak-p)))))
21366 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21367 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21368 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21369 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21371 (defvar org-element-paragraph-separate) ; org-element.el
21372 (defun org-fill-paragraph-separate-nobreak-p ()
21373 "Non-nil when a line break at point would insert a new item."
21374 (looking-at (substring org-element-paragraph-separate 1)))
21376 (defun org-fill-line-break-nobreak-p ()
21377 "Non-nil when a line break at point would create an Org line break."
21378 (save-excursion
21379 (skip-chars-backward "[ \t]")
21380 (skip-chars-backward "\\\\")
21381 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21383 (declare-function message-in-body-p "message" ())
21384 (defun org-adaptive-fill-function ()
21385 "Compute a fill prefix for the current line.
21386 Return fill prefix, as a string, or nil if current line isn't
21387 meant to be filled."
21388 (org-with-wide-buffer
21389 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21390 ;; FIXME: This is really the job of orgstruct++-mode
21391 (let* ((p (line-beginning-position))
21392 (element (save-excursion (beginning-of-line)
21393 (org-element-at-point)))
21394 (type (org-element-type element))
21395 (post-affiliated (org-element-property :post-affiliated element)))
21396 (unless (and post-affiliated (< p post-affiliated))
21397 (case type
21398 (comment (looking-at "[ \t]*# ?") (match-string 0))
21399 (footnote-definition "")
21400 ((item plain-list)
21401 (make-string (org-list-item-body-column
21402 (or post-affiliated
21403 (org-element-property :begin element)))
21404 ? ))
21405 (paragraph
21406 ;; Fill prefix is usually the same as the current line,
21407 ;; except if the paragraph is at the beginning of an item.
21408 (let ((parent (org-element-property :parent element)))
21409 (cond ((eq (org-element-type parent) 'item)
21410 (make-string (org-list-item-body-column
21411 (org-element-property :begin parent))
21412 ? ))
21413 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21414 (match-string 0))
21415 (t ""))))
21416 (comment-block
21417 ;; Only fill contents if P is within block boundaries.
21418 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21419 (forward-line)
21420 (point)))
21421 (cend (save-excursion
21422 (goto-char (org-element-property :end element))
21423 (skip-chars-backward " \r\t\n")
21424 (line-beginning-position))))
21425 (when (and (>= p cbeg) (< p cend))
21426 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21427 (match-string 0)
21428 ""))))))))))
21430 (declare-function message-goto-body "message" ())
21431 (defvar message-cite-prefix-regexp) ; From message.el
21432 (defvar org-element-all-objects) ; From org-element.el
21433 (defun org-fill-paragraph (&optional justify)
21434 "Fill element at point, when applicable.
21436 This function only applies to comment blocks, comments, example
21437 blocks and paragraphs. Also, as a special case, re-align table
21438 when point is at one.
21440 If JUSTIFY is non-nil (interactively, with prefix argument),
21441 justify as well. If `sentence-end-double-space' is non-nil, then
21442 period followed by one space does not end a sentence, so don't
21443 break a line there. The variable `fill-column' controls the
21444 width for filling.
21446 For convenience, when point is at a plain list, an item or
21447 a footnote definition, try to fill the first paragraph within."
21448 ;; Falls back on message-fill-paragraph when necessary
21449 (interactive)
21450 (if (and (derived-mode-p 'message-mode)
21451 (or (not (message-in-body-p))
21452 (save-excursion (move-beginning-of-line 1)
21453 (looking-at message-cite-prefix-regexp))))
21454 (let ((fill-paragraph-function
21455 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21456 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21457 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21458 (paragraph-separate
21459 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21460 (fill-paragraph nil))
21461 (save-excursion
21462 ;; Move to end of line in order to get the first paragraph
21463 ;; within a plain list or a footnote definition.
21464 (end-of-line)
21465 (let ((element (org-element-at-point)))
21466 ;; First check if point is in a blank line at the beginning of
21467 ;; the buffer. In that case, ignore filling.
21468 (if (< (point) (org-element-property :begin element)) t
21469 (case (org-element-type element)
21470 ;; Align Org tables, leave table.el tables as-is.
21471 (table-row (org-table-align) t)
21472 (table
21473 (when (eq (org-element-property :type element) 'org)
21474 (org-table-align))
21476 (paragraph
21477 ;; Paragraphs may contain `line-break' type objects.
21478 (let ((beg (max (point-min)
21479 (org-element-property :contents-begin element)))
21480 (end (min (point-max)
21481 (org-element-property :contents-end element))))
21482 ;; Do nothing if point is at an affiliated keyword.
21483 (if (< (point) beg) t
21484 (when (derived-mode-p 'message-mode)
21485 ;; In `message-mode', do not fill following
21486 ;; citation in current paragraph nor text before
21487 ;; message body.
21488 (let ((body-start (save-excursion (message-goto-body))))
21489 (when body-start (setq beg (max body-start beg))))
21490 (when (save-excursion
21491 (re-search-forward
21492 (concat "^" message-cite-prefix-regexp) end t))
21493 (setq end (match-beginning 0))))
21494 ;; Fill paragraph, taking line breaks into
21495 ;; consideration. For that, slice the paragraph
21496 ;; using line breaks as separators, and fill the
21497 ;; parts in reverse order to avoid messing with
21498 ;; markers.
21499 (save-excursion
21500 (goto-char end)
21501 (mapc
21502 (lambda (pos)
21503 (fill-region-as-paragraph pos (point) justify)
21504 (goto-char pos))
21505 ;; Find the list of ending positions for line
21506 ;; breaks in the current paragraph. Add paragraph
21507 ;; beginning to include first slice.
21508 (nreverse
21509 (cons
21511 (org-element-map
21512 (org-element--parse-objects
21513 beg end nil org-element-all-objects)
21514 'line-break
21515 (lambda (lb) (org-element-property :end lb)))))))
21516 t)))
21517 ;; Contents of `comment-block' type elements should be
21518 ;; filled as plain text, but only if point is within block
21519 ;; markers.
21520 (comment-block
21521 (let* ((case-fold-search t)
21522 (beg (save-excursion
21523 (goto-char (org-element-property :begin element))
21524 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21525 (forward-line)
21526 (point)))
21527 (end (save-excursion
21528 (goto-char (org-element-property :end element))
21529 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21530 (line-beginning-position))))
21531 (when (and (>= (point) beg) (< (point) end))
21532 (fill-region-as-paragraph
21533 (save-excursion
21534 (end-of-line)
21535 (re-search-backward "^[ \t]*$" beg 'move)
21536 (line-beginning-position))
21537 (save-excursion
21538 (beginning-of-line)
21539 (re-search-forward "^[ \t]*$" end 'move)
21540 (line-beginning-position))
21541 justify)))
21543 ;; Fill comments.
21544 (comment (fill-comment-paragraph justify))
21545 ;; Ignore every other element.
21546 (otherwise t)))))))
21548 (defun org-auto-fill-function ()
21549 "Auto-fill function."
21550 ;; Check if auto-filling is meaningful.
21551 (let ((fc (current-fill-column)))
21552 (when (and fc (> (current-column) fc))
21553 (let* ((fill-prefix (org-adaptive-fill-function))
21554 ;; Enforce empty fill prefix, if required. Otherwise, it
21555 ;; will be computed again.
21556 (adaptive-fill-mode (not (equal fill-prefix ""))))
21557 (when fill-prefix (do-auto-fill))))))
21559 (defun org-comment-line-break-function (&optional soft)
21560 "Break line at point and indent, continuing comment if within one.
21561 The inserted newline is marked hard if variable
21562 `use-hard-newlines' is true, unless optional argument SOFT is
21563 non-nil."
21564 (if soft (insert-and-inherit ?\n) (newline 1))
21565 (save-excursion (forward-char -1) (delete-horizontal-space))
21566 (delete-horizontal-space)
21567 (indent-to-left-margin)
21568 (insert-before-markers-and-inherit fill-prefix))
21571 ;;; Comments
21573 ;; Org comments syntax is quite complex. It requires the entire line
21574 ;; to be just a comment. Also, even with the right syntax at the
21575 ;; beginning of line, some some elements (i.e. verse-block or
21576 ;; example-block) don't accept comments. Usual Emacs comment commands
21577 ;; cannot cope with those requirements. Therefore, Org replaces them.
21579 ;; Org still relies on `comment-dwim', but cannot trust
21580 ;; `comment-only-p'. So, `comment-region-function' and
21581 ;; `uncomment-region-function' both point
21582 ;; to`org-comment-or-uncomment-region'. Eventually,
21583 ;; `org-insert-comment' takes care of insertion of comments at the
21584 ;; beginning of line.
21586 ;; `org-setup-comments-handling' install comments related variables
21587 ;; during `org-mode' initialization.
21589 (defun org-setup-comments-handling ()
21590 (interactive)
21591 (org-set-local 'comment-use-syntax nil)
21592 (org-set-local 'comment-start "# ")
21593 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21594 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21595 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21596 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21598 (defun org-insert-comment ()
21599 "Insert an empty comment above current line.
21600 If the line is empty, insert comment at its beginning."
21601 (beginning-of-line)
21602 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21603 (org-indent-line)
21604 (insert "# "))
21606 (defvar comment-empty-lines) ; From newcomment.el.
21607 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21608 "Comment or uncomment each non-blank line in the region.
21609 Uncomment each non-blank line between BEG and END if it only
21610 contains commented lines. Otherwise, comment them."
21611 (save-restriction
21612 ;; Restrict region
21613 (narrow-to-region (save-excursion (goto-char beg)
21614 (skip-chars-forward " \r\t\n" end)
21615 (line-beginning-position))
21616 (save-excursion (goto-char end)
21617 (skip-chars-backward " \r\t\n" beg)
21618 (line-end-position)))
21619 (let ((uncommentp
21620 ;; UNCOMMENTP is non-nil when every non blank line between
21621 ;; BEG and END is a comment.
21622 (save-excursion
21623 (goto-char (point-min))
21624 (while (and (not (eobp))
21625 (let ((element (org-element-at-point)))
21626 (and (eq (org-element-type element) 'comment)
21627 (goto-char (min (point-max)
21628 (org-element-property
21629 :end element)))))))
21630 (eobp))))
21631 (if uncommentp
21632 ;; Only blank lines and comments in region: uncomment it.
21633 (save-excursion
21634 (goto-char (point-min))
21635 (while (not (eobp))
21636 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21637 (replace-match "" nil nil nil 1))
21638 (forward-line)))
21639 ;; Comment each line in region.
21640 (let ((min-indent (point-max)))
21641 ;; First find the minimum indentation across all lines.
21642 (save-excursion
21643 (goto-char (point-min))
21644 (while (and (not (eobp)) (not (zerop min-indent)))
21645 (unless (looking-at "[ \t]*$")
21646 (setq min-indent (min min-indent (current-indentation))))
21647 (forward-line)))
21648 ;; Then loop over all lines.
21649 (save-excursion
21650 (goto-char (point-min))
21651 (while (not (eobp))
21652 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21653 (org-move-to-column min-indent t)
21654 (insert comment-start))
21655 (forward-line))))))))
21658 ;;; Other stuff.
21660 (defun org-toggle-fixed-width-section (arg)
21661 "Toggle the fixed-width export.
21662 If there is no active region, the QUOTE keyword at the current headline is
21663 inserted or removed. When present, it causes the text between this headline
21664 and the next to be exported as fixed-width text, and unmodified.
21665 If there is an active region, this command adds or removes a colon as the
21666 first character of this line. If the first character of a line is a colon,
21667 this line is also exported in fixed-width font."
21668 (interactive "P")
21669 (let* ((cc 0)
21670 (regionp (org-region-active-p))
21671 (beg (if regionp (region-beginning) (point)))
21672 (end (if regionp (region-end)))
21673 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21674 (case-fold-search nil)
21675 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21676 off)
21677 (if regionp
21678 (save-excursion
21679 (goto-char beg)
21680 (setq cc (current-column))
21681 (beginning-of-line 1)
21682 (setq off (looking-at re))
21683 (while (> nlines 0)
21684 (setq nlines (1- nlines))
21685 (beginning-of-line 1)
21686 (cond
21687 (arg
21688 (org-move-to-column cc t)
21689 (insert ": \n")
21690 (forward-line -1))
21691 ((and off (looking-at re))
21692 (replace-match "" t t nil 1))
21693 ((not off) (org-move-to-column cc t) (insert ": ")))
21694 (forward-line 1)))
21695 (save-excursion
21696 (org-back-to-heading)
21697 (cond
21698 ((looking-at (format org-heading-keyword-regexp-format
21699 org-quote-string))
21700 (goto-char (match-end 1))
21701 (looking-at (concat " +" org-quote-string))
21702 (replace-match "" t t)
21703 (when (eolp) (insert " ")))
21704 ((looking-at org-outline-regexp)
21705 (goto-char (match-end 0))
21706 (insert org-quote-string " ")))))))
21708 (defun org-reftex-citation ()
21709 "Use reftex-citation to insert a citation into the buffer.
21710 This looks for a line like
21712 #+BIBLIOGRAPHY: foo plain option:-d
21714 and derives from it that foo.bib is the bibliography file relevant
21715 for this document. It then installs the necessary environment for RefTeX
21716 to work in this buffer and calls `reftex-citation' to insert a citation
21717 into the buffer.
21719 Export of such citations to both LaTeX and HTML is handled by the contributed
21720 package org-exp-bibtex by Taru Karttunen."
21721 (interactive)
21722 (let ((reftex-docstruct-symbol 'rds)
21723 (reftex-cite-format "\\cite{%l}")
21724 rds bib)
21725 (save-excursion
21726 (save-restriction
21727 (widen)
21728 (let ((case-fold-search t)
21729 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21730 (if (not (save-excursion
21731 (or (re-search-forward re nil t)
21732 (re-search-backward re nil t))))
21733 (error "No bibliography defined in file")
21734 (setq bib (concat (match-string 1) ".bib")
21735 rds (list (list 'bib bib)))))))
21736 (call-interactively 'reftex-citation)))
21738 ;;;; Functions extending outline functionality
21740 (defun org-beginning-of-line (&optional arg)
21741 "Go to the beginning of the current line. If that is invisible, continue
21742 to a visible line beginning. This makes the function of C-a more intuitive.
21743 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21744 first attempt, and only move to after the tags when the cursor is already
21745 beyond the end of the headline."
21746 (interactive "P")
21747 (let ((pos (point))
21748 (special (if (consp org-special-ctrl-a/e)
21749 (car org-special-ctrl-a/e)
21750 org-special-ctrl-a/e))
21751 refpos)
21752 (if (org-bound-and-true-p visual-line-mode)
21753 (beginning-of-visual-line 1)
21754 (beginning-of-line 1))
21755 (if (and arg (fboundp 'move-beginning-of-line))
21756 (call-interactively 'move-beginning-of-line)
21757 (if (bobp)
21759 (backward-char 1)
21760 (if (org-truely-invisible-p)
21761 (while (and (not (bobp)) (org-truely-invisible-p))
21762 (backward-char 1)
21763 (beginning-of-line 1))
21764 (forward-char 1))))
21765 (when special
21766 (cond
21767 ((and (looking-at org-complex-heading-regexp)
21768 (= (char-after (match-end 1)) ?\ ))
21769 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21770 (point-at-eol)))
21771 (goto-char
21772 (if (eq special t)
21773 (cond ((> pos refpos) refpos)
21774 ((= pos (point)) refpos)
21775 (t (point)))
21776 (cond ((> pos (point)) (point))
21777 ((not (eq last-command this-command)) (point))
21778 (t refpos)))))
21779 ((org-at-item-p)
21780 ;; Being at an item and not looking at an the item means point
21781 ;; was previously moved to beginning of a visual line, which
21782 ;; doesn't contain the item. Therefore, do nothing special,
21783 ;; just stay here.
21784 (when (looking-at org-list-full-item-re)
21785 ;; Set special position at first white space character after
21786 ;; bullet, and check-box, if any.
21787 (let ((after-bullet
21788 (let ((box (match-end 3)))
21789 (if (not box) (match-end 1)
21790 (let ((after (char-after box)))
21791 (if (and after (= after ? )) (1+ box) box))))))
21792 ;; Special case: Move point to special position when
21793 ;; currently after it or at beginning of line.
21794 (if (eq special t)
21795 (when (or (> pos after-bullet) (= (point) pos))
21796 (goto-char after-bullet))
21797 ;; Reversed case: Move point to special position when
21798 ;; point was already at beginning of line and command is
21799 ;; repeated.
21800 (when (and (= (point) pos) (eq last-command this-command))
21801 (goto-char after-bullet))))))))
21802 (org-no-warnings
21803 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21805 (defun org-end-of-line (&optional arg)
21806 "Go to the end of the line.
21807 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21808 tags on the first attempt, and only move to after the tags when
21809 the cursor is already beyond the end of the headline."
21810 (interactive "P")
21811 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21812 org-special-ctrl-a/e))
21813 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21814 'end-of-visual-line)
21815 ((fboundp 'move-end-of-line) 'move-end-of-line)
21816 (t 'end-of-line))))
21817 (if (or (not special) arg) (call-interactively move-fun)
21818 (let* ((element (save-excursion (beginning-of-line)
21819 (org-element-at-point)))
21820 (type (org-element-type element)))
21821 (cond
21822 ((memq type '(headline inlinetask))
21823 (let ((pos (point)))
21824 (beginning-of-line 1)
21825 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21826 (if (eq special t)
21827 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21828 (goto-char (match-beginning 1))
21829 (goto-char (match-end 0)))
21830 (if (or (< pos (match-end 0))
21831 (not (eq this-command last-command)))
21832 (goto-char (match-end 0))
21833 (goto-char (match-beginning 1))))
21834 (call-interactively move-fun))))
21835 ((org-element-property :hiddenp element)
21836 ;; If element is hidden, `move-end-of-line' would put point
21837 ;; after it. Use `end-of-line' to stay on current line.
21838 (call-interactively 'end-of-line))
21839 (t (call-interactively move-fun)))))
21840 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21842 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21843 (define-key org-mode-map "\C-e" 'org-end-of-line)
21845 (defun org-backward-sentence (&optional arg)
21846 "Go to beginning of sentence, or beginning of table field.
21847 This will call `backward-sentence' or `org-table-beginning-of-field',
21848 depending on context."
21849 (interactive "P")
21850 (cond
21851 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21852 (t (call-interactively 'backward-sentence))))
21854 (defun org-forward-sentence (&optional arg)
21855 "Go to end of sentence, or end of table field.
21856 This will call `forward-sentence' or `org-table-end-of-field',
21857 depending on context."
21858 (interactive "P")
21859 (cond
21860 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21861 (t (call-interactively 'forward-sentence))))
21863 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21864 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21866 (defun org-kill-line (&optional arg)
21867 "Kill line, to tags or end of line."
21868 (interactive "P")
21869 (cond
21870 ((or (not org-special-ctrl-k)
21871 (bolp)
21872 (not (org-at-heading-p)))
21873 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21874 org-ctrl-k-protect-subtree)
21875 (if (or (eq org-ctrl-k-protect-subtree 'error)
21876 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21877 (error "C-k aborted - would kill hidden subtree")))
21878 (call-interactively
21879 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21880 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21881 (kill-region (point) (match-beginning 1))
21882 (org-set-tags nil t))
21883 (t (kill-region (point) (point-at-eol)))))
21885 (define-key org-mode-map "\C-k" 'org-kill-line)
21887 (defun org-yank (&optional arg)
21888 "Yank. If the kill is a subtree, treat it specially.
21889 This command will look at the current kill and check if is a single
21890 subtree, or a series of subtrees[1]. If it passes the test, and if the
21891 cursor is at the beginning of a line or after the stars of a currently
21892 empty headline, then the yank is handled specially. How exactly depends
21893 on the value of the following variables, both set by default.
21895 org-yank-folded-subtrees
21896 When set, the subtree(s) will be folded after insertion, but only
21897 if doing so would now swallow text after the yanked text.
21899 org-yank-adjusted-subtrees
21900 When set, the subtree will be promoted or demoted in order to
21901 fit into the local outline tree structure, which means that the level
21902 will be adjusted so that it becomes the smaller one of the two
21903 *visible* surrounding headings.
21905 Any prefix to this command will cause `yank' to be called directly with
21906 no special treatment. In particular, a simple \\[universal-argument] prefix \
21907 will just
21908 plainly yank the text as it is.
21910 \[1] The test checks if the first non-white line is a heading
21911 and if there are no other headings with fewer stars."
21912 (interactive "P")
21913 (org-yank-generic 'yank arg))
21915 (defun org-yank-generic (command arg)
21916 "Perform some yank-like command.
21918 This function implements the behavior described in the `org-yank'
21919 documentation. However, it has been generalized to work for any
21920 interactive command with similar behavior."
21922 ;; pretend to be command COMMAND
21923 (setq this-command command)
21925 (if arg
21926 (call-interactively command)
21928 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21929 (and (org-kill-is-subtree-p)
21930 (or (bolp)
21931 (and (looking-at "[ \t]*$")
21932 (string-match
21933 "\\`\\*+\\'"
21934 (buffer-substring (point-at-bol) (point)))))))
21935 swallowp)
21936 (cond
21937 ((and subtreep org-yank-folded-subtrees)
21938 (let ((beg (point))
21939 end)
21940 (if (and subtreep org-yank-adjusted-subtrees)
21941 (org-paste-subtree nil nil 'for-yank)
21942 (call-interactively command))
21944 (setq end (point))
21945 (goto-char beg)
21946 (when (and (bolp) subtreep
21947 (not (setq swallowp
21948 (org-yank-folding-would-swallow-text beg end))))
21949 (org-with-limited-levels
21950 (or (looking-at org-outline-regexp)
21951 (re-search-forward org-outline-regexp-bol end t))
21952 (while (and (< (point) end) (looking-at org-outline-regexp))
21953 (hide-subtree)
21954 (org-cycle-show-empty-lines 'folded)
21955 (condition-case nil
21956 (outline-forward-same-level 1)
21957 (error (goto-char end))))))
21958 (when swallowp
21959 (message
21960 "Inserted text not folded because that would swallow text"))
21962 (goto-char end)
21963 (skip-chars-forward " \t\n\r")
21964 (beginning-of-line 1)
21965 (push-mark beg 'nomsg)))
21966 ((and subtreep org-yank-adjusted-subtrees)
21967 (let ((beg (point-at-bol)))
21968 (org-paste-subtree nil nil 'for-yank)
21969 (push-mark beg 'nomsg)))
21971 (call-interactively command))))))
21973 (defun org-yank-folding-would-swallow-text (beg end)
21974 "Would hide-subtree at BEG swallow any text after END?"
21975 (let (level)
21976 (org-with-limited-levels
21977 (save-excursion
21978 (goto-char beg)
21979 (when (or (looking-at org-outline-regexp)
21980 (re-search-forward org-outline-regexp-bol end t))
21981 (setq level (org-outline-level)))
21982 (goto-char end)
21983 (skip-chars-forward " \t\r\n\v\f")
21984 (if (or (eobp)
21985 (and (bolp) (looking-at org-outline-regexp)
21986 (<= (org-outline-level) level)))
21987 nil ; Nothing would be swallowed
21988 t))))) ; something would swallow
21990 (define-key org-mode-map "\C-y" 'org-yank)
21992 (defun org-truely-invisible-p ()
21993 "Check if point is at a character currently not visible.
21994 This version does not only check the character property, but also
21995 `visible-mode'."
21996 ;; Early versions of noutline don't have `outline-invisible-p'.
21997 (if (org-bound-and-true-p visible-mode)
21999 (outline-invisible-p)))
22001 (defun org-invisible-p2 ()
22002 "Check if point is at a character currently not visible."
22003 (save-excursion
22004 (if (and (eolp) (not (bobp))) (backward-char 1))
22005 ;; Early versions of noutline don't have `outline-invisible-p'.
22006 (outline-invisible-p)))
22008 (defun org-back-to-heading (&optional invisible-ok)
22009 "Call `outline-back-to-heading', but provide a better error message."
22010 (condition-case nil
22011 (outline-back-to-heading invisible-ok)
22012 (error (error "Before first headline at position %d in buffer %s"
22013 (point) (current-buffer)))))
22015 (defun org-before-first-heading-p ()
22016 "Before first heading?"
22017 (save-excursion
22018 (end-of-line)
22019 (null (re-search-backward org-outline-regexp-bol nil t))))
22021 (defun org-at-heading-p (&optional ignored)
22022 (outline-on-heading-p t))
22023 ;; Compatibility alias with Org versions < 7.8.03
22024 (defalias 'org-on-heading-p 'org-at-heading-p)
22026 (defun org-at-comment-p nil
22027 "Is cursor in a line starting with a # character?"
22028 (save-excursion
22029 (beginning-of-line)
22030 (looking-at "^#")))
22032 (defun org-at-drawer-p nil
22033 "Is cursor at a drawer keyword?"
22034 (save-excursion
22035 (move-beginning-of-line 1)
22036 (looking-at org-drawer-regexp)))
22038 (defun org-at-block-p nil
22039 "Is cursor at a block keyword?"
22040 (save-excursion
22041 (move-beginning-of-line 1)
22042 (looking-at org-block-regexp)))
22044 (defun org-point-at-end-of-empty-headline ()
22045 "If point is at the end of an empty headline, return t, else nil.
22046 If the heading only contains a TODO keyword, it is still still considered
22047 empty."
22048 (and (looking-at "[ \t]*$")
22049 (when org-todo-line-regexp
22050 (save-excursion
22051 (beginning-of-line 1)
22052 (let ((case-fold-search nil))
22053 (looking-at org-todo-line-regexp)
22054 (string= (match-string 3) ""))))))
22056 (defun org-at-heading-or-item-p ()
22057 (or (org-at-heading-p) (org-at-item-p)))
22059 (defun org-at-target-p ()
22060 (or (org-in-regexp org-radio-target-regexp)
22061 (org-in-regexp org-target-regexp)))
22062 ;; Compatibility alias with Org versions < 7.8.03
22063 (defalias 'org-on-target-p 'org-at-target-p)
22065 (defun org-up-heading-all (arg)
22066 "Move to the heading line of which the present line is a subheading.
22067 This function considers both visible and invisible heading lines.
22068 With argument, move up ARG levels."
22069 (if (fboundp 'outline-up-heading-all)
22070 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22071 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22073 (defun org-up-heading-safe ()
22074 "Move to the heading line of which the present line is a subheading.
22075 This version will not throw an error. It will return the level of the
22076 headline found, or nil if no higher level is found.
22078 Also, this function will be a lot faster than `outline-up-heading',
22079 because it relies on stars being the outline starters. This can really
22080 make a significant difference in outlines with very many siblings."
22081 (let (start-level re)
22082 (org-back-to-heading t)
22083 (setq start-level (funcall outline-level))
22084 (if (equal start-level 1)
22086 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22087 (if (re-search-backward re nil t)
22088 (funcall outline-level)))))
22090 (defun org-first-sibling-p ()
22091 "Is this heading the first child of its parents?"
22092 (interactive)
22093 (let ((re org-outline-regexp-bol)
22094 level l)
22095 (unless (org-at-heading-p t)
22096 (error "Not at a heading"))
22097 (setq level (funcall outline-level))
22098 (save-excursion
22099 (if (not (re-search-backward re nil t))
22101 (setq l (funcall outline-level))
22102 (< l level)))))
22104 (defun org-goto-sibling (&optional previous)
22105 "Goto the next sibling, even if it is invisible.
22106 When PREVIOUS is set, go to the previous sibling instead. Returns t
22107 when a sibling was found. When none is found, return nil and don't
22108 move point."
22109 (let ((fun (if previous 're-search-backward 're-search-forward))
22110 (pos (point))
22111 (re org-outline-regexp-bol)
22112 level l)
22113 (when (condition-case nil (org-back-to-heading t) (error nil))
22114 (setq level (funcall outline-level))
22115 (catch 'exit
22116 (or previous (forward-char 1))
22117 (while (funcall fun re nil t)
22118 (setq l (funcall outline-level))
22119 (when (< l level) (goto-char pos) (throw 'exit nil))
22120 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22121 (goto-char pos)
22122 nil))))
22124 (defun org-show-siblings ()
22125 "Show all siblings of the current headline."
22126 (save-excursion
22127 (while (org-goto-sibling) (org-flag-heading nil)))
22128 (save-excursion
22129 (while (org-goto-sibling 'previous)
22130 (org-flag-heading nil))))
22132 (defun org-goto-first-child ()
22133 "Goto the first child, even if it is invisible.
22134 Return t when a child was found. Otherwise don't move point and
22135 return nil."
22136 (let (level (pos (point)) (re org-outline-regexp-bol))
22137 (when (condition-case nil (org-back-to-heading t) (error nil))
22138 (setq level (outline-level))
22139 (forward-char 1)
22140 (if (and (re-search-forward re nil t) (> (outline-level) level))
22141 (progn (goto-char (match-beginning 0)) t)
22142 (goto-char pos) nil))))
22144 (defun org-show-hidden-entry ()
22145 "Show an entry where even the heading is hidden."
22146 (save-excursion
22147 (org-show-entry)))
22149 (defun org-flag-heading (flag &optional entry)
22150 "Flag the current heading. FLAG non-nil means make invisible.
22151 When ENTRY is non-nil, show the entire entry."
22152 (save-excursion
22153 (org-back-to-heading t)
22154 ;; Check if we should show the entire entry
22155 (if entry
22156 (progn
22157 (org-show-entry)
22158 (save-excursion
22159 (and (outline-next-heading)
22160 (org-flag-heading nil))))
22161 (outline-flag-region (max (point-min) (1- (point)))
22162 (save-excursion (outline-end-of-heading) (point))
22163 flag))))
22165 (defun org-get-next-sibling ()
22166 "Move to next heading of the same level, and return point.
22167 If there is no such heading, return nil.
22168 This is like outline-next-sibling, but invisible headings are ok."
22169 (let ((level (funcall outline-level)))
22170 (outline-next-heading)
22171 (while (and (not (eobp)) (> (funcall outline-level) level))
22172 (outline-next-heading))
22173 (if (or (eobp) (< (funcall outline-level) level))
22175 (point))))
22177 (defun org-get-last-sibling ()
22178 "Move to previous heading of the same level, and return point.
22179 If there is no such heading, return nil."
22180 (let ((opoint (point))
22181 (level (funcall outline-level)))
22182 (outline-previous-heading)
22183 (when (and (/= (point) opoint) (outline-on-heading-p t))
22184 (while (and (> (funcall outline-level) level)
22185 (not (bobp)))
22186 (outline-previous-heading))
22187 (if (< (funcall outline-level) level)
22189 (point)))))
22191 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22192 "Goto to the end of a subtree."
22193 ;; This contains an exact copy of the original function, but it uses
22194 ;; `org-back-to-heading', to make it work also in invisible
22195 ;; trees. And is uses an invisible-ok argument.
22196 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22197 ;; Furthermore, when used inside Org, finding the end of a large subtree
22198 ;; with many children and grandchildren etc, this can be much faster
22199 ;; than the outline version.
22200 (org-back-to-heading invisible-ok)
22201 (let ((first t)
22202 (level (funcall outline-level)))
22203 (if (and (derived-mode-p 'org-mode) (< level 1000))
22204 ;; A true heading (not a plain list item), in Org-mode
22205 ;; This means we can easily find the end by looking
22206 ;; only for the right number of stars. Using a regexp to do
22207 ;; this is so much faster than using a Lisp loop.
22208 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22209 (forward-char 1)
22210 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22211 ;; something else, do it the slow way
22212 (while (and (not (eobp))
22213 (or first (> (funcall outline-level) level)))
22214 (setq first nil)
22215 (outline-next-heading)))
22216 (unless to-heading
22217 (if (memq (preceding-char) '(?\n ?\^M))
22218 (progn
22219 ;; Go to end of line before heading
22220 (forward-char -1)
22221 (if (memq (preceding-char) '(?\n ?\^M))
22222 ;; leave blank line before heading
22223 (forward-char -1))))))
22224 (point))
22226 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22227 "Use Org version in org-mode, for dramatic speed-up."
22228 (if (derived-mode-p 'org-mode)
22229 (progn
22230 (org-end-of-subtree nil t)
22231 (unless (eobp) (backward-char 1)))
22232 ad-do-it))
22234 (defun org-end-of-meta-data-and-drawers ()
22235 "Jump to the first text after meta data and drawers in the current entry.
22236 This will move over empty lines, lines with planning time stamps,
22237 clocking lines, and drawers."
22238 (org-back-to-heading t)
22239 (let ((end (save-excursion (outline-next-heading) (point)))
22240 (re (concat "\\(" org-drawer-regexp "\\)"
22241 "\\|" "[ \t]*" org-keyword-time-regexp)))
22242 (forward-line 1)
22243 (while (re-search-forward re end t)
22244 (if (not (match-end 1))
22245 ;; empty or planning line
22246 (forward-line 1)
22247 ;; a drawer, find the end
22248 (re-search-forward "^[ \t]*:END:" end 'move)
22249 (forward-line 1)))
22250 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22251 (point)))
22253 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22254 "Move forward to the arg'th subheading at same level as this one.
22255 Stop at the first and last subheadings of a superior heading.
22256 Normally this only looks at visible headings, but when INVISIBLE-OK is
22257 non-nil it will also look at invisible ones."
22258 (interactive "p")
22259 (org-back-to-heading invisible-ok)
22260 (org-at-heading-p)
22261 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22262 (re (format "^\\*\\{1,%d\\} " level))
22264 (forward-char 1)
22265 (while (> arg 0)
22266 (while (and (re-search-forward re nil 'move)
22267 (setq l (- (match-end 0) (match-beginning 0) 1))
22268 (= l level)
22269 (not invisible-ok)
22270 (progn (backward-char 1) (outline-invisible-p)))
22271 (if (< l level) (setq arg 1)))
22272 (setq arg (1- arg)))
22273 (beginning-of-line 1)))
22275 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22276 "Move backward to the arg'th subheading at same level as this one.
22277 Stop at the first and last subheadings of a superior heading."
22278 (interactive "p")
22279 (org-back-to-heading)
22280 (org-at-heading-p)
22281 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22282 (re (format "^\\*\\{1,%d\\} " level))
22284 (while (> arg 0)
22285 (while (and (re-search-backward re nil 'move)
22286 (setq l (- (match-end 0) (match-beginning 0) 1))
22287 (= l level)
22288 (not invisible-ok)
22289 (outline-invisible-p))
22290 (if (< l level) (setq arg 1)))
22291 (setq arg (1- arg)))))
22293 (defun org-forward-element ()
22294 "Move forward by one element.
22295 Move to the next element at the same level, when possible."
22296 (interactive)
22297 (cond ((eobp) (error "Cannot move further down"))
22298 ((org-with-limited-levels (org-at-heading-p))
22299 (let ((origin (point)))
22300 (org-forward-heading-same-level 1)
22301 (unless (org-with-limited-levels (org-at-heading-p))
22302 (goto-char origin)
22303 (error "Cannot move further down"))))
22305 (let* ((elem (org-element-at-point))
22306 (end (org-element-property :end elem))
22307 (parent (org-element-property :parent elem)))
22308 (if (and parent (= (org-element-property :contents-end parent) end))
22309 (goto-char (org-element-property :end parent))
22310 (goto-char end))))))
22312 (defun org-backward-element ()
22313 "Move backward by one element.
22314 Move to the previous element at the same level, when possible."
22315 (interactive)
22316 (cond ((bobp) (error "Cannot move further up"))
22317 ((org-with-limited-levels (org-at-heading-p))
22318 ;; At an headline, move to the previous one, if any, or stay
22319 ;; here.
22320 (let ((origin (point)))
22321 (org-backward-heading-same-level 1)
22322 (unless (org-with-limited-levels (org-at-heading-p))
22323 (goto-char origin)
22324 (error "Cannot move further up"))))
22326 (let* ((trail (org-element-at-point 'keep-trail))
22327 (elem (car trail))
22328 (prev-elem (nth 1 trail))
22329 (beg (org-element-property :begin elem)))
22330 (cond
22331 ;; Move to beginning of current element if point isn't
22332 ;; there already.
22333 ((/= (point) beg) (goto-char beg))
22334 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22335 ((org-before-first-heading-p) (goto-char (point-min)))
22336 (t (org-back-to-heading)))))))
22338 (defun org-up-element ()
22339 "Move to upper element."
22340 (interactive)
22341 (if (org-with-limited-levels (org-at-heading-p))
22342 (unless (org-up-heading-safe) (error "No surrounding element"))
22343 (let* ((elem (org-element-at-point))
22344 (parent (org-element-property :parent elem)))
22345 (if parent (goto-char (org-element-property :begin parent))
22346 (if (org-with-limited-levels (org-before-first-heading-p))
22347 (error "No surrounding element")
22348 (org-with-limited-levels (org-back-to-heading)))))))
22350 (defvar org-element-greater-elements)
22351 (defun org-down-element ()
22352 "Move to inner element."
22353 (interactive)
22354 (let ((element (org-element-at-point)))
22355 (cond
22356 ((memq (org-element-type element) '(plain-list table))
22357 (goto-char (org-element-property :contents-begin element))
22358 (forward-char))
22359 ((memq (org-element-type element) org-element-greater-elements)
22360 ;; If contents are hidden, first disclose them.
22361 (when (org-element-property :hiddenp element) (org-cycle))
22362 (goto-char (or (org-element-property :contents-begin element)
22363 (error "No content for this element"))))
22364 (t (error "No inner element")))))
22366 (defun org-drag-element-backward ()
22367 "Move backward element at point."
22368 (interactive)
22369 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22370 (let* ((trail (org-element-at-point 'keep-trail))
22371 (elem (car trail))
22372 (prev-elem (nth 1 trail)))
22373 ;; Error out if no previous element or previous element is
22374 ;; a parent of the current one.
22375 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22376 (error "Cannot drag element backward")
22377 (let ((pos (point)))
22378 (org-element-swap-A-B prev-elem elem)
22379 (goto-char (+ (org-element-property :begin prev-elem)
22380 (- pos (org-element-property :begin elem)))))))))
22382 (defun org-drag-element-forward ()
22383 "Move forward element at point."
22384 (interactive)
22385 (let* ((pos (point))
22386 (elem (org-element-at-point)))
22387 (when (= (point-max) (org-element-property :end elem))
22388 (error "Cannot drag element forward"))
22389 (goto-char (org-element-property :end elem))
22390 (let ((next-elem (org-element-at-point)))
22391 (when (or (org-element-nested-p elem next-elem)
22392 (and (eq (org-element-type next-elem) 'headline)
22393 (not (eq (org-element-type elem) 'headline))))
22394 (goto-char pos)
22395 (error "Cannot drag element forward"))
22396 ;; Compute new position of point: it's shifted by NEXT-ELEM
22397 ;; body's length (without final blanks) and by the length of
22398 ;; blanks between ELEM and NEXT-ELEM.
22399 (let ((size-next (- (save-excursion
22400 (goto-char (org-element-property :end next-elem))
22401 (skip-chars-backward " \r\t\n")
22402 (forward-line)
22403 ;; Small correction if buffer doesn't end
22404 ;; with a newline character.
22405 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22406 (org-element-property :begin next-elem)))
22407 (size-blank (- (org-element-property :end elem)
22408 (save-excursion
22409 (goto-char (org-element-property :end elem))
22410 (skip-chars-backward " \r\t\n")
22411 (forward-line)
22412 (point)))))
22413 (org-element-swap-A-B elem next-elem)
22414 (goto-char (+ pos size-next size-blank))))))
22416 (defun org-mark-element ()
22417 "Put point at beginning of this element, mark at end.
22419 Interactively, if this command is repeated or (in Transient Mark
22420 mode) if the mark is active, it marks the next element after the
22421 ones already marked."
22422 (interactive)
22423 (let (deactivate-mark)
22424 (if (and (org-called-interactively-p 'any)
22425 (or (and (eq last-command this-command) (mark t))
22426 (and transient-mark-mode mark-active)))
22427 (set-mark
22428 (save-excursion
22429 (goto-char (mark))
22430 (goto-char (org-element-property :end (org-element-at-point)))))
22431 (let ((element (org-element-at-point)))
22432 (end-of-line)
22433 (push-mark (org-element-property :end element) t t)
22434 (goto-char (org-element-property :begin element))))))
22436 (defun org-narrow-to-element ()
22437 "Narrow buffer to current element."
22438 (interactive)
22439 (let ((elem (org-element-at-point)))
22440 (cond
22441 ((eq (car elem) 'headline)
22442 (narrow-to-region
22443 (org-element-property :begin elem)
22444 (org-element-property :end elem)))
22445 ((memq (car elem) org-element-greater-elements)
22446 (narrow-to-region
22447 (org-element-property :contents-begin elem)
22448 (org-element-property :contents-end elem)))
22450 (narrow-to-region
22451 (org-element-property :begin elem)
22452 (org-element-property :end elem))))))
22454 (defun org-transpose-element ()
22455 "Transpose current and previous elements, keeping blank lines between.
22456 Point is moved after both elements."
22457 (interactive)
22458 (org-skip-whitespace)
22459 (let ((end (org-element-property :end (org-element-at-point))))
22460 (org-drag-element-backward)
22461 (goto-char end)))
22463 (defun org-unindent-buffer ()
22464 "Un-indent the visible part of the buffer.
22465 Relative indentation (between items, inside blocks, etc.) isn't
22466 modified."
22467 (interactive)
22468 (unless (eq major-mode 'org-mode)
22469 (error "Cannot un-indent a buffer not in Org mode"))
22470 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22471 unindent-tree ; For byte-compiler.
22472 (unindent-tree
22473 (function
22474 (lambda (contents)
22475 (mapc
22476 (lambda (element)
22477 (if (memq (org-element-type element) '(headline section))
22478 (funcall unindent-tree (org-element-contents element))
22479 (save-excursion
22480 (save-restriction
22481 (narrow-to-region
22482 (org-element-property :begin element)
22483 (org-element-property :end element))
22484 (org-do-remove-indentation)))))
22485 (reverse contents))))))
22486 (funcall unindent-tree (org-element-contents parse-tree))))
22488 (defun org-show-subtree ()
22489 "Show everything after this heading at deeper levels."
22490 (interactive)
22491 (outline-flag-region
22492 (point)
22493 (save-excursion
22494 (org-end-of-subtree t t))
22495 nil))
22497 (defun org-show-entry ()
22498 "Show the body directly following this heading.
22499 Show the heading too, if it is currently invisible."
22500 (interactive)
22501 (save-excursion
22502 (condition-case nil
22503 (progn
22504 (org-back-to-heading t)
22505 (outline-flag-region
22506 (max (point-min) (1- (point)))
22507 (save-excursion
22508 (if (re-search-forward
22509 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22510 (match-beginning 1)
22511 (point-max)))
22512 nil)
22513 (org-cycle-hide-drawers 'children))
22514 (error nil))))
22516 (defun org-make-options-regexp (kwds &optional extra)
22517 "Make a regular expression for keyword lines."
22518 (concat
22519 "^#\\+\\("
22520 (mapconcat 'regexp-quote kwds "\\|")
22521 (if extra (concat "\\|" extra))
22522 "\\):[ \t]*\\(.*\\)"))
22524 ;; Make isearch reveal the necessary context
22525 (defun org-isearch-end ()
22526 "Reveal context after isearch exits."
22527 (when isearch-success ; only if search was successful
22528 (if (featurep 'xemacs)
22529 ;; Under XEmacs, the hook is run in the correct place,
22530 ;; we directly show the context.
22531 (org-show-context 'isearch)
22532 ;; In Emacs the hook runs *before* restoring the overlays.
22533 ;; So we have to use a one-time post-command-hook to do this.
22534 ;; (Emacs 22 has a special variable, see function `org-mode')
22535 (unless (and (boundp 'isearch-mode-end-hook-quit)
22536 isearch-mode-end-hook-quit)
22537 ;; Only when the isearch was not quitted.
22538 (org-add-hook 'post-command-hook 'org-isearch-post-command
22539 'append 'local)))))
22541 (defun org-isearch-post-command ()
22542 "Remove self from hook, and show context."
22543 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22544 (org-show-context 'isearch))
22547 ;;;; Integration with and fixes for other packages
22549 ;;; Imenu support
22551 (defvar org-imenu-markers nil
22552 "All markers currently used by Imenu.")
22553 (make-variable-buffer-local 'org-imenu-markers)
22555 (defun org-imenu-new-marker (&optional pos)
22556 "Return a new marker for use by Imenu, and remember the marker."
22557 (let ((m (make-marker)))
22558 (move-marker m (or pos (point)))
22559 (push m org-imenu-markers)
22562 (defun org-imenu-get-tree ()
22563 "Produce the index for Imenu."
22564 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22565 (setq org-imenu-markers nil)
22566 (let* ((n org-imenu-depth)
22567 (re (concat "^" (org-get-limited-outline-regexp)))
22568 (subs (make-vector (1+ n) nil))
22569 (last-level 0)
22570 m level head)
22571 (save-excursion
22572 (save-restriction
22573 (widen)
22574 (goto-char (point-max))
22575 (while (re-search-backward re nil t)
22576 (setq level (org-reduced-level (funcall outline-level)))
22577 (when (and (<= level n)
22578 (looking-at org-complex-heading-regexp))
22579 (setq head (org-link-display-format
22580 (org-match-string-no-properties 4))
22581 m (org-imenu-new-marker))
22582 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22583 (if (>= level last-level)
22584 (push (cons head m) (aref subs level))
22585 (push (cons head (aref subs (1+ level))) (aref subs level))
22586 (loop for i from (1+ level) to n do (aset subs i nil)))
22587 (setq last-level level)))))
22588 (aref subs 1)))
22590 (eval-after-load "imenu"
22591 '(progn
22592 (add-hook 'imenu-after-jump-hook
22593 (lambda ()
22594 (if (derived-mode-p 'org-mode)
22595 (org-show-context 'org-goto))))))
22597 (defun org-link-display-format (link)
22598 "Replace a link with either the description, or the link target
22599 if no description is present"
22600 (save-match-data
22601 (if (string-match org-bracket-link-analytic-regexp link)
22602 (replace-match (if (match-end 5)
22603 (match-string 5 link)
22604 (concat (match-string 1 link)
22605 (match-string 3 link)))
22606 nil t link)
22607 link)))
22609 (defun org-toggle-link-display ()
22610 "Toggle the literal or descriptive display of links."
22611 (interactive)
22612 (if org-descriptive-links
22613 (progn (org-remove-from-invisibility-spec '(org-link))
22614 (org-restart-font-lock)
22615 (setq org-descriptive-links nil))
22616 (progn (add-to-invisibility-spec '(org-link))
22617 (org-restart-font-lock)
22618 (setq org-descriptive-links t))))
22620 ;; Speedbar support
22622 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22623 "Overlay marking the agenda restriction line in speedbar.")
22624 (overlay-put org-speedbar-restriction-lock-overlay
22625 'face 'org-agenda-restriction-lock)
22626 (overlay-put org-speedbar-restriction-lock-overlay
22627 'help-echo "Agendas are currently limited to this item.")
22628 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22630 (defun org-speedbar-set-agenda-restriction ()
22631 "Restrict future agenda commands to the location at point in speedbar.
22632 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22633 (interactive)
22634 (require 'org-agenda)
22635 (let (p m tp np dir txt)
22636 (cond
22637 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22638 'org-imenu t))
22639 (setq m (get-text-property p 'org-imenu-marker))
22640 (with-current-buffer (marker-buffer m)
22641 (goto-char m)
22642 (org-agenda-set-restriction-lock 'subtree)))
22643 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22644 'speedbar-function 'speedbar-find-file))
22645 (setq tp (previous-single-property-change
22646 (1+ p) 'speedbar-function)
22647 np (next-single-property-change
22648 tp 'speedbar-function)
22649 dir (speedbar-line-directory)
22650 txt (buffer-substring-no-properties (or tp (point-min))
22651 (or np (point-max))))
22652 (with-current-buffer (find-file-noselect
22653 (let ((default-directory dir))
22654 (expand-file-name txt)))
22655 (unless (derived-mode-p 'org-mode)
22656 (error "Cannot restrict to non-Org-mode file"))
22657 (org-agenda-set-restriction-lock 'file)))
22658 (t (error "Don't know how to restrict Org-mode's agenda")))
22659 (move-overlay org-speedbar-restriction-lock-overlay
22660 (point-at-bol) (point-at-eol))
22661 (setq current-prefix-arg nil)
22662 (org-agenda-maybe-redo)))
22664 (eval-after-load "speedbar"
22665 '(progn
22666 (speedbar-add-supported-extension ".org")
22667 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22668 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22669 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22670 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22671 (add-hook 'speedbar-visiting-tag-hook
22672 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22674 ;;; Fixes and Hacks for problems with other packages
22676 ;; Make flyspell not check words in links, to not mess up our keymap
22677 (defun org-mode-flyspell-verify ()
22678 "Don't let flyspell put overlays at active buttons, or on
22679 {todo,all-time,additional-option-like}-keywords."
22680 (let ((pos (max (1- (point)) (point-min)))
22681 (word (thing-at-point 'word)))
22682 (and (not (get-text-property pos 'keymap))
22683 (not (get-text-property pos 'org-no-flyspell))
22684 (not (member word org-todo-keywords-1))
22685 (not (member word org-all-time-keywords))
22686 (not (member word org-options-keywords))
22687 (not (member word (mapcar 'car org-startup-options)))
22688 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22690 (defun org-remove-flyspell-overlays-in (beg end)
22691 "Remove flyspell overlays in region."
22692 (and (org-bound-and-true-p flyspell-mode)
22693 (fboundp 'flyspell-delete-region-overlays)
22694 (flyspell-delete-region-overlays beg end))
22695 (add-text-properties beg end '(org-no-flyspell t)))
22697 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22698 (eval-after-load "bookmark"
22699 '(if (boundp 'bookmark-after-jump-hook)
22700 ;; We can use the hook
22701 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22702 ;; Hook not available, use advice
22703 (defadvice bookmark-jump (after org-make-visible activate)
22704 "Make the position visible."
22705 (org-bookmark-jump-unhide))))
22707 ;; Make sure saveplace shows the location if it was hidden
22708 (eval-after-load "saveplace"
22709 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22710 "Make the position visible."
22711 (org-bookmark-jump-unhide)))
22713 ;; Make sure ecb shows the location if it was hidden
22714 (eval-after-load "ecb"
22715 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22716 "Make hierarchy visible when jumping into location from ECB tree buffer."
22717 (if (derived-mode-p 'org-mode)
22718 (org-show-context))))
22720 (defun org-bookmark-jump-unhide ()
22721 "Unhide the current position, to show the bookmark location."
22722 (and (derived-mode-p 'org-mode)
22723 (or (outline-invisible-p)
22724 (save-excursion (goto-char (max (point-min) (1- (point))))
22725 (outline-invisible-p)))
22726 (org-show-context 'bookmark-jump)))
22728 ;; Make session.el ignore our circular variable
22729 (eval-after-load "session"
22730 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22732 ;;;; Experimental code
22734 (defun org-closed-in-range ()
22735 "Sparse tree of items closed in a certain time range.
22736 Still experimental, may disappear in the future."
22737 (interactive)
22738 ;; Get the time interval from the user.
22739 (let* ((time1 (org-float-time
22740 (org-read-date nil 'to-time nil "Starting date: ")))
22741 (time2 (org-float-time
22742 (org-read-date nil 'to-time nil "End date:")))
22743 ;; callback function
22744 (callback (lambda ()
22745 (let ((time
22746 (org-float-time
22747 (apply 'encode-time
22748 (org-parse-time-string
22749 (match-string 1))))))
22750 ;; check if time in interval
22751 (and (>= time time1) (<= time time2))))))
22752 ;; make tree, check each match with the callback
22753 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22755 ;;;; Finish up
22757 (provide 'org)
22759 (run-hooks 'org-load-hook)
22761 ;;; org.el ends here