Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobd8c01afc4853180035d3a16cbb6bb47b4f783323
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (let ((load-suffixes (list ".el")))
82 (load "org-loaddefs" 'noerror nil nil 'mustsuffix))
84 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
85 ;; some places -- e.g. see the macro org-with-limited-levels.
87 ;; In Org buffers, the value of `outline-regexp' is that of
88 ;; `org-outline-regexp'. The only function still directly relying on
89 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
90 ;; job when `orgstruct-mode' is active.
91 (defvar org-outline-regexp "\\*+ "
92 "Regexp to match Org headlines.")
94 (defvar org-outline-regexp-bol "^\\*+ "
95 "Regexp to match Org headlines.
96 This is similar to `org-outline-regexp' but additionally makes
97 sure that we are at the beginning of the line.")
99 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
100 "Matches an headline, putting stars and text into groups.
101 Stars are put in group 1 and the trimmed body in group 2.")
103 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
104 (when (fboundp 'defvaralias)
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-at-clock-log-p "org-clock" ())
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "org-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (autoload 'org-element-at-point "org-element")
139 (autoload 'org-element-type "org-element")
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-type "org-element" (element))
143 (declare-function org-element-context "org-element" ())
144 (declare-function org-element-contents "org-element" (element))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
150 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
152 ;; load languages based on value of `org-babel-load-languages'
153 (defvar org-babel-load-languages)
155 ;;;###autoload
156 (defun org-babel-do-load-languages (sym value)
157 "Load the languages defined in `org-babel-load-languages'."
158 (set-default sym value)
159 (mapc (lambda (pair)
160 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
161 (if active
162 (progn
163 (require (intern (concat "ob-" lang))))
164 (progn
165 (funcall 'fmakunbound
166 (intern (concat "org-babel-execute:" lang)))
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-expand-body:" lang)))))))
169 org-babel-load-languages))
171 (defcustom org-babel-load-languages '((emacs-lisp . t))
172 "Languages which can be evaluated in Org-mode buffers.
173 This list can be used to load support for any of the languages
174 below, note that each language will depend on a different set of
175 system executables and/or Emacs modes. When a language is
176 \"loaded\", then code blocks in that language can be evaluated
177 with `org-babel-execute-src-block' bound by default to C-c
178 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
179 be set to remove code block evaluation from the C-c C-c
180 keybinding. By default only Emacs Lisp (which has no
181 requirements) is loaded."
182 :group 'org-babel
183 :set 'org-babel-do-load-languages
184 :version "24.1"
185 :type '(alist :tag "Babel Languages"
186 :key-type
187 (choice
188 (const :tag "Awk" awk)
189 (const :tag "C" C)
190 (const :tag "R" R)
191 (const :tag "Asymptote" asymptote)
192 (const :tag "Calc" calc)
193 (const :tag "Clojure" clojure)
194 (const :tag "CSS" css)
195 (const :tag "Ditaa" ditaa)
196 (const :tag "Dot" dot)
197 (const :tag "Emacs Lisp" emacs-lisp)
198 (const :tag "Fortran" fortran)
199 (const :tag "Gnuplot" gnuplot)
200 (const :tag "Haskell" haskell)
201 (const :tag "IO" io)
202 (const :tag "Java" java)
203 (const :tag "Javascript" js)
204 (const :tag "LaTeX" latex)
205 (const :tag "Ledger" ledger)
206 (const :tag "Lilypond" lilypond)
207 (const :tag "Lisp" lisp)
208 (const :tag "Makefile" makefile)
209 (const :tag "Maxima" maxima)
210 (const :tag "Matlab" matlab)
211 (const :tag "Mscgen" mscgen)
212 (const :tag "Ocaml" ocaml)
213 (const :tag "Octave" octave)
214 (const :tag "Org" org)
215 (const :tag "Perl" perl)
216 (const :tag "Pico Lisp" picolisp)
217 (const :tag "PlantUML" plantuml)
218 (const :tag "Python" python)
219 (const :tag "Ruby" ruby)
220 (const :tag "Sass" sass)
221 (const :tag "Scala" scala)
222 (const :tag "Scheme" scheme)
223 (const :tag "Screen" screen)
224 (const :tag "Shell Script" sh)
225 (const :tag "Shen" shen)
226 (const :tag "Sql" sql)
227 (const :tag "Sqlite" sqlite))
228 :value-type (boolean :tag "Activate" :value t)))
230 ;;;; Customization variables
231 (defcustom org-clone-delete-id nil
232 "Remove ID property of clones of a subtree.
233 When non-nil, clones of a subtree don't inherit the ID property.
234 Otherwise they inherit the ID property with a new unique
235 identifier."
236 :type 'boolean
237 :version "24.1"
238 :group 'org-id)
240 ;;; Version
241 (require 'org-compat)
242 (org-check-version)
244 ;;;###autoload
245 (defun org-version (&optional here full message)
246 "Show the org-mode version in the echo area.
247 With prefix argument HERE, insert it at point.
248 When FULL is non-nil, use a verbose version string.
249 When MESSAGE is non-nil, display a message with the version."
250 (interactive "P")
251 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
252 (save-load-suffixes load-suffixes)
253 (load-suffixes (list ".el"))
254 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
255 (org-trash (or
256 (and (fboundp 'org-release) (fboundp 'org-git-version))
257 (load (concat org-dir "org-version")
258 'noerror 'nomessage nil 'mustsuffix)))
259 (load-suffixes save-load-suffixes)
260 (org-version (org-release))
261 (git-version (org-git-version))
262 (version (format "Org-mode version %s (%s @ %s)"
263 org-version
264 git-version
265 (if org-install-dir
266 (if (string= org-dir org-install-dir)
267 org-install-dir
268 (concat "mixed installation! " org-install-dir " and " org-dir))
269 "org-loaddefs.el can not be found!")))
270 (_version (if full version org-version)))
271 (if (org-called-interactively-p 'interactive)
272 (if here
273 (insert version)
274 (message version))
275 (if message (message _version))
276 _version)))
278 (defconst org-version (org-version))
280 ;;; Compatibility constants
282 ;;; The custom variables
284 (defgroup org nil
285 "Outline-based notes management and organizer."
286 :tag "Org"
287 :group 'outlines
288 :group 'calendar)
290 (defcustom org-mode-hook nil
291 "Mode hook for Org-mode, run after the mode was turned on."
292 :group 'org
293 :type 'hook)
295 (defcustom org-load-hook nil
296 "Hook that is run after org.el has been loaded."
297 :group 'org
298 :type 'hook)
300 (defcustom org-log-buffer-setup-hook nil
301 "Hook that is run after an Org log buffer is created."
302 :group 'org
303 :version "24.1"
304 :type 'hook)
306 (defvar org-modules) ; defined below
307 (defvar org-modules-loaded nil
308 "Have the modules been loaded already?")
310 (defun org-load-modules-maybe (&optional force)
311 "Load all extensions listed in `org-modules'."
312 (when (or force (not org-modules-loaded))
313 (mapc (lambda (ext)
314 (condition-case nil (require ext)
315 (error (message "Problems while trying to load feature `%s'" ext))))
316 org-modules)
317 (setq org-modules-loaded t)))
319 (defun org-set-modules (var value)
320 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
321 (set var value)
322 (when (featurep 'org)
323 (org-load-modules-maybe 'force)))
325 (when (org-bound-and-true-p org-modules)
326 (let ((a (member 'org-infojs org-modules)))
327 (and a (setcar a 'org-jsinfo))))
329 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
330 "Modules that should always be loaded together with org.el.
331 If a description starts with <C>, the file is not part of Emacs
332 and loading it will require that you have downloaded and properly installed
333 the org-mode distribution.
335 You can also use this system to load external packages (i.e. neither Org
336 core modules, nor modules from the CONTRIB directory). Just add symbols
337 to the end of the list. If the package is called org-xyz.el, then you need
338 to add the symbol `xyz', and the package must have a call to
340 (provide 'org-xyz)"
341 :group 'org
342 :set 'org-set-modules
343 :type
344 '(set :greedy t
345 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
346 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
347 (const :tag " crypt: Encryption of subtrees" org-crypt)
348 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
349 (const :tag " docview: Links to doc-view buffers" org-docview)
350 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
351 (const :tag " id: Global IDs for identifying entries" org-id)
352 (const :tag " info: Links to Info nodes" org-info)
353 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
354 (const :tag " habit: Track your consistency with habits" org-habit)
355 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
356 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
357 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
358 (const :tag " mew Links to Mew folders/messages" org-mew)
359 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
360 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
361 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
362 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
363 (const :tag " vm: Links to VM folders/messages" org-vm)
364 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
365 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
366 (const :tag " mouse: Additional mouse support" org-mouse)
367 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
369 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
370 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
371 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
372 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
373 (const :tag "C collector: Collect properties into tables" org-collector)
374 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
375 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
376 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
377 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
378 (const :tag "C eval: Include command output as text" org-eval)
379 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
380 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
381 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
382 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
383 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
385 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
387 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
388 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
389 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
390 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
391 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
392 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
393 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
394 (const :tag "C mtags: Support for muse-like tags" org-mtags)
395 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
396 (const :tag "C registry: A registry for Org-mode links" org-registry)
397 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
398 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
399 (const :tag "C secretary: Team management with org-mode" org-secretary)
400 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
401 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
402 (const :tag "C track: Keep up with Org-mode development" org-track)
403 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
404 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
405 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
407 (defcustom org-support-shift-select nil
408 "Non-nil means make shift-cursor commands select text when possible.
410 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
411 start selecting a region, or enlarge regions started in this way.
412 In Org-mode, in special contexts, these same keys are used for
413 other purposes, important enough to compete with shift selection.
414 Org tries to balance these needs by supporting `shift-select-mode'
415 outside these special contexts, under control of this variable.
417 The default of this variable is nil, to avoid confusing behavior. Shifted
418 cursor keys will then execute Org commands in the following contexts:
419 - on a headline, changing TODO state (left/right) and priority (up/down)
420 - on a time stamp, changing the time
421 - in a plain list item, changing the bullet type
422 - in a property definition line, switching between allowed values
423 - in the BEGIN line of a clock table (changing the time block).
424 Outside these contexts, the commands will throw an error.
426 When this variable is t and the cursor is not in a special
427 context, Org-mode will support shift-selection for making and
428 enlarging regions. To make this more effective, the bullet
429 cycling will no longer happen anywhere in an item line, but only
430 if the cursor is exactly on the bullet.
432 If you set this variable to the symbol `always', then the keys
433 will not be special in headlines, property lines, and item lines,
434 to make shift selection work there as well. If this is what you
435 want, you can use the following alternative commands: `C-c C-t'
436 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
437 can be used to switch TODO sets, `C-c -' to cycle item bullet
438 types, and properties can be edited by hand or in column view.
440 However, when the cursor is on a timestamp, shift-cursor commands
441 will still edit the time stamp - this is just too good to give up.
443 XEmacs user should have this variable set to nil, because
444 `shift-select-mode' is in Emacs 23 or later only."
445 :group 'org
446 :type '(choice
447 (const :tag "Never" nil)
448 (const :tag "When outside special context" t)
449 (const :tag "Everywhere except timestamps" always)))
451 (defcustom org-loop-over-headlines-in-active-region nil
452 "Shall some commands act upon headlines in the active region?
454 When set to `t', some commands will be performed in all headlines
455 within the active region.
457 When set to `start-level', some commands will be performed in all
458 headlines within the active region, provided that these headlines
459 are of the same level than the first one.
461 When set to a string, those commands will be performed on the
462 matching headlines within the active region. Such string must be
463 a tags/property/todo match as it is used in the agenda tags view.
465 The list of commands is: `org-schedule', `org-deadline',
466 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
467 `org-archive-to-archive-sibling'. The archiving commands skip
468 already archived entries."
469 :type '(choice (const :tag "Don't loop" nil)
470 (const :tag "All headlines in active region" t)
471 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
472 (string :tag "Tags/Property/Todo matcher"))
473 :version "24.1"
474 :group 'org-todo
475 :group 'org-archive)
477 (defgroup org-startup nil
478 "Options concerning startup of Org-mode."
479 :tag "Org Startup"
480 :group 'org)
482 (defcustom org-startup-folded t
483 "Non-nil means entering Org-mode will switch to OVERVIEW.
484 This can also be configured on a per-file basis by adding one of
485 the following lines anywhere in the buffer:
487 #+STARTUP: fold (or `overview', this is equivalent)
488 #+STARTUP: nofold (or `showall', this is equivalent)
489 #+STARTUP: content
490 #+STARTUP: showeverything"
491 :group 'org-startup
492 :type '(choice
493 (const :tag "nofold: show all" nil)
494 (const :tag "fold: overview" t)
495 (const :tag "content: all headlines" content)
496 (const :tag "show everything, even drawers" showeverything)))
498 (defcustom org-startup-truncated t
499 "Non-nil means entering Org-mode will set `truncate-lines'.
500 This is useful since some lines containing links can be very long and
501 uninteresting. Also tables look terrible when wrapped."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-startup-indented nil
506 "Non-nil means turn on `org-indent-mode' on startup.
507 This can also be configured on a per-file basis by adding one of
508 the following lines anywhere in the buffer:
510 #+STARTUP: indent
511 #+STARTUP: noindent"
512 :group 'org-structure
513 :type '(choice
514 (const :tag "Not" nil)
515 (const :tag "Globally (slow on startup in large files)" t)))
517 (defcustom org-use-sub-superscripts t
518 "Non-nil means interpret \"_\" and \"^\" for export.
519 When this option is turned on, you can use TeX-like syntax for sub- and
520 superscripts. Several characters after \"_\" or \"^\" will be
521 considered as a single item - so grouping with {} is normally not
522 needed. For example, the following things will be parsed as single
523 sub- or superscripts.
525 10^24 or 10^tau several digits will be considered 1 item.
526 10^-12 or 10^-tau a leading sign with digits or a word
527 x^2-y^3 will be read as x^2 - y^3, because items are
528 terminated by almost any nonword/nondigit char.
529 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
531 Still, ambiguity is possible - so when in doubt use {} to enclose the
532 sub/superscript. If you set this variable to the symbol `{}',
533 the braces are *required* in order to trigger interpretations as
534 sub/superscript. This can be helpful in documents that need \"_\"
535 frequently in plain text.
537 Not all export backends support this, but HTML does.
539 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
540 :group 'org-startup
541 :group 'org-export-translation
542 :version "24.1"
543 :type '(choice
544 (const :tag "Always interpret" t)
545 (const :tag "Only with braces" {})
546 (const :tag "Never interpret" nil)))
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
552 (defcustom org-startup-with-beamer-mode nil
553 "Non-nil means turn on `org-beamer-mode' on startup.
554 This can also be configured on a per-file basis by adding one of
555 the following lines anywhere in the buffer:
557 #+STARTUP: beamer"
558 :group 'org-startup
559 :version "24.1"
560 :type 'boolean)
562 (defcustom org-startup-align-all-tables nil
563 "Non-nil means align all tables when visiting a file.
564 This is useful when the column width in tables is forced with <N> cookies
565 in table fields. Such tables will look correct only after the first re-align.
566 This can also be configured on a per-file basis by adding one of
567 the following lines anywhere in the buffer:
568 #+STARTUP: align
569 #+STARTUP: noalign"
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-startup-with-inline-images nil
574 "Non-nil means show inline images when loading a new Org file.
575 This can also be configured on a per-file basis by adding one of
576 the following lines anywhere in the buffer:
577 #+STARTUP: inlineimages
578 #+STARTUP: noinlineimages"
579 :group 'org-startup
580 :version "24.1"
581 :type 'boolean)
583 (defcustom org-insert-mode-line-in-empty-file nil
584 "Non-nil means insert the first line setting Org-mode in empty files.
585 When the function `org-mode' is called interactively in an empty file, this
586 normally means that the file name does not automatically trigger Org-mode.
587 To ensure that the file will always be in Org-mode in the future, a
588 line enforcing Org-mode will be inserted into the buffer, if this option
589 has been set."
590 :group 'org-startup
591 :type 'boolean)
593 (defcustom org-replace-disputed-keys nil
594 "Non-nil means use alternative key bindings for some keys.
595 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
596 These keys are also used by other packages like shift-selection-mode'
597 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
598 If you want to use Org-mode together with one of these other modes,
599 or more generally if you would like to move some Org-mode commands to
600 other keys, set this variable and configure the keys with the variable
601 `org-disputed-keys'.
603 This option is only relevant at load-time of Org-mode, and must be set
604 *before* org.el is loaded. Changing it requires a restart of Emacs to
605 become effective."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-use-extra-keys nil
610 "Non-nil means use extra key sequence definitions for certain commands.
611 This happens automatically if you run XEmacs or if `window-system'
612 is nil. This variable lets you do the same manually. You must
613 set it before loading org.
615 Example: on Carbon Emacs 22 running graphically, with an external
616 keyboard on a Powerbook, the default way of setting M-left might
617 not work for either Alt or ESC. Setting this variable will make
618 it work for ESC."
619 :group 'org-startup
620 :type 'boolean)
622 (if (fboundp 'defvaralias)
623 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
625 (defcustom org-disputed-keys
626 '(([(shift up)] . [(meta p)])
627 ([(shift down)] . [(meta n)])
628 ([(shift left)] . [(meta -)])
629 ([(shift right)] . [(meta +)])
630 ([(control shift right)] . [(meta shift +)])
631 ([(control shift left)] . [(meta shift -)]))
632 "Keys for which Org-mode and other modes compete.
633 This is an alist, cars are the default keys, second element specifies
634 the alternative to use when `org-replace-disputed-keys' is t.
636 Keys can be specified in any syntax supported by `define-key'.
637 The value of this option takes effect only at Org-mode's startup,
638 therefore you'll have to restart Emacs to apply it after changing."
639 :group 'org-startup
640 :type 'alist)
642 (defun org-key (key)
643 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
644 Or return the original if not disputed.
645 Also apply the translations defined in `org-xemacs-key-equivalents'."
646 (when org-replace-disputed-keys
647 (let* ((nkey (key-description key))
648 (x (org-find-if (lambda (x)
649 (equal (key-description (car x)) nkey))
650 org-disputed-keys)))
651 (setq key (if x (cdr x) key))))
652 (when (featurep 'xemacs)
653 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
654 key)
656 (defun org-find-if (predicate seq)
657 (catch 'exit
658 (while seq
659 (if (funcall predicate (car seq))
660 (throw 'exit (car seq))
661 (pop seq)))))
663 (defun org-defkey (keymap key def)
664 "Define a key, possibly translated, as returned by `org-key'."
665 (define-key keymap (org-key key) def))
667 (defcustom org-ellipsis nil
668 "The ellipsis to use in the Org-mode outline.
669 When nil, just use the standard three dots. When a string, use that instead,
670 When a face, use the standard 3 dots, but with the specified face.
671 The change affects only Org-mode (which will then use its own display table).
672 Changing this requires executing `M-x org-mode' in a buffer to become
673 effective."
674 :group 'org-startup
675 :type '(choice (const :tag "Default" nil)
676 (face :tag "Face" :value org-warning)
677 (string :tag "String" :value "...#")))
679 (defvar org-display-table nil
680 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
682 (defgroup org-keywords nil
683 "Keywords in Org-mode."
684 :tag "Org Keywords"
685 :group 'org)
687 (defcustom org-deadline-string "DEADLINE:"
688 "String to mark deadline entries.
689 A deadline is this string, followed by a time stamp. Should be a word,
690 terminated by a colon. You can insert a schedule keyword and
691 a timestamp with \\[org-deadline].
692 Changes become only effective after restarting Emacs."
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-scheduled-string "SCHEDULED:"
697 "String to mark scheduled TODO entries.
698 A schedule is this string, followed by a time stamp. Should be a word,
699 terminated by a colon. You can insert a schedule keyword and
700 a timestamp with \\[org-schedule].
701 Changes become only effective after restarting Emacs."
702 :group 'org-keywords
703 :type 'string)
705 (defcustom org-closed-string "CLOSED:"
706 "String used as the prefix for timestamps logging closing a TODO entry."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-clock-string "CLOCK:"
711 "String used as prefix for timestamps clocking work hours on an item."
712 :group 'org-keywords
713 :type 'string)
715 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
716 org-scheduled-string "\\|"
717 org-deadline-string "\\|"
718 org-closed-string "\\|"
719 org-clock-string "\\)")
720 "Matches a line with planning or clock info.")
722 (defcustom org-comment-string "COMMENT"
723 "Entries starting with this keyword will never be exported.
724 An entry can be toggled between COMMENT and normal with
725 \\[org-toggle-comment].
726 Changes become only effective after restarting Emacs."
727 :group 'org-keywords
728 :type 'string)
730 (defcustom org-quote-string "QUOTE"
731 "Entries starting with this keyword will be exported in fixed-width font.
732 Quoting applies only to the text in the entry following the headline, and does
733 not extend beyond the next headline, even if that is lower level.
734 An entry can be toggled between QUOTE and normal with
735 \\[org-toggle-fixed-width-section]."
736 :group 'org-keywords
737 :type 'string)
739 (defconst org-repeat-re
740 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
741 "Regular expression for specifying repeated events.
742 After a match, group 1 contains the repeat expression.")
744 (defgroup org-structure nil
745 "Options concerning the general structure of Org-mode files."
746 :tag "Org Structure"
747 :group 'org)
749 (defgroup org-reveal-location nil
750 "Options about how to make context of a location visible."
751 :tag "Org Reveal Location"
752 :group 'org-structure)
754 (defconst org-context-choice
755 '(choice
756 (const :tag "Always" t)
757 (const :tag "Never" nil)
758 (repeat :greedy t :tag "Individual contexts"
759 (cons
760 (choice :tag "Context"
761 (const agenda)
762 (const org-goto)
763 (const occur-tree)
764 (const tags-tree)
765 (const link-search)
766 (const mark-goto)
767 (const bookmark-jump)
768 (const isearch)
769 (const default))
770 (boolean))))
771 "Contexts for the reveal options.")
773 (defcustom org-show-hierarchy-above '((default . t))
774 "Non-nil means show full hierarchy when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the hierarchy of headings
777 above the exposed location is shown.
778 Turning this off for example for sparse trees makes them very compact.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. Valid contexts are
781 agenda when exposing an entry from the agenda
782 org-goto when using the command `org-goto' on key C-c C-j
783 occur-tree when using the command `org-occur' on key C-c /
784 tags-tree when constructing a sparse tree based on tags matches
785 link-search when exposing search matches associated with a link
786 mark-goto when exposing the jump goal of a mark
787 bookmark-jump when exposing a bookmark location
788 isearch when exiting from an incremental search
789 default default for all contexts not set explicitly"
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-show-following-heading '((default . nil))
794 "Non-nil means show following heading when revealing a location.
795 Org-mode often shows locations in an org-mode file which might have
796 been invisible before. When this is set, the heading following the
797 match is shown.
798 Turning this off for example for sparse trees makes them very compact,
799 but makes it harder to edit the location of the match. In such a case,
800 use the command \\[org-reveal] to show more context.
801 Instead of t, this can also be an alist specifying this option for different
802 contexts. See `org-show-hierarchy-above' for valid contexts."
803 :group 'org-reveal-location
804 :type org-context-choice)
806 (defcustom org-show-siblings '((default . nil) (isearch t))
807 "Non-nil means show all sibling heading when revealing a location.
808 Org-mode often shows locations in an org-mode file which might have
809 been invisible before. When this is set, the sibling of the current entry
810 heading are all made visible. If `org-show-hierarchy-above' is t,
811 the same happens on each level of the hierarchy above the current entry.
813 By default this is on for the isearch context, off for all other contexts.
814 Turning this off for example for sparse trees makes them very compact,
815 but makes it harder to edit the location of the match. In such a case,
816 use the command \\[org-reveal] to show more context.
817 Instead of t, this can also be an alist specifying this option for different
818 contexts. See `org-show-hierarchy-above' for valid contexts."
819 :group 'org-reveal-location
820 :type org-context-choice)
822 (defcustom org-show-entry-below '((default . nil))
823 "Non-nil means show the entry below a headline when revealing a location.
824 Org-mode often shows locations in an org-mode file which might have
825 been invisible before. When this is set, the text below the headline that is
826 exposed is also shown.
828 By default this is off for all contexts.
829 Instead of t, this can also be an alist specifying this option for different
830 contexts. See `org-show-hierarchy-above' for valid contexts."
831 :group 'org-reveal-location
832 :type org-context-choice)
834 (defcustom org-indirect-buffer-display 'other-window
835 "How should indirect tree buffers be displayed?
836 This applies to indirect buffers created with the commands
837 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
838 Valid values are:
839 current-window Display in the current window
840 other-window Just display in another window.
841 dedicated-frame Create one new frame, and re-use it each time.
842 new-frame Make a new frame each time. Note that in this case
843 previously-made indirect buffers are kept, and you need to
844 kill these buffers yourself."
845 :group 'org-structure
846 :group 'org-agenda-windows
847 :type '(choice
848 (const :tag "In current window" current-window)
849 (const :tag "In current frame, other window" other-window)
850 (const :tag "Each time a new frame" new-frame)
851 (const :tag "One dedicated frame" dedicated-frame)))
853 (defcustom org-use-speed-commands nil
854 "Non-nil means activate single letter commands at beginning of a headline.
855 This may also be a function to test for appropriate locations where speed
856 commands should be active."
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Never" nil)
860 (const :tag "At beginning of headline stars" t)
861 (function)))
863 (defcustom org-speed-commands-user nil
864 "Alist of additional speed commands.
865 This list will be checked before `org-speed-commands-default'
866 when the variable `org-use-speed-commands' is non-nil
867 and when the cursor is at the beginning of a headline.
868 The car if each entry is a string with a single letter, which must
869 be assigned to `self-insert-command' in the global map.
870 The cdr is either a command to be called interactively, a function
871 to be called, or a form to be evaluated.
872 An entry that is just a list with a single string will be interpreted
873 as a descriptive headline that will be added when listing the speed
874 commands in the Help buffer using the `?' speed command."
875 :group 'org-structure
876 :type '(repeat :value ("k" . ignore)
877 (choice :value ("k" . ignore)
878 (list :tag "Descriptive Headline" (string :tag "Headline"))
879 (cons :tag "Letter and Command"
880 (string :tag "Command letter")
881 (choice
882 (function)
883 (sexp))))))
885 (defgroup org-cycle nil
886 "Options concerning visibility cycling in Org-mode."
887 :tag "Org Cycle"
888 :group 'org-structure)
890 (defcustom org-cycle-skip-children-state-if-no-children t
891 "Non-nil means skip CHILDREN state in entries that don't have any."
892 :group 'org-cycle
893 :type 'boolean)
895 (defcustom org-cycle-max-level nil
896 "Maximum level which should still be subject to visibility cycling.
897 Levels higher than this will, for cycling, be treated as text, not a headline.
898 When `org-odd-levels-only' is set, a value of N in this variable actually
899 means 2N-1 stars as the limiting headline.
900 When nil, cycle all levels.
901 Note that the limiting level of cycling is also influenced by
902 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
903 `org-inlinetask-min-level' is, cycling will be limited to levels one less
904 than its value."
905 :group 'org-cycle
906 :type '(choice
907 (const :tag "No limit" nil)
908 (integer :tag "Maximum level")))
910 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
911 "Names of drawers. Drawers are not opened by cycling on the headline above.
912 Drawers only open with a TAB on the drawer line itself. A drawer looks like
913 this:
914 :DRAWERNAME:
915 .....
916 :END:
917 The drawer \"PROPERTIES\" is special for capturing properties through
918 the property API.
920 Drawers can be defined on the per-file basis with a line like:
922 #+DRAWERS: HIDDEN STATE PROPERTIES"
923 :group 'org-structure
924 :group 'org-cycle
925 :type '(repeat (string :tag "Drawer Name")))
927 (defcustom org-hide-block-startup nil
928 "Non-nil means entering Org-mode will fold all blocks.
929 This can also be set in on a per-file basis with
931 #+STARTUP: hideblocks
932 #+STARTUP: showblocks"
933 :group 'org-startup
934 :group 'org-cycle
935 :type 'boolean)
937 (defcustom org-cycle-global-at-bob nil
938 "Cycle globally if cursor is at beginning of buffer and not at a headline.
939 This makes it possible to do global cycling without having to use S-TAB or
940 \\[universal-argument] TAB. For this special case to work, the first line
941 of the buffer must not be a headline -- it may be empty or some other text.
942 When used in this way, `org-cycle-hook' is disabled temporarily to make
943 sure the cursor stays at the beginning of the buffer. When this option is
944 nil, don't do anything special at the beginning of the buffer."
945 :group 'org-cycle
946 :type 'boolean)
948 (defcustom org-cycle-level-after-item/entry-creation t
949 "Non-nil means cycle entry level or item indentation in new empty entries.
951 When the cursor is at the end of an empty headline, i.e with only stars
952 and maybe a TODO keyword, TAB will then switch the entry to become a child,
953 and then all possible ancestor states, before returning to the original state.
954 This makes data entry extremely fast: M-RET to create a new headline,
955 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
957 When the cursor is at the end of an empty plain list item, one TAB will
958 make it a subitem, two or more tabs will back up to make this an item
959 higher up in the item hierarchy."
960 :group 'org-cycle
961 :type 'boolean)
963 (defcustom org-cycle-emulate-tab t
964 "Where should `org-cycle' emulate TAB.
965 nil Never
966 white Only in completely white lines
967 whitestart Only at the beginning of lines, before the first non-white char
968 t Everywhere except in headlines
969 exc-hl-bol Everywhere except at the start of a headline
970 If TAB is used in a place where it does not emulate TAB, the current subtree
971 visibility is cycled."
972 :group 'org-cycle
973 :type '(choice (const :tag "Never" nil)
974 (const :tag "Only in completely white lines" white)
975 (const :tag "Before first char in a line" whitestart)
976 (const :tag "Everywhere except in headlines" t)
977 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
980 (defcustom org-cycle-separator-lines 2
981 "Number of empty lines needed to keep an empty line between collapsed trees.
982 If you leave an empty line between the end of a subtree and the following
983 headline, this empty line is hidden when the subtree is folded.
984 Org-mode will leave (exactly) one empty line visible if the number of
985 empty lines is equal or larger to the number given in this variable.
986 So the default 2 means at least 2 empty lines after the end of a subtree
987 are needed to produce free space between a collapsed subtree and the
988 following headline.
990 If the number is negative, and the number of empty lines is at least -N,
991 all empty lines are shown.
993 Special case: when 0, never leave empty lines in collapsed view."
994 :group 'org-cycle
995 :type 'integer)
996 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
998 (defcustom org-pre-cycle-hook nil
999 "Hook that is run before visibility cycling is happening.
1000 The function(s) in this hook must accept a single argument which indicates
1001 the new state that will be set right after running this hook. The
1002 argument is a symbol. Before a global state change, it can have the values
1003 `overview', `content', or `all'. Before a local state change, it can have
1004 the values `folded', `children', or `subtree'."
1005 :group 'org-cycle
1006 :type 'hook)
1008 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1009 org-cycle-hide-drawers
1010 org-cycle-hide-inline-tasks
1011 org-cycle-show-empty-lines
1012 org-optimize-window-after-visibility-change)
1013 "Hook that is run after `org-cycle' has changed the buffer visibility.
1014 The function(s) in this hook must accept a single argument which indicates
1015 the new state that was set by the most recent `org-cycle' command. The
1016 argument is a symbol. After a global state change, it can have the values
1017 `overview', `contents', or `all'. After a local state change, it can have
1018 the values `folded', `children', or `subtree'."
1019 :group 'org-cycle
1020 :type 'hook)
1022 (defgroup org-edit-structure nil
1023 "Options concerning structure editing in Org-mode."
1024 :tag "Org Edit Structure"
1025 :group 'org-structure)
1027 (defcustom org-odd-levels-only nil
1028 "Non-nil means skip even levels and only use odd levels for the outline.
1029 This has the effect that two stars are being added/taken away in
1030 promotion/demotion commands. It also influences how levels are
1031 handled by the exporters.
1032 Changing it requires restart of `font-lock-mode' to become effective
1033 for fontification also in regions already fontified.
1034 You may also set this on a per-file basis by adding one of the following
1035 lines to the buffer:
1037 #+STARTUP: odd
1038 #+STARTUP: oddeven"
1039 :group 'org-edit-structure
1040 :group 'org-appearance
1041 :type 'boolean)
1043 (defcustom org-adapt-indentation t
1044 "Non-nil means adapt indentation to outline node level.
1046 When this variable is set, Org assumes that you write outlines by
1047 indenting text in each node to align with the headline (after the stars).
1048 The following issues are influenced by this variable:
1050 - When this is set and the *entire* text in an entry is indented, the
1051 indentation is increased by one space in a demotion command, and
1052 decreased by one in a promotion command. If any line in the entry
1053 body starts with text at column 0, indentation is not changed at all.
1055 - Property drawers and planning information is inserted indented when
1056 this variable s set. When nil, they will not be indented.
1058 - TAB indents a line relative to context. The lines below a headline
1059 will be indented when this variable is set.
1061 Note that this is all about true indentation, by adding and removing
1062 space characters. See also `org-indent.el' which does level-dependent
1063 indentation in a virtual way, i.e. at display time in Emacs."
1064 :group 'org-edit-structure
1065 :type 'boolean)
1067 (defcustom org-special-ctrl-a/e nil
1068 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1070 When t, `C-a' will bring back the cursor to the beginning of the
1071 headline text, i.e. after the stars and after a possible TODO
1072 keyword. In an item, this will be the position after bullet and
1073 check-box, if any. When the cursor is already at that position,
1074 another `C-a' will bring it to the beginning of the line.
1076 `C-e' will jump to the end of the headline, ignoring the presence
1077 of tags in the headline. A second `C-e' will then jump to the
1078 true end of the line, after any tags. This also means that, when
1079 this variable is non-nil, `C-e' also will never jump beyond the
1080 end of the heading of a folded section, i.e. not after the
1081 ellipses.
1083 When set to the symbol `reversed', the first `C-a' or `C-e' works
1084 normally, going to the true line boundary first. Only a directly
1085 following, identical keypress will bring the cursor to the
1086 special positions.
1088 This may also be a cons cell where the behavior for `C-a' and
1089 `C-e' is set separately."
1090 :group 'org-edit-structure
1091 :type '(choice
1092 (const :tag "off" nil)
1093 (const :tag "on: after stars/bullet and before tags first" t)
1094 (const :tag "reversed: true line boundary first" reversed)
1095 (cons :tag "Set C-a and C-e separately"
1096 (choice :tag "Special C-a"
1097 (const :tag "off" nil)
1098 (const :tag "on: after stars/bullet first" t)
1099 (const :tag "reversed: before stars/bullet first" reversed))
1100 (choice :tag "Special C-e"
1101 (const :tag "off" nil)
1102 (const :tag "on: before tags first" t)
1103 (const :tag "reversed: after tags first" reversed)))))
1104 (if (fboundp 'defvaralias)
1105 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1107 (defcustom org-special-ctrl-k nil
1108 "Non-nil means `C-k' will behave specially in headlines.
1109 When nil, `C-k' will call the default `kill-line' command.
1110 When t, the following will happen while the cursor is in the headline:
1112 - When the cursor is at the beginning of a headline, kill the entire
1113 line and possible the folded subtree below the line.
1114 - When in the middle of the headline text, kill the headline up to the tags.
1115 - When after the headline text, kill the tags."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-ctrl-k-protect-subtree nil
1120 "Non-nil means, do not delete a hidden subtree with C-k.
1121 When set to the symbol `error', simply throw an error when C-k is
1122 used to kill (part-of) a headline that has hidden text behind it.
1123 Any other non-nil value will result in a query to the user, if it is
1124 OK to kill that hidden subtree. When nil, kill without remorse."
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not protect hidden subtrees" nil)
1129 (const :tag "Protect hidden subtrees with a security query" t)
1130 (const :tag "Never kill a hidden subtree with C-k" error)))
1132 (defcustom org-catch-invisible-edits nil
1133 "Check if in invisible region before inserting or deleting a character.
1134 Valid values are:
1136 nil Do not check, so just do invisible edits.
1137 error Throw an error and do nothing.
1138 show Make point visible, and do the requested edit.
1139 show-and-error Make point visible, then throw an error and abort the edit.
1140 smart Make point visible, and do insertion/deletion if it is
1141 adjacent to visible text and the change feels predictable.
1142 Never delete a previously invisible character or add in the
1143 middle or right after an invisible region. Basically, this
1144 allows insertion and backward-delete right before ellipses.
1145 FIXME: maybe in this case we should not even show?"
1146 :group 'org-edit-structure
1147 :version "24.1"
1148 :type '(choice
1149 (const :tag "Do not check" nil)
1150 (const :tag "Throw error when trying to edit" error)
1151 (const :tag "Unhide, but do not do the edit" show-and-error)
1152 (const :tag "Show invisible part and do the edit" show)
1153 (const :tag "Be smart and do the right thing" smart)))
1155 (defcustom org-yank-folded-subtrees t
1156 "Non-nil means when yanking subtrees, fold them.
1157 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1158 it starts with a heading and all other headings in it are either children
1159 or siblings, then fold all the subtrees. However, do this only if no
1160 text after the yank would be swallowed into a folded tree by this action."
1161 :group 'org-edit-structure
1162 :type 'boolean)
1164 (defcustom org-yank-adjusted-subtrees nil
1165 "Non-nil means when yanking subtrees, adjust the level.
1166 With this setting, `org-paste-subtree' is used to insert the subtree, see
1167 this function for details."
1168 :group 'org-edit-structure
1169 :type 'boolean)
1171 (defcustom org-M-RET-may-split-line '((default . t))
1172 "Non-nil means M-RET will split the line at the cursor position.
1173 When nil, it will go to the end of the line before making a
1174 new line.
1175 You may also set this option in a different way for different
1176 contexts. Valid contexts are:
1178 headline when creating a new headline
1179 item when creating a new item
1180 table in a table field
1181 default the value to be used for all contexts not explicitly
1182 customized"
1183 :group 'org-structure
1184 :group 'org-table
1185 :type '(choice
1186 (const :tag "Always" t)
1187 (const :tag "Never" nil)
1188 (repeat :greedy t :tag "Individual contexts"
1189 (cons
1190 (choice :tag "Context"
1191 (const headline)
1192 (const item)
1193 (const table)
1194 (const default))
1195 (boolean)))))
1198 (defcustom org-insert-heading-respect-content nil
1199 "Non-nil means insert new headings after the current subtree.
1200 When nil, the new heading is created directly after the current line.
1201 The commands \\[org-insert-heading-respect-content] and
1202 \\[org-insert-todo-heading-respect-content] turn this variable on
1203 for the duration of the command."
1204 :group 'org-structure
1205 :type 'boolean)
1207 (defcustom org-blank-before-new-entry '((heading . auto)
1208 (plain-list-item . auto))
1209 "Should `org-insert-heading' leave a blank line before new heading/item?
1210 The value is an alist, with `heading' and `plain-list-item' as CAR,
1211 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1212 which case Org will look at the surrounding headings/items and try to
1213 make an intelligent decision whether to insert a blank line or not.
1215 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1216 set, the setting here is ignored and no empty line is inserted, to avoid
1217 breaking the list structure."
1218 :group 'org-edit-structure
1219 :type '(list
1220 (cons (const heading)
1221 (choice (const :tag "Never" nil)
1222 (const :tag "Always" t)
1223 (const :tag "Auto" auto)))
1224 (cons (const plain-list-item)
1225 (choice (const :tag "Never" nil)
1226 (const :tag "Always" t)
1227 (const :tag "Auto" auto)))))
1229 (defcustom org-insert-heading-hook nil
1230 "Hook being run after inserting a new heading."
1231 :group 'org-edit-structure
1232 :type 'hook)
1234 (defcustom org-enable-fixed-width-editor t
1235 "Non-nil means lines starting with \":\" are treated as fixed-width.
1236 This currently only means they are never auto-wrapped.
1237 When nil, such lines will be treated like ordinary lines.
1238 See also the QUOTE keyword."
1239 :group 'org-edit-structure
1240 :type 'boolean)
1242 (defcustom org-goto-auto-isearch t
1243 "Non-nil means typing characters in `org-goto' starts incremental search."
1244 :group 'org-edit-structure
1245 :type 'boolean)
1247 (defgroup org-sparse-trees nil
1248 "Options concerning sparse trees in Org-mode."
1249 :tag "Org Sparse Trees"
1250 :group 'org-structure)
1252 (defcustom org-highlight-sparse-tree-matches t
1253 "Non-nil means highlight all matches that define a sparse tree.
1254 The highlights will automatically disappear the next time the buffer is
1255 changed by an edit command."
1256 :group 'org-sparse-trees
1257 :type 'boolean)
1259 (defcustom org-remove-highlights-with-change t
1260 "Non-nil means any change to the buffer will remove temporary highlights.
1261 Such highlights are created by `org-occur' and `org-clock-display'.
1262 When nil, `C-c C-c needs to be used to get rid of the highlights.
1263 The highlights created by `org-preview-latex-fragment' always need
1264 `C-c C-c' to be removed."
1265 :group 'org-sparse-trees
1266 :group 'org-time
1267 :type 'boolean)
1270 (defcustom org-occur-hook '(org-first-headline-recenter)
1271 "Hook that is run after `org-occur' has constructed a sparse tree.
1272 This can be used to recenter the window to show as much of the structure
1273 as possible."
1274 :group 'org-sparse-trees
1275 :type 'hook)
1277 (defgroup org-imenu-and-speedbar nil
1278 "Options concerning imenu and speedbar in Org-mode."
1279 :tag "Org Imenu and Speedbar"
1280 :group 'org-structure)
1282 (defcustom org-imenu-depth 2
1283 "The maximum level for Imenu access to Org-mode headlines.
1284 This also applied for speedbar access."
1285 :group 'org-imenu-and-speedbar
1286 :type 'integer)
1288 (defgroup org-table nil
1289 "Options concerning tables in Org-mode."
1290 :tag "Org Table"
1291 :group 'org)
1293 (defcustom org-enable-table-editor 'optimized
1294 "Non-nil means lines starting with \"|\" are handled by the table editor.
1295 When nil, such lines will be treated like ordinary lines.
1297 When equal to the symbol `optimized', the table editor will be optimized to
1298 do the following:
1299 - Automatic overwrite mode in front of whitespace in table fields.
1300 This makes the structure of the table stay in tact as long as the edited
1301 field does not exceed the column width.
1302 - Minimize the number of realigns. Normally, the table is aligned each time
1303 TAB or RET are pressed to move to another field. With optimization this
1304 happens only if changes to a field might have changed the column width.
1305 Optimization requires replacing the functions `self-insert-command',
1306 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1307 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1308 very good at guessing when a re-align will be necessary, but you can always
1309 force one with \\[org-ctrl-c-ctrl-c].
1311 If you would like to use the optimized version in Org-mode, but the
1312 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1314 This variable can be used to turn on and off the table editor during a session,
1315 but in order to toggle optimization, a restart is required.
1317 See also the variable `org-table-auto-blank-field'."
1318 :group 'org-table
1319 :type '(choice
1320 (const :tag "off" nil)
1321 (const :tag "on" t)
1322 (const :tag "on, optimized" optimized)))
1324 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1325 (version<= emacs-version "24.1"))
1326 "Non-nil means cluster self-insert commands for undo when possible.
1327 If this is set, then, like in the Emacs command loop, 20 consecutive
1328 characters will be undone together.
1329 This is configurable, because there is some impact on typing performance."
1330 :group 'org-table
1331 :type 'boolean)
1333 (defcustom org-table-tab-recognizes-table.el t
1334 "Non-nil means TAB will automatically notice a table.el table.
1335 When it sees such a table, it moves point into it and - if necessary -
1336 calls `table-recognize-table'."
1337 :group 'org-table-editing
1338 :type 'boolean)
1340 (defgroup org-link nil
1341 "Options concerning links in Org-mode."
1342 :tag "Org Link"
1343 :group 'org)
1345 (defvar org-link-abbrev-alist-local nil
1346 "Buffer-local version of `org-link-abbrev-alist', which see.
1347 The value of this is taken from the #+LINK lines.")
1348 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1350 (defcustom org-link-abbrev-alist nil
1351 "Alist of link abbreviations.
1352 The car of each element is a string, to be replaced at the start of a link.
1353 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1354 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1356 [[linkkey:tag][description]]
1358 The 'linkkey' must be a word word, starting with a letter, followed
1359 by letters, numbers, '-' or '_'.
1361 If REPLACE is a string, the tag will simply be appended to create the link.
1362 If the string contains \"%s\", the tag will be inserted there. If the string
1363 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1364 at that point (see the function `url-hexify-string'). If the string contains
1365 the specifier \"%(my-function)\", then the custom function `my-function' will
1366 be invoked: this function takes the tag as its only argument and must return
1367 a string.
1369 REPLACE may also be a function that will be called with the tag as the
1370 only argument to create the link, which should be returned as a string.
1372 See the manual for examples."
1373 :group 'org-link
1374 :type '(repeat
1375 (cons
1376 (string :tag "Protocol")
1377 (choice
1378 (string :tag "Format")
1379 (function)))))
1381 (defcustom org-descriptive-links t
1382 "Non-nil means Org will display descriptive links.
1383 E.g. [[http://orgmode.org][Org website]] will be displayed as
1384 \"Org Website\", hiding the link itself and just displaying its
1385 description. When set to `nil', Org will display the full links
1386 literally.
1388 You can interactively set the value of this variable by calling
1389 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1390 :group 'org-link
1391 :type 'boolean)
1393 (defcustom org-link-file-path-type 'adaptive
1394 "How the path name in file links should be stored.
1395 Valid values are:
1397 relative Relative to the current directory, i.e. the directory of the file
1398 into which the link is being inserted.
1399 absolute Absolute path, if possible with ~ for home directory.
1400 noabbrev Absolute path, no abbreviation of home directory.
1401 adaptive Use relative path for files in the current directory and sub-
1402 directories of it. For other files, use an absolute path."
1403 :group 'org-link
1404 :type '(choice
1405 (const relative)
1406 (const absolute)
1407 (const noabbrev)
1408 (const adaptive)))
1410 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1411 "Types of links that should be activated in Org-mode files.
1412 This is a list of symbols, each leading to the activation of a certain link
1413 type. In principle, it does not hurt to turn on most link types - there may
1414 be a small gain when turning off unused link types. The types are:
1416 bracket The recommended [[link][description]] or [[link]] links with hiding.
1417 angle Links in angular brackets that may contain whitespace like
1418 <bbdb:Carsten Dominik>.
1419 plain Plain links in normal text, no whitespace, like http://google.com.
1420 radio Text that is matched by a radio target, see manual for details.
1421 tag Tag settings in a headline (link to tag search).
1422 date Time stamps (link to calendar).
1423 footnote Footnote labels.
1425 Changing this variable requires a restart of Emacs to become effective."
1426 :group 'org-link
1427 :type '(set :greedy t
1428 (const :tag "Double bracket links" bracket)
1429 (const :tag "Angular bracket links" angle)
1430 (const :tag "Plain text links" plain)
1431 (const :tag "Radio target matches" radio)
1432 (const :tag "Tags" tag)
1433 (const :tag "Timestamps" date)
1434 (const :tag "Footnotes" footnote)))
1436 (defcustom org-make-link-description-function nil
1437 "Function to use for generating link descriptions from links.
1438 When nil, the link location will be used. This function must take
1439 two parameters: the first one is the link, the second one is the
1440 description generated by `org-insert-link'. The function should
1441 return the description to use."
1442 :group 'org-link
1443 :type 'function)
1445 (defgroup org-link-store nil
1446 "Options concerning storing links in Org-mode."
1447 :tag "Org Store Link"
1448 :group 'org-link)
1450 (defcustom org-url-hexify-p t
1451 "When non-nil, hexify URL when creating a link."
1452 :type 'boolean
1453 :version "24.3"
1454 :group 'org-link-store)
1456 (defcustom org-email-link-description-format "Email %c: %.30s"
1457 "Format of the description part of a link to an email or usenet message.
1458 The following %-escapes will be replaced by corresponding information:
1460 %F full \"From\" field
1461 %f name, taken from \"From\" field, address if no name
1462 %T full \"To\" field
1463 %t first name in \"To\" field, address if no name
1464 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1465 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1466 %s subject
1467 %d date
1468 %m message-id.
1470 You may use normal field width specification between the % and the letter.
1471 This is for example useful to limit the length of the subject.
1473 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1474 :group 'org-link-store
1475 :type 'string)
1477 (defcustom org-from-is-user-regexp
1478 (let (r1 r2)
1479 (when (and user-mail-address (not (string= user-mail-address "")))
1480 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1481 (when (and user-full-name (not (string= user-full-name "")))
1482 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1483 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1484 "Regexp matched against the \"From:\" header of an email or usenet message.
1485 It should match if the message is from the user him/herself."
1486 :group 'org-link-store
1487 :type 'regexp)
1489 (defcustom org-context-in-file-links t
1490 "Non-nil means file links from `org-store-link' contain context.
1491 A search string will be added to the file name with :: as separator and
1492 used to find the context when the link is activated by the command
1493 `org-open-at-point'. When this option is t, the entire active region
1494 will be placed in the search string of the file link. If set to a
1495 positive integer, only the first n lines of context will be stored.
1497 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1498 negates this setting for the duration of the command."
1499 :group 'org-link-store
1500 :type '(choice boolean integer))
1502 (defcustom org-keep-stored-link-after-insertion nil
1503 "Non-nil means keep link in list for entire session.
1505 The command `org-store-link' adds a link pointing to the current
1506 location to an internal list. These links accumulate during a session.
1507 The command `org-insert-link' can be used to insert links into any
1508 Org-mode file (offering completion for all stored links). When this
1509 option is nil, every link which has been inserted once using \\[org-insert-link]
1510 will be removed from the list, to make completing the unused links
1511 more efficient."
1512 :group 'org-link-store
1513 :type 'boolean)
1515 (defgroup org-link-follow nil
1516 "Options concerning following links in Org-mode."
1517 :tag "Org Follow Link"
1518 :group 'org-link)
1520 (defcustom org-link-translation-function nil
1521 "Function to translate links with different syntax to Org syntax.
1522 This can be used to translate links created for example by the Planner
1523 or emacs-wiki packages to Org syntax.
1524 The function must accept two parameters, a TYPE containing the link
1525 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1526 which is everything after the link protocol. It should return a cons
1527 with possibly modified values of type and path.
1528 Org contains a function for this, so if you set this variable to
1529 `org-translate-link-from-planner', you should be able follow many
1530 links created by planner."
1531 :group 'org-link-follow
1532 :type 'function)
1534 (defcustom org-follow-link-hook nil
1535 "Hook that is run after a link has been followed."
1536 :group 'org-link-follow
1537 :type 'hook)
1539 (defcustom org-tab-follows-link nil
1540 "Non-nil means on links TAB will follow the link.
1541 Needs to be set before org.el is loaded.
1542 This really should not be used, it does not make sense, and the
1543 implementation is bad."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-return-follows-link nil
1548 "Non-nil means on links RET will follow the link."
1549 :group 'org-link-follow
1550 :type 'boolean)
1552 (defcustom org-mouse-1-follows-link
1553 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1554 "Non-nil means mouse-1 on a link will follow the link.
1555 A longer mouse click will still set point. Does not work on XEmacs.
1556 Needs to be set before org.el is loaded."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mark-ring-length 4
1561 "Number of different positions to be recorded in the ring.
1562 Changing this requires a restart of Emacs to work correctly."
1563 :group 'org-link-follow
1564 :type 'integer)
1566 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1567 "Non-nil means internal links in Org files must exactly match a headline.
1568 When nil, the link search tries to match a phrase with all words
1569 in the search text."
1570 :group 'org-link-follow
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Use fuzzy text search" nil)
1574 (const :tag "Match only exact headline" t)
1575 (const :tag "Match exact headline or query to create it"
1576 query-to-create)))
1578 (defcustom org-link-frame-setup
1579 '((vm . vm-visit-folder-other-frame)
1580 (vm-imap . vm-visit-imap-folder-other-frame)
1581 (gnus . org-gnus-no-new-news)
1582 (file . find-file-other-window)
1583 (wl . wl-other-frame))
1584 "Setup the frame configuration for following links.
1585 When following a link with Emacs, it may often be useful to display
1586 this link in another window or frame. This variable can be used to
1587 set this up for the different types of links.
1588 For VM, use any of
1589 `vm-visit-folder'
1590 `vm-visit-folder-other-window'
1591 `vm-visit-folder-other-frame'
1592 For Gnus, use any of
1593 `gnus'
1594 `gnus-other-frame'
1595 `org-gnus-no-new-news'
1596 For FILE, use any of
1597 `find-file'
1598 `find-file-other-window'
1599 `find-file-other-frame'
1600 For Wanderlust use any of
1601 `wl'
1602 `wl-other-frame'
1603 For the calendar, use the variable `calendar-setup'.
1604 For BBDB, it is currently only possible to display the matches in
1605 another window."
1606 :group 'org-link-follow
1607 :type '(list
1608 (cons (const vm)
1609 (choice
1610 (const vm-visit-folder)
1611 (const vm-visit-folder-other-window)
1612 (const vm-visit-folder-other-frame)))
1613 (cons (const gnus)
1614 (choice
1615 (const gnus)
1616 (const gnus-other-frame)
1617 (const org-gnus-no-new-news)))
1618 (cons (const file)
1619 (choice
1620 (const find-file)
1621 (const find-file-other-window)
1622 (const find-file-other-frame)))
1623 (cons (const wl)
1624 (choice
1625 (const wl)
1626 (const wl-other-frame)))))
1628 (defcustom org-display-internal-link-with-indirect-buffer nil
1629 "Non-nil means use indirect buffer to display infile links.
1630 Activating internal links (from one location in a file to another location
1631 in the same file) normally just jumps to the location. When the link is
1632 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 is displayed in
1634 another window. When this option is set, the other window actually displays
1635 an indirect buffer clone of the current buffer, to avoid any visibility
1636 changes to the current buffer."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-non-existing-files nil
1641 "Non-nil means `org-open-file' will open non-existing files.
1642 When nil, an error will be generated.
1643 This variable applies only to external applications because they
1644 might choke on non-existing files. If the link is to a file that
1645 will be opened in Emacs, the variable is ignored."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-directory-means-index-dot-org nil
1650 "Non-nil means a link to a directory really means to index.org.
1651 When nil, following a directory link will run dired or open a finder/explorer
1652 window on that directory."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1657 "Function and arguments to call for following mailto links.
1658 This is a list with the first element being a Lisp function, and the
1659 remaining elements being arguments to the function. In string arguments,
1660 %a will be replaced by the address, and %s will be replaced by the subject
1661 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1665 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1666 (const :tag "message-mail" (message-mail "%a" "%s"))
1667 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1669 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1670 "Non-nil means ask for confirmation before executing shell links.
1671 Shell links can be dangerous: just think about a link
1673 [[shell:rm -rf ~/*][Google Search]]
1675 This link would show up in your Org-mode document as \"Google Search\",
1676 but really it would remove your entire home directory.
1677 Therefore we advise against setting this variable to nil.
1678 Just change it to `y-or-n-p' if you want to confirm with a
1679 single keystroke rather than having to type \"yes\"."
1680 :group 'org-link-follow
1681 :type '(choice
1682 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1683 (const :tag "with y-or-n (faster)" y-or-n-p)
1684 (const :tag "no confirmation (dangerous)" nil)))
1685 (put 'org-confirm-shell-link-function
1686 'safe-local-variable
1687 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1689 (defcustom org-confirm-shell-link-not-regexp ""
1690 "A regexp to skip confirmation for shell links."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type 'regexp)
1695 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1696 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1697 Elisp links can be dangerous: just think about a link
1699 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1701 This link would show up in your Org-mode document as \"Google Search\",
1702 but really it would remove your entire home directory.
1703 Therefore we advise against setting this variable to nil.
1704 Just change it to `y-or-n-p' if you want to confirm with a
1705 single keystroke rather than having to type \"yes\"."
1706 :group 'org-link-follow
1707 :type '(choice
1708 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1709 (const :tag "with y-or-n (faster)" y-or-n-p)
1710 (const :tag "no confirmation (dangerous)" nil)))
1711 (put 'org-confirm-shell-link-function
1712 'safe-local-variable
1713 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1715 (defcustom org-confirm-elisp-link-not-regexp ""
1716 "A regexp to skip confirmation for Elisp links."
1717 :group 'org-link-follow
1718 :version "24.1"
1719 :type 'regexp)
1721 (defconst org-file-apps-defaults-gnu
1722 '((remote . emacs)
1723 (system . mailcap)
1724 (t . mailcap))
1725 "Default file applications on a UNIX or GNU/Linux system.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-macosx
1729 '((remote . emacs)
1730 (t . "open %s")
1731 (system . "open %s")
1732 ("ps.gz" . "gv %s")
1733 ("eps.gz" . "gv %s")
1734 ("dvi" . "xdvi %s")
1735 ("fig" . "xfig %s"))
1736 "Default file applications on a MacOS X system.
1737 The system \"open\" is known as a default, but we use X11 applications
1738 for some files for which the OS does not have a good default.
1739 See `org-file-apps'.")
1741 (defconst org-file-apps-defaults-windowsnt
1742 (list
1743 '(remote . emacs)
1744 (cons t
1745 (list (if (featurep 'xemacs)
1746 'mswindows-shell-execute
1747 'w32-shell-execute)
1748 "open" 'file))
1749 (cons 'system
1750 (list (if (featurep 'xemacs)
1751 'mswindows-shell-execute
1752 'w32-shell-execute)
1753 "open" 'file)))
1754 "Default file applications on a Windows NT system.
1755 The system \"open\" is used for most files.
1756 See `org-file-apps'.")
1758 (defcustom org-file-apps
1760 (auto-mode . emacs)
1761 ("\\.mm\\'" . default)
1762 ("\\.x?html?\\'" . default)
1763 ("\\.pdf\\'" . default)
1765 "External applications for opening `file:path' items in a document.
1766 Org-mode uses system defaults for different file types, but
1767 you can use this variable to set the application for a given file
1768 extension. The entries in this list are cons cells where the car identifies
1769 files and the cdr the corresponding command. Possible values for the
1770 file identifier are
1771 \"string\" A string as a file identifier can be interpreted in different
1772 ways, depending on its contents:
1774 - Alphanumeric characters only:
1775 Match links with this file extension.
1776 Example: (\"pdf\" . \"evince %s\")
1777 to open PDFs with evince.
1779 - Regular expression: Match links where the
1780 filename matches the regexp. If you want to
1781 use groups here, use shy groups.
1783 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1784 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1785 to open *.html and *.xhtml with firefox.
1787 - Regular expression which contains (non-shy) groups:
1788 Match links where the whole link, including \"::\", and
1789 anything after that, matches the regexp.
1790 In a custom command string, %1, %2, etc. are replaced with
1791 the parts of the link that were matched by the groups.
1792 For backwards compatibility, if a command string is given
1793 that does not use any of the group matches, this case is
1794 handled identically to the second one (i.e. match against
1795 file name only).
1796 In a custom lisp form, you can access the group matches with
1797 (match-string n link).
1799 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1800 to open [[file:document.pdf::5]] with evince at page 5.
1802 `directory' Matches a directory
1803 `remote' Matches a remote file, accessible through tramp or efs.
1804 Remote files most likely should be visited through Emacs
1805 because external applications cannot handle such paths.
1806 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1807 so all files Emacs knows how to handle. Using this with
1808 command `emacs' will open most files in Emacs. Beware that this
1809 will also open html files inside Emacs, unless you add
1810 (\"html\" . default) to the list as well.
1811 t Default for files not matched by any of the other options.
1812 `system' The system command to open files, like `open' on Windows
1813 and Mac OS X, and mailcap under GNU/Linux. This is the command
1814 that will be selected if you call `C-c C-o' with a double
1815 \\[universal-argument] \\[universal-argument] prefix.
1817 Possible values for the command are:
1818 `emacs' The file will be visited by the current Emacs process.
1819 `default' Use the default application for this file type, which is the
1820 association for t in the list, most likely in the system-specific
1821 part.
1822 This can be used to overrule an unwanted setting in the
1823 system-specific variable.
1824 `system' Use the system command for opening files, like \"open\".
1825 This command is specified by the entry whose car is `system'.
1826 Most likely, the system-specific version of this variable
1827 does define this command, but you can overrule/replace it
1828 here.
1829 string A command to be executed by a shell; %s will be replaced
1830 by the path to the file.
1831 sexp A Lisp form which will be evaluated. The file path will
1832 be available in the Lisp variable `file'.
1833 For more examples, see the system specific constants
1834 `org-file-apps-defaults-macosx'
1835 `org-file-apps-defaults-windowsnt'
1836 `org-file-apps-defaults-gnu'."
1837 :group 'org-link-follow
1838 :type '(repeat
1839 (cons (choice :value ""
1840 (string :tag "Extension")
1841 (const :tag "System command to open files" system)
1842 (const :tag "Default for unrecognized files" t)
1843 (const :tag "Remote file" remote)
1844 (const :tag "Links to a directory" directory)
1845 (const :tag "Any files that have Emacs modes"
1846 auto-mode))
1847 (choice :value ""
1848 (const :tag "Visit with Emacs" emacs)
1849 (const :tag "Use default" default)
1850 (const :tag "Use the system command" system)
1851 (string :tag "Command")
1852 (sexp :tag "Lisp form")))))
1854 (defcustom org-doi-server-url "http://dx.doi.org/"
1855 "The URL of the DOI server."
1856 :type 'string
1857 :version "24.3"
1858 :group 'org-link-follow)
1860 (defgroup org-refile nil
1861 "Options concerning refiling entries in Org-mode."
1862 :tag "Org Refile"
1863 :group 'org)
1865 (defcustom org-directory "~/org"
1866 "Directory with org files.
1867 This is just a default location to look for Org files. There is no need
1868 at all to put your files into this directory. It is only used in the
1869 following situations:
1871 1. When a capture template specifies a target file that is not an
1872 absolute path. The path will then be interpreted relative to
1873 `org-directory'
1874 2. When a capture note is filed away in an interactive way (when exiting the
1875 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1876 with `org-directory' as the default path."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :group 'org-capture
1880 :type 'directory)
1882 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1883 "Default target for storing notes.
1884 Used as a fall back file for org-remember.el and org-capture.el, for
1885 templates that do not specify a target file."
1886 :group 'org-refile
1887 :group 'org-remember
1888 :group 'org-capture
1889 :type '(choice
1890 (const :tag "Default from remember-data-file" nil)
1891 file))
1893 (defcustom org-goto-interface 'outline
1894 "The default interface to be used for `org-goto'.
1895 Allowed values are:
1896 outline The interface shows an outline of the relevant file
1897 and the correct heading is found by moving through
1898 the outline or by searching with incremental search.
1899 outline-path-completion Headlines in the current buffer are offered via
1900 completion. This is the interface also used by
1901 the refile command."
1902 :group 'org-refile
1903 :type '(choice
1904 (const :tag "Outline" outline)
1905 (const :tag "Outline-path-completion" outline-path-completion)))
1907 (defcustom org-goto-max-level 5
1908 "Maximum target level when running `org-goto' with refile interface."
1909 :group 'org-refile
1910 :type 'integer)
1912 (defcustom org-reverse-note-order nil
1913 "Non-nil means store new notes at the beginning of a file or entry.
1914 When nil, new notes will be filed to the end of a file or entry.
1915 This can also be a list with cons cells of regular expressions that
1916 are matched against file names, and values."
1917 :group 'org-remember
1918 :group 'org-capture
1919 :group 'org-refile
1920 :type '(choice
1921 (const :tag "Reverse always" t)
1922 (const :tag "Reverse never" nil)
1923 (repeat :tag "By file name regexp"
1924 (cons regexp boolean))))
1926 (defcustom org-log-refile nil
1927 "Information to record when a task is refiled.
1929 Possible values are:
1931 nil Don't add anything
1932 time Add a time stamp to the task
1933 note Prompt for a note and add it with template `org-log-note-headings'
1935 This option can also be set with on a per-file-basis with
1937 #+STARTUP: nologrefile
1938 #+STARTUP: logrefile
1939 #+STARTUP: lognoterefile
1941 You can have local logging settings for a subtree by setting the LOGGING
1942 property to one or more of these keywords.
1944 When bulk-refiling from the agenda, the value `note' is forbidden and
1945 will temporarily be changed to `time'."
1946 :group 'org-refile
1947 :group 'org-progress
1948 :version "24.1"
1949 :type '(choice
1950 (const :tag "No logging" nil)
1951 (const :tag "Record timestamp" time)
1952 (const :tag "Record timestamp with note." note)))
1954 (defcustom org-refile-targets nil
1955 "Targets for refiling entries with \\[org-refile].
1956 This is a list of cons cells. Each cell contains:
1957 - a specification of the files to be considered, either a list of files,
1958 or a symbol whose function or variable value will be used to retrieve
1959 a file name or a list of file names. If you use `org-agenda-files' for
1960 that, all agenda files will be scanned for targets. Nil means consider
1961 headings in the current buffer.
1962 - A specification of how to find candidate refile targets. This may be
1963 any of:
1964 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1965 This tag has to be present in all target headlines, inheritance will
1966 not be considered.
1967 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1968 todo keyword.
1969 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1970 headlines that are refiling targets.
1971 - a cons cell (:level . N). Any headline of level N is considered a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1974 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1975 Note that, when `org-odd-levels-only' is set, level corresponds to
1976 order in hierarchy, not to the number of stars.
1978 Each element of this list generates a set of possible targets.
1979 The union of these sets is presented (with completion) to
1980 the user by `org-refile'.
1982 You can set the variable `org-refile-target-verify-function' to a function
1983 to verify each headline found by the simple criteria above.
1985 When this variable is nil, all top-level headlines in the current buffer
1986 are used, equivalent to the value `((nil . (:level . 1))'."
1987 :group 'org-refile
1988 :type '(repeat
1989 (cons
1990 (choice :value org-agenda-files
1991 (const :tag "All agenda files" org-agenda-files)
1992 (const :tag "Current buffer" nil)
1993 (function) (variable) (file))
1994 (choice :tag "Identify target headline by"
1995 (cons :tag "Specific tag" (const :value :tag) (string))
1996 (cons :tag "TODO keyword" (const :value :todo) (string))
1997 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1998 (cons :tag "Level number" (const :value :level) (integer))
1999 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2001 (defcustom org-refile-target-verify-function nil
2002 "Function to verify if the headline at point should be a refile target.
2003 The function will be called without arguments, with point at the
2004 beginning of the headline. It should return t and leave point
2005 where it is if the headline is a valid target for refiling.
2007 If the target should not be selected, the function must return nil.
2008 In addition to this, it may move point to a place from where the search
2009 should be continued. For example, the function may decide that the entire
2010 subtree of the current entry should be excluded and move point to the end
2011 of the subtree."
2012 :group 'org-refile
2013 :type 'function)
2015 (defcustom org-refile-use-cache nil
2016 "Non-nil means cache refile targets to speed up the process.
2017 The cache for a particular file will be updated automatically when
2018 the buffer has been killed, or when any of the marker used for flagging
2019 refile targets no longer points at a live buffer.
2020 If you have added new entries to a buffer that might themselves be targets,
2021 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2022 find that easier, `C-u C-u C-u C-c C-w'."
2023 :group 'org-refile
2024 :version "24.1"
2025 :type 'boolean)
2027 (defcustom org-refile-use-outline-path nil
2028 "Non-nil means provide refile targets as paths.
2029 So a level 3 headline will be available as level1/level2/level3.
2031 When the value is `file', also include the file name (without directory)
2032 into the path. In this case, you can also stop the completion after
2033 the file name, to get entries inserted as top level in the file.
2035 When `full-file-path', include the full file path."
2036 :group 'org-refile
2037 :type '(choice
2038 (const :tag "Not" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Start with file name" file)
2041 (const :tag "Start with full file path" full-file-path)))
2043 (defcustom org-outline-path-complete-in-steps t
2044 "Non-nil means complete the outline path in hierarchical steps.
2045 When Org-mode uses the refile interface to select an outline path
2046 \(see variable `org-refile-use-outline-path'), the completion of
2047 the path can be done is a single go, or if can be done in steps down
2048 the headline hierarchy. Going in steps is probably the best if you
2049 do not use a special completion package like `ido' or `icicles'.
2050 However, when using these packages, going in one step can be very
2051 fast, while still showing the whole path to the entry."
2052 :group 'org-refile
2053 :type 'boolean)
2055 (defcustom org-refile-allow-creating-parent-nodes nil
2056 "Non-nil means allow to create new nodes as refile targets.
2057 New nodes are then created by adding \"/new node name\" to the completion
2058 of an existing node. When the value of this variable is `confirm',
2059 new node creation must be confirmed by the user (recommended)
2060 When nil, the completion must match an existing entry.
2062 Note that, if the new heading is not seen by the criteria
2063 listed in `org-refile-targets', multiple instances of the same
2064 heading would be created by trying again to file under the new
2065 heading."
2066 :group 'org-refile
2067 :type '(choice
2068 (const :tag "Never" nil)
2069 (const :tag "Always" t)
2070 (const :tag "Prompt for confirmation" confirm)))
2072 (defcustom org-refile-active-region-within-subtree nil
2073 "Non-nil means also refile active region within a subtree.
2075 By default `org-refile' doesn't allow refiling regions if they
2076 don't contain a set of subtrees, but it might be convenient to
2077 do so sometimes: in that case, the first line of the region is
2078 converted to a headline before refiling."
2079 :group 'org-refile
2080 :version "24.1"
2081 :type 'boolean)
2083 (defgroup org-todo nil
2084 "Options concerning TODO items in Org-mode."
2085 :tag "Org TODO"
2086 :group 'org)
2088 (defgroup org-progress nil
2089 "Options concerning Progress logging in Org-mode."
2090 :tag "Org Progress"
2091 :group 'org-time)
2093 (defvar org-todo-interpretation-widgets
2094 '((:tag "Sequence (cycling hits every state)" sequence)
2095 (:tag "Type (cycling directly to DONE)" type))
2096 "The available interpretation symbols for customizing `org-todo-keywords'.
2097 Interested libraries should add to this list.")
2099 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2100 "List of TODO entry keyword sequences and their interpretation.
2101 \\<org-mode-map>This is a list of sequences.
2103 Each sequence starts with a symbol, either `sequence' or `type',
2104 indicating if the keywords should be interpreted as a sequence of
2105 action steps, or as different types of TODO items. The first
2106 keywords are states requiring action - these states will select a headline
2107 for inclusion into the global TODO list Org-mode produces. If one of
2108 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2109 signify that no further action is necessary. If \"|\" is not found,
2110 the last keyword is treated as the only DONE state of the sequence.
2112 The command \\[org-todo] cycles an entry through these states, and one
2113 additional state where no keyword is present. For details about this
2114 cycling, see the manual.
2116 TODO keywords and interpretation can also be set on a per-file basis with
2117 the special #+SEQ_TODO and #+TYP_TODO lines.
2119 Each keyword can optionally specify a character for fast state selection
2120 \(in combination with the variable `org-use-fast-todo-selection')
2121 and specifiers for state change logging, using the same syntax that
2122 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2123 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2124 indicates to record a time stamp each time this state is selected.
2126 Each keyword may also specify if a timestamp or a note should be
2127 recorded when entering or leaving the state, by adding additional
2128 characters in the parenthesis after the keyword. This looks like this:
2129 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2130 record only the time of the state change. With X and Y being either
2131 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2132 Y when leaving the state if and only if the *target* state does not
2133 define X. You may omit any of the fast-selection key or X or /Y,
2134 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2136 For backward compatibility, this variable may also be just a list
2137 of keywords. In this case the interpretation (sequence or type) will be
2138 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2139 :group 'org-todo
2140 :group 'org-keywords
2141 :type '(choice
2142 (repeat :tag "Old syntax, just keywords"
2143 (string :tag "Keyword"))
2144 (repeat :tag "New syntax"
2145 (cons
2146 (choice
2147 :tag "Interpretation"
2148 ;;Quick and dirty way to see
2149 ;;`org-todo-interpretations'. This takes the
2150 ;;place of item arguments
2151 :convert-widget
2152 (lambda (widget)
2153 (widget-put widget
2154 :args (mapcar
2155 #'(lambda (x)
2156 (widget-convert
2157 (cons 'const x)))
2158 org-todo-interpretation-widgets))
2159 widget))
2160 (repeat
2161 (string :tag "Keyword"))))))
2163 (defvar org-todo-keywords-1 nil
2164 "All TODO and DONE keywords active in a buffer.")
2165 (make-variable-buffer-local 'org-todo-keywords-1)
2166 (defvar org-todo-keywords-for-agenda nil)
2167 (defvar org-done-keywords-for-agenda nil)
2168 (defvar org-drawers-for-agenda nil)
2169 (defvar org-todo-keyword-alist-for-agenda nil)
2170 (defvar org-tag-alist-for-agenda nil)
2171 (defvar org-agenda-contributing-files nil)
2172 (defvar org-not-done-keywords nil)
2173 (make-variable-buffer-local 'org-not-done-keywords)
2174 (defvar org-done-keywords nil)
2175 (make-variable-buffer-local 'org-done-keywords)
2176 (defvar org-todo-heads nil)
2177 (make-variable-buffer-local 'org-todo-heads)
2178 (defvar org-todo-sets nil)
2179 (make-variable-buffer-local 'org-todo-sets)
2180 (defvar org-todo-log-states nil)
2181 (make-variable-buffer-local 'org-todo-log-states)
2182 (defvar org-todo-kwd-alist nil)
2183 (make-variable-buffer-local 'org-todo-kwd-alist)
2184 (defvar org-todo-key-alist nil)
2185 (make-variable-buffer-local 'org-todo-key-alist)
2186 (defvar org-todo-key-trigger nil)
2187 (make-variable-buffer-local 'org-todo-key-trigger)
2189 (defcustom org-todo-interpretation 'sequence
2190 "Controls how TODO keywords are interpreted.
2191 This variable is in principle obsolete and is only used for
2192 backward compatibility, if the interpretation of todo keywords is
2193 not given already in `org-todo-keywords'. See that variable for
2194 more information."
2195 :group 'org-todo
2196 :group 'org-keywords
2197 :type '(choice (const sequence)
2198 (const type)))
2200 (defcustom org-use-fast-todo-selection t
2201 "Non-nil means use the fast todo selection scheme with C-c C-t.
2202 This variable describes if and under what circumstances the cycling
2203 mechanism for TODO keywords will be replaced by a single-key, direct
2204 selection scheme.
2206 When nil, fast selection is never used.
2208 When the symbol `prefix', it will be used when `org-todo' is called
2209 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2210 `C-u t' in an agenda buffer.
2212 When t, fast selection is used by default. In this case, the prefix
2213 argument forces cycling instead.
2215 In all cases, the special interface is only used if access keys have
2216 actually been assigned by the user, i.e. if keywords in the configuration
2217 are followed by a letter in parenthesis, like TODO(t)."
2218 :group 'org-todo
2219 :type '(choice
2220 (const :tag "Never" nil)
2221 (const :tag "By default" t)
2222 (const :tag "Only with C-u C-c C-t" prefix)))
2224 (defcustom org-provide-todo-statistics t
2225 "Non-nil means update todo statistics after insert and toggle.
2226 ALL-HEADLINES means update todo statistics by including headlines
2227 with no TODO keyword as well, counting them as not done.
2228 A list of TODO keywords means the same, but skip keywords that are
2229 not in this list.
2231 When this is set, todo statistics is updated in the parent of the
2232 current entry each time a todo state is changed."
2233 :group 'org-todo
2234 :type '(choice
2235 (const :tag "Yes, only for TODO entries" t)
2236 (const :tag "Yes, including all entries" 'all-headlines)
2237 (repeat :tag "Yes, for TODOs in this list"
2238 (string :tag "TODO keyword"))
2239 (other :tag "No TODO statistics" nil)))
2241 (defcustom org-hierarchical-todo-statistics t
2242 "Non-nil means TODO statistics covers just direct children.
2243 When nil, all entries in the subtree are considered.
2244 This has only an effect if `org-provide-todo-statistics' is set.
2245 To set this to nil for only a single subtree, use a COOKIE_DATA
2246 property and include the word \"recursive\" into the value."
2247 :group 'org-todo
2248 :type 'boolean)
2250 (defcustom org-after-todo-state-change-hook nil
2251 "Hook which is run after the state of a TODO item was changed.
2252 The new state (a string with a TODO keyword, or nil) is available in the
2253 Lisp variable `org-state'."
2254 :group 'org-todo
2255 :type 'hook)
2257 (defvar org-blocker-hook nil
2258 "Hook for functions that are allowed to block a state change.
2260 Functions in this hook should not modify the buffer.
2261 Each function gets as its single argument a property list,
2262 see `org-trigger-hook' for more information about this list.
2264 If any of the functions in this hook returns nil, the state change
2265 is blocked.")
2267 (defvar org-trigger-hook nil
2268 "Hook for functions that are triggered by a state change.
2270 Each function gets as its single argument a property list with at
2271 least the following elements:
2273 (:type type-of-change :position pos-at-entry-start
2274 :from old-state :to new-state)
2276 Depending on the type, more properties may be present.
2278 This mechanism is currently implemented for:
2280 TODO state changes
2281 ------------------
2282 :type todo-state-change
2283 :from previous state (keyword as a string), or nil, or a symbol
2284 'todo' or 'done', to indicate the general type of state.
2285 :to new state, like in :from")
2287 (defcustom org-enforce-todo-dependencies nil
2288 "Non-nil means undone TODO entries will block switching the parent to DONE.
2289 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2290 be blocked if any prior sibling is not yet done.
2291 Finally, if the parent is blocked because of ordered siblings of its own,
2292 the child will also be blocked."
2293 :set (lambda (var val)
2294 (set var val)
2295 (if val
2296 (add-hook 'org-blocker-hook
2297 'org-block-todo-from-children-or-siblings-or-parent)
2298 (remove-hook 'org-blocker-hook
2299 'org-block-todo-from-children-or-siblings-or-parent)))
2300 :group 'org-todo
2301 :type 'boolean)
2303 (defcustom org-enforce-todo-checkbox-dependencies nil
2304 "Non-nil means unchecked boxes will block switching the parent to DONE.
2305 When this is nil, checkboxes have no influence on switching TODO states.
2306 When non-nil, you first need to check off all check boxes before the TODO
2307 entry can be switched to DONE.
2308 This variable needs to be set before org.el is loaded, and you need to
2309 restart Emacs after a change to make the change effective. The only way
2310 to change is while Emacs is running is through the customize interface."
2311 :set (lambda (var val)
2312 (set var val)
2313 (if val
2314 (add-hook 'org-blocker-hook
2315 'org-block-todo-from-checkboxes)
2316 (remove-hook 'org-blocker-hook
2317 'org-block-todo-from-checkboxes)))
2318 :group 'org-todo
2319 :type 'boolean)
2321 (defcustom org-treat-insert-todo-heading-as-state-change nil
2322 "Non-nil means inserting a TODO heading is treated as state change.
2323 So when the command \\[org-insert-todo-heading] is used, state change
2324 logging will apply if appropriate. When nil, the new TODO item will
2325 be inserted directly, and no logging will take place."
2326 :group 'org-todo
2327 :type 'boolean)
2329 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2330 "Non-nil means switching TODO states with S-cursor counts as state change.
2331 This is the default behavior. However, setting this to nil allows a
2332 convenient way to select a TODO state and bypass any logging associated
2333 with that."
2334 :group 'org-todo
2335 :type 'boolean)
2337 (defcustom org-todo-state-tags-triggers nil
2338 "Tag changes that should be triggered by TODO state changes.
2339 This is a list. Each entry is
2341 (state-change (tag . flag) .......)
2343 State-change can be a string with a state, and empty string to indicate the
2344 state that has no TODO keyword, or it can be one of the symbols `todo'
2345 or `done', meaning any not-done or done state, respectively."
2346 :group 'org-todo
2347 :group 'org-tags
2348 :type '(repeat
2349 (cons (choice :tag "When changing to"
2350 (const :tag "Not-done state" todo)
2351 (const :tag "Done state" done)
2352 (string :tag "State"))
2353 (repeat
2354 (cons :tag "Tag action"
2355 (string :tag "Tag")
2356 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2358 (defcustom org-log-done nil
2359 "Information to record when a task moves to the DONE state.
2361 Possible values are:
2363 nil Don't add anything, just change the keyword
2364 time Add a time stamp to the task
2365 note Prompt for a note and add it with template `org-log-note-headings'
2367 This option can also be set with on a per-file-basis with
2369 #+STARTUP: nologdone
2370 #+STARTUP: logdone
2371 #+STARTUP: lognotedone
2373 You can have local logging settings for a subtree by setting the LOGGING
2374 property to one or more of these keywords."
2375 :group 'org-todo
2376 :group 'org-progress
2377 :type '(choice
2378 (const :tag "No logging" nil)
2379 (const :tag "Record CLOSED timestamp" time)
2380 (const :tag "Record CLOSED timestamp with note." note)))
2382 ;; Normalize old uses of org-log-done.
2383 (cond
2384 ((eq org-log-done t) (setq org-log-done 'time))
2385 ((and (listp org-log-done) (memq 'done org-log-done))
2386 (setq org-log-done 'note)))
2388 (defcustom org-log-reschedule nil
2389 "Information to record when the scheduling date of a tasks is modified.
2391 Possible values are:
2393 nil Don't add anything, just change the date
2394 time Add a time stamp to the task
2395 note Prompt for a note and add it with template `org-log-note-headings'
2397 This option can also be set with on a per-file-basis with
2399 #+STARTUP: nologreschedule
2400 #+STARTUP: logreschedule
2401 #+STARTUP: lognotereschedule"
2402 :group 'org-todo
2403 :group 'org-progress
2404 :type '(choice
2405 (const :tag "No logging" nil)
2406 (const :tag "Record timestamp" time)
2407 (const :tag "Record timestamp with note." note)))
2409 (defcustom org-log-redeadline nil
2410 "Information to record when the deadline date of a tasks is modified.
2412 Possible values are:
2414 nil Don't add anything, just change the date
2415 time Add a time stamp to the task
2416 note Prompt for a note and add it with template `org-log-note-headings'
2418 This option can also be set with on a per-file-basis with
2420 #+STARTUP: nologredeadline
2421 #+STARTUP: logredeadline
2422 #+STARTUP: lognoteredeadline
2424 You can have local logging settings for a subtree by setting the LOGGING
2425 property to one or more of these keywords."
2426 :group 'org-todo
2427 :group 'org-progress
2428 :type '(choice
2429 (const :tag "No logging" nil)
2430 (const :tag "Record timestamp" time)
2431 (const :tag "Record timestamp with note." note)))
2433 (defcustom org-log-note-clock-out nil
2434 "Non-nil means record a note when clocking out of an item.
2435 This can also be configured on a per-file basis by adding one of
2436 the following lines anywhere in the buffer:
2438 #+STARTUP: lognoteclock-out
2439 #+STARTUP: nolognoteclock-out"
2440 :group 'org-todo
2441 :group 'org-progress
2442 :type 'boolean)
2444 (defcustom org-log-done-with-time t
2445 "Non-nil means the CLOSED time stamp will contain date and time.
2446 When nil, only the date will be recorded."
2447 :group 'org-progress
2448 :type 'boolean)
2450 (defcustom org-log-note-headings
2451 '((done . "CLOSING NOTE %t")
2452 (state . "State %-12s from %-12S %t")
2453 (note . "Note taken on %t")
2454 (reschedule . "Rescheduled from %S on %t")
2455 (delschedule . "Not scheduled, was %S on %t")
2456 (redeadline . "New deadline from %S on %t")
2457 (deldeadline . "Removed deadline, was %S on %t")
2458 (refile . "Refiled on %t")
2459 (clock-out . ""))
2460 "Headings for notes added to entries.
2461 The value is an alist, with the car being a symbol indicating the note
2462 context, and the cdr is the heading to be used. The heading may also be the
2463 empty string.
2464 %t in the heading will be replaced by a time stamp.
2465 %T will be an active time stamp instead the default inactive one
2466 %d will be replaced by a short-format time stamp.
2467 %D will be replaced by an active short-format time stamp.
2468 %s will be replaced by the new TODO state, in double quotes.
2469 %S will be replaced by the old TODO state, in double quotes.
2470 %u will be replaced by the user name.
2471 %U will be replaced by the full user name.
2473 In fact, it is not a good idea to change the `state' entry, because
2474 agenda log mode depends on the format of these entries."
2475 :group 'org-todo
2476 :group 'org-progress
2477 :type '(list :greedy t
2478 (cons (const :tag "Heading when closing an item" done) string)
2479 (cons (const :tag
2480 "Heading when changing todo state (todo sequence only)"
2481 state) string)
2482 (cons (const :tag "Heading when just taking a note" note) string)
2483 (cons (const :tag "Heading when clocking out" clock-out) string)
2484 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2485 (cons (const :tag "Heading when rescheduling" reschedule) string)
2486 (cons (const :tag "Heading when changing deadline" redeadline) string)
2487 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2488 (cons (const :tag "Heading when refiling" refile) string)))
2490 (unless (assq 'note org-log-note-headings)
2491 (push '(note . "%t") org-log-note-headings))
2493 (defcustom org-log-into-drawer nil
2494 "Non-nil means insert state change notes and time stamps into a drawer.
2495 When nil, state changes notes will be inserted after the headline and
2496 any scheduling and clock lines, but not inside a drawer.
2498 The value of this variable should be the name of the drawer to use.
2499 LOGBOOK is proposed as the default drawer for this purpose, you can
2500 also set this to a string to define the drawer of your choice.
2502 A value of t is also allowed, representing \"LOGBOOK\".
2504 A value of t or nil can also be set with on a per-file-basis with
2506 #+STARTUP: logdrawer
2507 #+STARTUP: nologdrawer
2509 If this variable is set, `org-log-state-notes-insert-after-drawers'
2510 will be ignored.
2512 You can set the property LOG_INTO_DRAWER to overrule this setting for
2513 a subtree."
2514 :group 'org-todo
2515 :group 'org-progress
2516 :type '(choice
2517 (const :tag "Not into a drawer" nil)
2518 (const :tag "LOGBOOK" t)
2519 (string :tag "Other")))
2521 (if (fboundp 'defvaralias)
2522 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2524 (defun org-log-into-drawer ()
2525 "Return the value of `org-log-into-drawer', but let properties overrule.
2526 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2527 used instead of the default value."
2528 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2529 (cond
2530 ((not p) org-log-into-drawer)
2531 ((equal p "nil") nil)
2532 ((equal p "t") "LOGBOOK")
2533 (t p))))
2535 (defcustom org-log-state-notes-insert-after-drawers nil
2536 "Non-nil means insert state change notes after any drawers in entry.
2537 Only the drawers that *immediately* follow the headline and the
2538 deadline/scheduled line are skipped.
2539 When nil, insert notes right after the heading and perhaps the line
2540 with deadline/scheduling if present.
2542 This variable will have no effect if `org-log-into-drawer' is
2543 set."
2544 :group 'org-todo
2545 :group 'org-progress
2546 :type 'boolean)
2548 (defcustom org-log-states-order-reversed t
2549 "Non-nil means the latest state note will be directly after heading.
2550 When nil, the state change notes will be ordered according to time.
2552 This option can also be set with on a per-file-basis with
2554 #+STARTUP: logstatesreversed
2555 #+STARTUP: nologstatesreversed"
2556 :group 'org-todo
2557 :group 'org-progress
2558 :type 'boolean)
2560 (defcustom org-todo-repeat-to-state nil
2561 "The TODO state to which a repeater should return the repeating task.
2562 By default this is the first task in a TODO sequence, or the previous state
2563 in a TODO_TYP set. But you can specify another task here.
2564 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2565 :group 'org-todo
2566 :version "24.1"
2567 :type '(choice (const :tag "Head of sequence" nil)
2568 (string :tag "Specific state")))
2570 (defcustom org-log-repeat 'time
2571 "Non-nil means record moving through the DONE state when triggering repeat.
2572 An auto-repeating task is immediately switched back to TODO when
2573 marked DONE. If you are not logging state changes (by adding \"@\"
2574 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2575 record a closing note, there will be no record of the task moving
2576 through DONE. This variable forces taking a note anyway.
2578 nil Don't force a record
2579 time Record a time stamp
2580 note Prompt for a note and add it with template `org-log-note-headings'
2582 This option can also be set with on a per-file-basis with
2584 #+STARTUP: nologrepeat
2585 #+STARTUP: logrepeat
2586 #+STARTUP: lognoterepeat
2588 You can have local logging settings for a subtree by setting the LOGGING
2589 property to one or more of these keywords."
2590 :group 'org-todo
2591 :group 'org-progress
2592 :type '(choice
2593 (const :tag "Don't force a record" nil)
2594 (const :tag "Force recording the DONE state" time)
2595 (const :tag "Force recording a note with the DONE state" note)))
2598 (defgroup org-priorities nil
2599 "Priorities in Org-mode."
2600 :tag "Org Priorities"
2601 :group 'org-todo)
2603 (defcustom org-enable-priority-commands t
2604 "Non-nil means priority commands are active.
2605 When nil, these commands will be disabled, so that you never accidentally
2606 set a priority."
2607 :group 'org-priorities
2608 :type 'boolean)
2610 (defcustom org-highest-priority ?A
2611 "The highest priority of TODO items. A character like ?A, ?B etc.
2612 Must have a smaller ASCII number than `org-lowest-priority'."
2613 :group 'org-priorities
2614 :type 'character)
2616 (defcustom org-lowest-priority ?C
2617 "The lowest priority of TODO items. A character like ?A, ?B etc.
2618 Must have a larger ASCII number than `org-highest-priority'."
2619 :group 'org-priorities
2620 :type 'character)
2622 (defcustom org-default-priority ?B
2623 "The default priority of TODO items.
2624 This is the priority an item gets if no explicit priority is given.
2625 When starting to cycle on an empty priority the first step in the cycle
2626 depends on `org-priority-start-cycle-with-default'. The resulting first
2627 step priority must not exceed the range from `org-highest-priority' to
2628 `org-lowest-priority' which means that `org-default-priority' has to be
2629 in this range exclusive or inclusive the range boundaries. Else the
2630 first step refuses to set the default and the second will fall back
2631 to (depending on the command used) the highest or lowest priority."
2632 :group 'org-priorities
2633 :type 'character)
2635 (defcustom org-priority-start-cycle-with-default t
2636 "Non-nil means start with default priority when starting to cycle.
2637 When this is nil, the first step in the cycle will be (depending on the
2638 command used) one higher or lower than the default priority.
2639 See also `org-default-priority'."
2640 :group 'org-priorities
2641 :type 'boolean)
2643 (defcustom org-get-priority-function nil
2644 "Function to extract the priority from a string.
2645 The string is normally the headline. If this is nil Org computes the
2646 priority from the priority cookie like [#A] in the headline. It returns
2647 an integer, increasing by 1000 for each priority level.
2648 The user can set a different function here, which should take a string
2649 as an argument and return the numeric priority."
2650 :group 'org-priorities
2651 :version "24.1"
2652 :type 'function)
2654 (defgroup org-time nil
2655 "Options concerning time stamps and deadlines in Org-mode."
2656 :tag "Org Time"
2657 :group 'org)
2659 (defcustom org-insert-labeled-timestamps-at-point nil
2660 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2661 When nil, these labeled time stamps are forces into the second line of an
2662 entry, just after the headline. When scheduling from the global TODO list,
2663 the time stamp will always be forced into the second line."
2664 :group 'org-time
2665 :type 'boolean)
2667 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2668 "Formats for `format-time-string' which are used for time stamps.
2669 It is not recommended to change this constant.")
2671 (defcustom org-time-stamp-rounding-minutes '(0 5)
2672 "Number of minutes to round time stamps to.
2673 These are two values, the first applies when first creating a time stamp.
2674 The second applies when changing it with the commands `S-up' and `S-down'.
2675 When changing the time stamp, this means that it will change in steps
2676 of N minutes, as given by the second value.
2678 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2679 numbers should be factors of 60, so for example 5, 10, 15.
2681 When this is larger than 1, you can still force an exact time stamp by using
2682 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2683 and by using a prefix arg to `S-up/down' to specify the exact number
2684 of minutes to shift."
2685 :group 'org-time
2686 :get #'(lambda (var) ; Make sure both elements are there
2687 (if (integerp (default-value var))
2688 (list (default-value var) 5)
2689 (default-value var)))
2690 :type '(list
2691 (integer :tag "when inserting times")
2692 (integer :tag "when modifying times")))
2694 ;; Normalize old customizations of this variable.
2695 (when (integerp org-time-stamp-rounding-minutes)
2696 (setq org-time-stamp-rounding-minutes
2697 (list org-time-stamp-rounding-minutes
2698 org-time-stamp-rounding-minutes)))
2700 (defcustom org-display-custom-times nil
2701 "Non-nil means overlay custom formats over all time stamps.
2702 The formats are defined through the variable `org-time-stamp-custom-formats'.
2703 To turn this on on a per-file basis, insert anywhere in the file:
2704 #+STARTUP: customtime"
2705 :group 'org-time
2706 :set 'set-default
2707 :type 'sexp)
2708 (make-variable-buffer-local 'org-display-custom-times)
2710 (defcustom org-time-stamp-custom-formats
2711 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2712 "Custom formats for time stamps. See `format-time-string' for the syntax.
2713 These are overlaid over the default ISO format if the variable
2714 `org-display-custom-times' is set. Time like %H:%M should be at the
2715 end of the second format. The custom formats are also honored by export
2716 commands, if custom time display is turned on at the time of export."
2717 :group 'org-time
2718 :type 'sexp)
2720 (defun org-time-stamp-format (&optional long inactive)
2721 "Get the right format for a time string."
2722 (let ((f (if long (cdr org-time-stamp-formats)
2723 (car org-time-stamp-formats))))
2724 (if inactive
2725 (concat "[" (substring f 1 -1) "]")
2726 f)))
2728 (defcustom org-time-clocksum-format
2729 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2730 "The format string used when creating CLOCKSUM lines.
2731 This is also used when Org mode generates a time duration.
2733 The value can be a single format string containing two
2734 %-sequences, which will be filled with the number of hours and
2735 minutes in that order.
2737 Alternatively, the value can be a plist associating any of the
2738 keys :years, :months, :weeks, :days, :hours or :minutes with
2739 format strings. The time duration is formatted using only the
2740 time components that are needed and concatenating the results.
2741 If a time unit in absent, it falls back to the next smallest
2742 unit.
2744 The keys :require-years, :require-months, :require-days,
2745 :require-weeks, :require-hours, :require-minutes are also
2746 meaningful. A non-nil value for these keys indicates that the
2747 corresponding time component should always be included, even if
2748 its value is 0.
2751 For example,
2753 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2754 :require-minutes t)
2756 means durations longer than a day will be expressed in days,
2757 hours and minutes, and durations less than a day will always be
2758 expressed in hours and minutes (even for durations less than an
2759 hour).
2761 The value
2763 \(:days \"%dd\" :minutes \"%dm\")
2765 means durations longer than a day will be expressed in days and
2766 minutes, and durations less than a day will be expressed entirely
2767 in minutes (even for durations longer than an hour)."
2768 :group 'org-time
2769 :type '(choice (string :tag "Format string")
2770 (set :tag "Plist"
2771 (group :inline t (const :tag "Years" :years)
2772 (string :tag "Format string"))
2773 (group :inline t
2774 (const :tag "Always show years" :require-years)
2775 (const t))
2776 (group :inline t (const :tag "Months" :months)
2777 (string :tag "Format string"))
2778 (group :inline t
2779 (const :tag "Always show months" :require-months)
2780 (const t))
2781 (group :inline t (const :tag "Weeks" :weeks)
2782 (string :tag "Format string"))
2783 (group :inline t
2784 (const :tag "Always show weeks" :require-weeks)
2785 (const t))
2786 (group :inline t (const :tag "Days" :days)
2787 (string :tag "Format string"))
2788 (group :inline t
2789 (const :tag "Always show days" :require-days)
2790 (const t))
2791 (group :inline t (const :tag "Hours" :hours)
2792 (string :tag "Format string"))
2793 (group :inline t
2794 (const :tag "Always show hours" :require-hours)
2795 (const t))
2796 (group :inline t (const :tag "Minutes" :minutes)
2797 (string :tag "Format string"))
2798 (group :inline t
2799 (const :tag "Always show minutes" :require-minutes)
2800 (const t)))))
2802 (defcustom org-time-clocksum-use-fractional nil
2803 "If non-nil, \\[org-clock-display] uses fractional times.
2804 org-mode generates a time duration."
2805 :group 'org-time
2806 :type 'boolean)
2808 (defcustom org-time-clocksum-fractional-format "%.2f"
2809 "The format string used when creating CLOCKSUM lines,
2810 or when Org mode generates a time duration, if
2811 `org-time-clocksum-use-fractional' is enabled.
2813 The value can be a single format string containing one
2814 %-sequence, which will be filled with the number of hours as
2815 a float.
2817 Alternatively, the value can be a plist associating any of the
2818 keys :years, :months, :weeks, :days, :hours or :minutes with
2819 a format string. The time duration is formatted using the
2820 largest time unit which gives a non-zero integer part. If all
2821 specified formats have zero integer part, the smallest time unit
2822 is used."
2823 :group 'org-time
2824 :type '(choice (string :tag "Format string")
2825 (set (group :inline t (const :tag "Years" :years)
2826 (string :tag "Format string"))
2827 (group :inline t (const :tag "Months" :months)
2828 (string :tag "Format string"))
2829 (group :inline t (const :tag "Weeks" :weeks)
2830 (string :tag "Format string"))
2831 (group :inline t (const :tag "Days" :days)
2832 (string :tag "Format string"))
2833 (group :inline t (const :tag "Hours" :hours)
2834 (string :tag "Format string"))
2835 (group :inline t (const :tag "Minutes" :minutes)
2836 (string :tag "Format string")))))
2838 (defcustom org-deadline-warning-days 14
2839 "No. of days before expiration during which a deadline becomes active.
2840 This variable governs the display in sparse trees and in the agenda.
2841 When 0 or negative, it means use this number (the absolute value of it)
2842 even if a deadline has a different individual lead time specified.
2844 Custom commands can set this variable in the options section."
2845 :group 'org-time
2846 :group 'org-agenda-daily/weekly
2847 :type 'integer)
2849 (defcustom org-read-date-prefer-future t
2850 "Non-nil means assume future for incomplete date input from user.
2851 This affects the following situations:
2852 1. The user gives a month but not a year.
2853 For example, if it is April and you enter \"feb 2\", this will be read
2854 as Feb 2, *next* year. \"May 5\", however, will be this year.
2855 2. The user gives a day, but no month.
2856 For example, if today is the 15th, and you enter \"3\", Org-mode will
2857 read this as the third of *next* month. However, if you enter \"17\",
2858 it will be considered as *this* month.
2860 If you set this variable to the symbol `time', then also the following
2861 will work:
2863 3. If the user gives a time.
2864 If the time is before now, it will be interpreted as tomorrow.
2866 Currently none of this works for ISO week specifications.
2868 When this option is nil, the current day, month and year will always be
2869 used as defaults.
2871 See also `org-agenda-jump-prefer-future'."
2872 :group 'org-time
2873 :type '(choice
2874 (const :tag "Never" nil)
2875 (const :tag "Check month and day" t)
2876 (const :tag "Check month, day, and time" time)))
2878 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2879 "Should the agenda jump command prefer the future for incomplete dates?
2880 The default is to do the same as configured in `org-read-date-prefer-future'.
2881 But you can also set a deviating value here.
2882 This may t or nil, or the symbol `org-read-date-prefer-future'."
2883 :group 'org-agenda
2884 :group 'org-time
2885 :version "24.1"
2886 :type '(choice
2887 (const :tag "Use org-read-date-prefer-future"
2888 org-read-date-prefer-future)
2889 (const :tag "Never" nil)
2890 (const :tag "Always" t)))
2892 (defcustom org-read-date-force-compatible-dates t
2893 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2895 Depending on the system Emacs is running on, certain dates cannot
2896 be represented with the type used internally to represent time.
2897 Dates between 1970-1-1 and 2038-1-1 can always be represented
2898 correctly. Some systems allow for earlier dates, some for later,
2899 some for both. One way to find out it to insert any date into an
2900 Org buffer, putting the cursor on the year and hitting S-up and
2901 S-down to test the range.
2903 When this variable is set to t, the date/time prompt will not let
2904 you specify dates outside the 1970-2037 range, so it is certain that
2905 these dates will work in whatever version of Emacs you are
2906 running, and also that you can move a file from one Emacs implementation
2907 to another. WHenever Org is forcing the year for you, it will display
2908 a message and beep.
2910 When this variable is nil, Org will check if the date is
2911 representable in the specific Emacs implementation you are using.
2912 If not, it will force a year, usually the current year, and beep
2913 to remind you. Currently this setting is not recommended because
2914 the likelihood that you will open your Org files in an Emacs that
2915 has limited date range is not negligible.
2917 A workaround for this problem is to use diary sexp dates for time
2918 stamps outside of this range."
2919 :group 'org-time
2920 :version "24.1"
2921 :type 'boolean)
2923 (defcustom org-read-date-display-live t
2924 "Non-nil means display current interpretation of date prompt live.
2925 This display will be in an overlay, in the minibuffer."
2926 :group 'org-time
2927 :type 'boolean)
2929 (defcustom org-read-date-popup-calendar t
2930 "Non-nil means pop up a calendar when prompting for a date.
2931 In the calendar, the date can be selected with mouse-1. However, the
2932 minibuffer will also be active, and you can simply enter the date as well.
2933 When nil, only the minibuffer will be available."
2934 :group 'org-time
2935 :type 'boolean)
2936 (if (fboundp 'defvaralias)
2937 (defvaralias 'org-popup-calendar-for-date-prompt
2938 'org-read-date-popup-calendar))
2940 (defcustom org-read-date-minibuffer-setup-hook nil
2941 "Hook to be used to set up keys for the date/time interface.
2942 Add key definitions to `minibuffer-local-map', which will be a temporary
2943 copy."
2944 :group 'org-time
2945 :type 'hook)
2947 (defcustom org-extend-today-until 0
2948 "The hour when your day really ends. Must be an integer.
2949 This has influence for the following applications:
2950 - When switching the agenda to \"today\". It it is still earlier than
2951 the time given here, the day recognized as TODAY is actually yesterday.
2952 - When a date is read from the user and it is still before the time given
2953 here, the current date and time will be assumed to be yesterday, 23:59.
2954 Also, timestamps inserted in capture templates follow this rule.
2956 IMPORTANT: This is a feature whose implementation is and likely will
2957 remain incomplete. Really, it is only here because past midnight seems to
2958 be the favorite working time of John Wiegley :-)"
2959 :group 'org-time
2960 :type 'integer)
2962 (defcustom org-use-effective-time nil
2963 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2964 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2965 \"effective time\" of any timestamps between midnight and 8am will be
2966 23:59 of the previous day."
2967 :group 'org-time
2968 :version "24.1"
2969 :type 'boolean)
2971 (defcustom org-use-last-clock-out-time-as-effective-time nil
2972 "When non-nil, use the last clock out time for `org-todo'.
2973 Note that this option has precedence over the combined use of
2974 `org-use-effective-time' and `org-extend-today-until'."
2975 :group 'org-time
2976 ;; :version "24.3"
2977 :type 'boolean)
2979 (defcustom org-edit-timestamp-down-means-later nil
2980 "Non-nil means S-down will increase the time in a time stamp.
2981 When nil, S-up will increase."
2982 :group 'org-time
2983 :type 'boolean)
2985 (defcustom org-calendar-follow-timestamp-change t
2986 "Non-nil means make the calendar window follow timestamp changes.
2987 When a timestamp is modified and the calendar window is visible, it will be
2988 moved to the new date."
2989 :group 'org-time
2990 :type 'boolean)
2992 (defgroup org-tags nil
2993 "Options concerning tags in Org-mode."
2994 :tag "Org Tags"
2995 :group 'org)
2997 (defcustom org-tag-alist nil
2998 "List of tags allowed in Org-mode files.
2999 When this list is nil, Org-mode will base TAG input on what is already in the
3000 buffer.
3001 The value of this variable is an alist, the car of each entry must be a
3002 keyword as a string, the cdr may be a character that is used to select
3003 that tag through the fast-tag-selection interface.
3004 See the manual for details."
3005 :group 'org-tags
3006 :type '(repeat
3007 (choice
3008 (cons (string :tag "Tag name")
3009 (character :tag "Access char"))
3010 (list :tag "Start radio group"
3011 (const :startgroup)
3012 (option (string :tag "Group description")))
3013 (list :tag "End radio group"
3014 (const :endgroup)
3015 (option (string :tag "Group description")))
3016 (const :tag "New line" (:newline)))))
3018 (defcustom org-tag-persistent-alist nil
3019 "List of tags that will always appear in all Org-mode files.
3020 This is in addition to any in buffer settings or customizations
3021 of `org-tag-alist'.
3022 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3023 The value of this variable is an alist, the car of each entry must be a
3024 keyword as a string, the cdr may be a character that is used to select
3025 that tag through the fast-tag-selection interface.
3026 See the manual for details.
3027 To disable these tags on a per-file basis, insert anywhere in the file:
3028 #+STARTUP: noptag"
3029 :group 'org-tags
3030 :type '(repeat
3031 (choice
3032 (cons (string :tag "Tag name")
3033 (character :tag "Access char"))
3034 (const :tag "Start radio group" (:startgroup))
3035 (const :tag "End radio group" (:endgroup))
3036 (const :tag "New line" (:newline)))))
3038 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3039 "If non-nil, always offer completion for all tags of all agenda files.
3040 Instead of customizing this variable directly, you might want to
3041 set it locally for capture buffers, because there no list of
3042 tags in that file can be created dynamically (there are none).
3044 (add-hook 'org-capture-mode-hook
3045 (lambda ()
3046 (set (make-local-variable
3047 'org-complete-tags-always-offer-all-agenda-tags)
3048 t)))"
3049 :group 'org-tags
3050 :version "24.1"
3051 :type 'boolean)
3053 (defvar org-file-tags nil
3054 "List of tags that can be inherited by all entries in the file.
3055 The tags will be inherited if the variable `org-use-tag-inheritance'
3056 says they should be.
3057 This variable is populated from #+FILETAGS lines.")
3059 (defcustom org-use-fast-tag-selection 'auto
3060 "Non-nil means use fast tag selection scheme.
3061 This is a special interface to select and deselect tags with single keys.
3062 When nil, fast selection is never used.
3063 When the symbol `auto', fast selection is used if and only if selection
3064 characters for tags have been configured, either through the variable
3065 `org-tag-alist' or through a #+TAGS line in the buffer.
3066 When t, fast selection is always used and selection keys are assigned
3067 automatically if necessary."
3068 :group 'org-tags
3069 :type '(choice
3070 (const :tag "Always" t)
3071 (const :tag "Never" nil)
3072 (const :tag "When selection characters are configured" 'auto)))
3074 (defcustom org-fast-tag-selection-single-key nil
3075 "Non-nil means fast tag selection exits after first change.
3076 When nil, you have to press RET to exit it.
3077 During fast tag selection, you can toggle this flag with `C-c'.
3078 This variable can also have the value `expert'. In this case, the window
3079 displaying the tags menu is not even shown, until you press C-c again."
3080 :group 'org-tags
3081 :type '(choice
3082 (const :tag "No" nil)
3083 (const :tag "Yes" t)
3084 (const :tag "Expert" expert)))
3086 (defvar org-fast-tag-selection-include-todo nil
3087 "Non-nil means fast tags selection interface will also offer TODO states.
3088 This is an undocumented feature, you should not rely on it.")
3090 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3091 "The column to which tags should be indented in a headline.
3092 If this number is positive, it specifies the column. If it is negative,
3093 it means that the tags should be flushright to that column. For example,
3094 -80 works well for a normal 80 character screen.
3095 When 0, place tags directly after headline text, with only one space in
3096 between."
3097 :group 'org-tags
3098 :type 'integer)
3100 (defcustom org-auto-align-tags t
3101 "Non-nil keeps tags aligned when modifying headlines.
3102 Some operations (i.e. demoting) change the length of a headline and
3103 therefore shift the tags around. With this option turned on, after
3104 each such operation the tags are again aligned to `org-tags-column'."
3105 :group 'org-tags
3106 :type 'boolean)
3108 (defcustom org-use-tag-inheritance t
3109 "Non-nil means tags in levels apply also for sublevels.
3110 When nil, only the tags directly given in a specific line apply there.
3111 This may also be a list of tags that should be inherited, or a regexp that
3112 matches tags that should be inherited. Additional control is possible
3113 with the variable `org-tags-exclude-from-inheritance' which gives an
3114 explicit list of tags to be excluded from inheritance., even if the value of
3115 `org-use-tag-inheritance' would select it for inheritance.
3117 If this option is t, a match early-on in a tree can lead to a large
3118 number of matches in the subtree when constructing the agenda or creating
3119 a sparse tree. If you only want to see the first match in a tree during
3120 a search, check out the variable `org-tags-match-list-sublevels'."
3121 :group 'org-tags
3122 :type '(choice
3123 (const :tag "Not" nil)
3124 (const :tag "Always" t)
3125 (repeat :tag "Specific tags" (string :tag "Tag"))
3126 (regexp :tag "Tags matched by regexp")))
3128 (defcustom org-tags-exclude-from-inheritance nil
3129 "List of tags that should never be inherited.
3130 This is a way to exclude a few tags from inheritance. For way to do
3131 the opposite, to actively allow inheritance for selected tags,
3132 see the variable `org-use-tag-inheritance'."
3133 :group 'org-tags
3134 :type '(repeat (string :tag "Tag")))
3136 (defun org-tag-inherit-p (tag)
3137 "Check if TAG is one that should be inherited."
3138 (cond
3139 ((member tag org-tags-exclude-from-inheritance) nil)
3140 ((eq org-use-tag-inheritance t) t)
3141 ((not org-use-tag-inheritance) nil)
3142 ((stringp org-use-tag-inheritance)
3143 (string-match org-use-tag-inheritance tag))
3144 ((listp org-use-tag-inheritance)
3145 (member tag org-use-tag-inheritance))
3146 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3148 (defcustom org-tags-match-list-sublevels t
3149 "Non-nil means list also sublevels of headlines matching a search.
3150 This variable applies to tags/property searches, and also to stuck
3151 projects because this search is based on a tags match as well.
3153 When set to the symbol `indented', sublevels are indented with
3154 leading dots.
3156 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3157 the sublevels of a headline matching a tag search often also match
3158 the same search. Listing all of them can create very long lists.
3159 Setting this variable to nil causes subtrees of a match to be skipped.
3161 This variable is semi-obsolete and probably should always be true. It
3162 is better to limit inheritance to certain tags using the variables
3163 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3164 :group 'org-tags
3165 :type '(choice
3166 (const :tag "No, don't list them" nil)
3167 (const :tag "Yes, do list them" t)
3168 (const :tag "List them, indented with leading dots" indented)))
3170 (defcustom org-tags-sort-function nil
3171 "When set, tags are sorted using this function as a comparator."
3172 :group 'org-tags
3173 :type '(choice
3174 (const :tag "No sorting" nil)
3175 (const :tag "Alphabetical" string<)
3176 (const :tag "Reverse alphabetical" string>)
3177 (function :tag "Custom function" nil)))
3179 (defvar org-tags-history nil
3180 "History of minibuffer reads for tags.")
3181 (defvar org-last-tags-completion-table nil
3182 "The last used completion table for tags.")
3183 (defvar org-after-tags-change-hook nil
3184 "Hook that is run after the tags in a line have changed.")
3186 (defgroup org-properties nil
3187 "Options concerning properties in Org-mode."
3188 :tag "Org Properties"
3189 :group 'org)
3191 (defcustom org-property-format "%-10s %s"
3192 "How property key/value pairs should be formatted by `indent-line'.
3193 When `indent-line' hits a property definition, it will format the line
3194 according to this format, mainly to make sure that the values are
3195 lined-up with respect to each other."
3196 :group 'org-properties
3197 :type 'string)
3199 (defcustom org-properties-postprocess-alist nil
3200 "Alist of properties and functions to adjust inserted values.
3201 Elements of this alist must be of the form
3203 ([string] [function])
3205 where [string] must be a property name and [function] must be a
3206 lambda expression: this lambda expression must take one argument,
3207 the value to adjust, and return the new value as a string.
3209 For example, this element will allow the property \"Remaining\"
3210 to be updated wrt the relation between the \"Effort\" property
3211 and the clock summary:
3213 ((\"Remaining\" (lambda(value)
3214 (let ((clocksum (org-clock-sum-current-item))
3215 (effort (org-duration-string-to-minutes
3216 (org-entry-get (point) \"Effort\"))))
3217 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3218 :group 'org-properties
3219 :version "24.1"
3220 :type '(alist :key-type (string :tag "Property")
3221 :value-type (function :tag "Function")))
3223 (defcustom org-use-property-inheritance nil
3224 "Non-nil means properties apply also for sublevels.
3226 This setting is chiefly used during property searches. Turning it on can
3227 cause significant overhead when doing a search, which is why it is not
3228 on by default.
3230 When nil, only the properties directly given in the current entry count.
3231 When t, every property is inherited. The value may also be a list of
3232 properties that should have inheritance, or a regular expression matching
3233 properties that should be inherited.
3235 However, note that some special properties use inheritance under special
3236 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3237 and the properties ending in \"_ALL\" when they are used as descriptor
3238 for valid values of a property.
3240 Note for programmers:
3241 When querying an entry with `org-entry-get', you can control if inheritance
3242 should be used. By default, `org-entry-get' looks only at the local
3243 properties. You can request inheritance by setting the inherit argument
3244 to t (to force inheritance) or to `selective' (to respect the setting
3245 in this variable)."
3246 :group 'org-properties
3247 :type '(choice
3248 (const :tag "Not" nil)
3249 (const :tag "Always" t)
3250 (repeat :tag "Specific properties" (string :tag "Property"))
3251 (regexp :tag "Properties matched by regexp")))
3253 (defun org-property-inherit-p (property)
3254 "Check if PROPERTY is one that should be inherited."
3255 (cond
3256 ((eq org-use-property-inheritance t) t)
3257 ((not org-use-property-inheritance) nil)
3258 ((stringp org-use-property-inheritance)
3259 (string-match org-use-property-inheritance property))
3260 ((listp org-use-property-inheritance)
3261 (member property org-use-property-inheritance))
3262 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3264 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3265 "The default column format, if no other format has been defined.
3266 This variable can be set on the per-file basis by inserting a line
3268 #+COLUMNS: %25ITEM ....."
3269 :group 'org-properties
3270 :type 'string)
3272 (defcustom org-columns-ellipses ".."
3273 "The ellipses to be used when a field in column view is truncated.
3274 When this is the empty string, as many characters as possible are shown,
3275 but then there will be no visual indication that the field has been truncated.
3276 When this is a string of length N, the last N characters of a truncated
3277 field are replaced by this string. If the column is narrower than the
3278 ellipses string, only part of the ellipses string will be shown."
3279 :group 'org-properties
3280 :type 'string)
3282 (defcustom org-columns-modify-value-for-display-function nil
3283 "Function that modifies values for display in column view.
3284 For example, it can be used to cut out a certain part from a time stamp.
3285 The function must take 2 arguments:
3287 column-title The title of the column (*not* the property name)
3288 value The value that should be modified.
3290 The function should return the value that should be displayed,
3291 or nil if the normal value should be used."
3292 :group 'org-properties
3293 :type 'function)
3295 (defcustom org-effort-property "Effort"
3296 "The property that is being used to keep track of effort estimates.
3297 Effort estimates given in this property need to have the format H:MM."
3298 :group 'org-properties
3299 :group 'org-progress
3300 :type '(string :tag "Property"))
3302 (defconst org-global-properties-fixed
3303 '(("VISIBILITY_ALL" . "folded children content all")
3304 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3305 "List of property/value pairs that can be inherited by any entry.
3307 These are fixed values, for the preset properties. The user variable
3308 that can be used to add to this list is `org-global-properties'.
3310 The entries in this list are cons cells where the car is a property
3311 name and cdr is a string with the value. If the value represents
3312 multiple items like an \"_ALL\" property, separate the items by
3313 spaces.")
3315 (defcustom org-global-properties nil
3316 "List of property/value pairs that can be inherited by any entry.
3318 This list will be combined with the constant `org-global-properties-fixed'.
3320 The entries in this list are cons cells where the car is a property
3321 name and cdr is a string with the value.
3323 You can set buffer-local values for the same purpose in the variable
3324 `org-file-properties' this by adding lines like
3326 #+PROPERTY: NAME VALUE"
3327 :group 'org-properties
3328 :type '(repeat
3329 (cons (string :tag "Property")
3330 (string :tag "Value"))))
3332 (defvar org-file-properties nil
3333 "List of property/value pairs that can be inherited by any entry.
3334 Valid for the current buffer.
3335 This variable is populated from #+PROPERTY lines.")
3336 (make-variable-buffer-local 'org-file-properties)
3338 (defgroup org-agenda nil
3339 "Options concerning agenda views in Org-mode."
3340 :tag "Org Agenda"
3341 :group 'org)
3343 (defvar org-category nil
3344 "Variable used by org files to set a category for agenda display.
3345 Such files should use a file variable to set it, for example
3347 # -*- mode: org; org-category: \"ELisp\"
3349 or contain a special line
3351 #+CATEGORY: ELisp
3353 If the file does not specify a category, then file's base name
3354 is used instead.")
3355 (make-variable-buffer-local 'org-category)
3356 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3358 (defcustom org-agenda-files nil
3359 "The files to be used for agenda display.
3360 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3361 \\[org-remove-file]. You can also use customize to edit the list.
3363 If an entry is a directory, all files in that directory that are matched by
3364 `org-agenda-file-regexp' will be part of the file list.
3366 If the value of the variable is not a list but a single file name, then
3367 the list of agenda files is actually stored and maintained in that file, one
3368 agenda file per line. In this file paths can be given relative to
3369 `org-directory'. Tilde expansion and environment variable substitution
3370 are also made."
3371 :group 'org-agenda
3372 :type '(choice
3373 (repeat :tag "List of files and directories" file)
3374 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3376 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3377 "Regular expression to match files for `org-agenda-files'.
3378 If any element in the list in that variable contains a directory instead
3379 of a normal file, all files in that directory that are matched by this
3380 regular expression will be included."
3381 :group 'org-agenda
3382 :type 'regexp)
3384 (defcustom org-agenda-text-search-extra-files nil
3385 "List of extra files to be searched by text search commands.
3386 These files will be search in addition to the agenda files by the
3387 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3388 Note that these files will only be searched for text search commands,
3389 not for the other agenda views like todo lists, tag searches or the weekly
3390 agenda. This variable is intended to list notes and possibly archive files
3391 that should also be searched by these two commands.
3392 In fact, if the first element in the list is the symbol `agenda-archives',
3393 than all archive files of all agenda files will be added to the search
3394 scope."
3395 :group 'org-agenda
3396 :type '(set :greedy t
3397 (const :tag "Agenda Archives" agenda-archives)
3398 (repeat :inline t (file))))
3400 (if (fboundp 'defvaralias)
3401 (defvaralias 'org-agenda-multi-occur-extra-files
3402 'org-agenda-text-search-extra-files))
3404 (defcustom org-agenda-skip-unavailable-files nil
3405 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3406 A nil value means to remove them, after a query, from the list."
3407 :group 'org-agenda
3408 :type 'boolean)
3410 (defcustom org-calendar-to-agenda-key [?c]
3411 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3412 The command `org-calendar-goto-agenda' will be bound to this key. The
3413 default is the character `c' because then `c' can be used to switch back and
3414 forth between agenda and calendar."
3415 :group 'org-agenda
3416 :type 'sexp)
3418 (defcustom org-calendar-insert-diary-entry-key [?i]
3419 "The key to be installed in `calendar-mode-map' for adding diary entries.
3420 This option is irrelevant until `org-agenda-diary-file' has been configured
3421 to point to an Org-mode file. When that is the case, the command
3422 `org-agenda-diary-entry' will be bound to the key given here, by default
3423 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3424 if you want to continue doing this, you need to change this to a different
3425 key."
3426 :group 'org-agenda
3427 :type 'sexp)
3429 (defcustom org-agenda-diary-file 'diary-file
3430 "File to which to add new entries with the `i' key in agenda and calendar.
3431 When this is the symbol `diary-file', the functionality in the Emacs
3432 calendar will be used to add entries to the `diary-file'. But when this
3433 points to a file, `org-agenda-diary-entry' will be used instead."
3434 :group 'org-agenda
3435 :type '(choice
3436 (const :tag "The standard Emacs diary file" diary-file)
3437 (file :tag "Special Org file diary entries")))
3439 (eval-after-load "calendar"
3440 '(progn
3441 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3442 'org-calendar-goto-agenda)
3443 (add-hook 'calendar-mode-hook
3444 (lambda ()
3445 (unless (eq org-agenda-diary-file 'diary-file)
3446 (define-key calendar-mode-map
3447 org-calendar-insert-diary-entry-key
3448 'org-agenda-diary-entry))))))
3450 (defgroup org-latex nil
3451 "Options for embedding LaTeX code into Org-mode."
3452 :tag "Org LaTeX"
3453 :group 'org)
3455 (defcustom org-format-latex-options
3456 '(:foreground default :background default :scale 1.0
3457 :html-foreground "Black" :html-background "Transparent"
3458 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3459 "Options for creating images from LaTeX fragments.
3460 This is a property list with the following properties:
3461 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3462 `default' means use the foreground of the default face.
3463 `auto' means use the foreground from the text face.
3464 :background the background color, or \"Transparent\".
3465 `default' means use the background of the default face.
3466 `auto' means use the background from the text face.
3467 :scale a scaling factor for the size of the images, to get more pixels
3468 :html-foreground, :html-background, :html-scale
3469 the same numbers for HTML export.
3470 :matchers a list indicating which matchers should be used to
3471 find LaTeX fragments. Valid members of this list are:
3472 \"begin\" find environments
3473 \"$1\" find single characters surrounded by $.$
3474 \"$\" find math expressions surrounded by $...$
3475 \"$$\" find math expressions surrounded by $$....$$
3476 \"\\(\" find math expressions surrounded by \\(...\\)
3477 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3478 :group 'org-latex
3479 :type 'plist)
3481 (defcustom org-format-latex-signal-error t
3482 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3483 When nil, just push out a message."
3484 :group 'org-latex
3485 :version "24.1"
3486 :type 'boolean)
3488 (defcustom org-latex-to-mathml-jar-file nil
3489 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3490 Use this to specify additional executable file say a jar file.
3492 When using MathToWeb as the converter, specify the full-path to
3493 your mathtoweb.jar file."
3494 :group 'org-latex
3495 :version "24.1"
3496 :type '(choice
3497 (const :tag "None" nil)
3498 (file :tag "JAR file" :must-match t)))
3500 (defcustom org-latex-to-mathml-convert-command nil
3501 "Command to convert LaTeX fragments to MathML.
3502 Replace format-specifiers in the command as noted below and use
3503 `shell-command' to convert LaTeX to MathML.
3504 %j: Executable file in fully expanded form as specified by
3505 `org-latex-to-mathml-jar-file'.
3506 %I: Input LaTeX file in fully expanded form
3507 %o: Output MathML file
3508 This command is used by `org-create-math-formula'.
3510 When using MathToWeb as the converter, set this to
3511 \"java -jar %j -unicode -force -df %o %I\"."
3512 :group 'org-latex
3513 :version "24.1"
3514 :type '(choice
3515 (const :tag "None" nil)
3516 (string :tag "\nShell command")))
3518 (defcustom org-latex-create-formula-image-program 'dvipng
3519 "Program to convert LaTeX fragments with.
3521 dvipng Process the LaTeX fragments to dvi file, then convert
3522 dvi files to png files using dvipng.
3523 This will also include processing of non-math environments.
3524 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3525 to convert pdf files to png files"
3526 :group 'org-latex
3527 :version "24.1"
3528 :type '(choice
3529 (const :tag "dvipng" dvipng)
3530 (const :tag "imagemagick" imagemagick)))
3532 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3533 "Path to store latex preview images.
3534 A relative path here creates many directories relative to the
3535 processed org files paths. An absolute path puts all preview
3536 images at the same place."
3537 :group 'org-latex
3538 :version "24.3"
3539 :type 'string)
3541 (defun org-format-latex-mathml-available-p ()
3542 "Return t if `org-latex-to-mathml-convert-command' is usable."
3543 (save-match-data
3544 (when (and (boundp 'org-latex-to-mathml-convert-command)
3545 org-latex-to-mathml-convert-command)
3546 (let ((executable (car (split-string
3547 org-latex-to-mathml-convert-command))))
3548 (when (executable-find executable)
3549 (if (string-match
3550 "%j" org-latex-to-mathml-convert-command)
3551 (file-readable-p org-latex-to-mathml-jar-file)
3552 t))))))
3554 (defcustom org-format-latex-header "\\documentclass{article}
3555 \\usepackage[usenames]{color}
3556 \\usepackage{amsmath}
3557 \\usepackage[mathscr]{eucal}
3558 \\pagestyle{empty} % do not remove
3559 \[PACKAGES]
3560 \[DEFAULT-PACKAGES]
3561 % The settings below are copied from fullpage.sty
3562 \\setlength{\\textwidth}{\\paperwidth}
3563 \\addtolength{\\textwidth}{-3cm}
3564 \\setlength{\\oddsidemargin}{1.5cm}
3565 \\addtolength{\\oddsidemargin}{-2.54cm}
3566 \\setlength{\\evensidemargin}{\\oddsidemargin}
3567 \\setlength{\\textheight}{\\paperheight}
3568 \\addtolength{\\textheight}{-\\headheight}
3569 \\addtolength{\\textheight}{-\\headsep}
3570 \\addtolength{\\textheight}{-\\footskip}
3571 \\addtolength{\\textheight}{-3cm}
3572 \\setlength{\\topmargin}{1.5cm}
3573 \\addtolength{\\topmargin}{-2.54cm}"
3574 "The document header used for processing LaTeX fragments.
3575 It is imperative that this header make sure that no page number
3576 appears on the page. The package defined in the variables
3577 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3578 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3579 will be appended."
3580 :group 'org-latex
3581 :type 'string)
3583 (defvar org-format-latex-header-extra nil)
3585 (defun org-set-packages-alist (var val)
3586 "Set the packages alist and make sure it has 3 elements per entry."
3587 (set var (mapcar (lambda (x)
3588 (if (and (consp x) (= (length x) 2))
3589 (list (car x) (nth 1 x) t)
3591 val)))
3593 (defun org-get-packages-alist (var)
3595 "Get the packages alist and make sure it has 3 elements per entry."
3596 (mapcar (lambda (x)
3597 (if (and (consp x) (= (length x) 2))
3598 (list (car x) (nth 1 x) t)
3600 (default-value var)))
3602 ;; The following variables are defined here because is it also used
3603 ;; when formatting latex fragments. Originally it was part of the
3604 ;; LaTeX exporter, which is why the name includes "export".
3605 (defcustom org-export-latex-default-packages-alist
3606 '(("AUTO" "inputenc" t)
3607 ("T1" "fontenc" t)
3608 ("" "fixltx2e" nil)
3609 ("" "graphicx" t)
3610 ("" "longtable" nil)
3611 ("" "float" nil)
3612 ("" "wrapfig" nil)
3613 ("" "soul" t)
3614 ("" "textcomp" t)
3615 ("" "marvosym" t)
3616 ("" "wasysym" t)
3617 ("" "latexsym" t)
3618 ("" "amssymb" t)
3619 ("" "hyperref" nil)
3620 "\\tolerance=1000"
3622 "Alist of default packages to be inserted in the header.
3623 Change this only if one of the packages here causes an incompatibility
3624 with another package you are using.
3625 The packages in this list are needed by one part or another of Org-mode
3626 to function properly.
3628 - inputenc, fontenc: for basic font and character selection
3629 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3630 for interpreting the entities in `org-entities'. You can skip some of these
3631 packages if you don't use any of the symbols in it.
3632 - graphicx: for including images
3633 - float, wrapfig: for figure placement
3634 - longtable: for long tables
3635 - hyperref: for cross references
3637 Therefore you should not modify this variable unless you know what you
3638 are doing. The one reason to change it anyway is that you might be loading
3639 some other package that conflicts with one of the default packages.
3640 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3641 If SNIPPET-FLAG is t, the package also needs to be included when
3642 compiling LaTeX snippets into images for inclusion into HTML."
3643 :group 'org-export-latex
3644 :set 'org-set-packages-alist
3645 :get 'org-get-packages-alist
3646 :version "24.1"
3647 :type '(repeat
3648 (choice
3649 (list :tag "options/package pair"
3650 (string :tag "options")
3651 (string :tag "package")
3652 (boolean :tag "Snippet"))
3653 (string :tag "A line of LaTeX"))))
3655 (defcustom org-export-latex-packages-alist nil
3656 "Alist of packages to be inserted in every LaTeX header.
3657 These will be inserted after `org-export-latex-default-packages-alist'.
3658 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3659 SNIPPET-FLAG, when t, indicates that this package is also needed when
3660 turning LaTeX snippets into images for inclusion into HTML.
3661 Make sure that you only list packages here which:
3662 - you want in every file
3663 - do not conflict with the default packages in
3664 `org-export-latex-default-packages-alist'
3665 - do not conflict with the setup in `org-format-latex-header'."
3666 :group 'org-export-latex
3667 :set 'org-set-packages-alist
3668 :get 'org-get-packages-alist
3669 :type '(repeat
3670 (choice
3671 (list :tag "options/package pair"
3672 (string :tag "options")
3673 (string :tag "package")
3674 (boolean :tag "Snippet"))
3675 (string :tag "A line of LaTeX"))))
3678 (defgroup org-appearance nil
3679 "Settings for Org-mode appearance."
3680 :tag "Org Appearance"
3681 :group 'org)
3683 (defcustom org-level-color-stars-only nil
3684 "Non-nil means fontify only the stars in each headline.
3685 When nil, the entire headline is fontified.
3686 Changing it requires restart of `font-lock-mode' to become effective
3687 also in regions already fontified."
3688 :group 'org-appearance
3689 :type 'boolean)
3691 (defcustom org-hide-leading-stars nil
3692 "Non-nil means hide the first N-1 stars in a headline.
3693 This works by using the face `org-hide' for these stars. This
3694 face is white for a light background, and black for a dark
3695 background. You may have to customize the face `org-hide' to
3696 make this work.
3697 Changing it requires restart of `font-lock-mode' to become effective
3698 also in regions already fontified.
3699 You may also set this on a per-file basis by adding one of the following
3700 lines to the buffer:
3702 #+STARTUP: hidestars
3703 #+STARTUP: showstars"
3704 :group 'org-appearance
3705 :type 'boolean)
3707 (defcustom org-hidden-keywords nil
3708 "List of symbols corresponding to keywords to be hidden the org buffer.
3709 For example, a value '(title) for this list will make the document's title
3710 appear in the buffer without the initial #+TITLE: keyword."
3711 :group 'org-appearance
3712 :version "24.1"
3713 :type '(set (const :tag "#+AUTHOR" author)
3714 (const :tag "#+DATE" date)
3715 (const :tag "#+EMAIL" email)
3716 (const :tag "#+TITLE" title)))
3718 (defcustom org-custom-properties nil
3719 "List of properties (as strings) with a special meaning.
3720 The default use of these custom properties is to let the user
3721 hide them with `org-toggle-custom-properties-visibility'."
3722 :group 'org-properties
3723 :group 'org-appearance
3724 :version "24.3"
3725 :type '(repeat (string :tag "Property Name")))
3727 (defcustom org-fontify-done-headline nil
3728 "Non-nil means change the face of a headline if it is marked DONE.
3729 Normally, only the TODO/DONE keyword indicates the state of a headline.
3730 When this is non-nil, the headline after the keyword is set to the
3731 `org-headline-done' as an additional indication."
3732 :group 'org-appearance
3733 :type 'boolean)
3735 (defcustom org-fontify-emphasized-text t
3736 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3737 Changing this variable requires a restart of Emacs to take effect."
3738 :group 'org-appearance
3739 :type 'boolean)
3741 (defcustom org-fontify-whole-heading-line nil
3742 "Non-nil means fontify the whole line for headings.
3743 This is useful when setting a background color for the
3744 org-level-* faces."
3745 :group 'org-appearance
3746 :type 'boolean)
3748 (defcustom org-highlight-latex-fragments-and-specials nil
3749 "Non-nil means fontify what is treated specially by the exporters."
3750 :group 'org-appearance
3751 :type 'boolean)
3753 (defcustom org-hide-emphasis-markers nil
3754 "Non-nil mean font-lock should hide the emphasis marker characters."
3755 :group 'org-appearance
3756 :type 'boolean)
3758 (defcustom org-pretty-entities nil
3759 "Non-nil means show entities as UTF8 characters.
3760 When nil, the \\name form remains in the buffer."
3761 :group 'org-appearance
3762 :version "24.1"
3763 :type 'boolean)
3765 (defcustom org-pretty-entities-include-sub-superscripts t
3766 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3767 :group 'org-appearance
3768 :version "24.1"
3769 :type 'boolean)
3771 (defvar org-emph-re nil
3772 "Regular expression for matching emphasis.
3773 After a match, the match groups contain these elements:
3774 0 The match of the full regular expression, including the characters
3775 before and after the proper match
3776 1 The character before the proper match, or empty at beginning of line
3777 2 The proper match, including the leading and trailing markers
3778 3 The leading marker like * or /, indicating the type of highlighting
3779 4 The text between the emphasis markers, not including the markers
3780 5 The character after the match, empty at the end of a line")
3781 (defvar org-verbatim-re nil
3782 "Regular expression for matching verbatim text.")
3783 (defvar org-emphasis-regexp-components) ; defined just below
3784 (defvar org-emphasis-alist) ; defined just below
3785 (defun org-set-emph-re (var val)
3786 "Set variable and compute the emphasis regular expression."
3787 (set var val)
3788 (when (and (boundp 'org-emphasis-alist)
3789 (boundp 'org-emphasis-regexp-components)
3790 org-emphasis-alist org-emphasis-regexp-components)
3791 (let* ((e org-emphasis-regexp-components)
3792 (pre (car e))
3793 (post (nth 1 e))
3794 (border (nth 2 e))
3795 (body (nth 3 e))
3796 (nl (nth 4 e))
3797 (body1 (concat body "*?"))
3798 (markers (mapconcat 'car org-emphasis-alist ""))
3799 (vmarkers (mapconcat
3800 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3801 org-emphasis-alist "")))
3802 ;; make sure special characters appear at the right position in the class
3803 (if (string-match "\\^" markers)
3804 (setq markers (concat (replace-match "" t t markers) "^")))
3805 (if (string-match "-" markers)
3806 (setq markers (concat (replace-match "" t t markers) "-")))
3807 (if (string-match "\\^" vmarkers)
3808 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3809 (if (string-match "-" vmarkers)
3810 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3811 (if (> nl 0)
3812 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3813 (int-to-string nl) "\\}")))
3814 ;; Make the regexp
3815 (setq org-emph-re
3816 (concat "\\([" pre "]\\|^\\)"
3817 "\\("
3818 "\\([" markers "]\\)"
3819 "\\("
3820 "[^" border "]\\|"
3821 "[^" border "]"
3822 body1
3823 "[^" border "]"
3824 "\\)"
3825 "\\3\\)"
3826 "\\([" post "]\\|$\\)"))
3827 (setq org-verbatim-re
3828 (concat "\\([" pre "]\\|^\\)"
3829 "\\("
3830 "\\([" vmarkers "]\\)"
3831 "\\("
3832 "[^" border "]\\|"
3833 "[^" border "]"
3834 body1
3835 "[^" border "]"
3836 "\\)"
3837 "\\3\\)"
3838 "\\([" post "]\\|$\\)")))))
3840 (defcustom org-emphasis-regexp-components
3841 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3842 "Components used to build the regular expression for emphasis.
3843 This is a list with five entries. Terminology: In an emphasis string
3844 like \" *strong word* \", we call the initial space PREMATCH, the final
3845 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3846 and \"trong wor\" is the body. The different components in this variable
3847 specify what is allowed/forbidden in each part:
3849 pre Chars allowed as prematch. Beginning of line will be allowed too.
3850 post Chars allowed as postmatch. End of line will be allowed too.
3851 border The chars *forbidden* as border characters.
3852 body-regexp A regexp like \".\" to match a body character. Don't use
3853 non-shy groups here, and don't allow newline here.
3854 newline The maximum number of newlines allowed in an emphasis exp.
3856 Use customize to modify this, or restart Emacs after changing it."
3857 :group 'org-appearance
3858 :set 'org-set-emph-re
3859 :type '(list
3860 (sexp :tag "Allowed chars in pre ")
3861 (sexp :tag "Allowed chars in post ")
3862 (sexp :tag "Forbidden chars in border ")
3863 (sexp :tag "Regexp for body ")
3864 (integer :tag "number of newlines allowed")
3865 (option (boolean :tag "Please ignore this button"))))
3867 (defcustom org-emphasis-alist
3868 `(("*" bold "<b>" "</b>")
3869 ("/" italic "<i>" "</i>")
3870 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3871 ("=" org-code "<code>" "</code>" verbatim)
3872 ("~" org-verbatim "<code>" "</code>" verbatim)
3873 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3874 "<del>" "</del>")
3876 "Special syntax for emphasized text.
3877 Text starting and ending with a special character will be emphasized, for
3878 example *bold*, _underlined_ and /italic/. This variable sets the marker
3879 characters, the face to be used by font-lock for highlighting in Org-mode
3880 Emacs buffers, and the HTML tags to be used for this.
3881 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3882 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3883 Use customize to modify this, or restart Emacs after changing it."
3884 :group 'org-appearance
3885 :set 'org-set-emph-re
3886 :type '(repeat
3887 (list
3888 (string :tag "Marker character")
3889 (choice
3890 (face :tag "Font-lock-face")
3891 (plist :tag "Face property list"))
3892 (string :tag "HTML start tag")
3893 (string :tag "HTML end tag")
3894 (option (const verbatim)))))
3896 (defvar org-syntax-table
3897 (let ((st (make-syntax-table)))
3898 (mapc (lambda(c) (modify-syntax-entry
3899 (string-to-char (car c)) "w p" st))
3900 org-emphasis-alist)
3901 st))
3903 (defvar org-protecting-blocks
3904 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3905 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3906 This is needed for font-lock setup.")
3908 ;;; Miscellaneous options
3910 (defgroup org-completion nil
3911 "Completion in Org-mode."
3912 :tag "Org Completion"
3913 :group 'org)
3915 (defcustom org-completion-use-ido nil
3916 "Non-nil means use ido completion wherever possible.
3917 Note that `ido-mode' must be active for this variable to be relevant.
3918 If you decide to turn this variable on, you might well want to turn off
3919 `org-outline-path-complete-in-steps'.
3920 See also `org-completion-use-iswitchb'."
3921 :group 'org-completion
3922 :type 'boolean)
3924 (defcustom org-completion-use-iswitchb nil
3925 "Non-nil means use iswitchb completion wherever possible.
3926 Note that `iswitchb-mode' must be active for this variable to be relevant.
3927 If you decide to turn this variable on, you might well want to turn off
3928 `org-outline-path-complete-in-steps'.
3929 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3930 :group 'org-completion
3931 :type 'boolean)
3933 (defcustom org-completion-fallback-command 'hippie-expand
3934 "The expansion command called by \\[pcomplete] in normal context.
3935 Normal means, no org-mode-specific context."
3936 :group 'org-completion
3937 :type 'function)
3939 ;;; Functions and variables from their packages
3940 ;; Declared here to avoid compiler warnings
3942 ;; XEmacs only
3943 (defvar outline-mode-menu-heading)
3944 (defvar outline-mode-menu-show)
3945 (defvar outline-mode-menu-hide)
3946 (defvar zmacs-regions) ; XEmacs regions
3948 ;; Emacs only
3949 (defvar mark-active)
3951 ;; Various packages
3952 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3953 (declare-function calendar-forward-day "cal-move" (arg))
3954 (declare-function calendar-goto-date "cal-move" (date))
3955 (declare-function calendar-goto-today "cal-move" ())
3956 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3957 (defvar calc-embedded-close-formula)
3958 (defvar calc-embedded-open-formula)
3959 (declare-function cdlatex-tab "ext:cdlatex" ())
3960 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3961 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3962 (defvar font-lock-unfontify-region-function)
3963 (declare-function iswitchb-read-buffer "iswitchb"
3964 (prompt &optional default require-match start matches-set))
3965 (defvar iswitchb-temp-buflist)
3966 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3967 (defvar org-agenda-tags-todo-honor-ignore-options)
3968 (declare-function org-agenda-skip "org-agenda" ())
3969 (declare-function
3970 org-agenda-format-item "org-agenda"
3971 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3972 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3973 (declare-function org-agenda-change-all-lines "org-agenda"
3974 (newhead hdmarker &optional fixface just-this))
3975 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3976 (declare-function org-agenda-maybe-redo "org-agenda" ())
3977 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3978 (beg end))
3979 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3980 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3981 "org-agenda" (&optional end))
3982 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3983 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3984 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3985 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3986 (declare-function org-indent-mode "org-indent" (&optional arg))
3987 (declare-function parse-time-string "parse-time" (string))
3988 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3989 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3990 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3991 (defvar remember-data-file)
3992 (defvar texmathp-why)
3993 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3994 (declare-function table--at-cell-p "table" (position &optional object at-column))
3996 (defvar org-latex-regexps)
3998 ;;; Autoload and prepare some org modules
4000 ;; Some table stuff that needs to be defined here, because it is used
4001 ;; by the functions setting up org-mode or checking for table context.
4003 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4004 "Detect an org-type or table-type table.")
4005 (defconst org-table-line-regexp "^[ \t]*|"
4006 "Detect an org-type table line.")
4007 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4008 "Detect an org-type table line.")
4009 (defconst org-table-hline-regexp "^[ \t]*|-"
4010 "Detect an org-type table hline.")
4011 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4012 "Detect a table-type table hline.")
4013 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4014 "Detect the first line outside a table when searching from within it.
4015 This works for both table types.")
4017 ;; Autoload the functions in org-table.el that are needed by functions here.
4019 (eval-and-compile
4020 (org-autoload "org-table"
4021 '(org-table-begin org-table-blank-field org-table-end)))
4023 ;;;###autoload
4024 (defun turn-on-orgtbl ()
4025 "Unconditionally turn on `orgtbl-mode'."
4026 (require 'org-table)
4027 (orgtbl-mode 1))
4029 (defun org-at-table-p (&optional table-type)
4030 "Return t if the cursor is inside an org-type table.
4031 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4032 (if org-enable-table-editor
4033 (save-excursion
4034 (beginning-of-line 1)
4035 (looking-at (if table-type org-table-any-line-regexp
4036 org-table-line-regexp)))
4037 nil))
4038 (defsubst org-table-p () (org-at-table-p))
4040 (defun org-at-table.el-p ()
4041 "Return t if and only if we are at a table.el table."
4042 (and (org-at-table-p 'any)
4043 (save-excursion
4044 (goto-char (org-table-begin 'any))
4045 (looking-at org-table1-hline-regexp))))
4046 (defun org-table-recognize-table.el ()
4047 "If there is a table.el table nearby, recognize it and move into it."
4048 (if org-table-tab-recognizes-table.el
4049 (if (org-at-table.el-p)
4050 (progn
4051 (beginning-of-line 1)
4052 (if (looking-at org-table-dataline-regexp)
4054 (if (looking-at org-table1-hline-regexp)
4055 (progn
4056 (beginning-of-line 2)
4057 (if (looking-at org-table-any-border-regexp)
4058 (beginning-of-line -1)))))
4059 (if (re-search-forward "|" (org-table-end t) t)
4060 (progn
4061 (require 'table)
4062 (if (table--at-cell-p (point))
4064 (message "recognizing table.el table...")
4065 (table-recognize-table)
4066 (message "recognizing table.el table...done")))
4067 (error "This should not happen"))
4069 nil)
4070 nil))
4072 (defun org-at-table-hline-p ()
4073 "Return t if the cursor is inside a hline in a table."
4074 (if org-enable-table-editor
4075 (save-excursion
4076 (beginning-of-line 1)
4077 (looking-at org-table-hline-regexp))
4078 nil))
4080 (defvar org-table-clean-did-remove-column nil)
4082 (defun org-table-map-tables (function &optional quietly)
4083 "Apply FUNCTION to the start of all tables in the buffer."
4084 (save-excursion
4085 (save-restriction
4086 (widen)
4087 (goto-char (point-min))
4088 (while (re-search-forward org-table-any-line-regexp nil t)
4089 (unless quietly
4090 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4091 (beginning-of-line 1)
4092 (when (and (looking-at org-table-line-regexp)
4093 ;; Exclude tables in src/example/verbatim/clocktable blocks
4094 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4095 (save-excursion (funcall function))
4096 (or (looking-at org-table-line-regexp)
4097 (forward-char 1)))
4098 (re-search-forward org-table-any-border-regexp nil 1))))
4099 (unless quietly (message "Mapping tables: done")))
4101 ;; Declare and autoload functions from org-exp.el & Co
4103 (declare-function org-default-export-plist "org-exp")
4104 (declare-function org-infile-export-plist "org-exp")
4105 (declare-function org-get-current-options "org-exp")
4107 ;; Declare and autoload functions from org-agenda.el
4109 (eval-and-compile
4110 (org-autoload "org-agenda"
4111 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4113 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4114 (declare-function org-clock-update-mode-line "org-clock" ())
4115 (declare-function org-resolve-clocks "org-clock"
4116 (&optional also-non-dangling-p prompt last-valid))
4117 (defvar org-clock-start-time)
4118 (defvar org-clock-marker (make-marker)
4119 "Marker recording the last clock-in.")
4120 (defvar org-clock-hd-marker (make-marker)
4121 "Marker recording the last clock-in, but the headline position.")
4122 (defvar org-clock-heading ""
4123 "The heading of the current clock entry.")
4124 (defun org-clock-is-active ()
4125 "Return non-nil if clock is currently running.
4126 The return value is actually the clock marker."
4127 (marker-buffer org-clock-marker))
4129 (eval-and-compile
4130 (org-autoload "org-clock" '(org-clock-remove-overlays
4131 org-clock-update-time-maybe
4132 org-clocktable-shift)))
4134 (defun org-check-running-clock ()
4135 "Check if the current buffer contains the running clock.
4136 If yes, offer to stop it and to save the buffer with the changes."
4137 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4138 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4139 (buffer-name))))
4140 (org-clock-out)
4141 (when (y-or-n-p "Save changed buffer?")
4142 (save-buffer))))
4144 (defun org-clocktable-try-shift (dir n)
4145 "Check if this line starts a clock table, if yes, shift the time block."
4146 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4147 (org-clocktable-shift dir n)))
4149 ;;;###autoload
4150 (defun org-clock-persistence-insinuate ()
4151 "Set up hooks for clock persistence."
4152 (require 'org-clock)
4153 (add-hook 'org-mode-hook 'org-clock-load)
4154 (add-hook 'kill-emacs-hook 'org-clock-save))
4156 ;; Define the variable already here, to make sure we have it.
4157 (defvar org-indent-mode nil
4158 "Non-nil if Org-Indent mode is enabled.
4159 Use the command `org-indent-mode' to change this variable.")
4161 ;; Autoload archiving code
4162 ;; The stuff that is needed for cycling and tags has to be defined here.
4164 (defgroup org-archive nil
4165 "Options concerning archiving in Org-mode."
4166 :tag "Org Archive"
4167 :group 'org-structure)
4169 (defcustom org-archive-location "%s_archive::"
4170 "The location where subtrees should be archived.
4172 The value of this variable is a string, consisting of two parts,
4173 separated by a double-colon. The first part is a filename and
4174 the second part is a headline.
4176 When the filename is omitted, archiving happens in the same file.
4177 %s in the filename will be replaced by the current file
4178 name (without the directory part). Archiving to a different file
4179 is useful to keep archived entries from contributing to the
4180 Org-mode Agenda.
4182 The archived entries will be filed as subtrees of the specified
4183 headline. When the headline is omitted, the subtrees are simply
4184 filed away at the end of the file, as top-level entries. Also in
4185 the heading you can use %s to represent the file name, this can be
4186 useful when using the same archive for a number of different files.
4188 Here are a few examples:
4189 \"%s_archive::\"
4190 If the current file is Projects.org, archive in file
4191 Projects.org_archive, as top-level trees. This is the default.
4193 \"::* Archived Tasks\"
4194 Archive in the current file, under the top-level headline
4195 \"* Archived Tasks\".
4197 \"~/org/archive.org::\"
4198 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4200 \"~/org/archive.org::* From %s\"
4201 Archive in file ~/org/archive.org (absolute path), under headlines
4202 \"From FILENAME\" where file name is the current file name.
4204 \"~/org/datetree.org::datetree/* Finished Tasks\"
4205 The \"datetree/\" string is special, signifying to archive
4206 items to the datetree. Items are placed in either the CLOSED
4207 date of the item, or the current date if there is no CLOSED date.
4208 The heading will be a subentry to the current date. There doesn't
4209 need to be a heading, but there always needs to be a slash after
4210 datetree. For example, to store archived items directly in the
4211 datetree, use \"~/org/datetree.org::datetree/\".
4213 \"basement::** Finished Tasks\"
4214 Archive in file ./basement (relative path), as level 3 trees
4215 below the level 2 heading \"** Finished Tasks\".
4217 You may set this option on a per-file basis by adding to the buffer a
4218 line like
4220 #+ARCHIVE: basement::** Finished Tasks
4222 You may also define it locally for a subtree by setting an ARCHIVE property
4223 in the entry. If such a property is found in an entry, or anywhere up
4224 the hierarchy, it will be used."
4225 :group 'org-archive
4226 :type 'string)
4228 (defcustom org-archive-tag "ARCHIVE"
4229 "The tag that marks a subtree as archived.
4230 An archived subtree does not open during visibility cycling, and does
4231 not contribute to the agenda listings.
4232 After changing this, font-lock must be restarted in the relevant buffers to
4233 get the proper fontification."
4234 :group 'org-archive
4235 :group 'org-keywords
4236 :type 'string)
4238 (defcustom org-agenda-skip-archived-trees t
4239 "Non-nil means the agenda will skip any items located in archived trees.
4240 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4241 variable is no longer recommended, you should leave it at the value t.
4242 Instead, use the key `v' to cycle the archives-mode in the agenda."
4243 :group 'org-archive
4244 :group 'org-agenda-skip
4245 :type 'boolean)
4247 (defcustom org-columns-skip-archived-trees t
4248 "Non-nil means ignore archived trees when creating column view."
4249 :group 'org-archive
4250 :group 'org-properties
4251 :type 'boolean)
4253 (defcustom org-cycle-open-archived-trees nil
4254 "Non-nil means `org-cycle' will open archived trees.
4255 An archived tree is a tree marked with the tag ARCHIVE.
4256 When nil, archived trees will stay folded. You can still open them with
4257 normal outline commands like `show-all', but not with the cycling commands."
4258 :group 'org-archive
4259 :group 'org-cycle
4260 :type 'boolean)
4262 (defcustom org-sparse-tree-open-archived-trees nil
4263 "Non-nil means sparse tree construction shows matches in archived trees.
4264 When nil, matches in these trees are highlighted, but the trees are kept in
4265 collapsed state."
4266 :group 'org-archive
4267 :group 'org-sparse-trees
4268 :type 'boolean)
4270 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4271 "The default date type when building a sparse tree.
4272 When this is nil, a date is a scheduled or a deadline timestamp.
4273 Otherwise, these types are allowed:
4275 all: all timestamps
4276 active: only active timestamps (<...>)
4277 inactive: only inactive timestamps (<...)
4278 scheduled: only scheduled timestamps
4279 deadline: only deadline timestamps"
4280 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4281 (const :tag "All timestamps" all)
4282 (const :tag "Only active timestamps" active)
4283 (const :tag "Only inactive timestamps" inactive)
4284 (const :tag "Only scheduled timestamps" scheduled)
4285 (const :tag "Only deadline timestamps" deadline))
4286 :version "24.3"
4287 :group 'org-sparse-trees)
4289 (defun org-cycle-hide-archived-subtrees (state)
4290 "Re-hide all archived subtrees after a visibility state change."
4291 (when (and (not org-cycle-open-archived-trees)
4292 (not (memq state '(overview folded))))
4293 (save-excursion
4294 (let* ((globalp (memq state '(contents all)))
4295 (beg (if globalp (point-min) (point)))
4296 (end (if globalp (point-max) (org-end-of-subtree t))))
4297 (org-hide-archived-subtrees beg end)
4298 (goto-char beg)
4299 (if (looking-at (concat ".*:" org-archive-tag ":"))
4300 (message "%s" (substitute-command-keys
4301 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4303 (defun org-force-cycle-archived ()
4304 "Cycle subtree even if it is archived."
4305 (interactive)
4306 (setq this-command 'org-cycle)
4307 (let ((org-cycle-open-archived-trees t))
4308 (call-interactively 'org-cycle)))
4310 (defun org-hide-archived-subtrees (beg end)
4311 "Re-hide all archived subtrees after a visibility state change."
4312 (save-excursion
4313 (let* ((re (concat ":" org-archive-tag ":")))
4314 (goto-char beg)
4315 (while (re-search-forward re end t)
4316 (when (org-at-heading-p)
4317 (org-flag-subtree t)
4318 (org-end-of-subtree t))))))
4320 (declare-function outline-end-of-heading "outline" ())
4321 (declare-function outline-flag-region "outline" (from to flag))
4322 (defun org-flag-subtree (flag)
4323 (save-excursion
4324 (org-back-to-heading t)
4325 (outline-end-of-heading)
4326 (outline-flag-region (point)
4327 (progn (org-end-of-subtree t) (point))
4328 flag)))
4330 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4332 (eval-and-compile
4333 (org-autoload "org-archive"
4334 '(org-add-archive-files)))
4336 ;; Autoload Column View Code
4338 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4339 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4340 (declare-function org-columns-compute "org-colview" (property))
4342 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4343 '(org-columns-number-to-string
4344 org-columns-get-format-and-top-level
4345 org-columns-compute
4346 org-columns-remove-overlays))
4348 ;; Autoload ID code
4350 (declare-function org-id-store-link "org-id")
4351 (declare-function org-id-locations-load "org-id")
4352 (declare-function org-id-locations-save "org-id")
4353 (defvar org-id-track-globally)
4354 (org-autoload "org-id"
4355 '(org-id-new
4356 org-id-copy
4357 org-id-get-with-outline-path-completion
4358 org-id-get-with-outline-drilling))
4360 ;;; Variables for pre-computed regular expressions, all buffer local
4362 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4363 "Matches first line of a hidden block.")
4364 (make-variable-buffer-local 'org-drawer-regexp)
4365 (defvar org-todo-regexp nil
4366 "Matches any of the TODO state keywords.")
4367 (make-variable-buffer-local 'org-todo-regexp)
4368 (defvar org-not-done-regexp nil
4369 "Matches any of the TODO state keywords except the last one.")
4370 (make-variable-buffer-local 'org-not-done-regexp)
4371 (defvar org-not-done-heading-regexp nil
4372 "Matches a TODO headline that is not done.")
4373 (make-variable-buffer-local 'org-not-done-regexp)
4374 (defvar org-todo-line-regexp nil
4375 "Matches a headline and puts TODO state into group 2 if present.")
4376 (make-variable-buffer-local 'org-todo-line-regexp)
4377 (defvar org-complex-heading-regexp nil
4378 "Matches a headline and puts everything into groups:
4379 group 1: the stars
4380 group 2: The todo keyword, maybe
4381 group 3: Priority cookie
4382 group 4: True headline
4383 group 5: Tags")
4384 (make-variable-buffer-local 'org-complex-heading-regexp)
4385 (defvar org-complex-heading-regexp-format nil
4386 "Printf format to make regexp to match an exact headline.
4387 This regexp will match the headline of any node which has the
4388 exact headline text that is put into the format, but may have any
4389 TODO state, priority and tags.")
4390 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4391 (defvar org-todo-line-tags-regexp nil
4392 "Matches a headline and puts TODO state into group 2 if present.
4393 Also put tags into group 4 if tags are present.")
4394 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4395 (defvar org-ds-keyword-length 12
4396 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4397 (make-variable-buffer-local 'org-ds-keyword-length)
4398 (defvar org-deadline-regexp nil
4399 "Matches the DEADLINE keyword.")
4400 (make-variable-buffer-local 'org-deadline-regexp)
4401 (defvar org-deadline-time-regexp nil
4402 "Matches the DEADLINE keyword together with a time stamp.")
4403 (make-variable-buffer-local 'org-deadline-time-regexp)
4404 (defvar org-deadline-line-regexp nil
4405 "Matches the DEADLINE keyword and the rest of the line.")
4406 (make-variable-buffer-local 'org-deadline-line-regexp)
4407 (defvar org-scheduled-regexp nil
4408 "Matches the SCHEDULED keyword.")
4409 (make-variable-buffer-local 'org-scheduled-regexp)
4410 (defvar org-scheduled-time-regexp nil
4411 "Matches the SCHEDULED keyword together with a time stamp.")
4412 (make-variable-buffer-local 'org-scheduled-time-regexp)
4413 (defvar org-closed-time-regexp nil
4414 "Matches the CLOSED keyword together with a time stamp.")
4415 (make-variable-buffer-local 'org-closed-time-regexp)
4417 (defvar org-keyword-time-regexp nil
4418 "Matches any of the 4 keywords, together with the time stamp.")
4419 (make-variable-buffer-local 'org-keyword-time-regexp)
4420 (defvar org-keyword-time-not-clock-regexp nil
4421 "Matches any of the 3 keywords, together with the time stamp.")
4422 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4423 (defvar org-maybe-keyword-time-regexp nil
4424 "Matches a timestamp, possibly preceded by a keyword.")
4425 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4426 (defvar org-all-time-keywords nil
4427 "List of time keywords.")
4428 (make-variable-buffer-local 'org-all-time-keywords)
4430 (defconst org-plain-time-of-day-regexp
4431 (concat
4432 "\\(\\<[012]?[0-9]"
4433 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4434 "\\(--?"
4435 "\\(\\<[012]?[0-9]"
4436 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4437 "\\)?")
4438 "Regular expression to match a plain time or time range.
4439 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4440 groups carry important information:
4441 0 the full match
4442 1 the first time, range or not
4443 8 the second time, if it is a range.")
4445 (defconst org-plain-time-extension-regexp
4446 (concat
4447 "\\(\\<[012]?[0-9]"
4448 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4449 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4450 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4451 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4452 groups carry important information:
4453 0 the full match
4454 7 hours of duration
4455 9 minutes of duration")
4457 (defconst org-stamp-time-of-day-regexp
4458 (concat
4459 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4460 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4461 "\\(--?"
4462 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4463 "Regular expression to match a timestamp time or time range.
4464 After a match, the following groups carry important information:
4465 0 the full match
4466 1 date plus weekday, for back referencing to make sure both times are on the same day
4467 2 the first time, range or not
4468 4 the second time, if it is a range.")
4470 (defconst org-startup-options
4471 '(("fold" org-startup-folded t)
4472 ("overview" org-startup-folded t)
4473 ("nofold" org-startup-folded nil)
4474 ("showall" org-startup-folded nil)
4475 ("showeverything" org-startup-folded showeverything)
4476 ("content" org-startup-folded content)
4477 ("indent" org-startup-indented t)
4478 ("noindent" org-startup-indented nil)
4479 ("hidestars" org-hide-leading-stars t)
4480 ("showstars" org-hide-leading-stars nil)
4481 ("odd" org-odd-levels-only t)
4482 ("oddeven" org-odd-levels-only nil)
4483 ("align" org-startup-align-all-tables t)
4484 ("noalign" org-startup-align-all-tables nil)
4485 ("inlineimages" org-startup-with-inline-images t)
4486 ("noinlineimages" org-startup-with-inline-images nil)
4487 ("customtime" org-display-custom-times t)
4488 ("logdone" org-log-done time)
4489 ("lognotedone" org-log-done note)
4490 ("nologdone" org-log-done nil)
4491 ("lognoteclock-out" org-log-note-clock-out t)
4492 ("nolognoteclock-out" org-log-note-clock-out nil)
4493 ("logrepeat" org-log-repeat state)
4494 ("lognoterepeat" org-log-repeat note)
4495 ("logdrawer" org-log-into-drawer t)
4496 ("nologdrawer" org-log-into-drawer nil)
4497 ("logstatesreversed" org-log-states-order-reversed t)
4498 ("nologstatesreversed" org-log-states-order-reversed nil)
4499 ("nologrepeat" org-log-repeat nil)
4500 ("logreschedule" org-log-reschedule time)
4501 ("lognotereschedule" org-log-reschedule note)
4502 ("nologreschedule" org-log-reschedule nil)
4503 ("logredeadline" org-log-redeadline time)
4504 ("lognoteredeadline" org-log-redeadline note)
4505 ("nologredeadline" org-log-redeadline nil)
4506 ("logrefile" org-log-refile time)
4507 ("lognoterefile" org-log-refile note)
4508 ("nologrefile" org-log-refile nil)
4509 ("fninline" org-footnote-define-inline t)
4510 ("nofninline" org-footnote-define-inline nil)
4511 ("fnlocal" org-footnote-section nil)
4512 ("fnauto" org-footnote-auto-label t)
4513 ("fnprompt" org-footnote-auto-label nil)
4514 ("fnconfirm" org-footnote-auto-label confirm)
4515 ("fnplain" org-footnote-auto-label plain)
4516 ("fnadjust" org-footnote-auto-adjust t)
4517 ("nofnadjust" org-footnote-auto-adjust nil)
4518 ("constcgs" constants-unit-system cgs)
4519 ("constSI" constants-unit-system SI)
4520 ("noptag" org-tag-persistent-alist nil)
4521 ("hideblocks" org-hide-block-startup t)
4522 ("nohideblocks" org-hide-block-startup nil)
4523 ("beamer" org-startup-with-beamer-mode t)
4524 ("entitiespretty" org-pretty-entities t)
4525 ("entitiesplain" org-pretty-entities nil))
4526 "Variable associated with STARTUP options for org-mode.
4527 Each element is a list of three items: the startup options (as written
4528 in the #+STARTUP line), the corresponding variable, and the value to set
4529 this variable to if the option is found. An optional forth element PUSH
4530 means to push this value onto the list in the variable.")
4532 (defun org-update-property-plist (key val props)
4533 "Update PROPS with KEY and VAL."
4534 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4535 (key (if appending (substring key 0 (- (length key) 1)) key))
4536 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4537 (previous (cdr (assoc key props))))
4538 (if appending
4539 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4540 (cons (cons key val) remainder))))
4542 (defconst org-block-regexp
4543 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4544 "Regular expression for hiding blocks.")
4545 (defconst org-heading-keyword-regexp-format
4546 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4547 "Printf format for a regexp matching an headline with some keyword.
4548 This regexp will match the headline of any node which has the
4549 exact keyword that is put into the format. The keyword isn't in
4550 any group by default, but the stars and the body are.")
4551 (defconst org-heading-keyword-maybe-regexp-format
4552 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4553 "Printf format for a regexp matching an headline, possibly with some keyword.
4554 This regexp can match any headline with the specified keyword, or
4555 without a keyword. The keyword isn't in any group by default,
4556 but the stars and the body are.")
4558 (defun org-set-regexps-and-options ()
4559 "Precompute regular expressions for current buffer."
4560 (when (derived-mode-p 'org-mode)
4561 (org-set-local 'org-todo-kwd-alist nil)
4562 (org-set-local 'org-todo-key-alist nil)
4563 (org-set-local 'org-todo-key-trigger nil)
4564 (org-set-local 'org-todo-keywords-1 nil)
4565 (org-set-local 'org-done-keywords nil)
4566 (org-set-local 'org-todo-heads nil)
4567 (org-set-local 'org-todo-sets nil)
4568 (org-set-local 'org-todo-log-states nil)
4569 (org-set-local 'org-file-properties nil)
4570 (org-set-local 'org-file-tags nil)
4571 (let ((re (org-make-options-regexp
4572 '("CATEGORY" "TODO" "COLUMNS"
4573 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4574 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4575 "OPTIONS")
4576 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4577 (splitre "[ \t]+")
4578 (scripts org-use-sub-superscripts)
4579 kwds kws0 kwsa key log value cat arch tags const links hw dws
4580 tail sep kws1 prio props ftags drawers beamer-p
4581 ext-setup-or-nil setup-contents (start 0))
4582 (save-excursion
4583 (save-restriction
4584 (widen)
4585 (goto-char (point-min))
4586 (while (or (and ext-setup-or-nil
4587 (string-match re ext-setup-or-nil start)
4588 (setq start (match-end 0)))
4589 (and (setq ext-setup-or-nil nil start 0)
4590 (re-search-forward re nil t)))
4591 (setq key (upcase (match-string 1 ext-setup-or-nil))
4592 value (org-match-string-no-properties 2 ext-setup-or-nil))
4593 (if (stringp value) (setq value (org-trim value)))
4594 (cond
4595 ((equal key "CATEGORY")
4596 (setq cat value))
4597 ((member key '("SEQ_TODO" "TODO"))
4598 (push (cons 'sequence (org-split-string value splitre)) kwds))
4599 ((equal key "TYP_TODO")
4600 (push (cons 'type (org-split-string value splitre)) kwds))
4601 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4602 ;; general TODO-like setup
4603 (push (cons (intern (downcase (match-string 1 key)))
4604 (org-split-string value splitre)) kwds))
4605 ((equal key "TAGS")
4606 (setq tags (append tags (if tags '("\\n") nil)
4607 (org-split-string value splitre))))
4608 ((equal key "COLUMNS")
4609 (org-set-local 'org-columns-default-format value))
4610 ((equal key "LINK")
4611 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4612 (push (cons (match-string 1 value)
4613 (org-trim (match-string 2 value)))
4614 links)))
4615 ((equal key "PRIORITIES")
4616 (setq prio (org-split-string value " +")))
4617 ((equal key "PROPERTY")
4618 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4619 (setq props (org-update-property-plist (match-string 1 value)
4620 (match-string 2 value)
4621 props))))
4622 ((equal key "FILETAGS")
4623 (when (string-match "\\S-" value)
4624 (setq ftags
4625 (append
4626 ftags
4627 (apply 'append
4628 (mapcar (lambda (x) (org-split-string x ":"))
4629 (org-split-string value)))))))
4630 ((equal key "DRAWERS")
4631 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4632 ((equal key "CONSTANTS")
4633 (setq const (append const (org-split-string value splitre))))
4634 ((equal key "STARTUP")
4635 (let ((opts (org-split-string value splitre))
4636 l var val)
4637 (while (setq l (pop opts))
4638 (when (setq l (assoc l org-startup-options))
4639 (setq var (nth 1 l) val (nth 2 l))
4640 (if (not (nth 3 l))
4641 (set (make-local-variable var) val)
4642 (if (not (listp (symbol-value var)))
4643 (set (make-local-variable var) nil))
4644 (set (make-local-variable var) (symbol-value var))
4645 (add-to-list var val))))))
4646 ((equal key "ARCHIVE")
4647 (setq arch value)
4648 (remove-text-properties 0 (length arch)
4649 '(face t fontified t) arch))
4650 ((equal key "LATEX_CLASS")
4651 (setq beamer-p (equal value "beamer")))
4652 ((equal key "OPTIONS")
4653 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4654 (setq scripts (read (match-string 2 value)))))
4655 ((equal key "SETUPFILE")
4656 (setq setup-contents (org-file-contents
4657 (expand-file-name
4658 (org-remove-double-quotes value))
4659 'noerror))
4660 (if (not ext-setup-or-nil)
4661 (setq ext-setup-or-nil setup-contents start 0)
4662 (setq ext-setup-or-nil
4663 (concat (substring ext-setup-or-nil 0 start)
4664 "\n" setup-contents "\n"
4665 (substring ext-setup-or-nil start)))))))
4666 ;; search for property blocks
4667 (goto-char (point-min))
4668 (while (re-search-forward org-block-regexp nil t)
4669 (when (equal "PROPERTY" (upcase (match-string 1)))
4670 (setq value (replace-regexp-in-string
4671 "[\n\r]" " " (match-string 4)))
4672 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4673 (setq props (org-update-property-plist (match-string 1 value)
4674 (match-string 2 value)
4675 props)))))))
4676 (org-set-local 'org-use-sub-superscripts scripts)
4677 (when cat
4678 (org-set-local 'org-category (intern cat))
4679 (push (cons "CATEGORY" cat) props))
4680 (when prio
4681 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4682 (setq prio (mapcar 'string-to-char prio))
4683 (org-set-local 'org-highest-priority (nth 0 prio))
4684 (org-set-local 'org-lowest-priority (nth 1 prio))
4685 (org-set-local 'org-default-priority (nth 2 prio)))
4686 (and props (org-set-local 'org-file-properties (nreverse props)))
4687 (and ftags (org-set-local 'org-file-tags
4688 (mapcar 'org-add-prop-inherited ftags)))
4689 (and drawers (org-set-local 'org-drawers drawers))
4690 (and arch (org-set-local 'org-archive-location arch))
4691 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4692 ;; Process the TODO keywords
4693 (unless kwds
4694 ;; Use the global values as if they had been given locally.
4695 (setq kwds (default-value 'org-todo-keywords))
4696 (if (stringp (car kwds))
4697 (setq kwds (list (cons org-todo-interpretation
4698 (default-value 'org-todo-keywords)))))
4699 (setq kwds (reverse kwds)))
4700 (setq kwds (nreverse kwds))
4701 (let (inter kws kw)
4702 (while (setq kws (pop kwds))
4703 (let ((kws (or
4704 (run-hook-with-args-until-success
4705 'org-todo-setup-filter-hook kws)
4706 kws)))
4707 (setq inter (pop kws) sep (member "|" kws)
4708 kws0 (delete "|" (copy-sequence kws))
4709 kwsa nil
4710 kws1 (mapcar
4711 (lambda (x)
4712 ;; 1 2
4713 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4714 (progn
4715 (setq kw (match-string 1 x)
4716 key (and (match-end 2) (match-string 2 x))
4717 log (org-extract-log-state-settings x))
4718 (push (cons kw (and key (string-to-char key))) kwsa)
4719 (and log (push log org-todo-log-states))
4721 (error "Invalid TODO keyword %s" x)))
4722 kws0)
4723 kwsa (if kwsa (append '((:startgroup))
4724 (nreverse kwsa)
4725 '((:endgroup))))
4726 hw (car kws1)
4727 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4728 tail (list inter hw (car dws) (org-last dws))))
4729 (add-to-list 'org-todo-heads hw 'append)
4730 (push kws1 org-todo-sets)
4731 (setq org-done-keywords (append org-done-keywords dws nil))
4732 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4733 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4734 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4735 (setq org-todo-sets (nreverse org-todo-sets)
4736 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4737 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4738 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4739 ;; Process the constants
4740 (when const
4741 (let (e cst)
4742 (while (setq e (pop const))
4743 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4744 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4745 (setq org-table-formula-constants-local cst)))
4747 ;; Process the tags.
4748 (when tags
4749 (let (e tgs)
4750 (while (setq e (pop tags))
4751 (cond
4752 ((equal e "{") (push '(:startgroup) tgs))
4753 ((equal e "}") (push '(:endgroup) tgs))
4754 ((equal e "\\n") (push '(:newline) tgs))
4755 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4756 (push (cons (match-string 1 e)
4757 (string-to-char (match-string 2 e)))
4758 tgs))
4759 (t (push (list e) tgs))))
4760 (org-set-local 'org-tag-alist nil)
4761 (while (setq e (pop tgs))
4762 (or (and (stringp (car e))
4763 (assoc (car e) org-tag-alist))
4764 (push e org-tag-alist)))))
4766 ;; Compute the regular expressions and other local variables.
4767 ;; Using `org-outline-regexp-bol' would complicate them much,
4768 ;; because of the fixed white space at the end of that string.
4769 (if (not org-done-keywords)
4770 (setq org-done-keywords (and org-todo-keywords-1
4771 (list (org-last org-todo-keywords-1)))))
4772 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4773 (length org-scheduled-string)
4774 (length org-clock-string)
4775 (length org-closed-string)))
4776 org-drawer-regexp
4777 (concat "^[ \t]*:\\("
4778 (mapconcat 'regexp-quote org-drawers "\\|")
4779 "\\):[ \t]*$")
4780 org-not-done-keywords
4781 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4782 org-todo-regexp
4783 (concat "\\("
4784 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4785 "\\)")
4786 org-not-done-regexp
4787 (concat "\\("
4788 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4789 "\\)")
4790 org-not-done-heading-regexp
4791 (format org-heading-keyword-regexp-format org-not-done-regexp)
4792 org-todo-line-regexp
4793 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4794 org-complex-heading-regexp
4795 (concat "^\\(\\*+\\)"
4796 "\\(?: +" org-todo-regexp "\\)?"
4797 "\\(?: +\\(\\[#.\\]\\)\\)?"
4798 "\\(?: +\\(.*?\\)\\)??"
4799 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4800 "[ \t]*$")
4801 org-complex-heading-regexp-format
4802 (concat "^\\(\\*+\\)"
4803 "\\(?: +" org-todo-regexp "\\)?"
4804 "\\(?: +\\(\\[#.\\]\\)\\)?"
4805 "\\(?: +"
4806 ;; Stats cookies can be stuck to body.
4807 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4808 "\\(%s\\)"
4809 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4810 "\\)"
4811 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4812 "[ \t]*$")
4813 org-todo-line-tags-regexp
4814 (concat "^\\(\\*+\\)"
4815 "\\(?: +" org-todo-regexp "\\)?"
4816 "\\(?: +\\(.*?\\)\\)??"
4817 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4818 "[ \t]*$")
4819 org-deadline-regexp (concat "\\<" org-deadline-string)
4820 org-deadline-time-regexp
4821 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4822 org-deadline-line-regexp
4823 (concat "\\<\\(" org-deadline-string "\\).*")
4824 org-scheduled-regexp
4825 (concat "\\<" org-scheduled-string)
4826 org-scheduled-time-regexp
4827 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4828 org-closed-time-regexp
4829 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4830 org-keyword-time-regexp
4831 (concat "\\<\\(" org-scheduled-string
4832 "\\|" org-deadline-string
4833 "\\|" org-closed-string
4834 "\\|" org-clock-string "\\)"
4835 " *[[<]\\([^]>]+\\)[]>]")
4836 org-keyword-time-not-clock-regexp
4837 (concat "\\<\\(" org-scheduled-string
4838 "\\|" org-deadline-string
4839 "\\|" org-closed-string
4840 "\\)"
4841 " *[[<]\\([^]>]+\\)[]>]")
4842 org-maybe-keyword-time-regexp
4843 (concat "\\(\\<\\(" org-scheduled-string
4844 "\\|" org-deadline-string
4845 "\\|" org-closed-string
4846 "\\|" org-clock-string "\\)\\)?"
4847 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4848 org-all-time-keywords
4849 (mapcar (lambda (w) (substring w 0 -1))
4850 (list org-scheduled-string org-deadline-string
4851 org-clock-string org-closed-string))
4853 (org-compute-latex-and-specials-regexp)
4854 (org-set-font-lock-defaults))))
4856 (defun org-file-contents (file &optional noerror)
4857 "Return the contents of FILE, as a string."
4858 (if (or (not file)
4859 (not (file-readable-p file)))
4860 (if noerror
4861 (progn
4862 (message "Cannot read file \"%s\"" file)
4863 (ding) (sit-for 2)
4865 (error "Cannot read file \"%s\"" file))
4866 (with-temp-buffer
4867 (insert-file-contents file)
4868 (buffer-string))))
4870 (defun org-extract-log-state-settings (x)
4871 "Extract the log state setting from a TODO keyword string.
4872 This will extract info from a string like \"WAIT(w@/!)\"."
4873 (let (kw key log1 log2)
4874 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4875 (setq kw (match-string 1 x)
4876 key (and (match-end 2) (match-string 2 x))
4877 log1 (and (match-end 3) (match-string 3 x))
4878 log2 (and (match-end 4) (match-string 4 x)))
4879 (and (or log1 log2)
4880 (list kw
4881 (and log1 (if (equal log1 "!") 'time 'note))
4882 (and log2 (if (equal log2 "!") 'time 'note)))))))
4884 (defun org-remove-keyword-keys (list)
4885 "Remove a pair of parenthesis at the end of each string in LIST."
4886 (mapcar (lambda (x)
4887 (if (string-match "(.*)$" x)
4888 (substring x 0 (match-beginning 0))
4890 list))
4892 (defun org-assign-fast-keys (alist)
4893 "Assign fast keys to a keyword-key alist.
4894 Respect keys that are already there."
4895 (let (new e (alt ?0))
4896 (while (setq e (pop alist))
4897 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4898 (cdr e)) ;; Key already assigned.
4899 (push e new)
4900 (let ((clist (string-to-list (downcase (car e))))
4901 (used (append new alist)))
4902 (when (= (car clist) ?@)
4903 (pop clist))
4904 (while (and clist (rassoc (car clist) used))
4905 (pop clist))
4906 (unless clist
4907 (while (rassoc alt used)
4908 (incf alt)))
4909 (push (cons (car e) (or (car clist) alt)) new))))
4910 (nreverse new)))
4912 ;;; Some variables used in various places
4914 (defvar org-window-configuration nil
4915 "Used in various places to store a window configuration.")
4916 (defvar org-selected-window nil
4917 "Used in various places to store a window configuration.")
4918 (defvar org-finish-function nil
4919 "Function to be called when `C-c C-c' is used.
4920 This is for getting out of special buffers like capture.")
4923 ;; FIXME: Occasionally check by commenting these, to make sure
4924 ;; no other functions uses these, forgetting to let-bind them.
4925 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4926 (defvar org-last-state)
4927 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4929 ;; Defined somewhere in this file, but used before definition.
4930 (defvar org-entities) ;; defined in org-entities.el
4931 (defvar org-struct-menu)
4932 (defvar org-org-menu)
4933 (defvar org-tbl-menu)
4935 ;;;; Define the Org-mode
4937 ;; We use a before-change function to check if a table might need
4938 ;; an update.
4939 (defvar org-table-may-need-update t
4940 "Indicates that a table might need an update.
4941 This variable is set by `org-before-change-function'.
4942 `org-table-align' sets it back to nil.")
4943 (defun org-before-change-function (beg end)
4944 "Every change indicates that a table might need an update."
4945 (setq org-table-may-need-update t))
4946 (defvar org-mode-map)
4947 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4948 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4949 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4950 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4951 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4952 (defvar org-table-buffer-is-an nil)
4954 (defvar bidi-paragraph-direction)
4955 (defvar buffer-face-mode-face)
4957 (require 'outline)
4958 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4959 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4960 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4962 ;; Other stuff we need.
4963 (require 'time-date)
4964 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4965 (require 'easymenu)
4966 (require 'overlay)
4968 (require 'org-macs)
4969 (require 'org-entities)
4970 ;; (require 'org-compat) moved higher up in the file before it is first used
4971 (require 'org-faces)
4972 (require 'org-list)
4973 (require 'org-pcomplete)
4974 (require 'org-src)
4975 (require 'org-footnote)
4977 ;; babel
4978 (require 'ob)
4980 ;;;###autoload
4981 (define-derived-mode org-mode outline-mode "Org"
4982 "Outline-based notes management and organizer, alias
4983 \"Carsten's outline-mode for keeping track of everything.\"
4985 Org-mode develops organizational tasks around a NOTES file which
4986 contains information about projects as plain text. Org-mode is
4987 implemented on top of outline-mode, which is ideal to keep the content
4988 of large files well structured. It supports ToDo items, deadlines and
4989 time stamps, which magically appear in the diary listing of the Emacs
4990 calendar. Tables are easily created with a built-in table editor.
4991 Plain text URL-like links connect to websites, emails (VM), Usenet
4992 messages (Gnus), BBDB entries, and any files related to the project.
4993 For printing and sharing of notes, an Org-mode file (or a part of it)
4994 can be exported as a structured ASCII or HTML file.
4996 The following commands are available:
4998 \\{org-mode-map}"
5000 ;; Get rid of Outline menus, they are not needed
5001 ;; Need to do this here because define-derived-mode sets up
5002 ;; the keymap so late. Still, it is a waste to call this each time
5003 ;; we switch another buffer into org-mode.
5004 (if (featurep 'xemacs)
5005 (when (boundp 'outline-mode-menu-heading)
5006 ;; Assume this is Greg's port, it uses easymenu
5007 (easy-menu-remove outline-mode-menu-heading)
5008 (easy-menu-remove outline-mode-menu-show)
5009 (easy-menu-remove outline-mode-menu-hide))
5010 (define-key org-mode-map [menu-bar headings] 'undefined)
5011 (define-key org-mode-map [menu-bar hide] 'undefined)
5012 (define-key org-mode-map [menu-bar show] 'undefined))
5014 (org-load-modules-maybe)
5015 (easy-menu-add org-org-menu)
5016 (easy-menu-add org-tbl-menu)
5017 (org-install-agenda-files-menu)
5018 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5019 (add-to-invisibility-spec '(org-cwidth))
5020 (add-to-invisibility-spec '(org-hide-block . t))
5021 (when (featurep 'xemacs)
5022 (org-set-local 'line-move-ignore-invisible t))
5023 (org-set-local 'outline-regexp org-outline-regexp)
5024 (org-set-local 'outline-level 'org-outline-level)
5025 (setq bidi-paragraph-direction 'left-to-right)
5026 (when (and org-ellipsis
5027 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5028 (fboundp 'make-glyph-code))
5029 (unless org-display-table
5030 (setq org-display-table (make-display-table)))
5031 (set-display-table-slot
5032 org-display-table 4
5033 (vconcat (mapcar
5034 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5035 org-ellipsis)))
5036 (if (stringp org-ellipsis) org-ellipsis "..."))))
5037 (setq buffer-display-table org-display-table))
5038 (org-set-regexps-and-options)
5039 (when (and org-tag-faces (not org-tags-special-faces-re))
5040 ;; tag faces set outside customize.... force initialization.
5041 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5042 ;; Calc embedded
5043 (org-set-local 'calc-embedded-open-mode "# ")
5044 (modify-syntax-entry ?@ "w")
5045 (modify-syntax-entry ?\" "\"")
5046 (if org-startup-truncated (setq truncate-lines t))
5047 (org-set-local 'font-lock-unfontify-region-function
5048 'org-unfontify-region)
5049 ;; Activate before-change-function
5050 (org-set-local 'org-table-may-need-update t)
5051 (org-add-hook 'before-change-functions 'org-before-change-function nil
5052 'local)
5053 ;; Check for running clock before killing a buffer
5054 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5055 ;; Initialize macros templates.
5056 (org-macro-initialize-templates)
5057 ;; Initialize radio targets.
5058 (org-update-radio-target-regexp)
5059 ;; Indentation.
5060 (org-set-local 'indent-line-function 'org-indent-line)
5061 (org-set-local 'indent-region-function 'org-indent-region)
5062 ;; Filling and auto-filling.
5063 (org-setup-filling)
5064 ;; Comments.
5065 (org-setup-comments-handling)
5066 ;; Beginning/end of defun
5067 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5068 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5069 ;; Next error for sparse trees
5070 (org-set-local 'next-error-function 'org-occur-next-match)
5071 ;; Make sure dependence stuff works reliably, even for users who set it
5072 ;; too late :-(
5073 (if org-enforce-todo-dependencies
5074 (add-hook 'org-blocker-hook
5075 'org-block-todo-from-children-or-siblings-or-parent)
5076 (remove-hook 'org-blocker-hook
5077 'org-block-todo-from-children-or-siblings-or-parent))
5078 (if org-enforce-todo-checkbox-dependencies
5079 (add-hook 'org-blocker-hook
5080 'org-block-todo-from-checkboxes)
5081 (remove-hook 'org-blocker-hook
5082 'org-block-todo-from-checkboxes))
5084 ;; Align options lines
5085 (org-set-local
5086 'align-mode-rules-list
5087 '((org-in-buffer-settings
5088 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5089 (modes . '(org-mode)))))
5091 ;; Imenu
5092 (org-set-local 'imenu-create-index-function
5093 'org-imenu-get-tree)
5095 ;; Make isearch reveal context
5096 (if (or (featurep 'xemacs)
5097 (not (boundp 'outline-isearch-open-invisible-function)))
5098 ;; Emacs 21 and XEmacs make use of the hook
5099 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5100 ;; Emacs 22 deals with this through a special variable
5101 (org-set-local 'outline-isearch-open-invisible-function
5102 (lambda (&rest ignore) (org-show-context 'isearch))))
5104 ;; Turn on org-beamer-mode?
5105 (and org-startup-with-beamer-mode (org-beamer-mode))
5107 ;; Setup the pcomplete hooks
5108 (set (make-local-variable 'pcomplete-command-completion-function)
5109 'org-pcomplete-initial)
5110 (set (make-local-variable 'pcomplete-command-name-function)
5111 'org-command-at-point)
5112 (set (make-local-variable 'pcomplete-default-completion-function)
5113 'ignore)
5114 (set (make-local-variable 'pcomplete-parse-arguments-function)
5115 'org-parse-arguments)
5116 (set (make-local-variable 'pcomplete-termination-string) "")
5117 (when (>= emacs-major-version 23)
5118 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5120 ;; If empty file that did not turn on org-mode automatically, make it to.
5121 (if (and org-insert-mode-line-in-empty-file
5122 (org-called-interactively-p 'any)
5123 (= (point-min) (point-max)))
5124 (insert "# -*- mode: org -*-\n\n"))
5125 (unless org-inhibit-startup
5126 (when org-startup-align-all-tables
5127 (let ((bmp (buffer-modified-p)))
5128 (org-table-map-tables 'org-table-align 'quietly)
5129 (set-buffer-modified-p bmp)))
5130 (when org-startup-with-inline-images
5131 (org-display-inline-images))
5132 (when org-startup-indented
5133 (require 'org-indent)
5134 (org-indent-mode 1))
5135 (unless org-inhibit-startup-visibility-stuff
5136 (org-set-startup-visibility)))
5137 ;; Try to set org-hide correctly
5138 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5140 (when (fboundp 'abbrev-table-put)
5141 (abbrev-table-put org-mode-abbrev-table
5142 :parents (list text-mode-abbrev-table)))
5144 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5147 (defun org-find-invisible-foreground ()
5148 (let ((candidates (remove
5149 "unspecified-bg"
5150 (nconc
5151 (list (face-background 'default)
5152 (face-background 'org-default))
5153 (mapcar
5154 (lambda (alist)
5155 (when (boundp alist)
5156 (cdr (assoc 'background-color (symbol-value alist)))))
5157 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5158 (list (face-foreground 'org-hide))))))
5159 (car (remove nil candidates))))
5161 (defun org-current-time ()
5162 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5163 (if (> (car org-time-stamp-rounding-minutes) 1)
5164 (let ((r (car org-time-stamp-rounding-minutes))
5165 (time (decode-time)))
5166 (apply 'encode-time
5167 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5168 (nthcdr 2 time))))
5169 (current-time)))
5171 (defun org-today ()
5172 "Return today date, considering `org-extend-today-until'."
5173 (time-to-days
5174 (time-subtract (current-time)
5175 (list 0 (* 3600 org-extend-today-until) 0))))
5177 ;;;; Font-Lock stuff, including the activators
5179 (defvar org-mouse-map (make-sparse-keymap))
5180 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5181 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5182 (when org-mouse-1-follows-link
5183 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5184 (when org-tab-follows-link
5185 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5186 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5188 (require 'font-lock)
5190 (defconst org-non-link-chars "]\t\n\r<>")
5191 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5192 "shell" "elisp" "doi" "message"))
5193 (defvar org-link-types-re nil
5194 "Matches a link that has a url-like prefix like \"http:\"")
5195 (defvar org-link-re-with-space nil
5196 "Matches a link with spaces, optional angular brackets around it.")
5197 (defvar org-link-re-with-space2 nil
5198 "Matches a link with spaces, optional angular brackets around it.")
5199 (defvar org-link-re-with-space3 nil
5200 "Matches a link with spaces, only for internal part in bracket links.")
5201 (defvar org-angle-link-re nil
5202 "Matches link with angular brackets, spaces are allowed.")
5203 (defvar org-plain-link-re nil
5204 "Matches plain link, without spaces.")
5205 (defvar org-bracket-link-regexp nil
5206 "Matches a link in double brackets.")
5207 (defvar org-bracket-link-analytic-regexp nil
5208 "Regular expression used to analyze links.
5209 Here is what the match groups contain after a match:
5210 1: http:
5211 2: http
5212 3: path
5213 4: [desc]
5214 5: desc")
5215 (defvar org-bracket-link-analytic-regexp++ nil
5216 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5217 (defvar org-any-link-re nil
5218 "Regular expression matching any link.")
5220 (defcustom org-match-sexp-depth 3
5221 "Number of stacked braces for sub/superscript matching.
5222 This has to be set before loading org.el to be effective."
5223 :group 'org-export-translation ; ??????????????????????????/
5224 :type 'integer)
5226 (defun org-create-multibrace-regexp (left right n)
5227 "Create a regular expression which will match a balanced sexp.
5228 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5229 as single character strings.
5230 The regexp returned will match the entire expression including the
5231 delimiters. It will also define a single group which contains the
5232 match except for the outermost delimiters. The maximum depth of
5233 stacked delimiters is N. Escaping delimiters is not possible."
5234 (let* ((nothing (concat "[^" left right "]*?"))
5235 (or "\\|")
5236 (re nothing)
5237 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5238 (while (> n 1)
5239 (setq n (1- n)
5240 re (concat re or next)
5241 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5242 (concat left "\\(" re "\\)" right)))
5244 (defvar org-match-substring-regexp
5245 (concat
5246 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5247 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5248 "\\|"
5249 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5250 "\\|"
5251 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5252 "The regular expression matching a sub- or superscript.")
5254 (defvar org-match-substring-with-braces-regexp
5255 (concat
5256 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5257 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5258 "\\)")
5259 "The regular expression matching a sub- or superscript, forcing braces.")
5261 (defun org-make-link-regexps ()
5262 "Update the link regular expressions.
5263 This should be called after the variable `org-link-types' has changed."
5264 (setq org-link-types-re
5265 (concat
5266 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5267 org-link-re-with-space
5268 (concat
5269 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5270 "\\([^" org-non-link-chars " ]"
5271 "[^" org-non-link-chars "]*"
5272 "[^" org-non-link-chars " ]\\)>?")
5273 org-link-re-with-space2
5274 (concat
5275 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5276 "\\([^" org-non-link-chars " ]"
5277 "[^\t\n\r]*"
5278 "[^" org-non-link-chars " ]\\)>?")
5279 org-link-re-with-space3
5280 (concat
5281 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5282 "\\([^" org-non-link-chars " ]"
5283 "[^\t\n\r]*\\)")
5284 org-angle-link-re
5285 (concat
5286 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5287 "\\([^" org-non-link-chars " ]"
5288 "[^" org-non-link-chars "]*"
5289 "\\)>")
5290 org-plain-link-re
5291 (concat
5292 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5293 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5294 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5295 org-bracket-link-regexp
5296 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5297 org-bracket-link-analytic-regexp
5298 (concat
5299 "\\[\\["
5300 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5301 "\\([^]]+\\)"
5302 "\\]"
5303 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5304 "\\]")
5305 org-bracket-link-analytic-regexp++
5306 (concat
5307 "\\[\\["
5308 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5309 "\\([^]]+\\)"
5310 "\\]"
5311 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5312 "\\]")
5313 org-any-link-re
5314 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5315 org-angle-link-re "\\)\\|\\("
5316 org-plain-link-re "\\)")))
5318 (org-make-link-regexps)
5320 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5321 "Regular expression for fast time stamp matching.")
5322 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5323 "Regular expression for fast time stamp matching.")
5324 (defconst org-ts-regexp0
5325 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5326 "Regular expression matching time strings for analysis.
5327 This one does not require the space after the date, so it can be used
5328 on a string that terminates immediately after the date.")
5329 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5330 "Regular expression matching time strings for analysis.")
5331 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5332 "Regular expression matching time stamps, with groups.")
5333 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5334 "Regular expression matching time stamps (also [..]), with groups.")
5335 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5336 "Regular expression matching a time stamp range.")
5337 (defconst org-tr-regexp-both
5338 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5339 "Regular expression matching a time stamp range.")
5340 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5341 org-ts-regexp "\\)?")
5342 "Regular expression matching a time stamp or time stamp range.")
5343 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5344 org-ts-regexp-both "\\)?")
5345 "Regular expression matching a time stamp or time stamp range.
5346 The time stamps may be either active or inactive.")
5348 (defvar org-emph-face nil)
5350 (defun org-do-emphasis-faces (limit)
5351 "Run through the buffer and add overlays to emphasized strings."
5352 (let (rtn a)
5353 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5354 (if (not (= (char-after (match-beginning 3))
5355 (char-after (match-beginning 4))))
5356 (progn
5357 (setq rtn t)
5358 (setq a (assoc (match-string 3) org-emphasis-alist))
5359 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5360 'face
5361 (nth 1 a))
5362 (and (nth 4 a)
5363 (org-remove-flyspell-overlays-in
5364 (match-beginning 0) (match-end 0)))
5365 (add-text-properties (match-beginning 2) (match-end 2)
5366 '(font-lock-multiline t org-emphasis t))
5367 (when org-hide-emphasis-markers
5368 (add-text-properties (match-end 4) (match-beginning 5)
5369 '(invisible org-link))
5370 (add-text-properties (match-beginning 3) (match-end 3)
5371 '(invisible org-link)))))
5372 (backward-char 1))
5373 rtn))
5375 (defun org-emphasize (&optional char)
5376 "Insert or change an emphasis, i.e. a font like bold or italic.
5377 If there is an active region, change that region to a new emphasis.
5378 If there is no region, just insert the marker characters and position
5379 the cursor between them.
5380 CHAR should be either the marker character, or the first character of the
5381 HTML tag associated with that emphasis. If CHAR is a space, the means
5382 to remove the emphasis of the selected region.
5383 If char is not given (for example in an interactive call) it
5384 will be prompted for."
5385 (interactive)
5386 (let ((eal org-emphasis-alist) e det
5387 (erc org-emphasis-regexp-components)
5388 (prompt "")
5389 (string "") beg end move tag c s)
5390 (if (org-region-active-p)
5391 (setq beg (region-beginning) end (region-end)
5392 string (buffer-substring beg end))
5393 (setq move t))
5395 (while (setq e (pop eal))
5396 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5397 c (aref tag 0))
5398 (push (cons c (string-to-char (car e))) det)
5399 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5400 (substring tag 1)))))
5401 (setq det (nreverse det))
5402 (unless char
5403 (message "%s" (concat "Emphasis marker or tag:" prompt))
5404 (setq char (read-char-exclusive)))
5405 (setq char (or (cdr (assoc char det)) char))
5406 (if (equal char ?\ )
5407 (setq s "" move nil)
5408 (unless (assoc (char-to-string char) org-emphasis-alist)
5409 (error "No such emphasis marker: \"%c\"" char))
5410 (setq s (char-to-string char)))
5411 (while (and (> (length string) 1)
5412 (equal (substring string 0 1) (substring string -1))
5413 (assoc (substring string 0 1) org-emphasis-alist))
5414 (setq string (substring string 1 -1)))
5415 (setq string (concat s string s))
5416 (if beg (delete-region beg end))
5417 (unless (or (bolp)
5418 (string-match (concat "[" (nth 0 erc) "\n]")
5419 (char-to-string (char-before (point)))))
5420 (insert " "))
5421 (unless (or (eobp)
5422 (string-match (concat "[" (nth 1 erc) "\n]")
5423 (char-to-string (char-after (point)))))
5424 (insert " ") (backward-char 1))
5425 (insert string)
5426 (and move (backward-char 1))))
5428 (defconst org-nonsticky-props
5429 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5431 (defsubst org-rear-nonsticky-at (pos)
5432 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5434 (defun org-activate-plain-links (limit)
5435 "Run through the buffer and add overlays to links."
5436 (catch 'exit
5437 (let (f hl)
5438 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5439 (not (org-in-src-block-p)))
5440 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5441 (setq f (get-text-property (match-beginning 0) 'face))
5442 (setq hl (org-match-string-no-properties 0))
5443 (if (or (eq f 'org-tag)
5444 (and (listp f) (memq 'org-tag f)))
5446 (add-text-properties (match-beginning 0) (match-end 0)
5447 (list 'mouse-face 'highlight
5448 'face 'org-link
5449 'htmlize-link `(:uri ,hl)
5450 'keymap org-mouse-map))
5451 (org-rear-nonsticky-at (match-end 0)))
5452 t))))
5454 (defun org-activate-code (limit)
5455 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5456 (progn
5457 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5458 (remove-text-properties (match-beginning 0) (match-end 0)
5459 '(display t invisible t intangible t))
5460 t)))
5462 (defcustom org-src-fontify-natively nil
5463 "When non-nil, fontify code in code blocks."
5464 :type 'boolean
5465 :version "24.1"
5466 :group 'org-appearance
5467 :group 'org-babel)
5469 (defcustom org-allow-promoting-top-level-subtree nil
5470 "When non-nil, allow promoting a top level subtree.
5471 The leading star of the top level headline will be replaced
5472 by a #."
5473 :type 'boolean
5474 :version "24.1"
5475 :group 'org-appearance)
5477 (defun org-fontify-meta-lines-and-blocks (limit)
5478 (condition-case nil
5479 (org-fontify-meta-lines-and-blocks-1 limit)
5480 (error (message "org-mode fontification error"))))
5482 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5483 "Fontify #+ lines and blocks, in the correct ways."
5484 (let ((case-fold-search t))
5485 (if (re-search-forward
5486 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5487 limit t)
5488 (let ((beg (match-beginning 0))
5489 (block-start (match-end 0))
5490 (block-end nil)
5491 (lang (match-string 7))
5492 (beg1 (line-beginning-position 2))
5493 (dc1 (downcase (match-string 2)))
5494 (dc3 (downcase (match-string 3)))
5495 end end1 quoting block-type ovl)
5496 (cond
5497 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5498 ;; a single line of backend-specific content
5499 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5500 (remove-text-properties (match-beginning 0) (match-end 0)
5501 '(display t invisible t intangible t))
5502 (add-text-properties (match-beginning 1) (match-end 3)
5503 '(font-lock-fontified t face org-meta-line))
5504 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5505 '(font-lock-fontified t face org-block))
5506 ; for backend-specific code
5508 ((and (match-end 4) (equal dc3 "+begin"))
5509 ;; Truly a block
5510 (setq block-type (downcase (match-string 5))
5511 quoting (member block-type org-protecting-blocks))
5512 (when (re-search-forward
5513 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5514 nil t) ;; on purpose, we look further than LIMIT
5515 (setq end (min (point-max) (match-end 0))
5516 end1 (min (point-max) (1- (match-beginning 0))))
5517 (setq block-end (match-beginning 0))
5518 (when quoting
5519 (remove-text-properties beg end
5520 '(display t invisible t intangible t)))
5521 (add-text-properties
5522 beg end
5523 '(font-lock-fontified t font-lock-multiline t))
5524 (add-text-properties beg beg1 '(face org-meta-line))
5525 (add-text-properties end1 (min (point-max) (1+ end))
5526 '(face org-meta-line)) ; for end_src
5527 (cond
5528 ((and lang (not (string= lang "")) org-src-fontify-natively)
5529 (org-src-font-lock-fontify-block lang block-start block-end)
5530 ;; remove old background overlays
5531 (mapc (lambda (ov)
5532 (if (eq (overlay-get ov 'face) 'org-block-background)
5533 (delete-overlay ov)))
5534 (overlays-at (/ (+ beg1 block-end) 2)))
5535 ;; add a background overlay
5536 (setq ovl (make-overlay beg1 block-end))
5537 (overlay-put ovl 'face 'org-block-background)
5538 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5539 (quoting
5540 (add-text-properties beg1 (min (point-max) (1+ end1))
5541 '(face org-block))) ; end of source block
5542 ((not org-fontify-quote-and-verse-blocks))
5543 ((string= block-type "quote")
5544 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5545 ((string= block-type "verse")
5546 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5547 (add-text-properties beg beg1 '(face org-block-begin-line))
5548 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5549 '(face org-block-end-line))
5551 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5552 (add-text-properties
5553 beg (match-end 3)
5554 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5555 '(font-lock-fontified t invisible t)
5556 '(font-lock-fontified t face org-document-info-keyword)))
5557 (add-text-properties
5558 (match-beginning 6) (match-end 6)
5559 (if (string-equal dc1 "+title:")
5560 '(font-lock-fontified t face org-document-title)
5561 '(font-lock-fontified t face org-document-info))))
5562 ((or (equal dc1 "+results")
5563 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5564 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5565 "+call:" "+header:" "+headers:" "+name:"))
5566 (and (match-end 4) (equal dc3 "+attr")))
5567 (add-text-properties
5568 beg (match-end 0)
5569 '(font-lock-fontified t face org-meta-line))
5571 ((member dc3 '(" " ""))
5572 (add-text-properties
5573 beg (match-end 0)
5574 '(font-lock-fontified t face font-lock-comment-face)))
5575 ((not (member (char-after beg) '(?\ ?\t)))
5576 ;; just any other in-buffer setting, but not indented
5577 (add-text-properties
5578 beg (match-end 0)
5579 '(font-lock-fontified t face org-meta-line))
5581 (t nil))))))
5583 (defun org-activate-angle-links (limit)
5584 "Run through the buffer and add overlays to links."
5585 (if (and (re-search-forward org-angle-link-re limit t)
5586 (not (org-in-src-block-p)))
5587 (progn
5588 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5589 (add-text-properties (match-beginning 0) (match-end 0)
5590 (list 'mouse-face 'highlight
5591 'keymap org-mouse-map))
5592 (org-rear-nonsticky-at (match-end 0))
5593 t)))
5595 (defun org-activate-footnote-links (limit)
5596 "Run through the buffer and add overlays to footnotes."
5597 (let ((fn (org-footnote-next-reference-or-definition limit)))
5598 (when fn
5599 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5600 (org-remove-flyspell-overlays-in beg end)
5601 (add-text-properties beg end
5602 (list 'mouse-face 'highlight
5603 'keymap org-mouse-map
5604 'help-echo
5605 (if (= (point-at-bol) beg)
5606 "Footnote definition"
5607 "Footnote reference")
5608 'font-lock-fontified t
5609 'font-lock-multiline t
5610 'face 'org-footnote))))))
5612 (defun org-activate-bracket-links (limit)
5613 "Run through the buffer and add overlays to bracketed links."
5614 (if (and (re-search-forward org-bracket-link-regexp limit t)
5615 (not (org-in-src-block-p)))
5616 (let* ((hl (org-match-string-no-properties 1))
5617 (help (concat "LINK: " hl))
5618 ;; FIXME: Above we should remove the escapes. But that
5619 ;; requires another match, protecting match data, a lot
5620 ;; of overhead for font-lock.
5621 (ip (org-maybe-intangible
5622 (list 'invisible 'org-link
5623 'keymap org-mouse-map 'mouse-face 'highlight
5624 'font-lock-multiline t 'help-echo help
5625 'htmlize-link `(:uri ,hl))))
5626 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5627 'font-lock-multiline t 'help-echo help
5628 'htmlize-link `(:uri ,hl))))
5629 ;; We need to remove the invisible property here. Table narrowing
5630 ;; may have made some of this invisible.
5631 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5632 (remove-text-properties (match-beginning 0) (match-end 0)
5633 '(invisible nil))
5634 (if (match-end 3)
5635 (progn
5636 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5637 (org-rear-nonsticky-at (match-beginning 3))
5638 (add-text-properties (match-beginning 3) (match-end 3) vp)
5639 (org-rear-nonsticky-at (match-end 3))
5640 (add-text-properties (match-end 3) (match-end 0) ip)
5641 (org-rear-nonsticky-at (match-end 0)))
5642 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5643 (org-rear-nonsticky-at (match-beginning 1))
5644 (add-text-properties (match-beginning 1) (match-end 1) vp)
5645 (org-rear-nonsticky-at (match-end 1))
5646 (add-text-properties (match-end 1) (match-end 0) ip)
5647 (org-rear-nonsticky-at (match-end 0)))
5648 t)))
5650 (defun org-activate-dates (limit)
5651 "Run through the buffer and add overlays to dates."
5652 (if (re-search-forward org-tsr-regexp-both limit t)
5653 (progn
5654 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5655 (add-text-properties (match-beginning 0) (match-end 0)
5656 (list 'mouse-face 'highlight
5657 'keymap org-mouse-map))
5658 (org-rear-nonsticky-at (match-end 0))
5659 (when org-display-custom-times
5660 (if (match-end 3)
5661 (org-display-custom-time (match-beginning 3) (match-end 3)))
5662 (org-display-custom-time (match-beginning 1) (match-end 1)))
5663 t)))
5665 (defvar org-target-link-regexp nil
5666 "Regular expression matching radio targets in plain text.")
5667 (make-variable-buffer-local 'org-target-link-regexp)
5668 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5669 "Regular expression matching a link target.")
5670 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5671 "Regular expression matching a radio target.")
5672 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5673 "Regular expression matching any target.")
5675 (defun org-activate-target-links (limit)
5676 "Run through the buffer and add overlays to target matches."
5677 (when org-target-link-regexp
5678 (let ((case-fold-search t))
5679 (if (re-search-forward org-target-link-regexp limit t)
5680 (progn
5681 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5682 (add-text-properties (match-beginning 0) (match-end 0)
5683 (list 'mouse-face 'highlight
5684 'keymap org-mouse-map
5685 'help-echo "Radio target link"
5686 'org-linked-text t))
5687 (org-rear-nonsticky-at (match-end 0))
5688 t)))))
5690 (defun org-update-radio-target-regexp ()
5691 "Find all radio targets in this file and update the regular expression."
5692 (interactive)
5693 (when (memq 'radio org-activate-links)
5694 (setq org-target-link-regexp
5695 (org-make-target-link-regexp (org-all-targets 'radio)))
5696 (org-restart-font-lock)))
5698 (defun org-hide-wide-columns (limit)
5699 (let (s e)
5700 (setq s (text-property-any (point) (or limit (point-max))
5701 'org-cwidth t))
5702 (when s
5703 (setq e (next-single-property-change s 'org-cwidth))
5704 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5705 (goto-char e)
5706 t)))
5708 (defvar org-latex-and-specials-regexp nil
5709 "Regular expression for highlighting export special stuff.")
5710 (defvar org-match-substring-regexp)
5711 (defvar org-match-substring-with-braces-regexp)
5713 ;; This should be with the exporter code, but we also use if for font-locking
5714 (defconst org-export-html-special-string-regexps
5715 '(("\\\\-" . "&shy;")
5716 ("---\\([^-]\\)" . "&mdash;\\1")
5717 ("--\\([^-]\\)" . "&ndash;\\1")
5718 ("\\.\\.\\." . "&hellip;"))
5719 "Regular expressions for special string conversion.")
5722 (defun org-compute-latex-and-specials-regexp ()
5723 "Compute regular expression for stuff treated specially by exporters."
5724 (if (not org-highlight-latex-fragments-and-specials)
5725 (org-set-local 'org-latex-and-specials-regexp nil)
5726 (require 'org-exp)
5727 (let*
5728 ((matchers (plist-get org-format-latex-options :matchers))
5729 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5730 org-latex-regexps)))
5731 (org-export-allow-BIND nil)
5732 (options (org-combine-plists (org-default-export-plist)
5733 (org-infile-export-plist)))
5734 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5735 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5736 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5737 (org-export-html-expand (plist-get options :expand-quoted-html))
5738 (org-export-with-special-strings (plist-get options :special-strings))
5739 (re-sub
5740 (cond
5741 ((equal org-export-with-sub-superscripts '{})
5742 (list org-match-substring-with-braces-regexp))
5743 (org-export-with-sub-superscripts
5744 (list org-match-substring-regexp))))
5745 (re-latex
5746 (if org-export-with-LaTeX-fragments
5747 (mapcar (lambda (x) (nth 1 x)) latexs)))
5748 (re-macros
5749 (if org-export-with-TeX-macros
5750 (list (concat "\\\\"
5751 (regexp-opt
5752 (append
5754 (delq nil
5755 (mapcar 'car-safe
5756 (append org-entities-user
5757 org-entities)))
5758 (if (boundp 'org-latex-entities)
5759 (mapcar (lambda (x)
5760 (or (car-safe x) x))
5761 org-latex-entities)
5762 nil))
5763 'words))) ; FIXME
5765 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5766 (re-special (if org-export-with-special-strings
5767 (mapcar (lambda (x) (car x))
5768 org-export-html-special-string-regexps)))
5769 (re-rest
5770 (delq nil
5771 (list
5772 (if org-export-html-expand "@<[^>\n]+>")
5773 ))))
5774 (org-set-local
5775 'org-latex-and-specials-regexp
5776 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5777 re-rest) "\\|")))))
5779 (defun org-do-latex-and-special-faces (limit)
5780 "Run through the buffer and add overlays to links."
5781 (when org-latex-and-specials-regexp
5782 (let (rtn d)
5783 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5784 limit t))
5785 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5786 'face))
5787 '(org-code org-verbatim underline)))
5788 (progn
5789 (setq rtn t
5790 d (cond ((member (char-after (1+ (match-beginning 0)))
5791 '(?_ ?^)) 1)
5792 (t 0)))
5793 (font-lock-prepend-text-property
5794 (+ d (match-beginning 0)) (match-end 0)
5795 'face 'org-latex-and-export-specials)
5796 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5797 '(font-lock-multiline t)))))
5798 rtn)))
5800 (defun org-restart-font-lock ()
5801 "Restart `font-lock-mode', to force refontification."
5802 (when (and (boundp 'font-lock-mode) font-lock-mode)
5803 (font-lock-mode -1)
5804 (font-lock-mode 1)))
5806 (defun org-all-targets (&optional radio)
5807 "Return a list of all targets in this file.
5808 When optional argument RADIO is non-nil, only find radio
5809 targets."
5810 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5811 (save-excursion
5812 (goto-char (point-min))
5813 (while (re-search-forward re nil t)
5814 ;; Make sure point is really within the object.
5815 (backward-char)
5816 (let ((obj (org-element-context)))
5817 (when (memq (org-element-type obj) '(radio-target target))
5818 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5819 rtn)))
5821 (defun org-make-target-link-regexp (targets)
5822 "Make regular expression matching all strings in TARGETS.
5823 The regular expression finds the targets also if there is a line break
5824 between words."
5825 (and targets
5826 (concat
5827 "\\<\\("
5828 (mapconcat
5829 (lambda (x)
5830 (setq x (regexp-quote x))
5831 (while (string-match " +" x)
5832 (setq x (replace-match "\\s-+" t t x)))
5834 targets
5835 "\\|")
5836 "\\)\\>")))
5838 (defun org-activate-tags (limit)
5839 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5840 (progn
5841 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5842 (add-text-properties (match-beginning 1) (match-end 1)
5843 (list 'mouse-face 'highlight
5844 'keymap org-mouse-map))
5845 (org-rear-nonsticky-at (match-end 1))
5846 t)))
5848 (defun org-outline-level ()
5849 "Compute the outline level of the heading at point.
5850 If this is called at a normal headline, the level is the number of stars.
5851 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5852 (save-excursion
5853 (if (not (condition-case nil
5854 (org-back-to-heading t)
5855 (error nil)))
5857 (looking-at org-outline-regexp)
5858 (1- (- (match-end 0) (match-beginning 0))))))
5860 (defvar org-font-lock-keywords nil)
5862 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5863 "Regular expression matching a property line.")
5865 (defvar org-font-lock-hook nil
5866 "Functions to be called for special font lock stuff.")
5868 (defvar org-font-lock-set-keywords-hook nil
5869 "Functions that can manipulate `org-font-lock-extra-keywords'.
5870 This is called after `org-font-lock-extra-keywords' is defined, but before
5871 it is installed to be used by font lock. This can be useful if something
5872 needs to be inserted at a specific position in the font-lock sequence.")
5874 (defun org-font-lock-hook (limit)
5875 "Run `org-font-lock-hook' within LIMIT."
5876 (run-hook-with-args 'org-font-lock-hook limit))
5878 (defun org-set-font-lock-defaults ()
5879 "Set font lock defaults for the current buffer."
5880 (let* ((em org-fontify-emphasized-text)
5881 (lk org-activate-links)
5882 (org-font-lock-extra-keywords
5883 (list
5884 ;; Call the hook
5885 '(org-font-lock-hook)
5886 ;; Headlines
5887 `(,(if org-fontify-whole-heading-line
5888 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5889 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5890 (1 (org-get-level-face 1))
5891 (2 (org-get-level-face 2))
5892 (3 (org-get-level-face 3)))
5893 ;; Table lines
5894 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5895 (1 'org-table t))
5896 ;; Table internals
5897 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5898 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5899 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5900 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5901 ;; Drawers
5902 (list org-drawer-regexp '(0 'org-special-keyword t))
5903 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5904 ;; Properties
5905 (list org-property-re
5906 '(1 'org-special-keyword t)
5907 '(3 'org-property-value t))
5908 ;; Links
5909 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5910 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5911 (if (memq 'plain lk) '(org-activate-plain-links))
5912 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5913 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5914 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5915 (if (memq 'footnote lk) '(org-activate-footnote-links))
5916 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5917 '(org-hide-wide-columns (0 nil append))
5918 ;; TODO keyword
5919 (list (format org-heading-keyword-regexp-format
5920 org-todo-regexp)
5921 '(2 (org-get-todo-face 2) t))
5922 ;; DONE
5923 (if org-fontify-done-headline
5924 (list (format org-heading-keyword-regexp-format
5925 (concat
5926 "\\(?:"
5927 (mapconcat 'regexp-quote org-done-keywords "\\|")
5928 "\\)"))
5929 '(2 'org-headline-done t))
5930 nil)
5931 ;; Priorities
5932 '(org-font-lock-add-priority-faces)
5933 ;; Tags
5934 '(org-font-lock-add-tag-faces)
5935 ;; Special keywords
5936 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5937 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5938 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5939 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5940 ;; Emphasis
5941 (if em
5942 (if (featurep 'xemacs)
5943 '(org-do-emphasis-faces (0 nil append))
5944 '(org-do-emphasis-faces)))
5945 ;; Checkboxes
5946 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5947 1 'org-checkbox prepend)
5948 (if (cdr (assq 'checkbox org-list-automatic-rules))
5949 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5950 (0 (org-get-checkbox-statistics-face) t)))
5951 ;; Description list items
5952 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5953 1 'org-list-dt prepend)
5954 ;; ARCHIVEd headings
5955 (list (concat
5956 org-outline-regexp-bol
5957 "\\(.*:" org-archive-tag ":.*\\)")
5958 '(1 'org-archived prepend))
5959 ;; Specials
5960 '(org-do-latex-and-special-faces)
5961 '(org-fontify-entities)
5962 '(org-raise-scripts)
5963 ;; Code
5964 '(org-activate-code (1 'org-code t))
5965 ;; COMMENT
5966 (list (format org-heading-keyword-regexp-format
5967 (concat "\\("
5968 org-comment-string "\\|" org-quote-string
5969 "\\)"))
5970 '(2 'org-special-keyword t))
5971 ;; Blocks and meta lines
5972 '(org-fontify-meta-lines-and-blocks)
5974 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5975 (run-hooks 'org-font-lock-set-keywords-hook)
5976 ;; Now set the full font-lock-keywords
5977 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5978 (org-set-local 'font-lock-defaults
5979 '(org-font-lock-keywords t nil nil backward-paragraph))
5980 (kill-local-variable 'font-lock-keywords) nil))
5982 (defun org-toggle-pretty-entities ()
5983 "Toggle the composition display of entities as UTF8 characters."
5984 (interactive)
5985 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5986 (org-restart-font-lock)
5987 (if org-pretty-entities
5988 (message "Entities are displayed as UTF8 characters")
5989 (save-restriction
5990 (widen)
5991 (org-decompose-region (point-min) (point-max))
5992 (message "Entities are displayed plain"))))
5994 (defvar org-custom-properties-overlays nil
5995 "List of overlays used for custom properties.")
5996 (make-variable-buffer-local 'org-custom-properties-overlays)
5998 (defun org-toggle-custom-properties-visibility ()
5999 "Display or hide properties in `org-custom-properties'."
6000 (interactive)
6001 (if org-custom-properties-overlays
6002 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6003 (setq org-custom-properties-overlays nil))
6004 (unless (not org-custom-properties)
6005 (save-excursion
6006 (save-restriction
6007 (widen)
6008 (goto-char (point-min))
6009 (while (re-search-forward org-property-re nil t)
6010 (mapc (lambda(p)
6011 (when (equal p (substring (match-string 1) 1 -1))
6012 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6013 (overlay-put o 'invisible t)
6014 (overlay-put o 'org-custom-property t)
6015 (push o org-custom-properties-overlays))))
6016 org-custom-properties)))))))
6018 (defun org-fontify-entities (limit)
6019 "Find an entity to fontify."
6020 (let (ee)
6021 (when org-pretty-entities
6022 (catch 'match
6023 (while (re-search-forward
6024 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6025 limit t)
6026 (if (and (not (org-in-indented-comment-line))
6027 (setq ee (org-entity-get (match-string 1)))
6028 (= (length (nth 6 ee)) 1))
6029 (let*
6030 ((end (if (equal (match-string 2) "{}")
6031 (match-end 2)
6032 (match-end 1))))
6033 (add-text-properties
6034 (match-beginning 0) end
6035 (list 'font-lock-fontified t))
6036 (compose-region (match-beginning 0) end
6037 (nth 6 ee) nil)
6038 (backward-char 1)
6039 (throw 'match t))))
6040 nil))))
6042 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6043 "Fontify string S like in Org-mode."
6044 (with-temp-buffer
6045 (insert s)
6046 (let ((org-odd-levels-only odd-levels))
6047 (org-mode)
6048 (font-lock-fontify-buffer)
6049 (buffer-string))))
6051 (defvar org-m nil)
6052 (defvar org-l nil)
6053 (defvar org-f nil)
6054 (defun org-get-level-face (n)
6055 "Get the right face for match N in font-lock matching of headlines."
6056 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6057 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6058 (if org-cycle-level-faces
6059 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6060 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6061 (cond
6062 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6063 ((eq n 2) org-f)
6064 (t (if org-level-color-stars-only nil org-f))))
6067 (defun org-get-todo-face (kwd)
6068 "Get the right face for a TODO keyword KWD.
6069 If KWD is a number, get the corresponding match group."
6070 (if (numberp kwd) (setq kwd (match-string kwd)))
6071 (or (org-face-from-face-or-color
6072 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6073 (and (member kwd org-done-keywords) 'org-done)
6074 'org-todo))
6076 (defun org-face-from-face-or-color (context inherit face-or-color)
6077 "Create a face list that inherits INHERIT, but sets the foreground color.
6078 When FACE-OR-COLOR is not a string, just return it."
6079 (if (stringp face-or-color)
6080 (list :inherit inherit
6081 (cdr (assoc context org-faces-easy-properties))
6082 face-or-color)
6083 face-or-color))
6085 (defun org-font-lock-add-tag-faces (limit)
6086 "Add the special tag faces."
6087 (when (and org-tag-faces org-tags-special-faces-re)
6088 (while (re-search-forward org-tags-special-faces-re limit t)
6089 (add-text-properties (match-beginning 1) (match-end 1)
6090 (list 'face (org-get-tag-face 1)
6091 'font-lock-fontified t))
6092 (backward-char 1))))
6094 (defun org-font-lock-add-priority-faces (limit)
6095 "Add the special priority faces."
6096 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6097 (when (save-match-data (org-at-heading-p))
6098 (add-text-properties
6099 (match-beginning 0) (match-end 0)
6100 (list 'face (or (org-face-from-face-or-color
6101 'priority 'org-special-keyword
6102 (cdr (assoc (char-after (match-beginning 1))
6103 org-priority-faces)))
6104 'org-special-keyword)
6105 'font-lock-fontified t)))))
6107 (defun org-get-tag-face (kwd)
6108 "Get the right face for a TODO keyword KWD.
6109 If KWD is a number, get the corresponding match group."
6110 (if (numberp kwd) (setq kwd (match-string kwd)))
6111 (or (org-face-from-face-or-color
6112 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6113 'org-tag))
6115 (defun org-unfontify-region (beg end &optional maybe_loudly)
6116 "Remove fontification and activation overlays from links."
6117 (font-lock-default-unfontify-region beg end)
6118 (let* ((buffer-undo-list t)
6119 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6120 (inhibit-modification-hooks t)
6121 deactivate-mark buffer-file-name buffer-file-truename)
6122 (org-decompose-region beg end)
6123 (remove-text-properties beg end
6124 '(mouse-face t keymap t org-linked-text t
6125 invisible t intangible t
6126 org-no-flyspell t org-emphasis t))
6127 (org-remove-font-lock-display-properties beg end)))
6129 (defconst org-script-display '(((raise -0.3) (height 0.7))
6130 ((raise 0.3) (height 0.7))
6131 ((raise -0.5))
6132 ((raise 0.5)))
6133 "Display properties for showing superscripts and subscripts.")
6135 (defun org-remove-font-lock-display-properties (beg end)
6136 "Remove specific display properties that have been added by font lock.
6137 The will remove the raise properties that are used to show superscripts
6138 and subscripts."
6139 (let (next prop)
6140 (while (< beg end)
6141 (setq next (next-single-property-change beg 'display nil end)
6142 prop (get-text-property beg 'display))
6143 (if (member prop org-script-display)
6144 (put-text-property beg next 'display nil))
6145 (setq beg next))))
6147 (defun org-raise-scripts (limit)
6148 "Add raise properties to sub/superscripts."
6149 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6150 (if (re-search-forward
6151 (if (eq org-use-sub-superscripts t)
6152 org-match-substring-regexp
6153 org-match-substring-with-braces-regexp)
6154 limit t)
6155 (let* ((pos (point)) table-p comment-p
6156 (mpos (match-beginning 3))
6157 (emph-p (get-text-property mpos 'org-emphasis))
6158 (link-p (get-text-property mpos 'mouse-face))
6159 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6160 (goto-char (point-at-bol))
6161 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6162 comment-p (org-looking-at-p "[ \t]*#"))
6163 (goto-char pos)
6164 ;; FIXME: Should we go back one character here, for a_b^c
6165 ;; (goto-char (1- pos)) ;????????????????????
6166 (if (or comment-p emph-p link-p keyw-p)
6168 (put-text-property (match-beginning 3) (match-end 0)
6169 'display
6170 (if (equal (char-after (match-beginning 2)) ?^)
6171 (nth (if table-p 3 1) org-script-display)
6172 (nth (if table-p 2 0) org-script-display)))
6173 (add-text-properties (match-beginning 2) (match-end 2)
6174 (list 'invisible t
6175 'org-dwidth t 'org-dwidth-n 1))
6176 (if (and (eq (char-after (match-beginning 3)) ?{)
6177 (eq (char-before (match-end 3)) ?}))
6178 (progn
6179 (add-text-properties
6180 (match-beginning 3) (1+ (match-beginning 3))
6181 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6182 (add-text-properties
6183 (1- (match-end 3)) (match-end 3)
6184 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6185 t)))))
6187 ;;;; Visibility cycling, including org-goto and indirect buffer
6189 ;;; Cycling
6191 (defvar org-cycle-global-status nil)
6192 (make-variable-buffer-local 'org-cycle-global-status)
6193 (defvar org-cycle-subtree-status nil)
6194 (make-variable-buffer-local 'org-cycle-subtree-status)
6196 (defvar org-inlinetask-min-level)
6198 ;;;###autoload
6199 (defun org-cycle (&optional arg)
6200 "TAB-action and visibility cycling for Org-mode.
6202 This is the command invoked in Org-mode by the TAB key. Its main purpose
6203 is outline visibility cycling, but it also invokes other actions
6204 in special contexts.
6206 - When this function is called with a prefix argument, rotate the entire
6207 buffer through 3 states (global cycling)
6208 1. OVERVIEW: Show only top-level headlines.
6209 2. CONTENTS: Show all headlines of all levels, but no body text.
6210 3. SHOW ALL: Show everything.
6211 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6212 determined by the variable `org-startup-folded', and by any VISIBILITY
6213 properties in the buffer.
6214 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6215 including any drawers.
6217 - When inside a table, re-align the table and move to the next field.
6219 - When point is at the beginning of a headline, rotate the subtree started
6220 by this line through 3 different states (local cycling)
6221 1. FOLDED: Only the main headline is shown.
6222 2. CHILDREN: The main headline and the direct children are shown.
6223 From this state, you can move to one of the children
6224 and zoom in further.
6225 3. SUBTREE: Show the entire subtree, including body text.
6226 If there is no subtree, switch directly from CHILDREN to FOLDED.
6228 - When point is at the beginning of an empty headline and the variable
6229 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6230 of the headline by demoting and promoting it to likely levels. This
6231 speeds up creation document structure by pressing TAB once or several
6232 times right after creating a new headline.
6234 - When there is a numeric prefix, go up to a heading with level ARG, do
6235 a `show-subtree' and return to the previous cursor position. If ARG
6236 is negative, go up that many levels.
6238 - When point is not at the beginning of a headline, execute the global
6239 binding for TAB, which is re-indenting the line. See the option
6240 `org-cycle-emulate-tab' for details.
6242 - Special case: if point is at the beginning of the buffer and there is
6243 no headline in line 1, this function will act as if called with prefix arg
6244 (C-u TAB, same as S-TAB) also when called without prefix arg.
6245 But only if also the variable `org-cycle-global-at-bob' is t."
6246 (interactive "P")
6247 (org-load-modules-maybe)
6248 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6249 (and org-cycle-level-after-item/entry-creation
6250 (or (org-cycle-level)
6251 (org-cycle-item-indentation))))
6252 (let* (message-log-max ; Don't populate the *Messages* buffer
6253 (limit-level
6254 (or org-cycle-max-level
6255 (and (boundp 'org-inlinetask-min-level)
6256 org-inlinetask-min-level
6257 (1- org-inlinetask-min-level))))
6258 (nstars (and limit-level
6259 (if org-odd-levels-only
6260 (and limit-level (1- (* limit-level 2)))
6261 limit-level)))
6262 (org-outline-regexp
6263 (if (not (derived-mode-p 'org-mode))
6264 outline-regexp
6265 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6266 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6267 (not (looking-at org-outline-regexp))))
6268 (org-cycle-hook
6269 (if bob-special
6270 (delq 'org-optimize-window-after-visibility-change
6271 (copy-sequence org-cycle-hook))
6272 org-cycle-hook))
6273 (pos (point)))
6275 (if (or bob-special (equal arg '(4)))
6276 ;; special case: use global cycling
6277 (setq arg t))
6279 (cond
6281 ((equal arg '(16))
6282 (setq last-command 'dummy)
6283 (org-set-startup-visibility)
6284 (message "Startup visibility, plus VISIBILITY properties"))
6286 ((equal arg '(64))
6287 (show-all)
6288 (message "Entire buffer visible, including drawers"))
6290 ;; Table: enter it or move to the next field.
6291 ((org-at-table-p 'any)
6292 (if (org-at-table.el-p)
6293 (message "Use C-c ' to edit table.el tables")
6294 (if arg (org-table-edit-field t)
6295 (org-table-justify-field-maybe)
6296 (call-interactively 'org-table-next-field))))
6298 ((run-hook-with-args-until-success
6299 'org-tab-after-check-for-table-hook))
6301 ;; Global cycling: delegate to `org-cycle-internal-global'.
6302 ((eq arg t) (org-cycle-internal-global))
6304 ;; Drawers: delegate to `org-flag-drawer'.
6305 ((and org-drawers org-drawer-regexp
6306 (save-excursion
6307 (beginning-of-line 1)
6308 (looking-at org-drawer-regexp)))
6309 (org-flag-drawer ; toggle block visibility
6310 (not (get-char-property (match-end 0) 'invisible))))
6312 ;; Show-subtree, ARG levels up from here.
6313 ((integerp arg)
6314 (save-excursion
6315 (org-back-to-heading)
6316 (outline-up-heading (if (< arg 0) (- arg)
6317 (- (funcall outline-level) arg)))
6318 (org-show-subtree)))
6320 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6321 ((and (featurep 'org-inlinetask)
6322 (org-inlinetask-at-task-p)
6323 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6324 (org-inlinetask-toggle-visibility))
6326 ((org-try-cdlatex-tab))
6328 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6329 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6330 (save-excursion (beginning-of-line 1)
6331 (looking-at org-outline-regexp)))
6332 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6333 (org-cycle-internal-local))
6335 ;; From there: TAB emulation and template completion.
6336 (buffer-read-only (org-back-to-heading))
6338 ((run-hook-with-args-until-success
6339 'org-tab-after-check-for-cycling-hook))
6341 ((org-try-structure-completion))
6343 ((run-hook-with-args-until-success
6344 'org-tab-before-tab-emulation-hook))
6346 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6347 (or (not (bolp))
6348 (not (looking-at org-outline-regexp))))
6349 (call-interactively (global-key-binding "\t")))
6351 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6352 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6353 (or (and (eq org-cycle-emulate-tab 'white)
6354 (= (match-end 0) (point-at-eol)))
6355 (and (eq org-cycle-emulate-tab 'whitestart)
6356 (>= (match-end 0) pos))))
6358 (eq org-cycle-emulate-tab t))
6359 (call-interactively (global-key-binding "\t")))
6361 (t (save-excursion
6362 (org-back-to-heading)
6363 (org-cycle)))))))
6365 (defun org-cycle-internal-global ()
6366 "Do the global cycling action."
6367 ;; Hack to avoid display of messages for .org attachments in Gnus
6368 (let (message-log-max ; Don't populate the *Messages* buffer
6369 (ga (string-match "\\*fontification" (buffer-name))))
6370 (cond
6371 ((and (eq last-command this-command)
6372 (eq org-cycle-global-status 'overview))
6373 ;; We just created the overview - now do table of contents
6374 ;; This can be slow in very large buffers, so indicate action
6375 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6376 (unless ga (message "CONTENTS..."))
6377 (org-content)
6378 (unless ga (message "CONTENTS...done"))
6379 (setq org-cycle-global-status 'contents)
6380 (run-hook-with-args 'org-cycle-hook 'contents))
6382 ((and (eq last-command this-command)
6383 (eq org-cycle-global-status 'contents))
6384 ;; We just showed the table of contents - now show everything
6385 (run-hook-with-args 'org-pre-cycle-hook 'all)
6386 (show-all)
6387 (unless ga (message "SHOW ALL"))
6388 (setq org-cycle-global-status 'all)
6389 (run-hook-with-args 'org-cycle-hook 'all))
6392 ;; Default action: go to overview
6393 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6394 (org-overview)
6395 (unless ga (message "OVERVIEW"))
6396 (setq org-cycle-global-status 'overview)
6397 (run-hook-with-args 'org-cycle-hook 'overview)))))
6399 (defun org-cycle-internal-local ()
6400 "Do the local cycling action."
6401 (let (message-log-max ; Don't populate the *Messages* buffer
6402 (goal-column 0) eoh eol eos has-children children-skipped struct)
6403 ;; First, determine end of headline (EOH), end of subtree or item
6404 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6405 (save-excursion
6406 (if (org-at-item-p)
6407 (progn
6408 (beginning-of-line)
6409 (setq struct (org-list-struct))
6410 (setq eoh (point-at-eol))
6411 (setq eos (org-list-get-item-end-before-blank (point) struct))
6412 (setq has-children (org-list-has-child-p (point) struct)))
6413 (org-back-to-heading)
6414 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6415 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6416 (setq has-children
6417 (or (save-excursion
6418 (let ((level (funcall outline-level)))
6419 (outline-next-heading)
6420 (and (org-at-heading-p t)
6421 (> (funcall outline-level) level))))
6422 (save-excursion
6423 (org-list-search-forward (org-item-beginning-re) eos t)))))
6424 ;; Determine end invisible part of buffer (EOL)
6425 (beginning-of-line 2)
6426 ;; XEmacs doesn't have `next-single-char-property-change'
6427 (if (featurep 'xemacs)
6428 (while (and (not (eobp)) ;; this is like `next-line'
6429 (get-char-property (1- (point)) 'invisible))
6430 (beginning-of-line 2))
6431 (while (and (not (eobp)) ;; this is like `next-line'
6432 (get-char-property (1- (point)) 'invisible))
6433 (goto-char (next-single-char-property-change (point) 'invisible))
6434 (and (eolp) (beginning-of-line 2))))
6435 (setq eol (point)))
6436 ;; Find out what to do next and set `this-command'
6437 (cond
6438 ((= eos eoh)
6439 ;; Nothing is hidden behind this heading
6440 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6441 (message "EMPTY ENTRY")
6442 (setq org-cycle-subtree-status nil)
6443 (save-excursion
6444 (goto-char eos)
6445 (outline-next-heading)
6446 (if (outline-invisible-p) (org-flag-heading nil))))
6447 ((and (or (>= eol eos)
6448 (not (string-match "\\S-" (buffer-substring eol eos))))
6449 (or has-children
6450 (not (setq children-skipped
6451 org-cycle-skip-children-state-if-no-children))))
6452 ;; Entire subtree is hidden in one line: children view
6453 (run-hook-with-args 'org-pre-cycle-hook 'children)
6454 (if (org-at-item-p)
6455 (org-list-set-item-visibility (point-at-bol) struct 'children)
6456 (org-show-entry)
6457 (org-with-limited-levels (show-children))
6458 ;; FIXME: This slows down the func way too much.
6459 ;; How keep drawers hidden in subtree anyway?
6460 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6461 ;; (org-cycle-hide-drawers 'subtree))
6463 ;; Fold every list in subtree to top-level items.
6464 (when (eq org-cycle-include-plain-lists 'integrate)
6465 (save-excursion
6466 (org-back-to-heading)
6467 (while (org-list-search-forward (org-item-beginning-re) eos t)
6468 (beginning-of-line 1)
6469 (let* ((struct (org-list-struct))
6470 (prevs (org-list-prevs-alist struct))
6471 (end (org-list-get-bottom-point struct)))
6472 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6473 (org-list-get-all-items (point) struct prevs))
6474 (goto-char end))))))
6475 (message "CHILDREN")
6476 (save-excursion
6477 (goto-char eos)
6478 (outline-next-heading)
6479 (if (outline-invisible-p) (org-flag-heading nil)))
6480 (setq org-cycle-subtree-status 'children)
6481 (run-hook-with-args 'org-cycle-hook 'children))
6482 ((or children-skipped
6483 (and (eq last-command this-command)
6484 (eq org-cycle-subtree-status 'children)))
6485 ;; We just showed the children, or no children are there,
6486 ;; now show everything.
6487 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6488 (outline-flag-region eoh eos nil)
6489 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6490 (setq org-cycle-subtree-status 'subtree)
6491 (run-hook-with-args 'org-cycle-hook 'subtree))
6493 ;; Default action: hide the subtree.
6494 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6495 (outline-flag-region eoh eos t)
6496 (message "FOLDED")
6497 (setq org-cycle-subtree-status 'folded)
6498 (run-hook-with-args 'org-cycle-hook 'folded)))))
6500 ;;;###autoload
6501 (defun org-global-cycle (&optional arg)
6502 "Cycle the global visibility. For details see `org-cycle'.
6503 With \\[universal-argument] prefix arg, switch to startup visibility.
6504 With a numeric prefix, show all headlines up to that level."
6505 (interactive "P")
6506 (let ((org-cycle-include-plain-lists
6507 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6508 (cond
6509 ((integerp arg)
6510 (show-all)
6511 (hide-sublevels arg)
6512 (setq org-cycle-global-status 'contents))
6513 ((equal arg '(4))
6514 (org-set-startup-visibility)
6515 (message "Startup visibility, plus VISIBILITY properties."))
6517 (org-cycle '(4))))))
6519 (defun org-set-startup-visibility ()
6520 "Set the visibility required by startup options and properties."
6521 (cond
6522 ((eq org-startup-folded t)
6523 (org-cycle '(4)))
6524 ((eq org-startup-folded 'content)
6525 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6526 (org-cycle '(4)) (org-cycle '(4)))))
6527 (unless (eq org-startup-folded 'showeverything)
6528 (if org-hide-block-startup (org-hide-block-all))
6529 (org-set-visibility-according-to-property 'no-cleanup)
6530 (org-cycle-hide-archived-subtrees 'all)
6531 (org-cycle-hide-drawers 'all)
6532 (org-cycle-show-empty-lines t)))
6534 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6535 "Switch subtree visibilities according to :VISIBILITY: property."
6536 (interactive)
6537 (let (org-show-entry-below state)
6538 (save-excursion
6539 (goto-char (point-min))
6540 (while (re-search-forward
6541 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6542 nil t)
6543 (setq state (match-string 1))
6544 (save-excursion
6545 (org-back-to-heading t)
6546 (hide-subtree)
6547 (org-reveal)
6548 (cond
6549 ((equal state '("fold" "folded"))
6550 (hide-subtree))
6551 ((equal state "children")
6552 (org-show-hidden-entry)
6553 (show-children))
6554 ((equal state "content")
6555 (save-excursion
6556 (save-restriction
6557 (org-narrow-to-subtree)
6558 (org-content))))
6559 ((member state '("all" "showall"))
6560 (show-subtree)))))
6561 (unless no-cleanup
6562 (org-cycle-hide-archived-subtrees 'all)
6563 (org-cycle-hide-drawers 'all)
6564 (org-cycle-show-empty-lines 'all)))))
6566 ;; This function uses outline-regexp instead of the more fundamental
6567 ;; org-outline-regexp so that org-cycle-global works outside of Org
6568 ;; buffers, where outline-regexp is needed.
6569 (defun org-overview ()
6570 "Switch to overview mode, showing only top-level headlines.
6571 Really, this shows all headlines with level equal or greater than the level
6572 of the first headline in the buffer. This is important, because if the
6573 first headline is not level one, then (hide-sublevels 1) gives confusing
6574 results."
6575 (interactive)
6576 (let ((level (save-excursion
6577 (goto-char (point-min))
6578 (if (re-search-forward (concat "^" outline-regexp) nil t)
6579 (progn
6580 (goto-char (match-beginning 0))
6581 (funcall outline-level))))))
6582 (and level (hide-sublevels level))))
6584 (defun org-content (&optional arg)
6585 "Show all headlines in the buffer, like a table of contents.
6586 With numerical argument N, show content up to level N."
6587 (interactive "P")
6588 (save-excursion
6589 ;; Visit all headings and show their offspring
6590 (and (integerp arg) (org-overview))
6591 (goto-char (point-max))
6592 (catch 'exit
6593 (while (and (progn (condition-case nil
6594 (outline-previous-visible-heading 1)
6595 (error (goto-char (point-min))))
6597 (looking-at org-outline-regexp))
6598 (if (integerp arg)
6599 (show-children (1- arg))
6600 (show-branches))
6601 (if (bobp) (throw 'exit nil))))))
6604 (defun org-optimize-window-after-visibility-change (state)
6605 "Adjust the window after a change in outline visibility.
6606 This function is the default value of the hook `org-cycle-hook'."
6607 (when (get-buffer-window (current-buffer))
6608 (cond
6609 ((eq state 'content) nil)
6610 ((eq state 'all) nil)
6611 ((eq state 'folded) nil)
6612 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6613 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6615 (defun org-remove-empty-overlays-at (pos)
6616 "Remove outline overlays that do not contain non-white stuff."
6617 (mapc
6618 (lambda (o)
6619 (and (eq 'outline (overlay-get o 'invisible))
6620 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6621 (overlay-end o))))
6622 (delete-overlay o)))
6623 (overlays-at pos)))
6625 (defun org-clean-visibility-after-subtree-move ()
6626 "Fix visibility issues after moving a subtree."
6627 ;; First, find a reasonable region to look at:
6628 ;; Start two siblings above, end three below
6629 (let* ((beg (save-excursion
6630 (and (org-get-last-sibling)
6631 (org-get-last-sibling))
6632 (point)))
6633 (end (save-excursion
6634 (and (org-get-next-sibling)
6635 (org-get-next-sibling)
6636 (org-get-next-sibling))
6637 (if (org-at-heading-p)
6638 (point-at-eol)
6639 (point))))
6640 (level (looking-at "\\*+"))
6641 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6642 (save-excursion
6643 (save-restriction
6644 (narrow-to-region beg end)
6645 (when re
6646 ;; Properly fold already folded siblings
6647 (goto-char (point-min))
6648 (while (re-search-forward re nil t)
6649 (if (and (not (outline-invisible-p))
6650 (save-excursion
6651 (goto-char (point-at-eol)) (outline-invisible-p)))
6652 (hide-entry))))
6653 (org-cycle-show-empty-lines 'overview)
6654 (org-cycle-hide-drawers 'overview)))))
6656 (defun org-cycle-show-empty-lines (state)
6657 "Show empty lines above all visible headlines.
6658 The region to be covered depends on STATE when called through
6659 `org-cycle-hook'. Lisp program can use t for STATE to get the
6660 entire buffer covered. Note that an empty line is only shown if there
6661 are at least `org-cycle-separator-lines' empty lines before the headline."
6662 (when (not (= org-cycle-separator-lines 0))
6663 (save-excursion
6664 (let* ((n (abs org-cycle-separator-lines))
6665 (re (cond
6666 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6667 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6668 (t (let ((ns (number-to-string (- n 2))))
6669 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6670 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6671 beg end b e)
6672 (cond
6673 ((memq state '(overview contents t))
6674 (setq beg (point-min) end (point-max)))
6675 ((memq state '(children folded))
6676 (setq beg (point) end (progn (org-end-of-subtree t t)
6677 (beginning-of-line 2)
6678 (point)))))
6679 (when beg
6680 (goto-char beg)
6681 (while (re-search-forward re end t)
6682 (unless (get-char-property (match-end 1) 'invisible)
6683 (setq e (match-end 1))
6684 (if (< org-cycle-separator-lines 0)
6685 (setq b (save-excursion
6686 (goto-char (match-beginning 0))
6687 (org-back-over-empty-lines)
6688 (if (save-excursion
6689 (goto-char (max (point-min) (1- (point))))
6690 (org-at-heading-p))
6691 (1- (point))
6692 (point))))
6693 (setq b (match-beginning 1)))
6694 (outline-flag-region b e nil)))))))
6695 ;; Never hide empty lines at the end of the file.
6696 (save-excursion
6697 (goto-char (point-max))
6698 (outline-previous-heading)
6699 (outline-end-of-heading)
6700 (if (and (looking-at "[ \t\n]+")
6701 (= (match-end 0) (point-max)))
6702 (outline-flag-region (point) (match-end 0) nil))))
6704 (defun org-show-empty-lines-in-parent ()
6705 "Move to the parent and re-show empty lines before visible headlines."
6706 (save-excursion
6707 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6708 (org-cycle-show-empty-lines context))))
6710 (defun org-files-list ()
6711 "Return `org-agenda-files' list, plus all open org-mode files.
6712 This is useful for operations that need to scan all of a user's
6713 open and agenda-wise Org files."
6714 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6715 (dolist (buf (buffer-list))
6716 (with-current-buffer buf
6717 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6718 (let ((file (expand-file-name (buffer-file-name))))
6719 (unless (member file files)
6720 (push file files))))))
6721 files))
6723 (defsubst org-entry-beginning-position ()
6724 "Return the beginning position of the current entry."
6725 (save-excursion (outline-back-to-heading t) (point)))
6727 (defsubst org-entry-end-position ()
6728 "Return the end position of the current entry."
6729 (save-excursion (outline-next-heading) (point)))
6731 (defun org-cycle-hide-drawers (state)
6732 "Re-hide all drawers after a visibility state change."
6733 (when (and (derived-mode-p 'org-mode)
6734 (not (memq state '(overview folded contents))))
6735 (save-excursion
6736 (let* ((globalp (memq state '(contents all)))
6737 (beg (if globalp (point-min) (point)))
6738 (end (if globalp (point-max)
6739 (if (eq state 'children)
6740 (save-excursion (outline-next-heading) (point))
6741 (org-end-of-subtree t)))))
6742 (goto-char beg)
6743 (while (re-search-forward org-drawer-regexp end t)
6744 (org-flag-drawer t))))))
6746 (defun org-cycle-hide-inline-tasks (state)
6747 "Re-hide inline task when switching to 'contents visibility state."
6748 (when (and (eq state 'contents)
6749 (boundp 'org-inlinetask-min-level)
6750 org-inlinetask-min-level)
6751 (hide-sublevels (1- org-inlinetask-min-level))))
6753 (defun org-flag-drawer (flag)
6754 "When FLAG is non-nil, hide the drawer we are within.
6755 Otherwise make it visible."
6756 (save-excursion
6757 (beginning-of-line 1)
6758 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6759 (let ((b (match-end 0)))
6760 (if (re-search-forward
6761 "^[ \t]*:END:"
6762 (save-excursion (outline-next-heading) (point)) t)
6763 (outline-flag-region b (point-at-eol) flag)
6764 (error ":END: line missing at position %s" b))))))
6766 (defun org-subtree-end-visible-p ()
6767 "Is the end of the current subtree visible?"
6768 (pos-visible-in-window-p
6769 (save-excursion (org-end-of-subtree t) (point))))
6771 (defun org-first-headline-recenter (&optional N)
6772 "Move cursor to the first headline and recenter the headline.
6773 Optional argument N means put the headline into the Nth line of the window."
6774 (goto-char (point-min))
6775 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6776 (beginning-of-line)
6777 (recenter (prefix-numeric-value N))))
6779 ;;; Saving and restoring visibility
6781 (defun org-outline-overlay-data (&optional use-markers)
6782 "Return a list of the locations of all outline overlays.
6783 These are overlays with the `invisible' property value `outline'.
6784 The return value is a list of cons cells, with start and stop
6785 positions for each overlay.
6786 If USE-MARKERS is set, return the positions as markers."
6787 (let (beg end)
6788 (save-excursion
6789 (save-restriction
6790 (widen)
6791 (delq nil
6792 (mapcar (lambda (o)
6793 (when (eq (overlay-get o 'invisible) 'outline)
6794 (setq beg (overlay-start o)
6795 end (overlay-end o))
6796 (and beg end (> end beg)
6797 (if use-markers
6798 (cons (move-marker (make-marker) beg)
6799 (move-marker (make-marker) end))
6800 (cons beg end)))))
6801 (overlays-in (point-min) (point-max))))))))
6803 (defun org-set-outline-overlay-data (data)
6804 "Create visibility overlays for all positions in DATA.
6805 DATA should have been made by `org-outline-overlay-data'."
6806 (let (o)
6807 (save-excursion
6808 (save-restriction
6809 (widen)
6810 (show-all)
6811 (mapc (lambda (c)
6812 (outline-flag-region (car c) (cdr c) t))
6813 data)))))
6815 ;;; Folding of blocks
6817 (defvar org-hide-block-overlays nil
6818 "Overlays hiding blocks.")
6819 (make-variable-buffer-local 'org-hide-block-overlays)
6821 (defun org-block-map (function &optional start end)
6822 "Call FUNCTION at the head of all source blocks in the current buffer.
6823 Optional arguments START and END can be used to limit the range."
6824 (let ((start (or start (point-min)))
6825 (end (or end (point-max))))
6826 (save-excursion
6827 (goto-char start)
6828 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6829 (save-excursion
6830 (save-match-data
6831 (goto-char (match-beginning 0))
6832 (funcall function)))))))
6834 (defun org-hide-block-toggle-all ()
6835 "Toggle the visibility of all blocks in the current buffer."
6836 (org-block-map #'org-hide-block-toggle))
6838 (defun org-hide-block-all ()
6839 "Fold all blocks in the current buffer."
6840 (interactive)
6841 (org-show-block-all)
6842 (org-block-map #'org-hide-block-toggle-maybe))
6844 (defun org-show-block-all ()
6845 "Unfold all blocks in the current buffer."
6846 (interactive)
6847 (mapc 'delete-overlay org-hide-block-overlays)
6848 (setq org-hide-block-overlays nil))
6850 (defun org-hide-block-toggle-maybe ()
6851 "Toggle visibility of block at point."
6852 (interactive)
6853 (let ((case-fold-search t))
6854 (if (save-excursion
6855 (beginning-of-line 1)
6856 (looking-at org-block-regexp))
6857 (progn (org-hide-block-toggle)
6858 t) ;; to signal that we took action
6859 nil))) ;; to signal that we did not
6861 (defun org-hide-block-toggle (&optional force)
6862 "Toggle the visibility of the current block."
6863 (interactive)
6864 (save-excursion
6865 (beginning-of-line)
6866 (if (re-search-forward org-block-regexp nil t)
6867 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6868 (end (match-end 0)) ;; end of entire body
6870 (if (memq t (mapcar (lambda (overlay)
6871 (eq (overlay-get overlay 'invisible)
6872 'org-hide-block))
6873 (overlays-at start)))
6874 (if (or (not force) (eq force 'off))
6875 (mapc (lambda (ov)
6876 (when (member ov org-hide-block-overlays)
6877 (setq org-hide-block-overlays
6878 (delq ov org-hide-block-overlays)))
6879 (when (eq (overlay-get ov 'invisible)
6880 'org-hide-block)
6881 (delete-overlay ov)))
6882 (overlays-at start)))
6883 (setq ov (make-overlay start end))
6884 (overlay-put ov 'invisible 'org-hide-block)
6885 ;; make the block accessible to isearch
6886 (overlay-put
6887 ov 'isearch-open-invisible
6888 (lambda (ov)
6889 (when (member ov org-hide-block-overlays)
6890 (setq org-hide-block-overlays
6891 (delq ov org-hide-block-overlays)))
6892 (when (eq (overlay-get ov 'invisible)
6893 'org-hide-block)
6894 (delete-overlay ov))))
6895 (push ov org-hide-block-overlays)))
6896 (error "Not looking at a source block"))))
6898 ;; org-tab-after-check-for-cycling-hook
6899 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6900 ;; Remove overlays when changing major mode
6901 (add-hook 'org-mode-hook
6902 (lambda () (org-add-hook 'change-major-mode-hook
6903 'org-show-block-all 'append 'local)))
6905 ;;; Org-goto
6907 (defvar org-goto-window-configuration nil)
6908 (defvar org-goto-marker nil)
6909 (defvar org-goto-map
6910 (let ((map (make-sparse-keymap)))
6911 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6912 (while (setq cmd (pop cmds))
6913 (substitute-key-definition cmd cmd map global-map)))
6914 (suppress-keymap map)
6915 (org-defkey map "\C-m" 'org-goto-ret)
6916 (org-defkey map [(return)] 'org-goto-ret)
6917 (org-defkey map [(left)] 'org-goto-left)
6918 (org-defkey map [(right)] 'org-goto-right)
6919 (org-defkey map [(control ?g)] 'org-goto-quit)
6920 (org-defkey map "\C-i" 'org-cycle)
6921 (org-defkey map [(tab)] 'org-cycle)
6922 (org-defkey map [(down)] 'outline-next-visible-heading)
6923 (org-defkey map [(up)] 'outline-previous-visible-heading)
6924 (if org-goto-auto-isearch
6925 (if (fboundp 'define-key-after)
6926 (define-key-after map [t] 'org-goto-local-auto-isearch)
6927 nil)
6928 (org-defkey map "q" 'org-goto-quit)
6929 (org-defkey map "n" 'outline-next-visible-heading)
6930 (org-defkey map "p" 'outline-previous-visible-heading)
6931 (org-defkey map "f" 'outline-forward-same-level)
6932 (org-defkey map "b" 'outline-backward-same-level)
6933 (org-defkey map "u" 'outline-up-heading))
6934 (org-defkey map "/" 'org-occur)
6935 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6936 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6937 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6938 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6939 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6940 map))
6942 (defconst org-goto-help
6943 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6944 RET=jump to location [Q]uit and return to previous location
6945 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6947 (defvar org-goto-start-pos) ; dynamically scoped parameter
6949 ;; FIXME: Docstring does not mention both interfaces
6950 (defun org-goto (&optional alternative-interface)
6951 "Look up a different location in the current file, keeping current visibility.
6953 When you want look-up or go to a different location in a
6954 document, the fastest way is often to fold the entire buffer and
6955 then dive into the tree. This method has the disadvantage, that
6956 the previous location will be folded, which may not be what you
6957 want.
6959 This command works around this by showing a copy of the current
6960 buffer in an indirect buffer, in overview mode. You can dive
6961 into the tree in that copy, use org-occur and incremental search
6962 to find a location. When pressing RET or `Q', the command
6963 returns to the original buffer in which the visibility is still
6964 unchanged. After RET it will also jump to the location selected
6965 in the indirect buffer and expose the headline hierarchy above.
6967 With a prefix argument, use the alternative interface: e.g. if
6968 `org-goto-interface' is 'outline use 'outline-path-completion."
6969 (interactive "P")
6970 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6971 (org-refile-use-outline-path t)
6972 (org-refile-target-verify-function nil)
6973 (interface
6974 (if (not alternative-interface)
6975 org-goto-interface
6976 (if (eq org-goto-interface 'outline)
6977 'outline-path-completion
6978 'outline)))
6979 (org-goto-start-pos (point))
6980 (selected-point
6981 (if (eq interface 'outline)
6982 (car (org-get-location (current-buffer) org-goto-help))
6983 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6984 (org-refile-check-position pa)
6985 (nth 3 pa)))))
6986 (if selected-point
6987 (progn
6988 (org-mark-ring-push org-goto-start-pos)
6989 (goto-char selected-point)
6990 (if (or (outline-invisible-p) (org-invisible-p2))
6991 (org-show-context 'org-goto)))
6992 (message "Quit"))))
6994 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6995 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6996 (defvar org-goto-local-auto-isearch-map) ; defined below
6998 (defun org-get-location (buf help)
6999 "Let the user select a location in the Org-mode buffer BUF.
7000 This function uses a recursive edit. It returns the selected position
7001 or nil."
7002 (org-no-popups
7003 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7004 (isearch-hide-immediately nil)
7005 (isearch-search-fun-function
7006 (lambda () 'org-goto-local-search-headings))
7007 (org-goto-selected-point org-goto-exit-command))
7008 (save-excursion
7009 (save-window-excursion
7010 (delete-other-windows)
7011 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7012 (org-pop-to-buffer-same-window
7013 (condition-case nil
7014 (make-indirect-buffer (current-buffer) "*org-goto*")
7015 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7016 (with-output-to-temp-buffer "*Help*"
7017 (princ help))
7018 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7019 (setq buffer-read-only nil)
7020 (let ((org-startup-truncated t)
7021 (org-startup-folded nil)
7022 (org-startup-align-all-tables nil))
7023 (org-mode)
7024 (org-overview))
7025 (setq buffer-read-only t)
7026 (if (and (boundp 'org-goto-start-pos)
7027 (integer-or-marker-p org-goto-start-pos))
7028 (let ((org-show-hierarchy-above t)
7029 (org-show-siblings t)
7030 (org-show-following-heading t))
7031 (goto-char org-goto-start-pos)
7032 (and (outline-invisible-p) (org-show-context)))
7033 (goto-char (point-min)))
7034 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7035 (message "Select location and press RET")
7036 (use-local-map org-goto-map)
7037 (recursive-edit)
7039 (kill-buffer "*org-goto*")
7040 (cons org-goto-selected-point org-goto-exit-command))))
7042 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7043 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7044 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7045 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7047 (defun org-goto-local-search-headings (string bound noerror)
7048 "Search and make sure that any matches are in headlines."
7049 (catch 'return
7050 (while (if isearch-forward
7051 (search-forward string bound noerror)
7052 (search-backward string bound noerror))
7053 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7054 (and (member :headline context)
7055 (not (member :tags context))))
7056 (throw 'return (point))))))
7058 (defun org-goto-local-auto-isearch ()
7059 "Start isearch."
7060 (interactive)
7061 (goto-char (point-min))
7062 (let ((keys (this-command-keys)))
7063 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7064 (isearch-mode t)
7065 (isearch-process-search-char (string-to-char keys)))))
7067 (defun org-goto-ret (&optional arg)
7068 "Finish `org-goto' by going to the new location."
7069 (interactive "P")
7070 (setq org-goto-selected-point (point)
7071 org-goto-exit-command 'return)
7072 (throw 'exit nil))
7074 (defun org-goto-left ()
7075 "Finish `org-goto' by going to the new location."
7076 (interactive)
7077 (if (org-at-heading-p)
7078 (progn
7079 (beginning-of-line 1)
7080 (setq org-goto-selected-point (point)
7081 org-goto-exit-command 'left)
7082 (throw 'exit nil))
7083 (error "Not on a heading")))
7085 (defun org-goto-right ()
7086 "Finish `org-goto' by going to the new location."
7087 (interactive)
7088 (if (org-at-heading-p)
7089 (progn
7090 (setq org-goto-selected-point (point)
7091 org-goto-exit-command 'right)
7092 (throw 'exit nil))
7093 (error "Not on a heading")))
7095 (defun org-goto-quit ()
7096 "Finish `org-goto' without cursor motion."
7097 (interactive)
7098 (setq org-goto-selected-point nil)
7099 (setq org-goto-exit-command 'quit)
7100 (throw 'exit nil))
7102 ;;; Indirect buffer display of subtrees
7104 (defvar org-indirect-dedicated-frame nil
7105 "This is the frame being used for indirect tree display.")
7106 (defvar org-last-indirect-buffer nil)
7108 (defun org-tree-to-indirect-buffer (&optional arg)
7109 "Create indirect buffer and narrow it to current subtree.
7110 With a numerical prefix ARG, go up to this level and then take that tree.
7111 If ARG is negative, go up that many levels.
7113 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7114 indirect buffer previously made with this command, to avoid proliferation of
7115 indirect buffers. However, when you call the command with a \
7116 \\[universal-argument] prefix, or
7117 when `org-indirect-buffer-display' is `new-frame', the last buffer
7118 is kept so that you can work with several indirect buffers at the same time.
7119 If `org-indirect-buffer-display' is `dedicated-frame', the \
7120 \\[universal-argument] prefix also
7121 requests that a new frame be made for the new buffer, so that the dedicated
7122 frame is not changed."
7123 (interactive "P")
7124 (let ((cbuf (current-buffer))
7125 (cwin (selected-window))
7126 (pos (point))
7127 beg end level heading ibuf)
7128 (save-excursion
7129 (org-back-to-heading t)
7130 (when (numberp arg)
7131 (setq level (org-outline-level))
7132 (if (< arg 0) (setq arg (+ level arg)))
7133 (while (> (setq level (org-outline-level)) arg)
7134 (org-up-heading-safe)))
7135 (setq beg (point)
7136 heading (org-get-heading))
7137 (org-end-of-subtree t t)
7138 (if (org-at-heading-p) (backward-char 1))
7139 (setq end (point)))
7140 (if (and (buffer-live-p org-last-indirect-buffer)
7141 (not (eq org-indirect-buffer-display 'new-frame))
7142 (not arg))
7143 (kill-buffer org-last-indirect-buffer))
7144 (setq ibuf (org-get-indirect-buffer cbuf)
7145 org-last-indirect-buffer ibuf)
7146 (cond
7147 ((or (eq org-indirect-buffer-display 'new-frame)
7148 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7149 (select-frame (make-frame))
7150 (delete-other-windows)
7151 (org-pop-to-buffer-same-window ibuf)
7152 (org-set-frame-title heading))
7153 ((eq org-indirect-buffer-display 'dedicated-frame)
7154 (raise-frame
7155 (select-frame (or (and org-indirect-dedicated-frame
7156 (frame-live-p org-indirect-dedicated-frame)
7157 org-indirect-dedicated-frame)
7158 (setq org-indirect-dedicated-frame (make-frame)))))
7159 (delete-other-windows)
7160 (org-pop-to-buffer-same-window ibuf)
7161 (org-set-frame-title (concat "Indirect: " heading)))
7162 ((eq org-indirect-buffer-display 'current-window)
7163 (org-pop-to-buffer-same-window ibuf))
7164 ((eq org-indirect-buffer-display 'other-window)
7165 (pop-to-buffer ibuf))
7166 (t (error "Invalid value")))
7167 (if (featurep 'xemacs)
7168 (save-excursion (org-mode) (turn-on-font-lock)))
7169 (narrow-to-region beg end)
7170 (show-all)
7171 (goto-char pos)
7172 (run-hook-with-args 'org-cycle-hook 'all)
7173 (and (window-live-p cwin) (select-window cwin))))
7175 (defun org-get-indirect-buffer (&optional buffer)
7176 (setq buffer (or buffer (current-buffer)))
7177 (let ((n 1) (base (buffer-name buffer)) bname)
7178 (while (buffer-live-p
7179 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7180 (setq n (1+ n)))
7181 (condition-case nil
7182 (make-indirect-buffer buffer bname 'clone)
7183 (error (make-indirect-buffer buffer bname)))))
7185 (defun org-set-frame-title (title)
7186 "Set the title of the current frame to the string TITLE."
7187 ;; FIXME: how to name a single frame in XEmacs???
7188 (unless (featurep 'xemacs)
7189 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7191 ;;;; Structure editing
7193 ;;; Inserting headlines
7195 (defun org-previous-line-empty-p ()
7196 (save-excursion
7197 (and (not (bobp))
7198 (or (beginning-of-line 0) t)
7199 (save-match-data
7200 (looking-at "[ \t]*$")))))
7202 (defun org-insert-heading (&optional force-heading invisible-ok)
7203 "Insert a new heading or item with same depth at point.
7204 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7205 If point is at the beginning of a headline, insert a sibling before the
7206 current headline. If point is not at the beginning, split the line,
7207 create the new headline with the text in the current line after point
7208 \(but see also the variable `org-M-RET-may-split-line').
7210 With a double prefix arg, force the heading to be inserted at the
7211 end of the parent subtree.
7213 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7214 This is important for non-interactive uses of the command."
7215 (interactive "P")
7216 (if (or (= (buffer-size) 0)
7217 (and (not (save-excursion
7218 (and (ignore-errors (org-back-to-heading invisible-ok))
7219 (org-at-heading-p))))
7220 (or force-heading (not (org-in-item-p)))))
7221 (progn
7222 (insert "\n* ")
7223 (run-hooks 'org-insert-heading-hook))
7224 (when (or force-heading (not (org-insert-item)))
7225 (let* ((empty-line-p nil)
7226 (level nil)
7227 (on-heading (org-at-heading-p))
7228 (head (save-excursion
7229 (condition-case nil
7230 (progn
7231 (org-back-to-heading invisible-ok)
7232 (when (and (not on-heading)
7233 (featurep 'org-inlinetask)
7234 (integerp org-inlinetask-min-level)
7235 (>= (length (match-string 0))
7236 org-inlinetask-min-level))
7237 ;; Find a heading level before the inline task
7238 (while (and (setq level (org-up-heading-safe))
7239 (>= level org-inlinetask-min-level)))
7240 (if (org-at-heading-p)
7241 (org-back-to-heading invisible-ok)
7242 (error "This should not happen")))
7243 (setq empty-line-p (org-previous-line-empty-p))
7244 (match-string 0))
7245 (error "*"))))
7246 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7247 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7248 pos hide-previous previous-pos)
7249 (cond
7250 ((and (org-at-heading-p) (bolp)
7251 (or (bobp)
7252 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7253 ;; insert before the current line
7254 (open-line (if blank 2 1)))
7255 ((and (bolp)
7256 (not org-insert-heading-respect-content)
7257 (or (bobp)
7258 (save-excursion
7259 (backward-char 1) (not (outline-invisible-p)))))
7260 ;; insert right here
7261 nil)
7263 ;; somewhere in the line
7264 (save-excursion
7265 (setq previous-pos (point-at-bol))
7266 (end-of-line)
7267 (setq hide-previous (outline-invisible-p)))
7268 (and org-insert-heading-respect-content (org-show-subtree))
7269 (let ((split
7270 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7271 (save-excursion
7272 (let ((p (point)))
7273 (goto-char (point-at-bol))
7274 (and (looking-at org-complex-heading-regexp)
7275 (match-beginning 4)
7276 (> p (match-beginning 4)))))))
7277 tags pos)
7278 (cond
7279 (org-insert-heading-respect-content
7280 (if (not (equal force-heading '(16)))
7281 (org-end-of-subtree nil t)
7282 (org-up-heading-safe)
7283 (org-end-of-subtree nil t))
7284 (when (featurep 'org-inlinetask)
7285 (while (and (not (eobp))
7286 (looking-at "\\(\\*+\\)[ \t]+")
7287 (>= (length (match-string 1))
7288 org-inlinetask-min-level))
7289 (org-end-of-subtree nil t)))
7290 (or (bolp) (newline))
7291 (or (org-previous-line-empty-p)
7292 (and blank (newline)))
7293 (open-line 1))
7294 ((org-at-heading-p)
7295 (when hide-previous
7296 (show-children)
7297 (org-show-entry))
7298 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7299 (setq tags (and (match-end 2) (match-string 2)))
7300 (and (match-end 1)
7301 (delete-region (match-beginning 1) (match-end 1)))
7302 (setq pos (point-at-bol))
7303 (or split (end-of-line 1))
7304 (delete-horizontal-space)
7305 (if (string-match "\\`\\*+\\'"
7306 (buffer-substring (point-at-bol) (point)))
7307 (insert " "))
7308 (newline (if blank 2 1))
7309 (when tags
7310 (save-excursion
7311 (goto-char pos)
7312 (end-of-line 1)
7313 (insert " " tags)
7314 (org-set-tags nil 'align))))
7316 (or split (end-of-line 1))
7317 (newline (if blank 2 1)))))))
7318 (insert head) (just-one-space)
7319 (setq pos (point))
7320 (end-of-line 1)
7321 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7322 (when (and org-insert-heading-respect-content hide-previous)
7323 (save-excursion
7324 (goto-char previous-pos)
7325 (hide-subtree)))
7326 (run-hooks 'org-insert-heading-hook)))))
7328 (defun org-get-heading (&optional no-tags no-todo)
7329 "Return the heading of the current entry, without the stars.
7330 When NO-TAGS is non-nil, don't include tags.
7331 When NO-TODO is non-nil, don't include TODO keywords."
7332 (save-excursion
7333 (org-back-to-heading t)
7334 (cond
7335 ((and no-tags no-todo)
7336 (looking-at org-complex-heading-regexp)
7337 (match-string 4))
7338 (no-tags
7339 (looking-at (concat org-outline-regexp
7340 "\\(.*?\\)"
7341 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7342 (match-string 1))
7343 (no-todo
7344 (looking-at org-todo-line-regexp)
7345 (match-string 3))
7346 (t (looking-at org-heading-regexp)
7347 (match-string 2)))))
7349 (defun org-heading-components ()
7350 "Return the components of the current heading.
7351 This is a list with the following elements:
7352 - the level as an integer
7353 - the reduced level, different if `org-odd-levels-only' is set.
7354 - the TODO keyword, or nil
7355 - the priority character, like ?A, or nil if no priority is given
7356 - the headline text itself, or the tags string if no headline text
7357 - the tags string, or nil."
7358 (save-excursion
7359 (org-back-to-heading t)
7360 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7361 (list (length (match-string 1))
7362 (org-reduced-level (length (match-string 1)))
7363 (org-match-string-no-properties 2)
7364 (and (match-end 3) (aref (match-string 3) 2))
7365 (org-match-string-no-properties 4)
7366 (org-match-string-no-properties 5)))))
7368 (defun org-get-entry ()
7369 "Get the entry text, after heading, entire subtree."
7370 (save-excursion
7371 (org-back-to-heading t)
7372 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7374 (defun org-insert-heading-after-current ()
7375 "Insert a new heading with same level as current, after current subtree."
7376 (interactive)
7377 (org-back-to-heading)
7378 (org-insert-heading)
7379 (org-move-subtree-down)
7380 (end-of-line 1))
7382 (defun org-insert-heading-respect-content ()
7383 (interactive)
7384 (let ((org-insert-heading-respect-content t))
7385 (org-insert-heading t)))
7387 (defun org-insert-todo-heading-respect-content (&optional force-state)
7388 (interactive "P")
7389 (let ((org-insert-heading-respect-content t))
7390 (org-insert-todo-heading force-state t)))
7392 (defun org-insert-todo-heading (arg &optional force-heading)
7393 "Insert a new heading with the same level and TODO state as current heading.
7394 If the heading has no TODO state, or if the state is DONE, use the first
7395 state (TODO by default). Also one prefix arg, force first state. With two
7396 prefix args, force inserting at the end of the parent subtree."
7397 (interactive "P")
7398 (when (or force-heading (not (org-insert-item 'checkbox)))
7399 (org-insert-heading (or (and (equal arg '(16)) '(16))
7400 force-heading))
7401 (save-excursion
7402 (org-back-to-heading)
7403 (outline-previous-heading)
7404 (looking-at org-todo-line-regexp))
7405 (let*
7406 ((new-mark-x
7407 (if (or arg
7408 (not (match-beginning 2))
7409 (member (match-string 2) org-done-keywords))
7410 (car org-todo-keywords-1)
7411 (match-string 2)))
7412 (new-mark
7414 (run-hook-with-args-until-success
7415 'org-todo-get-default-hook new-mark-x nil)
7416 new-mark-x)))
7417 (beginning-of-line 1)
7418 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7419 (if org-treat-insert-todo-heading-as-state-change
7420 (org-todo new-mark)
7421 (insert new-mark " "))))
7422 (when org-provide-todo-statistics
7423 (org-update-parent-todo-statistics))))
7425 (defun org-insert-subheading (arg)
7426 "Insert a new subheading and demote it.
7427 Works for outline headings and for plain lists alike."
7428 (interactive "P")
7429 (org-insert-heading arg)
7430 (cond
7431 ((org-at-heading-p) (org-do-demote))
7432 ((org-at-item-p) (org-indent-item))))
7434 (defun org-insert-todo-subheading (arg)
7435 "Insert a new subheading with TODO keyword or checkbox and demote it.
7436 Works for outline headings and for plain lists alike."
7437 (interactive "P")
7438 (org-insert-todo-heading arg)
7439 (cond
7440 ((org-at-heading-p) (org-do-demote))
7441 ((org-at-item-p) (org-indent-item))))
7443 ;;; Promotion and Demotion
7445 (defvar org-after-demote-entry-hook nil
7446 "Hook run after an entry has been demoted.
7447 The cursor will be at the beginning of the entry.
7448 When a subtree is being demoted, the hook will be called for each node.")
7450 (defvar org-after-promote-entry-hook nil
7451 "Hook run after an entry has been promoted.
7452 The cursor will be at the beginning of the entry.
7453 When a subtree is being promoted, the hook will be called for each node.")
7455 (defun org-promote-subtree ()
7456 "Promote the entire subtree.
7457 See also `org-promote'."
7458 (interactive)
7459 (save-excursion
7460 (org-with-limited-levels (org-map-tree 'org-promote)))
7461 (org-fix-position-after-promote))
7463 (defun org-demote-subtree ()
7464 "Demote the entire subtree. See `org-demote'.
7465 See also `org-promote'."
7466 (interactive)
7467 (save-excursion
7468 (org-with-limited-levels (org-map-tree 'org-demote)))
7469 (org-fix-position-after-promote))
7472 (defun org-do-promote ()
7473 "Promote the current heading higher up the tree.
7474 If the region is active in `transient-mark-mode', promote all headings
7475 in the region."
7476 (interactive)
7477 (save-excursion
7478 (if (org-region-active-p)
7479 (org-map-region 'org-promote (region-beginning) (region-end))
7480 (org-promote)))
7481 (org-fix-position-after-promote))
7483 (defun org-do-demote ()
7484 "Demote the current heading lower down the tree.
7485 If the region is active in `transient-mark-mode', demote all headings
7486 in the region."
7487 (interactive)
7488 (save-excursion
7489 (if (org-region-active-p)
7490 (org-map-region 'org-demote (region-beginning) (region-end))
7491 (org-demote)))
7492 (org-fix-position-after-promote))
7494 (defun org-fix-position-after-promote ()
7495 "Make sure that after pro/demotion cursor position is right."
7496 (let ((pos (point)))
7497 (when (save-excursion
7498 (beginning-of-line 1)
7499 (looking-at org-todo-line-regexp)
7500 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7501 (cond ((eobp) (insert " "))
7502 ((eolp) (insert " "))
7503 ((equal (char-after) ?\ ) (forward-char 1))))))
7505 (defun org-current-level ()
7506 "Return the level of the current entry, or nil if before the first headline.
7507 The level is the number of stars at the beginning of the headline."
7508 (save-excursion
7509 (org-with-limited-levels
7510 (if (ignore-errors (org-back-to-heading t))
7511 (funcall outline-level)))))
7513 (defun org-get-previous-line-level ()
7514 "Return the outline depth of the last headline before the current line.
7515 Returns 0 for the first headline in the buffer, and nil if before the
7516 first headline."
7517 (let ((current-level (org-current-level))
7518 (prev-level (when (> (line-number-at-pos) 1)
7519 (save-excursion
7520 (beginning-of-line 0)
7521 (org-current-level)))))
7522 (cond ((null current-level) nil) ; Before first headline
7523 ((null prev-level) 0) ; At first headline
7524 (prev-level))))
7526 (defun org-reduced-level (l)
7527 "Compute the effective level of a heading.
7528 This takes into account the setting of `org-odd-levels-only'."
7529 (cond
7530 ((zerop l) 0)
7531 (org-odd-levels-only (1+ (floor (/ l 2))))
7532 (t l)))
7534 (defun org-level-increment ()
7535 "Return the number of stars that will be added or removed at a
7536 time to headlines when structure editing, based on the value of
7537 `org-odd-levels-only'."
7538 (if org-odd-levels-only 2 1))
7540 (defun org-get-valid-level (level &optional change)
7541 "Rectify a level change under the influence of `org-odd-levels-only'
7542 LEVEL is a current level, CHANGE is by how much the level should be
7543 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7544 even level numbers will become the next higher odd number."
7545 (if org-odd-levels-only
7546 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7547 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7548 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7549 (max 1 (+ level (or change 0)))))
7551 (if (boundp 'define-obsolete-function-alias)
7552 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7553 (define-obsolete-function-alias 'org-get-legal-level
7554 'org-get-valid-level)
7555 (define-obsolete-function-alias 'org-get-legal-level
7556 'org-get-valid-level "23.1")))
7558 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7559 ;; ̀org-with-limited-levels'
7560 (defun org-promote ()
7561 "Promote the current heading higher up the tree.
7562 If the region is active in `transient-mark-mode', promote 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 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7569 (diff (abs (- level (length up-head) -1))))
7570 (cond ((and (= level 1) org-called-with-limited-levels
7571 org-allow-promoting-top-level-subtree)
7572 (replace-match "# " nil t))
7573 ((= level 1)
7574 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7575 (t (replace-match up-head nil t)))
7576 ;; Fixup tag positioning
7577 (unless (= level 1)
7578 (and org-auto-align-tags (org-set-tags nil t))
7579 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7580 (run-hooks 'org-after-promote-entry-hook)))
7582 (defun org-demote ()
7583 "Demote the current heading lower down the tree.
7584 If the region is active in `transient-mark-mode', demote all headings
7585 in the region."
7586 (org-back-to-heading t)
7587 (let* ((level (save-match-data (funcall outline-level)))
7588 (after-change-functions (remove 'flyspell-after-change-function
7589 after-change-functions))
7590 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7591 (diff (abs (- level (length down-head) -1))))
7592 (replace-match down-head nil t)
7593 ;; Fixup tag positioning
7594 (and org-auto-align-tags (org-set-tags nil t))
7595 (if org-adapt-indentation (org-fixup-indentation diff))
7596 (run-hooks 'org-after-demote-entry-hook)))
7598 (defun org-cycle-level ()
7599 "Cycle the level of an empty headline through possible states.
7600 This goes first to child, then to parent, level, then up the hierarchy.
7601 After top level, it switches back to sibling level."
7602 (interactive)
7603 (let ((org-adapt-indentation nil))
7604 (when (org-point-at-end-of-empty-headline)
7605 (setq this-command 'org-cycle-level) ; Only needed for caching
7606 (let ((cur-level (org-current-level))
7607 (prev-level (org-get-previous-line-level)))
7608 (cond
7609 ;; If first headline in file, promote to top-level.
7610 ((= prev-level 0)
7611 (loop repeat (/ (- cur-level 1) (org-level-increment))
7612 do (org-do-promote)))
7613 ;; If same level as prev, demote one.
7614 ((= prev-level cur-level)
7615 (org-do-demote))
7616 ;; If parent is top-level, promote to top level if not already.
7617 ((= prev-level 1)
7618 (loop repeat (/ (- cur-level 1) (org-level-increment))
7619 do (org-do-promote)))
7620 ;; If top-level, return to prev-level.
7621 ((= cur-level 1)
7622 (loop repeat (/ (- prev-level 1) (org-level-increment))
7623 do (org-do-demote)))
7624 ;; If less than prev-level, promote one.
7625 ((< cur-level prev-level)
7626 (org-do-promote))
7627 ;; If deeper than prev-level, promote until higher than
7628 ;; prev-level.
7629 ((> cur-level prev-level)
7630 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7631 do (org-do-promote))))
7632 t))))
7634 (defun org-map-tree (fun)
7635 "Call FUN for every heading underneath the current one."
7636 (org-back-to-heading)
7637 (let ((level (funcall outline-level)))
7638 (save-excursion
7639 (funcall fun)
7640 (while (and (progn
7641 (outline-next-heading)
7642 (> (funcall outline-level) level))
7643 (not (eobp)))
7644 (funcall fun)))))
7646 (defun org-map-region (fun beg end)
7647 "Call FUN for every heading between BEG and END."
7648 (let ((org-ignore-region t))
7649 (save-excursion
7650 (setq end (copy-marker end))
7651 (goto-char beg)
7652 (if (and (re-search-forward org-outline-regexp-bol nil t)
7653 (< (point) end))
7654 (funcall fun))
7655 (while (and (progn
7656 (outline-next-heading)
7657 (< (point) end))
7658 (not (eobp)))
7659 (funcall fun)))))
7661 (defvar org-property-end-re) ; silence byte-compiler
7662 (defun org-fixup-indentation (diff)
7663 "Change the indentation in the current entry by DIFF.
7664 However, if any line in the current entry has no indentation, or if it
7665 would end up with no indentation after the change, nothing at all is done."
7666 (save-excursion
7667 (let ((end (save-excursion (outline-next-heading)
7668 (point-marker)))
7669 (prohibit (if (> diff 0)
7670 "^\\S-"
7671 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7672 col)
7673 (unless (save-excursion (end-of-line 1)
7674 (re-search-forward prohibit end t))
7675 (while (and (< (point) end)
7676 (re-search-forward "^[ \t]+" end t))
7677 (goto-char (match-end 0))
7678 (setq col (current-column))
7679 (if (< diff 0) (replace-match ""))
7680 (org-indent-to-column (+ diff col))))
7681 (move-marker end nil))))
7683 (defun org-convert-to-odd-levels ()
7684 "Convert an org-mode file with all levels allowed to one with odd levels.
7685 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7686 level 5 etc."
7687 (interactive)
7688 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7689 (let ((outline-level 'org-outline-level)
7690 (org-odd-levels-only nil) n)
7691 (save-excursion
7692 (goto-char (point-min))
7693 (while (re-search-forward "^\\*\\*+ " nil t)
7694 (setq n (- (length (match-string 0)) 2))
7695 (while (>= (setq n (1- n)) 0)
7696 (org-demote))
7697 (end-of-line 1))))))
7699 (defun org-convert-to-oddeven-levels ()
7700 "Convert an org-mode file with only odd levels to one with odd/even levels.
7701 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7702 file contains a section with an even level, conversion would
7703 destroy the structure of the file. An error is signaled in this
7704 case."
7705 (interactive)
7706 (goto-char (point-min))
7707 ;; First check if there are no even levels
7708 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7709 (org-show-context t)
7710 (error "Not all levels are odd in this file. Conversion not possible"))
7711 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7712 (let ((outline-regexp org-outline-regexp)
7713 (outline-level 'org-outline-level)
7714 (org-odd-levels-only nil) n)
7715 (save-excursion
7716 (goto-char (point-min))
7717 (while (re-search-forward "^\\*\\*+ " nil t)
7718 (setq n (/ (1- (length (match-string 0))) 2))
7719 (while (>= (setq n (1- n)) 0)
7720 (org-promote))
7721 (end-of-line 1))))))
7723 (defun org-tr-level (n)
7724 "Make N odd if required."
7725 (if org-odd-levels-only (1+ (/ n 2)) n))
7727 ;;; Vertical tree motion, cutting and pasting of subtrees
7729 (defun org-move-subtree-up (&optional arg)
7730 "Move the current subtree up past ARG headlines of the same level."
7731 (interactive "p")
7732 (org-move-subtree-down (- (prefix-numeric-value arg))))
7734 (defun org-move-subtree-down (&optional arg)
7735 "Move the current subtree down past ARG headlines of the same level."
7736 (interactive "p")
7737 (setq arg (prefix-numeric-value arg))
7738 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7739 'org-get-last-sibling))
7740 (ins-point (make-marker))
7741 (cnt (abs arg))
7742 (col (current-column))
7743 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7744 ;; Select the tree
7745 (org-back-to-heading)
7746 (setq beg0 (point))
7747 (save-excursion
7748 (setq ne-beg (org-back-over-empty-lines))
7749 (setq beg (point)))
7750 (save-match-data
7751 (save-excursion (outline-end-of-heading)
7752 (setq folded (outline-invisible-p)))
7753 (outline-end-of-subtree))
7754 (outline-next-heading)
7755 (setq ne-end (org-back-over-empty-lines))
7756 (setq end (point))
7757 (goto-char beg0)
7758 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7759 ;; include less whitespace
7760 (save-excursion
7761 (goto-char beg)
7762 (forward-line (- ne-beg ne-end))
7763 (setq beg (point))))
7764 ;; Find insertion point, with error handling
7765 (while (> cnt 0)
7766 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7767 (progn (goto-char beg0)
7768 (error "Cannot move past superior level or buffer limit")))
7769 (setq cnt (1- cnt)))
7770 (if (> arg 0)
7771 ;; Moving forward - still need to move over subtree
7772 (progn (org-end-of-subtree t t)
7773 (save-excursion
7774 (org-back-over-empty-lines)
7775 (or (bolp) (newline)))))
7776 (setq ne-ins (org-back-over-empty-lines))
7777 (move-marker ins-point (point))
7778 (setq txt (buffer-substring beg end))
7779 (org-save-markers-in-region beg end)
7780 (delete-region beg end)
7781 (org-remove-empty-overlays-at beg)
7782 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7783 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7784 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7785 (let ((bbb (point)))
7786 (insert-before-markers txt)
7787 (org-reinstall-markers-in-region bbb)
7788 (move-marker ins-point bbb))
7789 (or (bolp) (insert "\n"))
7790 (setq ins-end (point))
7791 (goto-char ins-point)
7792 (org-skip-whitespace)
7793 (when (and (< arg 0)
7794 (org-first-sibling-p)
7795 (> ne-ins ne-beg))
7796 ;; Move whitespace back to beginning
7797 (save-excursion
7798 (goto-char ins-end)
7799 (let ((kill-whole-line t))
7800 (kill-line (- ne-ins ne-beg)) (point)))
7801 (insert (make-string (- ne-ins ne-beg) ?\n)))
7802 (move-marker ins-point nil)
7803 (if folded
7804 (hide-subtree)
7805 (org-show-entry)
7806 (show-children)
7807 (org-cycle-hide-drawers 'children))
7808 (org-clean-visibility-after-subtree-move)
7809 ;; move back to the initial column we were at
7810 (move-to-column col)))
7812 (defvar org-subtree-clip ""
7813 "Clipboard for cut and paste of subtrees.
7814 This is actually only a copy of the kill, because we use the normal kill
7815 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7817 (defvar org-subtree-clip-folded nil
7818 "Was the last copied subtree folded?
7819 This is used to fold the tree back after pasting.")
7821 (defun org-cut-subtree (&optional n)
7822 "Cut the current subtree into the clipboard.
7823 With prefix arg N, cut this many sequential subtrees.
7824 This is a short-hand for marking the subtree and then cutting it."
7825 (interactive "p")
7826 (org-copy-subtree n 'cut))
7828 (defun org-copy-subtree (&optional n cut force-store-markers)
7829 "Cut the current subtree into the clipboard.
7830 With prefix arg N, cut this many sequential subtrees.
7831 This is a short-hand for marking the subtree and then copying it.
7832 If CUT is non-nil, actually cut the subtree.
7833 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7834 of some markers in the region, even if CUT is non-nil. This is
7835 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7836 (interactive "p")
7837 (let (beg end folded (beg0 (point)))
7838 (if (org-called-interactively-p 'any)
7839 (org-back-to-heading nil) ; take what looks like a subtree
7840 (org-back-to-heading t)) ; take what is really there
7841 (setq beg (point))
7842 (skip-chars-forward " \t\r\n")
7843 (save-match-data
7844 (save-excursion (outline-end-of-heading)
7845 (setq folded (outline-invisible-p)))
7846 (condition-case nil
7847 (org-forward-heading-same-level (1- n) t)
7848 (error nil))
7849 (org-end-of-subtree t t))
7850 (setq end (point))
7851 (goto-char beg0)
7852 (when (> end beg)
7853 (setq org-subtree-clip-folded folded)
7854 (when (or cut force-store-markers)
7855 (org-save-markers-in-region beg end))
7856 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7857 (setq org-subtree-clip (current-kill 0))
7858 (message "%s: Subtree(s) with %d characters"
7859 (if cut "Cut" "Copied")
7860 (length org-subtree-clip)))))
7862 (defun org-paste-subtree (&optional level tree for-yank)
7863 "Paste the clipboard as a subtree, with modification of headline level.
7864 The entire subtree is promoted or demoted in order to match a new headline
7865 level.
7867 If the cursor is at the beginning of a headline, the same level as
7868 that headline is used to paste the tree
7870 If not, the new level is derived from the *visible* headings
7871 before and after the insertion point, and taken to be the inferior headline
7872 level of the two. So if the previous visible heading is level 3 and the
7873 next is level 4 (or vice versa), level 4 will be used for insertion.
7874 This makes sure that the subtree remains an independent subtree and does
7875 not swallow low level entries.
7877 You can also force a different level, either by using a numeric prefix
7878 argument, or by inserting the heading marker by hand. For example, if the
7879 cursor is after \"*****\", then the tree will be shifted to level 5.
7881 If optional TREE is given, use this text instead of the kill ring.
7883 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7884 move back over whitespace before inserting, and move point to the end of
7885 the inserted text when done."
7886 (interactive "P")
7887 (setq tree (or tree (and kill-ring (current-kill 0))))
7888 (unless (org-kill-is-subtree-p tree)
7889 (error "%s"
7890 (substitute-command-keys
7891 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7892 (org-with-limited-levels
7893 (let* ((visp (not (outline-invisible-p)))
7894 (txt tree)
7895 (^re_ "\\(\\*+\\)[ \t]*")
7896 (old-level (if (string-match org-outline-regexp-bol txt)
7897 (- (match-end 0) (match-beginning 0) 1)
7898 -1))
7899 (force-level (cond (level (prefix-numeric-value level))
7900 ((and (looking-at "[ \t]*$")
7901 (string-match
7902 "^\\*+$" (buffer-substring
7903 (point-at-bol) (point))))
7904 (- (match-end 1) (match-beginning 1)))
7905 ((and (bolp)
7906 (looking-at org-outline-regexp))
7907 (- (match-end 0) (point) 1))))
7908 (previous-level (save-excursion
7909 (condition-case nil
7910 (progn
7911 (outline-previous-visible-heading 1)
7912 (if (looking-at ^re_)
7913 (- (match-end 0) (match-beginning 0) 1)
7915 (error 1))))
7916 (next-level (save-excursion
7917 (condition-case nil
7918 (progn
7919 (or (looking-at org-outline-regexp)
7920 (outline-next-visible-heading 1))
7921 (if (looking-at ^re_)
7922 (- (match-end 0) (match-beginning 0) 1)
7924 (error 1))))
7925 (new-level (or force-level (max previous-level next-level)))
7926 (shift (if (or (= old-level -1)
7927 (= new-level -1)
7928 (= old-level new-level))
7930 (- new-level old-level)))
7931 (delta (if (> shift 0) -1 1))
7932 (func (if (> shift 0) 'org-demote 'org-promote))
7933 (org-odd-levels-only nil)
7934 beg end newend)
7935 ;; Remove the forced level indicator
7936 (if force-level
7937 (delete-region (point-at-bol) (point)))
7938 ;; Paste
7939 (beginning-of-line (if (bolp) 1 2))
7940 (setq beg (point))
7941 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7942 (insert-before-markers txt)
7943 (unless (string-match "\n\\'" txt) (insert "\n"))
7944 (setq newend (point))
7945 (org-reinstall-markers-in-region beg)
7946 (setq end (point))
7947 (goto-char beg)
7948 (skip-chars-forward " \t\n\r")
7949 (setq beg (point))
7950 (if (and (outline-invisible-p) visp)
7951 (save-excursion (outline-show-heading)))
7952 ;; Shift if necessary
7953 (unless (= shift 0)
7954 (save-restriction
7955 (narrow-to-region beg end)
7956 (while (not (= shift 0))
7957 (org-map-region func (point-min) (point-max))
7958 (setq shift (+ delta shift)))
7959 (goto-char (point-min))
7960 (setq newend (point-max))))
7961 (when (or (org-called-interactively-p 'interactive) for-yank)
7962 (message "Clipboard pasted as level %d subtree" new-level))
7963 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7964 kill-ring
7965 (eq org-subtree-clip (current-kill 0))
7966 org-subtree-clip-folded)
7967 ;; The tree was folded before it was killed/copied
7968 (hide-subtree))
7969 (and for-yank (goto-char newend)))))
7971 (defun org-kill-is-subtree-p (&optional txt)
7972 "Check if the current kill is an outline subtree, or a set of trees.
7973 Returns nil if kill does not start with a headline, or if the first
7974 headline level is not the largest headline level in the tree.
7975 So this will actually accept several entries of equal levels as well,
7976 which is OK for `org-paste-subtree'.
7977 If optional TXT is given, check this string instead of the current kill."
7978 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7979 (re (org-get-limited-outline-regexp))
7980 (^re (concat "^" re))
7981 (start-level (and kill
7982 (string-match
7983 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7984 kill)
7985 (- (match-end 2) (match-beginning 2) 1)))
7986 (start (1+ (or (match-beginning 2) -1))))
7987 (if (not start-level)
7988 (progn
7989 nil) ;; does not even start with a heading
7990 (catch 'exit
7991 (while (setq start (string-match ^re kill (1+ start)))
7992 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7993 (throw 'exit nil)))
7994 t))))
7996 (defvar org-markers-to-move nil
7997 "Markers that should be moved with a cut-and-paste operation.
7998 Those markers are stored together with their positions relative to
7999 the start of the region.")
8001 (defun org-save-markers-in-region (beg end)
8002 "Check markers in region.
8003 If these markers are between BEG and END, record their position relative
8004 to BEG, so that after moving the block of text, we can put the markers back
8005 into place.
8006 This function gets called just before an entry or tree gets cut from the
8007 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8008 called immediately, to move the markers with the entries."
8009 (setq org-markers-to-move nil)
8010 (when (featurep 'org-clock)
8011 (org-clock-save-markers-for-cut-and-paste beg end))
8012 (when (featurep 'org-agenda)
8013 (org-agenda-save-markers-for-cut-and-paste beg end)))
8015 (defun org-check-and-save-marker (marker beg end)
8016 "Check if MARKER is between BEG and END.
8017 If yes, remember the marker and the distance to BEG."
8018 (when (and (marker-buffer marker)
8019 (equal (marker-buffer marker) (current-buffer)))
8020 (if (and (>= marker beg) (< marker end))
8021 (push (cons marker (- marker beg)) org-markers-to-move))))
8023 (defun org-reinstall-markers-in-region (beg)
8024 "Move all remembered markers to their position relative to BEG."
8025 (mapc (lambda (x)
8026 (move-marker (car x) (+ beg (cdr x))))
8027 org-markers-to-move)
8028 (setq org-markers-to-move nil))
8030 (defun org-narrow-to-subtree ()
8031 "Narrow buffer to the current subtree."
8032 (interactive)
8033 (save-excursion
8034 (save-match-data
8035 (org-with-limited-levels
8036 (narrow-to-region
8037 (progn (org-back-to-heading t) (point))
8038 (progn (org-end-of-subtree t t)
8039 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8040 (point)))))))
8042 (defun org-narrow-to-block ()
8043 "Narrow buffer to the current block."
8044 (interactive)
8045 (let* ((case-fold-search t)
8046 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8047 "^[ \t]*#\\+end_.*")))
8048 (if blockp
8049 (narrow-to-region (car blockp) (cdr blockp))
8050 (error "Not in a block"))))
8052 (eval-when-compile
8053 (defvar org-property-drawer-re))
8055 (defvar org-property-start-re) ;; defined below
8056 (defun org-clone-subtree-with-time-shift (n &optional shift)
8057 "Clone the task (subtree) at point N times.
8058 The clones will be inserted as siblings.
8060 In interactive use, the user will be prompted for the number of
8061 clones to be produced, and for a time SHIFT, which may be a
8062 repeater as used in time stamps, for example `+3d'.
8064 When a valid repeater is given and the entry contains any time
8065 stamps, the clones will become a sequence in time, with time
8066 stamps in the subtree shifted for each clone produced. If SHIFT
8067 is nil or the empty string, time stamps will be left alone. The
8068 ID property of the original subtree is removed.
8070 If the original subtree did contain time stamps with a repeater,
8071 the following will happen:
8072 - the repeater will be removed in each clone
8073 - an additional clone will be produced, with the current, unshifted
8074 date(s) in the entry.
8075 - the original entry will be placed *after* all the clones, with
8076 repeater intact.
8077 - the start days in the repeater in the original entry will be shifted
8078 to past the last clone.
8079 In this way you can spell out a number of instances of a repeating task,
8080 and still retain the repeater to cover future instances of the task."
8081 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8082 (let (beg end template task idprop
8083 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8084 (drawer-re org-drawer-regexp))
8085 (if (not (and (integerp n) (> n 0)))
8086 (error "Invalid number of replications %s" n))
8087 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8088 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8089 shift)))
8090 (error "Invalid shift specification %s" shift))
8091 (when doshift
8092 (setq shift-n (string-to-number (match-string 1 shift))
8093 shift-what (cdr (assoc (match-string 2 shift)
8094 '(("d" . day) ("w" . week)
8095 ("m" . month) ("y" . year))))))
8096 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8097 (setq nmin 1 nmax n)
8098 (org-back-to-heading t)
8099 (setq beg (point))
8100 (setq idprop (org-entry-get nil "ID"))
8101 (org-end-of-subtree t t)
8102 (or (bolp) (insert "\n"))
8103 (setq end (point))
8104 (setq template (buffer-substring beg end))
8105 (when (and doshift
8106 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8107 (delete-region beg end)
8108 (setq end beg)
8109 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8110 (goto-char end)
8111 (loop for n from nmin to nmax do
8112 ;; prepare clone
8113 (with-temp-buffer
8114 (insert template)
8115 (org-mode)
8116 (goto-char (point-min))
8117 (org-show-subtree)
8118 (and idprop (if org-clone-delete-id
8119 (org-entry-delete nil "ID")
8120 (org-id-get-create t)))
8121 (unless (= n 0)
8122 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8123 (kill-whole-line))
8124 (goto-char (point-min))
8125 (while (re-search-forward drawer-re nil t)
8126 (mapc (lambda (d)
8127 (org-remove-empty-drawer-at d (point))) org-drawers)))
8128 (goto-char (point-min))
8129 (when doshift
8130 (while (re-search-forward org-ts-regexp-both nil t)
8131 (org-timestamp-change (* n shift-n) shift-what))
8132 (unless (= n n-no-remove)
8133 (goto-char (point-min))
8134 (while (re-search-forward org-ts-regexp nil t)
8135 (save-excursion
8136 (goto-char (match-beginning 0))
8137 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8138 (delete-region (match-beginning 1) (match-end 1)))))))
8139 (setq task (buffer-string)))
8140 (insert task))
8141 (goto-char beg)))
8143 ;;; Outline Sorting
8145 (defun org-sort (with-case)
8146 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8147 Optional argument WITH-CASE means sort case-sensitively."
8148 (interactive "P")
8149 (cond
8150 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8151 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8153 (org-call-with-arg 'org-sort-entries with-case))))
8155 (defun org-sort-remove-invisible (s)
8156 (remove-text-properties 0 (length s) org-rm-props s)
8157 (while (string-match org-bracket-link-regexp s)
8158 (setq s (replace-match (if (match-end 2)
8159 (match-string 3 s)
8160 (match-string 1 s)) t t s)))
8163 (defvar org-priority-regexp) ; defined later in the file
8165 (defvar org-after-sorting-entries-or-items-hook nil
8166 "Hook that is run after a bunch of entries or items have been sorted.
8167 When children are sorted, the cursor is in the parent line when this
8168 hook gets called. When a region or a plain list is sorted, the cursor
8169 will be in the first entry of the sorted region/list.")
8171 (defun org-sort-entries
8172 (&optional with-case sorting-type getkey-func compare-func property)
8173 "Sort entries on a certain level of an outline tree.
8174 If there is an active region, the entries in the region are sorted.
8175 Else, if the cursor is before the first entry, sort the top-level items.
8176 Else, the children of the entry at point are sorted.
8178 Sorting can be alphabetically, numerically, by date/time as given by
8179 a time stamp, by a property or by priority.
8181 The command prompts for the sorting type unless it has been given to the
8182 function through the SORTING-TYPE argument, which needs to be a character,
8183 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8184 precise meaning of each character:
8186 n Numerically, by converting the beginning of the entry/item to a number.
8187 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8188 o By order of TODO keywords.
8189 t By date/time, either the first active time stamp in the entry, or, if
8190 none exist, by the first inactive one.
8191 s By the scheduled date/time.
8192 d By deadline date/time.
8193 c By creation time, which is assumed to be the first inactive time stamp
8194 at the beginning of a line.
8195 p By priority according to the cookie.
8196 r By the value of a property.
8198 Capital letters will reverse the sort order.
8200 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8201 called with point at the beginning of the record. It must return either
8202 a string or a number that should serve as the sorting key for that record.
8204 Comparing entries ignores case by default. However, with an optional argument
8205 WITH-CASE, the sorting considers case as well."
8206 (interactive "P")
8207 (let ((case-func (if with-case 'identity 'downcase))
8208 (cmstr
8209 ;; The clock marker is lost when using `sort-subr', let's
8210 ;; store the clocking string.
8211 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8212 (save-excursion
8213 (goto-char org-clock-marker)
8214 (looking-back "^.*") (match-string-no-properties 0))))
8215 start beg end stars re re2
8216 txt what tmp)
8217 ;; Find beginning and end of region to sort
8218 (cond
8219 ((org-region-active-p)
8220 ;; we will sort the region
8221 (setq end (region-end)
8222 what "region")
8223 (goto-char (region-beginning))
8224 (if (not (org-at-heading-p)) (outline-next-heading))
8225 (setq start (point)))
8226 ((or (org-at-heading-p)
8227 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8228 ;; we will sort the children of the current headline
8229 (org-back-to-heading)
8230 (setq start (point)
8231 end (progn (org-end-of-subtree t t)
8232 (or (bolp) (insert "\n"))
8233 (org-back-over-empty-lines)
8234 (point))
8235 what "children")
8236 (goto-char start)
8237 (show-subtree)
8238 (outline-next-heading))
8240 ;; we will sort the top-level entries in this file
8241 (goto-char (point-min))
8242 (or (org-at-heading-p) (outline-next-heading))
8243 (setq start (point))
8244 (goto-char (point-max))
8245 (beginning-of-line 1)
8246 (when (looking-at ".*?\\S-")
8247 ;; File ends in a non-white line
8248 (end-of-line 1)
8249 (insert "\n"))
8250 (setq end (point-max))
8251 (setq what "top-level")
8252 (goto-char start)
8253 (show-all)))
8255 (setq beg (point))
8256 (if (>= beg end) (error "Nothing to sort"))
8258 (looking-at "\\(\\*+\\)")
8259 (setq stars (match-string 1)
8260 re (concat "^" (regexp-quote stars) " +")
8261 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8262 txt (buffer-substring beg end))
8263 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8264 (if (and (not (equal stars "*")) (string-match re2 txt))
8265 (error "Region to sort contains a level above the first entry"))
8267 (unless sorting-type
8268 (message
8269 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8270 [t]ime [s]cheduled [d]eadline [c]reated
8271 A/N/P/R/O/F/T/S/D/C means reversed:"
8272 what)
8273 (setq sorting-type (read-char-exclusive))
8275 (unless getkey-func
8276 (and (= (downcase sorting-type) ?f)
8277 (setq getkey-func
8278 (org-icompleting-read "Sort using function: "
8279 obarray 'fboundp t nil nil))
8280 (setq getkey-func (intern getkey-func))))
8282 (and (= (downcase sorting-type) ?r)
8283 (not property)
8284 (setq property
8285 (org-icompleting-read "Property: "
8286 (mapcar 'list (org-buffer-property-keys t))
8287 nil t))))
8289 (message "Sorting entries...")
8291 (save-restriction
8292 (narrow-to-region start end)
8293 (let ((dcst (downcase sorting-type))
8294 (case-fold-search nil)
8295 (now (current-time)))
8296 (sort-subr
8297 (/= dcst sorting-type)
8298 ;; This function moves to the beginning character of the "record" to
8299 ;; be sorted.
8300 (lambda nil
8301 (if (re-search-forward re nil t)
8302 (goto-char (match-beginning 0))
8303 (goto-char (point-max))))
8304 ;; This function moves to the last character of the "record" being
8305 ;; sorted.
8306 (lambda nil
8307 (save-match-data
8308 (condition-case nil
8309 (outline-forward-same-level 1)
8310 (error
8311 (goto-char (point-max))))))
8312 ;; This function returns the value that gets sorted against.
8313 (lambda nil
8314 (cond
8315 ((= dcst ?n)
8316 (if (looking-at org-complex-heading-regexp)
8317 (string-to-number (match-string 4))
8318 nil))
8319 ((= dcst ?a)
8320 (if (looking-at org-complex-heading-regexp)
8321 (funcall case-func (match-string 4))
8322 nil))
8323 ((= dcst ?t)
8324 (let ((end (save-excursion (outline-next-heading) (point))))
8325 (if (or (re-search-forward org-ts-regexp end t)
8326 (re-search-forward org-ts-regexp-both end t))
8327 (org-time-string-to-seconds (match-string 0))
8328 (org-float-time now))))
8329 ((= dcst ?c)
8330 (let ((end (save-excursion (outline-next-heading) (point))))
8331 (if (re-search-forward
8332 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8333 end t)
8334 (org-time-string-to-seconds (match-string 0))
8335 (org-float-time now))))
8336 ((= dcst ?s)
8337 (let ((end (save-excursion (outline-next-heading) (point))))
8338 (if (re-search-forward org-scheduled-time-regexp end t)
8339 (org-time-string-to-seconds (match-string 1))
8340 (org-float-time now))))
8341 ((= dcst ?d)
8342 (let ((end (save-excursion (outline-next-heading) (point))))
8343 (if (re-search-forward org-deadline-time-regexp end t)
8344 (org-time-string-to-seconds (match-string 1))
8345 (org-float-time now))))
8346 ((= dcst ?p)
8347 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8348 (string-to-char (match-string 2))
8349 org-default-priority))
8350 ((= dcst ?r)
8351 (or (org-entry-get nil property) ""))
8352 ((= dcst ?o)
8353 (if (looking-at org-complex-heading-regexp)
8354 (- 9999 (length (member (match-string 2)
8355 org-todo-keywords-1)))))
8356 ((= dcst ?f)
8357 (if getkey-func
8358 (progn
8359 (setq tmp (funcall getkey-func))
8360 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8361 tmp)
8362 (error "Invalid key function `%s'" getkey-func)))
8363 (t (error "Invalid sorting type `%c'" sorting-type))))
8365 (cond
8366 ((= dcst ?a) 'string<)
8367 ((= dcst ?f) compare-func)
8368 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8369 (run-hooks 'org-after-sorting-entries-or-items-hook)
8370 ;; Reset the clock marker if needed
8371 (when cmstr
8372 (save-excursion
8373 (goto-char start)
8374 (search-forward cmstr nil t)
8375 (move-marker org-clock-marker (point))))
8376 (message "Sorting entries...done")))
8378 (defun org-do-sort (table what &optional with-case sorting-type)
8379 "Sort TABLE of WHAT according to SORTING-TYPE.
8380 The user will be prompted for the SORTING-TYPE if the call to this
8381 function does not specify it. WHAT is only for the prompt, to indicate
8382 what is being sorted. The sorting key will be extracted from
8383 the car of the elements of the table.
8384 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8385 (unless sorting-type
8386 (message
8387 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8388 what)
8389 (setq sorting-type (read-char-exclusive)))
8390 (let ((dcst (downcase sorting-type))
8391 extractfun comparefun)
8392 ;; Define the appropriate functions
8393 (cond
8394 ((= dcst ?n)
8395 (setq extractfun 'string-to-number
8396 comparefun (if (= dcst sorting-type) '< '>)))
8397 ((= dcst ?a)
8398 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8399 (lambda(x) (downcase (org-sort-remove-invisible x))))
8400 comparefun (if (= dcst sorting-type)
8401 'string<
8402 (lambda (a b) (and (not (string< a b))
8403 (not (string= a b)))))))
8404 ((= dcst ?t)
8405 (setq extractfun
8406 (lambda (x)
8407 (if (or (string-match org-ts-regexp x)
8408 (string-match org-ts-regexp-both x))
8409 (org-float-time
8410 (org-time-string-to-time (match-string 0 x)))
8412 comparefun (if (= dcst sorting-type) '< '>)))
8413 (t (error "Invalid sorting type `%c'" sorting-type)))
8415 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8416 table)
8417 (lambda (a b) (funcall comparefun (car a) (car b))))))
8420 ;;; The orgstruct minor mode
8422 ;; Define a minor mode which can be used in other modes in order to
8423 ;; integrate the org-mode structure editing commands.
8425 ;; This is really a hack, because the org-mode structure commands use
8426 ;; keys which normally belong to the major mode. Here is how it
8427 ;; works: The minor mode defines all the keys necessary to operate the
8428 ;; structure commands, but wraps the commands into a function which
8429 ;; tests if the cursor is currently at a headline or a plain list
8430 ;; item. If that is the case, the structure command is used,
8431 ;; temporarily setting many Org-mode variables like regular
8432 ;; expressions for filling etc. However, when any of those keys is
8433 ;; used at a different location, function uses `key-binding' to look
8434 ;; up if the key has an associated command in another currently active
8435 ;; keymap (minor modes, major mode, global), and executes that
8436 ;; command. There might be problems if any of the keys is otherwise
8437 ;; used as a prefix key.
8439 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8440 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8441 ;; addresses this by checking explicitly for both bindings.
8443 (defvar orgstruct-mode-map (make-sparse-keymap)
8444 "Keymap for the minor `orgstruct-mode'.")
8446 (defvar org-local-vars nil
8447 "List of local variables, for use by `orgstruct-mode'.")
8449 ;;;###autoload
8450 (define-minor-mode orgstruct-mode
8451 "Toggle the minor mode `orgstruct-mode'.
8452 This mode is for using Org-mode structure commands in other
8453 modes. The following keys behave as if Org-mode were active, if
8454 the cursor is on a headline, or on a plain list item (both as
8455 defined by Org-mode).
8457 M-up Move entry/item up
8458 M-down Move entry/item down
8459 M-left Promote
8460 M-right Demote
8461 M-S-up Move entry/item up
8462 M-S-down Move entry/item down
8463 M-S-left Promote subtree
8464 M-S-right Demote subtree
8465 M-q Fill paragraph and items like in Org-mode
8466 C-c ^ Sort entries
8467 C-c - Cycle list bullet
8468 TAB Cycle item visibility
8469 M-RET Insert new heading/item
8470 S-M-RET Insert new TODO heading / Checkbox item
8471 C-c C-c Set tags / toggle checkbox"
8472 nil " OrgStruct" nil
8473 (org-load-modules-maybe)
8474 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8476 ;;;###autoload
8477 (defun turn-on-orgstruct ()
8478 "Unconditionally turn on `orgstruct-mode'."
8479 (orgstruct-mode 1))
8481 (defvar org-fb-vars nil)
8482 (make-variable-buffer-local 'org-fb-vars)
8483 (defun orgstruct++-mode (&optional arg)
8484 "Toggle `orgstruct-mode', the enhanced version of it.
8485 In addition to setting orgstruct-mode, this also exports all
8486 indentation and autofilling variables from org-mode into the
8487 buffer. It will also recognize item context in multiline items."
8488 (interactive "P")
8489 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8490 (if (< arg 1)
8491 (progn (orgstruct-mode -1)
8492 (mapc (lambda(v)
8493 (org-set-local (car v)
8494 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8495 org-fb-vars))
8496 (orgstruct-mode 1)
8497 (setq org-fb-vars nil)
8498 (let (var val)
8499 (mapc
8500 (lambda (x)
8501 (when (string-match
8502 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8503 (symbol-name (car x)))
8504 (setq var (car x) val (nth 1 x))
8505 (push (list var `(quote ,(eval var))) org-fb-vars)
8506 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8507 org-local-vars)
8508 (org-set-local 'orgstruct-is-++ t))))
8510 (defvar orgstruct-is-++ nil
8511 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8512 (make-variable-buffer-local 'orgstruct-is-++)
8514 ;;;###autoload
8515 (defun turn-on-orgstruct++ ()
8516 "Unconditionally turn on `orgstruct++-mode'."
8517 (orgstruct++-mode 1))
8519 (defun orgstruct-error ()
8520 "Error when there is no default binding for a structure key."
8521 (interactive)
8522 (error "This key has no function outside structure elements"))
8524 (defun orgstruct-setup ()
8525 "Setup orgstruct keymaps."
8526 (let ((nfunc 0)
8527 (bindings
8528 (list
8529 '([(meta up)] org-metaup)
8530 '([(meta down)] org-metadown)
8531 '([(meta left)] org-metaleft)
8532 '([(meta right)] org-metaright)
8533 '([(meta shift up)] org-shiftmetaup)
8534 '([(meta shift down)] org-shiftmetadown)
8535 '([(meta shift left)] org-shiftmetaleft)
8536 '([(meta shift right)] org-shiftmetaright)
8537 '([?\e (up)] org-metaup)
8538 '([?\e (down)] org-metadown)
8539 '([?\e (left)] org-metaleft)
8540 '([?\e (right)] org-metaright)
8541 '([?\e (shift up)] org-shiftmetaup)
8542 '([?\e (shift down)] org-shiftmetadown)
8543 '([?\e (shift left)] org-shiftmetaleft)
8544 '([?\e (shift right)] org-shiftmetaright)
8545 '([(shift up)] org-shiftup)
8546 '([(shift down)] org-shiftdown)
8547 '([(shift left)] org-shiftleft)
8548 '([(shift right)] org-shiftright)
8549 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8550 '("\M-q" fill-paragraph)
8551 '("\C-c^" org-sort)
8552 '("\C-c-" org-cycle-list-bullet)))
8553 elt key fun cmd)
8554 (while (setq elt (pop bindings))
8555 (setq nfunc (1+ nfunc))
8556 (setq key (org-key (car elt))
8557 fun (nth 1 elt)
8558 cmd (orgstruct-make-binding fun nfunc key))
8559 (org-defkey orgstruct-mode-map key cmd))
8561 ;; Prevent an error for users who forgot to make autoloads
8562 (require 'org-element)
8564 ;; Special treatment needed for TAB and RET
8565 (org-defkey orgstruct-mode-map [(tab)]
8566 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8567 (org-defkey orgstruct-mode-map "\C-i"
8568 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8570 (org-defkey orgstruct-mode-map "\M-\C-m"
8571 (orgstruct-make-binding 'org-insert-heading 105
8572 "\M-\C-m" [(meta return)]))
8573 (org-defkey orgstruct-mode-map [(meta return)]
8574 (orgstruct-make-binding 'org-insert-heading 106
8575 [(meta return)] "\M-\C-m"))
8577 (org-defkey orgstruct-mode-map [(shift meta return)]
8578 (orgstruct-make-binding 'org-insert-todo-heading 107
8579 [(meta return)] "\M-\C-m"))
8581 (org-defkey orgstruct-mode-map "\e\C-m"
8582 (orgstruct-make-binding 'org-insert-heading 108
8583 "\e\C-m" [?\e (return)]))
8584 (org-defkey orgstruct-mode-map [?\e (return)]
8585 (orgstruct-make-binding 'org-insert-heading 109
8586 [?\e (return)] "\e\C-m"))
8587 (org-defkey orgstruct-mode-map [?\e (shift return)]
8588 (orgstruct-make-binding 'org-insert-todo-heading 110
8589 [?\e (return)] "\e\C-m"))
8591 (unless org-local-vars
8592 (setq org-local-vars (org-get-local-variables)))
8596 (defun orgstruct-make-binding (fun n &rest keys)
8597 "Create a function for binding in the structure minor mode.
8598 FUN is the command to call inside a table. N is used to create a unique
8599 command name. KEYS are keys that should be checked in for a command
8600 to execute outside of tables."
8601 (eval
8602 (list 'defun
8603 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8604 '(arg)
8605 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8606 "Outside of structure, run the binding of `"
8607 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8608 "'.")
8609 '(interactive "p")
8610 (list 'if
8611 `(org-context-p 'headline 'item
8612 (and orgstruct-is-++
8613 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8614 'item-body))
8615 (list 'org-run-like-in-org-mode (list 'quote fun))
8616 (list 'let '(orgstruct-mode)
8617 (list 'call-interactively
8618 (append '(or)
8619 (mapcar (lambda (k)
8620 (list 'key-binding k))
8621 keys)
8622 '('orgstruct-error))))))))
8624 (defun org-contextualize-keys (alist contexts)
8625 "Return valid elements in ALIST depending on CONTEXTS.
8627 `org-agenda-custom-commands' or `org-capture-templates' are the
8628 values used for ALIST, and `org-agenda-custom-commands-contexts'
8629 or `org-capture-templates-contexts' are the associated contexts
8630 definitions."
8631 (let ((contexts
8632 ;; normalize contexts
8633 (mapcar
8634 (lambda(c) (cond ((listp (cadr c))
8635 (list (car c) (car c) (cadr c)))
8636 ((string= "" (cadr c))
8637 (list (car c) (car c) (caddr c)))
8638 (t c))) contexts))
8639 (a alist) c r s)
8640 ;; loop over all commands or templates
8641 (while (setq c (pop a))
8642 (let (vrules repl)
8643 (cond
8644 ((not (assoc (car c) contexts))
8645 (push c r))
8646 ((and (assoc (car c) contexts)
8647 (setq vrules (org-contextualize-validate-key
8648 (car c) contexts)))
8649 (mapc (lambda (vr)
8650 (when (not (equal (car vr) (cadr vr)))
8651 (setq repl vr))) vrules)
8652 (if (not repl) (push c r)
8653 (push (cadr repl) s)
8654 (push
8655 (cons (car c)
8656 (cdr (or (assoc (cadr repl) alist)
8657 (error "Undefined key `%s' as contextual replacement for `%s'"
8658 (cadr repl) (car c)))))
8659 r))))))
8660 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8661 (delq
8663 (delete-dups
8664 (mapcar (lambda (x)
8665 (let ((tpl (car x)))
8666 (when (not (delq
8668 (mapcar (lambda(y)
8669 (equal y tpl)) s))) x)))
8670 (reverse r))))))
8672 (defun org-contextualize-validate-key (key contexts)
8673 "Check CONTEXTS for agenda or capture KEY."
8674 (let (r rr res)
8675 (while (setq r (pop contexts))
8676 (mapc
8677 (lambda (rr)
8678 (when
8679 (and (equal key (car r))
8680 (if (functionp rr) (funcall rr)
8681 (or (and (eq (car rr) 'in-file)
8682 (buffer-file-name)
8683 (string-match (cdr rr) (buffer-file-name)))
8684 (and (eq (car rr) 'in-mode)
8685 (string-match (cdr rr) (symbol-name major-mode)))
8686 (when (and (eq (car rr) 'not-in-file)
8687 (buffer-file-name))
8688 (not (string-match (cdr rr) (buffer-file-name))))
8689 (when (eq (car rr) 'not-in-mode)
8690 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8691 (push r res)))
8692 (car (last r))))
8693 (delete-dups (delq nil res))))
8695 (defun org-context-p (&rest contexts)
8696 "Check if local context is any of CONTEXTS.
8697 Possible values in the list of contexts are `table', `headline', and `item'."
8698 (let ((pos (point)))
8699 (goto-char (point-at-bol))
8700 (prog1 (or (and (memq 'table contexts)
8701 (looking-at "[ \t]*|"))
8702 (and (memq 'headline contexts)
8703 (looking-at org-outline-regexp))
8704 (and (memq 'item contexts)
8705 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8706 (and (memq 'item-body contexts)
8707 (org-in-item-p)))
8708 (goto-char pos))))
8710 (defun org-get-local-variables ()
8711 "Return a list of all local variables in an Org mode buffer."
8712 (let (varlist)
8713 (with-current-buffer (get-buffer-create "*Org tmp*")
8714 (erase-buffer)
8715 (org-mode)
8716 (setq varlist (buffer-local-variables)))
8717 (kill-buffer "*Org tmp*")
8718 (delq nil
8719 (mapcar
8720 (lambda (x)
8721 (setq x
8722 (if (symbolp x)
8723 (list x)
8724 (list (car x) (list 'quote (cdr x)))))
8725 (if (string-match
8726 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8727 (symbol-name (car x)))
8728 x nil))
8729 varlist))))
8731 (defun org-clone-local-variables (from-buffer &optional regexp)
8732 "Clone local variables from FROM-BUFFER.
8733 Optional argument REGEXP selects variables to clone."
8734 (mapc
8735 (lambda (pair)
8736 (and (symbolp (car pair))
8737 (or (null regexp)
8738 (string-match regexp (symbol-name (car pair))))
8739 (set (make-local-variable (car pair))
8740 (cdr pair))))
8741 (buffer-local-variables from-buffer)))
8743 ;;;###autoload
8744 (defun org-run-like-in-org-mode (cmd)
8745 "Run a command, pretending that the current buffer is in Org-mode.
8746 This will temporarily bind local variables that are typically bound in
8747 Org-mode to the values they have in Org-mode, and then interactively
8748 call CMD."
8749 (org-load-modules-maybe)
8750 (unless org-local-vars
8751 (setq org-local-vars (org-get-local-variables)))
8752 (eval (list 'let org-local-vars
8753 (list 'call-interactively (list 'quote cmd)))))
8755 ;;;; Archiving
8757 (defun org-get-category (&optional pos force-refresh)
8758 "Get the category applying to position POS."
8759 (save-match-data
8760 (if force-refresh (org-refresh-category-properties))
8761 (let ((pos (or pos (point))))
8762 (or (get-text-property pos 'org-category)
8763 (progn (org-refresh-category-properties)
8764 (get-text-property pos 'org-category))))))
8766 (defun org-refresh-category-properties ()
8767 "Refresh category text properties in the buffer."
8768 (let ((case-fold-search t)
8769 (inhibit-read-only t)
8770 (def-cat (cond
8771 ((null org-category)
8772 (if buffer-file-name
8773 (file-name-sans-extension
8774 (file-name-nondirectory buffer-file-name))
8775 "???"))
8776 ((symbolp org-category) (symbol-name org-category))
8777 (t org-category)))
8778 beg end cat pos optionp)
8779 (org-unmodified
8780 (save-excursion
8781 (save-restriction
8782 (widen)
8783 (goto-char (point-min))
8784 (put-text-property (point) (point-max) 'org-category def-cat)
8785 (while (re-search-forward
8786 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8787 (setq pos (match-end 0)
8788 optionp (equal (char-after (match-beginning 0)) ?#)
8789 cat (org-trim (match-string 2)))
8790 (if optionp
8791 (setq beg (point-at-bol) end (point-max))
8792 (org-back-to-heading t)
8793 (setq beg (point) end (org-end-of-subtree t t)))
8794 (put-text-property beg end 'org-category cat)
8795 (put-text-property beg end 'org-category-position beg)
8796 (goto-char pos)))))))
8799 ;;;; Link Stuff
8801 ;;; Link abbreviations
8803 (defun org-link-expand-abbrev (link)
8804 "Apply replacements as defined in `org-link-abbrev-alist'."
8805 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8806 (let* ((key (match-string 1 link))
8807 (as (or (assoc key org-link-abbrev-alist-local)
8808 (assoc key org-link-abbrev-alist)))
8809 (tag (and (match-end 2) (match-string 3 link)))
8810 rpl)
8811 (if (not as)
8812 link
8813 (setq rpl (cdr as))
8814 (cond
8815 ((symbolp rpl) (funcall rpl tag))
8816 ((string-match "%(\\([^)]+\\))" rpl)
8817 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8818 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8819 ((string-match "%h" rpl)
8820 (replace-match (url-hexify-string (or tag "")) t t rpl))
8821 (t (concat rpl tag)))))
8822 link))
8824 ;;; Storing and inserting links
8826 (defvar org-insert-link-history nil
8827 "Minibuffer history for links inserted with `org-insert-link'.")
8829 (defvar org-stored-links nil
8830 "Contains the links stored with `org-store-link'.")
8832 (defvar org-store-link-plist nil
8833 "Plist with info about the most recently link created with `org-store-link'.")
8835 (defvar org-link-protocols nil
8836 "Link protocols added to Org-mode using `org-add-link-type'.")
8838 (defvar org-store-link-functions nil
8839 "List of functions that are called to create and store a link.
8840 Each function will be called in turn until one returns a non-nil
8841 value. Each function should check if it is responsible for creating
8842 this link (for example by looking at the major mode).
8843 If not, it must exit and return nil.
8844 If yes, it should return a non-nil value after a calling
8845 `org-store-link-props' with a list of properties and values.
8846 Special properties are:
8848 :type The link prefix, like \"http\". This must be given.
8849 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8850 This is obligatory as well.
8851 :description Optional default description for the second pair
8852 of brackets in an Org-mode link. The user can still change
8853 this when inserting this link into an Org-mode buffer.
8855 In addition to these, any additional properties can be specified
8856 and then used in capture templates.")
8858 (defun org-add-link-type (type &optional follow export)
8859 "Add TYPE to the list of `org-link-types'.
8860 Re-compute all regular expressions depending on `org-link-types'
8862 FOLLOW and EXPORT are two functions.
8864 FOLLOW should take the link path as the single argument and do whatever
8865 is necessary to follow the link, for example find a file or display
8866 a mail message.
8868 EXPORT should format the link path for export to one of the export formats.
8869 It should be a function accepting three arguments:
8871 path the path of the link, the text after the prefix (like \"http:\")
8872 desc the description of the link, if any, or a description added by
8873 org-export-normalize-links if there is none
8874 format the export format, a symbol like `html' or `latex' or `ascii'..
8876 The function may use the FORMAT information to return different values
8877 depending on the format. The return value will be put literally into
8878 the exported file. If the return value is nil, this means Org should
8879 do what it normally does with links which do not have EXPORT defined.
8881 Org-mode has a built-in default for exporting links. If you are happy with
8882 this default, there is no need to define an export function for the link
8883 type. For a simple example of an export function, see `org-bbdb.el'."
8884 (add-to-list 'org-link-types type t)
8885 (org-make-link-regexps)
8886 (if (assoc type org-link-protocols)
8887 (setcdr (assoc type org-link-protocols) (list follow export))
8888 (push (list type follow export) org-link-protocols)))
8890 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8891 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8893 ;;;###autoload
8894 (defun org-store-link (arg)
8895 "\\<org-mode-map>Store an org-link to the current location.
8896 This link is added to `org-stored-links' and can later be inserted
8897 into an org-buffer with \\[org-insert-link].
8899 For some link types, a prefix arg is interpreted.
8900 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8901 For file links, arg negates `org-context-in-file-links'.
8903 A double prefix arg force skipping storing functions that are not
8904 part of Org's core."
8905 (interactive "P")
8906 (org-load-modules-maybe)
8907 (setq org-store-link-plist nil) ; reset
8908 (org-with-limited-levels
8909 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8910 (cond
8911 ((and (not (equal arg '(16)))
8912 (setq sfuns
8913 (delq
8914 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8915 org-store-link-functions))
8916 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8917 (or (and (cdr sfuns)
8918 (funcall (intern
8919 (completing-read "Which function for creating the link? "
8920 sfunsn t (car sfunsn)))))
8921 (funcall (caar sfuns)))
8922 (setq link (plist-get org-store-link-plist :link)
8923 desc (or (plist-get org-store-link-plist :description) link))))
8924 ((org-src-edit-buffer-p)
8925 (let (label gc)
8926 (while (or (not label)
8927 (save-excursion
8928 (save-restriction
8929 (widen)
8930 (goto-char (point-min))
8931 (re-search-forward
8932 (regexp-quote (format org-coderef-label-format label))
8933 nil t))))
8934 (when label (message "Label exists already") (sit-for 2))
8935 (setq label (read-string "Code line label: " label)))
8936 (end-of-line 1)
8937 (setq link (format org-coderef-label-format label))
8938 (setq gc (- 79 (length link)))
8939 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8940 (insert link)
8941 (setq link (concat "(" label ")") desc nil)))
8943 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8944 ;; We are in the agenda, link to referenced location
8945 (let ((m (or (get-text-property (point) 'org-hd-marker)
8946 (get-text-property (point) 'org-marker))))
8947 (when m
8948 (org-with-point-at m
8949 (setq agenda-link
8950 (if (org-called-interactively-p 'any)
8951 (call-interactively 'org-store-link)
8952 (org-store-link nil)))))))
8954 ((eq major-mode 'calendar-mode)
8955 (let ((cd (calendar-cursor-to-date)))
8956 (setq link
8957 (format-time-string
8958 (car org-time-stamp-formats)
8959 (apply 'encode-time
8960 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8961 nil nil nil))))
8962 (org-store-link-props :type "calendar" :date cd)))
8964 ((eq major-mode 'help-mode)
8965 (setq link (concat "help:" (save-excursion
8966 (goto-char (point-min))
8967 (looking-at "^[^ ]+")
8968 (match-string 0))))
8969 (org-store-link-props :type "help"))
8971 ((eq major-mode 'w3-mode)
8972 (setq cpltxt (if (and (buffer-name)
8973 (not (string-match "Untitled" (buffer-name))))
8974 (buffer-name)
8975 (url-view-url t))
8976 link (url-view-url t))
8977 (org-store-link-props :type "w3" :url (url-view-url t)))
8979 ((setq search (run-hook-with-args-until-success
8980 'org-create-file-search-functions))
8981 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8982 "::" search))
8983 (setq cpltxt (or description link)))
8985 ((eq major-mode 'image-mode)
8986 (setq cpltxt (concat "file:"
8987 (abbreviate-file-name buffer-file-name))
8988 link cpltxt)
8989 (org-store-link-props :type "image" :file buffer-file-name))
8991 ((eq major-mode 'dired-mode)
8992 ;; link to the file in the current line
8993 (let ((file (dired-get-filename nil t)))
8994 (setq file (if file
8995 (abbreviate-file-name
8996 (expand-file-name (dired-get-filename nil t)))
8997 ;; otherwise, no file so use current directory.
8998 default-directory))
8999 (setq cpltxt (concat "file:" file)
9000 link cpltxt)))
9002 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9003 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9004 (cond
9005 ((org-in-regexp "<<\\(.*?\\)>>")
9006 (setq cpltxt
9007 (concat "file:"
9008 (abbreviate-file-name
9009 (buffer-file-name (buffer-base-buffer)))
9010 "::" (match-string 1))
9011 link cpltxt))
9012 ((and (featurep 'org-id)
9013 (or (eq org-link-to-org-use-id t)
9014 (and (org-called-interactively-p 'any)
9015 (or (eq org-link-to-org-use-id 'create-if-interactive)
9016 (and (eq org-link-to-org-use-id
9017 'create-if-interactive-and-no-custom-id)
9018 (not custom-id))))
9019 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9020 ;; We can make a link using the ID.
9021 (setq link (condition-case nil
9022 (prog1 (org-id-store-link)
9023 (setq desc (plist-get org-store-link-plist :description)))
9024 (error
9025 ;; probably before first headline, link to file only
9026 (concat "file:"
9027 (abbreviate-file-name
9028 (buffer-file-name (buffer-base-buffer))))))))
9030 ;; Just link to current headline
9031 (setq cpltxt (concat "file:"
9032 (abbreviate-file-name
9033 (buffer-file-name (buffer-base-buffer)))))
9034 ;; Add a context search string
9035 (when (org-xor org-context-in-file-links arg)
9036 (let* ((ee (org-element-at-point))
9037 (et (org-element-type ee))
9038 (ev (plist-get (cadr ee) :value)))
9039 (setq txt (cond
9040 ((org-at-heading-p) nil)
9041 ((eq et 'keyword) ev)
9042 ((org-region-active-p)
9043 (buffer-substring (region-beginning) (region-end)))))
9044 (when (or (null txt) (string-match "\\S-" txt))
9045 (setq cpltxt
9046 (concat cpltxt "::"
9047 (condition-case nil
9048 (org-make-org-heading-search-string txt)
9049 (error "")))
9050 desc (or (and (eq et 'keyword) ev)
9051 (nth 4 (ignore-errors (org-heading-components)))
9052 "NONE")))))
9053 (if (string-match "::\\'" cpltxt)
9054 (setq cpltxt (substring cpltxt 0 -2)))
9055 (setq link cpltxt))))
9057 ((buffer-file-name (buffer-base-buffer))
9058 ;; Just link to this file here.
9059 (setq cpltxt (concat "file:"
9060 (abbreviate-file-name
9061 (buffer-file-name (buffer-base-buffer)))))
9062 ;; Add a context string
9063 (when (org-xor org-context-in-file-links arg)
9064 (setq txt (if (org-region-active-p)
9065 (buffer-substring (region-beginning) (region-end))
9066 (buffer-substring (point-at-bol) (point-at-eol))))
9067 ;; Only use search option if there is some text.
9068 (when (string-match "\\S-" txt)
9069 (setq cpltxt
9070 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9071 desc "NONE")))
9072 (setq link cpltxt))
9074 ((org-called-interactively-p 'interactive)
9075 (user-error "No method for storing a link from this buffer"))
9077 (t (setq link nil)))
9079 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9080 (setq link (or link cpltxt)
9081 desc (or desc cpltxt))
9082 (cond ((equal desc "NONE") (setq desc nil))
9083 ((string-match org-bracket-link-regexp desc)
9084 (setq desc (replace-regexp-in-string
9085 org-bracket-link-regexp
9086 (concat "\\3" (if (equal (length (match-string 0 desc))
9087 (length desc)) "*" "")) desc))))
9089 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9090 (progn
9091 (setq org-stored-links
9092 (cons (list link desc) org-stored-links))
9093 (message "Stored: %s" (or desc link))
9094 (when custom-id
9095 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9096 "::#" custom-id))
9097 (setq org-stored-links
9098 (cons (list link desc) org-stored-links))))
9099 (or agenda-link (and link (org-make-link-string link desc)))))))
9101 (defun org-store-link-props (&rest plist)
9102 "Store link properties, extract names and addresses."
9103 (let (x adr)
9104 (when (setq x (plist-get plist :from))
9105 (setq adr (mail-extract-address-components x))
9106 (setq plist (plist-put plist :fromname (car adr)))
9107 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9108 (when (setq x (plist-get plist :to))
9109 (setq adr (mail-extract-address-components x))
9110 (setq plist (plist-put plist :toname (car adr)))
9111 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9112 (let ((from (plist-get plist :from))
9113 (to (plist-get plist :to)))
9114 (when (and from to org-from-is-user-regexp)
9115 (setq plist
9116 (plist-put plist :fromto
9117 (if (string-match org-from-is-user-regexp from)
9118 (concat "to %t")
9119 (concat "from %f"))))))
9120 (setq org-store-link-plist plist))
9122 (defun org-add-link-props (&rest plist)
9123 "Add these properties to the link property list."
9124 (let (key value)
9125 (while plist
9126 (setq key (pop plist) value (pop plist))
9127 (setq org-store-link-plist
9128 (plist-put org-store-link-plist key value)))))
9130 (defun org-email-link-description (&optional fmt)
9131 "Return the description part of an email link.
9132 This takes information from `org-store-link-plist' and formats it
9133 according to FMT (default from `org-email-link-description-format')."
9134 (setq fmt (or fmt org-email-link-description-format))
9135 (let* ((p org-store-link-plist)
9136 (to (plist-get p :toaddress))
9137 (from (plist-get p :fromaddress))
9138 (table
9139 (list
9140 (cons "%c" (plist-get p :fromto))
9141 (cons "%F" (plist-get p :from))
9142 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9143 (cons "%T" (plist-get p :to))
9144 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9145 (cons "%s" (plist-get p :subject))
9146 (cons "%d" (plist-get p :date))
9147 (cons "%m" (plist-get p :message-id)))))
9148 (when (string-match "%c" fmt)
9149 ;; Check if the user wrote this message
9150 (if (and org-from-is-user-regexp from to
9151 (save-match-data (string-match org-from-is-user-regexp from)))
9152 (setq fmt (replace-match "to %t" t t fmt))
9153 (setq fmt (replace-match "from %f" t t fmt))))
9154 (org-replace-escapes fmt table)))
9156 (defun org-make-org-heading-search-string (&optional string)
9157 "Make search string for the current headline or STRING."
9158 (let ((s (or string
9159 (and (derived-mode-p 'org-mode)
9160 (save-excursion
9161 (org-back-to-heading t)
9162 (plist-get (cadr (org-element-at-point))
9163 :raw-value)))))
9164 (lines org-context-in-file-links))
9165 (or string (setq s (concat "*" s))) ; Add * for headlines
9166 (when (and string (integerp lines) (> lines 0))
9167 (let ((slines (org-split-string s "\n")))
9168 (when (< lines (length slines))
9169 (setq s (mapconcat
9170 'identity
9171 (reverse (nthcdr (- (length slines) lines)
9172 (reverse slines))) "\n")))))
9173 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9175 (defun org-make-link-string (link &optional description)
9176 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9177 (unless (string-match "\\S-" link)
9178 (error "Empty link"))
9179 (when (and description
9180 (stringp description)
9181 (not (string-match "\\S-" description)))
9182 (setq description nil))
9183 (when (stringp description)
9184 ;; Remove brackets from the description, they are fatal.
9185 (while (string-match "\\[" description)
9186 (setq description (replace-match "{" t t description)))
9187 (while (string-match "\\]" description)
9188 (setq description (replace-match "}" t t description))))
9189 (when (equal link description)
9190 ;; No description needed, it is identical
9191 (setq description nil))
9192 (when (and (not description)
9193 (not (string-match (org-image-file-name-regexp) link))
9194 (not (equal link (org-link-escape link))))
9195 (setq description (org-extract-attributes link)))
9196 (setq link
9197 (cond ((string-match (org-image-file-name-regexp) link) link)
9198 ((string-match org-link-types-re link)
9199 (concat (match-string 1 link)
9200 (org-link-escape (substring link (match-end 1)))))
9201 (t (org-link-escape link))))
9202 (concat "[[" link "]"
9203 (if description (concat "[" description "]") "")
9204 "]"))
9206 (defconst org-link-escape-chars
9207 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9208 "List of characters that should be escaped in link.
9209 This is the list that is used for internal purposes.")
9211 (defconst org-link-escape-chars-browser
9212 '(?\ )
9213 "List of escapes for characters that are problematic in links.
9214 This is the list that is used before handing over to the browser.")
9216 (defun org-link-escape (text &optional table merge)
9217 "Return percent escaped representation of TEXT.
9218 TEXT is a string with the text to escape.
9219 Optional argument TABLE is a list with characters that should be
9220 escaped. When nil, `org-link-escape-chars' is used.
9221 If optional argument MERGE is set, merge TABLE into
9222 `org-link-escape-chars'."
9223 (cond
9224 ((and table merge)
9225 (mapc (lambda (defchr)
9226 (unless (member defchr table)
9227 (setq table (cons defchr table)))) org-link-escape-chars))
9228 ((null table)
9229 (setq table org-link-escape-chars)))
9230 (mapconcat
9231 (lambda (char)
9232 (if (or (member char table)
9233 (and (or (< char 32) (= char 37) (> char 126))
9234 org-url-hexify-p))
9235 (mapconcat (lambda (sequence-element)
9236 (format "%%%.2X" sequence-element))
9237 (or (encode-coding-char char 'utf-8)
9238 (error "Unable to percent escape character: %s"
9239 (char-to-string char))) "")
9240 (char-to-string char))) text ""))
9242 (defun org-link-unescape (str)
9243 "Unhex hexified Unicode strings as returned from the JavaScript function
9244 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9245 (unless (and (null str) (string= "" str))
9246 (let ((pos 0) (case-fold-search t) unhexed)
9247 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9248 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9249 (setq str (replace-match unhexed t t str))
9250 (setq pos (+ pos (length unhexed))))))
9251 str)
9253 (defun org-link-unescape-compound (hex)
9254 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9255 Note: this function also decodes single byte encodings like
9256 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9257 (save-match-data
9258 (let* ((bytes (cdr (split-string hex "%")))
9259 (ret "")
9260 (eat 0)
9261 (sum 0))
9262 (while bytes
9263 (let* ((val (string-to-number (pop bytes) 16))
9264 (shift-xor
9265 (if (= 0 eat)
9266 (cond
9267 ((>= val 252) (cons 6 252))
9268 ((>= val 248) (cons 5 248))
9269 ((>= val 240) (cons 4 240))
9270 ((>= val 224) (cons 3 224))
9271 ((>= val 192) (cons 2 192))
9272 (t (cons 0 0)))
9273 (cons 6 128))))
9274 (if (>= val 192) (setq eat (car shift-xor)))
9275 (setq val (logxor val (cdr shift-xor)))
9276 (setq sum (+ (lsh sum (car shift-xor)) val))
9277 (if (> eat 0) (setq eat (- eat 1)))
9278 (cond
9279 ((= 0 eat) ;multi byte
9280 (setq ret (concat ret (org-char-to-string sum)))
9281 (setq sum 0))
9282 ((not bytes) ; single byte(s)
9283 (setq ret (org-link-unescape-single-byte-sequence hex))))
9284 )) ;; end (while bytes
9285 ret )))
9287 (defun org-link-unescape-single-byte-sequence (hex)
9288 "Unhexify hex-encoded single byte character sequences."
9289 (mapconcat (lambda (byte)
9290 (char-to-string (string-to-number byte 16)))
9291 (cdr (split-string hex "%")) ""))
9293 (defun org-xor (a b)
9294 "Exclusive or."
9295 (if a (not b) b))
9297 (defun org-fixup-message-id-for-http (s)
9298 "Replace special characters in a message id, so it can be used in an http query."
9299 (when (string-match "%" s)
9300 (setq s (mapconcat (lambda (c)
9301 (if (eq c ?%)
9302 "%25"
9303 (char-to-string c)))
9304 s "")))
9305 (while (string-match "<" s)
9306 (setq s (replace-match "%3C" t t s)))
9307 (while (string-match ">" s)
9308 (setq s (replace-match "%3E" t t s)))
9309 (while (string-match "@" s)
9310 (setq s (replace-match "%40" t t s)))
9313 (defun org-link-prettify (link)
9314 "Return a human-readable representation of LINK.
9315 The car of LINK must be a raw link the cdr of LINK must be either
9316 a link description or nil."
9317 (let ((desc (or (cadr link) "<no description>")))
9318 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9319 "<" (car link) ">")))
9321 ;;;###autoload
9322 (defun org-insert-link-global ()
9323 "Insert a link like Org-mode does.
9324 This command can be called in any mode to insert a link in Org-mode syntax."
9325 (interactive)
9326 (org-load-modules-maybe)
9327 (org-run-like-in-org-mode 'org-insert-link))
9329 (defun org-insert-all-links (&optional keep)
9330 "Insert all links in `org-stored-links'."
9331 (interactive "P")
9332 (let ((links (copy-sequence org-stored-links)) l)
9333 (while (setq l (if keep (pop links) (pop org-stored-links)))
9334 (insert "- ")
9335 (org-insert-link nil (car l) (cadr l))
9336 (insert "\n"))))
9338 (defun org-link-fontify-links-to-this-file ()
9339 "Fontify links to the current file in `org-stored-links'."
9340 (let ((f (buffer-file-name)) a b)
9341 (setq a (mapcar (lambda(l)
9342 (let ((ll (car l)))
9343 (when (and (string-match "^file:\\(.+\\)::" ll)
9344 (equal f (expand-file-name (match-string 1 ll))))
9345 ll)))
9346 org-stored-links))
9347 (when (featurep 'org-id)
9348 (setq b (mapcar (lambda(l)
9349 (let ((ll (car l)))
9350 (when (and (string-match "^id:\\(.+\\)$" ll)
9351 (equal f (expand-file-name
9352 (or (org-id-find-id-file
9353 (match-string 1 ll)) ""))))
9354 ll)))
9355 org-stored-links)))
9356 (mapcar (lambda(l)
9357 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9358 (delq nil (append a b)))))
9360 (defvar org-link-links-in-this-file nil)
9361 (defun org-insert-link (&optional complete-file link-location default-description)
9362 "Insert a link. At the prompt, enter the link.
9364 Completion can be used to insert any of the link protocol prefixes like
9365 http or ftp in use.
9367 The history can be used to select a link previously stored with
9368 `org-store-link'. When the empty string is entered (i.e. if you just
9369 press RET at the prompt), the link defaults to the most recently
9370 stored link. As SPC triggers completion in the minibuffer, you need to
9371 use M-SPC or C-q SPC to force the insertion of a space character.
9373 You will also be prompted for a description, and if one is given, it will
9374 be displayed in the buffer instead of the link.
9376 If there is already a link at point, this command will allow you to edit link
9377 and description parts.
9379 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9380 be selected using completion. The path to the file will be relative to the
9381 current directory if the file is in the current directory or a subdirectory.
9382 Otherwise, the link will be the absolute path as completed in the minibuffer
9383 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9384 option `org-link-file-path-type'.
9386 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9387 the current directory or below.
9389 With three \\[universal-argument] prefixes, negate the meaning of
9390 `org-keep-stored-link-after-insertion'.
9392 If `org-make-link-description-function' is non-nil, this function will be
9393 called with the link target, and the result will be the default
9394 link description.
9396 If the LINK-LOCATION parameter is non-nil, this value will be
9397 used as the link location instead of reading one interactively.
9399 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9400 be used as the default description."
9401 (interactive "P")
9402 (let* ((wcf (current-window-configuration))
9403 (origbuf (current-buffer))
9404 (region (if (org-region-active-p)
9405 (buffer-substring (region-beginning) (region-end))))
9406 (remove (and region (list (region-beginning) (region-end))))
9407 (desc region)
9408 tmphist ; byte-compile incorrectly complains about this
9409 (link link-location)
9410 (abbrevs org-link-abbrev-alist-local)
9411 entry file all-prefixes auto-desc)
9412 (cond
9413 (link-location) ; specified by arg, just use it.
9414 ((org-in-regexp org-bracket-link-regexp 1)
9415 ;; We do have a link at point, and we are going to edit it.
9416 (setq remove (list (match-beginning 0) (match-end 0)))
9417 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9418 (setq link (read-string "Link: "
9419 (org-link-unescape
9420 (org-match-string-no-properties 1)))))
9421 ((or (org-in-regexp org-angle-link-re)
9422 (org-in-regexp org-plain-link-re))
9423 ;; Convert to bracket link
9424 (setq remove (list (match-beginning 0) (match-end 0))
9425 link (read-string "Link: "
9426 (org-remove-angle-brackets (match-string 0)))))
9427 ((member complete-file '((4) (16)))
9428 ;; Completing read for file names.
9429 (setq link (org-file-complete-link complete-file)))
9431 ;; Read link, with completion for stored links.
9432 (org-link-fontify-links-to-this-file)
9433 (org-switch-to-buffer-other-window "*Org Links*")
9434 (with-current-buffer "*Org Links*"
9435 (erase-buffer)
9436 (insert "Insert a link.
9437 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9438 (when org-stored-links
9439 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9440 (insert (mapconcat 'org-link-prettify
9441 (reverse org-stored-links) "\n")))
9442 (goto-char (point-min)))
9443 (let ((cw (selected-window)))
9444 (select-window (get-buffer-window "*Org Links*" 'visible))
9445 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9446 (unless (pos-visible-in-window-p (point-max))
9447 (org-fit-window-to-buffer))
9448 (and (window-live-p cw) (select-window cw)))
9449 ;; Fake a link history, containing the stored links.
9450 (setq tmphist (append (mapcar 'car org-stored-links)
9451 org-insert-link-history))
9452 (setq all-prefixes (append (mapcar 'car abbrevs)
9453 (mapcar 'car org-link-abbrev-alist)
9454 org-link-types))
9455 (unwind-protect
9456 (progn
9457 (setq link
9458 (org-completing-read
9459 "Link: "
9460 (append
9461 (mapcar (lambda (x) (concat x ":"))
9462 all-prefixes)
9463 (mapcar 'car org-stored-links))
9464 nil nil nil
9465 'tmphist
9466 (caar org-stored-links)))
9467 (if (not (string-match "\\S-" link))
9468 (error "No link selected"))
9469 (mapc (lambda(l)
9470 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9471 org-stored-links)
9472 (if (or (member link all-prefixes)
9473 (and (equal ":" (substring link -1))
9474 (member (substring link 0 -1) all-prefixes)
9475 (setq link (substring link 0 -1))))
9476 (setq link (with-current-buffer origbuf
9477 (org-link-try-special-completion link)))))
9478 (set-window-configuration wcf)
9479 (kill-buffer "*Org Links*"))
9480 (setq entry (assoc link org-stored-links))
9481 (or entry (push link org-insert-link-history))
9482 (setq desc (or desc (nth 1 entry)))))
9484 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9485 (not org-keep-stored-link-after-insertion))
9486 (setq org-stored-links (delq (assoc link org-stored-links)
9487 org-stored-links)))
9489 (if (string-match org-plain-link-re link)
9490 ;; URL-like link, normalize the use of angular brackets.
9491 (setq link (org-remove-angle-brackets link)))
9493 ;; Check if we are linking to the current file with a search
9494 ;; option If yes, simplify the link by using only the search
9495 ;; option.
9496 (when (and buffer-file-name
9497 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9498 (let* ((path (match-string 1 link))
9499 (case-fold-search nil)
9500 (search (match-string 2 link)))
9501 (save-match-data
9502 (if (equal (file-truename buffer-file-name) (file-truename path))
9503 ;; We are linking to this same file, with a search option
9504 (setq link search)))))
9506 ;; Check if we can/should use a relative path. If yes, simplify the link
9507 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9508 (let* ((type (match-string 1 link))
9509 (path (match-string 2 link))
9510 (origpath path)
9511 (case-fold-search nil))
9512 (cond
9513 ((or (eq org-link-file-path-type 'absolute)
9514 (equal complete-file '(16)))
9515 (setq path (abbreviate-file-name (expand-file-name path))))
9516 ((eq org-link-file-path-type 'noabbrev)
9517 (setq path (expand-file-name path)))
9518 ((eq org-link-file-path-type 'relative)
9519 (setq path (file-relative-name path)))
9521 (save-match-data
9522 (if (string-match (concat "^" (regexp-quote
9523 (expand-file-name
9524 (file-name-as-directory
9525 default-directory))))
9526 (expand-file-name path))
9527 ;; We are linking a file with relative path name.
9528 (setq path (substring (expand-file-name path)
9529 (match-end 0)))
9530 (setq path (abbreviate-file-name (expand-file-name path)))))))
9531 (setq link (concat type path))
9532 (if (equal desc origpath)
9533 (setq desc path))))
9535 (if org-make-link-description-function
9536 (setq desc
9537 (or (condition-case nil
9538 (funcall org-make-link-description-function link desc)
9539 (error (progn (message "Can't get link description from `%s'"
9540 (symbol-name org-make-link-description-function))
9541 (sit-for 2) nil)))
9542 (read-string "Description: " default-description)))
9543 (if default-description (setq desc default-description)
9544 (setq desc (or (and auto-desc desc)
9545 (read-string "Description: " desc)))))
9547 (unless (string-match "\\S-" desc) (setq desc nil))
9548 (if remove (apply 'delete-region remove))
9549 (insert (org-make-link-string link desc))))
9551 (defun org-link-try-special-completion (type)
9552 "If there is completion support for link type TYPE, offer it."
9553 (let ((fun (intern (concat "org-" type "-complete-link"))))
9554 (if (functionp fun)
9555 (funcall fun)
9556 (read-string "Link (no completion support): " (concat type ":")))))
9558 (defun org-file-complete-link (&optional arg)
9559 "Create a file link using completion."
9560 (let (file link)
9561 (setq file (org-iread-file-name "File: "))
9562 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9563 (pwd1 (file-name-as-directory (abbreviate-file-name
9564 (expand-file-name ".")))))
9565 (cond
9566 ((equal arg '(16))
9567 (setq link (concat
9568 "file:"
9569 (abbreviate-file-name (expand-file-name file)))))
9570 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9571 (setq link (concat "file:" (match-string 1 file))))
9572 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9573 (expand-file-name file))
9574 (setq link (concat
9575 "file:" (match-string 1 (expand-file-name file)))))
9576 (t (setq link (concat "file:" file)))))
9577 link))
9579 (defun org-iread-file-name (&rest args)
9580 "Read-file-name using `ido-mode' speedup if available.
9581 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9582 See `read-file-name' for a description of parameters."
9583 (org-without-partial-completion
9584 (if (and org-completion-use-ido
9585 (fboundp 'ido-read-file-name)
9586 (boundp 'ido-mode) ido-mode
9587 (listp (second args)))
9588 (let ((ido-enter-matching-directory nil))
9589 (apply 'ido-read-file-name args))
9590 (apply 'read-file-name args))))
9592 (defun org-completing-read (&rest args)
9593 "Completing-read with SPACE being a normal character."
9594 (let ((enable-recursive-minibuffers t)
9595 (minibuffer-local-completion-map
9596 (copy-keymap minibuffer-local-completion-map)))
9597 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9598 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9599 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9600 (apply 'org-icompleting-read args)))
9602 (defun org-completing-read-no-i (&rest args)
9603 (let (org-completion-use-ido org-completion-use-iswitchb)
9604 (apply 'org-completing-read args)))
9606 (defun org-iswitchb-completing-read (prompt choices &rest args)
9607 "Use iswitch as a completing-read replacement to choose from choices.
9608 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9609 from."
9610 (let* ((iswitchb-use-virtual-buffers nil)
9611 (iswitchb-make-buflist-hook
9612 (lambda ()
9613 (setq iswitchb-temp-buflist choices))))
9614 (iswitchb-read-buffer prompt)))
9616 (defun org-icompleting-read (&rest args)
9617 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9618 (org-without-partial-completion
9619 (if (and org-completion-use-ido
9620 (fboundp 'ido-completing-read)
9621 (boundp 'ido-mode) ido-mode
9622 (listp (second args)))
9623 (let ((ido-enter-matching-directory nil))
9624 (apply 'ido-completing-read (concat (car args))
9625 (if (consp (car (nth 1 args)))
9626 (mapcar 'car (nth 1 args))
9627 (nth 1 args))
9628 (cddr args)))
9629 (if (and org-completion-use-iswitchb
9630 (boundp 'iswitchb-mode) iswitchb-mode
9631 (listp (second args)))
9632 (apply 'org-iswitchb-completing-read (concat (car args))
9633 (if (consp (car (nth 1 args)))
9634 (mapcar 'car (nth 1 args))
9635 (nth 1 args))
9636 (cddr args))
9637 (apply 'completing-read args)))))
9639 (defun org-extract-attributes (s)
9640 "Extract the attributes cookie from a string and set as text property."
9641 (let (a attr (start 0) key value)
9642 (save-match-data
9643 (when (string-match "{{\\([^}]+\\)}}$" s)
9644 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9645 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9646 (setq key (match-string 1 a) value (match-string 2 a)
9647 start (match-end 0)
9648 attr (plist-put attr (intern key) value))))
9649 (org-add-props s nil 'org-attr attr))
9652 (defun org-extract-attributes-from-string (tag)
9653 (let (key value attr)
9654 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9655 (setq key (match-string 1 tag) value (match-string 2 tag)
9656 tag (replace-match "" t t tag)
9657 attr (plist-put attr (intern key) value)))
9658 (cons tag attr)))
9660 (defun org-attributes-to-string (plist)
9661 "Format a property list into an HTML attribute list."
9662 (let ((s "") key value)
9663 (while plist
9664 (setq key (pop plist) value (pop plist))
9665 (and value
9666 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9669 ;;; Opening/following a link
9671 (defvar org-link-search-failed nil)
9673 (defvar org-open-link-functions nil
9674 "Hook for functions finding a plain text link.
9675 These functions must take a single argument, the link content.
9676 They will be called for links that look like [[link text][description]]
9677 when LINK TEXT does not have a protocol like \"http:\" and does not look
9678 like a filename (e.g. \"./blue.png\").
9680 These functions will be called *before* Org attempts to resolve the
9681 link by doing text searches in the current buffer - so if you want a
9682 link \"[[target]]\" to still find \"<<target>>\", your function should
9683 handle this as a special case.
9685 When the function does handle the link, it must return a non-nil value.
9686 If it decides that it is not responsible for this link, it must return
9687 nil to indicate that that Org-mode can continue with other options
9688 like exact and fuzzy text search.")
9690 (defun org-next-link ()
9691 "Move forward to the next link.
9692 If the link is in hidden text, expose it."
9693 (interactive)
9694 (when (and org-link-search-failed (eq this-command last-command))
9695 (goto-char (point-min))
9696 (message "Link search wrapped back to beginning of buffer"))
9697 (setq org-link-search-failed nil)
9698 (let* ((pos (point))
9699 (ct (org-context))
9700 (a (assoc :link ct)))
9701 (if a (goto-char (nth 2 a)))
9702 (if (re-search-forward org-any-link-re nil t)
9703 (progn
9704 (goto-char (match-beginning 0))
9705 (if (outline-invisible-p) (org-show-context)))
9706 (goto-char pos)
9707 (setq org-link-search-failed t)
9708 (error "No further link found"))))
9710 (defun org-previous-link ()
9711 "Move backward to the previous link.
9712 If the link is in hidden text, expose it."
9713 (interactive)
9714 (when (and org-link-search-failed (eq this-command last-command))
9715 (goto-char (point-max))
9716 (message "Link search wrapped back to end of buffer"))
9717 (setq org-link-search-failed nil)
9718 (let* ((pos (point))
9719 (ct (org-context))
9720 (a (assoc :link ct)))
9721 (if a (goto-char (nth 1 a)))
9722 (if (re-search-backward org-any-link-re nil t)
9723 (progn
9724 (goto-char (match-beginning 0))
9725 (if (outline-invisible-p) (org-show-context)))
9726 (goto-char pos)
9727 (setq org-link-search-failed t)
9728 (error "No further link found"))))
9730 (defun org-translate-link (s)
9731 "Translate a link string if a translation function has been defined."
9732 (if (and org-link-translation-function
9733 (fboundp org-link-translation-function)
9734 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9735 (progn
9736 (setq s (funcall org-link-translation-function
9737 (match-string 1 s) (match-string 2 s)))
9738 (concat (car s) ":" (cdr s)))
9741 (defun org-translate-link-from-planner (type path)
9742 "Translate a link from Emacs Planner syntax so that Org can follow it.
9743 This is still an experimental function, your mileage may vary."
9744 (cond
9745 ((member type '("http" "https" "news" "ftp"))
9746 ;; standard Internet links are the same.
9747 nil)
9748 ((and (equal type "irc") (string-match "^//" path))
9749 ;; Planner has two / at the beginning of an irc link, we have 1.
9750 ;; We should have zero, actually....
9751 (setq path (substring path 1)))
9752 ((and (equal type "lisp") (string-match "^/" path))
9753 ;; Planner has a slash, we do not.
9754 (setq type "elisp" path (substring path 1)))
9755 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9756 ;; A typical message link. Planner has the id after the final slash,
9757 ;; we separate it with a hash mark
9758 (setq path (concat (match-string 1 path) "#"
9759 (org-remove-angle-brackets (match-string 2 path)))))
9761 (cons type path))
9763 (defun org-find-file-at-mouse (ev)
9764 "Open file link or URL at mouse."
9765 (interactive "e")
9766 (mouse-set-point ev)
9767 (org-open-at-point 'in-emacs))
9769 (defun org-open-at-mouse (ev)
9770 "Open file link or URL at mouse.
9771 See the docstring of `org-open-file' for details."
9772 (interactive "e")
9773 (mouse-set-point ev)
9774 (if (eq major-mode 'org-agenda-mode)
9775 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9776 (org-open-at-point))
9778 (defvar org-window-config-before-follow-link nil
9779 "The window configuration before following a link.
9780 This is saved in case the need arises to restore it.")
9782 (defvar org-open-link-marker (make-marker)
9783 "Marker pointing to the location where `org-open-at-point; was called.")
9785 ;;;###autoload
9786 (defun org-open-at-point-global ()
9787 "Follow a link like Org-mode does.
9788 This command can be called in any mode to follow a link that has
9789 Org-mode syntax."
9790 (interactive)
9791 (org-run-like-in-org-mode 'org-open-at-point))
9793 ;;;###autoload
9794 (defun org-open-link-from-string (s &optional arg reference-buffer)
9795 "Open a link in the string S, as if it was in Org-mode."
9796 (interactive "sLink: \nP")
9797 (let ((reference-buffer (or reference-buffer (current-buffer))))
9798 (with-temp-buffer
9799 (let ((org-inhibit-startup (not reference-buffer)))
9800 (org-mode)
9801 (insert s)
9802 (goto-char (point-min))
9803 (when reference-buffer
9804 (setq org-link-abbrev-alist-local
9805 (with-current-buffer reference-buffer
9806 org-link-abbrev-alist-local)))
9807 (org-open-at-point arg reference-buffer)))))
9809 (defvar org-open-at-point-functions nil
9810 "Hook that is run when following a link at point.
9812 Functions in this hook must return t if they identify and follow
9813 a link at point. If they don't find anything interesting at point,
9814 they must return nil.")
9816 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9817 (defun org-open-at-point (&optional arg reference-buffer)
9818 "Open link at or after point.
9819 If there is no link at point, this function will search forward up to
9820 the end of the current line.
9821 Normally, files will be opened by an appropriate application. If the
9822 optional prefix argument ARG is non-nil, Emacs will visit the file.
9823 With a double prefix argument, try to open outside of Emacs, in the
9824 application the system uses for this file type."
9825 (interactive "P")
9826 ;; if in a code block, then open the block's results
9827 (unless (call-interactively #'org-babel-open-src-block-result)
9828 (org-load-modules-maybe)
9829 (move-marker org-open-link-marker (point))
9830 (setq org-window-config-before-follow-link (current-window-configuration))
9831 (org-remove-occur-highlights nil nil t)
9832 (cond
9833 ((and (org-at-heading-p)
9834 (not (org-at-timestamp-p t))
9835 (not (org-in-regexp
9836 (concat org-plain-link-re "\\|"
9837 org-bracket-link-regexp "\\|"
9838 org-angle-link-re "\\|"
9839 "[ \t]:[^ \t\n]+:[ \t]*$")))
9840 (not (get-text-property (point) 'org-linked-text)))
9841 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9842 (lk (car lkall))
9843 (lkend (cdr lkall)))
9844 (when lk
9845 (prog1 (search-forward lk nil lkend)
9846 (goto-char (match-beginning 0))
9847 (org-open-at-point))))
9848 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9849 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9850 ((and (org-at-timestamp-p t)
9851 (not (org-in-regexp org-bracket-link-regexp)))
9852 (org-follow-timestamp-link))
9853 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9854 (not (org-in-regexp org-any-link-re)))
9855 (org-footnote-action))
9857 (let (type path link line search (pos (point)))
9858 (catch 'match
9859 (save-excursion
9860 (skip-chars-forward "^]\n\r")
9861 (when (org-in-regexp org-bracket-link-regexp 1)
9862 (setq link (org-extract-attributes
9863 (org-link-unescape (org-match-string-no-properties 1))))
9864 (while (string-match " *\n *" link)
9865 (setq link (replace-match " " t t link)))
9866 (setq link (org-link-expand-abbrev link))
9867 (cond
9868 ((or (file-name-absolute-p link)
9869 (string-match "^\\.\\.?/" link))
9870 (setq type "file" path link))
9871 ((string-match org-link-re-with-space3 link)
9872 (setq type (match-string 1 link) path (match-string 2 link)))
9873 ((string-match "^help:+\\(.+\\)" link)
9874 (setq type "help" path (match-string 1 link)))
9875 (t (setq type "thisfile" path link)))
9876 (throw 'match t)))
9878 (when (get-text-property (point) 'org-linked-text)
9879 (setq type "thisfile"
9880 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9881 (1+ (point)) (point))
9882 path (buffer-substring
9883 (or (previous-single-property-change pos 'org-linked-text)
9884 (point-min))
9885 (or (next-single-property-change pos 'org-linked-text)
9886 (point-max))))
9887 (throw 'match t))
9889 (save-excursion
9890 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9891 (when (or (org-in-regexp org-angle-link-re)
9892 (and plinkpos (goto-char (car plinkpos))
9893 (save-match-data (not (looking-back "\\[\\[")))))
9894 (setq type (match-string 1)
9895 path (org-link-unescape (match-string 2)))
9896 (throw 'match t))))
9897 (save-excursion
9898 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9899 (setq type "tags"
9900 path (match-string 1))
9901 (while (string-match ":" path)
9902 (setq path (replace-match "+" t t path)))
9903 (throw 'match t)))
9904 (when (org-in-regexp "<\\([^><\n]+\\)>")
9905 (setq type "tree-match"
9906 path (match-string 1))
9907 (throw 'match t)))
9908 (unless path
9909 (user-error "No link found"))
9911 ;; switch back to reference buffer
9912 ;; needed when if called in a temporary buffer through
9913 ;; org-open-link-from-string
9914 (with-current-buffer (or reference-buffer (current-buffer))
9916 ;; Remove any trailing spaces in path
9917 (if (string-match " +\\'" path)
9918 (setq path (replace-match "" t t path)))
9919 (if (and org-link-translation-function
9920 (fboundp org-link-translation-function))
9921 ;; Check if we need to translate the link
9922 (let ((tmp (funcall org-link-translation-function type path)))
9923 (setq type (car tmp) path (cdr tmp))))
9925 (cond
9927 ((assoc type org-link-protocols)
9928 (funcall (nth 1 (assoc type org-link-protocols)) path))
9930 ((equal type "help")
9931 (let ((f-or-v (intern path)))
9932 (cond ((fboundp f-or-v)
9933 (describe-function f-or-v))
9934 ((boundp f-or-v)
9935 (describe-variable f-or-v))
9936 (t (error "Not a known function or variable")))))
9938 ((equal type "mailto")
9939 (let ((cmd (car org-link-mailto-program))
9940 (args (cdr org-link-mailto-program)) args1
9941 (address path) (subject "") a)
9942 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9943 (setq address (match-string 1 path)
9944 subject (org-link-escape (match-string 2 path))))
9945 (while args
9946 (cond
9947 ((not (stringp (car args))) (push (pop args) args1))
9948 (t (setq a (pop args))
9949 (if (string-match "%a" a)
9950 (setq a (replace-match address t t a)))
9951 (if (string-match "%s" a)
9952 (setq a (replace-match subject t t a)))
9953 (push a args1))))
9954 (apply cmd (nreverse args1))))
9956 ((member type '("http" "https" "ftp" "news"))
9957 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9958 (org-link-escape
9959 path org-link-escape-chars-browser)
9960 path))))
9962 ((string= type "doi")
9963 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9964 (org-link-escape
9965 path org-link-escape-chars-browser)
9966 path))))
9968 ((member type '("message"))
9969 (browse-url (concat type ":" path)))
9971 ((string= type "tags")
9972 (org-tags-view arg path))
9974 ((string= type "tree-match")
9975 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9977 ((string= type "file")
9978 (if (string-match "::\\([0-9]+\\)\\'" path)
9979 (setq line (string-to-number (match-string 1 path))
9980 path (substring path 0 (match-beginning 0)))
9981 (if (string-match "::\\(.+\\)\\'" path)
9982 (setq search (match-string 1 path)
9983 path (substring path 0 (match-beginning 0)))))
9984 (if (string-match "[*?{]" (file-name-nondirectory path))
9985 (dired path)
9986 (org-open-file path arg line search)))
9988 ((string= type "shell")
9989 (let ((buf (generate-new-buffer "*Org Shell Output"))
9990 (cmd path))
9991 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9992 (string-match org-confirm-shell-link-not-regexp cmd))
9993 (not org-confirm-shell-link-function)
9994 (funcall org-confirm-shell-link-function
9995 (format "Execute \"%s\" in shell? "
9996 (org-add-props cmd nil
9997 'face 'org-warning))))
9998 (progn
9999 (message "Executing %s" cmd)
10000 (shell-command cmd buf)
10001 (if (featurep 'midnight)
10002 (setq clean-buffer-list-kill-buffer-names
10003 (cons buf clean-buffer-list-kill-buffer-names))))
10004 (error "Abort"))))
10006 ((string= type "elisp")
10007 (let ((cmd path))
10008 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10009 (string-match org-confirm-elisp-link-not-regexp cmd))
10010 (not org-confirm-elisp-link-function)
10011 (funcall org-confirm-elisp-link-function
10012 (format "Execute \"%s\" as elisp? "
10013 (org-add-props cmd nil
10014 'face 'org-warning))))
10015 (message "%s => %s" cmd
10016 (if (equal (string-to-char cmd) ?\()
10017 (eval (read cmd))
10018 (call-interactively (read cmd))))
10019 (error "Abort"))))
10021 ((and (string= type "thisfile")
10022 (run-hook-with-args-until-success
10023 'org-open-link-functions path)))
10025 ((string= type "thisfile")
10026 (if arg
10027 (switch-to-buffer-other-window
10028 (org-get-buffer-for-internal-link (current-buffer)))
10029 (org-mark-ring-push))
10030 (let ((cmd `(org-link-search
10031 ,path
10032 ,(cond ((equal arg '(4)) ''occur)
10033 ((equal arg '(16)) ''org-occur))
10034 ,pos)))
10035 (condition-case nil (let ((org-link-search-inhibit-query t))
10036 (eval cmd))
10037 (error (progn (widen) (eval cmd))))))
10039 (t (browse-url-at-point)))))))
10040 (move-marker org-open-link-marker nil)
10041 (run-hook-with-args 'org-follow-link-hook)))
10043 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10044 "Offer links in the current entry and return the selected link.
10045 If there is only one link, return it.
10046 If NTH is an integer, return the NTH link found.
10047 If ZERO is a string, check also this string for a link, and if
10048 there is one, return it."
10049 (with-current-buffer buffer
10050 (save-excursion
10051 (save-restriction
10052 (widen)
10053 (goto-char marker)
10054 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10055 "\\(" org-angle-link-re "\\)\\|"
10056 "\\(" org-plain-link-re "\\)"))
10057 (cnt ?0)
10058 (in-emacs (if (integerp nth) nil nth))
10059 have-zero end links link c)
10060 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10061 (push (match-string 0 zero) links)
10062 (setq cnt (1- cnt) have-zero t))
10063 (save-excursion
10064 (org-back-to-heading t)
10065 (setq end (save-excursion (outline-next-heading) (point)))
10066 (while (re-search-forward re end t)
10067 (push (match-string 0) links))
10068 (setq links (org-uniquify (reverse links))))
10069 (cond
10070 ((null links)
10071 (message "No links"))
10072 ((equal (length links) 1)
10073 (setq link (car links)))
10074 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10075 (setq link (nth (if have-zero nth (1- nth)) links)))
10076 (t ; we have to select a link
10077 (save-excursion
10078 (save-window-excursion
10079 (delete-other-windows)
10080 (with-output-to-temp-buffer "*Select Link*"
10081 (mapc (lambda (l)
10082 (if (not (string-match org-bracket-link-regexp l))
10083 (princ (format "[%c] %s\n" (incf cnt)
10084 (org-remove-angle-brackets l)))
10085 (if (match-end 3)
10086 (princ (format "[%c] %s (%s)\n" (incf cnt)
10087 (match-string 3 l) (match-string 1 l)))
10088 (princ (format "[%c] %s\n" (incf cnt)
10089 (match-string 1 l))))))
10090 links))
10091 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10092 (message "Select link to open, RET to open all:")
10093 (setq c (read-char-exclusive))
10094 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10095 (when (equal c ?q) (error "Abort"))
10096 (if (equal c ?\C-m)
10097 (setq link links)
10098 (setq nth (- c ?0))
10099 (if have-zero (setq nth (1+ nth)))
10100 (unless (and (integerp nth) (>= (length links) nth))
10101 (error "Invalid link selection"))
10102 (setq link (nth (1- nth) links)))))
10103 (cons link end))))))
10105 ;; Add special file links that specify the way of opening
10107 (org-add-link-type "file+sys" 'org-open-file-with-system)
10108 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10109 (defun org-open-file-with-system (path)
10110 "Open file at PATH using the system way of opening it."
10111 (org-open-file path 'system))
10112 (defun org-open-file-with-emacs (path)
10113 "Open file at PATH in Emacs."
10114 (org-open-file path 'emacs))
10115 (defun org-remove-file-link-modifiers ()
10116 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10117 (goto-char (point-min))
10118 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10119 (org-if-unprotected
10120 (replace-match "file:" t t))))
10121 (eval-after-load "org-exp"
10122 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10123 'org-remove-file-link-modifiers))
10125 ;;;; Time estimates
10127 (defun org-get-effort (&optional pom)
10128 "Get the effort estimate for the current entry."
10129 (org-entry-get pom org-effort-property))
10131 ;;; File search
10133 (defvar org-create-file-search-functions nil
10134 "List of functions to construct the right search string for a file link.
10135 These functions are called in turn with point at the location to
10136 which the link should point.
10138 A function in the hook should first test if it would like to
10139 handle this file type, for example by checking the `major-mode'
10140 or the file extension. If it decides not to handle this file, it
10141 should just return nil to give other functions a chance. If it
10142 does handle the file, it must return the search string to be used
10143 when following the link. The search string will be part of the
10144 file link, given after a double colon, and `org-open-at-point'
10145 will automatically search for it. If special measures must be
10146 taken to make the search successful, another function should be
10147 added to the companion hook `org-execute-file-search-functions',
10148 which see.
10150 A function in this hook may also use `setq' to set the variable
10151 `description' to provide a suggestion for the descriptive text to
10152 be used for this link when it gets inserted into an Org-mode
10153 buffer with \\[org-insert-link].")
10155 (defvar org-execute-file-search-functions nil
10156 "List of functions to execute a file search triggered by a link.
10158 Functions added to this hook must accept a single argument, the
10159 search string that was part of the file link, the part after the
10160 double colon. The function must first check if it would like to
10161 handle this search, for example by checking the `major-mode' or
10162 the file extension. If it decides not to handle this search, it
10163 should just return nil to give other functions a chance. If it
10164 does handle the search, it must return a non-nil value to keep
10165 other functions from trying.
10167 Each function can access the current prefix argument through the
10168 variable `current-prefix-argument'. Note that a single prefix is
10169 used to force opening a link in Emacs, so it may be good to only
10170 use a numeric or double prefix to guide the search function.
10172 In case this is needed, a function in this hook can also restore
10173 the window configuration before `org-open-at-point' was called using:
10175 (set-window-configuration org-window-config-before-follow-link)")
10177 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10178 (defun org-link-search (s &optional type avoid-pos stealth)
10179 "Search for a link search option.
10180 If S is surrounded by forward slashes, it is interpreted as a
10181 regular expression. In org-mode files, this will create an `org-occur'
10182 sparse tree. In ordinary files, `occur' will be used to list matches.
10183 If the current buffer is in `dired-mode', grep will be used to search
10184 in all files. If AVOID-POS is given, ignore matches near that position.
10186 When optional argument STEALTH is non-nil, do not modify
10187 visibility around point, thus ignoring
10188 `org-show-hierarchy-above', `org-show-following-heading' and
10189 `org-show-siblings' variables."
10190 (let ((case-fold-search t)
10191 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10192 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10193 (append '(("") (" ") ("\t") ("\n"))
10194 org-emphasis-alist)
10195 "\\|") "\\)"))
10196 (pos (point))
10197 (pre nil) (post nil)
10198 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10199 (cond
10200 ;; First check if there are any special search functions
10201 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10202 ;; Now try the builtin stuff
10203 ((and (equal (string-to-char s0) ?#)
10204 (> (length s0) 1)
10205 (save-excursion
10206 (goto-char (point-min))
10207 (and
10208 (re-search-forward
10209 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10210 (setq type 'dedicated
10211 pos (match-beginning 0))))
10212 ;; There is an exact target for this
10213 (goto-char pos)
10214 (org-back-to-heading t)))
10215 ((save-excursion
10216 (goto-char (point-min))
10217 (and
10218 (re-search-forward
10219 (concat "<<" (regexp-quote s0) ">>") nil t)
10220 (setq type 'dedicated
10221 pos (match-beginning 0))))
10222 ;; There is an exact target for this
10223 (goto-char pos))
10224 ((save-excursion
10225 (goto-char (point-min))
10226 (and
10227 (re-search-forward
10228 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10229 (setq type 'dedicated pos (match-beginning 0))))
10230 ;; Found an invisible target.
10231 (goto-char pos))
10232 ((save-excursion
10233 (goto-char (point-min))
10234 (and
10235 (re-search-forward
10236 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10237 (setq type 'dedicated pos (match-beginning 0))))
10238 ;; Found an element with a matching #+name affiliated keyword.
10239 (goto-char pos))
10240 ((and (string-match "^(\\(.*\\))$" s0)
10241 (save-excursion
10242 (goto-char (point-min))
10243 (and
10244 (re-search-forward
10245 (concat "[^[]" (regexp-quote
10246 (format org-coderef-label-format
10247 (match-string 1 s0))))
10248 nil t)
10249 (setq type 'dedicated
10250 pos (1+ (match-beginning 0))))))
10251 ;; There is a coderef target for this
10252 (goto-char pos))
10253 ((string-match "^/\\(.*\\)/$" s)
10254 ;; A regular expression
10255 (cond
10256 ((derived-mode-p 'org-mode)
10257 (org-occur (match-string 1 s)))
10258 ;;((eq major-mode 'dired-mode)
10259 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10260 (t (org-do-occur (match-string 1 s)))))
10261 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10262 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10263 (goto-char (point-min))
10264 (cond
10265 ((let (case-fold-search)
10266 (re-search-forward (format org-complex-heading-regexp-format
10267 (regexp-quote s))
10268 nil t))
10269 ;; OK, found a match
10270 (setq type 'dedicated)
10271 (goto-char (match-beginning 0)))
10272 ((and (not org-link-search-inhibit-query)
10273 (eq org-link-search-must-match-exact-headline 'query-to-create)
10274 (y-or-n-p "No match - create this as a new heading? "))
10275 (goto-char (point-max))
10276 (or (bolp) (newline))
10277 (insert "* " s "\n")
10278 (beginning-of-line 0))
10280 (goto-char pos)
10281 (error "No match"))))
10283 ;; A normal search string
10284 (when (equal (string-to-char s) ?*)
10285 ;; Anchor on headlines, post may include tags.
10286 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10287 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10288 s (substring s 1)))
10289 (remove-text-properties
10290 0 (length s)
10291 '(face nil mouse-face nil keymap nil fontified nil) s)
10292 ;; Make a series of regular expressions to find a match
10293 (setq words (org-split-string s "[ \n\r\t]+")
10295 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10296 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10297 "\\)" markers)
10298 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10299 re2a (concat "[ \t\r\n]" re2a_)
10300 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10301 re4 (concat "[^a-zA-Z_]" re4_)
10303 re1 (concat pre re2 post)
10304 re3 (concat pre (if pre re4_ re4) post)
10305 re5 (concat pre ".*" re4)
10306 re2 (concat pre re2)
10307 re2a (concat pre (if pre re2a_ re2a))
10308 re4 (concat pre (if pre re4_ re4))
10309 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10310 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10311 re5 "\\)"
10313 (cond
10314 ((eq type 'org-occur) (org-occur reall))
10315 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10316 (t (goto-char (point-min))
10317 (setq type 'fuzzy)
10318 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10319 (org-search-not-self 1 re1 nil t)
10320 (org-search-not-self 1 re2 nil t)
10321 (org-search-not-self 1 re2a nil t)
10322 (org-search-not-self 1 re3 nil t)
10323 (org-search-not-self 1 re4 nil t)
10324 (org-search-not-self 1 re5 nil t)
10326 (goto-char (match-beginning 1))
10327 (goto-char pos)
10328 (error "No match"))))))
10329 (and (derived-mode-p 'org-mode)
10330 (not stealth)
10331 (org-show-context 'link-search))
10332 type))
10334 (defun org-search-not-self (group &rest args)
10335 "Execute `re-search-forward', but only accept matches that do not
10336 enclose the position of `org-open-link-marker'."
10337 (let ((m org-open-link-marker))
10338 (catch 'exit
10339 (while (apply 're-search-forward args)
10340 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10341 (goto-char (match-end group))
10342 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10343 (> (match-beginning 0) (marker-position m))
10344 (< (match-end 0) (marker-position m)))
10345 (save-match-data
10346 (or (not (org-in-regexp
10347 org-bracket-link-analytic-regexp 1))
10348 (not (match-end 4)) ; no description
10349 (and (<= (match-beginning 4) (point))
10350 (>= (match-end 4) (point))))))
10351 (throw 'exit (point))))))))
10353 (defun org-get-buffer-for-internal-link (buffer)
10354 "Return a buffer to be used for displaying the link target of internal links."
10355 (cond
10356 ((not org-display-internal-link-with-indirect-buffer)
10357 buffer)
10358 ((string-match "(Clone)$" (buffer-name buffer))
10359 (message "Buffer is already a clone, not making another one")
10360 ;; we also do not modify visibility in this case
10361 buffer)
10362 (t ; make a new indirect buffer for displaying the link
10363 (let* ((bn (buffer-name buffer))
10364 (ibn (concat bn "(Clone)"))
10365 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10366 (with-current-buffer ib (org-overview))
10367 ib))))
10369 (defun org-do-occur (regexp &optional cleanup)
10370 "Call the Emacs command `occur'.
10371 If CLEANUP is non-nil, remove the printout of the regular expression
10372 in the *Occur* buffer. This is useful if the regex is long and not useful
10373 to read."
10374 (occur regexp)
10375 (when cleanup
10376 (let ((cwin (selected-window)) win beg end)
10377 (when (setq win (get-buffer-window "*Occur*"))
10378 (select-window win))
10379 (goto-char (point-min))
10380 (when (re-search-forward "match[a-z]+" nil t)
10381 (setq beg (match-end 0))
10382 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10383 (setq end (1- (match-beginning 0)))))
10384 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10385 (goto-char (point-min))
10386 (select-window cwin))))
10388 ;;; The mark ring for links jumps
10390 (defvar org-mark-ring nil
10391 "Mark ring for positions before jumps in Org-mode.")
10392 (defvar org-mark-ring-last-goto nil
10393 "Last position in the mark ring used to go back.")
10394 ;; Fill and close the ring
10395 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10396 (loop for i from 1 to org-mark-ring-length do
10397 (push (make-marker) org-mark-ring))
10398 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10399 org-mark-ring)
10401 (defun org-mark-ring-push (&optional pos buffer)
10402 "Put the current position or POS into the mark ring and rotate it."
10403 (interactive)
10404 (setq pos (or pos (point)))
10405 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10406 (move-marker (car org-mark-ring)
10407 (or pos (point))
10408 (or buffer (current-buffer)))
10409 (message "%s"
10410 (substitute-command-keys
10411 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10413 (defun org-mark-ring-goto (&optional n)
10414 "Jump to the previous position in the mark ring.
10415 With prefix arg N, jump back that many stored positions. When
10416 called several times in succession, walk through the entire ring.
10417 Org-mode commands jumping to a different position in the current file,
10418 or to another Org-mode file, automatically push the old position
10419 onto the ring."
10420 (interactive "p")
10421 (let (p m)
10422 (if (eq last-command this-command)
10423 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10424 (setq p org-mark-ring))
10425 (setq org-mark-ring-last-goto p)
10426 (setq m (car p))
10427 (org-pop-to-buffer-same-window (marker-buffer m))
10428 (goto-char m)
10429 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10431 (defun org-remove-angle-brackets (s)
10432 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10433 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10435 (defun org-add-angle-brackets (s)
10436 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10437 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10439 (defun org-remove-double-quotes (s)
10440 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10441 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10444 ;;; Following specific links
10446 (defun org-follow-timestamp-link ()
10447 "Open an agenda view for the time-stamp date/range at point."
10448 (cond
10449 ((org-at-date-range-p t)
10450 (let ((org-agenda-start-on-weekday)
10451 (t1 (match-string 1))
10452 (t2 (match-string 2)) tt1 tt2)
10453 (setq tt1 (time-to-days (org-time-string-to-time t1))
10454 tt2 (time-to-days (org-time-string-to-time t2)))
10455 (let ((org-agenda-buffer-tmp-name
10456 (format "*Org Agenda(a:%s)"
10457 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10458 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10459 ((org-at-timestamp-p t)
10460 (let ((org-agenda-buffer-tmp-name
10461 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10462 (org-agenda-list nil (time-to-days (org-time-string-to-time
10463 (substring (match-string 1) 0 10)))
10464 1)))
10465 (t (error "This should not happen"))))
10468 ;;; Following file links
10469 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10470 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10471 (declare-function mailcap-mime-info
10472 "mailcap" (string &optional request no-decode))
10473 (defvar org-wait nil)
10474 (defun org-open-file (path &optional in-emacs line search)
10475 "Open the file at PATH.
10476 First, this expands any special file name abbreviations. Then the
10477 configuration variable `org-file-apps' is checked if it contains an
10478 entry for this file type, and if yes, the corresponding command is launched.
10480 If no application is found, Emacs simply visits the file.
10482 With optional prefix argument IN-EMACS, Emacs will visit the file.
10483 With a double \\[universal-argument] \\[universal-argument] \
10484 prefix arg, Org tries to avoid opening in Emacs
10485 and to use an external application to visit the file.
10487 Optional LINE specifies a line to go to, optional SEARCH a string
10488 to search for. If LINE or SEARCH is given, the file will be
10489 opened in Emacs, unless an entry from org-file-apps that makes
10490 use of groups in a regexp matches.
10492 If you want to change the way frames are used when following a
10493 link, please customize `org-link-frame-setup'.
10495 If the file does not exist, an error is thrown."
10496 (let* ((file (if (equal path "")
10497 buffer-file-name
10498 (substitute-in-file-name (expand-file-name path))))
10499 (file-apps (append org-file-apps (org-default-apps)))
10500 (apps (org-remove-if
10501 'org-file-apps-entry-match-against-dlink-p file-apps))
10502 (apps-dlink (org-remove-if-not
10503 'org-file-apps-entry-match-against-dlink-p file-apps))
10504 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10505 (dirp (if remp nil (file-directory-p file)))
10506 (file (if (and dirp org-open-directory-means-index-dot-org)
10507 (concat (file-name-as-directory file) "index.org")
10508 file))
10509 (a-m-a-p (assq 'auto-mode apps))
10510 (dfile (downcase file))
10511 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10512 (link (cond ((and (eq line nil)
10513 (eq search nil))
10514 file)
10515 (line
10516 (concat file "::" (number-to-string line)))
10517 (search
10518 (concat file "::" search))))
10519 (dlink (downcase link))
10520 (old-buffer (current-buffer))
10521 (old-pos (point))
10522 (old-mode major-mode)
10523 ext cmd link-match-data)
10524 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10525 (setq ext (match-string 1 dfile))
10526 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10527 (setq ext (match-string 1 dfile))))
10528 (cond
10529 ((member in-emacs '((16) system))
10530 (setq cmd (cdr (assoc 'system apps))))
10531 (in-emacs (setq cmd 'emacs))
10533 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10534 (and dirp (cdr (assoc 'directory apps)))
10535 ; first, try matching against apps-dlink
10536 ; if we get a match here, store the match data for later
10537 (let ((match (assoc-default dlink apps-dlink
10538 'string-match)))
10539 (if match
10540 (progn (setq link-match-data (match-data))
10541 match)
10542 (progn (setq in-emacs (or in-emacs line search))
10543 nil))) ; if we have no match in apps-dlink,
10544 ; always open the file in emacs if line or search
10545 ; is given (for backwards compatibility)
10546 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10547 'string-match)
10548 (cdr (assoc ext apps))
10549 (cdr (assoc t apps))))))
10550 (when (eq cmd 'system)
10551 (setq cmd (cdr (assoc 'system apps))))
10552 (when (eq cmd 'default)
10553 (setq cmd (cdr (assoc t apps))))
10554 (when (eq cmd 'mailcap)
10555 (require 'mailcap)
10556 (mailcap-parse-mailcaps)
10557 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10558 (command (mailcap-mime-info mime-type)))
10559 (if (stringp command)
10560 (setq cmd command)
10561 (setq cmd 'emacs))))
10562 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10563 (not (file-exists-p file))
10564 (not org-open-non-existing-files))
10565 (error "No such file: %s" file))
10566 (cond
10567 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10568 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10569 (while (string-match "['\"]%s['\"]" cmd)
10570 (setq cmd (replace-match "%s" t t cmd)))
10571 (while (string-match "%s" cmd)
10572 (setq cmd (replace-match
10573 (save-match-data
10574 (shell-quote-argument
10575 (convert-standard-filename file)))
10576 t t cmd)))
10578 ;; Replace "%1", "%2" etc. in command with group matches from regex
10579 (save-match-data
10580 (let ((match-index 1)
10581 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10582 (set-match-data link-match-data)
10583 (while (<= match-index number-of-groups)
10584 (let ((regex (concat "%" (number-to-string match-index)))
10585 (replace-with (match-string match-index dlink)))
10586 (while (string-match regex cmd)
10587 (setq cmd (replace-match replace-with t t cmd))))
10588 (setq match-index (+ match-index 1)))))
10590 (save-window-excursion
10591 (message "Running %s...done" cmd)
10592 (start-process-shell-command cmd nil cmd)
10593 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10594 ((or (stringp cmd)
10595 (eq cmd 'emacs))
10596 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10597 (widen)
10598 (if line (org-goto-line line)
10599 (if search (org-link-search search))))
10600 ((consp cmd)
10601 (let ((file (convert-standard-filename file)))
10602 (save-match-data
10603 (set-match-data link-match-data)
10604 (eval cmd))))
10605 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10606 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10607 (or (not (equal old-buffer (current-buffer)))
10608 (not (equal old-pos (point))))
10609 (org-mark-ring-push old-pos old-buffer))))
10611 (defun org-file-apps-entry-match-against-dlink-p (entry)
10612 "This function returns non-nil if `entry' uses a regular
10613 expression which should be matched against the whole link by
10614 org-open-file.
10616 It assumes that is the case when the entry uses a regular
10617 expression which has at least one grouping construct and the
10618 action is either a lisp form or a command string containing
10619 '%1', i.e. using at least one subexpression match as a
10620 parameter."
10621 (let ((selector (car entry))
10622 (action (cdr entry)))
10623 (if (stringp selector)
10624 (and (> (regexp-opt-depth selector) 0)
10625 (or (and (stringp action)
10626 (string-match "%[0-9]" action))
10627 (consp action)))
10628 nil)))
10630 (defun org-default-apps ()
10631 "Return the default applications for this operating system."
10632 (cond
10633 ((eq system-type 'darwin)
10634 org-file-apps-defaults-macosx)
10635 ((eq system-type 'windows-nt)
10636 org-file-apps-defaults-windowsnt)
10637 (t org-file-apps-defaults-gnu)))
10639 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10640 "Convert extensions to regular expressions in the cars of LIST.
10641 Also, weed out any non-string entries, because the return value is used
10642 only for regexp matching.
10643 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10644 point to the symbol `emacs', indicating that the file should
10645 be opened in Emacs."
10646 (append
10647 (delq nil
10648 (mapcar (lambda (x)
10649 (if (not (stringp (car x)))
10651 (if (string-match "\\W" (car x))
10653 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10654 list))
10655 (if add-auto-mode
10656 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10658 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10659 (defun org-file-remote-p (file)
10660 "Test whether FILE specifies a location on a remote system.
10661 Return non-nil if the location is indeed remote.
10663 For example, the filename \"/user@host:/foo\" specifies a location
10664 on the system \"/user@host:\"."
10665 (cond ((fboundp 'file-remote-p)
10666 (file-remote-p file))
10667 ((fboundp 'tramp-handle-file-remote-p)
10668 (tramp-handle-file-remote-p file))
10669 ((and (boundp 'ange-ftp-name-format)
10670 (string-match (car ange-ftp-name-format) file))
10671 t)))
10674 ;;;; Refiling
10676 (defun org-get-org-file ()
10677 "Read a filename, with default directory `org-directory'."
10678 (let ((default (or org-default-notes-file remember-data-file)))
10679 (read-file-name (format "File name [%s]: " default)
10680 (file-name-as-directory org-directory)
10681 default)))
10683 (defun org-notes-order-reversed-p ()
10684 "Check if the current file should receive notes in reversed order."
10685 (cond
10686 ((not org-reverse-note-order) nil)
10687 ((eq t org-reverse-note-order) t)
10688 ((not (listp org-reverse-note-order)) nil)
10689 (t (catch 'exit
10690 (let ((all org-reverse-note-order)
10691 entry)
10692 (while (setq entry (pop all))
10693 (if (string-match (car entry) buffer-file-name)
10694 (throw 'exit (cdr entry))))
10695 nil)))))
10697 (defvar org-refile-target-table nil
10698 "The list of refile targets, created by `org-refile'.")
10700 (defvar org-agenda-new-buffers nil
10701 "Buffers created to visit agenda files.")
10703 (defvar org-refile-cache nil
10704 "Cache for refile targets.")
10706 (defvar org-refile-markers nil
10707 "All the markers used for caching refile locations.")
10709 (defun org-refile-marker (pos)
10710 "Get a new refile marker, but only if caching is in use."
10711 (if (not org-refile-use-cache)
10713 (let ((m (make-marker)))
10714 (move-marker m pos)
10715 (push m org-refile-markers)
10716 m)))
10718 (defun org-refile-cache-clear ()
10719 "Clear the refile cache and disable all the markers."
10720 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10721 (setq org-refile-markers nil)
10722 (setq org-refile-cache nil)
10723 (message "Refile cache has been cleared"))
10725 (defun org-refile-cache-check-set (set)
10726 "Check if all the markers in the cache still have live buffers."
10727 (let (marker)
10728 (catch 'exit
10729 (while (and set (setq marker (nth 3 (pop set))))
10730 ;; if org-refile-use-outline-path is 'file, marker may be nil
10731 (when (and marker (null (marker-buffer marker)))
10732 (message "not found") (sit-for 3)
10733 (throw 'exit nil)))
10734 t)))
10736 (defun org-refile-cache-put (set &rest identifiers)
10737 "Push the refile targets SET into the cache, under IDENTIFIERS."
10738 (let* ((key (sha1 (prin1-to-string identifiers)))
10739 (entry (assoc key org-refile-cache)))
10740 (if entry
10741 (setcdr entry set)
10742 (push (cons key set) org-refile-cache))))
10744 (defun org-refile-cache-get (&rest identifiers)
10745 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10746 (cond
10747 ((not org-refile-cache) nil)
10748 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10750 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10751 org-refile-cache))))
10752 (and set (org-refile-cache-check-set set) set)))))
10754 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10755 "Produce a table with refile targets."
10756 (let ((case-fold-search nil)
10757 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10758 (entries (or org-refile-targets '((nil . (:level . 1)))))
10759 targets tgs txt re files f desc descre fast-path-p level pos0)
10760 (message "Getting targets...")
10761 (with-current-buffer (or default-buffer (current-buffer))
10762 (while (setq entry (pop entries))
10763 (setq files (car entry) desc (cdr entry))
10764 (setq fast-path-p nil)
10765 (cond
10766 ((null files) (setq files (list (current-buffer))))
10767 ((eq files 'org-agenda-files)
10768 (setq files (org-agenda-files 'unrestricted)))
10769 ((and (symbolp files) (fboundp files))
10770 (setq files (funcall files)))
10771 ((and (symbolp files) (boundp files))
10772 (setq files (symbol-value files))))
10773 (if (stringp files) (setq files (list files)))
10774 (cond
10775 ((eq (car desc) :tag)
10776 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10777 ((eq (car desc) :todo)
10778 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10779 ((eq (car desc) :regexp)
10780 (setq descre (cdr desc)))
10781 ((eq (car desc) :level)
10782 (setq descre (concat "^\\*\\{" (number-to-string
10783 (if org-odd-levels-only
10784 (1- (* 2 (cdr desc)))
10785 (cdr desc)))
10786 "\\}[ \t]")))
10787 ((eq (car desc) :maxlevel)
10788 (setq fast-path-p t)
10789 (setq descre (concat "^\\*\\{1," (number-to-string
10790 (if org-odd-levels-only
10791 (1- (* 2 (cdr desc)))
10792 (cdr desc)))
10793 "\\}[ \t]")))
10794 (t (error "Bad refiling target description %s" desc)))
10795 (while (setq f (pop files))
10796 (with-current-buffer
10797 (if (bufferp f) f (org-get-agenda-file-buffer f))
10799 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10800 (progn
10801 (if (bufferp f) (setq f (buffer-file-name
10802 (buffer-base-buffer f))))
10803 (setq f (and f (expand-file-name f)))
10804 (if (eq org-refile-use-outline-path 'file)
10805 (push (list (file-name-nondirectory f) f nil nil) tgs))
10806 (save-excursion
10807 (save-restriction
10808 (widen)
10809 (goto-char (point-min))
10810 (while (re-search-forward descre nil t)
10811 (goto-char (setq pos0 (point-at-bol)))
10812 (catch 'next
10813 (when org-refile-target-verify-function
10814 (save-match-data
10815 (or (funcall org-refile-target-verify-function)
10816 (throw 'next t))))
10817 (when (and (looking-at org-complex-heading-regexp)
10818 (not (member (match-string 4) excluded-entries))
10819 (match-string 4))
10820 (setq level (org-reduced-level
10821 (- (match-end 1) (match-beginning 1)))
10822 txt (org-link-display-format (match-string 4))
10823 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10824 re (format org-complex-heading-regexp-format
10825 (regexp-quote (match-string 4))))
10826 (when org-refile-use-outline-path
10827 (setq txt (mapconcat
10828 'org-protect-slash
10829 (append
10830 (if (eq org-refile-use-outline-path
10831 'file)
10832 (list (file-name-nondirectory
10833 (buffer-file-name
10834 (buffer-base-buffer))))
10835 (if (eq org-refile-use-outline-path
10836 'full-file-path)
10837 (list (buffer-file-name
10838 (buffer-base-buffer)))))
10839 (org-get-outline-path fast-path-p
10840 level txt)
10841 (list txt))
10842 "/")))
10843 (push (list txt f re (org-refile-marker (point)))
10844 tgs)))
10845 (when (= (point) pos0)
10846 ;; verification function has not moved point
10847 (goto-char (point-at-eol))))))))
10848 (when org-refile-use-cache
10849 (org-refile-cache-put tgs (buffer-file-name) descre))
10850 (setq targets (append tgs targets))
10851 ))))
10852 (message "Getting targets...done")
10853 (nreverse targets)))
10855 (defun org-protect-slash (s)
10856 (while (string-match "/" s)
10857 (setq s (replace-match "\\" t t s)))
10860 (defvar org-olpa (make-vector 20 nil))
10862 (defun org-get-outline-path (&optional fastp level heading)
10863 "Return the outline path to the current entry, as a list.
10865 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10866 routine which makes outline path derivations for an entire file,
10867 avoiding backtracing. Refile target collection makes use of that."
10868 (if fastp
10869 (progn
10870 (if (> level 19)
10871 (error "Outline path failure, more than 19 levels"))
10872 (loop for i from level upto 19 do
10873 (aset org-olpa i nil))
10874 (prog1
10875 (delq nil (append org-olpa nil))
10876 (aset org-olpa level heading)))
10877 (let (rtn case-fold-search)
10878 (save-excursion
10879 (save-restriction
10880 (widen)
10881 (while (org-up-heading-safe)
10882 (when (looking-at org-complex-heading-regexp)
10883 (push (org-match-string-no-properties 4) rtn)))
10884 rtn)))))
10886 (defun org-format-outline-path (path &optional width prefix separator)
10887 "Format the outline path PATH for display.
10888 WIDTH is the maximum number of characters that is available.
10889 PREFIX is a prefix to be included in the returned string,
10890 such as the file name.
10891 SEPARATOR is inserted between the different parts of the path,
10892 the default is \"/\"."
10893 (setq width (or width 79))
10894 (if prefix (setq width (- width (length prefix))))
10895 (if (not path)
10896 (or prefix "")
10897 (let* ((nsteps (length path))
10898 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10899 (maxwidth (if (<= total-width width)
10900 10000 ;; everything fits
10901 ;; we need to shorten the level headings
10902 (/ (- width nsteps) nsteps)))
10903 (org-odd-levels-only nil)
10904 (n 0)
10905 (total (1+ (length prefix))))
10906 (setq maxwidth (max maxwidth 10))
10907 (concat prefix
10908 (if prefix (or separator "/"))
10909 (mapconcat
10910 (lambda (h)
10911 (setq n (1+ n))
10912 (if (and (= n nsteps) (< maxwidth 10000))
10913 (setq maxwidth (- total-width total)))
10914 (if (< (length h) maxwidth)
10915 (progn (setq total (+ total (length h) 1)) h)
10916 (setq h (substring h 0 (- maxwidth 2))
10917 total (+ total maxwidth 1))
10918 (if (string-match "[ \t]+\\'" h)
10919 (setq h (substring h 0 (match-beginning 0))))
10920 (setq h (concat h "..")))
10921 (org-add-props h nil 'face
10922 (nth (% (1- n) org-n-level-faces)
10923 org-level-faces))
10925 path (or separator "/"))))))
10927 (defun org-display-outline-path (&optional file current separator just-return-string)
10928 "Display the current outline path in the echo area.
10930 If FILE is non-nil, prepend the output with the file name.
10931 If CURRENT is non-nil, append the current heading to the output.
10932 SEPARATOR is passed through to `org-format-outline-path'. It separates
10933 the different parts of the path and defaults to \"/\".
10934 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10935 (interactive "P")
10936 (let* (case-fold-search
10937 message-log-max ; Don't populate the *Messages* buffer
10938 (bfn (buffer-file-name (buffer-base-buffer)))
10939 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10940 res)
10941 (if current (setq path (append path
10942 (save-excursion
10943 (org-back-to-heading t)
10944 (if (looking-at org-complex-heading-regexp)
10945 (list (match-string 4)))))))
10946 (setq res
10947 (org-format-outline-path
10948 path
10949 (1- (frame-width))
10950 (and file bfn (concat (file-name-nondirectory bfn) separator))
10951 separator))
10952 (if just-return-string
10953 (org-no-properties res)
10954 (message "%s" res))))
10956 (defvar org-refile-history nil
10957 "History for refiling operations.")
10959 (defvar org-after-refile-insert-hook nil
10960 "Hook run after `org-refile' has inserted its stuff at the new location.
10961 Note that this is still *before* the stuff will be removed from
10962 the *old* location.")
10964 (defvar org-capture-last-stored-marker)
10965 (defvar org-refile-keep nil
10966 "Non-nil means `org-refile' will copy instead of refile.")
10968 (defun org-copy ()
10969 "Like `org-refile', but copy."
10970 (interactive)
10971 (let ((org-refile-keep t))
10972 (funcall 'org-refile nil nil nil "Copy")))
10974 (defun org-refile (&optional goto default-buffer rfloc msg)
10975 "Move the entry or entries at point to another heading.
10976 The list of target headings is compiled using the information in
10977 `org-refile-targets', which see.
10979 At the target location, the entry is filed as a subitem of the target
10980 heading. Depending on `org-reverse-note-order', the new subitem will
10981 either be the first or the last subitem.
10983 If there is an active region, all entries in that region will be moved.
10984 However, the region must fulfill the requirement that the first heading
10985 is the first one sets the top-level of the moved text - at most siblings
10986 below it are allowed.
10988 With prefix arg GOTO, the command will only visit the target location
10989 and not actually move anything.
10991 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10992 go to the location where the last refiling operation has put the subtree.
10993 With a prefix argument of `2', refile to the running clock.
10995 RFLOC can be a refile location obtained in a different way.
10997 MSG is a string to replace \"Refile\" in the default prompt with
10998 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11000 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11002 If you are using target caching (see `org-refile-use-cache'),
11003 you have to clear the target cache in order to find new targets.
11004 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11005 prefix argument (`C-u C-u C-u C-c C-w')."
11007 (interactive "P")
11008 (if (member goto '(0 (64)))
11009 (org-refile-cache-clear)
11010 (let* ((actionmsg (or msg "Refile"))
11011 (cbuf (current-buffer))
11012 (regionp (org-region-active-p))
11013 (region-start (and regionp (region-beginning)))
11014 (region-end (and regionp (region-end)))
11015 (region-length (and regionp (- region-end region-start)))
11016 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11017 pos it nbuf file re level reversed)
11018 (setq last-command nil)
11019 (when regionp
11020 (goto-char region-start)
11021 (or (bolp) (goto-char (point-at-bol)))
11022 (setq region-start (point))
11023 (unless (or (org-kill-is-subtree-p
11024 (buffer-substring region-start region-end))
11025 (prog1 org-refile-active-region-within-subtree
11026 (org-toggle-heading)))
11027 (error "The region is not a (sequence of) subtree(s)")))
11028 (if (equal goto '(16))
11029 (org-refile-goto-last-stored)
11030 (when (or
11031 (and (equal goto 2)
11032 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11033 (prog1
11034 (setq it (list (or org-clock-heading "running clock")
11035 (buffer-file-name
11036 (marker-buffer org-clock-hd-marker))
11038 (marker-position org-clock-hd-marker)))
11039 (setq goto nil)))
11040 (setq it (or rfloc
11041 (let (heading-text)
11042 (save-excursion
11043 (unless goto
11044 (org-back-to-heading t)
11045 (setq heading-text
11046 (nth 4 (org-heading-components))))
11048 (org-refile-get-location
11049 (cond (goto "Goto")
11050 (regionp (concat actionmsg " region to"))
11051 (t (concat actionmsg " subtree \""
11052 heading-text "\" to")))
11053 default-buffer
11054 (and (not (equal '(4) goto))
11055 org-refile-allow-creating-parent-nodes)
11056 goto))))))
11057 (setq file (nth 1 it)
11058 re (nth 2 it)
11059 pos (nth 3 it))
11060 (if (and (not goto)
11062 (equal (buffer-file-name) file)
11063 (if regionp
11064 (and (>= pos region-start)
11065 (<= pos region-end))
11066 (and (>= pos (point))
11067 (< pos (save-excursion
11068 (org-end-of-subtree t t))))))
11069 (error "Cannot refile to position inside the tree or region"))
11071 (setq nbuf (or (find-buffer-visiting file)
11072 (find-file-noselect file)))
11073 (if goto
11074 (progn
11075 (org-pop-to-buffer-same-window nbuf)
11076 (goto-char pos)
11077 (org-show-context 'org-goto))
11078 (if regionp
11079 (progn
11080 (org-kill-new (buffer-substring region-start region-end))
11081 (org-save-markers-in-region region-start region-end))
11082 (org-copy-subtree 1 nil t))
11083 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11084 (find-file-noselect file)))
11085 (setq reversed (org-notes-order-reversed-p))
11086 (save-excursion
11087 (save-restriction
11088 (widen)
11089 (if pos
11090 (progn
11091 (goto-char pos)
11092 (looking-at org-outline-regexp)
11093 (setq level (org-get-valid-level (funcall outline-level) 1))
11094 (goto-char
11095 (if reversed
11096 (or (outline-next-heading) (point-max))
11097 (or (save-excursion (org-get-next-sibling))
11098 (org-end-of-subtree t t)
11099 (point-max)))))
11100 (setq level 1)
11101 (if (not reversed)
11102 (goto-char (point-max))
11103 (goto-char (point-min))
11104 (or (outline-next-heading) (goto-char (point-max)))))
11105 (if (not (bolp)) (newline))
11106 (org-paste-subtree level)
11107 (when org-log-refile
11108 (org-add-log-setup 'refile nil nil 'findpos
11109 org-log-refile)
11110 (unless (eq org-log-refile 'note)
11111 (save-excursion (org-add-log-note))))
11112 (and org-auto-align-tags
11113 (let ((org-loop-over-headlines-in-active-region nil))
11114 (org-set-tags nil t)))
11115 (with-demoted-errors
11116 (bookmark-set "org-refile-last-stored"))
11117 ;; If we are refiling for capture, make sure that the
11118 ;; last-capture pointers point here
11119 (when (org-bound-and-true-p org-refile-for-capture)
11120 (with-demoted-errors
11121 (bookmark-set "org-capture-last-stored-marker"))
11122 (move-marker org-capture-last-stored-marker (point)))
11123 (if (fboundp 'deactivate-mark) (deactivate-mark))
11124 (run-hooks 'org-after-refile-insert-hook))))
11125 (unless org-refile-keep
11126 (if regionp
11127 (delete-region (point) (+ (point) region-length))
11128 (org-cut-subtree)))
11129 (when (featurep 'org-inlinetask)
11130 (org-inlinetask-remove-END-maybe))
11131 (setq org-markers-to-move nil)
11132 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11134 (defun org-refile-goto-last-stored ()
11135 "Go to the location where the last refile was stored."
11136 (interactive)
11137 (bookmark-jump "org-refile-last-stored")
11138 (message "This is the location of the last refile"))
11140 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11141 no-exclude)
11142 "Prompt the user for a refile location, using PROMPT.
11143 PROMPT should not be suffixed with a colon and a space, because
11144 this function appends the default value from
11145 `org-refile-history' automatically, if that is not empty.
11146 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11147 this is used for the GOTO interface."
11148 (let ((org-refile-targets org-refile-targets)
11149 (org-refile-use-outline-path org-refile-use-outline-path)
11150 excluded-entries)
11151 (when (and (derived-mode-p 'org-mode)
11152 (not org-refile-use-cache)
11153 (not no-exclude))
11154 (org-map-tree
11155 (lambda()
11156 (setq excluded-entries
11157 (append excluded-entries (list (org-get-heading t t)))))))
11158 (setq org-refile-target-table
11159 (org-refile-get-targets default-buffer excluded-entries)))
11160 (unless org-refile-target-table
11161 (error "No refile targets"))
11162 (let* ((cbuf (current-buffer))
11163 (partial-completion-mode nil)
11164 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11165 (cfunc (if (and org-refile-use-outline-path
11166 org-outline-path-complete-in-steps)
11167 'org-olpath-completing-read
11168 'org-icompleting-read))
11169 (extra (if org-refile-use-outline-path "/" ""))
11170 (cbnex (concat (buffer-name) extra))
11171 (filename (and cfn (expand-file-name cfn)))
11172 (tbl (mapcar
11173 (lambda (x)
11174 (if (and (not (member org-refile-use-outline-path
11175 '(file full-file-path)))
11176 (not (equal filename (nth 1 x))))
11177 (cons (concat (car x) extra " ("
11178 (file-name-nondirectory (nth 1 x)) ")")
11179 (cdr x))
11180 (cons (concat (car x) extra) (cdr x))))
11181 org-refile-target-table))
11182 (completion-ignore-case t)
11183 cdef
11184 (prompt (concat prompt
11185 (or (and (car org-refile-history)
11186 (concat " (default " (car org-refile-history) ")"))
11187 (and (assoc cbnex tbl) (setq cdef cbnex)
11188 (concat " (default " cbnex ")"))) ": "))
11189 pa answ parent-target child parent old-hist)
11190 (setq old-hist org-refile-history)
11191 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11192 nil 'org-refile-history (or cdef (car org-refile-history))))
11193 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11194 (org-refile-check-position pa)
11195 (if pa
11196 (progn
11197 (when (or (not org-refile-history)
11198 (not (eq old-hist org-refile-history))
11199 (not (equal (car pa) (car org-refile-history))))
11200 (setq org-refile-history
11201 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11202 org-refile-history
11203 (cdr org-refile-history))))
11204 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11205 (pop org-refile-history)))
11207 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11208 (progn
11209 (setq parent (match-string 1 answ)
11210 child (match-string 2 answ))
11211 (setq parent-target (or (assoc parent tbl)
11212 (assoc (concat parent "/") tbl)))
11213 (when (and parent-target
11214 (or (eq new-nodes t)
11215 (and (eq new-nodes 'confirm)
11216 (y-or-n-p (format "Create new node \"%s\"? "
11217 child)))))
11218 (org-refile-new-child parent-target child)))
11219 (error "Invalid target location")))))
11221 (declare-function org-string-nw-p "org-macs" (s))
11222 (defun org-refile-check-position (refile-pointer)
11223 "Check if the refile pointer matches the headline to which it points."
11224 (let* ((file (nth 1 refile-pointer))
11225 (re (nth 2 refile-pointer))
11226 (pos (nth 3 refile-pointer))
11227 buffer)
11228 (if (and (not (markerp pos)) (not file))
11229 (error "Please save the buffer to a file before refiling")
11230 (when (org-string-nw-p re)
11231 (setq buffer (if (markerp pos)
11232 (marker-buffer pos)
11233 (or (find-buffer-visiting file)
11234 (find-file-noselect file))))
11235 (with-current-buffer buffer
11236 (save-excursion
11237 (save-restriction
11238 (widen)
11239 (goto-char pos)
11240 (beginning-of-line 1)
11241 (unless (org-looking-at-p re)
11242 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11244 (defun org-refile-new-child (parent-target child)
11245 "Use refile target PARENT-TARGET to add new CHILD below it."
11246 (unless parent-target
11247 (error "Cannot find parent for new node"))
11248 (let ((file (nth 1 parent-target))
11249 (pos (nth 3 parent-target))
11250 level)
11251 (with-current-buffer (or (find-buffer-visiting file)
11252 (find-file-noselect file))
11253 (save-excursion
11254 (save-restriction
11255 (widen)
11256 (if pos
11257 (goto-char pos)
11258 (goto-char (point-max))
11259 (if (not (bolp)) (newline)))
11260 (when (looking-at org-outline-regexp)
11261 (setq level (funcall outline-level))
11262 (org-end-of-subtree t t))
11263 (org-back-over-empty-lines)
11264 (insert "\n" (make-string
11265 (if pos (org-get-valid-level level 1) 1) ?*)
11266 " " child "\n")
11267 (beginning-of-line 0)
11268 (list (concat (car parent-target) "/" child) file "" (point)))))))
11270 (defun org-olpath-completing-read (prompt collection &rest args)
11271 "Read an outline path like a file name."
11272 (let ((thetable collection)
11273 (org-completion-use-ido nil) ; does not work with ido.
11274 (org-completion-use-iswitchb nil)) ; or iswitchb
11275 (apply
11276 'org-icompleting-read prompt
11277 (lambda (string predicate &optional flag)
11278 (let (rtn r f (l (length string)))
11279 (cond
11280 ((eq flag nil)
11281 ;; try completion
11282 (try-completion string thetable))
11283 ((eq flag t)
11284 ;; all-completions
11285 (setq rtn (all-completions string thetable predicate))
11286 (mapcar
11287 (lambda (x)
11288 (setq r (substring x l))
11289 (if (string-match " ([^)]*)$" x)
11290 (setq f (match-string 0 x))
11291 (setq f ""))
11292 (if (string-match "/" r)
11293 (concat string (substring r 0 (match-end 0)) f)
11295 rtn))
11296 ((eq flag 'lambda)
11297 ;; exact match?
11298 (assoc string thetable)))))
11299 args)))
11301 ;;;; Dynamic blocks
11303 (defun org-find-dblock (name)
11304 "Find the first dynamic block with name NAME in the buffer.
11305 If not found, stay at current position and return nil."
11306 (let ((case-fold-search t) pos)
11307 (save-excursion
11308 (goto-char (point-min))
11309 (setq pos (and (re-search-forward
11310 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11311 (match-beginning 0))))
11312 (if pos (goto-char pos))
11313 pos))
11315 (defconst org-dblock-start-re
11316 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11317 "Matches the start line of a dynamic block, with parameters.")
11319 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11320 "Matches the end of a dynamic block.")
11322 (defun org-create-dblock (plist)
11323 "Create a dynamic block section, with parameters taken from PLIST.
11324 PLIST must contain a :name entry which is used as name of the block."
11325 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11326 (end-of-line 1)
11327 (newline))
11328 (let ((col (current-column))
11329 (name (plist-get plist :name)))
11330 (insert "#+BEGIN: " name)
11331 (while plist
11332 (if (eq (car plist) :name)
11333 (setq plist (cddr plist))
11334 (insert " " (prin1-to-string (pop plist)))))
11335 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11336 (beginning-of-line -2)))
11338 (defun org-prepare-dblock ()
11339 "Prepare dynamic block for refresh.
11340 This empties the block, puts the cursor at the insert position and returns
11341 the property list including an extra property :name with the block name."
11342 (unless (looking-at org-dblock-start-re)
11343 (error "Not at a dynamic block"))
11344 (let* ((begdel (1+ (match-end 0)))
11345 (name (org-no-properties (match-string 1)))
11346 (params (append (list :name name)
11347 (read (concat "(" (match-string 3) ")")))))
11348 (save-excursion
11349 (beginning-of-line 1)
11350 (skip-chars-forward " \t")
11351 (setq params (plist-put params :indentation-column (current-column))))
11352 (unless (re-search-forward org-dblock-end-re nil t)
11353 (error "Dynamic block not terminated"))
11354 (setq params
11355 (append params
11356 (list :content (buffer-substring
11357 begdel (match-beginning 0)))))
11358 (delete-region begdel (match-beginning 0))
11359 (goto-char begdel)
11360 (open-line 1)
11361 params))
11363 (defun org-map-dblocks (&optional command)
11364 "Apply COMMAND to all dynamic blocks in the current buffer.
11365 If COMMAND is not given, use `org-update-dblock'."
11366 (let ((cmd (or command 'org-update-dblock)))
11367 (save-excursion
11368 (goto-char (point-min))
11369 (while (re-search-forward org-dblock-start-re nil t)
11370 (goto-char (match-beginning 0))
11371 (save-excursion
11372 (condition-case nil
11373 (funcall cmd)
11374 (error (message "Error during update of dynamic block"))))
11375 (unless (re-search-forward org-dblock-end-re nil t)
11376 (error "Dynamic block not terminated"))))))
11378 (defun org-dblock-update (&optional arg)
11379 "User command for updating dynamic blocks.
11380 Update the dynamic block at point. With prefix ARG, update all dynamic
11381 blocks in the buffer."
11382 (interactive "P")
11383 (if arg
11384 (org-update-all-dblocks)
11385 (or (looking-at org-dblock-start-re)
11386 (org-beginning-of-dblock))
11387 (org-update-dblock)))
11389 (defun org-update-dblock ()
11390 "Update the dynamic block at point.
11391 This means to empty the block, parse for parameters and then call
11392 the correct writing function."
11393 (interactive)
11394 (save-window-excursion
11395 (let* ((pos (point))
11396 (line (org-current-line))
11397 (params (org-prepare-dblock))
11398 (name (plist-get params :name))
11399 (indent (plist-get params :indentation-column))
11400 (cmd (intern (concat "org-dblock-write:" name))))
11401 (message "Updating dynamic block `%s' at line %d..." name line)
11402 (funcall cmd params)
11403 (message "Updating dynamic block `%s' at line %d...done" name line)
11404 (goto-char pos)
11405 (when (and indent (> indent 0))
11406 (setq indent (make-string indent ?\ ))
11407 (save-excursion
11408 (org-beginning-of-dblock)
11409 (forward-line 1)
11410 (while (not (looking-at org-dblock-end-re))
11411 (insert indent)
11412 (beginning-of-line 2))
11413 (when (looking-at org-dblock-end-re)
11414 (and (looking-at "[ \t]+")
11415 (replace-match ""))
11416 (insert indent)))))))
11418 (defun org-beginning-of-dblock ()
11419 "Find the beginning of the dynamic block at point.
11420 Error if there is no such block at point."
11421 (let ((pos (point))
11422 beg)
11423 (end-of-line 1)
11424 (if (and (re-search-backward org-dblock-start-re nil t)
11425 (setq beg (match-beginning 0))
11426 (re-search-forward org-dblock-end-re nil t)
11427 (> (match-end 0) pos))
11428 (goto-char beg)
11429 (goto-char pos)
11430 (error "Not in a dynamic block"))))
11432 (defun org-update-all-dblocks ()
11433 "Update all dynamic blocks in the buffer.
11434 This function can be used in a hook."
11435 (interactive)
11436 (when (derived-mode-p 'org-mode)
11437 (org-map-dblocks 'org-update-dblock)))
11440 ;;;; Completion
11442 (defconst org-additional-option-like-keywords
11443 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11444 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11445 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11446 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11447 "BEGIN:" "END:"
11448 "ORGTBL" "TBLFM:" "TBLNAME:"
11449 "BEGIN_EXAMPLE" "END_EXAMPLE"
11450 "BEGIN_VERBATIM" "END_VERBATIM"
11451 "BEGIN_QUOTE" "END_QUOTE"
11452 "BEGIN_VERSE" "END_VERSE"
11453 "BEGIN_CENTER" "END_CENTER"
11454 "BEGIN_SRC" "END_SRC"
11455 "BEGIN_RESULT" "END_RESULT"
11456 "BEGIN_lstlisting" "END_lstlisting"
11457 "NAME:" "RESULTS:"
11458 "HEADER:" "HEADERS:"
11459 "COLUMNS:" "PROPERTY:"
11460 "CAPTION:" "LABEL:"
11461 "SETUPFILE:"
11462 "INCLUDE:" "INDEX:"
11463 "BIND:"
11464 "MACRO:"))
11466 (defconst org-options-keywords
11467 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11468 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11469 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11470 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11471 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11472 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11473 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11475 (defconst org-additional-option-like-keywords-for-flyspell
11476 (delete-dups
11477 (split-string
11478 (mapconcat (lambda(k)
11479 (replace-regexp-in-string
11480 "_\\|:" " "
11481 (concat k " " (downcase k) " " (upcase k))))
11482 (append org-options-keywords org-additional-option-like-keywords)
11483 " ")
11484 " +" t)))
11486 (defcustom org-structure-template-alist
11487 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11488 "<src lang=\"?\">\n\n</src>")
11489 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11490 "<example>\n?\n</example>")
11491 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11492 "<quote>\n?\n</quote>")
11493 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11494 "<verse>\n?\n</verse>")
11495 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11496 "<verbatim>\n?\n</verbatim>")
11497 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11498 "<center>\n?\n</center>")
11499 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11500 "<literal style=\"latex\">\n?\n</literal>")
11501 ("L" "#+LaTeX: "
11502 "<literal style=\"latex\">?</literal>")
11503 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11504 "<literal style=\"html\">\n?\n</literal>")
11505 ("H" "#+HTML: "
11506 "<literal style=\"html\">?</literal>")
11507 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11508 ("A" "#+ASCII: ")
11509 ("i" "#+INDEX: ?"
11510 "#+INDEX: ?")
11511 ("I" "#+INCLUDE: %file ?"
11512 "<include file=%file markup=\"?\">"))
11513 "Structure completion elements.
11514 This is a list of abbreviation keys and values. The value gets inserted
11515 if you type `<' followed by the key and then press the completion key,
11516 usually `M-TAB'. %file will be replaced by a file name after prompting
11517 for the file using completion. The cursor will be placed at the position
11518 of the `?` in the template.
11519 There are two templates for each key, the first uses the original Org syntax,
11520 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11521 the default when the /org-mtags.el/ module has been loaded. See also the
11522 variable `org-mtags-prefer-muse-templates'."
11523 :group 'org-completion
11524 :type '(repeat
11525 (string :tag "Key")
11526 (string :tag "Template")
11527 (string :tag "Muse Template")))
11529 (defun org-try-structure-completion ()
11530 "Try to complete a structure template before point.
11531 This looks for strings like \"<e\" on an otherwise empty line and
11532 expands them."
11533 (let ((l (buffer-substring (point-at-bol) (point)))
11535 (when (and (looking-at "[ \t]*$")
11536 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11537 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11538 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11539 (match-beginning 1)) a)
11540 t)))
11542 (defun org-complete-expand-structure-template (start cell)
11543 "Expand a structure template."
11544 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11545 (rpl (nth (if musep 2 1) cell))
11546 (ind ""))
11547 (delete-region start (point))
11548 (when (string-match "\\`#\\+" rpl)
11549 (cond
11550 ((bolp))
11551 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11552 (setq ind (buffer-substring (point-at-bol) (point))))
11553 (t (newline))))
11554 (setq start (point))
11555 (if (string-match "%file" rpl)
11556 (setq rpl (replace-match
11557 (concat
11558 "\""
11559 (save-match-data
11560 (abbreviate-file-name (read-file-name "Include file: ")))
11561 "\"")
11562 t t rpl)))
11563 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11564 (concat "\n" ind)))
11565 (insert rpl)
11566 (if (re-search-backward "\\?" start t) (delete-char 1))))
11568 ;;;; TODO, DEADLINE, Comments
11570 (defun org-toggle-comment ()
11571 "Change the COMMENT state of an entry."
11572 (interactive)
11573 (save-excursion
11574 (org-back-to-heading)
11575 (let (case-fold-search)
11576 (cond
11577 ((looking-at (format org-heading-keyword-regexp-format
11578 org-comment-string))
11579 (goto-char (match-end 1))
11580 (looking-at (concat " +" org-comment-string))
11581 (replace-match "" t t)
11582 (when (eolp) (insert " ")))
11583 ((looking-at org-outline-regexp)
11584 (goto-char (match-end 0))
11585 (insert org-comment-string " "))))))
11587 (defvar org-last-todo-state-is-todo nil
11588 "This is non-nil when the last TODO state change led to a TODO state.
11589 If the last change removed the TODO tag or switched to DONE, then
11590 this is nil.")
11592 (defvar org-setting-tags nil) ; dynamically skipped
11594 (defvar org-todo-setup-filter-hook nil
11595 "Hook for functions that pre-filter todo specs.
11596 Each function takes a todo spec and returns either nil or the spec
11597 transformed into canonical form." )
11599 (defvar org-todo-get-default-hook nil
11600 "Hook for functions that get a default item for todo.
11601 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11602 nil or a string to be used for the todo mark." )
11604 (defvar org-agenda-headline-snapshot-before-repeat)
11606 (defun org-current-effective-time ()
11607 "Return current time adjusted for `org-extend-today-until' variable."
11608 (let* ((ct (org-current-time))
11609 (dct (decode-time ct))
11610 (ct1
11611 (cond
11612 (org-use-last-clock-out-time-as-effective-time
11613 (or (org-clock-get-last-clock-out-time) ct))
11614 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11615 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11616 (t ct))))
11617 ct1))
11619 (defun org-todo-yesterday (&optional arg)
11620 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11621 (interactive "P")
11622 (if (eq major-mode 'org-agenda-mode)
11623 (apply 'org-agenda-todo-yesterday arg)
11624 (let* ((hour (third (decode-time
11625 (org-current-time))))
11626 (org-extend-today-until (1+ hour)))
11627 (org-todo arg))))
11629 (defvar org-block-entry-blocking ""
11630 "First entry preventing the TODO state change.")
11632 (defun org-todo (&optional arg)
11633 "Change the TODO state of an item.
11634 The state of an item is given by a keyword at the start of the heading,
11635 like
11636 *** TODO Write paper
11637 *** DONE Call mom
11639 The different keywords are specified in the variable `org-todo-keywords'.
11640 By default the available states are \"TODO\" and \"DONE\".
11641 So for this example: when the item starts with TODO, it is changed to DONE.
11642 When it starts with DONE, the DONE is removed. And when neither TODO nor
11643 DONE are present, add TODO at the beginning of the heading.
11645 With \\[universal-argument] prefix arg, use completion to determine the new \
11646 state.
11647 With numeric prefix arg, switch to that state.
11648 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11649 keywords (nextset).
11650 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11651 With a numeric prefix arg of 0, inhibit note taking for the change.
11653 For calling through lisp, arg is also interpreted in the following way:
11654 'none -> empty state
11655 \"\"(empty string) -> switch to empty state
11656 'done -> switch to DONE
11657 'nextset -> switch to the next set of keywords
11658 'previousset -> switch to the previous set of keywords
11659 \"WAITING\" -> switch to the specified keyword, but only if it
11660 really is a member of `org-todo-keywords'."
11661 (interactive "P")
11662 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11663 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11664 'region-start-level 'region))
11665 org-loop-over-headlines-in-active-region)
11666 (org-map-entries
11667 `(org-todo ,arg)
11668 org-loop-over-headlines-in-active-region
11669 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11670 (if (equal arg '(16)) (setq arg 'nextset))
11671 (let ((org-blocker-hook org-blocker-hook)
11672 commentp
11673 case-fold-search)
11674 (when (equal arg '(64))
11675 (setq arg nil org-blocker-hook nil))
11676 (when (and org-blocker-hook
11677 (or org-inhibit-blocking
11678 (org-entry-get nil "NOBLOCKING")))
11679 (setq org-blocker-hook nil))
11680 (save-excursion
11681 (catch 'exit
11682 (org-back-to-heading t)
11683 (when (looking-at (concat "^\\*+ " org-comment-string))
11684 (org-toggle-comment)
11685 (setq commentp t))
11686 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11687 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11688 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11689 (let* ((match-data (match-data))
11690 (startpos (point-at-bol))
11691 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11692 (org-log-done org-log-done)
11693 (org-log-repeat org-log-repeat)
11694 (org-todo-log-states org-todo-log-states)
11695 (org-inhibit-logging
11696 (if (equal arg 0)
11697 (progn (setq arg nil) 'note) org-inhibit-logging))
11698 (this (match-string 1))
11699 (hl-pos (match-beginning 0))
11700 (head (org-get-todo-sequence-head this))
11701 (ass (assoc head org-todo-kwd-alist))
11702 (interpret (nth 1 ass))
11703 (done-word (nth 3 ass))
11704 (final-done-word (nth 4 ass))
11705 (org-last-state (or this ""))
11706 (completion-ignore-case t)
11707 (member (member this org-todo-keywords-1))
11708 (tail (cdr member))
11709 (org-state (cond
11710 ((and org-todo-key-trigger
11711 (or (and (equal arg '(4))
11712 (eq org-use-fast-todo-selection 'prefix))
11713 (and (not arg) org-use-fast-todo-selection
11714 (not (eq org-use-fast-todo-selection
11715 'prefix)))))
11716 ;; Use fast selection
11717 (org-fast-todo-selection))
11718 ((and (equal arg '(4))
11719 (or (not org-use-fast-todo-selection)
11720 (not org-todo-key-trigger)))
11721 ;; Read a state with completion
11722 (org-icompleting-read
11723 "State: " (mapcar (lambda(x) (list x))
11724 org-todo-keywords-1)
11725 nil t))
11726 ((eq arg 'right)
11727 (if this
11728 (if tail (car tail) nil)
11729 (car org-todo-keywords-1)))
11730 ((eq arg 'left)
11731 (if (equal member org-todo-keywords-1)
11733 (if this
11734 (nth (- (length org-todo-keywords-1)
11735 (length tail) 2)
11736 org-todo-keywords-1)
11737 (org-last org-todo-keywords-1))))
11738 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11739 (setq arg nil))) ; hack to fall back to cycling
11740 (arg
11741 ;; user or caller requests a specific state
11742 (cond
11743 ((equal arg "") nil)
11744 ((eq arg 'none) nil)
11745 ((eq arg 'done) (or done-word (car org-done-keywords)))
11746 ((eq arg 'nextset)
11747 (or (car (cdr (member head org-todo-heads)))
11748 (car org-todo-heads)))
11749 ((eq arg 'previousset)
11750 (let ((org-todo-heads (reverse org-todo-heads)))
11751 (or (car (cdr (member head org-todo-heads)))
11752 (car org-todo-heads))))
11753 ((car (member arg org-todo-keywords-1)))
11754 ((stringp arg)
11755 (error "State `%s' not valid in this file" arg))
11756 ((nth (1- (prefix-numeric-value arg))
11757 org-todo-keywords-1))))
11758 ((null member) (or head (car org-todo-keywords-1)))
11759 ((equal this final-done-word) nil) ;; -> make empty
11760 ((null tail) nil) ;; -> first entry
11761 ((memq interpret '(type priority))
11762 (if (eq this-command last-command)
11763 (car tail)
11764 (if (> (length tail) 0)
11765 (or done-word (car org-done-keywords))
11766 nil)))
11768 (car tail))))
11769 (org-state (or
11770 (run-hook-with-args-until-success
11771 'org-todo-get-default-hook org-state org-last-state)
11772 org-state))
11773 (next (if org-state (concat " " org-state " ") " "))
11774 (change-plist (list :type 'todo-state-change :from this :to org-state
11775 :position startpos))
11776 dolog now-done-p)
11777 (when org-blocker-hook
11778 (setq org-last-todo-state-is-todo
11779 (not (member this org-done-keywords)))
11780 (unless (save-excursion
11781 (save-match-data
11782 (org-with-wide-buffer
11783 (run-hook-with-args-until-failure
11784 'org-blocker-hook change-plist))))
11785 (if (org-called-interactively-p 'interactive)
11786 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11787 this org-state org-block-entry-blocking)
11788 ;; fail silently
11789 (message "TODO state change from %s to %s blocked (by \"%s\")"
11790 this org-state org-block-entry-blocking)
11791 (throw 'exit nil))))
11792 (store-match-data match-data)
11793 (replace-match next t t)
11794 (unless (pos-visible-in-window-p hl-pos)
11795 (message "TODO state changed to %s" (org-trim next)))
11796 (unless head
11797 (setq head (org-get-todo-sequence-head org-state)
11798 ass (assoc head org-todo-kwd-alist)
11799 interpret (nth 1 ass)
11800 done-word (nth 3 ass)
11801 final-done-word (nth 4 ass)))
11802 (when (memq arg '(nextset previousset))
11803 (message "Keyword-Set %d/%d: %s"
11804 (- (length org-todo-sets) -1
11805 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11806 (length org-todo-sets)
11807 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11808 (setq org-last-todo-state-is-todo
11809 (not (member org-state org-done-keywords)))
11810 (setq now-done-p (and (member org-state org-done-keywords)
11811 (not (member this org-done-keywords))))
11812 (and logging (org-local-logging logging))
11813 (when (and (or org-todo-log-states org-log-done)
11814 (not (eq org-inhibit-logging t))
11815 (not (memq arg '(nextset previousset))))
11816 ;; we need to look at recording a time and note
11817 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11818 (nth 2 (assoc this org-todo-log-states))))
11819 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11820 (setq dolog 'time))
11821 (when (and org-state
11822 (member org-state org-not-done-keywords)
11823 (not (member this org-not-done-keywords)))
11824 ;; This is now a todo state and was not one before
11825 ;; If there was a CLOSED time stamp, get rid of it.
11826 (org-add-planning-info nil nil 'closed))
11827 (when (and now-done-p org-log-done)
11828 ;; It is now done, and it was not done before
11829 (org-add-planning-info 'closed (org-current-effective-time))
11830 (if (and (not dolog) (eq 'note org-log-done))
11831 (org-add-log-setup 'done org-state this 'findpos 'note)))
11832 (when (and org-state dolog)
11833 ;; This is a non-nil state, and we need to log it
11834 (org-add-log-setup 'state org-state this 'findpos dolog)))
11835 ;; Fixup tag positioning
11836 (org-todo-trigger-tag-changes org-state)
11837 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11838 (when org-provide-todo-statistics
11839 (org-update-parent-todo-statistics))
11840 (run-hooks 'org-after-todo-state-change-hook)
11841 (if (and arg (not (member org-state org-done-keywords)))
11842 (setq head (org-get-todo-sequence-head org-state)))
11843 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11844 ;; Do we need to trigger a repeat?
11845 (when now-done-p
11846 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11847 ;; This is for the agenda, take a snapshot of the headline.
11848 (save-match-data
11849 (setq org-agenda-headline-snapshot-before-repeat
11850 (org-get-heading))))
11851 (org-auto-repeat-maybe org-state))
11852 ;; Fixup cursor location if close to the keyword
11853 (if (and (outline-on-heading-p)
11854 (not (bolp))
11855 (save-excursion (beginning-of-line 1)
11856 (looking-at org-todo-line-regexp))
11857 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11858 (progn
11859 (goto-char (or (match-end 2) (match-end 1)))
11860 (and (looking-at " ") (just-one-space))))
11861 (when org-trigger-hook
11862 (save-excursion
11863 (run-hook-with-args 'org-trigger-hook change-plist)))
11864 (when commentp (org-toggle-comment))))))))
11866 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11867 "Block turning an entry into a TODO, using the hierarchy.
11868 This checks whether the current task should be blocked from state
11869 changes. Such blocking occurs when:
11871 1. The task has children which are not all in a completed state.
11873 2. A task has a parent with the property :ORDERED:, and there
11874 are siblings prior to the current task with incomplete
11875 status.
11877 3. The parent of the task is blocked because it has siblings that should
11878 be done first, or is child of a block grandparent TODO entry."
11880 (if (not org-enforce-todo-dependencies)
11881 t ; if locally turned off don't block
11882 (catch 'dont-block
11883 ;; If this is not a todo state change, or if this entry is already DONE,
11884 ;; do not block
11885 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11886 (member (plist-get change-plist :from)
11887 (cons 'done org-done-keywords))
11888 (member (plist-get change-plist :to)
11889 (cons 'todo org-not-done-keywords))
11890 (not (plist-get change-plist :to)))
11891 (throw 'dont-block t))
11892 ;; If this task has children, and any are undone, it's blocked
11893 (save-excursion
11894 (org-back-to-heading t)
11895 (let ((this-level (funcall outline-level)))
11896 (outline-next-heading)
11897 (let ((child-level (funcall outline-level)))
11898 (while (and (not (eobp))
11899 (> child-level this-level))
11900 ;; this todo has children, check whether they are all
11901 ;; completed
11902 (if (and (not (org-entry-is-done-p))
11903 (org-entry-is-todo-p))
11904 (progn (setq org-block-entry-blocking (org-get-heading))
11905 (throw 'dont-block nil)))
11906 (outline-next-heading)
11907 (setq child-level (funcall outline-level))))))
11908 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11909 ;; any previous siblings are undone, it's blocked
11910 (save-excursion
11911 (org-back-to-heading t)
11912 (let* ((pos (point))
11913 (parent-pos (and (org-up-heading-safe) (point))))
11914 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11915 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11916 (forward-line 1)
11917 (re-search-forward org-not-done-heading-regexp pos t))
11918 (setq org-block-entry-blocking (match-string 0))
11919 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11920 ;; Search further up the hierarchy, to see if an ancestor is blocked
11921 (while t
11922 (goto-char parent-pos)
11923 (if (not (looking-at org-not-done-heading-regexp))
11924 (throw 'dont-block t)) ; do not block, parent is not a TODO
11925 (setq pos (point))
11926 (setq parent-pos (and (org-up-heading-safe) (point)))
11927 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11928 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11929 (forward-line 1)
11930 (re-search-forward org-not-done-heading-regexp pos t)
11931 (setq org-block-entry-blocking (org-get-heading)))
11932 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11934 (defcustom org-track-ordered-property-with-tag nil
11935 "Should the ORDERED property also be shown as a tag?
11936 The ORDERED property decides if an entry should require subtasks to be
11937 completed in sequence. Since a property is not very visible, setting
11938 this option means that toggling the ORDERED property with the command
11939 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11940 not relevant for the behavior, but it makes things more visible.
11942 Note that toggling the tag with tags commands will not change the property
11943 and therefore not influence behavior!
11945 This can be t, meaning the tag ORDERED should be used, It can also be a
11946 string to select a different tag for this task."
11947 :group 'org-todo
11948 :type '(choice
11949 (const :tag "No tracking" nil)
11950 (const :tag "Track with ORDERED tag" t)
11951 (string :tag "Use other tag")))
11953 (defun org-toggle-ordered-property ()
11954 "Toggle the ORDERED property of the current entry.
11955 For better visibility, you can track the value of this property with a tag.
11956 See variable `org-track-ordered-property-with-tag'."
11957 (interactive)
11958 (let* ((t1 org-track-ordered-property-with-tag)
11959 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11960 (save-excursion
11961 (org-back-to-heading)
11962 (if (org-entry-get nil "ORDERED")
11963 (progn
11964 (org-delete-property "ORDERED")
11965 (and tag (org-toggle-tag tag 'off))
11966 (message "Subtasks can be completed in arbitrary order"))
11967 (org-entry-put nil "ORDERED" "t")
11968 (and tag (org-toggle-tag tag 'on))
11969 (message "Subtasks must be completed in sequence")))))
11971 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11972 (defun org-block-todo-from-checkboxes (change-plist)
11973 "Block turning an entry into a TODO, using checkboxes.
11974 This checks whether the current task should be blocked from state
11975 changes because there are unchecked boxes in this entry."
11976 (if (not org-enforce-todo-checkbox-dependencies)
11977 t ; if locally turned off don't block
11978 (catch 'dont-block
11979 ;; If this is not a todo state change, or if this entry is already DONE,
11980 ;; do not block
11981 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11982 (member (plist-get change-plist :from)
11983 (cons 'done org-done-keywords))
11984 (member (plist-get change-plist :to)
11985 (cons 'todo org-not-done-keywords))
11986 (not (plist-get change-plist :to)))
11987 (throw 'dont-block t))
11988 ;; If this task has checkboxes that are not checked, it's blocked
11989 (save-excursion
11990 (org-back-to-heading t)
11991 (let ((beg (point)) end)
11992 (outline-next-heading)
11993 (setq end (point))
11994 (goto-char beg)
11995 (if (org-list-search-forward
11996 (concat (org-item-beginning-re)
11997 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11998 "\\[[- ]\\]")
11999 end t)
12000 (progn
12001 (if (boundp 'org-blocked-by-checkboxes)
12002 (setq org-blocked-by-checkboxes t))
12003 (throw 'dont-block nil)))))
12004 t))) ; do not block
12006 (defun org-entry-blocked-p ()
12007 "Is the current entry blocked?"
12008 (with-buffer-modified-unmodified
12009 (if (org-entry-get nil "NOBLOCKING")
12010 nil ;; Never block this entry
12011 (not
12012 (run-hook-with-args-until-failure
12013 'org-blocker-hook
12014 (list :type 'todo-state-change
12015 :position (point)
12016 :from 'todo
12017 :to 'done))))))
12019 (defun org-update-statistics-cookies (all)
12020 "Update the statistics cookie, either from TODO or from checkboxes.
12021 This should be called with the cursor in a line with a statistics cookie."
12022 (interactive "P")
12023 (if all
12024 (progn
12025 (org-update-checkbox-count 'all)
12026 (org-map-entries 'org-update-parent-todo-statistics))
12027 (if (not (org-at-heading-p))
12028 (org-update-checkbox-count)
12029 (let ((pos (point-marker))
12030 end l1 l2)
12031 (ignore-errors (org-back-to-heading t))
12032 (if (not (org-at-heading-p))
12033 (org-update-checkbox-count)
12034 (setq l1 (org-outline-level))
12035 (setq end (save-excursion
12036 (outline-next-heading)
12037 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12038 (point)))
12039 (if (and (save-excursion
12040 (re-search-forward
12041 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12042 (not (save-excursion (re-search-forward
12043 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12044 (org-update-checkbox-count)
12045 (if (and l2 (> l2 l1))
12046 (progn
12047 (goto-char end)
12048 (org-update-parent-todo-statistics))
12049 (goto-char pos)
12050 (beginning-of-line 1)
12051 (while (re-search-forward
12052 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12053 (point-at-eol) t)
12054 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12055 (goto-char pos)
12056 (move-marker pos nil)))))
12058 (defvar org-entry-property-inherited-from) ;; defined below
12059 (defun org-update-parent-todo-statistics ()
12060 "Update any statistics cookie in the parent of the current headline.
12061 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12062 the entire subtree and this will travel up the hierarchy and update
12063 statistics everywhere."
12064 (let* ((prop (save-excursion (org-up-heading-safe)
12065 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12066 (recursive (or (not org-hierarchical-todo-statistics)
12067 (and prop (string-match "\\<recursive\\>" prop))))
12068 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12070 (first t)
12071 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12072 level ltoggle l1 new ndel
12073 (cnt-all 0) (cnt-done 0) is-percent kwd
12074 checkbox-beg ov ovs ove cookie-present)
12075 (catch 'exit
12076 (save-excursion
12077 (beginning-of-line 1)
12078 (setq ltoggle (funcall outline-level))
12079 ;; Three situations are to consider:
12081 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12082 ;; to the top-level ancestor on the headline;
12084 ;; 2. If parent has "recursive" property, repeat up to the
12085 ;; headline setting that property, taking inheritance into
12086 ;; account;
12088 ;; 3. Else, move up to direct parent and proceed only once.
12089 (while (and (setq level (org-up-heading-safe))
12090 (or recursive first)
12091 (>= (point) lim))
12092 (setq first nil cookie-present nil)
12093 (unless (and level
12094 (not (string-match
12095 "\\<checkbox\\>"
12096 (downcase (or (org-entry-get nil "COOKIE_DATA")
12097 "")))))
12098 (throw 'exit nil))
12099 (while (re-search-forward box-re (point-at-eol) t)
12100 (setq cnt-all 0 cnt-done 0 cookie-present t)
12101 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12102 (save-match-data
12103 (unless (outline-next-heading) (throw 'exit nil))
12104 (while (and (looking-at org-complex-heading-regexp)
12105 (> (setq l1 (length (match-string 1))) level))
12106 (setq kwd (and (or recursive (= l1 ltoggle))
12107 (match-string 2)))
12108 (if (or (eq org-provide-todo-statistics 'all-headlines)
12109 (and (listp org-provide-todo-statistics)
12110 (or (member kwd org-provide-todo-statistics)
12111 (member kwd org-done-keywords))))
12112 (setq cnt-all (1+ cnt-all))
12113 (if (eq org-provide-todo-statistics t)
12114 (and kwd (setq cnt-all (1+ cnt-all)))))
12115 (and (member kwd org-done-keywords)
12116 (setq cnt-done (1+ cnt-done)))
12117 (outline-next-heading)))
12118 (setq new
12119 (if is-percent
12120 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12121 (format "[%d/%d]" cnt-done cnt-all))
12122 ndel (- (match-end 0) checkbox-beg))
12123 ;; handle overlays when updating cookie from column view
12124 (when (setq ov (car (overlays-at checkbox-beg)))
12125 (setq ovs (overlay-start ov) ove (overlay-end ov))
12126 (delete-overlay ov))
12127 (goto-char checkbox-beg)
12128 (insert new)
12129 (delete-region (point) (+ (point) ndel))
12130 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12131 (when ov (move-overlay ov ovs ove)))
12132 (when cookie-present
12133 (run-hook-with-args 'org-after-todo-statistics-hook
12134 cnt-done (- cnt-all cnt-done))))))
12135 (run-hooks 'org-todo-statistics-hook)))
12137 (defvar org-after-todo-statistics-hook nil
12138 "Hook that is called after a TODO statistics cookie has been updated.
12139 Each function is called with two arguments: the number of not-done entries
12140 and the number of done entries.
12142 For example, the following function, when added to this hook, will switch
12143 an entry to DONE when all children are done, and back to TODO when new
12144 entries are set to a TODO status. Note that this hook is only called
12145 when there is a statistics cookie in the headline!
12147 (defun org-summary-todo (n-done n-not-done)
12148 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12149 (let (org-log-done org-log-states) ; turn off logging
12150 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12153 (defvar org-todo-statistics-hook nil
12154 "Hook that is run whenever Org thinks TODO statistics should be updated.
12155 This hook runs even if there is no statistics cookie present, in which case
12156 `org-after-todo-statistics-hook' would not run.")
12158 (defun org-todo-trigger-tag-changes (state)
12159 "Apply the changes defined in `org-todo-state-tags-triggers'."
12160 (let ((l org-todo-state-tags-triggers)
12161 changes)
12162 (when (or (not state) (equal state ""))
12163 (setq changes (append changes (cdr (assoc "" l)))))
12164 (when (and (stringp state) (> (length state) 0))
12165 (setq changes (append changes (cdr (assoc state l)))))
12166 (when (member state org-not-done-keywords)
12167 (setq changes (append changes (cdr (assoc 'todo l)))))
12168 (when (member state org-done-keywords)
12169 (setq changes (append changes (cdr (assoc 'done l)))))
12170 (dolist (c changes)
12171 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12173 (defun org-local-logging (value)
12174 "Get logging settings from a property VALUE."
12175 (let* (words w a)
12176 ;; directly set the variables, they are already local.
12177 (setq org-log-done nil
12178 org-log-repeat nil
12179 org-todo-log-states nil)
12180 (setq words (org-split-string value))
12181 (while (setq w (pop words))
12182 (cond
12183 ((setq a (assoc w org-startup-options))
12184 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12185 (set (nth 1 a) (nth 2 a))))
12186 ((setq a (org-extract-log-state-settings w))
12187 (and (member (car a) org-todo-keywords-1)
12188 (push a org-todo-log-states)))))))
12190 (defun org-get-todo-sequence-head (kwd)
12191 "Return the head of the TODO sequence to which KWD belongs.
12192 If KWD is not set, check if there is a text property remembering the
12193 right sequence."
12194 (let (p)
12195 (cond
12196 ((not kwd)
12197 (or (get-text-property (point-at-bol) 'org-todo-head)
12198 (progn
12199 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12200 nil (point-at-eol)))
12201 (get-text-property p 'org-todo-head))))
12202 ((not (member kwd org-todo-keywords-1))
12203 (car org-todo-keywords-1))
12204 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12206 (defun org-fast-todo-selection ()
12207 "Fast TODO keyword selection with single keys.
12208 Returns the new TODO keyword, or nil if no state change should occur."
12209 (let* ((fulltable org-todo-key-alist)
12210 (done-keywords org-done-keywords) ;; needed for the faces.
12211 (maxlen (apply 'max (mapcar
12212 (lambda (x)
12213 (if (stringp (car x)) (string-width (car x)) 0))
12214 fulltable)))
12215 (expert nil)
12216 (fwidth (+ maxlen 3 1 3))
12217 (ncol (/ (- (window-width) 4) fwidth))
12218 tg cnt e c tbl
12219 groups ingroup)
12220 (save-excursion
12221 (save-window-excursion
12222 (if expert
12223 (set-buffer (get-buffer-create " *Org todo*"))
12224 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12225 (erase-buffer)
12226 (org-set-local 'org-done-keywords done-keywords)
12227 (setq tbl fulltable cnt 0)
12228 (while (setq e (pop tbl))
12229 (cond
12230 ((equal e '(:startgroup))
12231 (push '() groups) (setq ingroup t)
12232 (when (not (= cnt 0))
12233 (setq cnt 0)
12234 (insert "\n"))
12235 (insert "{ "))
12236 ((equal e '(:endgroup))
12237 (setq ingroup nil cnt 0)
12238 (insert "}\n"))
12239 ((equal e '(:newline))
12240 (when (not (= cnt 0))
12241 (setq cnt 0)
12242 (insert "\n")
12243 (setq e (car tbl))
12244 (while (equal (car tbl) '(:newline))
12245 (insert "\n")
12246 (setq tbl (cdr tbl)))))
12248 (setq tg (car e) c (cdr e))
12249 (if ingroup (push tg (car groups)))
12250 (setq tg (org-add-props tg nil 'face
12251 (org-get-todo-face tg)))
12252 (if (and (= cnt 0) (not ingroup)) (insert " "))
12253 (insert "[" c "] " tg (make-string
12254 (- fwidth 4 (length tg)) ?\ ))
12255 (when (= (setq cnt (1+ cnt)) ncol)
12256 (insert "\n")
12257 (if ingroup (insert " "))
12258 (setq cnt 0)))))
12259 (insert "\n")
12260 (goto-char (point-min))
12261 (if (not expert) (org-fit-window-to-buffer))
12262 (message "[a-z..]:Set [SPC]:clear")
12263 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12264 (cond
12265 ((or (= c ?\C-g)
12266 (and (= c ?q) (not (rassoc c fulltable))))
12267 (setq quit-flag t))
12268 ((= c ?\ ) nil)
12269 ((setq e (rassoc c fulltable) tg (car e))
12271 (t (setq quit-flag t)))))))
12273 (defun org-entry-is-todo-p ()
12274 (member (org-get-todo-state) org-not-done-keywords))
12276 (defun org-entry-is-done-p ()
12277 (member (org-get-todo-state) org-done-keywords))
12279 (defun org-get-todo-state ()
12280 (save-excursion
12281 (org-back-to-heading t)
12282 (and (looking-at org-todo-line-regexp)
12283 (match-end 2)
12284 (match-string 2))))
12286 (defun org-at-date-range-p (&optional inactive-ok)
12287 "Is the cursor inside a date range?"
12288 (interactive)
12289 (save-excursion
12290 (catch 'exit
12291 (let ((pos (point)))
12292 (skip-chars-backward "^[<\r\n")
12293 (skip-chars-backward "<[")
12294 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12295 (>= (match-end 0) pos)
12296 (throw 'exit t))
12297 (skip-chars-backward "^<[\r\n")
12298 (skip-chars-backward "<[")
12299 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12300 (>= (match-end 0) pos)
12301 (throw 'exit t)))
12302 nil)))
12304 (defun org-get-repeat (&optional tagline)
12305 "Check if there is a deadline/schedule with repeater in this entry."
12306 (save-match-data
12307 (save-excursion
12308 (org-back-to-heading t)
12309 (and (re-search-forward (if tagline
12310 (concat tagline "\\s-*" org-repeat-re)
12311 org-repeat-re)
12312 (org-entry-end-position) t)
12313 (match-string-no-properties 1)))))
12315 (defvar org-last-changed-timestamp)
12316 (defvar org-last-inserted-timestamp)
12317 (defvar org-log-post-message)
12318 (defvar org-log-note-purpose)
12319 (defvar org-log-note-how)
12320 (defvar org-log-note-extra)
12321 (defun org-auto-repeat-maybe (done-word)
12322 "Check if the current headline contains a repeated deadline/schedule.
12323 If yes, set TODO state back to what it was and change the base date
12324 of repeating deadline/scheduled time stamps to new date.
12325 This function is run automatically after each state change to a DONE state."
12326 ;; last-state is dynamically scoped into this function
12327 (let* ((repeat (org-get-repeat))
12328 (aa (assoc org-last-state org-todo-kwd-alist))
12329 (interpret (nth 1 aa))
12330 (head (nth 2 aa))
12331 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12332 (msg "Entry repeats: ")
12333 (org-log-done nil)
12334 (org-todo-log-states nil)
12335 re type n what ts time to-state)
12336 (when repeat
12337 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12338 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12339 org-todo-repeat-to-state))
12340 (unless (and to-state (member to-state org-todo-keywords-1))
12341 (setq to-state (if (eq interpret 'type) org-last-state head)))
12342 (org-todo to-state)
12343 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12344 (org-entry-put nil "LAST_REPEAT" (format-time-string
12345 (org-time-stamp-format t t))))
12346 (when org-log-repeat
12347 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12348 (memq 'org-add-log-note post-command-hook))
12349 ;; OK, we are already setup for some record
12350 (if (eq org-log-repeat 'note)
12351 ;; make sure we take a note, not only a time stamp
12352 (setq org-log-note-how 'note))
12353 ;; Set up for taking a record
12354 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12355 org-last-state
12356 'findpos org-log-repeat)))
12357 (org-back-to-heading t)
12358 (org-add-planning-info nil nil 'closed)
12359 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12360 org-deadline-time-regexp "\\)\\|\\("
12361 org-ts-regexp "\\)"))
12362 (while (re-search-forward
12363 re (save-excursion (outline-next-heading) (point)) t)
12364 (setq type (if (match-end 1) org-scheduled-string
12365 (if (match-end 3) org-deadline-string "Plain:"))
12366 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12367 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12368 (setq n (string-to-number (match-string 2 ts))
12369 what (match-string 3 ts))
12370 (if (equal what "w") (setq n (* n 7) what "d"))
12371 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12372 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12373 ;; Preparation, see if we need to modify the start date for the change
12374 (when (match-end 1)
12375 (setq time (save-match-data (org-time-string-to-time ts)))
12376 (cond
12377 ((equal (match-string 1 ts) ".")
12378 ;; Shift starting date to today
12379 (org-timestamp-change
12380 (- (org-today) (time-to-days time))
12381 'day))
12382 ((equal (match-string 1 ts) "+")
12383 (let ((nshiftmax 10) (nshift 0))
12384 (while (or (= nshift 0)
12385 (<= (time-to-days time)
12386 (time-to-days (current-time))))
12387 (when (= (incf nshift) nshiftmax)
12388 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12389 (error "Abort")))
12390 (org-timestamp-change n (cdr (assoc what whata)))
12391 (org-at-timestamp-p t)
12392 (setq ts (match-string 1))
12393 (setq time (save-match-data (org-time-string-to-time ts)))))
12394 (org-timestamp-change (- n) (cdr (assoc what whata)))
12395 ;; rematch, so that we have everything in place for the real shift
12396 (org-at-timestamp-p t)
12397 (setq ts (match-string 1))
12398 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12399 (org-timestamp-change n (cdr (assoc what whata)))
12400 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12401 (setq org-log-post-message msg)
12402 (message "%s" msg))))
12404 (defun org-show-todo-tree (arg)
12405 "Make a compact tree which shows all headlines marked with TODO.
12406 The tree will show the lines where the regexp matches, and all higher
12407 headlines above the match.
12408 With a \\[universal-argument] prefix, prompt for a regexp to match.
12409 With a numeric prefix N, construct a sparse tree for the Nth element
12410 of `org-todo-keywords-1'."
12411 (interactive "P")
12412 (let ((case-fold-search nil)
12413 (kwd-re
12414 (cond ((null arg) org-not-done-regexp)
12415 ((equal arg '(4))
12416 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12417 (mapcar 'list org-todo-keywords-1))))
12418 (concat "\\("
12419 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12420 "\\)\\>")))
12421 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12422 (regexp-quote (nth (1- (prefix-numeric-value arg))
12423 org-todo-keywords-1)))
12424 (t (error "Invalid prefix argument: %s" arg)))))
12425 (message "%d TODO entries found"
12426 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12428 (defun org-deadline (&optional remove time)
12429 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12430 With argument REMOVE, remove any deadline from the item.
12431 With argument TIME, set the deadline at the corresponding date. TIME
12432 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12433 (interactive "P")
12434 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12435 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12436 'region-start-level 'region))
12437 org-loop-over-headlines-in-active-region)
12438 (org-map-entries
12439 `(org-deadline ',remove ,time)
12440 org-loop-over-headlines-in-active-region
12441 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12442 (let* ((old-date (org-entry-get nil "DEADLINE"))
12443 (repeater (and old-date
12444 (string-match
12445 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12446 old-date)
12447 (match-string 1 old-date))))
12448 (if remove
12449 (progn
12450 (when (and old-date org-log-redeadline)
12451 (org-add-log-setup 'deldeadline nil old-date 'findpos
12452 org-log-redeadline))
12453 (org-remove-timestamp-with-keyword org-deadline-string)
12454 (message "Item no longer has a deadline."))
12455 (org-add-planning-info 'deadline time 'closed)
12456 (when (and old-date org-log-redeadline
12457 (not (equal old-date
12458 (substring org-last-inserted-timestamp 1 -1))))
12459 (org-add-log-setup 'redeadline nil old-date 'findpos
12460 org-log-redeadline))
12461 (when repeater
12462 (save-excursion
12463 (org-back-to-heading t)
12464 (when (re-search-forward (concat org-deadline-string " "
12465 org-last-inserted-timestamp)
12466 (save-excursion
12467 (outline-next-heading) (point)) t)
12468 (goto-char (1- (match-end 0)))
12469 (insert " " repeater)
12470 (setq org-last-inserted-timestamp
12471 (concat (substring org-last-inserted-timestamp 0 -1)
12472 " " repeater
12473 (substring org-last-inserted-timestamp -1))))))
12474 (message "Deadline on %s" org-last-inserted-timestamp)))))
12476 (defun org-schedule (&optional remove time)
12477 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12478 With argument REMOVE, remove any scheduling date from the item.
12479 With argument TIME, scheduled at the corresponding date. TIME can
12480 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12481 (interactive "P")
12482 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12483 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12484 'region-start-level 'region))
12485 org-loop-over-headlines-in-active-region)
12486 (org-map-entries
12487 `(org-schedule ',remove ,time)
12488 org-loop-over-headlines-in-active-region
12489 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12490 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12491 (repeater (and old-date
12492 (string-match
12493 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12494 old-date)
12495 (match-string 1 old-date))))
12496 (if remove
12497 (progn
12498 (when (and old-date org-log-reschedule)
12499 (org-add-log-setup 'delschedule nil old-date 'findpos
12500 org-log-reschedule))
12501 (org-remove-timestamp-with-keyword org-scheduled-string)
12502 (message "Item is no longer scheduled."))
12503 (org-add-planning-info 'scheduled time 'closed)
12504 (when (and old-date org-log-reschedule
12505 (not (equal old-date
12506 (substring org-last-inserted-timestamp 1 -1))))
12507 (org-add-log-setup 'reschedule nil old-date 'findpos
12508 org-log-reschedule))
12509 (when repeater
12510 (save-excursion
12511 (org-back-to-heading t)
12512 (when (re-search-forward (concat org-scheduled-string " "
12513 org-last-inserted-timestamp)
12514 (save-excursion
12515 (outline-next-heading) (point)) t)
12516 (goto-char (1- (match-end 0)))
12517 (insert " " repeater)
12518 (setq org-last-inserted-timestamp
12519 (concat (substring org-last-inserted-timestamp 0 -1)
12520 " " repeater
12521 (substring org-last-inserted-timestamp -1))))))
12522 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12524 (defun org-get-scheduled-time (pom &optional inherit)
12525 "Get the scheduled time as a time tuple, of a format suitable
12526 for calling org-schedule with, or if there is no scheduling,
12527 returns nil."
12528 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12529 (when time
12530 (apply 'encode-time (org-parse-time-string time)))))
12532 (defun org-get-deadline-time (pom &optional inherit)
12533 "Get the deadline as a time tuple, of a format suitable for
12534 calling org-deadline with, or if there is no scheduling, returns
12535 nil."
12536 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12537 (when time
12538 (apply 'encode-time (org-parse-time-string time)))))
12540 (defun org-remove-timestamp-with-keyword (keyword)
12541 "Remove all time stamps with KEYWORD in the current entry."
12542 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12543 beg)
12544 (save-excursion
12545 (org-back-to-heading t)
12546 (setq beg (point))
12547 (outline-next-heading)
12548 (while (re-search-backward re beg t)
12549 (replace-match "")
12550 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12551 (equal (char-before) ?\ ))
12552 (backward-delete-char 1)
12553 (if (string-match "^[ \t]*$" (buffer-substring
12554 (point-at-bol) (point-at-eol)))
12555 (delete-region (point-at-bol)
12556 (min (point-max) (1+ (point-at-eol))))))))))
12558 (defun org-add-planning-info (what &optional time &rest remove)
12559 "Insert new timestamp with keyword in the line directly after the headline.
12560 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12561 If non is given, the user is prompted for a date.
12562 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12563 be removed."
12564 (interactive)
12565 (let (org-time-was-given org-end-time-was-given ts
12566 end default-time default-input)
12568 (catch 'exit
12569 (when (and (memq what '(scheduled deadline))
12570 (or (not time)
12571 (and (stringp time)
12572 (string-match "^[-+]+[0-9]" time))))
12573 ;; Try to get a default date/time from existing timestamp
12574 (save-excursion
12575 (org-back-to-heading t)
12576 (setq end (save-excursion (outline-next-heading) (point)))
12577 (when (re-search-forward (if (eq what 'scheduled)
12578 org-scheduled-time-regexp
12579 org-deadline-time-regexp)
12580 end t)
12581 (setq ts (match-string 1)
12582 default-time
12583 (apply 'encode-time (org-parse-time-string ts))
12584 default-input (and ts (org-get-compact-tod ts))))))
12585 (when what
12586 (setq time
12587 (if (stringp time)
12588 ;; This is a string (relative or absolute), set proper date
12589 (apply 'encode-time
12590 (org-read-date-analyze
12591 time default-time (decode-time default-time)))
12592 ;; If necessary, get the time from the user
12593 (or time (org-read-date nil 'to-time nil nil
12594 default-time default-input)))))
12596 (when (and org-insert-labeled-timestamps-at-point
12597 (member what '(scheduled deadline)))
12598 (insert
12599 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12600 (org-insert-time-stamp time org-time-was-given
12601 nil nil nil (list org-end-time-was-given))
12602 (setq what nil))
12603 (save-excursion
12604 (save-restriction
12605 (let (col list elt ts buffer-invisibility-spec)
12606 (org-back-to-heading t)
12607 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12608 (goto-char (match-end 1))
12609 (setq col (current-column))
12610 (goto-char (match-end 0))
12611 (if (eobp) (insert "\n") (forward-char 1))
12612 (when (and (not what)
12613 (not (looking-at
12614 (concat "[ \t]*"
12615 org-keyword-time-not-clock-regexp))))
12616 ;; Nothing to add, nothing to remove...... :-)
12617 (throw 'exit nil))
12618 (if (and (not (looking-at org-outline-regexp))
12619 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12620 "[^\r\n]*"))
12621 (not (equal (match-string 1) org-clock-string)))
12622 (narrow-to-region (match-beginning 0) (match-end 0))
12623 (insert-before-markers "\n")
12624 (backward-char 1)
12625 (narrow-to-region (point) (point))
12626 (and org-adapt-indentation (org-indent-to-column col)))
12627 ;; Check if we have to remove something.
12628 (setq list (cons what remove))
12629 (while list
12630 (setq elt (pop list))
12631 (when (or (and (eq elt 'scheduled)
12632 (re-search-forward org-scheduled-time-regexp nil t))
12633 (and (eq elt 'deadline)
12634 (re-search-forward org-deadline-time-regexp nil t))
12635 (and (eq elt 'closed)
12636 (re-search-forward org-closed-time-regexp nil t)))
12637 (replace-match "")
12638 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12639 (and (looking-at "[ \t]+") (replace-match ""))
12640 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12641 (when what
12642 (insert
12643 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12644 (cond ((eq what 'scheduled) org-scheduled-string)
12645 ((eq what 'deadline) org-deadline-string)
12646 ((eq what 'closed) org-closed-string))
12647 " ")
12648 (setq ts (org-insert-time-stamp
12649 time
12650 (or org-time-was-given
12651 (and (eq what 'closed) org-log-done-with-time))
12652 (eq what 'closed)
12653 nil nil (list org-end-time-was-given)))
12654 (insert
12655 (if (not (or (bolp) (eq (char-before) ?\ )
12656 (memq (char-after) '(32 10))
12657 (eobp))) " " ""))
12658 (end-of-line 1))
12659 (goto-char (point-min))
12660 (widen)
12661 (if (and (looking-at "[ \t]*\n")
12662 (equal (char-before) ?\n))
12663 (delete-region (1- (point)) (point-at-eol)))
12664 ts))))))
12666 (defvar org-log-note-marker (make-marker))
12667 (defvar org-log-note-purpose nil)
12668 (defvar org-log-note-state nil)
12669 (defvar org-log-note-previous-state nil)
12670 (defvar org-log-note-how nil)
12671 (defvar org-log-note-extra nil)
12672 (defvar org-log-note-window-configuration nil)
12673 (defvar org-log-note-return-to (make-marker))
12674 (defvar org-log-note-effective-time nil
12675 "Remembered current time so that dynamically scoped
12676 `org-extend-today-until' affects tha timestamps in state change
12677 log")
12679 (defvar org-log-post-message nil
12680 "Message to be displayed after a log note has been stored.
12681 The auto-repeater uses this.")
12683 (defun org-add-note ()
12684 "Add a note to the current entry.
12685 This is done in the same way as adding a state change note."
12686 (interactive)
12687 (org-add-log-setup 'note nil nil 'findpos nil))
12689 (defvar org-property-end-re)
12690 (defun org-add-log-setup (&optional purpose state prev-state
12691 findpos how extra)
12692 "Set up the post command hook to take a note.
12693 If this is about to TODO state change, the new state is expected in STATE.
12694 When FINDPOS is non-nil, find the correct position for the note in
12695 the current entry. If not, assume that it can be inserted at point.
12696 HOW is an indicator what kind of note should be created.
12697 EXTRA is additional text that will be inserted into the notes buffer."
12698 (let* ((org-log-into-drawer (org-log-into-drawer))
12699 (drawer (cond ((stringp org-log-into-drawer)
12700 org-log-into-drawer)
12701 (org-log-into-drawer "LOGBOOK"))))
12702 (save-restriction
12703 (save-excursion
12704 (when findpos
12705 (org-back-to-heading t)
12706 (narrow-to-region (point) (save-excursion
12707 (outline-next-heading) (point)))
12708 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12709 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12710 "[^\r\n]*\\)?"))
12711 (goto-char (match-end 0))
12712 (cond
12713 (drawer
12714 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12715 nil t)
12716 (progn
12717 (goto-char (match-end 0))
12718 (or org-log-states-order-reversed
12719 (and (re-search-forward org-property-end-re nil t)
12720 (goto-char (1- (match-beginning 0))))))
12721 (insert "\n:" drawer ":\n:END:")
12722 (beginning-of-line 0)
12723 (org-indent-line)
12724 (beginning-of-line 2)
12725 (org-indent-line)
12726 (end-of-line 0)))
12727 ((and org-log-state-notes-insert-after-drawers
12728 (save-excursion
12729 (forward-line) (looking-at org-drawer-regexp)))
12730 (forward-line)
12731 (while (looking-at org-drawer-regexp)
12732 (goto-char (match-end 0))
12733 (re-search-forward org-property-end-re (point-max) t)
12734 (forward-line))
12735 (forward-line -1)))
12736 (unless org-log-states-order-reversed
12737 (and (= (char-after) ?\n) (forward-char 1))
12738 (org-skip-over-state-notes)
12739 (skip-chars-backward " \t\n\r")))
12740 (move-marker org-log-note-marker (point))
12741 (setq org-log-note-purpose purpose
12742 org-log-note-state state
12743 org-log-note-previous-state prev-state
12744 org-log-note-how how
12745 org-log-note-extra extra
12746 org-log-note-effective-time (org-current-effective-time))
12747 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12749 (defun org-skip-over-state-notes ()
12750 "Skip past the list of State notes in an entry."
12751 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12752 (when (ignore-errors (goto-char (org-in-item-p)))
12753 (let* ((struct (org-list-struct))
12754 (prevs (org-list-prevs-alist struct)))
12755 (while (looking-at "[ \t]*- State")
12756 (goto-char (or (org-list-get-next-item (point) struct prevs)
12757 (org-list-get-item-end (point) struct)))))))
12759 (defun org-add-log-note (&optional purpose)
12760 "Pop up a window for taking a note, and add this note later at point."
12761 (remove-hook 'post-command-hook 'org-add-log-note)
12762 (setq org-log-note-window-configuration (current-window-configuration))
12763 (delete-other-windows)
12764 (move-marker org-log-note-return-to (point))
12765 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12766 (goto-char org-log-note-marker)
12767 (org-switch-to-buffer-other-window "*Org Note*")
12768 (erase-buffer)
12769 (if (memq org-log-note-how '(time state))
12770 (let (current-prefix-arg) (org-store-log-note))
12771 (let ((org-inhibit-startup t)) (org-mode))
12772 (insert (format "# Insert note for %s.
12773 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12774 (cond
12775 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12776 ((eq org-log-note-purpose 'done) "closed todo item")
12777 ((eq org-log-note-purpose 'state)
12778 (format "state change from \"%s\" to \"%s\""
12779 (or org-log-note-previous-state "")
12780 (or org-log-note-state "")))
12781 ((eq org-log-note-purpose 'reschedule)
12782 "rescheduling")
12783 ((eq org-log-note-purpose 'delschedule)
12784 "no longer scheduled")
12785 ((eq org-log-note-purpose 'redeadline)
12786 "changing deadline")
12787 ((eq org-log-note-purpose 'deldeadline)
12788 "removing deadline")
12789 ((eq org-log-note-purpose 'refile)
12790 "refiling")
12791 ((eq org-log-note-purpose 'note)
12792 "this entry")
12793 (t (error "This should not happen")))))
12794 (if org-log-note-extra (insert org-log-note-extra))
12795 (org-set-local 'org-finish-function 'org-store-log-note)
12796 (run-hooks 'org-log-buffer-setup-hook)))
12798 (defvar org-note-abort nil) ; dynamically scoped
12799 (defun org-store-log-note ()
12800 "Finish taking a log note, and insert it to where it belongs."
12801 (let ((txt (buffer-string)))
12802 (kill-buffer (current-buffer))
12803 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12804 lines ind bul)
12805 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12806 (setq txt (replace-match "" t t txt)))
12807 (if (string-match "\\s-+\\'" txt)
12808 (setq txt (replace-match "" t t txt)))
12809 (setq lines (org-split-string txt "\n"))
12810 (when (and note (string-match "\\S-" note))
12811 (setq note
12812 (org-replace-escapes
12813 note
12814 (list (cons "%u" (user-login-name))
12815 (cons "%U" user-full-name)
12816 (cons "%t" (format-time-string
12817 (org-time-stamp-format 'long 'inactive)
12818 org-log-note-effective-time))
12819 (cons "%T" (format-time-string
12820 (org-time-stamp-format 'long nil)
12821 org-log-note-effective-time))
12822 (cons "%d" (format-time-string
12823 (org-time-stamp-format nil 'inactive)
12824 org-log-note-effective-time))
12825 (cons "%D" (format-time-string
12826 (org-time-stamp-format nil nil)
12827 org-log-note-effective-time))
12828 (cons "%s" (if org-log-note-state
12829 (concat "\"" org-log-note-state "\"")
12830 ""))
12831 (cons "%S" (if org-log-note-previous-state
12832 (concat "\"" org-log-note-previous-state "\"")
12833 "\"\"")))))
12834 (if lines (setq note (concat note " \\\\")))
12835 (push note lines))
12836 (when (or current-prefix-arg org-note-abort)
12837 (when org-log-into-drawer
12838 (org-remove-empty-drawer-at
12839 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12840 org-log-note-marker))
12841 (setq lines nil))
12842 (when lines
12843 (with-current-buffer (marker-buffer org-log-note-marker)
12844 (save-excursion
12845 (goto-char org-log-note-marker)
12846 (move-marker org-log-note-marker nil)
12847 (end-of-line 1)
12848 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12849 (setq ind (save-excursion
12850 (if (ignore-errors (goto-char (org-in-item-p)))
12851 (let ((struct (org-list-struct)))
12852 (org-list-get-ind
12853 (org-list-get-top-point struct) struct))
12854 (skip-chars-backward " \r\t\n")
12855 (cond
12856 ((and (org-at-heading-p)
12857 org-adapt-indentation)
12858 (1+ (org-current-level)))
12859 ((org-at-heading-p) 0)
12860 (t (org-get-indentation))))))
12861 (setq bul (org-list-bullet-string "-"))
12862 (org-indent-line-to ind)
12863 (insert bul (pop lines))
12864 (let ((ind-body (+ (length bul) ind)))
12865 (while lines
12866 (insert "\n")
12867 (org-indent-line-to ind-body)
12868 (insert (pop lines))))
12869 (message "Note stored")
12870 (org-back-to-heading t)
12871 (org-cycle-hide-drawers 'children))))))
12872 (set-window-configuration org-log-note-window-configuration)
12873 (with-current-buffer (marker-buffer org-log-note-return-to)
12874 (goto-char org-log-note-return-to))
12875 (move-marker org-log-note-return-to nil)
12876 (and org-log-post-message (message "%s" org-log-post-message)))
12878 (defun org-remove-empty-drawer-at (drawer pos)
12879 "Remove an empty drawer DRAWER at position POS.
12880 POS may also be a marker."
12881 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12882 (save-excursion
12883 (save-restriction
12884 (widen)
12885 (goto-char pos)
12886 (if (org-in-regexp
12887 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12888 (replace-match ""))))))
12890 (defvar org-ts-type nil)
12891 (defun org-sparse-tree (&optional arg type)
12892 "Create a sparse tree, prompt for the details.
12893 This command can create sparse trees. You first need to select the type
12894 of match used to create the tree:
12896 t Show all TODO entries.
12897 T Show entries with a specific TODO keyword.
12898 m Show entries selected by a tags/property match.
12899 p Enter a property name and its value (both with completion on existing
12900 names/values) and show entries with that property.
12901 r Show entries matching a regular expression (`/' can be used as well).
12902 b Show deadlines and scheduled items before a date.
12903 a Show deadlines and scheduled items after a date.
12904 d Show deadlines due within `org-deadline-warning-days'.
12905 D Show deadlines and scheduled items between a date range."
12906 (interactive "P")
12907 (let (ans kwd value ts-type)
12908 (setq type (or type org-sparse-tree-default-date-type))
12909 (setq org-ts-type type)
12910 (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"
12911 (cond ((eq type 'all) "all timestamps")
12912 ((eq type 'scheduled) "only scheduled")
12913 ((eq type 'deadline) "only deadline")
12914 ((eq type 'active) "only active timestamps")
12915 ((eq type 'inactive) "only inactive timestamps")
12916 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12917 (t "scheduled/deadline")))
12918 (setq ans (read-char-exclusive))
12919 (cond
12920 ((equal ans ?c)
12921 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12922 ((equal ans ?d)
12923 (call-interactively 'org-check-deadlines))
12924 ((equal ans ?b)
12925 (call-interactively 'org-check-before-date))
12926 ((equal ans ?a)
12927 (call-interactively 'org-check-after-date))
12928 ((equal ans ?D)
12929 (call-interactively 'org-check-dates-range))
12930 ((equal ans ?t)
12931 (call-interactively 'org-show-todo-tree))
12932 ((equal ans ?T)
12933 (org-show-todo-tree '(4)))
12934 ((member ans '(?T ?m))
12935 (call-interactively 'org-match-sparse-tree))
12936 ((member ans '(?p ?P))
12937 (setq kwd (org-icompleting-read "Property: "
12938 (mapcar 'list (org-buffer-property-keys))))
12939 (setq value (org-icompleting-read "Value: "
12940 (mapcar 'list (org-property-values kwd))))
12941 (unless (string-match "\\`{.*}\\'" value)
12942 (setq value (concat "\"" value "\"")))
12943 (org-match-sparse-tree arg (concat kwd "=" value)))
12944 ((member ans '(?r ?R ?/))
12945 (call-interactively 'org-occur))
12946 (t (error "No such sparse tree command \"%c\"" ans)))))
12948 (defvar org-occur-highlights nil
12949 "List of overlays used for occur matches.")
12950 (make-variable-buffer-local 'org-occur-highlights)
12951 (defvar org-occur-parameters nil
12952 "Parameters of the active org-occur calls.
12953 This is a list, each call to org-occur pushes as cons cell,
12954 containing the regular expression and the callback, onto the list.
12955 The list can contain several entries if `org-occur' has been called
12956 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12957 will only contain one set of parameters. When the highlights are
12958 removed (for example with `C-c C-c', or with the next edit (depending
12959 on `org-remove-highlights-with-change'), this variable is emptied
12960 as well.")
12961 (make-variable-buffer-local 'org-occur-parameters)
12963 (defun org-occur (regexp &optional keep-previous callback)
12964 "Make a compact tree which shows all matches of REGEXP.
12965 The tree will show the lines where the regexp matches, and all higher
12966 headlines above the match. It will also show the heading after the match,
12967 to make sure editing the matching entry is easy.
12968 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12969 call to `org-occur' will be kept, to allow stacking of calls to this
12970 command.
12971 If CALLBACK is non-nil, it is a function which is called to confirm
12972 that the match should indeed be shown."
12973 (interactive "sRegexp: \nP")
12974 (when (equal regexp "")
12975 (error "Regexp cannot be empty"))
12976 (unless keep-previous
12977 (org-remove-occur-highlights nil nil t))
12978 (push (cons regexp callback) org-occur-parameters)
12979 (let ((cnt 0))
12980 (save-excursion
12981 (goto-char (point-min))
12982 (if (or (not keep-previous) ; do not want to keep
12983 (not org-occur-highlights)) ; no previous matches
12984 ;; hide everything
12985 (org-overview))
12986 (while (re-search-forward regexp nil t)
12987 (when (or (not callback)
12988 (save-match-data (funcall callback)))
12989 (setq cnt (1+ cnt))
12990 (when org-highlight-sparse-tree-matches
12991 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12992 (org-show-context 'occur-tree))))
12993 (when org-remove-highlights-with-change
12994 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12995 nil 'local))
12996 (unless org-sparse-tree-open-archived-trees
12997 (org-hide-archived-subtrees (point-min) (point-max)))
12998 (run-hooks 'org-occur-hook)
12999 (if (org-called-interactively-p 'interactive)
13000 (message "%d match(es) for regexp %s" cnt regexp))
13001 cnt))
13003 (defun org-occur-next-match (&optional n reset)
13004 "Function for `next-error-function' to find sparse tree matches.
13005 N is the number of matches to move, when negative move backwards.
13006 RESET is entirely ignored - this function always goes back to the
13007 starting point when no match is found."
13008 (let* ((limit (if (< n 0) (point-min) (point-max)))
13009 (search-func (if (< n 0)
13010 'previous-single-char-property-change
13011 'next-single-char-property-change))
13012 (n (abs n))
13013 (pos (point))
13015 (catch 'exit
13016 (while (setq p1 (funcall search-func (point) 'org-type))
13017 (when (equal p1 limit)
13018 (goto-char pos)
13019 (error "No more matches"))
13020 (when (equal (get-char-property p1 'org-type) 'org-occur)
13021 (setq n (1- n))
13022 (when (= n 0)
13023 (goto-char p1)
13024 (throw 'exit (point))))
13025 (goto-char p1))
13026 (goto-char p1)
13027 (error "No more matches"))))
13029 (defun org-show-context (&optional key)
13030 "Make sure point and context are visible.
13031 How much context is shown depends upon the variables
13032 `org-show-hierarchy-above', `org-show-following-heading',
13033 `org-show-entry-below' and `org-show-siblings'."
13034 (let ((heading-p (org-at-heading-p t))
13035 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13036 (following-p (org-get-alist-option org-show-following-heading key))
13037 (entry-p (org-get-alist-option org-show-entry-below key))
13038 (siblings-p (org-get-alist-option org-show-siblings key)))
13039 (catch 'exit
13040 ;; Show heading or entry text
13041 (if (and heading-p (not entry-p))
13042 (org-flag-heading nil) ; only show the heading
13043 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13044 (org-show-hidden-entry))) ; show entire entry
13045 (when following-p
13046 ;; Show next sibling, or heading below text
13047 (save-excursion
13048 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13049 (org-flag-heading nil))))
13050 (when siblings-p (org-show-siblings))
13051 (when hierarchy-p
13052 ;; show all higher headings, possibly with siblings
13053 (save-excursion
13054 (while (and (condition-case nil
13055 (progn (org-up-heading-all 1) t)
13056 (error nil))
13057 (not (bobp)))
13058 (org-flag-heading nil)
13059 (when siblings-p (org-show-siblings))))))))
13061 (defvar org-reveal-start-hook nil
13062 "Hook run before revealing a location.")
13064 (defun org-reveal (&optional siblings)
13065 "Show current entry, hierarchy above it, and the following headline.
13066 This can be used to show a consistent set of context around locations
13067 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13068 not t for the search context.
13070 With optional argument SIBLINGS, on each level of the hierarchy all
13071 siblings are shown. This repairs the tree structure to what it would
13072 look like when opened with hierarchical calls to `org-cycle'.
13073 With double optional argument \\[universal-argument] \\[universal-argument], \
13074 go to the parent and show the
13075 entire tree."
13076 (interactive "P")
13077 (run-hooks 'org-reveal-start-hook)
13078 (let ((org-show-hierarchy-above t)
13079 (org-show-following-heading t)
13080 (org-show-siblings (if siblings t org-show-siblings)))
13081 (org-show-context nil))
13082 (when (equal siblings '(16))
13083 (save-excursion
13084 (when (org-up-heading-safe)
13085 (org-show-subtree)
13086 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13088 (defun org-highlight-new-match (beg end)
13089 "Highlight from BEG to END and mark the highlight is an occur headline."
13090 (let ((ov (make-overlay beg end)))
13091 (overlay-put ov 'face 'secondary-selection)
13092 (overlay-put ov 'org-type 'org-occur)
13093 (push ov org-occur-highlights)))
13095 (defun org-remove-occur-highlights (&optional beg end noremove)
13096 "Remove the occur highlights from the buffer.
13097 BEG and END are ignored. If NOREMOVE is nil, remove this function
13098 from the `before-change-functions' in the current buffer."
13099 (interactive)
13100 (unless org-inhibit-highlight-removal
13101 (mapc 'delete-overlay org-occur-highlights)
13102 (setq org-occur-highlights nil)
13103 (setq org-occur-parameters nil)
13104 (unless noremove
13105 (remove-hook 'before-change-functions
13106 'org-remove-occur-highlights 'local))))
13108 ;;;; Priorities
13110 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13111 "Regular expression matching the priority indicator.")
13113 (defvar org-remove-priority-next-time nil)
13115 (defun org-priority-up ()
13116 "Increase the priority of the current item."
13117 (interactive)
13118 (org-priority 'up))
13120 (defun org-priority-down ()
13121 "Decrease the priority of the current item."
13122 (interactive)
13123 (org-priority 'down))
13125 (defun org-priority (&optional action show)
13126 "Change the priority of an item.
13127 ACTION can be `set', `up', `down', or a character."
13128 (interactive "P")
13129 (if (equal action '(4))
13130 (org-show-priority)
13131 (unless org-enable-priority-commands
13132 (error "Priority commands are disabled"))
13133 (setq action (or action 'set))
13134 (let (current new news have remove)
13135 (save-excursion
13136 (org-back-to-heading t)
13137 (if (looking-at org-priority-regexp)
13138 (setq current (string-to-char (match-string 2))
13139 have t))
13140 (cond
13141 ((eq action 'remove)
13142 (setq remove t new ?\ ))
13143 ((or (eq action 'set)
13144 (if (featurep 'xemacs) (characterp action) (integerp action)))
13145 (if (not (eq action 'set))
13146 (setq new action)
13147 (message "Priority %c-%c, SPC to remove: "
13148 org-highest-priority org-lowest-priority)
13149 (save-match-data
13150 (setq new (read-char-exclusive))))
13151 (if (and (= (upcase org-highest-priority) org-highest-priority)
13152 (= (upcase org-lowest-priority) org-lowest-priority))
13153 (setq new (upcase new)))
13154 (cond ((equal new ?\ ) (setq remove t))
13155 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13156 (error "Priority must be between `%c' and `%c'"
13157 org-highest-priority org-lowest-priority))))
13158 ((eq action 'up)
13159 (setq new (if have
13160 (1- current) ; normal cycling
13161 ;; last priority was empty
13162 (if (eq last-command this-command)
13163 org-lowest-priority ; wrap around empty to lowest
13164 ;; default
13165 (if org-priority-start-cycle-with-default
13166 org-default-priority
13167 (1- org-default-priority))))))
13168 ((eq action 'down)
13169 (setq new (if have
13170 (1+ current) ; normal cycling
13171 ;; last priority was empty
13172 (if (eq last-command this-command)
13173 org-highest-priority ; wrap around empty to highest
13174 ;; default
13175 (if org-priority-start-cycle-with-default
13176 org-default-priority
13177 (1+ org-default-priority))))))
13178 (t (error "Invalid action")))
13179 (if (or (< (upcase new) org-highest-priority)
13180 (> (upcase new) org-lowest-priority))
13181 (if (and (memq action '(up down))
13182 (not have) (not (eq last-command this-command)))
13183 ;; `new' is from default priority
13184 (error
13185 "The default can not be set, see `org-default-priority' why")
13186 ;; normal cycling: `new' is beyond highest/lowest priority
13187 ;; and is wrapped around to the empty priority
13188 (setq remove t)))
13189 (setq news (format "%c" new))
13190 (if have
13191 (if remove
13192 (replace-match "" t t nil 1)
13193 (replace-match news t t nil 2))
13194 (if remove
13195 (error "No priority cookie found in line")
13196 (let ((case-fold-search nil))
13197 (looking-at org-todo-line-regexp))
13198 (if (match-end 2)
13199 (progn
13200 (goto-char (match-end 2))
13201 (insert " [#" news "]"))
13202 (goto-char (match-beginning 3))
13203 (insert "[#" news "] "))))
13204 (org-preserve-lc (org-set-tags nil 'align)))
13205 (if remove
13206 (message "Priority removed")
13207 (message "Priority of current item set to %s" news)))))
13209 (defun org-show-priority ()
13210 "Show the priority of the current item.
13211 This priority is composed of the main priority given with the [#A] cookies,
13212 and by additional input from the age of a schedules or deadline entry."
13213 (interactive)
13214 (let ((pri (if (eq major-mode 'org-agenda-mode)
13215 (org-get-at-bol 'priority)
13216 (save-excursion
13217 (save-match-data
13218 (beginning-of-line)
13219 (and (looking-at org-heading-regexp)
13220 (org-get-priority (match-string 0))))))))
13221 (message "Priority is %d" (if pri pri -1000))))
13223 (defun org-get-priority (s)
13224 "Find priority cookie and return priority."
13225 (if (functionp org-get-priority-function)
13226 (funcall org-get-priority-function)
13227 (save-match-data
13228 (if (not (string-match org-priority-regexp s))
13229 (* 1000 (- org-lowest-priority org-default-priority))
13230 (* 1000 (- org-lowest-priority
13231 (string-to-char (match-string 2 s))))))))
13233 ;;;; Tags
13235 (defvar org-agenda-archives-mode)
13236 (defvar org-map-continue-from nil
13237 "Position from where mapping should continue.
13238 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13240 (defvar org-scanner-tags nil
13241 "The current tag list while the tags scanner is running.")
13242 (defvar org-trust-scanner-tags nil
13243 "Should `org-get-tags-at' use the tags for the scanner.
13244 This is for internal dynamical scoping only.
13245 When this is non-nil, the function `org-get-tags-at' will return the value
13246 of `org-scanner-tags' instead of building the list by itself. This
13247 can lead to large speed-ups when the tags scanner is used in a file with
13248 many entries, and when the list of tags is retrieved, for example to
13249 obtain a list of properties. Building the tags list for each entry in such
13250 a file becomes an N^2 operation - but with this variable set, it scales
13251 as N.")
13253 (defun org-scan-tags (action matcher todo-only &optional start-level)
13254 "Scan headline tags with inheritance and produce output ACTION.
13256 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13257 or `agenda' to produce an entry list for an agenda view. It can also be
13258 a Lisp form or a function that should be called at each matched headline, in
13259 this case the return value is a list of all return values from these calls.
13261 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13262 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13263 only lines with a not-done TODO keyword are included in the output.
13264 This should be the same variable that was scoped into
13265 and set by `org-make-tags-matcher' when it constructed MATCHER.
13267 START-LEVEL can be a string with asterisks, reducing the scope to
13268 headlines matching this string."
13269 (require 'org-agenda)
13270 (let* ((re (concat "^"
13271 (if start-level
13272 ;; Get the correct level to match
13273 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13274 org-outline-regexp)
13275 " *\\(\\<\\("
13276 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13277 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13278 (props (list 'face 'default
13279 'done-face 'org-agenda-done
13280 'undone-face 'default
13281 'mouse-face 'highlight
13282 'org-not-done-regexp org-not-done-regexp
13283 'org-todo-regexp org-todo-regexp
13284 'org-complex-heading-regexp org-complex-heading-regexp
13285 'help-echo
13286 (format "mouse-2 or RET jump to org file %s"
13287 (abbreviate-file-name
13288 (or (buffer-file-name (buffer-base-buffer))
13289 (buffer-name (buffer-base-buffer)))))))
13290 (case-fold-search nil)
13291 (org-map-continue-from nil)
13292 lspos tags tags-list
13293 (tags-alist (list (cons 0 org-file-tags)))
13294 (llast 0) rtn rtn1 level category i txt
13295 todo marker entry priority)
13296 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13297 (setq action (list 'lambda nil action)))
13298 (save-excursion
13299 (goto-char (point-min))
13300 (when (eq action 'sparse-tree)
13301 (org-overview)
13302 (org-remove-occur-highlights))
13303 (while (re-search-forward re nil t)
13304 (setq org-map-continue-from nil)
13305 (catch :skip
13306 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13307 tags (if (match-end 4) (org-match-string-no-properties 4)))
13308 (goto-char (setq lspos (match-beginning 0)))
13309 (setq level (org-reduced-level (org-outline-level))
13310 category (org-get-category))
13311 (setq i llast llast level)
13312 ;; remove tag lists from same and sublevels
13313 (while (>= i level)
13314 (when (setq entry (assoc i tags-alist))
13315 (setq tags-alist (delete entry tags-alist)))
13316 (setq i (1- i)))
13317 ;; add the next tags
13318 (when tags
13319 (setq tags (org-split-string tags ":")
13320 tags-alist
13321 (cons (cons level tags) tags-alist)))
13322 ;; compile tags for current headline
13323 (setq tags-list
13324 (if org-use-tag-inheritance
13325 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13326 tags)
13327 org-scanner-tags tags-list)
13328 (when org-use-tag-inheritance
13329 (setcdr (car tags-alist)
13330 (mapcar (lambda (x)
13331 (setq x (copy-sequence x))
13332 (org-add-prop-inherited x))
13333 (cdar tags-alist))))
13334 (when (and tags org-use-tag-inheritance
13335 (or (not (eq t org-use-tag-inheritance))
13336 org-tags-exclude-from-inheritance))
13337 ;; selective inheritance, remove uninherited ones
13338 (setcdr (car tags-alist)
13339 (org-remove-uninherited-tags (cdar tags-alist))))
13340 (when (and
13342 ;; eval matcher only when the todo condition is OK
13343 (and (or (not todo-only) (member todo org-not-done-keywords))
13344 (let ((case-fold-search t) (org-trust-scanner-tags t))
13345 (eval matcher)))
13347 ;; Call the skipper, but return t if it does not skip,
13348 ;; so that the `and' form continues evaluating
13349 (progn
13350 (unless (eq action 'sparse-tree) (org-agenda-skip))
13353 ;; Check if timestamps are deselecting this entry
13354 (or (not todo-only)
13355 (and (member todo org-not-done-keywords)
13356 (or (not org-agenda-tags-todo-honor-ignore-options)
13357 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13359 ;; Extra check for the archive tag
13360 ;; FIXME: Does the skipper already do this????
13362 (not (member org-archive-tag tags-list))
13363 ;; we have an archive tag, should we use this anyway?
13364 (or (not org-agenda-skip-archived-trees)
13365 (and (eq action 'agenda) org-agenda-archives-mode))))
13367 ;; select this headline
13368 (cond
13369 ((eq action 'sparse-tree)
13370 (and org-highlight-sparse-tree-matches
13371 (org-get-heading) (match-end 0)
13372 (org-highlight-new-match
13373 (match-beginning 1) (match-end 1)))
13374 (org-show-context 'tags-tree))
13375 ((eq action 'agenda)
13376 (setq txt (org-agenda-format-item
13378 (concat
13379 (if (eq org-tags-match-list-sublevels 'indented)
13380 (make-string (1- level) ?.) "")
13381 (org-get-heading))
13382 level category
13383 tags-list)
13384 priority (org-get-priority txt))
13385 (goto-char lspos)
13386 (setq marker (org-agenda-new-marker))
13387 (org-add-props txt props
13388 'org-marker marker 'org-hd-marker marker 'org-category category
13389 'todo-state todo
13390 'priority priority 'type "tagsmatch")
13391 (push txt rtn))
13392 ((functionp action)
13393 (setq org-map-continue-from nil)
13394 (save-excursion
13395 (setq rtn1 (funcall action))
13396 (push rtn1 rtn)))
13397 (t (error "Invalid action")))
13399 ;; if we are to skip sublevels, jump to end of subtree
13400 (unless org-tags-match-list-sublevels
13401 (org-end-of-subtree t)
13402 (backward-char 1))))
13403 ;; Get the correct position from where to continue
13404 (if org-map-continue-from
13405 (goto-char org-map-continue-from)
13406 (and (= (point) lspos) (end-of-line 1)))))
13407 (when (and (eq action 'sparse-tree)
13408 (not org-sparse-tree-open-archived-trees))
13409 (org-hide-archived-subtrees (point-min) (point-max)))
13410 (nreverse rtn)))
13412 (defun org-remove-uninherited-tags (tags)
13413 "Remove all tags that are not inherited from the list TAGS."
13414 (cond
13415 ((eq org-use-tag-inheritance t)
13416 (if org-tags-exclude-from-inheritance
13417 (org-delete-all org-tags-exclude-from-inheritance tags)
13418 tags))
13419 ((not org-use-tag-inheritance) nil)
13420 ((stringp org-use-tag-inheritance)
13421 (delq nil (mapcar
13422 (lambda (x)
13423 (if (and (string-match org-use-tag-inheritance x)
13424 (not (member x org-tags-exclude-from-inheritance)))
13425 x nil))
13426 tags)))
13427 ((listp org-use-tag-inheritance)
13428 (delq nil (mapcar
13429 (lambda (x)
13430 (if (member x org-use-tag-inheritance) x nil))
13431 tags)))))
13433 (defun org-match-sparse-tree (&optional todo-only match)
13434 "Create a sparse tree according to tags string MATCH.
13435 MATCH can contain positive and negative selection of tags, like
13436 \"+WORK+URGENT-WITHBOSS\".
13437 If optional argument TODO-ONLY is non-nil, only select lines that are
13438 also TODO lines."
13439 (interactive "P")
13440 (org-agenda-prepare-buffers (list (current-buffer)))
13441 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13443 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13445 (defvar org-cached-props nil)
13446 (defun org-cached-entry-get (pom property)
13447 (if (or (eq t org-use-property-inheritance)
13448 (and (stringp org-use-property-inheritance)
13449 (string-match org-use-property-inheritance property))
13450 (and (listp org-use-property-inheritance)
13451 (member property org-use-property-inheritance)))
13452 ;; Caching is not possible, check it directly
13453 (org-entry-get pom property 'inherit)
13454 ;; Get all properties, so that we can do complicated checks easily
13455 (cdr (assoc property (or org-cached-props
13456 (setq org-cached-props
13457 (org-entry-properties pom)))))))
13459 (defun org-global-tags-completion-table (&optional files)
13460 "Return the list of all tags in all agenda buffer/files.
13461 Optional FILES argument is a list of files which can be used
13462 instead of the agenda files."
13463 (save-excursion
13464 (org-uniquify
13465 (delq nil
13466 (apply 'append
13467 (mapcar
13468 (lambda (file)
13469 (set-buffer (find-file-noselect file))
13470 (append (org-get-buffer-tags)
13471 (mapcar (lambda (x) (if (stringp (car-safe x))
13472 (list (car-safe x)) nil))
13473 org-tag-alist)))
13474 (if (and files (car files))
13475 files
13476 (org-agenda-files))))))))
13478 (defun org-make-tags-matcher (match)
13479 "Create the TAGS/TODO matcher form for the selection string MATCH.
13481 The variable `todo-only' is scoped dynamically into this function.
13482 It will be set to t if the matcher restricts matching to TODO entries,
13483 otherwise will not be touched.
13485 Returns a cons of the selection string MATCH and the constructed
13486 lisp form implementing the matcher. The matcher is to be evaluated
13487 at an Org entry, with point on the headline, and returns t if the
13488 entry matches the selection string MATCH. The returned lisp form
13489 references two variables with information about the entry, which
13490 must be bound around the form's evaluation: todo, the TODO keyword
13491 at the entry (or nil of none); and tags-list, the list of all tags
13492 at the entry including inherited ones. Additionally, the category
13493 of the entry (if any) must be specified as the text property
13494 'org-category on the headline.
13496 See also `org-scan-tags'.
13498 (declare (special todo-only))
13499 (unless (boundp 'todo-only)
13500 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13501 (unless match
13502 ;; Get a new match request, with completion
13503 (let ((org-last-tags-completion-table
13504 (org-global-tags-completion-table)))
13505 (setq match (org-completing-read-no-i
13506 "Match: " 'org-tags-completion-function nil nil nil
13507 'org-tags-history))))
13509 ;; Parse the string and create a lisp form
13510 (let ((match0 match)
13511 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13512 minus tag mm
13513 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13514 orterms term orlist re-p str-p level-p level-op time-p
13515 prop-p pn pv po gv rest)
13516 (if (string-match "/+" match)
13517 ;; match contains also a todo-matching request
13518 (progn
13519 (setq tagsmatch (substring match 0 (match-beginning 0))
13520 todomatch (substring match (match-end 0)))
13521 (if (string-match "^!" todomatch)
13522 (setq todo-only t todomatch (substring todomatch 1)))
13523 (if (string-match "^\\s-*$" todomatch)
13524 (setq todomatch nil)))
13525 ;; only matching tags
13526 (setq tagsmatch match todomatch nil))
13528 ;; Make the tags matcher
13529 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13530 (setq tagsmatcher t)
13531 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13532 (while (setq term (pop orterms))
13533 (while (and (equal (substring term -1) "\\") orterms)
13534 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13535 (while (string-match re term)
13536 (setq rest (substring term (match-end 0))
13537 minus (and (match-end 1)
13538 (equal (match-string 1 term) "-"))
13539 tag (save-match-data (replace-regexp-in-string
13540 "\\\\-" "-"
13541 (match-string 2 term)))
13542 re-p (equal (string-to-char tag) ?{)
13543 level-p (match-end 4)
13544 prop-p (match-end 5)
13545 mm (cond
13546 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13547 (level-p
13548 (setq level-op (org-op-to-function (match-string 3 term)))
13549 `(,level-op level ,(string-to-number
13550 (match-string 4 term))))
13551 (prop-p
13552 (setq pn (match-string 5 term)
13553 po (match-string 6 term)
13554 pv (match-string 7 term)
13555 re-p (equal (string-to-char pv) ?{)
13556 str-p (equal (string-to-char pv) ?\")
13557 time-p (save-match-data
13558 (string-match "^\"[[<].*[]>]\"$" pv))
13559 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13560 (if time-p (setq pv (org-matcher-time pv)))
13561 (setq po (org-op-to-function po (if time-p 'time str-p)))
13562 (cond
13563 ((equal pn "CATEGORY")
13564 (setq gv '(get-text-property (point) 'org-category)))
13565 ((equal pn "TODO")
13566 (setq gv 'todo))
13568 (setq gv `(org-cached-entry-get nil ,pn))))
13569 (if re-p
13570 (if (eq po 'org<>)
13571 `(not (string-match ,pv (or ,gv "")))
13572 `(string-match ,pv (or ,gv "")))
13573 (if str-p
13574 `(,po (or ,gv "") ,pv)
13575 `(,po (string-to-number (or ,gv ""))
13576 ,(string-to-number pv) ))))
13577 (t `(member ,tag tags-list)))
13578 mm (if minus (list 'not mm) mm)
13579 term rest)
13580 (push mm tagsmatcher))
13581 (push (if (> (length tagsmatcher) 1)
13582 (cons 'and tagsmatcher)
13583 (car tagsmatcher))
13584 orlist)
13585 (setq tagsmatcher nil))
13586 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13587 (setq tagsmatcher
13588 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13589 ;; Make the todo matcher
13590 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13591 (setq todomatcher t)
13592 (setq orterms (org-split-string todomatch "|") orlist nil)
13593 (while (setq term (pop orterms))
13594 (while (string-match re term)
13595 (setq minus (and (match-end 1)
13596 (equal (match-string 1 term) "-"))
13597 kwd (match-string 2 term)
13598 re-p (equal (string-to-char kwd) ?{)
13599 term (substring term (match-end 0))
13600 mm (if re-p
13601 `(string-match ,(substring kwd 1 -1) todo)
13602 (list 'equal 'todo kwd))
13603 mm (if minus (list 'not mm) mm))
13604 (push mm todomatcher))
13605 (push (if (> (length todomatcher) 1)
13606 (cons 'and todomatcher)
13607 (car todomatcher))
13608 orlist)
13609 (setq todomatcher nil))
13610 (setq todomatcher (if (> (length orlist) 1)
13611 (cons 'or orlist) (car orlist))))
13613 ;; Return the string and lisp forms of the matcher
13614 (setq matcher (if todomatcher
13615 (list 'and tagsmatcher todomatcher)
13616 tagsmatcher))
13617 (when todo-only
13618 (setq matcher (list 'and '(member todo org-not-done-keywords)
13619 matcher)))
13620 (cons match0 matcher)))
13622 (defun org-op-to-function (op &optional stringp)
13623 "Turn an operator into the appropriate function."
13624 (setq op
13625 (cond
13626 ((equal op "<" ) '(< string< org-time<))
13627 ((equal op ">" ) '(> org-string> org-time>))
13628 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13629 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13630 ((member op '("=" "==")) '(= string= org-time=))
13631 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13632 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13634 (defun org<> (a b) (not (= a b)))
13635 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13636 (defun org-string>= (a b) (not (string< a b)))
13637 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13638 (defun org-string<> (a b) (not (string= a b)))
13639 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13640 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13641 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13642 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13643 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13644 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13645 (defun org-2ft (s)
13646 "Convert S to a floating point time.
13647 If S is already a number, just return it. If it is a string, parse
13648 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13649 (cond
13650 ((numberp s) s)
13651 ((stringp s)
13652 (condition-case nil
13653 (float-time (apply 'encode-time (org-parse-time-string s)))
13654 (error 0.)))
13655 (t 0.)))
13657 (defun org-time-today ()
13658 "Time in seconds today at 0:00.
13659 Returns the float number of seconds since the beginning of the
13660 epoch to the beginning of today (00:00)."
13661 (float-time (apply 'encode-time
13662 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13664 (defun org-matcher-time (s)
13665 "Interpret a time comparison value."
13666 (save-match-data
13667 (cond
13668 ((string= s "<now>") (float-time))
13669 ((string= s "<today>") (org-time-today))
13670 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13671 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13672 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13673 (+ (org-time-today)
13674 (* (string-to-number (match-string 1 s))
13675 (cdr (assoc (match-string 2 s)
13676 '(("d" . 86400.0) ("w" . 604800.0)
13677 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13678 (t (org-2ft s)))))
13680 (defun org-match-any-p (re list)
13681 "Does re match any element of list?"
13682 (setq list (mapcar (lambda (x) (string-match re x)) list))
13683 (delq nil list))
13685 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13686 (defvar org-tags-overlay (make-overlay 1 1))
13687 (org-detach-overlay org-tags-overlay)
13689 (defun org-get-local-tags-at (&optional pos)
13690 "Get a list of tags defined in the current headline."
13691 (org-get-tags-at pos 'local))
13693 (defun org-get-local-tags ()
13694 "Get a list of tags defined in the current headline."
13695 (org-get-tags-at nil 'local))
13697 (defun org-get-tags-at (&optional pos local)
13698 "Get a list of all headline tags applicable at POS.
13699 POS defaults to point. If tags are inherited, the list contains
13700 the targets in the same sequence as the headlines appear, i.e.
13701 the tags of the current headline come last.
13702 When LOCAL is non-nil, only return tags from the current headline,
13703 ignore inherited ones."
13704 (interactive)
13705 (if (and org-trust-scanner-tags
13706 (or (not pos) (equal pos (point)))
13707 (not local))
13708 org-scanner-tags
13709 (let (tags ltags lastpos parent)
13710 (save-excursion
13711 (save-restriction
13712 (widen)
13713 (goto-char (or pos (point)))
13714 (save-match-data
13715 (catch 'done
13716 (condition-case nil
13717 (progn
13718 (org-back-to-heading t)
13719 (while (not (equal lastpos (point)))
13720 (setq lastpos (point))
13721 (when (looking-at
13722 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13723 (setq ltags (org-split-string
13724 (org-match-string-no-properties 1) ":"))
13725 (when parent
13726 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13727 (setq tags (append
13728 (if parent
13729 (org-remove-uninherited-tags ltags)
13730 ltags)
13731 tags)))
13732 (or org-use-tag-inheritance (throw 'done t))
13733 (if local (throw 'done t))
13734 (or (org-up-heading-safe) (error nil))
13735 (setq parent t)))
13736 (error nil)))))
13737 (if local
13738 tags
13739 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13741 (defun org-add-prop-inherited (s)
13742 (add-text-properties 0 (length s) '(inherited t) s)
13745 (defun org-toggle-tag (tag &optional onoff)
13746 "Toggle the tag TAG for the current line.
13747 If ONOFF is `on' or `off', don't toggle but set to this state."
13748 (let (res current)
13749 (save-excursion
13750 (org-back-to-heading t)
13751 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13752 (point-at-eol) t)
13753 (progn
13754 (setq current (match-string 1))
13755 (replace-match ""))
13756 (setq current ""))
13757 (setq current (nreverse (org-split-string current ":")))
13758 (cond
13759 ((eq onoff 'on)
13760 (setq res t)
13761 (or (member tag current) (push tag current)))
13762 ((eq onoff 'off)
13763 (or (not (member tag current)) (setq current (delete tag current))))
13764 (t (if (member tag current)
13765 (setq current (delete tag current))
13766 (setq res t)
13767 (push tag current))))
13768 (end-of-line 1)
13769 (if current
13770 (progn
13771 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13772 (org-set-tags nil t))
13773 (delete-horizontal-space))
13774 (run-hooks 'org-after-tags-change-hook))
13775 res))
13777 (defun org-align-tags-here (to-col)
13778 ;; Assumes that this is a headline
13779 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13780 (beginning-of-line 1)
13781 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13782 (< pos (match-beginning 2)))
13783 (progn
13784 (setq tags-l (- (match-end 2) (match-beginning 2)))
13785 (goto-char (match-beginning 1))
13786 (insert " ")
13787 (delete-region (point) (1+ (match-beginning 2)))
13788 (setq ncol (max (current-column)
13789 (1+ col)
13790 (if (> to-col 0)
13791 to-col
13792 (- (abs to-col) tags-l))))
13793 (setq p (point))
13794 (insert (make-string (- ncol (current-column)) ?\ ))
13795 (setq ncol (current-column))
13796 (when indent-tabs-mode (tabify p (point-at-eol)))
13797 (org-move-to-column (min ncol col) t))
13798 (goto-char pos))))
13800 (defun org-set-tags-command (&optional arg just-align)
13801 "Call the set-tags command for the current entry."
13802 (interactive "P")
13803 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13804 (org-set-tags arg just-align)
13805 (save-excursion
13806 (org-back-to-heading t)
13807 (org-set-tags arg just-align))))
13809 (defun org-set-tags-to (data)
13810 "Set the tags of the current entry to DATA, replacing the current tags.
13811 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13812 If DATA is nil or the empty string, any tags will be removed."
13813 (interactive "sTags: ")
13814 (setq data
13815 (cond
13816 ((eq data nil) "")
13817 ((equal data "") "")
13818 ((stringp data)
13819 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13820 ":"))
13821 ((listp data)
13822 (concat ":" (mapconcat 'identity data ":") ":"))))
13823 (when data
13824 (save-excursion
13825 (org-back-to-heading t)
13826 (when (looking-at org-complex-heading-regexp)
13827 (if (match-end 5)
13828 (progn
13829 (goto-char (match-beginning 5))
13830 (insert data)
13831 (delete-region (point) (point-at-eol))
13832 (org-set-tags nil 'align))
13833 (goto-char (point-at-eol))
13834 (insert " " data)
13835 (org-set-tags nil 'align)))
13836 (beginning-of-line 1)
13837 (if (looking-at ".*?\\([ \t]+\\)$")
13838 (delete-region (match-beginning 1) (match-end 1))))))
13840 (defun org-align-all-tags ()
13841 "Align the tags i all headings."
13842 (interactive)
13843 (save-excursion
13844 (or (ignore-errors (org-back-to-heading t))
13845 (outline-next-heading))
13846 (if (org-at-heading-p)
13847 (org-set-tags t)
13848 (message "No headings"))))
13850 (defvar org-indent-indentation-per-level)
13851 (defun org-set-tags (&optional arg just-align)
13852 "Set the tags for the current headline.
13853 With prefix ARG, realign all tags in headings in the current buffer."
13854 (interactive "P")
13855 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13856 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13857 'region-start-level 'region))
13858 org-loop-over-headlines-in-active-region)
13859 (org-map-entries
13860 ;; We don't use ARG and JUST-ALIGN here these args are not
13861 ;; useful when looping over headlines
13862 `(org-set-tags)
13863 org-loop-over-headlines-in-active-region
13864 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13865 (let* ((re org-outline-regexp-bol)
13866 (current (unless arg (org-get-tags-string)))
13867 (col (current-column))
13868 (org-setting-tags t)
13869 table current-tags inherited-tags ; computed below when needed
13870 tags p0 c0 c1 rpl di tc level)
13871 (if arg
13872 (save-excursion
13873 (goto-char (point-min))
13874 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13875 (while (re-search-forward re nil t)
13876 (org-set-tags nil t)
13877 (end-of-line 1)))
13878 (message "All tags realigned to column %d" org-tags-column))
13879 (if just-align
13880 (setq tags current)
13881 ;; Get a new set of tags from the user
13882 (save-excursion
13883 (setq table (append org-tag-persistent-alist
13884 (or org-tag-alist (org-get-buffer-tags))
13885 (and
13886 org-complete-tags-always-offer-all-agenda-tags
13887 (org-global-tags-completion-table
13888 (org-agenda-files))))
13889 org-last-tags-completion-table table
13890 current-tags (org-split-string current ":")
13891 inherited-tags (nreverse
13892 (nthcdr (length current-tags)
13893 (nreverse (org-get-tags-at))))
13894 tags
13895 (if (or (eq t org-use-fast-tag-selection)
13896 (and org-use-fast-tag-selection
13897 (delq nil (mapcar 'cdr table))))
13898 (org-fast-tag-selection
13899 current-tags inherited-tags table
13900 (if org-fast-tag-selection-include-todo
13901 org-todo-key-alist))
13902 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13903 (org-trim
13904 (org-icompleting-read "Tags: "
13905 'org-tags-completion-function
13906 nil nil current 'org-tags-history))))))
13907 (while (string-match "[-+&]+" tags)
13908 ;; No boolean logic, just a list
13909 (setq tags (replace-match ":" t t tags))))
13911 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13913 (if org-tags-sort-function
13914 (setq tags (mapconcat 'identity
13915 (sort (org-split-string
13916 tags (org-re "[^[:alnum:]_@#%]+"))
13917 org-tags-sort-function) ":")))
13919 (if (string-match "\\`[\t ]*\\'" tags)
13920 (setq tags "")
13921 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13922 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13924 ;; Insert new tags at the correct column
13925 (beginning-of-line 1)
13926 (setq level (or (and (looking-at org-outline-regexp)
13927 (- (match-end 0) (point) 1))
13929 (cond
13930 ((and (equal current "") (equal tags "")))
13931 ((re-search-forward
13932 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13933 (point-at-eol) t)
13934 (if (equal tags "")
13935 (setq rpl "")
13936 (goto-char (match-beginning 0))
13937 (setq c0 (current-column)
13938 ;; compute offset for the case of org-indent-mode active
13939 di (if org-indent-mode
13940 (* (1- org-indent-indentation-per-level) (1- level))
13942 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13943 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13944 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13945 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13946 (replace-match rpl t t)
13947 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13948 tags)
13949 (t (error "Tags alignment failed")))
13950 (org-move-to-column col)
13951 (unless just-align
13952 (run-hooks 'org-after-tags-change-hook))))))
13954 (defun org-change-tag-in-region (beg end tag off)
13955 "Add or remove TAG for each entry in the region.
13956 This works in the agenda, and also in an org-mode buffer."
13957 (interactive
13958 (list (region-beginning) (region-end)
13959 (let ((org-last-tags-completion-table
13960 (if (derived-mode-p 'org-mode)
13961 (org-get-buffer-tags)
13962 (org-global-tags-completion-table))))
13963 (org-icompleting-read
13964 "Tag: " 'org-tags-completion-function nil nil nil
13965 'org-tags-history))
13966 (progn
13967 (message "[s]et or [r]emove? ")
13968 (equal (read-char-exclusive) ?r))))
13969 (if (fboundp 'deactivate-mark) (deactivate-mark))
13970 (let ((agendap (equal major-mode 'org-agenda-mode))
13971 l1 l2 m buf pos newhead (cnt 0))
13972 (goto-char end)
13973 (setq l2 (1- (org-current-line)))
13974 (goto-char beg)
13975 (setq l1 (org-current-line))
13976 (loop for l from l1 to l2 do
13977 (org-goto-line l)
13978 (setq m (get-text-property (point) 'org-hd-marker))
13979 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13980 (and agendap m))
13981 (setq buf (if agendap (marker-buffer m) (current-buffer))
13982 pos (if agendap m (point)))
13983 (with-current-buffer buf
13984 (save-excursion
13985 (save-restriction
13986 (goto-char pos)
13987 (setq cnt (1+ cnt))
13988 (org-toggle-tag tag (if off 'off 'on))
13989 (setq newhead (org-get-heading)))))
13990 (and agendap (org-agenda-change-all-lines newhead m))))
13991 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13993 (defun org-tags-completion-function (string predicate &optional flag)
13994 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13995 (confirm (lambda (x) (stringp (car x)))))
13996 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13997 (setq s1 (match-string 1 string)
13998 s2 (match-string 2 string))
13999 (setq s1 "" s2 string))
14000 (cond
14001 ((eq flag nil)
14002 ;; try completion
14003 (setq rtn (try-completion s2 ctable confirm))
14004 (if (stringp rtn)
14005 (setq rtn
14006 (concat s1 s2 (substring rtn (length s2))
14007 (if (and org-add-colon-after-tag-completion
14008 (assoc rtn ctable))
14009 ":" ""))))
14010 rtn)
14011 ((eq flag t)
14012 ;; all-completions
14013 (all-completions s2 ctable confirm)
14015 ((eq flag 'lambda)
14016 ;; exact match?
14017 (assoc s2 ctable)))
14020 (defun org-fast-tag-insert (kwd tags face &optional end)
14021 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14022 (insert (format "%-12s" (concat kwd ":"))
14023 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14024 (or end "")))
14026 (defun org-fast-tag-show-exit (flag)
14027 (save-excursion
14028 (org-goto-line 3)
14029 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14030 (replace-match ""))
14031 (when flag
14032 (end-of-line 1)
14033 (org-move-to-column (- (window-width) 19) t)
14034 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14036 (defun org-set-current-tags-overlay (current prefix)
14037 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14038 (if (featurep 'xemacs)
14039 (org-overlay-display org-tags-overlay (concat prefix s)
14040 'secondary-selection)
14041 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14042 (org-overlay-display org-tags-overlay (concat prefix s)))))
14044 (defvar org-last-tag-selection-key nil)
14045 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14046 "Fast tag selection with single keys.
14047 CURRENT is the current list of tags in the headline, INHERITED is the
14048 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14049 possibly with grouping information. TODO-TABLE is a similar table with
14050 TODO keywords, should these have keys assigned to them.
14051 If the keys are nil, a-z are automatically assigned.
14052 Returns the new tags string, or nil to not change the current settings."
14053 (let* ((fulltable (append table todo-table))
14054 (maxlen (apply 'max (mapcar
14055 (lambda (x)
14056 (if (stringp (car x)) (string-width (car x)) 0))
14057 fulltable)))
14058 (buf (current-buffer))
14059 (expert (eq org-fast-tag-selection-single-key 'expert))
14060 (buffer-tags nil)
14061 (fwidth (+ maxlen 3 1 3))
14062 (ncol (/ (- (window-width) 4) fwidth))
14063 (i-face 'org-done)
14064 (c-face 'org-todo)
14065 tg cnt e c char c1 c2 ntable tbl rtn
14066 ov-start ov-end ov-prefix
14067 (exit-after-next org-fast-tag-selection-single-key)
14068 (done-keywords org-done-keywords)
14069 groups ingroup)
14070 (save-excursion
14071 (beginning-of-line 1)
14072 (if (looking-at
14073 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14074 (setq ov-start (match-beginning 1)
14075 ov-end (match-end 1)
14076 ov-prefix "")
14077 (setq ov-start (1- (point-at-eol))
14078 ov-end (1+ ov-start))
14079 (skip-chars-forward "^\n\r")
14080 (setq ov-prefix
14081 (concat
14082 (buffer-substring (1- (point)) (point))
14083 (if (> (current-column) org-tags-column)
14085 (make-string (- org-tags-column (current-column)) ?\ ))))))
14086 (move-overlay org-tags-overlay ov-start ov-end)
14087 (save-window-excursion
14088 (if expert
14089 (set-buffer (get-buffer-create " *Org tags*"))
14090 (delete-other-windows)
14091 (split-window-vertically)
14092 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14093 (erase-buffer)
14094 (org-set-local 'org-done-keywords done-keywords)
14095 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14096 (org-fast-tag-insert "Current" current c-face "\n\n")
14097 (org-fast-tag-show-exit exit-after-next)
14098 (org-set-current-tags-overlay current ov-prefix)
14099 (setq tbl fulltable char ?a cnt 0)
14100 (while (setq e (pop tbl))
14101 (cond
14102 ((equal (car e) :startgroup)
14103 (push '() groups) (setq ingroup t)
14104 (when (not (= cnt 0))
14105 (setq cnt 0)
14106 (insert "\n"))
14107 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14108 ((equal (car e) :endgroup)
14109 (setq ingroup nil cnt 0)
14110 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14111 ((equal e '(:newline))
14112 (when (not (= cnt 0))
14113 (setq cnt 0)
14114 (insert "\n")
14115 (setq e (car tbl))
14116 (while (equal (car tbl) '(:newline))
14117 (insert "\n")
14118 (setq tbl (cdr tbl)))))
14120 (setq tg (copy-sequence (car e)) c2 nil)
14121 (if (cdr e)
14122 (setq c (cdr e))
14123 ;; automatically assign a character.
14124 (setq c1 (string-to-char
14125 (downcase (substring
14126 tg (if (= (string-to-char tg) ?@) 1 0)))))
14127 (if (or (rassoc c1 ntable) (rassoc c1 table))
14128 (while (or (rassoc char ntable) (rassoc char table))
14129 (setq char (1+ char)))
14130 (setq c2 c1))
14131 (setq c (or c2 char)))
14132 (if ingroup (push tg (car groups)))
14133 (setq tg (org-add-props tg nil 'face
14134 (cond
14135 ((not (assoc tg table))
14136 (org-get-todo-face tg))
14137 ((member tg current) c-face)
14138 ((member tg inherited) i-face))))
14139 (if (and (= cnt 0) (not ingroup)) (insert " "))
14140 (insert "[" c "] " tg (make-string
14141 (- fwidth 4 (length tg)) ?\ ))
14142 (push (cons tg c) ntable)
14143 (when (= (setq cnt (1+ cnt)) ncol)
14144 (insert "\n")
14145 (if ingroup (insert " "))
14146 (setq cnt 0)))))
14147 (setq ntable (nreverse ntable))
14148 (insert "\n")
14149 (goto-char (point-min))
14150 (if (not expert) (org-fit-window-to-buffer))
14151 (setq rtn
14152 (catch 'exit
14153 (while t
14154 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14155 (if (not groups) "no " "")
14156 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14157 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14158 (setq org-last-tag-selection-key c)
14159 (cond
14160 ((= c ?\r) (throw 'exit t))
14161 ((= c ?!)
14162 (setq groups (not groups))
14163 (goto-char (point-min))
14164 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14165 ((= c ?\C-c)
14166 (if (not expert)
14167 (org-fast-tag-show-exit
14168 (setq exit-after-next (not exit-after-next)))
14169 (setq expert nil)
14170 (delete-other-windows)
14171 (set-window-buffer (split-window-vertically) " *Org tags*")
14172 (org-switch-to-buffer-other-window " *Org tags*")
14173 (org-fit-window-to-buffer)))
14174 ((or (= c ?\C-g)
14175 (and (= c ?q) (not (rassoc c ntable))))
14176 (org-detach-overlay org-tags-overlay)
14177 (setq quit-flag t))
14178 ((= c ?\ )
14179 (setq current nil)
14180 (if exit-after-next (setq exit-after-next 'now)))
14181 ((= c ?\t)
14182 (condition-case nil
14183 (setq tg (org-icompleting-read
14184 "Tag: "
14185 (or buffer-tags
14186 (with-current-buffer buf
14187 (org-get-buffer-tags)))))
14188 (quit (setq tg "")))
14189 (when (string-match "\\S-" tg)
14190 (add-to-list 'buffer-tags (list tg))
14191 (if (member tg current)
14192 (setq current (delete tg current))
14193 (push tg current)))
14194 (if exit-after-next (setq exit-after-next 'now)))
14195 ((setq e (rassoc c todo-table) tg (car e))
14196 (with-current-buffer buf
14197 (save-excursion (org-todo tg)))
14198 (if exit-after-next (setq exit-after-next 'now)))
14199 ((setq e (rassoc c ntable) tg (car e))
14200 (if (member tg current)
14201 (setq current (delete tg current))
14202 (loop for g in groups do
14203 (if (member tg g)
14204 (mapc (lambda (x)
14205 (setq current (delete x current)))
14206 g)))
14207 (push tg current))
14208 (if exit-after-next (setq exit-after-next 'now))))
14210 ;; Create a sorted list
14211 (setq current
14212 (sort current
14213 (lambda (a b)
14214 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14215 (if (eq exit-after-next 'now) (throw 'exit t))
14216 (goto-char (point-min))
14217 (beginning-of-line 2)
14218 (delete-region (point) (point-at-eol))
14219 (org-fast-tag-insert "Current" current c-face)
14220 (org-set-current-tags-overlay current ov-prefix)
14221 (while (re-search-forward
14222 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14223 (setq tg (match-string 1))
14224 (add-text-properties
14225 (match-beginning 1) (match-end 1)
14226 (list 'face
14227 (cond
14228 ((member tg current) c-face)
14229 ((member tg inherited) i-face)
14230 (t (get-text-property (match-beginning 1) 'face))))))
14231 (goto-char (point-min)))))
14232 (org-detach-overlay org-tags-overlay)
14233 (if rtn
14234 (mapconcat 'identity current ":")
14235 nil))))
14237 (defun org-get-tags-string ()
14238 "Get the TAGS string in the current headline."
14239 (unless (org-at-heading-p t)
14240 (error "Not on a heading"))
14241 (save-excursion
14242 (beginning-of-line 1)
14243 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14244 (org-match-string-no-properties 1)
14245 "")))
14247 (defun org-get-tags ()
14248 "Get the list of tags specified in the current headline."
14249 (org-split-string (org-get-tags-string) ":"))
14251 (defun org-get-buffer-tags ()
14252 "Get a table of all tags used in the buffer, for completion."
14253 (let (tags)
14254 (save-excursion
14255 (goto-char (point-min))
14256 (while (re-search-forward
14257 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14258 (when (equal (char-after (point-at-bol 0)) ?*)
14259 (mapc (lambda (x) (add-to-list 'tags x))
14260 (org-split-string (org-match-string-no-properties 1) ":")))))
14261 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14262 (mapcar 'list tags)))
14264 ;;;; The mapping API
14266 (defun org-map-entries (func &optional match scope &rest skip)
14267 "Call FUNC at each headline selected by MATCH in SCOPE.
14269 FUNC is a function or a lisp form. The function will be called without
14270 arguments, with the cursor positioned at the beginning of the headline.
14271 The return values of all calls to the function will be collected and
14272 returned as a list.
14274 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14275 does not need to preserve point. After evaluation, the cursor will be
14276 moved to the end of the line (presumably of the headline of the
14277 processed entry) and search continues from there. Under some
14278 circumstances, this may not produce the wanted results. For example,
14279 if you have removed (e.g. archived) the current (sub)tree it could
14280 mean that the next entry will be skipped entirely. In such cases, you
14281 can specify the position from where search should continue by making
14282 FUNC set the variable `org-map-continue-from' to the desired buffer
14283 position.
14285 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14286 Only headlines that are matched by this query will be considered during
14287 the iteration. When MATCH is nil or t, all headlines will be
14288 visited by the iteration.
14290 SCOPE determines the scope of this command. It can be any of:
14292 nil The current buffer, respecting the restriction if any
14293 tree The subtree started with the entry at point
14294 region The entries within the active region, if any
14295 region-start-level
14296 The entries within the active region, but only those at
14297 the same level than the first one.
14298 file The current buffer, without restriction
14299 file-with-archives
14300 The current buffer, and any archives associated with it
14301 agenda All agenda files
14302 agenda-with-archives
14303 All agenda files with any archive files associated with them
14304 \(file1 file2 ...)
14305 If this is a list, all files in the list will be scanned
14307 The remaining args are treated as settings for the skipping facilities of
14308 the scanner. The following items can be given here:
14310 archive skip trees with the archive tag.
14311 comment skip trees with the COMMENT keyword
14312 function or Emacs Lisp form:
14313 will be used as value for `org-agenda-skip-function', so whenever
14314 the function returns t, FUNC will not be called for that
14315 entry and search will continue from the point where the
14316 function leaves it.
14318 If your function needs to retrieve the tags including inherited tags
14319 at the *current* entry, you can use the value of the variable
14320 `org-scanner-tags' which will be much faster than getting the value
14321 with `org-get-tags-at'. If your function gets properties with
14322 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14323 to t around the call to `org-entry-properties' to get the same speedup.
14324 Note that if your function moves around to retrieve tags and properties at
14325 a *different* entry, you cannot use these techniques."
14326 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14327 (not (org-region-active-p)))
14328 (let* ((org-agenda-archives-mode nil) ; just to make sure
14329 (org-agenda-skip-archived-trees (memq 'archive skip))
14330 (org-agenda-skip-comment-trees (memq 'comment skip))
14331 (org-agenda-skip-function
14332 (car (org-delete-all '(comment archive) skip)))
14333 (org-tags-match-list-sublevels t)
14334 (start-level (eq scope 'region-start-level))
14335 matcher file res
14336 org-todo-keywords-for-agenda
14337 org-done-keywords-for-agenda
14338 org-todo-keyword-alist-for-agenda
14339 org-drawers-for-agenda
14340 org-tag-alist-for-agenda
14341 todo-only)
14343 (cond
14344 ((eq match t) (setq matcher t))
14345 ((eq match nil) (setq matcher t))
14346 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14348 (save-excursion
14349 (save-restriction
14350 (cond ((eq scope 'tree)
14351 (org-back-to-heading t)
14352 (org-narrow-to-subtree)
14353 (setq scope nil))
14354 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14355 (org-region-active-p))
14356 ;; If needed, set start-level to a string like "2"
14357 (when start-level
14358 (save-excursion
14359 (goto-char (region-beginning))
14360 (unless (org-at-heading-p) (outline-next-heading))
14361 (setq start-level (org-current-level))))
14362 (narrow-to-region (region-beginning)
14363 (save-excursion
14364 (goto-char (region-end))
14365 (unless (and (bolp) (org-at-heading-p))
14366 (outline-next-heading))
14367 (point)))
14368 (setq scope nil)))
14370 (if (not scope)
14371 (progn
14372 (org-agenda-prepare-buffers
14373 (list (buffer-file-name (current-buffer))))
14374 (setq res (org-scan-tags func matcher todo-only start-level)))
14375 ;; Get the right scope
14376 (cond
14377 ((and scope (listp scope) (symbolp (car scope)))
14378 (setq scope (eval scope)))
14379 ((eq scope 'agenda)
14380 (setq scope (org-agenda-files t)))
14381 ((eq scope 'agenda-with-archives)
14382 (setq scope (org-agenda-files t))
14383 (setq scope (org-add-archive-files scope)))
14384 ((eq scope 'file)
14385 (setq scope (list (buffer-file-name))))
14386 ((eq scope 'file-with-archives)
14387 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14388 (org-agenda-prepare-buffers scope)
14389 (while (setq file (pop scope))
14390 (with-current-buffer (org-find-base-buffer-visiting file)
14391 (save-excursion
14392 (save-restriction
14393 (widen)
14394 (goto-char (point-min))
14395 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14396 res)))
14398 ;;;; Properties
14400 ;;; Setting and retrieving properties
14402 (defconst org-special-properties
14403 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14404 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14405 "The special properties valid in Org-mode.
14407 These are properties that are not defined in the property drawer,
14408 but in some other way.")
14410 (defconst org-default-properties
14411 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14412 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14413 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14414 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14415 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14416 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14417 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14418 "Some properties that are used by Org-mode for various purposes.
14419 Being in this list makes sure that they are offered for completion.")
14421 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14422 "Regular expression matching the first line of a property drawer.")
14424 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14425 "Regular expression matching the last line of a property drawer.")
14427 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14428 "Regular expression matching the first line of a property drawer.")
14430 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14431 "Regular expression matching the first line of a property drawer.")
14433 (defconst org-property-drawer-re
14434 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14435 org-property-end-re "\\)\n?")
14436 "Matches an entire property drawer.")
14438 (defconst org-clock-drawer-re
14439 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14440 org-property-end-re "\\)\n?")
14441 "Matches an entire clock drawer.")
14443 (defsubst org-re-property (property)
14444 "Return a regexp matching a PROPERTY line.
14445 Match group 1 will be set to the value."
14446 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14448 (defsubst org-re-property-keyword (property)
14449 "Return a regexp matching a PROPERTY line, possibly with no
14450 value for the property."
14451 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14453 (defun org-property-action ()
14454 "Do an action on properties."
14455 (interactive)
14456 (let (c)
14457 (org-at-property-p)
14458 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14459 (setq c (read-char-exclusive))
14460 (cond
14461 ((equal c ?s)
14462 (call-interactively 'org-set-property))
14463 ((equal c ?d)
14464 (call-interactively 'org-delete-property))
14465 ((equal c ?D)
14466 (call-interactively 'org-delete-property-globally))
14467 ((equal c ?c)
14468 (call-interactively 'org-compute-property-at-point))
14469 (t (error "No such property action %c" c)))))
14471 (defun org-inc-effort ()
14472 "Increment the value of the effort property in the current entry."
14473 (interactive)
14474 (org-set-effort nil t))
14476 (defun org-set-effort (&optional value increment)
14477 "Set the effort property of the current entry.
14478 With numerical prefix arg, use the nth allowed value, 0 stands for the
14479 10th allowed value.
14481 When INCREMENT is non-nil, set the property to the next allowed value."
14482 (interactive "P")
14483 (if (equal value 0) (setq value 10))
14484 (let* ((completion-ignore-case t)
14485 (prop org-effort-property)
14486 (cur (org-entry-get nil prop))
14487 (allowed (org-property-get-allowed-values nil prop 'table))
14488 (existing (mapcar 'list (org-property-values prop)))
14490 (val (cond
14491 ((stringp value) value)
14492 ((and allowed (integerp value))
14493 (or (car (nth (1- value) allowed))
14494 (car (org-last allowed))))
14495 ((and allowed increment)
14496 (or (caadr (member (list cur) allowed))
14497 (error "Allowed effort values are not set")))
14498 (allowed
14499 (message "Select 1-9,0, [RET%s]: %s"
14500 (if cur (concat "=" cur) "")
14501 (mapconcat 'car allowed " "))
14502 (setq rpl (read-char-exclusive))
14503 (if (equal rpl ?\r)
14505 (setq rpl (- rpl ?0))
14506 (if (equal rpl 0) (setq rpl 10))
14507 (if (and (> rpl 0) (<= rpl (length allowed)))
14508 (car (nth (1- rpl) allowed))
14509 (org-completing-read "Effort: " allowed nil))))
14511 (let (org-completion-use-ido org-completion-use-iswitchb)
14512 (org-completing-read
14513 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14514 (concat "[" cur "]") "")
14515 ": ")
14516 existing nil nil "" nil cur))))))
14517 (unless (equal (org-entry-get nil prop) val)
14518 (org-entry-put nil prop val))
14519 (message "%s is now %s" prop val)))
14521 (defun org-at-property-p ()
14522 "Is cursor inside a property drawer?"
14523 (save-excursion
14524 (beginning-of-line 1)
14525 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14526 (save-match-data ;; Used by calling procedures
14527 (let ((p (point))
14528 (range (unless (org-before-first-heading-p)
14529 (org-get-property-block))))
14530 (and range (<= (car range) p) (< p (cdr range))))))))
14532 (defun org-get-property-block (&optional beg end force)
14533 "Return the (beg . end) range of the body of the property drawer.
14534 BEG and END are the beginning and end of the current subtree, or of
14535 the part before the first headline. If they are not given, they will
14536 be found. If the drawer does not exist and FORCE is non-nil, create
14537 the drawer."
14538 (catch 'exit
14539 (save-excursion
14540 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14541 (progn (org-back-to-heading t) (point))))
14542 (end (or end (and (not (outline-next-heading)) (point-max))
14543 (point))))
14544 (goto-char beg)
14545 (if (re-search-forward org-property-start-re end t)
14546 (setq beg (1+ (match-end 0)))
14547 (if force
14548 (save-excursion
14549 (org-insert-property-drawer)
14550 (setq end (progn (outline-next-heading) (point))))
14551 (throw 'exit nil))
14552 (goto-char beg)
14553 (if (re-search-forward org-property-start-re end t)
14554 (setq beg (1+ (match-end 0)))))
14555 (if (re-search-forward org-property-end-re end t)
14556 (setq end (match-beginning 0))
14557 (or force (throw 'exit nil))
14558 (goto-char beg)
14559 (setq end beg)
14560 (org-indent-line)
14561 (insert ":END:\n"))
14562 (cons beg end)))))
14564 (defun org-entry-properties (&optional pom which specific)
14565 "Get all properties of the entry at point-or-marker POM.
14566 This includes the TODO keyword, the tags, time strings for deadline,
14567 scheduled, and clocking, and any additional properties defined in the
14568 entry. The return value is an alist, keys may occur multiple times
14569 if the property key was used several times.
14570 POM may also be nil, in which case the current entry is used.
14571 If WHICH is nil or `all', get all properties. If WHICH is
14572 `special' or `standard', only get that subclass. If WHICH
14573 is a string only get exactly this property. SPECIFIC can be a string, the
14574 specific property we are interested in. Specifying it can speed
14575 things up because then unnecessary parsing is avoided."
14576 (setq which (or which 'all))
14577 (org-with-point-at pom
14578 (let ((clockstr (substring org-clock-string 0 -1))
14579 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14580 (case-fold-search nil)
14581 beg end range props sum-props key key1 value string clocksum clocksumt)
14582 (save-excursion
14583 (when (condition-case nil
14584 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14585 (error nil))
14586 (setq beg (point))
14587 (setq sum-props (get-text-property (point) 'org-summaries))
14588 (setq clocksum (get-text-property (point) :org-clock-minutes)
14589 clocksumt (get-text-property (point) :org-clock-minutes-today))
14590 (outline-next-heading)
14591 (setq end (point))
14592 (when (memq which '(all special))
14593 ;; Get the special properties, like TODO and tags
14594 (goto-char beg)
14595 (when (and (or (not specific) (string= specific "TODO"))
14596 (looking-at org-todo-line-regexp) (match-end 2))
14597 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14598 (when (and (or (not specific) (string= specific "PRIORITY"))
14599 (looking-at org-priority-regexp))
14600 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14601 (when (or (not specific) (string= specific "FILE"))
14602 (push (cons "FILE" buffer-file-name) props))
14603 (when (and (or (not specific) (string= specific "TAGS"))
14604 (setq value (org-get-tags-string))
14605 (string-match "\\S-" value))
14606 (push (cons "TAGS" value) props))
14607 (when (and (or (not specific) (string= specific "ALLTAGS"))
14608 (setq value (org-get-tags-at)))
14609 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14610 ":"))
14611 props))
14612 (when (or (not specific) (string= specific "BLOCKED"))
14613 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14614 (when (or (not specific)
14615 (member specific
14616 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14617 "TIMESTAMP" "TIMESTAMP_IA")))
14618 (catch 'match
14619 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14620 (setq key (if (match-end 1)
14621 (substring (org-match-string-no-properties 1)
14622 0 -1))
14623 string (if (equal key clockstr)
14624 (org-trim
14625 (buffer-substring-no-properties
14626 (match-beginning 3) (goto-char
14627 (point-at-eol))))
14628 (substring (org-match-string-no-properties 3)
14629 1 -1)))
14630 ;; Get the correct property name from the key. This is
14631 ;; necessary if the user has configured time keywords.
14632 (setq key1 (concat key ":"))
14633 (cond
14634 ((not key)
14635 (setq key
14636 (if (= (char-after (match-beginning 3)) ?\[)
14637 "TIMESTAMP_IA" "TIMESTAMP")))
14638 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14639 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14640 ((equal key1 org-closed-string) (setq key "CLOSED"))
14641 ((equal key1 org-clock-string) (setq key "CLOCK")))
14642 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14643 (progn
14644 (push (cons key string) props)
14645 ;; no need to search further if match is found
14646 (throw 'match t))
14647 (when (or (equal key "CLOCK") (not (assoc key props)))
14648 (push (cons key string) props)))))))
14650 (when (memq which '(all standard))
14651 ;; Get the standard properties, like :PROP: ...
14652 (setq range (org-get-property-block beg end))
14653 (when range
14654 (goto-char (car range))
14655 (while (re-search-forward
14656 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14657 (cdr range) t)
14658 (setq key (org-match-string-no-properties 1)
14659 value (org-trim (or (org-match-string-no-properties 2) "")))
14660 (unless (member key excluded)
14661 (push (cons key (or value "")) props)))))
14662 (if clocksum
14663 (push (cons "CLOCKSUM"
14664 (org-columns-number-to-string (/ (float clocksum) 60.)
14665 'add_times))
14666 props))
14667 (if clocksumt
14668 (push (cons "CLOCKSUM_T"
14669 (org-columns-number-to-string (/ (float clocksumt) 60.)
14670 'add_times))
14671 props))
14672 (unless (assoc "CATEGORY" props)
14673 (push (cons "CATEGORY" (org-get-category)) props))
14674 (append sum-props (nreverse props)))))))
14676 (defun org-entry-get (pom property &optional inherit literal-nil)
14677 "Get value of PROPERTY for entry or content at point-or-marker POM.
14678 If INHERIT is non-nil and the entry does not have the property,
14679 then also check higher levels of the hierarchy.
14680 If INHERIT is the symbol `selective', use inheritance only if the setting
14681 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14682 If the property is present but empty, the return value is the empty string.
14683 If the property is not present at all, nil is returned.
14685 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14686 do not interpret it as the list atom nil. This is used for inheritance
14687 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14688 (org-with-point-at pom
14689 (if (and inherit (if (eq inherit 'selective)
14690 (org-property-inherit-p property)
14692 (org-entry-get-with-inheritance property literal-nil)
14693 (if (member property org-special-properties)
14694 ;; We need a special property. Use `org-entry-properties' to
14695 ;; retrieve it, but specify the wanted property
14696 (cdr (assoc property (org-entry-properties nil 'special property)))
14697 (let* ((range (org-get-property-block))
14698 (props (list (or (assoc property org-file-properties)
14699 (assoc property org-global-properties)
14700 (assoc property org-global-properties-fixed))))
14701 (ap (lambda (key)
14702 (when (re-search-forward
14703 (org-re-property key) (cdr range) t)
14704 (setq props
14705 (org-update-property-plist
14707 (if (match-end 1)
14708 (org-match-string-no-properties 1) "")
14709 props)))))
14710 val)
14711 (when (and range (goto-char (car range)))
14712 (funcall ap property)
14713 (goto-char (car range))
14714 (while (funcall ap (concat property "+")))
14715 (setq val (cdr (assoc property props)))
14716 (when val (if literal-nil val (org-not-nil val)))))))))
14718 (defun org-property-or-variable-value (var &optional inherit)
14719 "Check if there is a property fixing the value of VAR.
14720 If yes, return this value. If not, return the current value of the variable."
14721 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14722 (if (and prop (stringp prop) (string-match "\\S-" prop))
14723 (read prop)
14724 (symbol-value var))))
14726 (defun org-entry-delete (pom property)
14727 "Delete the property PROPERTY from entry at point-or-marker POM."
14728 (org-with-point-at pom
14729 (if (member property org-special-properties)
14730 nil ; cannot delete these properties.
14731 (let ((range (org-get-property-block)))
14732 (if (and range
14733 (goto-char (car range))
14734 (re-search-forward
14735 (org-re-property property)
14736 (cdr range) t))
14737 (progn
14738 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14740 nil)))))
14742 ;; Multi-values properties are properties that contain multiple values
14743 ;; These values are assumed to be single words, separated by whitespace.
14744 (defun org-entry-add-to-multivalued-property (pom property value)
14745 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14746 (let* ((old (org-entry-get pom property))
14747 (values (and old (org-split-string old "[ \t]"))))
14748 (setq value (org-entry-protect-space value))
14749 (unless (member value values)
14750 (setq values (cons value values))
14751 (org-entry-put pom property
14752 (mapconcat 'identity values " ")))))
14754 (defun org-entry-remove-from-multivalued-property (pom property value)
14755 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14756 (let* ((old (org-entry-get pom property))
14757 (values (and old (org-split-string old "[ \t]"))))
14758 (setq value (org-entry-protect-space value))
14759 (when (member value values)
14760 (setq values (delete value values))
14761 (org-entry-put pom property
14762 (mapconcat 'identity values " ")))))
14764 (defun org-entry-member-in-multivalued-property (pom property value)
14765 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14766 (let* ((old (org-entry-get pom property))
14767 (values (and old (org-split-string old "[ \t]"))))
14768 (setq value (org-entry-protect-space value))
14769 (member value values)))
14771 (defun org-entry-get-multivalued-property (pom property)
14772 "Return a list of values in a multivalued property."
14773 (let* ((value (org-entry-get pom property))
14774 (values (and value (org-split-string value "[ \t]"))))
14775 (mapcar 'org-entry-restore-space values)))
14777 (defun org-entry-put-multivalued-property (pom property &rest values)
14778 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14779 VALUES should be a list of strings. Spaces will be protected."
14780 (org-entry-put pom property
14781 (mapconcat 'org-entry-protect-space values " "))
14782 (let* ((value (org-entry-get pom property))
14783 (values (and value (org-split-string value "[ \t]"))))
14784 (mapcar 'org-entry-restore-space values)))
14786 (defun org-entry-protect-space (s)
14787 "Protect spaces and newline in string S."
14788 (while (string-match " " s)
14789 (setq s (replace-match "%20" t t s)))
14790 (while (string-match "\n" s)
14791 (setq s (replace-match "%0A" t t s)))
14794 (defun org-entry-restore-space (s)
14795 "Restore spaces and newline in string S."
14796 (while (string-match "%20" s)
14797 (setq s (replace-match " " t t s)))
14798 (while (string-match "%0A" s)
14799 (setq s (replace-match "\n" t t s)))
14802 (defvar org-entry-property-inherited-from (make-marker)
14803 "Marker pointing to the entry from where a property was inherited.
14804 Each call to `org-entry-get-with-inheritance' will set this marker to the
14805 location of the entry where the inheritance search matched. If there was
14806 no match, the marker will point nowhere.
14807 Note that also `org-entry-get' calls this function, if the INHERIT flag
14808 is set.")
14810 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14811 "Get PROPERTY of entry or content at point, search higher levels if needed.
14812 The search will stop at the first ancestor which has the property defined.
14813 If the value found is \"nil\", return nil to show that the property
14814 should be considered as undefined (this is the meaning of nil here).
14815 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14816 (move-marker org-entry-property-inherited-from nil)
14817 (let (tmp)
14818 (save-excursion
14819 (save-restriction
14820 (widen)
14821 (catch 'ex
14822 (while t
14823 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14824 (or (ignore-errors (org-back-to-heading t))
14825 (goto-char (point-min)))
14826 (move-marker org-entry-property-inherited-from (point))
14827 (throw 'ex tmp))
14828 (or (ignore-errors (org-up-heading-safe))
14829 (throw 'ex nil))))))
14830 (setq tmp (or tmp
14831 (cdr (assoc property org-file-properties))
14832 (cdr (assoc property org-global-properties))
14833 (cdr (assoc property org-global-properties-fixed))))
14834 (if literal-nil tmp (org-not-nil tmp))))
14836 (defvar org-property-changed-functions nil
14837 "Hook called when the value of a property has changed.
14838 Each hook function should accept two arguments, the name of the property
14839 and the new value.")
14841 (defun org-entry-put (pom property value)
14842 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14843 (org-with-point-at pom
14844 (org-back-to-heading t)
14845 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14846 range)
14847 (cond
14848 ((equal property "TODO")
14849 (when (and (stringp value) (string-match "\\S-" value)
14850 (not (member value org-todo-keywords-1)))
14851 (error "\"%s\" is not a valid TODO state" value))
14852 (if (or (not value)
14853 (not (string-match "\\S-" value)))
14854 (setq value 'none))
14855 (org-todo value)
14856 (org-set-tags nil 'align))
14857 ((equal property "PRIORITY")
14858 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14859 (string-to-char value) ?\ ))
14860 (org-set-tags nil 'align))
14861 ((equal property "CLOCKSUM")
14862 (if (not (re-search-forward
14863 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14864 (error "Cannot find a clock log")
14865 (goto-char (- (match-end 1) 2))
14866 (cond
14867 ((eq value 'earlier) (org-timestamp-down))
14868 ((eq value 'later) (org-timestamp-up)))
14869 (org-clock-sum-current-item)))
14870 ((equal property "SCHEDULED")
14871 (if (re-search-forward org-scheduled-time-regexp end t)
14872 (cond
14873 ((eq value 'earlier) (org-timestamp-change -1 'day))
14874 ((eq value 'later) (org-timestamp-change 1 'day))
14875 (t (call-interactively 'org-schedule)))
14876 (call-interactively 'org-schedule)))
14877 ((equal property "DEADLINE")
14878 (if (re-search-forward org-deadline-time-regexp end t)
14879 (cond
14880 ((eq value 'earlier) (org-timestamp-change -1 'day))
14881 ((eq value 'later) (org-timestamp-change 1 'day))
14882 (t (call-interactively 'org-deadline)))
14883 (call-interactively 'org-deadline)))
14884 ((member property org-special-properties)
14885 (error "The %s property can not yet be set with `org-entry-put'"
14886 property))
14887 (t ; a non-special property
14888 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14889 (setq range (org-get-property-block beg end 'force))
14890 (goto-char (car range))
14891 (if (re-search-forward
14892 (org-re-property-keyword property) (cdr range) t)
14893 (progn
14894 (delete-region (match-beginning 0) (match-end 0))
14895 (goto-char (match-beginning 0)))
14896 (goto-char (cdr range))
14897 (insert "\n")
14898 (backward-char 1)
14899 (org-indent-line))
14900 (insert ":" property ":")
14901 (and value (insert " " value))
14902 (org-indent-line)))))
14903 (run-hook-with-args 'org-property-changed-functions property value)))
14905 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14906 "Get all property keys in the current buffer.
14907 With INCLUDE-SPECIALS, also list the special properties that reflect things
14908 like tags and TODO state.
14909 With INCLUDE-DEFAULTS, also include properties that has special meaning
14910 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14911 and others.
14912 With INCLUDE-COLUMNS, also include property names given in COLUMN
14913 formats in the current buffer."
14914 (let (rtn range cfmt s p)
14915 (save-excursion
14916 (save-restriction
14917 (widen)
14918 (goto-char (point-min))
14919 (while (re-search-forward org-property-start-re nil t)
14920 (setq range (org-get-property-block))
14921 (goto-char (car range))
14922 (while (re-search-forward
14923 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14924 (cdr range) t)
14925 (add-to-list 'rtn (org-match-string-no-properties 1)))
14926 (outline-next-heading))))
14928 (when include-specials
14929 (setq rtn (append org-special-properties rtn)))
14931 (when include-defaults
14932 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14933 (add-to-list 'rtn org-effort-property))
14935 (when include-columns
14936 (save-excursion
14937 (save-restriction
14938 (widen)
14939 (goto-char (point-min))
14940 (while (re-search-forward
14941 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14942 nil t)
14943 (setq cfmt (match-string 2) s 0)
14944 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14945 cfmt s)
14946 (setq s (match-end 0)
14947 p (match-string 1 cfmt))
14948 (unless (or (equal p "ITEM")
14949 (member p org-special-properties))
14950 (add-to-list 'rtn (match-string 1 cfmt))))))))
14952 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14954 (defun org-property-values (key)
14955 "Return a list of all values of property KEY in the current buffer."
14956 (save-excursion
14957 (save-restriction
14958 (widen)
14959 (goto-char (point-min))
14960 (let ((re (org-re-property key))
14961 values)
14962 (while (re-search-forward re nil t)
14963 (add-to-list 'values (org-trim (match-string 1))))
14964 (delete "" values)))))
14966 (defun org-insert-property-drawer ()
14967 "Insert a property drawer into the current entry."
14968 (org-back-to-heading t)
14969 (looking-at org-outline-regexp)
14970 (let ((indent (if org-adapt-indentation
14971 (- (match-end 0) (match-beginning 0))
14973 (beg (point))
14974 (re (concat "^[ \t]*" org-keyword-time-regexp))
14975 end hiddenp)
14976 (outline-next-heading)
14977 (setq end (point))
14978 (goto-char beg)
14979 (while (re-search-forward re end t))
14980 (setq hiddenp (outline-invisible-p))
14981 (end-of-line 1)
14982 (and (equal (char-after) ?\n) (forward-char 1))
14983 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14984 (if (member (match-string 1) '("CLOCK:" ":END:"))
14985 ;; just skip this line
14986 (beginning-of-line 2)
14987 ;; Drawer start, find the end
14988 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14989 (beginning-of-line 1)))
14990 (org-skip-over-state-notes)
14991 (skip-chars-backward " \t\n\r")
14992 (if (eq (char-before) ?*) (forward-char 1))
14993 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14994 (beginning-of-line 0)
14995 (org-indent-to-column indent)
14996 (beginning-of-line 2)
14997 (org-indent-to-column indent)
14998 (beginning-of-line 0)
14999 (if hiddenp
15000 (save-excursion
15001 (org-back-to-heading t)
15002 (hide-entry))
15003 (org-flag-drawer t))))
15005 (defun org-insert-drawer (&optional arg drawer)
15006 "Insert a drawer at point.
15008 Optional argument DRAWER, when non-nil, is a string representing
15009 drawer's name. Otherwise, the user is prompted for a name.
15011 If a region is active, insert the drawer around that region
15012 instead.
15014 Point is left between drawer's boundaries."
15015 (interactive "P")
15016 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15017 "LOGBOOK"))
15018 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15019 ;; internally by Org. They are meant to be inserted
15020 ;; automatically.
15021 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15022 ;; Remove system drawers from list. Note: For some reason,
15023 ;; `org-completing-read' ignores the predicate while
15024 ;; `completing-read' handles it fine.
15025 (drawer (if arg "PROPERTIES"
15026 (or drawer
15027 (completing-read
15028 "Drawer: " org-drawers
15029 (lambda (d) (not (member d system-drawers))))))))
15030 (cond
15031 ;; With C-u, fall back on `org-insert-property-drawer'
15032 (arg (org-insert-property-drawer))
15033 ;; With an active region, insert a drawer at point.
15034 ((not (org-region-active-p))
15035 (progn
15036 (unless (bolp) (insert "\n"))
15037 (insert (format ":%s:\n\n:END:\n" drawer))
15038 (forward-line -2)))
15039 ;; Otherwise, insert the drawer at point
15041 (let ((rbeg (region-beginning))
15042 (rend (copy-marker (region-end))))
15043 (unwind-protect
15044 (progn
15045 (goto-char rbeg)
15046 (beginning-of-line)
15047 (when (save-excursion
15048 (re-search-forward org-outline-regexp-bol rend t))
15049 (error "Drawers cannot contain headlines"))
15050 ;; Position point at the beginning of the first
15051 ;; non-blank line in region. Insert drawer's opening
15052 ;; there, then indent it.
15053 (org-skip-whitespace)
15054 (beginning-of-line)
15055 (insert ":" drawer ":\n")
15056 (forward-line -1)
15057 (indent-for-tab-command)
15058 ;; Move point to the beginning of the first blank line
15059 ;; after the last non-blank line in region. Insert
15060 ;; drawer's closing, then indent it.
15061 (goto-char rend)
15062 (skip-chars-backward " \r\t\n")
15063 (insert "\n:END:")
15064 (deactivate-mark t)
15065 (indent-for-tab-command)
15066 (unless (eolp) (insert "\n")))
15067 ;; Clear marker, whatever the outcome of insertion is.
15068 (set-marker rend nil)))))))
15070 (defvar org-property-set-functions-alist nil
15071 "Property set function alist.
15072 Each entry should have the following format:
15074 (PROPERTY . READ-FUNCTION)
15076 The read function will be called with the same argument as
15077 `org-completing-read'.")
15079 (defun org-set-property-function (property)
15080 "Get the function that should be used to set PROPERTY.
15081 This is computed according to `org-property-set-functions-alist'."
15082 (or (cdr (assoc property org-property-set-functions-alist))
15083 'org-completing-read))
15085 (defun org-read-property-value (property)
15086 "Read PROPERTY value from user."
15087 (let* ((completion-ignore-case t)
15088 (allowed (org-property-get-allowed-values nil property 'table))
15089 (cur (org-entry-get nil property))
15090 (prompt (concat property " value"
15091 (if (and cur (string-match "\\S-" cur))
15092 (concat " [" cur "]") "") ": "))
15093 (set-function (org-set-property-function property))
15094 (val (if allowed
15095 (funcall set-function prompt allowed nil
15096 (not (get-text-property 0 'org-unrestricted
15097 (caar allowed))))
15098 (let (org-completion-use-ido org-completion-use-iswitchb)
15099 (funcall set-function prompt
15100 (mapcar 'list (org-property-values property))
15101 nil nil "" nil cur)))))
15102 (if (equal val "")
15104 val)))
15106 (defvar org-last-set-property nil)
15107 (defvar org-last-set-property-value nil)
15108 (defun org-read-property-name ()
15109 "Read a property name."
15110 (let* ((completion-ignore-case t)
15111 (keys (org-buffer-property-keys nil t t))
15112 (default-prop (or (save-excursion
15113 (save-match-data
15114 (beginning-of-line)
15115 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15116 (null (string= (match-string 1) "END"))
15117 (match-string 1))))
15118 org-last-set-property))
15119 (property (org-icompleting-read
15120 (concat "Property"
15121 (if default-prop (concat " [" default-prop "]") "")
15122 ": ")
15123 (mapcar 'list keys)
15124 nil nil nil nil
15125 default-prop)))
15126 (if (member property keys)
15127 property
15128 (or (cdr (assoc (downcase property)
15129 (mapcar (lambda (x) (cons (downcase x) x))
15130 keys)))
15131 property))))
15133 (defun org-set-property-and-value (use-last)
15134 "Allow to set [PROPERTY]: [value] direction from prompt.
15135 When use-default, don't even ask, just use the last
15136 \"[PROPERTY]: [value]\" string from the history."
15137 (interactive "P")
15138 (let* ((completion-ignore-case t)
15139 (pv (or (and use-last org-last-set-property-value)
15140 (org-completing-read
15141 "Enter a \"[Property]: [value]\" pair: "
15142 nil nil nil nil nil
15143 org-last-set-property-value)))
15144 prop val)
15145 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15146 (setq prop (match-string 1 pv)
15147 val (match-string 2 pv))
15148 (org-set-property prop val))))
15150 (defun org-set-property (property value)
15151 "In the current entry, set PROPERTY to VALUE.
15152 When called interactively, this will prompt for a property name, offering
15153 completion on existing and default properties. And then it will prompt
15154 for a value, offering completion either on allowed values (via an inherited
15155 xxx_ALL property) or on existing values in other instances of this property
15156 in the current file."
15157 (interactive (list nil nil))
15158 (let* ((property (or property (org-read-property-name)))
15159 (value (or value (org-read-property-value property)))
15160 (fn (cdr (assoc property org-properties-postprocess-alist))))
15161 (setq org-last-set-property property)
15162 (setq org-last-set-property-value (concat property ": " value))
15163 ;; Possibly postprocess the inserted value:
15164 (when fn (setq value (funcall fn value)))
15165 (unless (equal (org-entry-get nil property) value)
15166 (org-entry-put nil property value))))
15168 (defun org-delete-property (property)
15169 "In the current entry, delete PROPERTY."
15170 (interactive
15171 (let* ((completion-ignore-case t)
15172 (prop (org-icompleting-read "Property: "
15173 (org-entry-properties nil 'standard))))
15174 (list prop)))
15175 (message "Property %s %s" property
15176 (if (org-entry-delete nil property)
15177 "deleted"
15178 "was not present in the entry")))
15180 (defun org-delete-property-globally (property)
15181 "Remove PROPERTY globally, from all entries."
15182 (interactive
15183 (let* ((completion-ignore-case t)
15184 (prop (org-icompleting-read
15185 "Globally remove property: "
15186 (mapcar 'list (org-buffer-property-keys)))))
15187 (list prop)))
15188 (save-excursion
15189 (save-restriction
15190 (widen)
15191 (goto-char (point-min))
15192 (let ((cnt 0))
15193 (while (re-search-forward
15194 (org-re-property property)
15195 nil t)
15196 (setq cnt (1+ cnt))
15197 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15198 (message "Property \"%s\" removed from %d entries" property cnt)))))
15200 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15202 (defun org-compute-property-at-point ()
15203 "Compute the property at point.
15204 This looks for an enclosing column format, extracts the operator and
15205 then applies it to the property in the column format's scope."
15206 (interactive)
15207 (unless (org-at-property-p)
15208 (error "Not at a property"))
15209 (let ((prop (org-match-string-no-properties 2)))
15210 (org-columns-get-format-and-top-level)
15211 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15212 (error "No operator defined for property %s" prop))
15213 (org-columns-compute prop)))
15215 (defvar org-property-allowed-value-functions nil
15216 "Hook for functions supplying allowed values for a specific property.
15217 The functions must take a single argument, the name of the property, and
15218 return a flat list of allowed values. If \":ETC\" is one of
15219 the values, this means that these values are intended as defaults for
15220 completion, but that other values should be allowed too.
15221 The functions must return nil if they are not responsible for this
15222 property.")
15224 (defun org-property-get-allowed-values (pom property &optional table)
15225 "Get allowed values for the property PROPERTY.
15226 When TABLE is non-nil, return an alist that can directly be used for
15227 completion."
15228 (let (vals)
15229 (cond
15230 ((equal property "TODO")
15231 (setq vals (org-with-point-at pom
15232 (append org-todo-keywords-1 '("")))))
15233 ((equal property "PRIORITY")
15234 (let ((n org-lowest-priority))
15235 (while (>= n org-highest-priority)
15236 (push (char-to-string n) vals)
15237 (setq n (1- n)))))
15238 ((member property org-special-properties))
15239 ((setq vals (run-hook-with-args-until-success
15240 'org-property-allowed-value-functions property)))
15242 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15243 (when (and vals (string-match "\\S-" vals))
15244 (setq vals (car (read-from-string (concat "(" vals ")"))))
15245 (setq vals (mapcar (lambda (x)
15246 (cond ((stringp x) x)
15247 ((numberp x) (number-to-string x))
15248 ((symbolp x) (symbol-name x))
15249 (t "???")))
15250 vals)))))
15251 (when (member ":ETC" vals)
15252 (setq vals (remove ":ETC" vals))
15253 (org-add-props (car vals) '(org-unrestricted t)))
15254 (if table (mapcar 'list vals) vals)))
15256 (defun org-property-previous-allowed-value (&optional previous)
15257 "Switch to the next allowed value for this property."
15258 (interactive)
15259 (org-property-next-allowed-value t))
15261 (defun org-property-next-allowed-value (&optional previous)
15262 "Switch to the next allowed value for this property."
15263 (interactive)
15264 (unless (org-at-property-p)
15265 (error "Not at a property"))
15266 (let* ((key (match-string 2))
15267 (value (match-string 3))
15268 (allowed (or (org-property-get-allowed-values (point) key)
15269 (and (member value '("[ ]" "[-]" "[X]"))
15270 '("[ ]" "[X]"))))
15271 nval)
15272 (unless allowed
15273 (error "Allowed values for this property have not been defined"))
15274 (if previous (setq allowed (reverse allowed)))
15275 (if (member value allowed)
15276 (setq nval (car (cdr (member value allowed)))))
15277 (setq nval (or nval (car allowed)))
15278 (if (equal nval value)
15279 (error "Only one allowed value for this property"))
15280 (org-at-property-p)
15281 (replace-match (concat " :" key ": " nval) t t)
15282 (org-indent-line)
15283 (beginning-of-line 1)
15284 (skip-chars-forward " \t")
15285 (run-hook-with-args 'org-property-changed-functions key nval)))
15287 (defun org-find-olp (path &optional this-buffer)
15288 "Return a marker pointing to the entry at outline path OLP.
15289 If anything goes wrong, throw an error.
15290 You can wrap this call to catch the error like this:
15292 (condition-case msg
15293 (org-mobile-locate-entry (match-string 4))
15294 (error (nth 1 msg)))
15296 The return value will then be either a string with the error message,
15297 or a marker if everything is OK.
15299 If THIS-BUFFER is set, the outline path does not contain a file,
15300 only headings."
15301 (let* ((file (if this-buffer buffer-file-name (pop path)))
15302 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15303 (level 1)
15304 (lmin 1)
15305 (lmax 1)
15306 limit re end found pos heading cnt flevel)
15307 (unless buffer (error "File not found :%s" file))
15308 (with-current-buffer buffer
15309 (save-excursion
15310 (save-restriction
15311 (widen)
15312 (setq limit (point-max))
15313 (goto-char (point-min))
15314 (while (setq heading (pop path))
15315 (setq re (format org-complex-heading-regexp-format
15316 (regexp-quote heading)))
15317 (setq cnt 0 pos (point))
15318 (while (re-search-forward re end t)
15319 (setq level (- (match-end 1) (match-beginning 1)))
15320 (if (and (>= level lmin) (<= level lmax))
15321 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15322 (when (= cnt 0) (error "Heading not found on level %d: %s"
15323 lmax heading))
15324 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15325 lmax heading))
15326 (goto-char found)
15327 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15328 (setq end (save-excursion (org-end-of-subtree t t))))
15329 (when (org-at-heading-p)
15330 (point-marker)))))))
15332 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15333 "Find node HEADING in BUFFER.
15334 Return a marker to the heading if it was found, or nil if not.
15335 If POS-ONLY is set, return just the position instead of a marker.
15337 The heading text must match exact, but it may have a TODO keyword,
15338 a priority cookie and tags in the standard locations."
15339 (with-current-buffer (or buffer (current-buffer))
15340 (save-excursion
15341 (save-restriction
15342 (widen)
15343 (goto-char (point-min))
15344 (let (case-fold-search)
15345 (if (re-search-forward
15346 (format org-complex-heading-regexp-format
15347 (regexp-quote heading)) nil t)
15348 (if pos-only
15349 (match-beginning 0)
15350 (move-marker (make-marker) (match-beginning 0)))))))))
15352 (defun org-find-exact-heading-in-directory (heading &optional dir)
15353 "Find Org node headline HEADING in all .org files in directory DIR.
15354 When the target headline is found, return a marker to this location."
15355 (let ((files (directory-files (or dir default-directory)
15356 nil "\\`[^.#].*\\.org\\'"))
15357 file visiting m buffer)
15358 (catch 'found
15359 (while (setq file (pop files))
15360 (message "trying %s" file)
15361 (setq visiting (org-find-base-buffer-visiting file))
15362 (setq buffer (or visiting (find-file-noselect file)))
15363 (setq m (org-find-exact-headline-in-buffer
15364 heading buffer))
15365 (when (and (not m) (not visiting)) (kill-buffer buffer))
15366 (and m (throw 'found m))))))
15368 (defun org-find-entry-with-id (ident)
15369 "Locate the entry that contains the ID property with exact value IDENT.
15370 IDENT can be a string, a symbol or a number, this function will search for
15371 the string representation of it.
15372 Return the position where this entry starts, or nil if there is no such entry."
15373 (interactive "sID: ")
15374 (let ((id (cond
15375 ((stringp ident) ident)
15376 ((symbol-name ident) (symbol-name ident))
15377 ((numberp ident) (number-to-string ident))
15378 (t (error "IDENT %s must be a string, symbol or number" ident))))
15379 (case-fold-search nil))
15380 (save-excursion
15381 (save-restriction
15382 (widen)
15383 (goto-char (point-min))
15384 (when (re-search-forward
15385 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15386 nil t)
15387 (org-back-to-heading t)
15388 (point))))))
15390 ;;;; Timestamps
15392 (defvar org-last-changed-timestamp nil)
15393 (defvar org-last-inserted-timestamp nil
15394 "The last time stamp inserted with `org-insert-time-stamp'.")
15395 (defvar org-time-was-given) ; dynamically scoped parameter
15396 (defvar org-end-time-was-given) ; dynamically scoped parameter
15397 (defvar org-ts-what) ; dynamically scoped parameter
15399 (defun org-time-stamp (arg &optional inactive)
15400 "Prompt for a date/time and insert a time stamp.
15401 If the user specifies a time like HH:MM or if this command is
15402 called with at least one prefix argument, the time stamp contains
15403 the date and the time. Otherwise, only the date is be included.
15405 All parts of a date not specified by the user is filled in from
15406 the current date/time. So if you just press return without
15407 typing anything, the time stamp will represent the current
15408 date/time.
15410 If there is already a timestamp at the cursor, it will be
15411 modified.
15413 With two universal prefix arguments, insert an active timestamp
15414 with the current time without prompting the user."
15415 (interactive "P")
15416 (let* ((ts nil)
15417 (default-time
15418 ;; Default time is either today, or, when entering a range,
15419 ;; the range start.
15420 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15421 (save-excursion
15422 (re-search-backward
15423 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15424 (- (point) 20) t)))
15425 (apply 'encode-time (org-parse-time-string (match-string 1)))
15426 (current-time)))
15427 (default-input (and ts (org-get-compact-tod ts)))
15428 (repeater (save-excursion
15429 (save-match-data
15430 (beginning-of-line)
15431 (when (re-search-forward
15432 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15433 (save-excursion (progn (end-of-line) (point))) t)
15434 (match-string 0)))))
15435 org-time-was-given org-end-time-was-given time)
15436 (cond
15437 ((and (org-at-timestamp-p t)
15438 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15439 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15440 (insert "--")
15441 (setq time (let ((this-command this-command))
15442 (org-read-date arg 'totime nil nil
15443 default-time default-input inactive)))
15444 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15445 ((org-at-timestamp-p t)
15446 (setq time (let ((this-command this-command))
15447 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15448 (when (org-at-timestamp-p t) ; just to get the match data
15449 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15450 (replace-match "")
15451 (setq org-last-changed-timestamp
15452 (org-insert-time-stamp
15453 time (or org-time-was-given arg)
15454 inactive nil nil (list org-end-time-was-given)))
15455 (when repeater (goto-char (1- (point))) (insert " " repeater)
15456 (setq org-last-changed-timestamp
15457 (concat (substring org-last-inserted-timestamp 0 -1)
15458 " " repeater ">"))))
15459 (message "Timestamp updated"))
15460 ((equal arg '(16))
15461 (org-insert-time-stamp (current-time) t))
15463 (setq time (let ((this-command this-command))
15464 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15465 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15466 nil nil (list org-end-time-was-given))))))
15468 ;; FIXME: can we use this for something else, like computing time differences?
15469 (defun org-get-compact-tod (s)
15470 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15471 (let* ((t1 (match-string 1 s))
15472 (h1 (string-to-number (match-string 2 s)))
15473 (m1 (string-to-number (match-string 3 s)))
15474 (t2 (and (match-end 4) (match-string 5 s)))
15475 (h2 (and t2 (string-to-number (match-string 6 s))))
15476 (m2 (and t2 (string-to-number (match-string 7 s))))
15477 dh dm)
15478 (if (not t2)
15480 (setq dh (- h2 h1) dm (- m2 m1))
15481 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15482 (concat t1 "+" (number-to-string dh)
15483 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15485 (defun org-time-stamp-inactive (&optional arg)
15486 "Insert an inactive time stamp.
15487 An inactive time stamp is enclosed in square brackets instead of angle
15488 brackets. It is inactive in the sense that it does not trigger agenda entries,
15489 does not link to the calendar and cannot be changed with the S-cursor keys.
15490 So these are more for recording a certain time/date."
15491 (interactive "P")
15492 (org-time-stamp arg 'inactive))
15494 (defvar org-date-ovl (make-overlay 1 1))
15495 (overlay-put org-date-ovl 'face 'org-date-selected)
15496 (org-detach-overlay org-date-ovl)
15498 (defvar org-ans1) ; dynamically scoped parameter
15499 (defvar org-ans2) ; dynamically scoped parameter
15501 (defvar org-plain-time-of-day-regexp) ; defined below
15503 (defvar org-overriding-default-time nil) ; dynamically scoped
15504 (defvar org-read-date-overlay nil)
15505 (defvar org-dcst nil) ; dynamically scoped
15506 (defvar org-read-date-history nil)
15507 (defvar org-read-date-final-answer nil)
15508 (defvar org-read-date-analyze-futurep nil)
15509 (defvar org-read-date-analyze-forced-year nil)
15510 (defvar org-read-date-inactive)
15512 (defun org-read-date (&optional org-with-time to-time from-string prompt
15513 default-time default-input inactive)
15514 "Read a date, possibly a time, and make things smooth for the user.
15515 The prompt will suggest to enter an ISO date, but you can also enter anything
15516 which will at least partially be understood by `parse-time-string'.
15517 Unrecognized parts of the date will default to the current day, month, year,
15518 hour and minute. If this command is called to replace a timestamp at point,
15519 or to enter the second timestamp of a range, the default time is taken
15520 from the existing stamp. Furthermore, the command prefers the future,
15521 so if you are giving a date where the year is not given, and the day-month
15522 combination is already past in the current year, it will assume you
15523 mean next year. For details, see the manual. A few examples:
15525 3-2-5 --> 2003-02-05
15526 feb 15 --> currentyear-02-15
15527 2/15 --> currentyear-02-15
15528 sep 12 9 --> 2009-09-12
15529 12:45 --> today 12:45
15530 22 sept 0:34 --> currentyear-09-22 0:34
15531 12 --> currentyear-currentmonth-12
15532 Fri --> nearest Friday (today or later)
15533 etc.
15535 Furthermore you can specify a relative date by giving, as the *first* thing
15536 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15537 change in days weeks, months, years.
15538 With a single plus or minus, the date is relative to today. With a double
15539 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15540 +4d --> four days from today
15541 +4 --> same as above
15542 +2w --> two weeks from today
15543 ++5 --> five days from default date
15545 The function understands only English month and weekday abbreviations.
15547 While prompting, a calendar is popped up - you can also select the
15548 date with the mouse (button 1). The calendar shows a period of three
15549 months. To scroll it to other months, use the keys `>' and `<'.
15550 If you don't like the calendar, turn it off with
15551 \(setq org-read-date-popup-calendar nil)
15553 With optional argument TO-TIME, the date will immediately be converted
15554 to an internal time.
15555 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15556 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15557 still enter a time, and this function will inform the calling routine
15558 about this change. The calling routine may then choose to change the
15559 format used to insert the time stamp into the buffer to include the time.
15560 With optional argument FROM-STRING, read from this string instead from
15561 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15562 the time/date that is used for everything that is not specified by the
15563 user."
15564 (require 'parse-time)
15565 (let* ((org-time-stamp-rounding-minutes
15566 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15567 (org-dcst org-display-custom-times)
15568 (ct (org-current-time))
15569 (org-def (or org-overriding-default-time default-time ct))
15570 (org-defdecode (decode-time org-def))
15571 (dummy (progn
15572 (when (< (nth 2 org-defdecode) org-extend-today-until)
15573 (setcar (nthcdr 2 org-defdecode) -1)
15574 (setcar (nthcdr 1 org-defdecode) 59)
15575 (setq org-def (apply 'encode-time org-defdecode)
15576 org-defdecode (decode-time org-def)))))
15577 (calendar-frame-setup nil)
15578 (calendar-setup nil)
15579 (calendar-move-hook nil)
15580 (calendar-view-diary-initially-flag nil)
15581 (calendar-view-holidays-initially-flag nil)
15582 (timestr (format-time-string
15583 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15584 (prompt (concat (if prompt (concat prompt " ") "")
15585 (format "Date+time [%s]: " timestr)))
15586 ans (org-ans0 "") org-ans1 org-ans2 final)
15588 (cond
15589 (from-string (setq ans from-string))
15590 (org-read-date-popup-calendar
15591 (save-excursion
15592 (save-window-excursion
15593 (calendar)
15594 (org-eval-in-calendar '(setq cursor-type nil) t)
15595 (unwind-protect
15596 (progn
15597 (calendar-forward-day (- (time-to-days org-def)
15598 (calendar-absolute-from-gregorian
15599 (calendar-current-date))))
15600 (org-eval-in-calendar nil t)
15601 (let* ((old-map (current-local-map))
15602 (map (copy-keymap calendar-mode-map))
15603 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15604 (org-defkey map (kbd "RET") 'org-calendar-select)
15605 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15606 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15607 (org-defkey minibuffer-local-map [(meta shift left)]
15608 (lambda () (interactive)
15609 (org-eval-in-calendar '(calendar-backward-month 1))))
15610 (org-defkey minibuffer-local-map [(meta shift right)]
15611 (lambda () (interactive)
15612 (org-eval-in-calendar '(calendar-forward-month 1))))
15613 (org-defkey minibuffer-local-map [(meta shift up)]
15614 (lambda () (interactive)
15615 (org-eval-in-calendar '(calendar-backward-year 1))))
15616 (org-defkey minibuffer-local-map [(meta shift down)]
15617 (lambda () (interactive)
15618 (org-eval-in-calendar '(calendar-forward-year 1))))
15619 (org-defkey minibuffer-local-map [?\e (shift left)]
15620 (lambda () (interactive)
15621 (org-eval-in-calendar '(calendar-backward-month 1))))
15622 (org-defkey minibuffer-local-map [?\e (shift right)]
15623 (lambda () (interactive)
15624 (org-eval-in-calendar '(calendar-forward-month 1))))
15625 (org-defkey minibuffer-local-map [?\e (shift up)]
15626 (lambda () (interactive)
15627 (org-eval-in-calendar '(calendar-backward-year 1))))
15628 (org-defkey minibuffer-local-map [?\e (shift down)]
15629 (lambda () (interactive)
15630 (org-eval-in-calendar '(calendar-forward-year 1))))
15631 (org-defkey minibuffer-local-map [(shift up)]
15632 (lambda () (interactive)
15633 (org-eval-in-calendar '(calendar-backward-week 1))))
15634 (org-defkey minibuffer-local-map [(shift down)]
15635 (lambda () (interactive)
15636 (org-eval-in-calendar '(calendar-forward-week 1))))
15637 (org-defkey minibuffer-local-map [(shift left)]
15638 (lambda () (interactive)
15639 (org-eval-in-calendar '(calendar-backward-day 1))))
15640 (org-defkey minibuffer-local-map [(shift right)]
15641 (lambda () (interactive)
15642 (org-eval-in-calendar '(calendar-forward-day 1))))
15643 (org-defkey minibuffer-local-map ">"
15644 (lambda () (interactive)
15645 (org-eval-in-calendar '(scroll-calendar-left 1))))
15646 (org-defkey minibuffer-local-map "<"
15647 (lambda () (interactive)
15648 (org-eval-in-calendar '(scroll-calendar-right 1))))
15649 (org-defkey minibuffer-local-map "\C-v"
15650 (lambda () (interactive)
15651 (org-eval-in-calendar
15652 '(calendar-scroll-left-three-months 1))))
15653 (org-defkey minibuffer-local-map "\M-v"
15654 (lambda () (interactive)
15655 (org-eval-in-calendar
15656 '(calendar-scroll-right-three-months 1))))
15657 (run-hooks 'org-read-date-minibuffer-setup-hook)
15658 (unwind-protect
15659 (progn
15660 (use-local-map map)
15661 (setq org-read-date-inactive inactive)
15662 (add-hook 'post-command-hook 'org-read-date-display)
15663 (setq org-ans0 (read-string prompt default-input
15664 'org-read-date-history nil))
15665 ;; org-ans0: from prompt
15666 ;; org-ans1: from mouse click
15667 ;; org-ans2: from calendar motion
15668 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15669 (remove-hook 'post-command-hook 'org-read-date-display)
15670 (use-local-map old-map)
15671 (when org-read-date-overlay
15672 (delete-overlay org-read-date-overlay)
15673 (setq org-read-date-overlay nil)))))
15674 (bury-buffer "*Calendar*")))))
15676 (t ; Naked prompt only
15677 (unwind-protect
15678 (setq ans (read-string prompt default-input
15679 'org-read-date-history timestr))
15680 (when org-read-date-overlay
15681 (delete-overlay org-read-date-overlay)
15682 (setq org-read-date-overlay nil)))))
15684 (setq final (org-read-date-analyze ans org-def org-defdecode))
15686 (when org-read-date-analyze-forced-year
15687 (message "Year was forced into %s"
15688 (if org-read-date-force-compatible-dates
15689 "compatible range (1970-2037)"
15690 "range representable on this machine"))
15691 (ding))
15693 ;; One round trip to get rid of 34th of August and stuff like that....
15694 (setq final (decode-time (apply 'encode-time final)))
15696 (setq org-read-date-final-answer ans)
15698 (if to-time
15699 (apply 'encode-time final)
15700 (if (and (boundp 'org-time-was-given) org-time-was-given)
15701 (format "%04d-%02d-%02d %02d:%02d"
15702 (nth 5 final) (nth 4 final) (nth 3 final)
15703 (nth 2 final) (nth 1 final))
15704 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15706 (defvar org-def)
15707 (defvar org-defdecode)
15708 (defvar org-with-time)
15709 (defun org-read-date-display ()
15710 "Display the current date prompt interpretation in the minibuffer."
15711 (when org-read-date-display-live
15712 (when org-read-date-overlay
15713 (delete-overlay org-read-date-overlay))
15714 (when (minibufferp (current-buffer))
15715 (save-excursion
15716 (end-of-line 1)
15717 (while (not (equal (buffer-substring
15718 (max (point-min) (- (point) 4)) (point))
15719 " "))
15720 (insert " ")))
15721 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15722 " " (or org-ans1 org-ans2)))
15723 (org-end-time-was-given nil)
15724 (f (org-read-date-analyze ans org-def org-defdecode))
15725 (fmts (if org-dcst
15726 org-time-stamp-custom-formats
15727 org-time-stamp-formats))
15728 (fmt (if (or org-with-time
15729 (and (boundp 'org-time-was-given) org-time-was-given))
15730 (cdr fmts)
15731 (car fmts)))
15732 (txt (format-time-string fmt (apply 'encode-time f)))
15733 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15734 (txt (concat "=> " txt)))
15735 (when (and org-end-time-was-given
15736 (string-match org-plain-time-of-day-regexp txt))
15737 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15738 org-end-time-was-given
15739 (substring txt (match-end 0)))))
15740 (when org-read-date-analyze-futurep
15741 (setq txt (concat txt " (=>F)")))
15742 (setq org-read-date-overlay
15743 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15744 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15746 (defun org-read-date-analyze (ans org-def org-defdecode)
15747 "Analyze the combined answer of the date prompt."
15748 ;; FIXME: cleanup and comment
15749 (let ((nowdecode (decode-time (current-time)))
15750 delta deltan deltaw deltadef year month day
15751 hour minute second wday pm h2 m2 tl wday1
15752 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15753 (setq org-read-date-analyze-futurep nil
15754 org-read-date-analyze-forced-year nil)
15755 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15756 (setq ans "+0"))
15758 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15759 (setq ans (replace-match "" t t ans)
15760 deltan (car delta)
15761 deltaw (nth 1 delta)
15762 deltadef (nth 2 delta)))
15764 ;; Check if there is an iso week date in there. If yes, store the
15765 ;; info and postpone interpreting it until the rest of the parsing
15766 ;; is done.
15767 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15768 (setq iso-year (if (match-end 1)
15769 (org-small-year-to-year
15770 (string-to-number (match-string 1 ans))))
15771 iso-weekday (if (match-end 3)
15772 (string-to-number (match-string 3 ans)))
15773 iso-week (string-to-number (match-string 2 ans)))
15774 (setq ans (replace-match "" t t ans)))
15776 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15777 (when (string-match
15778 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15779 (setq year (if (match-end 2)
15780 (string-to-number (match-string 2 ans))
15781 (progn (setq kill-year t)
15782 (string-to-number (format-time-string "%Y"))))
15783 month (string-to-number (match-string 3 ans))
15784 day (string-to-number (match-string 4 ans)))
15785 (if (< year 100) (setq year (+ 2000 year)))
15786 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15787 t nil ans)))
15789 ;; Help matching dotted european dates
15790 (when (string-match
15791 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15792 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15793 (setq kill-year t)
15794 (string-to-number (format-time-string "%Y")))
15795 day (string-to-number (match-string 1 ans))
15796 month (string-to-number (match-string 2 ans))
15797 ans (replace-match (format "%04d-%02d-%02d" year month day)
15798 t nil ans)))
15800 ;; Help matching american dates, like 5/30 or 5/30/7
15801 (when (string-match
15802 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15803 (setq year (if (match-end 4)
15804 (string-to-number (match-string 4 ans))
15805 (progn (setq kill-year t)
15806 (string-to-number (format-time-string "%Y"))))
15807 month (string-to-number (match-string 1 ans))
15808 day (string-to-number (match-string 2 ans)))
15809 (if (< year 100) (setq year (+ 2000 year)))
15810 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15811 t nil ans)))
15812 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15813 ;; If there is a time with am/pm, and *no* time without it, we convert
15814 ;; so that matching will be successful.
15815 (loop for i from 1 to 2 do ; twice, for end time as well
15816 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15817 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15818 (setq hour (string-to-number (match-string 1 ans))
15819 minute (if (match-end 3)
15820 (string-to-number (match-string 3 ans))
15822 pm (equal ?p
15823 (string-to-char (downcase (match-string 4 ans)))))
15824 (if (and (= hour 12) (not pm))
15825 (setq hour 0)
15826 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15827 (setq ans (replace-match (format "%02d:%02d" hour minute)
15828 t t ans))))
15830 ;; Check if a time range is given as a duration
15831 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15832 (setq hour (string-to-number (match-string 1 ans))
15833 h2 (+ hour (string-to-number (match-string 3 ans)))
15834 minute (string-to-number (match-string 2 ans))
15835 m2 (+ minute (if (match-end 5) (string-to-number
15836 (match-string 5 ans))0)))
15837 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15838 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15839 t t ans)))
15841 ;; Check if there is a time range
15842 (when (boundp 'org-end-time-was-given)
15843 (setq org-time-was-given nil)
15844 (when (and (string-match org-plain-time-of-day-regexp ans)
15845 (match-end 8))
15846 (setq org-end-time-was-given (match-string 8 ans))
15847 (setq ans (concat (substring ans 0 (match-beginning 7))
15848 (substring ans (match-end 7))))))
15850 (setq tl (parse-time-string ans)
15851 day (or (nth 3 tl) (nth 3 org-defdecode))
15852 month (or (nth 4 tl)
15853 (if (and org-read-date-prefer-future
15854 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15855 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15856 (nth 4 org-defdecode)))
15857 year (or (and (not kill-year) (nth 5 tl))
15858 (if (and org-read-date-prefer-future
15859 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15860 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15861 (nth 5 org-defdecode)))
15862 hour (or (nth 2 tl) (nth 2 org-defdecode))
15863 minute (or (nth 1 tl) (nth 1 org-defdecode))
15864 second (or (nth 0 tl) 0)
15865 wday (nth 6 tl))
15867 (when (and (eq org-read-date-prefer-future 'time)
15868 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15869 (equal day (nth 3 nowdecode))
15870 (equal month (nth 4 nowdecode))
15871 (equal year (nth 5 nowdecode))
15872 (nth 2 tl)
15873 (or (< (nth 2 tl) (nth 2 nowdecode))
15874 (and (= (nth 2 tl) (nth 2 nowdecode))
15875 (nth 1 tl)
15876 (< (nth 1 tl) (nth 1 nowdecode)))))
15877 (setq day (1+ day)
15878 futurep t))
15880 ;; Special date definitions below
15881 (cond
15882 (iso-week
15883 ;; There was an iso week
15884 (require 'cal-iso)
15885 (setq futurep nil)
15886 (setq year (or iso-year year)
15887 day (or iso-weekday wday 1)
15888 wday nil ; to make sure that the trigger below does not match
15889 iso-date (calendar-gregorian-from-absolute
15890 (calendar-absolute-from-iso
15891 (list iso-week day year))))
15892 ; FIXME: Should we also push ISO weeks into the future?
15893 ; (when (and org-read-date-prefer-future
15894 ; (not iso-year)
15895 ; (< (calendar-absolute-from-gregorian iso-date)
15896 ; (time-to-days (current-time))))
15897 ; (setq year (1+ year)
15898 ; iso-date (calendar-gregorian-from-absolute
15899 ; (calendar-absolute-from-iso
15900 ; (list iso-week day year)))))
15901 (setq month (car iso-date)
15902 year (nth 2 iso-date)
15903 day (nth 1 iso-date)))
15904 (deltan
15905 (setq futurep nil)
15906 (unless deltadef
15907 (let ((now (decode-time (current-time))))
15908 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15909 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15910 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15911 ((equal deltaw "m") (setq month (+ month deltan)))
15912 ((equal deltaw "y") (setq year (+ year deltan)))))
15913 ((and wday (not (nth 3 tl)))
15914 ;; Weekday was given, but no day, so pick that day in the week
15915 ;; on or after the derived date.
15916 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15917 (unless (equal wday wday1)
15918 (setq day (+ day (% (- wday wday1 -7) 7))))))
15919 (if (and (boundp 'org-time-was-given)
15920 (nth 2 tl))
15921 (setq org-time-was-given t))
15922 (if (< year 100) (setq year (+ 2000 year)))
15923 ;; Check of the date is representable
15924 (if org-read-date-force-compatible-dates
15925 (progn
15926 (if (< year 1970)
15927 (setq year 1970 org-read-date-analyze-forced-year t))
15928 (if (> year 2037)
15929 (setq year 2037 org-read-date-analyze-forced-year t)))
15930 (condition-case nil
15931 (ignore (encode-time second minute hour day month year))
15932 (error
15933 (setq year (nth 5 org-defdecode))
15934 (setq org-read-date-analyze-forced-year t))))
15935 (setq org-read-date-analyze-futurep futurep)
15936 (list second minute hour day month year)))
15938 (defvar parse-time-weekdays)
15939 (defun org-read-date-get-relative (s today default)
15940 "Check string S for special relative date string.
15941 TODAY and DEFAULT are internal times, for today and for a default.
15942 Return shift list (N what def-flag)
15943 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15944 N is the number of WHATs to shift.
15945 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15946 the DEFAULT date rather than TODAY."
15947 (require 'parse-time)
15948 (when (and
15949 (string-match
15950 (concat
15951 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15952 "\\([0-9]+\\)?"
15953 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15954 "\\([ \t]\\|$\\)") s)
15955 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15956 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15957 (string-to-char (substring (match-string 1 s) -1))
15958 ?+))
15959 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15960 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15961 (what (if (match-end 3) (match-string 3 s) "d"))
15962 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15963 (date (if rel default today))
15964 (wday (nth 6 (decode-time date)))
15965 delta)
15966 (if wday1
15967 (progn
15968 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15969 (if (= dir ?-) (setq delta (- delta 7)))
15970 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15971 (list delta "d" rel))
15972 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15974 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15975 "Turn a user-specified date into the internal representation.
15976 The internal representation needed by the calendar is (month day year).
15977 This is a wrapper to handle the brain-dead convention in calendar that
15978 user function argument order change dependent on argument order."
15979 (if (boundp 'calendar-date-style)
15980 (cond
15981 ((eq calendar-date-style 'american)
15982 (list arg1 arg2 arg3))
15983 ((eq calendar-date-style 'european)
15984 (list arg2 arg1 arg3))
15985 ((eq calendar-date-style 'iso)
15986 (list arg2 arg3 arg1)))
15987 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15988 (if (org-bound-and-true-p european-calendar-style)
15989 (list arg2 arg1 arg3)
15990 (list arg1 arg2 arg3)))))
15992 (defun org-eval-in-calendar (form &optional keepdate)
15993 "Eval FORM in the calendar window and return to current window.
15994 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15995 otherwise stick to the current value of `org-ans2'."
15996 (let ((sf (selected-frame))
15997 (sw (selected-window)))
15998 (select-window (get-buffer-window "*Calendar*" t))
15999 (eval form)
16000 (when (and (not keepdate) (calendar-cursor-to-date))
16001 (let* ((date (calendar-cursor-to-date))
16002 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16003 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16004 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16005 (select-window sw)
16006 (org-select-frame-set-input-focus sf)))
16008 (defun org-calendar-select ()
16009 "Return to `org-read-date' with the date currently selected.
16010 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16011 (interactive)
16012 (when (calendar-cursor-to-date)
16013 (let* ((date (calendar-cursor-to-date))
16014 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16015 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16016 (if (active-minibuffer-window) (exit-minibuffer))))
16018 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16019 "Insert a date stamp for the date given by the internal TIME.
16020 WITH-HM means use the stamp format that includes the time of the day.
16021 INACTIVE means use square brackets instead of angular ones, so that the
16022 stamp will not contribute to the agenda.
16023 PRE and POST are optional strings to be inserted before and after the
16024 stamp.
16025 The command returns the inserted time stamp."
16026 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16027 stamp)
16028 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16029 (insert-before-markers (or pre ""))
16030 (when (listp extra)
16031 (setq extra (car extra))
16032 (if (and (stringp extra)
16033 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16034 (setq extra (format "-%02d:%02d"
16035 (string-to-number (match-string 1 extra))
16036 (string-to-number (match-string 2 extra))))
16037 (setq extra nil)))
16038 (when extra
16039 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16040 (insert-before-markers (setq stamp (format-time-string fmt time)))
16041 (insert-before-markers (or post ""))
16042 (setq org-last-inserted-timestamp stamp)))
16044 (defun org-toggle-time-stamp-overlays ()
16045 "Toggle the use of custom time stamp formats."
16046 (interactive)
16047 (setq org-display-custom-times (not org-display-custom-times))
16048 (unless org-display-custom-times
16049 (let ((p (point-min)) (bmp (buffer-modified-p)))
16050 (while (setq p (next-single-property-change p 'display))
16051 (if (and (get-text-property p 'display)
16052 (eq (get-text-property p 'face) 'org-date))
16053 (remove-text-properties
16054 p (setq p (next-single-property-change p 'display))
16055 '(display t))))
16056 (set-buffer-modified-p bmp)))
16057 (if (featurep 'xemacs)
16058 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16059 (org-restart-font-lock)
16060 (setq org-table-may-need-update t)
16061 (if org-display-custom-times
16062 (message "Time stamps are overlaid with custom format")
16063 (message "Time stamp overlays removed")))
16065 (defun org-display-custom-time (beg end)
16066 "Overlay modified time stamp format over timestamp between BEG and END."
16067 (let* ((ts (buffer-substring beg end))
16068 t1 w1 with-hm tf time str w2 (off 0))
16069 (save-match-data
16070 (setq t1 (org-parse-time-string ts t))
16071 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16072 (setq off (- (match-end 0) (match-beginning 0)))))
16073 (setq end (- end off))
16074 (setq w1 (- end beg)
16075 with-hm (and (nth 1 t1) (nth 2 t1))
16076 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16077 time (org-fix-decoded-time t1)
16078 str (org-add-props
16079 (format-time-string
16080 (substring tf 1 -1) (apply 'encode-time time))
16081 nil 'mouse-face 'highlight)
16082 w2 (length str))
16083 (if (not (= w2 w1))
16084 (add-text-properties (1+ beg) (+ 2 beg)
16085 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16086 (if (featurep 'xemacs)
16087 (progn
16088 (put-text-property beg end 'invisible t)
16089 (put-text-property beg end 'end-glyph (make-glyph str)))
16090 (put-text-property beg end 'display str))))
16092 (defun org-translate-time (string)
16093 "Translate all timestamps in STRING to custom format.
16094 But do this only if the variable `org-display-custom-times' is set."
16095 (when org-display-custom-times
16096 (save-match-data
16097 (let* ((start 0)
16098 (re org-ts-regexp-both)
16099 t1 with-hm inactive tf time str beg end)
16100 (while (setq start (string-match re string start))
16101 (setq beg (match-beginning 0)
16102 end (match-end 0)
16103 t1 (save-match-data
16104 (org-parse-time-string (substring string beg end) t))
16105 with-hm (and (nth 1 t1) (nth 2 t1))
16106 inactive (equal (substring string beg (1+ beg)) "[")
16107 tf (funcall (if with-hm 'cdr 'car)
16108 org-time-stamp-custom-formats)
16109 time (org-fix-decoded-time t1)
16110 str (format-time-string
16111 (concat
16112 (if inactive "[" "<") (substring tf 1 -1)
16113 (if inactive "]" ">"))
16114 (apply 'encode-time time))
16115 string (replace-match str t t string)
16116 start (+ start (length str)))))))
16117 string)
16119 (defun org-fix-decoded-time (time)
16120 "Set 0 instead of nil for the first 6 elements of time.
16121 Don't touch the rest."
16122 (let ((n 0))
16123 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16125 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16127 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16128 "Difference between TIMESTAMP-STRING and now in days.
16129 If SECONDS is non-nil, return the difference in seconds."
16130 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16131 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16132 (funcall fdiff (current-time)))))
16134 (defun org-deadline-close (timestamp-string &optional ndays)
16135 "Is the time in TIMESTAMP-STRING close to the current date?"
16136 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16137 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16138 (not (org-entry-is-done-p))))
16140 (defun org-get-wdays (ts)
16141 "Get the deadline lead time appropriate for timestring TS."
16142 (cond
16143 ((<= org-deadline-warning-days 0)
16144 ;; 0 or negative, enforce this value no matter what
16145 (- org-deadline-warning-days))
16146 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16147 ;; lead time is specified.
16148 (floor (* (string-to-number (match-string 1 ts))
16149 (cdr (assoc (match-string 2 ts)
16150 '(("d" . 1) ("w" . 7)
16151 ("m" . 30.4) ("y" . 365.25)))))))
16152 ;; go for the default.
16153 (t org-deadline-warning-days)))
16155 (defun org-calendar-select-mouse (ev)
16156 "Return to `org-read-date' with the date currently selected.
16157 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16158 (interactive "e")
16159 (mouse-set-point ev)
16160 (when (calendar-cursor-to-date)
16161 (let* ((date (calendar-cursor-to-date))
16162 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16163 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16164 (if (active-minibuffer-window) (exit-minibuffer))))
16166 (defun org-check-deadlines (ndays)
16167 "Check if there are any deadlines due or past due.
16168 A deadline is considered due if it happens within `org-deadline-warning-days'
16169 days from today's date. If the deadline appears in an entry marked DONE,
16170 it is not shown. The prefix arg NDAYS can be used to test that many
16171 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16172 (interactive "P")
16173 (let* ((org-warn-days
16174 (cond
16175 ((equal ndays '(4)) 100000)
16176 (ndays (prefix-numeric-value ndays))
16177 (t (abs org-deadline-warning-days))))
16178 (case-fold-search nil)
16179 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16180 (callback
16181 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16183 (message "%d deadlines past-due or due within %d days"
16184 (org-occur regexp nil callback)
16185 org-warn-days)))
16187 (defsubst org-re-timestamp (type)
16188 "Return a regexp for timestamp TYPE.
16189 Allowed values for TYPE are:
16191 all: all timestamps
16192 active: only active timestamps (<...>)
16193 inactive: only inactive timestamps ([...])
16194 scheduled: only scheduled timestamps
16195 deadline: only deadline timestamps
16197 When TYPE is nil, fall back on returning a regexp that matches
16198 both scheduled and deadline timestamps."
16199 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16200 ((eq type 'active) org-ts-regexp)
16201 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16202 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16203 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16204 ((eq type 'scheduled-or-deadline)
16205 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16207 (defun org-check-before-date (date)
16208 "Check if there are deadlines or scheduled entries before DATE."
16209 (interactive (list (org-read-date)))
16210 (let ((case-fold-search nil)
16211 (regexp (org-re-timestamp org-ts-type))
16212 (callback
16213 (lambda () (time-less-p
16214 (org-time-string-to-time (match-string 1))
16215 (org-time-string-to-time date)))))
16216 (message "%d entries before %s"
16217 (org-occur regexp nil callback) date)))
16219 (defun org-check-after-date (date)
16220 "Check if there are deadlines or scheduled entries after DATE."
16221 (interactive (list (org-read-date)))
16222 (let ((case-fold-search nil)
16223 (regexp (org-re-timestamp org-ts-type))
16224 (callback
16225 (lambda () (not
16226 (time-less-p
16227 (org-time-string-to-time (match-string 1))
16228 (org-time-string-to-time date))))))
16229 (message "%d entries after %s"
16230 (org-occur regexp nil callback) date)))
16232 (defun org-check-dates-range (start-date end-date)
16233 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16234 (interactive (list (org-read-date nil nil nil "Range starts")
16235 (org-read-date nil nil nil "Range end")))
16236 (let ((case-fold-search nil)
16237 (regexp (org-re-timestamp org-ts-type))
16238 (callback
16239 (lambda ()
16240 (let ((match (match-string 1)))
16241 (and
16242 (not (time-less-p
16243 (org-time-string-to-time match)
16244 (org-time-string-to-time start-date)))
16245 (time-less-p
16246 (org-time-string-to-time match)
16247 (org-time-string-to-time end-date)))))))
16248 (message "%d entries between %s and %s"
16249 (org-occur regexp nil callback) start-date end-date)))
16251 (defun org-evaluate-time-range (&optional to-buffer)
16252 "Evaluate a time range by computing the difference between start and end.
16253 Normally the result is just printed in the echo area, but with prefix arg
16254 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16255 If the time range is actually in a table, the result is inserted into the
16256 next column.
16257 For time difference computation, a year is assumed to be exactly 365
16258 days in order to avoid rounding problems."
16259 (interactive "P")
16261 (org-clock-update-time-maybe)
16262 (save-excursion
16263 (unless (org-at-date-range-p t)
16264 (goto-char (point-at-bol))
16265 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16266 (if (not (org-at-date-range-p t))
16267 (error "Not at a time-stamp range, and none found in current line")))
16268 (let* ((ts1 (match-string 1))
16269 (ts2 (match-string 2))
16270 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16271 (match-end (match-end 0))
16272 (time1 (org-time-string-to-time ts1))
16273 (time2 (org-time-string-to-time ts2))
16274 (t1 (org-float-time time1))
16275 (t2 (org-float-time time2))
16276 (diff (abs (- t2 t1)))
16277 (negative (< (- t2 t1) 0))
16278 ;; (ys (floor (* 365 24 60 60)))
16279 (ds (* 24 60 60))
16280 (hs (* 60 60))
16281 (fy "%dy %dd %02d:%02d")
16282 (fy1 "%dy %dd")
16283 (fd "%dd %02d:%02d")
16284 (fd1 "%dd")
16285 (fh "%02d:%02d")
16286 y d h m align)
16287 (if havetime
16288 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16290 d (floor (/ diff ds)) diff (mod diff ds)
16291 h (floor (/ diff hs)) diff (mod diff hs)
16292 m (floor (/ diff 60)))
16293 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16295 d (floor (+ (/ diff ds) 0.5))
16296 h 0 m 0))
16297 (if (not to-buffer)
16298 (message "%s" (org-make-tdiff-string y d h m))
16299 (if (org-at-table-p)
16300 (progn
16301 (goto-char match-end)
16302 (setq align t)
16303 (and (looking-at " *|") (goto-char (match-end 0))))
16304 (goto-char match-end))
16305 (if (looking-at
16306 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16307 (replace-match ""))
16308 (if negative (insert " -"))
16309 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16310 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16311 (insert " " (format fh h m))))
16312 (if align (org-table-align))
16313 (message "Time difference inserted")))))
16315 (defun org-make-tdiff-string (y d h m)
16316 (let ((fmt "")
16317 (l nil))
16318 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16319 l (push y l)))
16320 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16321 l (push d l)))
16322 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16323 l (push h l)))
16324 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16325 l (push m l)))
16326 (apply 'format fmt (nreverse l))))
16328 (defun org-time-string-to-time (s &optional buffer pos)
16329 "Convert a timestamp string into internal time."
16330 (condition-case errdata
16331 (apply 'encode-time (org-parse-time-string s))
16332 (error (error "Bad timestamp `%s'%s\nError was: %s"
16333 s (if (not (and buffer pos))
16335 (format " at %d in buffer `%s'" pos buffer))
16336 (cdr errdata)))))
16338 (defun org-time-string-to-seconds (s)
16339 "Convert a timestamp string to a number of seconds."
16340 (org-float-time (org-time-string-to-time s)))
16342 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16343 "Convert a time stamp to an absolute day number.
16344 If there is a specifier for a cyclic time stamp, get the closest date to
16345 DAYNR.
16346 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16347 The variable date is bound by the calendar when this is called."
16348 (cond
16349 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16350 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16351 daynr
16352 (+ daynr 1000)))
16353 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16354 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16355 (time-to-days (current-time))) (match-string 0 s)
16356 prefer show-all))
16357 (t (time-to-days
16358 (condition-case errdata
16359 (apply 'encode-time (org-parse-time-string s))
16360 (error (error "Bad timestamp `%s'%s\nError was: %s"
16361 s (if (not (and buffer pos))
16363 (format " at %d in buffer `%s'" pos buffer))
16364 (cdr errdata))))))))
16366 (defun org-days-to-iso-week (days)
16367 "Return the iso week number."
16368 (require 'cal-iso)
16369 (car (calendar-iso-from-absolute days)))
16371 (defun org-small-year-to-year (year)
16372 "Convert 2-digit years into 4-digit years.
16373 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16374 The year 2000 cannot be abbreviated. Any year larger than 99
16375 is returned unchanged."
16376 (if (< year 38)
16377 (setq year (+ 2000 year))
16378 (if (< year 100)
16379 (setq year (+ 1900 year))))
16380 year)
16382 (defun org-time-from-absolute (d)
16383 "Return the time corresponding to date D.
16384 D may be an absolute day number, or a calendar-type list (month day year)."
16385 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16386 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16388 (defun org-calendar-holiday ()
16389 "List of holidays, for Diary display in Org-mode."
16390 (require 'holidays)
16391 (let ((hl (funcall
16392 (if (fboundp 'calendar-check-holidays)
16393 'calendar-check-holidays 'check-calendar-holidays) date)))
16394 (if hl (mapconcat 'identity hl "; "))))
16396 (defun org-diary-sexp-entry (sexp entry date)
16397 "Process a SEXP diary ENTRY for DATE."
16398 (require 'diary-lib)
16399 (let ((result (if calendar-debug-sexp
16400 (let ((stack-trace-on-error t))
16401 (eval (car (read-from-string sexp))))
16402 (condition-case nil
16403 (eval (car (read-from-string sexp)))
16404 (error
16405 (beep)
16406 (message "Bad sexp at line %d in %s: %s"
16407 (org-current-line)
16408 (buffer-file-name) sexp)
16409 (sleep-for 2))))))
16410 (cond ((stringp result) (split-string result "; "))
16411 ((and (consp result)
16412 (not (consp (cdr result)))
16413 (stringp (cdr result))) (cdr result))
16414 ((and (consp result)
16415 (stringp (car result))) result)
16416 (result entry))))
16418 (defun org-diary-to-ical-string (frombuf)
16419 "Get iCalendar entries from diary entries in buffer FROMBUF.
16420 This uses the icalendar.el library."
16421 (let* ((tmpdir (if (featurep 'xemacs)
16422 (temp-directory)
16423 temporary-file-directory))
16424 (tmpfile (make-temp-name
16425 (expand-file-name "orgics" tmpdir)))
16426 buf rtn b e)
16427 (with-current-buffer frombuf
16428 (icalendar-export-region (point-min) (point-max) tmpfile)
16429 (setq buf (find-buffer-visiting tmpfile))
16430 (set-buffer buf)
16431 (goto-char (point-min))
16432 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16433 (setq b (match-beginning 0)))
16434 (goto-char (point-max))
16435 (if (re-search-backward "^END:VEVENT" nil t)
16436 (setq e (match-end 0)))
16437 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16438 (kill-buffer buf)
16439 (delete-file tmpfile)
16440 rtn))
16442 (defun org-closest-date (start current change prefer show-all)
16443 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16444 When PREFER is `past', return a date that is either CURRENT or past.
16445 When PREFER is `future', return a date that is either CURRENT or future.
16446 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16447 ;; Make the proper lists from the dates
16448 (catch 'exit
16449 (let ((a1 '(("h" . hour)
16450 ("d" . day)
16451 ("w" . week)
16452 ("m" . month)
16453 ("y" . year)))
16454 (shour (nth 2 (org-parse-time-string start)))
16455 dn dw sday cday n1 n2 n0
16456 d m y y1 y2 date1 date2 nmonths nm ny m2)
16458 (setq start (org-date-to-gregorian start)
16459 current (org-date-to-gregorian
16460 (if show-all
16461 current
16462 (time-to-days (current-time))))
16463 sday (calendar-absolute-from-gregorian start)
16464 cday (calendar-absolute-from-gregorian current))
16466 (if (<= cday sday) (throw 'exit sday))
16468 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16469 (setq dn (string-to-number (match-string 1 change))
16470 dw (cdr (assoc (match-string 2 change) a1)))
16471 (error "Invalid change specifier: %s" change))
16472 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16473 (cond
16474 ((eq dw 'hour)
16475 (let ((missing-hours
16476 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16477 dn)))
16478 (setq n1 (if (zerop missing-hours) cday
16479 (- cday (1+ (floor (/ missing-hours 24)))))
16480 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16481 ((eq dw 'day)
16482 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16483 n2 (+ n1 dn)))
16484 ((eq dw 'year)
16485 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16486 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16487 (setq date1 (list m d y1)
16488 n1 (calendar-absolute-from-gregorian date1)
16489 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16490 n2 (calendar-absolute-from-gregorian date2)))
16491 ((eq dw 'month)
16492 ;; approx number of month between the two dates
16493 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16494 ;; How often does dn fit in there?
16495 (setq d (nth 1 start) m (car start) y (nth 2 start)
16496 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16497 m (+ m nm)
16498 ny (floor (/ m 12))
16499 y (+ y ny)
16500 m (- m (* ny 12)))
16501 (while (> m 12) (setq m (- m 12) y (1+ y)))
16502 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16503 (setq m2 (+ m dn) y2 y)
16504 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16505 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16506 (while (<= n2 cday)
16507 (setq n1 n2 m m2 y y2)
16508 (setq m2 (+ m dn) y2 y)
16509 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16510 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16511 ;; Make sure n1 is the earlier date
16512 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16513 (if show-all
16514 (cond
16515 ((eq prefer 'past) (if (= cday n2) n2 n1))
16516 ((eq prefer 'future) (if (= cday n1) n1 n2))
16517 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16518 (cond
16519 ((eq prefer 'past) (if (= cday n2) n2 n1))
16520 ((eq prefer 'future) (if (= cday n1) n1 n2))
16521 (t (if (= cday n1) n1 n2)))))))
16523 (defun org-date-to-gregorian (date)
16524 "Turn any specification of DATE into a Gregorian date for the calendar."
16525 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16526 ((and (listp date) (= (length date) 3)) date)
16527 ((stringp date)
16528 (setq date (org-parse-time-string date))
16529 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16530 ((listp date)
16531 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16533 (defun org-parse-time-string (s &optional nodefault)
16534 "Parse the standard Org-mode time string.
16535 This should be a lot faster than the normal `parse-time-string'.
16536 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16537 hour and minute fields will be nil if not given."
16538 (if (string-match org-ts-regexp0 s)
16539 (list 0
16540 (if (or (match-beginning 8) (not nodefault))
16541 (string-to-number (or (match-string 8 s) "0")))
16542 (if (or (match-beginning 7) (not nodefault))
16543 (string-to-number (or (match-string 7 s) "0")))
16544 (string-to-number (match-string 4 s))
16545 (string-to-number (match-string 3 s))
16546 (string-to-number (match-string 2 s))
16547 nil nil nil)
16548 (error "Not a standard Org-mode time string: %s" s)))
16550 (defun org-timestamp-up (&optional arg)
16551 "Increase the date item at the cursor by one.
16552 If the cursor is on the year, change the year. If it is on the month,
16553 the day or the time, change that.
16554 With prefix ARG, change by that many units."
16555 (interactive "p")
16556 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16558 (defun org-timestamp-down (&optional arg)
16559 "Decrease the date item at the cursor by one.
16560 If the cursor is on the year, change the year. If it is on the month,
16561 the day or the time, change that.
16562 With prefix ARG, change by that many units."
16563 (interactive "p")
16564 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16566 (defun org-timestamp-up-day (&optional arg)
16567 "Increase the date in the time stamp by one day.
16568 With prefix ARG, change that many days."
16569 (interactive "p")
16570 (if (and (not (org-at-timestamp-p t))
16571 (org-at-heading-p))
16572 (org-todo 'up)
16573 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16575 (defun org-timestamp-down-day (&optional arg)
16576 "Decrease the date in the time stamp by one day.
16577 With prefix ARG, change that many days."
16578 (interactive "p")
16579 (if (and (not (org-at-timestamp-p t))
16580 (org-at-heading-p))
16581 (org-todo 'down)
16582 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16584 (defun org-at-timestamp-p (&optional inactive-ok)
16585 "Determine if the cursor is in or at a timestamp."
16586 (interactive)
16587 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16588 (pos (point))
16589 (ans (or (looking-at tsr)
16590 (save-excursion
16591 (skip-chars-backward "^[<\n\r\t")
16592 (if (> (point) (point-min)) (backward-char 1))
16593 (and (looking-at tsr)
16594 (> (- (match-end 0) pos) -1))))))
16595 (and ans
16596 (boundp 'org-ts-what)
16597 (setq org-ts-what
16598 (cond
16599 ((= pos (match-beginning 0)) 'bracket)
16600 ;; Point is considered to be "on the bracket" whether
16601 ;; it's really on it or right after it.
16602 ((= pos (1- (match-end 0))) 'bracket)
16603 ((= pos (match-end 0)) 'after)
16604 ((org-pos-in-match-range pos 2) 'year)
16605 ((org-pos-in-match-range pos 3) 'month)
16606 ((org-pos-in-match-range pos 7) 'hour)
16607 ((org-pos-in-match-range pos 8) 'minute)
16608 ((or (org-pos-in-match-range pos 4)
16609 (org-pos-in-match-range pos 5)) 'day)
16610 ((and (> pos (or (match-end 8) (match-end 5)))
16611 (< pos (match-end 0)))
16612 (- pos (or (match-end 8) (match-end 5))))
16613 (t 'day))))
16614 ans))
16616 (defun org-toggle-timestamp-type ()
16617 "Toggle the type (<active> or [inactive]) of a time stamp."
16618 (interactive)
16619 (when (org-at-timestamp-p t)
16620 (let ((beg (match-beginning 0)) (end (match-end 0))
16621 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16622 (save-excursion
16623 (goto-char beg)
16624 (while (re-search-forward "[][<>]" end t)
16625 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16626 t t)))
16627 (message "Timestamp is now %sactive"
16628 (if (equal (char-after beg) ?<) "" "in")))))
16630 (defvar org-clock-history) ; defined in org-clock.el
16631 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16632 (defun org-timestamp-change (n &optional what updown)
16633 "Change the date in the time stamp at point.
16634 The date will be changed by N times WHAT. WHAT can be `day', `month',
16635 `year', `minute', `second'. If WHAT is not given, the cursor position
16636 in the timestamp determines what will be changed."
16637 (let ((origin (point)) origin-cat
16638 with-hm inactive
16639 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16640 org-ts-what
16641 extra rem
16642 ts time time0 fixnext clrgx)
16643 (if (not (org-at-timestamp-p t))
16644 (error "Not at a timestamp"))
16645 (if (and (not what) (eq org-ts-what 'bracket))
16646 (org-toggle-timestamp-type)
16647 ;; Point isn't on brackets. Remember the part of the time-stamp
16648 ;; the point was in. Indeed, size of time-stamps may change,
16649 ;; but point must be kept in the same category nonetheless.
16650 (setq origin-cat org-ts-what)
16651 (if (and (not what) (not (eq org-ts-what 'day))
16652 org-display-custom-times
16653 (get-text-property (point) 'display)
16654 (not (get-text-property (1- (point)) 'display)))
16655 (setq org-ts-what 'day))
16656 (setq org-ts-what (or what org-ts-what)
16657 inactive (= (char-after (match-beginning 0)) ?\[)
16658 ts (match-string 0))
16659 (replace-match "")
16660 (if (string-match
16661 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16663 (setq extra (match-string 1 ts)))
16664 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16665 (setq with-hm t))
16666 (setq time0 (org-parse-time-string ts))
16667 (when (and updown
16668 (eq org-ts-what 'minute)
16669 (not current-prefix-arg))
16670 ;; This looks like s-up and s-down. Change by one rounding step.
16671 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16672 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16673 (setcar (cdr time0) (+ (nth 1 time0)
16674 (if (> n 0) (- rem) (- dm rem))))))
16675 (setq time
16676 (encode-time (or (car time0) 0)
16677 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16678 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16679 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16680 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16681 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16682 (nthcdr 6 time0)))
16683 (when (and (member org-ts-what '(hour minute))
16684 extra
16685 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16686 (setq extra (org-modify-ts-extra
16687 extra
16688 (if (eq org-ts-what 'hour) 2 5)
16689 n dm)))
16690 (when (integerp org-ts-what)
16691 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16692 (if (eq what 'calendar)
16693 (let ((cal-date (org-get-date-from-calendar)))
16694 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16695 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16696 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16697 (setcar time0 (or (car time0) 0))
16698 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16699 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16700 (setq time (apply 'encode-time time0))))
16701 ;; Insert the new time-stamp, and ensure point stays in the same
16702 ;; category as before (i.e. not after the last position in that
16703 ;; category).
16704 (let ((pos (point)))
16705 ;; Stay before inserted string. `save-excursion' is of no use.
16706 (setq org-last-changed-timestamp
16707 (org-insert-time-stamp time with-hm inactive nil nil extra))
16708 (goto-char pos))
16709 (save-match-data
16710 (looking-at org-ts-regexp3)
16711 (goto-char (cond
16712 ;; `day' category ends before `hour' if any, or at
16713 ;; the end of the day name.
16714 ((eq origin-cat 'day)
16715 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16716 ((eq origin-cat 'hour) (min (match-end 7) origin))
16717 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16718 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16719 ;; `year' and `month' have both fixed size: point
16720 ;; couldn't have moved into another part.
16721 (t origin))))
16722 ;; Update clock if on a CLOCK line.
16723 (org-clock-update-time-maybe)
16724 ;; Maybe adjust the closest clock in `org-clock-history'
16725 (when org-clock-adjust-closest
16726 (if (not (and (org-at-clock-log-p)
16727 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16728 org-clock-history))))))
16729 (message "No clock to adjust")
16730 (cond ((save-excursion ; fix previous clock?
16731 (re-search-backward org-ts-regexp0 nil t)
16732 (org-looking-back (concat org-clock-string " \\[")))
16733 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16734 ((save-excursion ; fix next clock?
16735 (re-search-backward org-ts-regexp0 nil t)
16736 (looking-at (concat org-ts-regexp0 "\\] =>")))
16737 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16738 (save-window-excursion
16739 ;; Find closest clock to point, adjust the previous/next one in history
16740 (let* ((p (save-excursion (org-back-to-heading t)))
16741 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16742 (clfixnth
16743 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16744 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16745 (if (not clfixpos)
16746 (message "No clock to adjust")
16747 (save-excursion
16748 (org-goto-marker-or-bmk clfixpos)
16749 (org-show-subtree)
16750 (when (re-search-forward clrgx nil t)
16751 (goto-char (match-beginning 1))
16752 (let (org-clock-adjust-closest)
16753 (org-timestamp-change n org-ts-what updown))
16754 (message "Clock adjusted in %s for heading: %s"
16755 (file-name-nondirectory (buffer-file-name))
16756 (org-get-heading t t)))))))))
16757 ;; Try to recenter the calendar window, if any.
16758 (if (and org-calendar-follow-timestamp-change
16759 (get-buffer-window "*Calendar*" t)
16760 (memq org-ts-what '(day month year)))
16761 (org-recenter-calendar (time-to-days time))))))
16763 (defun org-modify-ts-extra (s pos n dm)
16764 "Change the different parts of the lead-time and repeat fields in timestamp."
16765 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16766 ng h m new rem)
16767 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16768 (cond
16769 ((or (org-pos-in-match-range pos 2)
16770 (org-pos-in-match-range pos 3))
16771 (setq m (string-to-number (match-string 3 s))
16772 h (string-to-number (match-string 2 s)))
16773 (if (org-pos-in-match-range pos 2)
16774 (setq h (+ h n))
16775 (setq n (* dm (org-no-warnings (signum n))))
16776 (when (not (= 0 (setq rem (% m dm))))
16777 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16778 (setq m (+ m n)))
16779 (if (< m 0) (setq m (+ m 60) h (1- h)))
16780 (if (> m 59) (setq m (- m 60) h (1+ h)))
16781 (setq h (min 24 (max 0 h)))
16782 (setq ng 1 new (format "-%02d:%02d" h m)))
16783 ((org-pos-in-match-range pos 6)
16784 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16785 ((org-pos-in-match-range pos 5)
16786 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16788 ((org-pos-in-match-range pos 9)
16789 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16790 ((org-pos-in-match-range pos 8)
16791 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16793 (when ng
16794 (setq s (concat
16795 (substring s 0 (match-beginning ng))
16797 (substring s (match-end ng))))))
16800 (defun org-recenter-calendar (date)
16801 "If the calendar is visible, recenter it to DATE."
16802 (let ((cwin (get-buffer-window "*Calendar*" t)))
16803 (when cwin
16804 (let ((calendar-move-hook nil))
16805 (with-selected-window cwin
16806 (calendar-goto-date (if (listp date) date
16807 (calendar-gregorian-from-absolute date))))))))
16809 (defun org-goto-calendar (&optional arg)
16810 "Go to the Emacs calendar at the current date.
16811 If there is a time stamp in the current line, go to that date.
16812 A prefix ARG can be used to force the current date."
16813 (interactive "P")
16814 (let ((tsr org-ts-regexp) diff
16815 (calendar-move-hook nil)
16816 (calendar-view-holidays-initially-flag nil)
16817 (calendar-view-diary-initially-flag nil))
16818 (if (or (org-at-timestamp-p)
16819 (save-excursion
16820 (beginning-of-line 1)
16821 (looking-at (concat ".*" tsr))))
16822 (let ((d1 (time-to-days (current-time)))
16823 (d2 (time-to-days
16824 (org-time-string-to-time (match-string 1)))))
16825 (setq diff (- d2 d1))))
16826 (calendar)
16827 (calendar-goto-today)
16828 (if (and diff (not arg)) (calendar-forward-day diff))))
16830 (defun org-get-date-from-calendar ()
16831 "Return a list (month day year) of date at point in calendar."
16832 (with-current-buffer "*Calendar*"
16833 (save-match-data
16834 (calendar-cursor-to-date))))
16836 (defun org-date-from-calendar ()
16837 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16838 If there is already a time stamp at the cursor position, update it."
16839 (interactive)
16840 (if (org-at-timestamp-p t)
16841 (org-timestamp-change 0 'calendar)
16842 (let ((cal-date (org-get-date-from-calendar)))
16843 (org-insert-time-stamp
16844 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16846 (defun org-minutes-to-clocksum-string (m)
16847 "Format number of minutes as a clocksum string.
16848 The format is determined by `org-time-clocksum-format',
16849 `org-time-clocksum-use-fractional' and
16850 `org-time-clocksum-fractional-format'."
16851 (let ((clocksum "") fmt n)
16852 ;; fractional format
16853 (if org-time-clocksum-use-fractional
16854 (cond
16855 ;; single format string
16856 ((stringp org-time-clocksum-fractional-format)
16857 (format org-time-clocksum-fractional-format (/ m 60.0)))
16858 ;; choice of fractional formats for different time units
16859 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16860 (> (/ (truncate m) (* 365 24 60)) 0))
16861 (format fmt (/ m (* 365 24 60.0))))
16862 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16863 (> (/ (truncate m) (* 30 24 60)) 0))
16864 (format fmt (/ m (* 30 24 60.0))))
16865 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16866 (> (/ (truncate m) (* 7 24 60)) 0))
16867 (format fmt (/ m (* 7 24 60.0))))
16868 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16869 (> (/ (truncate m) (* 24 60)) 0))
16870 (format fmt (/ m (* 24 60.0))))
16871 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16872 (> (/ (truncate m) 60) 0))
16873 (format fmt (/ m 60.0)))
16874 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16875 (format fmt m))
16876 ;; fall back to smallest time unit with a format
16877 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16878 (format fmt (/ m 60.0)))
16879 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16880 (format fmt (/ m (* 24 60.0))))
16881 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16882 (format fmt (/ m (* 7 24 60.0))))
16883 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16884 (format fmt (/ m (* 30 24 60.0))))
16885 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16886 (format fmt (/ m (* 365 24 60.0)))))
16887 ;; standard (non-fractional) format, with single format string
16888 (if (stringp org-time-clocksum-format)
16889 (format org-time-clocksum-format (setq n (/ m 60)) (- m (* 60 n)))
16890 ;; separate formats components
16891 (and (setq fmt (plist-get org-time-clocksum-format :years))
16892 (or (> (setq n (/ (truncate m) (* 365 24 60))) 0)
16893 (plist-get org-time-clocksum-format :require-years))
16894 (setq clocksum (concat clocksum (format fmt n))
16895 m (- m (* n 365 24 60))))
16896 (and (setq fmt (plist-get org-time-clocksum-format :months))
16897 (or (> (setq n (/ (truncate m) (* 30 24 60))) 0)
16898 (plist-get org-time-clocksum-format :require-months))
16899 (setq clocksum (concat clocksum (format fmt n))
16900 m (- m (* n 30 24 60))))
16901 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16902 (or (> (setq n (/ (truncate m) (* 7 24 60))) 0)
16903 (plist-get org-time-clocksum-format :require-weeks))
16904 (setq clocksum (concat clocksum (format fmt n))
16905 m (- m (* n 7 24 60))))
16906 (and (setq fmt (plist-get org-time-clocksum-format :days))
16907 (or (> (setq n (/ (truncate m) (* 24 60))) 0)
16908 (plist-get org-time-clocksum-format :require-days))
16909 (setq clocksum (concat clocksum (format fmt n))
16910 m (- m (* n 24 60))))
16911 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16912 (or (> (setq n (/ (truncate m) 60)) 0)
16913 (plist-get org-time-clocksum-format :require-hours))
16914 (setq clocksum (concat clocksum (format fmt n))
16915 m (- m (* n 60))))
16916 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16917 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16918 (setq clocksum (concat clocksum (format fmt m))))
16919 ;; return formatted time duration
16920 clocksum))))
16922 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16923 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16924 "Org mode version 8.0")
16926 (defun org-hours-to-clocksum-string (n)
16927 (org-minutes-to-clocksum-string (* n 60)))
16929 (defun org-hh:mm-string-to-minutes (s)
16930 "Convert a string H:MM to a number of minutes.
16931 If the string is just a number, interpret it as minutes.
16932 In fact, the first hh:mm or number in the string will be taken,
16933 there can be extra stuff in the string.
16934 If no number is found, the return value is 0."
16935 (cond
16936 ((integerp s) s)
16937 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16938 (+ (* (string-to-number (match-string 1 s)) 60)
16939 (string-to-number (match-string 2 s))))
16940 ((string-match "\\([0-9]+\\)" s)
16941 (string-to-number (match-string 1 s)))
16942 (t 0)))
16944 (defcustom org-effort-durations
16945 `(("h" . 60)
16946 ("d" . ,(* 60 8))
16947 ("w" . ,(* 60 8 5))
16948 ("m" . ,(* 60 8 5 4))
16949 ("y" . ,(* 60 8 5 40)))
16950 "Conversion factor to minutes for an effort modifier.
16952 Each entry has the form (MODIFIER . MINUTES).
16954 In an effort string, a number followed by MODIFIER is multiplied
16955 by the specified number of MINUTES to obtain an effort in
16956 minutes.
16958 For example, if the value of this variable is ((\"hours\" . 60)), then an
16959 effort string \"2hours\" is equivalent to 120 minutes."
16960 :group 'org-agenda
16961 :version "24.1"
16962 :type '(alist :key-type (string :tag "Modifier")
16963 :value-type (number :tag "Minutes")))
16965 (defcustom org-image-actual-width t
16966 "Should we use the actual width of images when inlining them?
16968 When set to `t', always use the image width.
16970 When set to a number, use imagemagick (when available) to set
16971 the image's width to this value.
16973 When set to a number in a list, try to get the width from the
16974 #+ATTR.* keyword if it matches a width specification like
16975 width=\"[0-9]+\", and fall back on that number if none is found.
16977 When set to nil, try to get the width from an #+ATTR.* keyword
16978 and fall back on the original width if none is found.
16980 This requires Emacs >= 24.1, build with imagemagick support."
16981 :group 'org-appearance
16982 :version "24.3"
16983 :type '(choice
16984 (const :tag "Use the image width" t)
16985 (integer :tag "Use a number of pixels")
16986 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16987 (const :tag "Use #+ATTR* or don't resize" nil)))
16989 (defun org-duration-string-to-minutes (s &optional output-to-string)
16990 "Convert a duration string S to minutes.
16992 A bare number is interpreted as minutes, modifiers can be set by
16993 customizing `org-effort-durations' (which see).
16995 Entries containing a colon are interpreted as H:MM by
16996 `org-hh:mm-string-to-minutes'."
16997 (let ((result 0)
16998 (re (concat "\\([0-9.]+\\) *\\("
16999 (regexp-opt (mapcar 'car org-effort-durations))
17000 "\\)")))
17001 (while (string-match re s)
17002 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17003 (string-to-number (match-string 1 s))))
17004 (setq s (replace-match "" nil t s)))
17005 (setq result (floor result))
17006 (incf result (org-hh:mm-string-to-minutes s))
17007 (if output-to-string (number-to-string result) result)))
17009 ;;;; Files
17011 (defun org-save-all-org-buffers ()
17012 "Save all Org-mode buffers without user confirmation."
17013 (interactive)
17014 (message "Saving all Org-mode buffers...")
17015 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17016 (when (featurep 'org-id) (org-id-locations-save))
17017 (message "Saving all Org-mode buffers... done"))
17019 (defun org-revert-all-org-buffers ()
17020 "Revert all Org-mode buffers.
17021 Prompt for confirmation when there are unsaved changes.
17022 Be sure you know what you are doing before letting this function
17023 overwrite your changes.
17025 This function is useful in a setup where one tracks org files
17026 with a version control system, to revert on one machine after pulling
17027 changes from another. I believe the procedure must be like this:
17029 1. M-x org-save-all-org-buffers
17030 2. Pull changes from the other machine, resolve conflicts
17031 3. M-x org-revert-all-org-buffers"
17032 (interactive)
17033 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17034 (error "Abort"))
17035 (save-excursion
17036 (save-window-excursion
17037 (mapc
17038 (lambda (b)
17039 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17040 (with-current-buffer b buffer-file-name))
17041 (org-pop-to-buffer-same-window b)
17042 (revert-buffer t 'no-confirm)))
17043 (buffer-list))
17044 (when (and (featurep 'org-id) org-id-track-globally)
17045 (org-id-locations-load)))))
17047 ;;;; Agenda files
17049 ;;;###autoload
17050 (defun org-switchb (&optional arg)
17051 "Switch between Org buffers.
17052 With one prefix argument, restrict available buffers to files.
17053 With two prefix arguments, restrict available buffers to agenda files.
17055 Defaults to `iswitchb' for buffer name completion.
17056 Set `org-completion-use-ido' to make it use ido instead."
17057 (interactive "P")
17058 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17059 ((equal arg '(16)) (org-buffer-list 'agenda))
17060 (t (org-buffer-list))))
17061 (org-completion-use-iswitchb org-completion-use-iswitchb)
17062 (org-completion-use-ido org-completion-use-ido))
17063 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17064 (setq org-completion-use-iswitchb t))
17065 (org-pop-to-buffer-same-window
17066 (org-icompleting-read "Org buffer: "
17067 (mapcar 'list (mapcar 'buffer-name blist))
17068 nil t))))
17070 ;;; Define some older names previously used for this functionality
17071 ;;;###autoload
17072 (defalias 'org-ido-switchb 'org-switchb)
17073 ;;;###autoload
17074 (defalias 'org-iswitchb 'org-switchb)
17076 (defun org-buffer-list (&optional predicate exclude-tmp)
17077 "Return a list of Org buffers.
17078 PREDICATE can be `export', `files' or `agenda'.
17080 export restrict the list to Export buffers.
17081 files restrict the list to buffers visiting Org files.
17082 agenda restrict the list to buffers visiting agenda files.
17084 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17085 (let* ((bfn nil)
17086 (agenda-files (and (eq predicate 'agenda)
17087 (mapcar 'file-truename (org-agenda-files t))))
17088 (filter
17089 (cond
17090 ((eq predicate 'files)
17091 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17092 ((eq predicate 'export)
17093 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17094 ((eq predicate 'agenda)
17095 (lambda (b)
17096 (with-current-buffer b
17097 (and (derived-mode-p 'org-mode)
17098 (setq bfn (buffer-file-name b))
17099 (member (file-truename bfn) agenda-files)))))
17100 (t (lambda (b) (with-current-buffer b
17101 (or (derived-mode-p 'org-mode)
17102 (string-match "\*Org .*Export"
17103 (buffer-name b)))))))))
17104 (delq nil
17105 (mapcar
17106 (lambda(b)
17107 (if (and (funcall filter b)
17108 (or (not exclude-tmp)
17109 (not (string-match "tmp" (buffer-name b)))))
17111 nil))
17112 (buffer-list)))))
17114 (defun org-agenda-files (&optional unrestricted archives)
17115 "Get the list of agenda files.
17116 Optional UNRESTRICTED means return the full list even if a restriction
17117 is currently in place.
17118 When ARCHIVES is t, include all archive files that are really being
17119 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17120 `org-agenda-archives-mode' is t."
17121 (let ((files
17122 (cond
17123 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17124 ((stringp org-agenda-files) (org-read-agenda-file-list))
17125 ((listp org-agenda-files) org-agenda-files)
17126 (t (error "Invalid value of `org-agenda-files'")))))
17127 (setq files (apply 'append
17128 (mapcar (lambda (f)
17129 (if (file-directory-p f)
17130 (directory-files
17131 f t org-agenda-file-regexp)
17132 (list f)))
17133 files)))
17134 (when org-agenda-skip-unavailable-files
17135 (setq files (delq nil
17136 (mapcar (function
17137 (lambda (file)
17138 (and (file-readable-p file) file)))
17139 files))))
17140 (when (or (eq archives t)
17141 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17142 (setq files (org-add-archive-files files)))
17143 files))
17145 (defun org-agenda-file-p (&optional file)
17146 "Return non-nil, if FILE is an agenda file.
17147 If FILE is omitted, use the file associated with the current
17148 buffer."
17149 (member (or file (buffer-file-name))
17150 (org-agenda-files t)))
17152 (defun org-edit-agenda-file-list ()
17153 "Edit the list of agenda files.
17154 Depending on setup, this either uses customize to edit the variable
17155 `org-agenda-files', or it visits the file that is holding the list. In the
17156 latter case, the buffer is set up in a way that saving it automatically kills
17157 the buffer and restores the previous window configuration."
17158 (interactive)
17159 (if (stringp org-agenda-files)
17160 (let ((cw (current-window-configuration)))
17161 (find-file org-agenda-files)
17162 (org-set-local 'org-window-configuration cw)
17163 (org-add-hook 'after-save-hook
17164 (lambda ()
17165 (set-window-configuration
17166 (prog1 org-window-configuration
17167 (kill-buffer (current-buffer))))
17168 (org-install-agenda-files-menu)
17169 (message "New agenda file list installed"))
17170 nil 'local)
17171 (message "%s" (substitute-command-keys
17172 "Edit list and finish with \\[save-buffer]")))
17173 (customize-variable 'org-agenda-files)))
17175 (defun org-store-new-agenda-file-list (list)
17176 "Set new value for the agenda file list and save it correctly."
17177 (if (stringp org-agenda-files)
17178 (let ((fe (org-read-agenda-file-list t)) b u)
17179 (while (setq b (find-buffer-visiting org-agenda-files))
17180 (kill-buffer b))
17181 (with-temp-file org-agenda-files
17182 (insert
17183 (mapconcat
17184 (lambda (f) ;; Keep un-expanded entries.
17185 (if (setq u (assoc f fe))
17186 (cdr u)
17188 list "\n")
17189 "\n")))
17190 (let ((org-mode-hook nil) (org-inhibit-startup t)
17191 (org-insert-mode-line-in-empty-file nil))
17192 (setq org-agenda-files list)
17193 (customize-save-variable 'org-agenda-files org-agenda-files))))
17195 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17196 "Read the list of agenda files from a file.
17197 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17198 filenames, used by `org-store-new-agenda-file-list' to write back
17199 un-expanded file names."
17200 (when (file-directory-p org-agenda-files)
17201 (error "`org-agenda-files' cannot be a single directory"))
17202 (when (stringp org-agenda-files)
17203 (with-temp-buffer
17204 (insert-file-contents org-agenda-files)
17205 (mapcar
17206 (lambda (f)
17207 (let ((e (expand-file-name (substitute-in-file-name f)
17208 org-directory)))
17209 (if pair-with-expansion
17210 (cons e f)
17211 e)))
17212 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17214 ;;;###autoload
17215 (defun org-cycle-agenda-files ()
17216 "Cycle through the files in `org-agenda-files'.
17217 If the current buffer visits an agenda file, find the next one in the list.
17218 If the current buffer does not, find the first agenda file."
17219 (interactive)
17220 (let* ((fs (org-agenda-files t))
17221 (files (append fs (list (car fs))))
17222 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17223 file)
17224 (unless files (error "No agenda files"))
17225 (catch 'exit
17226 (while (setq file (pop files))
17227 (if (equal (file-truename file) tcf)
17228 (when (car files)
17229 (find-file (car files))
17230 (throw 'exit t))))
17231 (find-file (car fs)))
17232 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17234 (defun org-agenda-file-to-front (&optional to-end)
17235 "Move/add the current file to the top of the agenda file list.
17236 If the file is not present in the list, it is added to the front. If it is
17237 present, it is moved there. With optional argument TO-END, add/move to the
17238 end of the list."
17239 (interactive "P")
17240 (let ((org-agenda-skip-unavailable-files nil)
17241 (file-alist (mapcar (lambda (x)
17242 (cons (file-truename x) x))
17243 (org-agenda-files t)))
17244 (ctf (file-truename
17245 (or buffer-file-name
17246 (error "Please save the current buffer to a file"))))
17247 x had)
17248 (setq x (assoc ctf file-alist) had x)
17250 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17251 (if to-end
17252 (setq file-alist (append (delq x file-alist) (list x)))
17253 (setq file-alist (cons x (delq x file-alist))))
17254 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17255 (org-install-agenda-files-menu)
17256 (message "File %s to %s of agenda file list"
17257 (if had "moved" "added") (if to-end "end" "front"))))
17259 (defun org-remove-file (&optional file)
17260 "Remove current file from the list of files in variable `org-agenda-files'.
17261 These are the files which are being checked for agenda entries.
17262 Optional argument FILE means use this file instead of the current."
17263 (interactive)
17264 (let* ((org-agenda-skip-unavailable-files nil)
17265 (file (or file buffer-file-name
17266 (error "Current buffer does not visit a file")))
17267 (true-file (file-truename file))
17268 (afile (abbreviate-file-name file))
17269 (files (delq nil (mapcar
17270 (lambda (x)
17271 (if (equal true-file
17272 (file-truename x))
17273 nil x))
17274 (org-agenda-files t)))))
17275 (if (not (= (length files) (length (org-agenda-files t))))
17276 (progn
17277 (org-store-new-agenda-file-list files)
17278 (org-install-agenda-files-menu)
17279 (message "Removed file: %s" afile))
17280 (message "File was not in list: %s (not removed)" afile))))
17282 (defun org-file-menu-entry (file)
17283 (vector file (list 'find-file file) t))
17285 (defun org-check-agenda-file (file)
17286 "Make sure FILE exists. If not, ask user what to do."
17287 (when (not (file-exists-p file))
17288 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17289 (abbreviate-file-name file))
17290 (let ((r (downcase (read-char-exclusive))))
17291 (cond
17292 ((equal r ?r)
17293 (org-remove-file file)
17294 (throw 'nextfile t))
17295 (t (error "Abort"))))))
17297 (defun org-get-agenda-file-buffer (file)
17298 "Get a buffer visiting FILE. If the buffer needs to be created, add
17299 it to the list of buffers which might be released later."
17300 (let ((buf (org-find-base-buffer-visiting file)))
17301 (if buf
17302 buf ; just return it
17303 ;; Make a new buffer and remember it
17304 (setq buf (find-file-noselect file))
17305 (if buf (push buf org-agenda-new-buffers))
17306 buf)))
17308 (defun org-release-buffers (blist)
17309 "Release all buffers in list, asking the user for confirmation when needed.
17310 When a buffer is unmodified, it is just killed. When modified, it is saved
17311 \(if the user agrees) and then killed."
17312 (let (buf file)
17313 (while (setq buf (pop blist))
17314 (setq file (buffer-file-name buf))
17315 (when (and (buffer-modified-p buf)
17316 file
17317 (y-or-n-p (format "Save file %s? " file)))
17318 (with-current-buffer buf (save-buffer)))
17319 (kill-buffer buf))))
17321 (defun org-agenda-prepare-buffers (files)
17322 "Create buffers for all agenda files, protect archived trees and comments."
17323 (interactive)
17324 (let ((pa '(:org-archived t))
17325 (pc '(:org-comment t))
17326 (pall '(:org-archived t :org-comment t))
17327 (inhibit-read-only t)
17328 (rea (concat ":" org-archive-tag ":"))
17329 bmp file re)
17330 (save-excursion
17331 (save-restriction
17332 (while (setq file (pop files))
17333 (catch 'nextfile
17334 (if (bufferp file)
17335 (set-buffer file)
17336 (org-check-agenda-file file)
17337 (set-buffer (org-get-agenda-file-buffer file)))
17338 (widen)
17339 (setq bmp (buffer-modified-p))
17340 (org-refresh-category-properties)
17341 (setq org-todo-keywords-for-agenda
17342 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17343 (setq org-done-keywords-for-agenda
17344 (append org-done-keywords-for-agenda org-done-keywords))
17345 (setq org-todo-keyword-alist-for-agenda
17346 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17347 (setq org-drawers-for-agenda
17348 (append org-drawers-for-agenda org-drawers))
17349 (setq org-tag-alist-for-agenda
17350 (append org-tag-alist-for-agenda org-tag-alist))
17352 (save-excursion
17353 (remove-text-properties (point-min) (point-max) pall)
17354 (when org-agenda-skip-archived-trees
17355 (goto-char (point-min))
17356 (while (re-search-forward rea nil t)
17357 (if (org-at-heading-p t)
17358 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17359 (goto-char (point-min))
17360 (setq re (format org-heading-keyword-regexp-format
17361 org-comment-string))
17362 (while (re-search-forward re nil t)
17363 (add-text-properties
17364 (match-beginning 0) (org-end-of-subtree t) pc)))
17365 (set-buffer-modified-p bmp)))))
17366 (setq org-todo-keywords-for-agenda
17367 (org-uniquify org-todo-keywords-for-agenda))
17368 (setq org-todo-keyword-alist-for-agenda
17369 (org-uniquify org-todo-keyword-alist-for-agenda)
17370 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17372 ;;;; Embedded LaTeX
17374 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17375 "Keymap for the minor `org-cdlatex-mode'.")
17377 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17378 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17379 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17380 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17381 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17383 (defvar org-cdlatex-texmathp-advice-is-done nil
17384 "Flag remembering if we have applied the advice to texmathp already.")
17386 (define-minor-mode org-cdlatex-mode
17387 "Toggle the minor `org-cdlatex-mode'.
17388 This mode supports entering LaTeX environment and math in LaTeX fragments
17389 in Org-mode.
17390 \\{org-cdlatex-mode-map}"
17391 nil " OCDL" nil
17392 (when org-cdlatex-mode
17393 (require 'cdlatex)
17394 (run-hooks 'cdlatex-mode-hook)
17395 (cdlatex-compute-tables))
17396 (unless org-cdlatex-texmathp-advice-is-done
17397 (setq org-cdlatex-texmathp-advice-is-done t)
17398 (defadvice texmathp (around org-math-always-on activate)
17399 "Always return t in org-mode buffers.
17400 This is because we want to insert math symbols without dollars even outside
17401 the LaTeX math segments. If Orgmode thinks that point is actually inside
17402 an embedded LaTeX fragment, let texmathp do its job.
17403 \\[org-cdlatex-mode-map]"
17404 (interactive)
17405 (let (p)
17406 (cond
17407 ((not (derived-mode-p 'org-mode)) ad-do-it)
17408 ((eq this-command 'cdlatex-math-symbol)
17409 (setq ad-return-value t
17410 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17412 (let ((p (org-inside-LaTeX-fragment-p)))
17413 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17414 (setq ad-return-value t
17415 texmathp-why '("Org-mode embedded math" . 0))
17416 (if p ad-do-it)))))))))
17418 (defun turn-on-org-cdlatex ()
17419 "Unconditionally turn on `org-cdlatex-mode'."
17420 (org-cdlatex-mode 1))
17422 (defun org-inside-LaTeX-fragment-p ()
17423 "Test if point is inside a LaTeX fragment.
17424 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17425 sequence appearing also before point.
17426 Even though the matchers for math are configurable, this function assumes
17427 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17428 delimiters are skipped when they have been removed by customization.
17429 The return value is nil, or a cons cell with the delimiter and the
17430 position of this delimiter.
17432 This function does a reasonably good job, but can locally be fooled by
17433 for example currency specifications. For example it will assume being in
17434 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17435 fragments that are properly closed, but during editing, we have to live
17436 with the uncertainty caused by missing closing delimiters. This function
17437 looks only before point, not after."
17438 (catch 'exit
17439 (let ((pos (point))
17440 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17441 (lim (progn
17442 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17443 (point)))
17444 dd-on str (start 0) m re)
17445 (goto-char pos)
17446 (when dodollar
17447 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17448 re (nth 1 (assoc "$" org-latex-regexps)))
17449 (while (string-match re str start)
17450 (cond
17451 ((= (match-end 0) (length str))
17452 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17453 ((= (match-end 0) (- (length str) 5))
17454 (throw 'exit nil))
17455 (t (setq start (match-end 0))))))
17456 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17457 (goto-char pos)
17458 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17459 (and (match-beginning 2) (throw 'exit nil))
17460 ;; count $$
17461 (while (re-search-backward "\\$\\$" lim t)
17462 (setq dd-on (not dd-on)))
17463 (goto-char pos)
17464 (if dd-on (cons "$$" m))))))
17466 (defun org-inside-latex-macro-p ()
17467 "Is point inside a LaTeX macro or its arguments?"
17468 (save-match-data
17469 (org-in-regexp
17470 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17472 (defun org-try-cdlatex-tab ()
17473 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17474 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17475 - inside a LaTeX fragment, or
17476 - after the first word in a line, where an abbreviation expansion could
17477 insert a LaTeX environment."
17478 (when org-cdlatex-mode
17479 (cond
17480 ;; Before any word on the line: No expansion possible.
17481 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17482 ;; Just after first word on the line: Expand it. Make sure it
17483 ;; cannot happen on headlines, though.
17484 ((save-excursion
17485 (skip-chars-backward "a-zA-Z0-9*")
17486 (skip-chars-backward " \t")
17487 (and (bolp) (not (org-at-heading-p))))
17488 (cdlatex-tab) t)
17489 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17491 (defun org-cdlatex-underscore-caret (&optional arg)
17492 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17493 Revert to the normal definition outside of these fragments."
17494 (interactive "P")
17495 (if (org-inside-LaTeX-fragment-p)
17496 (call-interactively 'cdlatex-sub-superscript)
17497 (let (org-cdlatex-mode)
17498 (call-interactively (key-binding (vector last-input-event))))))
17500 (defun org-cdlatex-math-modify (&optional arg)
17501 "Execute `cdlatex-math-modify' in LaTeX fragments.
17502 Revert to the normal definition outside of these fragments."
17503 (interactive "P")
17504 (if (org-inside-LaTeX-fragment-p)
17505 (call-interactively 'cdlatex-math-modify)
17506 (let (org-cdlatex-mode)
17507 (call-interactively (key-binding (vector last-input-event))))))
17509 (defvar org-latex-fragment-image-overlays nil
17510 "List of overlays carrying the images of latex fragments.")
17511 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17513 (defun org-remove-latex-fragment-image-overlays ()
17514 "Remove all overlays with LaTeX fragment images in current buffer."
17515 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17516 (setq org-latex-fragment-image-overlays nil))
17518 (defun org-preview-latex-fragment (&optional subtree)
17519 "Preview the LaTeX fragment at point, or all locally or globally.
17520 If the cursor is in a LaTeX fragment, create the image and overlay
17521 it over the source code. If there is no fragment at point, display
17522 all fragments in the current text, from one headline to the next. With
17523 prefix SUBTREE, display all fragments in the current subtree. With a
17524 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17525 the cursor is before the first headline,
17526 display all fragments in the buffer.
17527 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17528 (interactive "P")
17529 (unless buffer-file-name
17530 (error "Can't preview LaTeX fragment in a non-file buffer"))
17531 (org-remove-latex-fragment-image-overlays)
17532 (save-excursion
17533 (save-restriction
17534 (let (beg end at msg)
17535 (cond
17536 ((or (equal subtree '(16))
17537 (not (save-excursion
17538 (re-search-backward org-outline-regexp-bol nil t))))
17539 (setq beg (point-min) end (point-max)
17540 msg "Creating images for buffer...%s"))
17541 ((equal subtree '(4))
17542 (org-back-to-heading)
17543 (setq beg (point) end (org-end-of-subtree t)
17544 msg "Creating images for subtree...%s"))
17546 (if (setq at (org-inside-LaTeX-fragment-p))
17547 (goto-char (max (point-min) (- (cdr at) 2)))
17548 (org-back-to-heading))
17549 (setq beg (point) end (progn (outline-next-heading) (point))
17550 msg (if at "Creating image...%s"
17551 "Creating images for entry...%s"))))
17552 (message msg "")
17553 (narrow-to-region beg end)
17554 (goto-char beg)
17555 (org-format-latex
17556 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17557 (file-name-nondirectory
17558 buffer-file-name)))
17559 default-directory 'overlays msg at 'forbuffer
17560 org-latex-create-formula-image-program)
17561 (message msg "done. Use `C-c C-c' to remove images.")))))
17563 (defvar org-latex-regexps
17564 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17565 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17566 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17567 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17568 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17569 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17570 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17571 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17572 "Regular expressions for matching embedded LaTeX.")
17574 (defvar org-export-have-math nil) ;; dynamic scoping
17575 (defun org-format-latex (prefix &optional dir overlays msg at
17576 forbuffer processing-type)
17577 "Replace LaTeX fragments with links to an image, and produce images.
17578 Some of the options can be changed using the variable
17579 `org-format-latex-options'."
17580 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17581 (let* ((prefixnodir (file-name-nondirectory prefix))
17582 (absprefix (expand-file-name prefix dir))
17583 (todir (file-name-directory absprefix))
17584 (opt org-format-latex-options)
17585 (optnew org-format-latex-options)
17586 (matchers (plist-get opt :matchers))
17587 (re-list org-latex-regexps)
17588 (org-format-latex-header-extra
17589 (plist-get (org-infile-export-plist) :latex-header-extra))
17590 (cnt 0) txt hash link beg end re e checkdir
17591 string
17592 m n block-type block linkfile movefile ov)
17593 ;; Check the different regular expressions
17594 (while (setq e (pop re-list))
17595 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17596 block (if block-type "\n\n" ""))
17597 (when (member m matchers)
17598 (goto-char (point-min))
17599 (while (re-search-forward re nil t)
17600 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17601 (not (get-text-property (match-beginning n)
17602 'org-protected))
17603 (or (not overlays)
17604 (not (eq (get-char-property (match-beginning n)
17605 'org-overlay-type)
17606 'org-latex-overlay))))
17607 (setq org-export-have-math t)
17608 (cond
17609 ((eq processing-type 'verbatim)
17610 ;; Leave the text verbatim, just protect it
17611 (add-text-properties (match-beginning n) (match-end n)
17612 '(org-protected t)))
17613 ((eq processing-type 'mathjax)
17614 ;; Prepare for MathJax processing
17615 (setq string (match-string n))
17616 (if (member m '("$" "$1"))
17617 (save-excursion
17618 (delete-region (match-beginning n) (match-end n))
17619 (goto-char (match-beginning n))
17620 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17621 "\\)")
17622 '(org-protected t))))
17623 (add-text-properties (match-beginning n) (match-end n)
17624 '(org-protected t))))
17625 ((or (eq processing-type 'dvipng)
17626 (eq processing-type 'imagemagick))
17627 ;; Process to an image
17628 (setq txt (match-string n)
17629 beg (match-beginning n) end (match-end n)
17630 cnt (1+ cnt))
17631 (let ((face (face-at-point))
17632 (fg (plist-get opt :foreground))
17633 (bg (plist-get opt :background))
17634 print-length print-level) ; make sure full list is printed
17635 (when forbuffer
17636 ; Get the colors from the face at point
17637 (goto-char beg)
17638 (when (eq fg 'auto)
17639 (setq fg (face-attribute face :foreground nil 'default)))
17640 (when (eq bg 'auto)
17641 (setq bg (face-attribute face :background nil 'default)))
17642 (setq optnew (copy-sequence opt))
17643 (plist-put optnew :foreground fg)
17644 (plist-put optnew :background bg))
17645 (setq hash (sha1 (prin1-to-string
17646 (list org-format-latex-header
17647 org-format-latex-header-extra
17648 org-export-latex-default-packages-alist
17649 org-export-latex-packages-alist
17650 org-format-latex-options
17651 forbuffer txt fg bg)))
17652 linkfile (format "%s_%s.png" prefix hash)
17653 movefile (format "%s_%s.png" absprefix hash)))
17654 (setq link (concat block "[[file:" linkfile "]]" block))
17655 (if msg (message msg cnt))
17656 (goto-char beg)
17657 (unless checkdir ; make sure the directory exists
17658 (setq checkdir t)
17659 (or (file-directory-p todir) (make-directory todir t)))
17660 (unless (file-exists-p movefile)
17661 (org-create-formula-image
17662 txt movefile optnew forbuffer processing-type))
17663 (if overlays
17664 (progn
17665 (mapc (lambda (o)
17666 (if (eq (overlay-get o 'org-overlay-type)
17667 'org-latex-overlay)
17668 (delete-overlay o)))
17669 (overlays-in beg end))
17670 (setq ov (make-overlay beg end))
17671 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17672 (if (featurep 'xemacs)
17673 (progn
17674 (overlay-put ov 'invisible t)
17675 (overlay-put
17676 ov 'end-glyph
17677 (make-glyph (vector 'png :file movefile))))
17678 (overlay-put
17679 ov 'display
17680 (list 'image :type 'png :file movefile :ascent 'center)))
17681 (push ov org-latex-fragment-image-overlays)
17682 (goto-char end))
17683 (delete-region beg end)
17684 (insert (org-add-props link
17685 (list 'org-latex-src
17686 (replace-regexp-in-string
17687 "\"" "" txt)
17688 'org-latex-src-embed-type
17689 (if block-type 'paragraph 'character))))))
17690 ((eq processing-type 'mathml)
17691 ;; Process to MathML
17692 (unless (save-match-data (org-format-latex-mathml-available-p))
17693 (error "LaTeX to MathML converter not configured"))
17694 (setq txt (match-string n)
17695 beg (match-beginning n) end (match-end n)
17696 cnt (1+ cnt))
17697 (if msg (message msg cnt))
17698 (goto-char beg)
17699 (delete-region beg end)
17700 (insert (org-format-latex-as-mathml
17701 txt block-type prefix dir)))
17703 (error "Unknown conversion type %s for latex fragments"
17704 processing-type)))))))))
17706 (defun org-create-math-formula (latex-frag &optional mathml-file)
17707 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17708 Use `org-latex-to-mathml-convert-command'. If the conversion is
17709 sucessful, return the portion between \"<math...> </math>\"
17710 elements otherwise return nil. When MATHML-FILE is specified,
17711 write the results in to that file. When invoked as an
17712 interactive command, prompt for LATEX-FRAG, with initial value
17713 set to the current active region and echo the results for user
17714 inspection."
17715 (interactive (list (let ((frag (when (org-region-active-p)
17716 (buffer-substring-no-properties
17717 (region-beginning) (region-end)))))
17718 (read-string "LaTeX Fragment: " frag nil frag))))
17719 (unless latex-frag (error "Invalid latex-frag"))
17720 (let* ((tmp-in-file (file-relative-name
17721 (make-temp-name (expand-file-name "ltxmathml-in"))))
17722 (ignore (write-region latex-frag nil tmp-in-file))
17723 (tmp-out-file (file-relative-name
17724 (make-temp-name (expand-file-name "ltxmathml-out"))))
17725 (cmd (format-spec
17726 org-latex-to-mathml-convert-command
17727 `((?j . ,(shell-quote-argument
17728 (expand-file-name org-latex-to-mathml-jar-file)))
17729 (?I . ,(shell-quote-argument tmp-in-file))
17730 (?o . ,(shell-quote-argument tmp-out-file)))))
17731 mathml shell-command-output)
17732 (when (org-called-interactively-p 'any)
17733 (unless (org-format-latex-mathml-available-p)
17734 (error "LaTeX to MathML converter not configured")))
17735 (message "Running %s" cmd)
17736 (setq shell-command-output (shell-command-to-string cmd))
17737 (setq mathml
17738 (when (file-readable-p tmp-out-file)
17739 (with-current-buffer (find-file-noselect tmp-out-file t)
17740 (goto-char (point-min))
17741 (when (re-search-forward
17742 (concat
17743 (regexp-quote
17744 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17745 "\\(.\\|\n\\)*"
17746 (regexp-quote "</math>")) nil t)
17747 (prog1 (match-string 0) (kill-buffer))))))
17748 (cond
17749 (mathml
17750 (setq mathml
17751 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17752 (when mathml-file
17753 (write-region mathml nil mathml-file))
17754 (when (org-called-interactively-p 'any)
17755 (message mathml)))
17756 ((message "LaTeX to MathML conversion failed")
17757 (message shell-command-output)))
17758 (delete-file tmp-in-file)
17759 (when (file-exists-p tmp-out-file)
17760 (delete-file tmp-out-file))
17761 mathml))
17763 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17764 prefix &optional dir)
17765 "Use `org-create-math-formula' but check local cache first."
17766 (let* ((absprefix (expand-file-name prefix dir))
17767 (print-length nil) (print-level nil)
17768 (formula-id (concat
17769 "formula-"
17770 (sha1
17771 (prin1-to-string
17772 (list latex-frag
17773 org-latex-to-mathml-convert-command)))))
17774 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17775 (formula-cache-dir (file-name-directory formula-cache)))
17777 (unless (file-directory-p formula-cache-dir)
17778 (make-directory formula-cache-dir t))
17780 (unless (file-exists-p formula-cache)
17781 (org-create-math-formula latex-frag formula-cache))
17783 (if (file-exists-p formula-cache)
17784 ;; Successful conversion. Return the link to MathML file.
17785 (org-add-props
17786 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17787 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17788 'org-latex-src-embed-type (if latex-frag-type
17789 'paragraph 'character)))
17790 ;; Failed conversion. Return the LaTeX fragment verbatim
17791 (add-text-properties
17792 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17793 latex-frag)))
17795 (defun org-create-formula-image (string tofile options buffer &optional type)
17796 "Create an image from LaTeX source using dvipng or convert.
17797 This function calls either `org-create-formula-image-with-dvipng'
17798 or `org-create-formula-image-with-imagemagick' depending on the
17799 value of `org-latex-create-formula-image-program' or on the value
17800 of the optional TYPE variable.
17802 Note: ultimately these two function should be combined as they
17803 share a good deal of logic."
17804 (org-check-external-command
17805 "latex" "needed to convert LaTeX fragments to images")
17806 (funcall
17807 (case (or type org-latex-create-formula-image-program)
17808 ('dvipng
17809 (org-check-external-command
17810 "dvipng" "needed to convert LaTeX fragments to images")
17811 #'org-create-formula-image-with-dvipng)
17812 ('imagemagick
17813 (org-check-external-command
17814 "convert" "you need to install imagemagick")
17815 #'org-create-formula-image-with-imagemagick)
17816 (t (error
17817 "invalid value of `org-latex-create-formula-image-program'")))
17818 string tofile options buffer))
17820 ;; This function borrows from Ganesh Swami's latex2png.el
17821 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17822 "This calls dvipng."
17823 (require 'org-latex)
17824 (let* ((tmpdir (if (featurep 'xemacs)
17825 (temp-directory)
17826 temporary-file-directory))
17827 (texfilebase (make-temp-name
17828 (expand-file-name "orgtex" tmpdir)))
17829 (texfile (concat texfilebase ".tex"))
17830 (dvifile (concat texfilebase ".dvi"))
17831 (pngfile (concat texfilebase ".png"))
17832 (fnh (if (featurep 'xemacs)
17833 (font-height (face-font 'default))
17834 (face-attribute 'default :height nil)))
17835 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17836 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17837 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17838 "Black"))
17839 (bg (or (plist-get options (if buffer :background :html-background))
17840 "Transparent")))
17841 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17842 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17843 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17844 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17845 (with-temp-file texfile
17846 (insert (org-splice-latex-header
17847 org-format-latex-header
17848 org-export-latex-default-packages-alist
17849 org-export-latex-packages-alist t
17850 org-format-latex-header-extra))
17851 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17852 (require 'org-latex)
17853 (org-export-latex-fix-inputenc))
17854 (let ((dir default-directory))
17855 (condition-case nil
17856 (progn
17857 (cd tmpdir)
17858 (call-process "latex" nil nil nil texfile))
17859 (error nil))
17860 (cd dir))
17861 (if (not (file-exists-p dvifile))
17862 (progn (message "Failed to create dvi file from %s" texfile) nil)
17863 (condition-case nil
17864 (if (featurep 'xemacs)
17865 (call-process "dvipng" nil nil nil
17866 "-fg" fg "-bg" bg
17867 "-T" "tight"
17868 "-o" pngfile
17869 dvifile)
17870 (call-process "dvipng" nil nil nil
17871 "-fg" fg "-bg" bg
17872 "-D" dpi
17873 ;;"-x" scale "-y" scale
17874 "-T" "tight"
17875 "-o" pngfile
17876 dvifile))
17877 (error nil))
17878 (if (not (file-exists-p pngfile))
17879 (if org-format-latex-signal-error
17880 (error "Failed to create png file from %s" texfile)
17881 (message "Failed to create png file from %s" texfile)
17882 nil)
17883 ;; Use the requested file name and clean up
17884 (copy-file pngfile tofile 'replace)
17885 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17886 (if (file-exists-p (concat texfilebase e))
17887 (delete-file (concat texfilebase e))))
17888 pngfile))))
17890 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17891 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17892 "This calls convert, which is included into imagemagick."
17893 (require 'org-latex)
17894 (let* ((tmpdir (if (featurep 'xemacs)
17895 (temp-directory)
17896 temporary-file-directory))
17897 (texfilebase (make-temp-name
17898 (expand-file-name "orgtex" tmpdir)))
17899 (texfile (concat texfilebase ".tex"))
17900 (pdffile (concat texfilebase ".pdf"))
17901 (pngfile (concat texfilebase ".png"))
17902 (fnh (if (featurep 'xemacs)
17903 (font-height (face-font 'default))
17904 (face-attribute 'default :height nil)))
17905 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17906 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17907 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17908 "black"))
17909 (bg (or (plist-get options (if buffer :background :html-background))
17910 "white")))
17911 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17912 (setq fg (org-latex-color-format fg)))
17913 (if (eq bg 'default) (setq bg (org-latex-color :background))
17914 (setq bg (org-latex-color-format
17915 (if (string= bg "Transparent") "white" bg))))
17916 (with-temp-file texfile
17917 (insert (org-splice-latex-header
17918 org-format-latex-header
17919 org-export-latex-default-packages-alist
17920 org-export-latex-packages-alist t
17921 org-format-latex-header-extra))
17922 (insert "\n\\begin{document}\n"
17923 "\\definecolor{fg}{rgb}{" fg "}\n"
17924 "\\definecolor{bg}{rgb}{" bg "}\n"
17925 "\n\\pagecolor{bg}\n"
17926 "\n{\\color{fg}\n"
17927 string
17928 "\n}\n"
17929 "\n\\end{document}\n" )
17930 (require 'org-latex)
17931 (org-export-latex-fix-inputenc))
17932 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17933 (condition-case nil
17934 (progn
17935 (cd tmpdir)
17936 (setq cmds org-latex-to-pdf-process)
17937 (while cmds
17938 (setq latex-frags-cmds (pop cmds))
17939 (if (listp latex-frags-cmds)
17940 (setq cmds nil)
17941 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17942 (while latex-frags-cmds
17943 (setq cmd (pop latex-frags-cmds))
17944 (while (string-match "%b" cmd)
17945 (setq cmd (replace-match
17946 (save-match-data
17947 (shell-quote-argument texfile))
17948 t t cmd)))
17949 (while (string-match "%f" cmd)
17950 (setq cmd (replace-match
17951 (save-match-data
17952 (shell-quote-argument (file-name-nondirectory texfile)))
17953 t t cmd)))
17954 (while (string-match "%o" cmd)
17955 (setq cmd (replace-match
17956 (save-match-data
17957 (shell-quote-argument (file-name-directory texfile)))
17958 t t cmd)))
17959 (setq cmd (split-string cmd))
17960 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17961 (error nil))
17962 (cd dir))
17963 (if (not (file-exists-p pdffile))
17964 (progn (message "Failed to create pdf file from %s" texfile) nil)
17965 (condition-case nil
17966 (if (featurep 'xemacs)
17967 (call-process "convert" nil nil nil
17968 "-density" "96"
17969 "-trim"
17970 "-antialias"
17971 pdffile
17972 "-quality" "100"
17973 ;; "-sharpen" "0x1.0"
17974 pngfile)
17975 (call-process "convert" nil nil nil
17976 "-density" dpi
17977 "-trim"
17978 "-antialias"
17979 pdffile
17980 "-quality" "100"
17981 ; "-sharpen" "0x1.0"
17982 pngfile))
17983 (error nil))
17984 (if (not (file-exists-p pngfile))
17985 (if org-format-latex-signal-error
17986 (error "Failed to create png file from %s" texfile)
17987 (message "Failed to create png file from %s" texfile)
17988 nil)
17989 ;; Use the requested file name and clean up
17990 (copy-file pngfile tofile 'replace)
17991 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17992 (if (file-exists-p (concat texfilebase e))
17993 (delete-file (concat texfilebase e))))
17994 pngfile))))
17996 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17997 "Fill a LaTeX header template TPL.
17998 In the template, the following place holders will be recognized:
18000 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18001 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18002 [PACKAGES] \\usepackage statements for PKG
18003 [NO-PACKAGES] do not include PKG
18004 [EXTRA] the string EXTRA
18005 [NO-EXTRA] do not include EXTRA
18007 For backward compatibility, if both the positive and the negative place
18008 holder is missing, the positive one (without the \"NO-\") will be
18009 assumed to be present at the end of the template.
18010 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18011 EXTRA is a string.
18012 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18013 (let (rpl (end ""))
18014 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18015 (setq rpl (if (or (match-end 1) (not def-pkg))
18016 "" (org-latex-packages-to-string def-pkg snippets-p t))
18017 tpl (replace-match rpl t t tpl))
18018 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18020 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18021 (setq rpl (if (or (match-end 1) (not pkg))
18022 "" (org-latex-packages-to-string pkg snippets-p t))
18023 tpl (replace-match rpl t t tpl))
18024 (if pkg (setq end
18025 (concat end "\n"
18026 (org-latex-packages-to-string pkg snippets-p)))))
18028 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18029 (setq rpl (if (or (match-end 1) (not extra))
18030 "" (concat extra "\n"))
18031 tpl (replace-match rpl t t tpl))
18032 (if (and extra (string-match "\\S-" extra))
18033 (setq end (concat end "\n" extra))))
18035 (if (string-match "\\S-" end)
18036 (concat tpl "\n" end)
18037 tpl)))
18039 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18040 "Turn an alist of packages into a string with the \\usepackage macros."
18041 (setq pkg (mapconcat (lambda(p)
18042 (cond
18043 ((stringp p) p)
18044 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18045 (format "%% Package %s omitted" (cadr p)))
18046 ((equal "" (car p))
18047 (format "\\usepackage{%s}" (cadr p)))
18049 (format "\\usepackage[%s]{%s}"
18050 (car p) (cadr p)))))
18052 "\n"))
18053 (if newline (concat pkg "\n") pkg))
18055 (defun org-dvipng-color (attr)
18056 "Return a RGB color specification for dvipng."
18057 (apply 'format "rgb %s %s %s"
18058 (mapcar 'org-normalize-color
18059 (if (featurep 'xemacs)
18060 (color-rgb-components
18061 (face-property 'default
18062 (cond ((eq attr :foreground) 'foreground)
18063 ((eq attr :background) 'background))))
18064 (color-values (face-attribute 'default attr nil))))))
18066 (defun org-dvipng-color-format (color-name)
18067 "Convert COLOR-NAME to a RGB color value for dvipng."
18068 (apply 'format "rgb %s %s %s"
18069 (mapcar 'org-normalize-color
18070 (color-values color-name))))
18072 (defun org-latex-color (attr)
18073 "Return a RGB color for the LaTeX color package."
18074 (apply 'format "%s,%s,%s"
18075 (mapcar 'org-normalize-color
18076 (if (featurep 'xemacs)
18077 (color-rgb-components
18078 (face-property 'default
18079 (cond ((eq attr :foreground) 'foreground)
18080 ((eq attr :background) 'background))))
18081 (color-values (face-attribute 'default attr nil))))))
18083 (defun org-latex-color-format (color-name)
18084 "Convert COLOR-NAME to a RGB color value."
18085 (apply 'format "%s,%s,%s"
18086 (mapcar 'org-normalize-color
18087 (color-values color-name))))
18089 (defun org-normalize-color (value)
18090 "Return string to be used as color value for an RGB component."
18091 (format "%g" (/ value 65535.0)))
18093 ;; Image display
18096 (defvar org-inline-image-overlays nil)
18097 (make-variable-buffer-local 'org-inline-image-overlays)
18099 (defun org-toggle-inline-images (&optional include-linked)
18100 "Toggle the display of inline images.
18101 INCLUDE-LINKED is passed to `org-display-inline-images'."
18102 (interactive "P")
18103 (if org-inline-image-overlays
18104 (progn
18105 (org-remove-inline-images)
18106 (message "Inline image display turned off"))
18107 (org-display-inline-images include-linked)
18108 (if (and (org-called-interactively-p)
18109 org-inline-image-overlays)
18110 (message "%d images displayed inline"
18111 (length org-inline-image-overlays))
18112 (message "No images to display inline"))))
18114 (defun org-redisplay-inline-images ()
18115 "Refresh the display of inline images."
18116 (interactive)
18117 (if (not org-inline-image-overlays)
18118 (org-toggle-inline-images)
18119 (org-toggle-inline-images)
18120 (org-toggle-inline-images)))
18122 (defun org-display-inline-images (&optional include-linked refresh beg end)
18123 "Display inline images.
18124 Normally only links without a description part are inlined, because this
18125 is how it will work for export. When INCLUDE-LINKED is set, also links
18126 with a description part will be inlined. This can be nice for a quick
18127 look at those images, but it does not reflect what exported files will look
18128 like.
18129 When REFRESH is set, refresh existing images between BEG and END.
18130 This will create new image displays only if necessary.
18131 BEG and END default to the buffer boundaries."
18132 (interactive "P")
18133 (unless refresh
18134 (org-remove-inline-images)
18135 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18136 (save-excursion
18137 (save-restriction
18138 (widen)
18139 (setq beg (or beg (point-min)) end (or end (point-max)))
18140 (goto-char beg)
18141 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18142 (substring (org-image-file-name-regexp) 0 -2)
18143 "\\)\\]" (if include-linked "" "\\]")))
18144 old file ov img type attrwidth width)
18145 (while (re-search-forward re end t)
18146 (setq old (get-char-property-and-overlay (match-beginning 1)
18147 'org-image-overlay)
18148 file (expand-file-name
18149 (concat (or (match-string 3) "") (match-string 4))))
18150 (when (image-type-available-p 'imagemagick)
18151 (setq attrwidth (if (or (listp org-image-actual-width)
18152 (null org-image-actual-width))
18153 (save-excursion
18154 (save-match-data
18155 (when (re-search-backward
18156 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18157 (save-excursion
18158 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18159 (string-to-number (match-string 1))))))
18160 width (cond ((eq org-image-actual-width t) nil)
18161 ((null org-image-actual-width) attrwidth)
18162 ((numberp org-image-actual-width)
18163 org-image-actual-width)
18164 ((listp org-image-actual-width)
18165 (or attrwidth (car org-image-actual-width))))
18166 type (if width 'imagemagick)))
18167 (when (file-exists-p file)
18168 (if (and (car-safe old) refresh)
18169 (image-refresh (overlay-get (cdr old) 'display))
18170 (setq img (save-match-data (create-image file type nil :width width)))
18171 (when img
18172 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18173 (overlay-put ov 'display img)
18174 (overlay-put ov 'face 'default)
18175 (overlay-put ov 'org-image-overlay t)
18176 (overlay-put ov 'modification-hooks
18177 (list 'org-display-inline-remove-overlay))
18178 (push ov org-inline-image-overlays)))))))))
18180 (define-obsolete-function-alias
18181 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18183 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18184 "Remove inline-display overlay if a corresponding region is modified."
18185 (let ((inhibit-modification-hooks t))
18186 (when (and ov after)
18187 (delete ov org-inline-image-overlays)
18188 (delete-overlay ov))))
18190 (defun org-remove-inline-images ()
18191 "Remove inline display of images."
18192 (interactive)
18193 (mapc 'delete-overlay org-inline-image-overlays)
18194 (setq org-inline-image-overlays nil))
18196 ;;;; Key bindings
18198 ;; Outline functions from `outline-mode-prefix-map'
18199 ;; that can be remapped in Org:
18200 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18201 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18202 (define-key org-mode-map [remap outline-forward-same-level]
18203 'org-forward-heading-same-level)
18204 (define-key org-mode-map [remap outline-backward-same-level]
18205 'org-backward-heading-same-level)
18206 (define-key org-mode-map [remap show-branches]
18207 'org-kill-note-or-show-branches)
18208 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18209 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18210 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18212 ;; Outline functions from `outline-mode-prefix-map' that can not
18213 ;; be remapped in Org:
18215 ;; - the column "key binding" shows whether the Outline function is still
18216 ;; available in Org mode on the same key that it has been bound to in
18217 ;; Outline mode:
18218 ;; - "overridden": key used for a different functionality in Org mode
18219 ;; - else: key still bound to the same Outline function in Org mode
18221 ;; | Outline function | key binding | Org replacement |
18222 ;; |------------------------------------+-------------+-----------------------|
18223 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18224 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18225 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18226 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18227 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18228 ;; | `show-entry' | overridden | no replacement |
18229 ;; | `show-children' | `C-c C-i' | visibility cycling |
18230 ;; | `show-branches' | `C-c C-k' | still same function |
18231 ;; | `show-subtree' | overridden | visibility cycling |
18232 ;; | `show-all' | overridden | no replacement |
18233 ;; | `hide-subtree' | overridden | visibility cycling |
18234 ;; | `hide-body' | overridden | no replacement |
18235 ;; | `hide-entry' | overridden | visibility cycling |
18236 ;; | `hide-leaves' | overridden | no replacement |
18237 ;; | `hide-sublevels' | overridden | no replacement |
18238 ;; | `hide-other' | overridden | no replacement |
18240 ;; Make `C-c C-x' a prefix key
18241 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18243 ;; TAB key with modifiers
18244 (org-defkey org-mode-map "\C-i" 'org-cycle)
18245 (org-defkey org-mode-map [(tab)] 'org-cycle)
18246 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18247 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18248 ;; The following line is necessary under Suse GNU/Linux
18249 (unless (featurep 'xemacs)
18250 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18251 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18252 (define-key org-mode-map [backtab] 'org-shifttab)
18254 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18255 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18256 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18258 ;; Cursor keys with modifiers
18259 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18260 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18261 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18262 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18264 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18265 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18266 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18267 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18269 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18270 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18271 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18272 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18274 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18275 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18276 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18277 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18279 ;; Babel keys
18280 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18281 (mapc (lambda (pair)
18282 (define-key org-babel-map (car pair) (cdr pair)))
18283 org-babel-key-bindings)
18285 ;;; Extra keys for tty access.
18286 ;; We only set them when really needed because otherwise the
18287 ;; menus don't show the simple keys
18289 (when (or org-use-extra-keys
18290 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18291 (not window-system))
18292 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18293 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18294 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18295 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18296 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18297 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18298 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18299 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18300 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18301 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18302 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18303 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18304 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18305 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18306 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18307 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18308 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18309 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18310 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18311 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18312 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18313 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18314 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18315 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18316 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18317 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18318 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18319 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18321 ;; All the other keys
18323 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18324 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18325 (if (boundp 'narrow-map)
18326 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18327 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18328 (if (boundp 'narrow-map)
18329 (org-defkey narrow-map "b" 'org-narrow-to-block)
18330 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18331 (if (boundp 'narrow-map)
18332 (org-defkey narrow-map "e" 'org-narrow-to-element)
18333 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18334 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18335 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18336 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18337 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18338 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18339 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18340 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18341 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18342 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18343 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18344 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18345 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18346 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18347 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18348 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18349 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18350 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18351 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18352 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18353 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18354 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18355 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18356 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18357 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18358 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18359 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18360 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18361 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18362 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18363 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18364 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18365 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18366 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18367 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18368 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18369 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18370 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18371 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18372 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18373 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18374 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18375 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18376 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18377 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18378 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18379 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18380 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18381 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18382 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18383 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18384 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18385 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18386 (org-defkey org-mode-map "\C-c^" 'org-sort)
18387 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18388 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18389 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18390 (org-defkey org-mode-map "\C-m" 'org-return)
18391 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18392 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18393 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18394 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18395 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18396 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18397 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18398 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18399 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18400 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18401 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18402 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18403 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18404 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18405 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18406 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18407 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18408 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18409 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18410 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18411 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18412 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18413 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18415 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18416 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18417 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18419 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18420 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18421 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18422 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18423 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18424 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18425 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18426 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18427 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18428 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18429 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18430 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18431 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18432 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18433 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18434 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18435 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18436 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18437 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18438 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18439 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18440 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18441 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18443 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18444 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18445 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18446 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18447 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18449 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18451 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18453 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18454 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18456 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18459 (when (featurep 'xemacs)
18460 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18463 (defconst org-speed-commands-default
18465 ("Outline Navigation")
18466 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18467 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18468 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18469 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18470 ("u" . (org-speed-move-safe 'outline-up-heading))
18471 ("j" . org-goto)
18472 ("g" . (org-refile t))
18473 ("Outline Visibility")
18474 ("c" . org-cycle)
18475 ("C" . org-shifttab)
18476 (" " . org-display-outline-path)
18477 (":" . org-columns)
18478 ("Outline Structure Editing")
18479 ("U" . org-shiftmetaup)
18480 ("D" . org-shiftmetadown)
18481 ("r" . org-metaright)
18482 ("l" . org-metaleft)
18483 ("R" . org-shiftmetaright)
18484 ("L" . org-shiftmetaleft)
18485 ("i" . (progn (forward-char 1) (call-interactively
18486 'org-insert-heading-respect-content)))
18487 ("^" . org-sort)
18488 ("w" . org-refile)
18489 ("a" . org-archive-subtree-default-with-confirmation)
18490 ("." . org-mark-subtree)
18491 ("#" . org-toggle-comment)
18492 ("Clock Commands")
18493 ("I" . org-clock-in)
18494 ("O" . org-clock-out)
18495 ("Meta Data Editing")
18496 ("t" . org-todo)
18497 ("," . (org-priority))
18498 ("0" . (org-priority ?\ ))
18499 ("1" . (org-priority ?A))
18500 ("2" . (org-priority ?B))
18501 ("3" . (org-priority ?C))
18502 (";" . org-set-tags-command)
18503 ("e" . org-set-effort)
18504 ("E" . org-inc-effort)
18505 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18506 (org-entry-put (point) "APPT_WARNTIME" m)))
18507 ("Agenda Views etc")
18508 ("v" . org-agenda)
18509 ("/" . org-sparse-tree)
18510 ("Misc")
18511 ("o" . org-open-at-point)
18512 ("?" . org-speed-command-help)
18513 ("<" . (org-agenda-set-restriction-lock 'subtree))
18514 (">" . (org-agenda-remove-restriction-lock))
18516 "The default speed commands.")
18518 (defun org-print-speed-command (e)
18519 (if (> (length (car e)) 1)
18520 (progn
18521 (princ "\n")
18522 (princ (car e))
18523 (princ "\n")
18524 (princ (make-string (length (car e)) ?-))
18525 (princ "\n"))
18526 (princ (car e))
18527 (princ " ")
18528 (if (symbolp (cdr e))
18529 (princ (symbol-name (cdr e)))
18530 (prin1 (cdr e)))
18531 (princ "\n")))
18533 (defun org-speed-command-help ()
18534 "Show the available speed commands."
18535 (interactive)
18536 (if (not org-use-speed-commands)
18537 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18538 (with-output-to-temp-buffer "*Help*"
18539 (princ "User-defined Speed commands\n===========================\n")
18540 (mapc 'org-print-speed-command org-speed-commands-user)
18541 (princ "\n")
18542 (princ "Built-in Speed commands\n=======================\n")
18543 (mapc 'org-print-speed-command org-speed-commands-default))
18544 (with-current-buffer "*Help*"
18545 (setq truncate-lines t))))
18547 (defun org-speed-move-safe (cmd)
18548 "Execute CMD, but make sure that the cursor always ends up in a headline.
18549 If not, return to the original position and throw an error."
18550 (interactive)
18551 (let ((pos (point)))
18552 (call-interactively cmd)
18553 (unless (and (bolp) (org-at-heading-p))
18554 (goto-char pos)
18555 (error "Boundary reached while executing %s" cmd))))
18557 (defvar org-self-insert-command-undo-counter 0)
18559 (defvar org-table-auto-blank-field) ; defined in org-table.el
18560 (defvar org-speed-command nil)
18562 (define-obsolete-function-alias
18563 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18565 (defun org-speed-command-activate (keys)
18566 "Hook for activating single-letter speed commands.
18567 `org-speed-commands-default' specifies a minimal command set.
18568 Use `org-speed-commands-user' for further customization."
18569 (when (or (and (bolp) (looking-at org-outline-regexp))
18570 (and (functionp org-use-speed-commands)
18571 (funcall org-use-speed-commands)))
18572 (cdr (assoc keys (append org-speed-commands-user
18573 org-speed-commands-default)))))
18575 (define-obsolete-function-alias
18576 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18578 (defun org-babel-speed-command-activate (keys)
18579 "Hook for activating single-letter code block commands."
18580 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18581 (cdr (assoc keys org-babel-key-bindings))))
18583 (defcustom org-speed-command-hook
18584 '(org-speed-command-default-hook org-babel-speed-command-hook)
18585 "Hook for activating speed commands at strategic locations.
18586 Hook functions are called in sequence until a valid handler is
18587 found.
18589 Each hook takes a single argument, a user-pressed command key
18590 which is also a `self-insert-command' from the global map.
18592 Within the hook, examine the cursor position and the command key
18593 and return nil or a valid handler as appropriate. Handler could
18594 be one of an interactive command, a function, or a form.
18596 Set `org-use-speed-commands' to non-nil value to enable this
18597 hook. The default setting is `org-speed-command-activate'."
18598 :group 'org-structure
18599 :version "24.1"
18600 :type 'hook)
18602 (defun org-self-insert-command (N)
18603 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18604 If the cursor is in a table looking at whitespace, the whitespace is
18605 overwritten, and the table is not marked as requiring realignment."
18606 (interactive "p")
18607 (org-check-before-invisible-edit 'insert)
18608 (cond
18609 ((and org-use-speed-commands
18610 (setq org-speed-command
18611 (run-hook-with-args-until-success
18612 'org-speed-command-hook (this-command-keys))))
18613 (cond
18614 ((commandp org-speed-command)
18615 (setq this-command org-speed-command)
18616 (call-interactively org-speed-command))
18617 ((functionp org-speed-command)
18618 (funcall org-speed-command))
18619 ((and org-speed-command (listp org-speed-command))
18620 (eval org-speed-command))
18621 (t (let (org-use-speed-commands)
18622 (call-interactively 'org-self-insert-command)))))
18623 ((and
18624 (org-table-p)
18625 (progn
18626 ;; check if we blank the field, and if that triggers align
18627 (and (featurep 'org-table) org-table-auto-blank-field
18628 (member last-command
18629 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18630 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18631 ;; got extra space, this field does not determine column width
18632 (let (org-table-may-need-update) (org-table-blank-field))
18633 ;; no extra space, this field may determine column width
18634 (org-table-blank-field)))
18636 (eq N 1)
18637 (looking-at "[^|\n]* |"))
18638 (let (org-table-may-need-update)
18639 (goto-char (1- (match-end 0)))
18640 (backward-delete-char 1)
18641 (goto-char (match-beginning 0))
18642 (self-insert-command N)))
18644 (setq org-table-may-need-update t)
18645 (self-insert-command N)
18646 (org-fix-tags-on-the-fly)
18647 (if org-self-insert-cluster-for-undo
18648 (if (not (eq last-command 'org-self-insert-command))
18649 (setq org-self-insert-command-undo-counter 1)
18650 (if (>= org-self-insert-command-undo-counter 20)
18651 (setq org-self-insert-command-undo-counter 1)
18652 (and (> org-self-insert-command-undo-counter 0)
18653 buffer-undo-list (listp buffer-undo-list)
18654 (not (cadr buffer-undo-list)) ; remove nil entry
18655 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18656 (setq org-self-insert-command-undo-counter
18657 (1+ org-self-insert-command-undo-counter))))))))
18659 (defun org-check-before-invisible-edit (kind)
18660 "Check is editing if kind KIND would be dangerous with invisible text around.
18661 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18662 ;; First, try to get out of here as quickly as possible, to reduce overhead
18663 (if (and org-catch-invisible-edits
18664 (or (not (boundp 'visible-mode)) (not visible-mode))
18665 (or (get-char-property (point) 'invisible)
18666 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18667 ;; OK, we need to take a closer look
18668 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18669 (invisible-before-point (if (bobp) nil (get-char-property
18670 (1- (point)) 'invisible)))
18671 (border-and-ok-direction
18673 ;; Check if we are acting predictably before invisible text
18674 (and invisible-at-point (not invisible-before-point)
18675 (memq kind '(insert delete-backward)))
18676 ;; Check if we are acting predictably after invisible text
18677 ;; This works not well, and I have turned it off. It seems
18678 ;; better to always show and stop after invisible text.
18679 ;; (and (not invisible-at-point) invisible-before-point
18680 ;; (memq kind '(insert delete)))
18682 (when (or (memq invisible-at-point '(outline org-hide-block t))
18683 (memq invisible-before-point '(outline org-hide-block t)))
18684 (if (eq org-catch-invisible-edits 'error)
18685 (error "Editing in invisible areas is prohibited - make visible first"))
18686 (if (and org-custom-properties-overlays
18687 (y-or-n-p "Display invisible properties in this buffer? "))
18688 (org-toggle-custom-properties-visibility)
18689 ;; Make the area visible
18690 (save-excursion
18691 (if invisible-before-point
18692 (goto-char (previous-single-char-property-change
18693 (point) 'invisible)))
18694 (org-cycle))
18695 (cond
18696 ((eq org-catch-invisible-edits 'show)
18697 ;; That's it, we do the edit after showing
18698 (message
18699 "Unfolding invisible region around point before editing")
18700 (sit-for 1))
18701 ((and (eq org-catch-invisible-edits 'smart)
18702 border-and-ok-direction)
18703 (message "Unfolding invisible region around point before editing"))
18705 ;; Don't do the edit, make the user repeat it in full visibility
18706 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18708 (defun org-fix-tags-on-the-fly ()
18709 (when (and (equal (char-after (point-at-bol)) ?*)
18710 (org-at-heading-p))
18711 (org-align-tags-here org-tags-column)))
18713 (defun org-delete-backward-char (N)
18714 "Like `delete-backward-char', insert whitespace at field end in tables.
18715 When deleting backwards, in tables this function will insert whitespace in
18716 front of the next \"|\" separator, to keep the table aligned. The table will
18717 still be marked for re-alignment if the field did fill the entire column,
18718 because, in this case the deletion might narrow the column."
18719 (interactive "p")
18720 (save-match-data
18721 (org-check-before-invisible-edit 'delete-backward)
18722 (if (and (org-table-p)
18723 (eq N 1)
18724 (string-match "|" (buffer-substring (point-at-bol) (point)))
18725 (looking-at ".*?|"))
18726 (let ((pos (point))
18727 (noalign (looking-at "[^|\n\r]* |"))
18728 (c org-table-may-need-update))
18729 (backward-delete-char N)
18730 (if (not overwrite-mode)
18731 (progn
18732 (skip-chars-forward "^|")
18733 (insert " ")
18734 (goto-char (1- pos))))
18735 ;; noalign: if there were two spaces at the end, this field
18736 ;; does not determine the width of the column.
18737 (if noalign (setq org-table-may-need-update c)))
18738 (backward-delete-char N)
18739 (org-fix-tags-on-the-fly))))
18741 (defun org-delete-char (N)
18742 "Like `delete-char', but insert whitespace at field end in tables.
18743 When deleting characters, in tables this function will insert whitespace in
18744 front of the next \"|\" separator, to keep the table aligned. The table will
18745 still be marked for re-alignment if the field did fill the entire column,
18746 because, in this case the deletion might narrow the column."
18747 (interactive "p")
18748 (save-match-data
18749 (org-check-before-invisible-edit 'delete)
18750 (if (and (org-table-p)
18751 (not (bolp))
18752 (not (= (char-after) ?|))
18753 (eq N 1))
18754 (if (looking-at ".*?|")
18755 (let ((pos (point))
18756 (noalign (looking-at "[^|\n\r]* |"))
18757 (c org-table-may-need-update))
18758 (replace-match (concat
18759 (substring (match-string 0) 1 -1)
18760 " |"))
18761 (goto-char pos)
18762 ;; noalign: if there were two spaces at the end, this field
18763 ;; does not determine the width of the column.
18764 (if noalign (setq org-table-may-need-update c)))
18765 (delete-char N))
18766 (delete-char N)
18767 (org-fix-tags-on-the-fly))))
18769 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18770 (put 'org-self-insert-command 'delete-selection t)
18771 (put 'orgtbl-self-insert-command 'delete-selection t)
18772 (put 'org-delete-char 'delete-selection 'supersede)
18773 (put 'org-delete-backward-char 'delete-selection 'supersede)
18774 (put 'org-yank 'delete-selection 'yank)
18776 ;; Make `flyspell-mode' delay after some commands
18777 (put 'org-self-insert-command 'flyspell-delayed t)
18778 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18779 (put 'org-delete-char 'flyspell-delayed t)
18780 (put 'org-delete-backward-char 'flyspell-delayed t)
18782 ;; Make pabbrev-mode expand after org-mode commands
18783 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18784 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18786 ;; How to do this: Measure non-white length of current string
18787 ;; If equal to column width, we should realign.
18789 (defun org-remap (map &rest commands)
18790 "In MAP, remap the functions given in COMMANDS.
18791 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18792 (let (new old)
18793 (while commands
18794 (setq old (pop commands) new (pop commands))
18795 (if (fboundp 'command-remapping)
18796 (org-defkey map (vector 'remap old) new)
18797 (substitute-key-definition old new map global-map)))))
18799 (when (eq org-enable-table-editor 'optimized)
18800 ;; If the user wants maximum table support, we need to hijack
18801 ;; some standard editing functions
18802 (org-remap org-mode-map
18803 'self-insert-command 'org-self-insert-command
18804 'delete-char 'org-delete-char
18805 'delete-backward-char 'org-delete-backward-char)
18806 (org-defkey org-mode-map "|" 'org-force-self-insert))
18808 (defvar org-ctrl-c-ctrl-c-hook nil
18809 "Hook for functions attaching themselves to `C-c C-c'.
18811 This can be used to add additional functionality to the C-c C-c
18812 key which executes context-dependent commands. This hook is run
18813 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18814 run after the last test.
18816 Each function will be called with no arguments. The function
18817 must check if the context is appropriate for it to act. If yes,
18818 it should do its thing and then return a non-nil value. If the
18819 context is wrong, just do nothing and return nil.")
18821 (defvar org-ctrl-c-ctrl-c-final-hook nil
18822 "Hook for functions attaching themselves to `C-c C-c'.
18824 This can be used to add additional functionality to the C-c C-c
18825 key which executes context-dependent commands. This hook is run
18826 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18827 before the first test.
18829 Each function will be called with no arguments. The function
18830 must check if the context is appropriate for it to act. If yes,
18831 it should do its thing and then return a non-nil value. If the
18832 context is wrong, just do nothing and return nil.")
18834 (defvar org-tab-first-hook nil
18835 "Hook for functions to attach themselves to TAB.
18836 See `org-ctrl-c-ctrl-c-hook' for more information.
18837 This hook runs as the first action when TAB is pressed, even before
18838 `org-cycle' messes around with the `outline-regexp' to cater for
18839 inline tasks and plain list item folding.
18840 If any function in this hook returns t, any other actions that
18841 would have been caused by TAB (such as table field motion or visibility
18842 cycling) will not occur.")
18844 (defvar org-tab-after-check-for-table-hook nil
18845 "Hook for functions to attach themselves to TAB.
18846 See `org-ctrl-c-ctrl-c-hook' for more information.
18847 This hook runs after it has been established that the cursor is not in a
18848 table, but before checking if the cursor is in a headline or if global cycling
18849 should be done.
18850 If any function in this hook returns t, not other actions like visibility
18851 cycling will be done.")
18853 (defvar org-tab-after-check-for-cycling-hook nil
18854 "Hook for functions to attach themselves to TAB.
18855 See `org-ctrl-c-ctrl-c-hook' for more information.
18856 This hook runs after it has been established that not table field motion and
18857 not visibility should be done because of current context. This is probably
18858 the place where a package like yasnippets can hook in.")
18860 (defvar org-tab-before-tab-emulation-hook nil
18861 "Hook for functions to attach themselves to TAB.
18862 See `org-ctrl-c-ctrl-c-hook' for more information.
18863 This hook runs after every other options for TAB have been exhausted, but
18864 before indentation and \t insertion takes place.")
18866 (defvar org-metaleft-hook nil
18867 "Hook for functions attaching themselves to `M-left'.
18868 See `org-ctrl-c-ctrl-c-hook' for more information.")
18869 (defvar org-metaright-hook nil
18870 "Hook for functions attaching themselves to `M-right'.
18871 See `org-ctrl-c-ctrl-c-hook' for more information.")
18872 (defvar org-metaup-hook nil
18873 "Hook for functions attaching themselves to `M-up'.
18874 See `org-ctrl-c-ctrl-c-hook' for more information.")
18875 (defvar org-metadown-hook nil
18876 "Hook for functions attaching themselves to `M-down'.
18877 See `org-ctrl-c-ctrl-c-hook' for more information.")
18878 (defvar org-shiftmetaleft-hook nil
18879 "Hook for functions attaching themselves to `M-S-left'.
18880 See `org-ctrl-c-ctrl-c-hook' for more information.")
18881 (defvar org-shiftmetaright-hook nil
18882 "Hook for functions attaching themselves to `M-S-right'.
18883 See `org-ctrl-c-ctrl-c-hook' for more information.")
18884 (defvar org-shiftmetaup-hook nil
18885 "Hook for functions attaching themselves to `M-S-up'.
18886 See `org-ctrl-c-ctrl-c-hook' for more information.")
18887 (defvar org-shiftmetadown-hook nil
18888 "Hook for functions attaching themselves to `M-S-down'.
18889 See `org-ctrl-c-ctrl-c-hook' for more information.")
18890 (defvar org-metareturn-hook nil
18891 "Hook for functions attaching themselves to `M-RET'.
18892 See `org-ctrl-c-ctrl-c-hook' for more information.")
18893 (defvar org-shiftup-hook nil
18894 "Hook for functions attaching themselves to `S-up'.
18895 See `org-ctrl-c-ctrl-c-hook' for more information.")
18896 (defvar org-shiftup-final-hook nil
18897 "Hook for functions attaching themselves to `S-up'.
18898 This one runs after all other options except shift-select have been excluded.
18899 See `org-ctrl-c-ctrl-c-hook' for more information.")
18900 (defvar org-shiftdown-hook nil
18901 "Hook for functions attaching themselves to `S-down'.
18902 See `org-ctrl-c-ctrl-c-hook' for more information.")
18903 (defvar org-shiftdown-final-hook nil
18904 "Hook for functions attaching themselves to `S-down'.
18905 This one runs after all other options except shift-select have been excluded.
18906 See `org-ctrl-c-ctrl-c-hook' for more information.")
18907 (defvar org-shiftleft-hook nil
18908 "Hook for functions attaching themselves to `S-left'.
18909 See `org-ctrl-c-ctrl-c-hook' for more information.")
18910 (defvar org-shiftleft-final-hook nil
18911 "Hook for functions attaching themselves to `S-left'.
18912 This one runs after all other options except shift-select have been excluded.
18913 See `org-ctrl-c-ctrl-c-hook' for more information.")
18914 (defvar org-shiftright-hook nil
18915 "Hook for functions attaching themselves to `S-right'.
18916 See `org-ctrl-c-ctrl-c-hook' for more information.")
18917 (defvar org-shiftright-final-hook nil
18918 "Hook for functions attaching themselves to `S-right'.
18919 This one runs after all other options except shift-select have been excluded.
18920 See `org-ctrl-c-ctrl-c-hook' for more information.")
18922 (defun org-modifier-cursor-error ()
18923 "Throw an error, a modified cursor command was applied in wrong context."
18924 (error "This command is active in special context like tables, headlines or items"))
18926 (defun org-shiftselect-error ()
18927 "Throw an error because Shift-Cursor command was applied in wrong context."
18928 (if (and (boundp 'shift-select-mode) shift-select-mode)
18929 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18930 (error "This command works only in special context like headlines or timestamps")))
18932 (defun org-call-for-shift-select (cmd)
18933 (let ((this-command-keys-shift-translated t))
18934 (call-interactively cmd)))
18936 (defun org-shifttab (&optional arg)
18937 "Global visibility cycling or move to previous table field.
18938 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18939 on context.
18940 See the individual commands for more information."
18941 (interactive "P")
18942 (cond
18943 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18944 ((integerp arg)
18945 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18946 (message "Content view to level: %d" arg)
18947 (org-content (prefix-numeric-value arg2))
18948 (setq org-cycle-global-status 'overview)))
18949 (t (call-interactively 'org-global-cycle))))
18951 (defun org-shiftmetaleft ()
18952 "Promote subtree or delete table column.
18953 Calls `org-promote-subtree', `org-outdent-item-tree', or
18954 `org-table-delete-column', depending on context. See the
18955 individual commands for more information."
18956 (interactive)
18957 (cond
18958 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18959 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18960 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18961 ((if (not (org-region-active-p)) (org-at-item-p)
18962 (save-excursion (goto-char (region-beginning))
18963 (org-at-item-p)))
18964 (call-interactively 'org-outdent-item-tree))
18965 (t (org-modifier-cursor-error))))
18967 (defun org-shiftmetaright ()
18968 "Demote subtree or insert table column.
18969 Calls `org-demote-subtree', `org-indent-item-tree', or
18970 `org-table-insert-column', depending on context. See the
18971 individual commands for more information."
18972 (interactive)
18973 (cond
18974 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18975 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18976 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18977 ((if (not (org-region-active-p)) (org-at-item-p)
18978 (save-excursion (goto-char (region-beginning))
18979 (org-at-item-p)))
18980 (call-interactively 'org-indent-item-tree))
18981 (t (org-modifier-cursor-error))))
18983 (defun org-shiftmetaup (&optional arg)
18984 "Move subtree up or kill table row.
18985 Calls `org-move-subtree-up' or `org-table-kill-row' or
18986 `org-move-item-up' or `org-timestamp-up', depending on context.
18987 See the individual commands for more information."
18988 (interactive "P")
18989 (cond
18990 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18991 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18992 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18993 ((org-at-item-p) (call-interactively 'org-move-item-up))
18994 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18995 (call-interactively 'org-timestamp-up)))
18996 (t (org-modifier-cursor-error))))
18998 (defun org-shiftmetadown (&optional arg)
18999 "Move subtree down or insert table row.
19000 Calls `org-move-subtree-down' or `org-table-insert-row' or
19001 `org-move-item-down' or `org-timestamp-up', depending on context.
19002 See the individual commands for more information."
19003 (interactive "P")
19004 (cond
19005 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19006 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19007 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19008 ((org-at-item-p) (call-interactively 'org-move-item-down))
19009 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19010 (call-interactively 'org-timestamp-down)))
19011 (t (org-modifier-cursor-error))))
19013 (defsubst org-hidden-tree-error ()
19014 (error
19015 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19017 (defun org-metaleft (&optional arg)
19018 "Promote heading or move table column to left.
19019 Calls `org-do-promote' or `org-table-move-column', depending on context.
19020 With no specific context, calls the Emacs default `backward-word'.
19021 See the individual commands for more information."
19022 (interactive "P")
19023 (cond
19024 ((run-hook-with-args-until-success 'org-metaleft-hook))
19025 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19026 ((org-with-limited-levels
19027 (or (org-at-heading-p)
19028 (and (org-region-active-p)
19029 (save-excursion
19030 (goto-char (region-beginning))
19031 (org-at-heading-p)))))
19032 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19033 (call-interactively 'org-do-promote))
19034 ;; At an inline task.
19035 ((org-at-heading-p)
19036 (call-interactively 'org-inlinetask-promote))
19037 ((or (org-at-item-p)
19038 (and (org-region-active-p)
19039 (save-excursion
19040 (goto-char (region-beginning))
19041 (org-at-item-p))))
19042 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19043 (call-interactively 'org-outdent-item))
19044 (t (call-interactively 'backward-word))))
19046 (defun org-metaright (&optional arg)
19047 "Demote a subtree, a list item or move table column to right.
19048 In front of a drawer or a block keyword, indent it correctly.
19049 With no specific context, calls the Emacs default `forward-word'.
19050 See the individual commands for more information."
19051 (interactive "P")
19052 (cond
19053 ((run-hook-with-args-until-success 'org-metaright-hook))
19054 ((org-at-table-p) (call-interactively 'org-table-move-column))
19055 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19056 ((org-at-block-p) (call-interactively 'org-indent-block))
19057 ((org-with-limited-levels
19058 (or (org-at-heading-p)
19059 (and (org-region-active-p)
19060 (save-excursion
19061 (goto-char (region-beginning))
19062 (org-at-heading-p)))))
19063 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19064 (call-interactively 'org-do-demote))
19065 ;; At an inline task.
19066 ((org-at-heading-p)
19067 (call-interactively 'org-inlinetask-demote))
19068 ((or (org-at-item-p)
19069 (and (org-region-active-p)
19070 (save-excursion
19071 (goto-char (region-beginning))
19072 (org-at-item-p))))
19073 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19074 (call-interactively 'org-indent-item))
19075 (t (call-interactively 'forward-word))))
19077 (defun org-check-for-hidden (what)
19078 "Check if there are hidden headlines/items in the current visual line.
19079 WHAT can be either `headlines' or `items'. If the current line is
19080 an outline or item heading and it has a folded subtree below it,
19081 this function returns t, nil otherwise."
19082 (let ((re (cond
19083 ((eq what 'headlines) org-outline-regexp-bol)
19084 ((eq what 'items) (org-item-beginning-re))
19085 (t (error "This should not happen"))))
19086 beg end)
19087 (save-excursion
19088 (catch 'exit
19089 (unless (org-region-active-p)
19090 (setq beg (point-at-bol))
19091 (beginning-of-line 2)
19092 (while (and (not (eobp)) ;; this is like `next-line'
19093 (get-char-property (1- (point)) 'invisible))
19094 (beginning-of-line 2))
19095 (setq end (point))
19096 (goto-char beg)
19097 (goto-char (point-at-eol))
19098 (setq end (max end (point)))
19099 (while (re-search-forward re end t)
19100 (if (get-char-property (match-beginning 0) 'invisible)
19101 (throw 'exit t))))
19102 nil))))
19104 (defun org-metaup (&optional arg)
19105 "Move subtree up or move table row up.
19106 Calls `org-move-subtree-up' or `org-table-move-row' or
19107 `org-move-item-up', depending on context. See the individual commands
19108 for more information."
19109 (interactive "P")
19110 (cond
19111 ((run-hook-with-args-until-success 'org-metaup-hook))
19112 ((org-region-active-p)
19113 (let* ((a (min (region-beginning) (region-end)))
19114 (b (1- (max (region-beginning) (region-end))))
19115 (c (save-excursion (goto-char a)
19116 (move-beginning-of-line 0)))
19117 (d (save-excursion (goto-char a)
19118 (move-end-of-line 0) (point))))
19119 (transpose-regions a b c d)
19120 (goto-char c)))
19121 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19122 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19123 ((org-at-item-p) (call-interactively 'org-move-item-up))
19124 (t (org-drag-element-backward))))
19126 (defun org-metadown (&optional arg)
19127 "Move subtree down or move table row down.
19128 Calls `org-move-subtree-down' or `org-table-move-row' or
19129 `org-move-item-down', depending on context. See the individual
19130 commands for more information."
19131 (interactive "P")
19132 (cond
19133 ((run-hook-with-args-until-success 'org-metadown-hook))
19134 ((org-region-active-p)
19135 (let* ((a (min (region-beginning) (region-end)))
19136 (b (max (region-beginning) (region-end)))
19137 (c (save-excursion (goto-char b)
19138 (move-beginning-of-line 1)))
19139 (d (save-excursion (goto-char b)
19140 (move-end-of-line 1) (1+ (point)))))
19141 (transpose-regions a b c d)
19142 (goto-char d)))
19143 ((org-at-table-p) (call-interactively 'org-table-move-row))
19144 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19145 ((org-at-item-p) (call-interactively 'org-move-item-down))
19146 (t (org-drag-element-forward))))
19148 (defun org-shiftup (&optional arg)
19149 "Increase item in timestamp or increase priority of current headline.
19150 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19151 depending on context. See the individual commands for more information."
19152 (interactive "P")
19153 (cond
19154 ((run-hook-with-args-until-success 'org-shiftup-hook))
19155 ((and org-support-shift-select (org-region-active-p))
19156 (org-call-for-shift-select 'previous-line))
19157 ((org-at-timestamp-p t)
19158 (call-interactively (if org-edit-timestamp-down-means-later
19159 'org-timestamp-down 'org-timestamp-up)))
19160 ((and (not (eq org-support-shift-select 'always))
19161 org-enable-priority-commands
19162 (org-at-heading-p))
19163 (call-interactively 'org-priority-up))
19164 ((and (not org-support-shift-select) (org-at-item-p))
19165 (call-interactively 'org-previous-item))
19166 ((org-clocktable-try-shift 'up arg))
19167 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19168 (org-support-shift-select
19169 (org-call-for-shift-select 'previous-line))
19170 (t (org-shiftselect-error))))
19172 (defun org-shiftdown (&optional arg)
19173 "Decrease item in timestamp or decrease priority of current headline.
19174 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19175 depending on context. See the individual commands for more information."
19176 (interactive "P")
19177 (cond
19178 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19179 ((and org-support-shift-select (org-region-active-p))
19180 (org-call-for-shift-select 'next-line))
19181 ((org-at-timestamp-p t)
19182 (call-interactively (if org-edit-timestamp-down-means-later
19183 'org-timestamp-up 'org-timestamp-down)))
19184 ((and (not (eq org-support-shift-select 'always))
19185 org-enable-priority-commands
19186 (org-at-heading-p))
19187 (call-interactively 'org-priority-down))
19188 ((and (not org-support-shift-select) (org-at-item-p))
19189 (call-interactively 'org-next-item))
19190 ((org-clocktable-try-shift 'down arg))
19191 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19192 (org-support-shift-select
19193 (org-call-for-shift-select 'next-line))
19194 (t (org-shiftselect-error))))
19196 (defun org-shiftright (&optional arg)
19197 "Cycle the thing at point or in the current line, depending on context.
19198 Depending on context, this does one of the following:
19200 - switch a timestamp at point one day into the future
19201 - on a headline, switch to the next TODO keyword.
19202 - on an item, switch entire list to the next bullet type
19203 - on a property line, switch to the next allowed value
19204 - on a clocktable definition line, move time block into the future"
19205 (interactive "P")
19206 (cond
19207 ((run-hook-with-args-until-success 'org-shiftright-hook))
19208 ((and org-support-shift-select (org-region-active-p))
19209 (org-call-for-shift-select 'forward-char))
19210 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19211 ((and (not (eq org-support-shift-select 'always))
19212 (org-at-heading-p))
19213 (let ((org-inhibit-logging
19214 (not org-treat-S-cursor-todo-selection-as-state-change))
19215 (org-inhibit-blocking
19216 (not org-treat-S-cursor-todo-selection-as-state-change)))
19217 (org-call-with-arg 'org-todo 'right)))
19218 ((or (and org-support-shift-select
19219 (not (eq org-support-shift-select 'always))
19220 (org-at-item-bullet-p))
19221 (and (not org-support-shift-select) (org-at-item-p)))
19222 (org-call-with-arg 'org-cycle-list-bullet nil))
19223 ((and (not (eq org-support-shift-select 'always))
19224 (org-at-property-p))
19225 (call-interactively 'org-property-next-allowed-value))
19226 ((org-clocktable-try-shift 'right arg))
19227 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19228 (org-support-shift-select
19229 (org-call-for-shift-select 'forward-char))
19230 (t (org-shiftselect-error))))
19232 (defun org-shiftleft (&optional arg)
19233 "Cycle the thing at point or in the current line, depending on context.
19234 Depending on context, this does one of the following:
19236 - switch a timestamp at point one day into the past
19237 - on a headline, switch to the previous TODO keyword.
19238 - on an item, switch entire list to the previous bullet type
19239 - on a property line, switch to the previous allowed value
19240 - on a clocktable definition line, move time block into the past"
19241 (interactive "P")
19242 (cond
19243 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19244 ((and org-support-shift-select (org-region-active-p))
19245 (org-call-for-shift-select 'backward-char))
19246 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19247 ((and (not (eq org-support-shift-select 'always))
19248 (org-at-heading-p))
19249 (let ((org-inhibit-logging
19250 (not org-treat-S-cursor-todo-selection-as-state-change))
19251 (org-inhibit-blocking
19252 (not org-treat-S-cursor-todo-selection-as-state-change)))
19253 (org-call-with-arg 'org-todo 'left)))
19254 ((or (and org-support-shift-select
19255 (not (eq org-support-shift-select 'always))
19256 (org-at-item-bullet-p))
19257 (and (not org-support-shift-select) (org-at-item-p)))
19258 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19259 ((and (not (eq org-support-shift-select 'always))
19260 (org-at-property-p))
19261 (call-interactively 'org-property-previous-allowed-value))
19262 ((org-clocktable-try-shift 'left arg))
19263 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19264 (org-support-shift-select
19265 (org-call-for-shift-select 'backward-char))
19266 (t (org-shiftselect-error))))
19268 (defun org-shiftcontrolright ()
19269 "Switch to next TODO set."
19270 (interactive)
19271 (cond
19272 ((and org-support-shift-select (org-region-active-p))
19273 (org-call-for-shift-select 'forward-word))
19274 ((and (not (eq org-support-shift-select 'always))
19275 (org-at-heading-p))
19276 (org-call-with-arg 'org-todo 'nextset))
19277 (org-support-shift-select
19278 (org-call-for-shift-select 'forward-word))
19279 (t (org-shiftselect-error))))
19281 (defun org-shiftcontrolleft ()
19282 "Switch to previous TODO set."
19283 (interactive)
19284 (cond
19285 ((and org-support-shift-select (org-region-active-p))
19286 (org-call-for-shift-select 'backward-word))
19287 ((and (not (eq org-support-shift-select 'always))
19288 (org-at-heading-p))
19289 (org-call-with-arg 'org-todo 'previousset))
19290 (org-support-shift-select
19291 (org-call-for-shift-select 'backward-word))
19292 (t (org-shiftselect-error))))
19294 (defun org-shiftcontrolup (&optional n)
19295 "Change timestamps synchronously up in CLOCK log lines.
19296 Optional argument N tells to change by that many units."
19297 (interactive "P")
19298 (cond ((and (not org-support-shift-select)
19299 (org-at-clock-log-p)
19300 (org-at-timestamp-p t))
19301 (org-clock-timestamps-up n))
19302 (t (org-shiftselect-error))))
19304 (defun org-shiftcontroldown (&optional n)
19305 "Change timestamps synchronously down in CLOCK log lines.
19306 Optional argument N tells to change by that many units."
19307 (interactive "P")
19308 (cond ((and (not org-support-shift-select)
19309 (org-at-clock-log-p)
19310 (org-at-timestamp-p t))
19311 (org-clock-timestamps-down n))
19312 (t (org-shiftselect-error))))
19314 (defun org-ctrl-c-ret ()
19315 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19316 (interactive)
19317 (cond
19318 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19319 (t (call-interactively 'org-insert-heading))))
19321 (defun org-find-visible ()
19322 (let ((s (point)))
19323 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19324 (get-char-property s 'invisible)))
19326 (defun org-find-invisible ()
19327 (let ((s (point)))
19328 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19329 (not (get-char-property s 'invisible))))
19332 (defun org-copy-visible (beg end)
19333 "Copy the visible parts of the region."
19334 (interactive "r")
19335 (let (snippets s)
19336 (save-excursion
19337 (save-restriction
19338 (narrow-to-region beg end)
19339 (setq s (goto-char (point-min)))
19340 (while (not (= (point) (point-max)))
19341 (goto-char (org-find-invisible))
19342 (push (buffer-substring s (point)) snippets)
19343 (setq s (goto-char (org-find-visible))))))
19344 (kill-new (apply 'concat (nreverse snippets)))))
19346 (defun org-copy-special ()
19347 "Copy region in table or copy current subtree.
19348 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19349 See the individual commands for more information."
19350 (interactive)
19351 (call-interactively
19352 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19354 (defun org-cut-special ()
19355 "Cut region in table or cut current subtree.
19356 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19357 See the individual commands for more information."
19358 (interactive)
19359 (call-interactively
19360 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19362 (defun org-paste-special (arg)
19363 "Paste rectangular region into table, or past subtree relative to level.
19364 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19365 See the individual commands for more information."
19366 (interactive "P")
19367 (if (org-at-table-p)
19368 (org-table-paste-rectangle)
19369 (org-paste-subtree arg)))
19371 (defsubst org-in-fixed-width-region-p ()
19372 "Is point in a fixed-width region?"
19373 (save-match-data
19374 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19376 (defun org-edit-special (&optional arg)
19377 "Call a special editor for the stuff at point.
19378 When at a table, call the formula editor with `org-table-edit-formulas'.
19379 When in a source code block, call `org-edit-src-code'.
19380 When in a fixed-width region, call `org-edit-fixed-width-region'.
19381 When in an #+include line, visit the included file.
19382 On a link, call `ffap' to visit the link at point.
19383 Otherwise, return a user error."
19384 (interactive)
19385 ;; possibly prep session before editing source
19386 (when (and (org-in-src-block-p) arg)
19387 (let* ((info (org-babel-get-src-block-info))
19388 (lang (nth 0 info))
19389 (params (nth 2 info))
19390 (session (cdr (assoc :session params))))
19391 (when (and info session) ;; we are in a source-code block with a session
19392 (funcall
19393 (intern (concat "org-babel-prep-session:" lang)) session params))))
19394 (cond ;; proceed with `org-edit-special'
19395 ((save-excursion
19396 (beginning-of-line 1)
19397 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19398 (find-file (org-trim (match-string 1))))
19399 ((or (org-at-table-p)
19400 (save-excursion
19401 (beginning-of-line 1)
19402 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19403 (call-interactively 'org-table-edit-formulas))
19404 ((or (org-in-block-p '("src" "example" "latex" "html"))
19405 (org-at-table.el-p))
19406 (org-edit-src-code))
19407 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19408 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19409 (t (user-error "No special environment to edit here"))))
19411 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19412 (defun org-ctrl-c-ctrl-c (&optional arg)
19413 "Set tags in headline, or update according to changed information at point.
19415 This command does many different things, depending on context:
19417 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19418 this is what we do.
19420 - If the cursor is on a statistics cookie, update it.
19422 - If the cursor is in a headline, prompt for tags and insert them
19423 into the current line, aligned to `org-tags-column'. When called
19424 with prefix arg, realign all tags in the current buffer.
19426 - If the cursor is in one of the special #+KEYWORD lines, this
19427 triggers scanning the buffer for these lines and updating the
19428 information.
19430 - If the cursor is inside a table, realign the table. This command
19431 works even if the automatic table editor has been turned off.
19433 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19434 the entire table.
19436 - If the cursor is at a footnote reference or definition, jump to
19437 the corresponding definition or references, respectively.
19439 - If the cursor is a the beginning of a dynamic block, update it.
19441 - If the current buffer is a capture buffer, close note and file it.
19443 - If the cursor is on a <<<target>>>, update radio targets and
19444 corresponding links in this buffer.
19446 - If the cursor is on a numbered item in a plain list, renumber the
19447 ordered list.
19449 - If the cursor is on a checkbox, toggle it.
19451 - If the cursor is on a code block, evaluate it. The variable
19452 `org-confirm-babel-evaluate' can be used to control prompting
19453 before code block evaluation, by default every code block
19454 evaluation requires confirmation. Code block evaluation can be
19455 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19456 (interactive "P")
19457 (let ((org-enable-table-editor t))
19458 (cond
19459 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19460 org-occur-highlights
19461 org-latex-fragment-image-overlays)
19462 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19463 (org-remove-occur-highlights)
19464 (org-remove-latex-fragment-image-overlays)
19465 (message "Temporary highlights/overlays removed from current buffer"))
19466 ((and (local-variable-p 'org-finish-function (current-buffer))
19467 (fboundp org-finish-function))
19468 (funcall org-finish-function))
19469 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19470 ((org-in-regexp org-ts-regexp-both)
19471 (org-timestamp-change 0 'day))
19472 ((or (looking-at org-property-start-re)
19473 (org-at-property-p))
19474 (call-interactively 'org-property-action))
19475 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19476 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19477 (or (org-at-heading-p) (org-at-item-p)))
19478 (call-interactively 'org-update-statistics-cookies))
19479 ((org-at-heading-p) (call-interactively 'org-set-tags))
19480 ((org-at-table.el-p)
19481 (message "Use C-c ' to edit table.el tables"))
19482 ((org-at-table-p)
19483 (org-table-maybe-eval-formula)
19484 (if arg
19485 (call-interactively 'org-table-recalculate)
19486 (org-table-maybe-recalculate-line))
19487 (call-interactively 'org-table-align)
19488 (orgtbl-send-table 'maybe))
19489 ((or (org-footnote-at-reference-p)
19490 (org-footnote-at-definition-p))
19491 (call-interactively 'org-footnote-action))
19492 ((org-at-item-checkbox-p)
19493 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19494 ;; list only if at top item.
19495 (let* ((cbox (match-string 1))
19496 (struct (org-list-struct))
19497 (old-struct (copy-tree struct))
19498 (parents (org-list-parents-alist struct))
19499 (orderedp (org-entry-get nil "ORDERED"))
19500 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19501 block-item)
19502 ;; Use a light version of `org-toggle-checkbox' to avoid
19503 ;; computing list structure twice.
19504 (let ((new-box (cond
19505 ((equal arg '(16)) "[-]")
19506 ((equal arg '(4)) nil)
19507 ((equal "[X]" cbox) "[ ]")
19508 (t "[X]"))))
19509 (if (and firstp arg)
19510 ;; If at first item of sub-list, remove check-box from
19511 ;; every item at the same level.
19512 (mapc
19513 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19514 (org-list-get-all-items
19515 (point-at-bol) struct (org-list-prevs-alist struct)))
19516 (org-list-set-checkbox (point-at-bol) struct new-box)))
19517 ;; Replicate `org-list-write-struct', while grabbing a return
19518 ;; value from `org-list-struct-fix-box'.
19519 (org-list-struct-fix-ind struct parents 2)
19520 (org-list-struct-fix-item-end struct)
19521 (let ((prevs (org-list-prevs-alist struct)))
19522 (org-list-struct-fix-bul struct prevs)
19523 (org-list-struct-fix-ind struct parents)
19524 (setq block-item
19525 (org-list-struct-fix-box struct parents prevs orderedp)))
19526 (org-list-struct-apply-struct struct old-struct)
19527 (org-update-checkbox-count-maybe)
19528 (when block-item
19529 (message
19530 "Checkboxes were removed due to unchecked box at line %d"
19531 (org-current-line block-item)))
19532 (when firstp (org-list-send-list 'maybe))))
19533 ((org-at-item-p)
19534 ;; Cursor at an item: repair list. Do checkbox related actions
19535 ;; only if function was called with an argument. Send list only
19536 ;; if at top item.
19537 (let* ((struct (org-list-struct))
19538 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19539 old-struct)
19540 (when arg
19541 (setq old-struct (copy-tree struct))
19542 (if firstp
19543 ;; If at first item of sub-list, add check-box to every
19544 ;; item at the same level.
19545 (mapc
19546 (lambda (pos)
19547 (unless (org-list-get-checkbox pos struct)
19548 (org-list-set-checkbox pos struct "[ ]")))
19549 (org-list-get-all-items
19550 (point-at-bol) struct (org-list-prevs-alist struct)))
19551 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19552 (org-list-write-struct
19553 struct (org-list-parents-alist struct) old-struct)
19554 (when arg (org-update-checkbox-count-maybe))
19555 (when firstp (org-list-send-list 'maybe))))
19556 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19557 ;; Dynamic block
19558 (beginning-of-line 1)
19559 (save-excursion (org-update-dblock)))
19560 ((save-excursion
19561 (let ((case-fold-search t))
19562 (beginning-of-line 1)
19563 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19564 (cond
19565 ((or (equal (match-string 1) "TBLFM")
19566 (equal (match-string 1) "tblfm"))
19567 ;; Recalculate the table before this line
19568 (save-excursion
19569 (beginning-of-line 1)
19570 (skip-chars-backward " \r\n\t")
19571 (if (org-at-table-p)
19572 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19574 (let ((org-inhibit-startup-visibility-stuff t)
19575 (org-startup-align-all-tables nil))
19576 (when (boundp 'org-table-coordinate-overlays)
19577 (mapc 'delete-overlay org-table-coordinate-overlays)
19578 (setq org-table-coordinate-overlays nil))
19579 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19580 (message "Local setup has been refreshed"))))
19581 ((org-clock-update-time-maybe))
19583 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19584 (error "C-c C-c can do nothing useful at this location"))))))
19586 (defun org-mode-restart ()
19587 "Restart Org-mode, to scan again for special lines.
19588 Also updates the keyword regular expressions."
19589 (interactive)
19590 (org-mode)
19591 (message "Org-mode restarted"))
19593 (defun org-kill-note-or-show-branches ()
19594 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19595 (interactive)
19596 (if (not org-finish-function)
19597 (progn
19598 (hide-subtree)
19599 (call-interactively 'show-branches))
19600 (let ((org-note-abort t))
19601 (funcall org-finish-function))))
19603 (defun org-return (&optional indent)
19604 "Goto next table row or insert a newline.
19605 Calls `org-table-next-row' or `newline', depending on context.
19606 See the individual commands for more information."
19607 (interactive)
19608 (let (org-ts-what)
19609 (cond
19610 ((or (bobp) (org-in-src-block-p))
19611 (if indent (newline-and-indent) (newline)))
19612 ((org-at-table-p)
19613 (org-table-justify-field-maybe)
19614 (call-interactively 'org-table-next-row))
19615 ;; when `newline-and-indent' is called within a list, make sure
19616 ;; text moved stays inside the item.
19617 ((and (org-in-item-p) indent)
19618 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19619 (progn
19620 (save-match-data (newline))
19621 (org-indent-line-to (length (match-string 0))))
19622 (let ((ind (org-get-indentation)))
19623 (newline)
19624 (if (org-looking-back org-list-end-re)
19625 (org-indent-line)
19626 (org-indent-line-to ind)))))
19627 ((and org-return-follows-link
19628 (org-at-timestamp-p t)
19629 (not (eq org-ts-what 'after)))
19630 (org-follow-timestamp-link))
19631 ((and org-return-follows-link
19632 (let ((tprop (get-text-property (point) 'face)))
19633 (or (eq tprop 'org-link)
19634 (and (listp tprop) (memq 'org-link tprop)))))
19635 (call-interactively 'org-open-at-point))
19636 ((and (org-at-heading-p)
19637 (looking-at
19638 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19639 (org-show-entry)
19640 (end-of-line 1)
19641 (newline))
19642 (t (if indent (newline-and-indent) (newline))))))
19644 (defun org-return-indent ()
19645 "Goto next table row or insert a newline and indent.
19646 Calls `org-table-next-row' or `newline-and-indent', depending on
19647 context. See the individual commands for more information."
19648 (interactive)
19649 (org-return t))
19651 (defun org-ctrl-c-star ()
19652 "Compute table, or change heading status of lines.
19653 Calls `org-table-recalculate' or `org-toggle-heading',
19654 depending on context."
19655 (interactive)
19656 (cond
19657 ((org-at-table-p)
19658 (call-interactively 'org-table-recalculate))
19660 ;; Convert all lines in region to list items
19661 (call-interactively 'org-toggle-heading))))
19663 (defun org-ctrl-c-minus ()
19664 "Insert separator line in table or modify bullet status of line.
19665 Also turns a plain line or a region of lines into list items.
19666 Calls `org-table-insert-hline', `org-toggle-item', or
19667 `org-cycle-list-bullet', depending on context."
19668 (interactive)
19669 (cond
19670 ((org-at-table-p)
19671 (call-interactively 'org-table-insert-hline))
19672 ((org-region-active-p)
19673 (call-interactively 'org-toggle-item))
19674 ((org-in-item-p)
19675 (call-interactively 'org-cycle-list-bullet))
19677 (call-interactively 'org-toggle-item))))
19679 (defun org-toggle-item (arg)
19680 "Convert headings or normal lines to items, items to normal lines.
19681 If there is no active region, only the current line is considered.
19683 If the first non blank line in the region is an headline, convert
19684 all headlines to items, shifting text accordingly.
19686 If it is an item, convert all items to normal lines.
19688 If it is normal text, change region into an item. With a prefix
19689 argument ARG, change each line in region into an item."
19690 (interactive "P")
19691 (let ((shift-text
19692 (function
19693 ;; Shift text in current section to IND, from point to END.
19694 ;; The function leaves point to END line.
19695 (lambda (ind end)
19696 (let ((min-i 1000) (end (copy-marker end)))
19697 ;; First determine the minimum indentation (MIN-I) of
19698 ;; the text.
19699 (save-excursion
19700 (catch 'exit
19701 (while (< (point) end)
19702 (let ((i (org-get-indentation)))
19703 (cond
19704 ;; Skip blank lines and inline tasks.
19705 ((looking-at "^[ \t]*$"))
19706 ((looking-at org-outline-regexp-bol))
19707 ;; We can't find less than 0 indentation.
19708 ((zerop i) (throw 'exit (setq min-i 0)))
19709 ((< i min-i) (setq min-i i))))
19710 (forward-line))))
19711 ;; Then indent each line so that a line indented to
19712 ;; MIN-I becomes indented to IND. Ignore blank lines
19713 ;; and inline tasks in the process.
19714 (let ((delta (- ind min-i)))
19715 (while (< (point) end)
19716 (unless (or (looking-at "^[ \t]*$")
19717 (looking-at org-outline-regexp-bol))
19718 (org-indent-line-to (+ (org-get-indentation) delta)))
19719 (forward-line)))))))
19720 (skip-blanks
19721 (function
19722 ;; Return beginning of first non-blank line, starting from
19723 ;; line at POS.
19724 (lambda (pos)
19725 (save-excursion
19726 (goto-char pos)
19727 (skip-chars-forward " \r\t\n")
19728 (point-at-bol)))))
19729 beg end)
19730 ;; Determine boundaries of changes.
19731 (if (org-region-active-p)
19732 (setq beg (funcall skip-blanks (region-beginning))
19733 end (copy-marker (region-end)))
19734 (setq beg (funcall skip-blanks (point-at-bol))
19735 end (copy-marker (point-at-eol))))
19736 ;; Depending on the starting line, choose an action on the text
19737 ;; between BEG and END.
19738 (org-with-limited-levels
19739 (save-excursion
19740 (goto-char beg)
19741 (cond
19742 ;; Case 1. Start at an item: de-itemize. Note that it only
19743 ;; happens when a region is active: `org-ctrl-c-minus'
19744 ;; would call `org-cycle-list-bullet' otherwise.
19745 ((org-at-item-p)
19746 (while (< (point) end)
19747 (when (org-at-item-p)
19748 (skip-chars-forward " \t")
19749 (delete-region (point) (match-end 0)))
19750 (forward-line)))
19751 ;; Case 2. Start at an heading: convert to items.
19752 ((org-at-heading-p)
19753 (let* ((bul (org-list-bullet-string "-"))
19754 (bul-len (length bul))
19755 ;; Indentation of the first heading. It should be
19756 ;; relative to the indentation of its parent, if any.
19757 (start-ind (save-excursion
19758 (cond
19759 ((not org-adapt-indentation) 0)
19760 ((not (outline-previous-heading)) 0)
19761 (t (length (match-string 0))))))
19762 ;; Level of first heading. Further headings will be
19763 ;; compared to it to determine hierarchy in the list.
19764 (ref-level (org-reduced-level (org-outline-level))))
19765 (while (< (point) end)
19766 (let* ((level (org-reduced-level (org-outline-level)))
19767 (delta (max 0 (- level ref-level))))
19768 ;; If current headline is less indented than the first
19769 ;; one, set it as reference, in order to preserve
19770 ;; subtrees.
19771 (when (< level ref-level) (setq ref-level level))
19772 (replace-match bul t t)
19773 (org-indent-line-to (+ start-ind (* delta bul-len)))
19774 ;; Ensure all text down to END (or SECTION-END) belongs
19775 ;; to the newly created item.
19776 (let ((section-end (save-excursion
19777 (or (outline-next-heading) (point)))))
19778 (forward-line)
19779 (funcall shift-text
19780 (+ start-ind (* (1+ delta) bul-len))
19781 (min end section-end)))))))
19782 ;; Case 3. Normal line with ARG: turn each non-item line into
19783 ;; an item.
19784 (arg
19785 (while (< (point) end)
19786 (unless (or (org-at-heading-p) (org-at-item-p))
19787 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19788 (replace-match
19789 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19790 (forward-line)))
19791 ;; Case 4. Normal line without ARG: make the first line of
19792 ;; region an item, and shift indentation of others
19793 ;; lines to set them as item's body.
19794 (t (let* ((bul (org-list-bullet-string "-"))
19795 (bul-len (length bul))
19796 (ref-ind (org-get-indentation)))
19797 (skip-chars-forward " \t")
19798 (insert bul)
19799 (forward-line)
19800 (while (< (point) end)
19801 ;; Ensure that lines less indented than first one
19802 ;; still get included in item body.
19803 (funcall shift-text
19804 (+ ref-ind bul-len)
19805 (min end (save-excursion (or (outline-next-heading)
19806 (point)))))
19807 (forward-line)))))))))
19809 (defun org-toggle-heading (&optional nstars)
19810 "Convert headings to normal text, or items or text to headings.
19811 If there is no active region, only the current line is considered.
19813 With a \\[universal-argument] prefix, convert the whole list at
19814 point into heading.
19816 In a region:
19818 - If the first non blank line is an headline, remove the stars
19819 from all headlines in the region.
19821 - If it is a normal line turn each and every normal line (i.e. not an
19822 heading or an item) in the region into a heading.
19824 - If it is a plain list item, turn all plain list items into headings.
19826 When converting a line into a heading, the number of stars is chosen
19827 such that the lines become children of the current entry. However,
19828 when a prefix argument is given, its value determines the number of
19829 stars to add."
19830 (interactive "P")
19831 (let ((skip-blanks
19832 (function
19833 ;; Return beginning of first non-blank line, starting from
19834 ;; line at POS.
19835 (lambda (pos)
19836 (save-excursion
19837 (goto-char pos)
19838 (while (org-at-comment-p) (forward-line))
19839 (skip-chars-forward " \r\t\n")
19840 (point-at-bol)))))
19841 beg end toggled)
19842 ;; Determine boundaries of changes. If a universal prefix has
19843 ;; been given, put the list in a region. If region ends at a bol,
19844 ;; do not consider the last line to be in the region.
19846 (when (and current-prefix-arg (org-at-item-p))
19847 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19848 (org-mark-element))
19850 (if (org-region-active-p)
19851 (setq beg (funcall skip-blanks (region-beginning))
19852 end (copy-marker (save-excursion
19853 (goto-char (region-end))
19854 (if (bolp) (point) (point-at-eol)))))
19855 (setq beg (funcall skip-blanks (point-at-bol))
19856 end (copy-marker (point-at-eol))))
19857 ;; Ensure inline tasks don't count as headings.
19858 (org-with-limited-levels
19859 (save-excursion
19860 (goto-char beg)
19861 (cond
19862 ;; Case 1. Started at an heading: de-star headings.
19863 ((org-at-heading-p)
19864 (while (< (point) end)
19865 (when (org-at-heading-p t)
19866 (looking-at org-outline-regexp) (replace-match "")
19867 (setq toggled t))
19868 (forward-line)))
19869 ;; Case 2. Started at an item: change items into headlines.
19870 ;; One star will be added by `org-list-to-subtree'.
19871 ((org-at-item-p)
19872 (let* ((stars (make-string
19873 (if nstars
19874 ;; subtract the star that will be added again by
19875 ;; `org-list-to-subtree'
19876 (1- (prefix-numeric-value current-prefix-arg))
19877 (or (org-current-level) 0))
19878 ?*))
19879 (add-stars
19880 (cond (nstars "") ; stars from prefix only
19881 ((equal stars "") "") ; before first heading
19882 (org-odd-levels-only "*") ; inside heading, odd
19883 (t "")))) ; inside heading, oddeven
19884 (while (< (point) end)
19885 (when (org-at-item-p)
19886 ;; Pay attention to cases when region ends before list.
19887 (let* ((struct (org-list-struct))
19888 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19889 (save-restriction
19890 (narrow-to-region (point) list-end)
19891 (insert
19892 (org-list-to-subtree
19893 (org-list-parse-list t)
19894 '(:istart (concat stars add-stars (funcall get-stars depth))
19895 :icount (concat stars add-stars (funcall get-stars depth)))))))
19896 (setq toggled t))
19897 (forward-line))))
19898 ;; Case 3. Started at normal text: make every line an heading,
19899 ;; skipping headlines and items.
19900 (t (let* ((stars (make-string
19901 (if nstars
19902 (prefix-numeric-value current-prefix-arg)
19903 (or (org-current-level) 0))
19904 ?*))
19905 (add-stars
19906 (cond (nstars "") ; stars from prefix only
19907 ((equal stars "") "*") ; before first heading
19908 (org-odd-levels-only "**") ; inside heading, odd
19909 (t "*"))) ; inside heading, oddeven
19910 (rpl (concat stars add-stars " ")))
19911 (while (< (point) end)
19912 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19913 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19914 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19915 (forward-line)))))))
19916 (unless toggled (message "Cannot toggle heading from here"))))
19918 (defun org-meta-return (&optional arg)
19919 "Insert a new heading or wrap a region in a table.
19920 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19921 See the individual commands for more information."
19922 (interactive "P")
19923 (cond
19924 ((run-hook-with-args-until-success 'org-metareturn-hook))
19925 ((or (org-at-drawer-p) (org-at-property-p))
19926 (newline-and-indent))
19927 ((org-at-table-p)
19928 (call-interactively 'org-table-wrap-region))
19929 (t (call-interactively 'org-insert-heading))))
19931 ;;; Menu entries
19933 (defsubst org-in-subtree-not-table-p ()
19934 "Are we in a subtree and not in a table?"
19935 (and (not (org-before-first-heading-p))
19936 (not (org-at-table-p))))
19938 ;; Define the Org-mode menus
19939 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19940 '("Tbl"
19941 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19942 ["Next Field" org-cycle (org-at-table-p)]
19943 ["Previous Field" org-shifttab (org-at-table-p)]
19944 ["Next Row" org-return (org-at-table-p)]
19945 "--"
19946 ["Blank Field" org-table-blank-field (org-at-table-p)]
19947 ["Edit Field" org-table-edit-field (org-at-table-p)]
19948 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19949 "--"
19950 ("Column"
19951 ["Move Column Left" org-metaleft (org-at-table-p)]
19952 ["Move Column Right" org-metaright (org-at-table-p)]
19953 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19954 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19955 ("Row"
19956 ["Move Row Up" org-metaup (org-at-table-p)]
19957 ["Move Row Down" org-metadown (org-at-table-p)]
19958 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19959 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19960 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19961 "--"
19962 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19963 ("Rectangle"
19964 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19965 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19966 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19967 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19968 "--"
19969 ("Calculate"
19970 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19971 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19972 ["Edit Formulas" org-edit-special (org-at-table-p)]
19973 "--"
19974 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19975 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19976 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19977 "--"
19978 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19979 "--"
19980 ["Sum Column/Rectangle" org-table-sum
19981 (or (org-at-table-p) (org-region-active-p))]
19982 ["Which Column?" org-table-current-column (org-at-table-p)])
19983 ["Debug Formulas"
19984 org-table-toggle-formula-debugger
19985 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19986 ["Show Col/Row Numbers"
19987 org-table-toggle-coordinate-overlays
19988 :style toggle
19989 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19990 "--"
19991 ["Create" org-table-create (and (not (org-at-table-p))
19992 org-enable-table-editor)]
19993 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19994 ["Import from File" org-table-import (not (org-at-table-p))]
19995 ["Export to File" org-table-export (org-at-table-p)]
19996 "--"
19997 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19999 (easy-menu-define org-org-menu org-mode-map "Org menu"
20000 '("Org"
20001 ("Show/Hide"
20002 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20003 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20004 ["Sparse Tree..." org-sparse-tree t]
20005 ["Reveal Context" org-reveal t]
20006 ["Show All" show-all t]
20007 "--"
20008 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20009 "--"
20010 ["New Heading" org-insert-heading t]
20011 ("Navigate Headings"
20012 ["Up" outline-up-heading t]
20013 ["Next" outline-next-visible-heading t]
20014 ["Previous" outline-previous-visible-heading t]
20015 ["Next Same Level" outline-forward-same-level t]
20016 ["Previous Same Level" outline-backward-same-level t]
20017 "--"
20018 ["Jump" org-goto t])
20019 ("Edit Structure"
20020 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20021 "--"
20022 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20023 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20024 "--"
20025 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20026 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20027 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20028 "--"
20029 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20030 "--"
20031 ["Copy visible text" org-copy-visible t]
20032 "--"
20033 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20034 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20035 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20036 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20037 "--"
20038 ["Sort Region/Children" org-sort t]
20039 "--"
20040 ["Convert to odd levels" org-convert-to-odd-levels t]
20041 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20042 ("Editing"
20043 ["Emphasis..." org-emphasize t]
20044 ["Edit Source Example" org-edit-special t]
20045 "--"
20046 ["Footnote new/jump" org-footnote-action t]
20047 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20048 ("Archive"
20049 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20050 "--"
20051 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20052 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20053 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20055 "--"
20056 ("Hyperlinks"
20057 ["Store Link (Global)" org-store-link t]
20058 ["Find existing link to here" org-occur-link-in-agenda-files t]
20059 ["Insert Link" org-insert-link t]
20060 ["Follow Link" org-open-at-point t]
20061 "--"
20062 ["Next link" org-next-link t]
20063 ["Previous link" org-previous-link t]
20064 "--"
20065 ["Descriptive Links"
20066 org-toggle-link-display
20067 :style radio
20068 :selected org-descriptive-links
20070 ["Literal Links"
20071 org-toggle-link-display
20072 :style radio
20073 :selected (not org-descriptive-links)])
20074 "--"
20075 ("TODO Lists"
20076 ["TODO/DONE/-" org-todo t]
20077 ("Select keyword"
20078 ["Next keyword" org-shiftright (org-at-heading-p)]
20079 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20080 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20081 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20082 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20083 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20084 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20085 "--"
20086 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20087 :selected org-enforce-todo-dependencies :style toggle :active t]
20088 "Settings for tree at point"
20089 ["Do Children sequentially" org-toggle-ordered-property :style radio
20090 :selected (org-entry-get nil "ORDERED")
20091 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20092 ["Do Children parallel" org-toggle-ordered-property :style radio
20093 :selected (not (org-entry-get nil "ORDERED"))
20094 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20095 "--"
20096 ["Set Priority" org-priority t]
20097 ["Priority Up" org-shiftup t]
20098 ["Priority Down" org-shiftdown t]
20099 "--"
20100 ["Get news from all feeds" org-feed-update-all t]
20101 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20102 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20103 ("TAGS and Properties"
20104 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20105 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20106 "--"
20107 ["Set property" org-set-property (not (org-before-first-heading-p))]
20108 ["Column view of properties" org-columns t]
20109 ["Insert Column View DBlock" org-insert-columns-dblock t])
20110 ("Dates and Scheduling"
20111 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20112 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20113 ("Change Date"
20114 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20115 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20116 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20117 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20118 ["Compute Time Range" org-evaluate-time-range t]
20119 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20120 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20121 "--"
20122 ["Custom time format" org-toggle-time-stamp-overlays
20123 :style radio :selected org-display-custom-times]
20124 "--"
20125 ["Goto Calendar" org-goto-calendar t]
20126 ["Date from Calendar" org-date-from-calendar t]
20127 "--"
20128 ["Start/Restart Timer" org-timer-start t]
20129 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20130 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20131 ["Insert Timer String" org-timer t]
20132 ["Insert Timer Item" org-timer-item t])
20133 ("Logging work"
20134 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20135 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20136 ["Clock out" org-clock-out t]
20137 ["Clock cancel" org-clock-cancel t]
20138 "--"
20139 ["Mark as default task" org-clock-mark-default-task t]
20140 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20141 ["Goto running clock" org-clock-goto t]
20142 "--"
20143 ["Display times" org-clock-display t]
20144 ["Create clock table" org-clock-report t]
20145 "--"
20146 ["Record DONE time"
20147 (progn (setq org-log-done (not org-log-done))
20148 (message "Switching to %s will %s record a timestamp"
20149 (car org-done-keywords)
20150 (if org-log-done "automatically" "not")))
20151 :style toggle :selected org-log-done])
20152 "--"
20153 ["Agenda Command..." org-agenda t]
20154 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20155 ("File List for Agenda")
20156 ("Special views current file"
20157 ["TODO Tree" org-show-todo-tree t]
20158 ["Check Deadlines" org-check-deadlines t]
20159 ["Timeline" org-timeline t]
20160 ["Tags/Property tree" org-match-sparse-tree t])
20161 "--"
20162 ["Export/Publish..." org-export t]
20163 ("LaTeX"
20164 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20165 :selected org-cdlatex-mode]
20166 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20167 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20168 ["Modify math symbol" org-cdlatex-math-modify
20169 (org-inside-LaTeX-fragment-p)]
20170 ["Insert citation" org-reftex-citation t]
20171 "--"
20172 ["Template for BEAMER" (progn (require 'org-beamer)
20173 (org-insert-beamer-options-template)) t])
20174 "--"
20175 ("MobileOrg"
20176 ["Push Files and Views" org-mobile-push t]
20177 ["Get Captured and Flagged" org-mobile-pull t]
20178 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20179 "--"
20180 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20181 "--"
20182 ("Documentation"
20183 ["Show Version" org-version t]
20184 ["Info Documentation" org-info t])
20185 ("Customize"
20186 ["Browse Org Group" org-customize t]
20187 "--"
20188 ["Expand This Menu" org-create-customize-menu
20189 (fboundp 'customize-menu-create)])
20190 ["Send bug report" org-submit-bug-report t]
20191 "--"
20192 ("Refresh/Reload"
20193 ["Refresh setup current buffer" org-mode-restart t]
20194 ["Reload Org (after update)" org-reload t]
20195 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20198 (defun org-info (&optional node)
20199 "Read documentation for Org-mode in the info system.
20200 With optional NODE, go directly to that node."
20201 (interactive)
20202 (info (format "(org)%s" (or node ""))))
20204 ;;;###autoload
20205 (defun org-submit-bug-report ()
20206 "Submit a bug report on Org-mode via mail.
20208 Don't hesitate to report any problems or inaccurate documentation.
20210 If you don't have setup sending mail from (X)Emacs, please copy the
20211 output buffer into your mail program, as it gives us important
20212 information about your Org-mode version and configuration."
20213 (interactive)
20214 (require 'reporter)
20215 (org-load-modules-maybe)
20216 (org-require-autoloaded-modules)
20217 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20218 (reporter-submit-bug-report
20219 "emacs-orgmode@gnu.org"
20220 (org-version nil 'full)
20221 (let (list)
20222 (save-window-excursion
20223 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20224 (delete-other-windows)
20225 (erase-buffer)
20226 (insert "You are about to submit a bug report to the Org-mode mailing list.
20228 We would like to add your full Org-mode and Outline configuration to the
20229 bug report. This greatly simplifies the work of the maintainer and
20230 other experts on the mailing list.
20232 HOWEVER, some variables you have customized may contain private
20233 information. The names of customers, colleagues, or friends, might
20234 appear in the form of file names, tags, todo states, or search strings.
20235 If you answer yes to the prompt, you might want to check and remove
20236 such private information before sending the email.")
20237 (add-text-properties (point-min) (point-max) '(face org-warning))
20238 (when (yes-or-no-p "Include your Org-mode configuration ")
20239 (mapatoms
20240 (lambda (v)
20241 (and (boundp v)
20242 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20243 (or (and (symbol-value v)
20244 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20245 (and
20246 (get v 'custom-type) (get v 'standard-value)
20247 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20248 (push v list)))))
20249 (kill-buffer (get-buffer "*Warn about privacy*"))
20250 list))
20251 nil nil
20252 "Remember to cover the basics, that is, what you expected to happen and
20253 what in fact did happen. You don't know how to make a good report? See
20255 http://orgmode.org/manual/Feedback.html#Feedback
20257 Your bug report will be posted to the Org-mode mailing list.
20258 ------------------------------------------------------------------------")
20259 (save-excursion
20260 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20261 (replace-match "\\1Bug: \\3 [\\2]")))))
20264 (defun org-install-agenda-files-menu ()
20265 (let ((bl (buffer-list)))
20266 (save-excursion
20267 (while bl
20268 (set-buffer (pop bl))
20269 (if (derived-mode-p 'org-mode) (setq bl nil)))
20270 (when (derived-mode-p 'org-mode)
20271 (easy-menu-change
20272 '("Org") "File List for Agenda"
20273 (append
20274 (list
20275 ["Edit File List" (org-edit-agenda-file-list) t]
20276 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20277 ["Remove Current File from List" org-remove-file t]
20278 ["Cycle through agenda files" org-cycle-agenda-files t]
20279 ["Occur in all agenda files" org-occur-in-agenda-files t]
20280 "--")
20281 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20283 ;;;; Documentation
20285 (defun org-require-autoloaded-modules ()
20286 (interactive)
20287 (mapc 'require
20288 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20289 org-docbook org-exp org-html org-icalendar
20290 org-id org-latex
20291 org-publish org-remember org-table
20292 org-timer org-xoxo)))
20294 ;;;###autoload
20295 (defun org-reload (&optional uncompiled)
20296 "Reload all org lisp files.
20297 With prefix arg UNCOMPILED, load the uncompiled versions."
20298 (interactive "P")
20299 (require 'loadhist)
20300 (let* ((org-dir (org-find-library-dir "org"))
20301 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20302 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20303 (remove-re (mapconcat 'identity
20304 (mapcar (lambda (f) (concat "^" f "$"))
20305 (list (if (featurep 'xemacs)
20306 "org-colview"
20307 "org-colview-xemacs")
20308 "org" "org-loaddefs" "org-version"))
20309 "\\|"))
20310 (feats (delete-dups
20311 (mapcar 'file-name-sans-extension
20312 (mapcar 'file-name-nondirectory
20313 (delq nil
20314 (mapcar 'feature-file
20315 features))))))
20316 (lfeat (append
20317 (sort
20318 (setq feats
20319 (delq nil (mapcar
20320 (lambda (f)
20321 (if (and (string-match feature-re f)
20322 (not (string-match remove-re f)))
20323 f nil))
20324 feats)))
20325 'string-lessp)
20326 (list "org-version" "org")))
20327 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20328 load-uncore load-misses)
20329 (setq load-misses
20330 (delq 't
20331 (mapcar (lambda (f)
20332 (or (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20333 (and (string= org-dir contrib-dir)
20334 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20335 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20336 (add-to-list 'load-uncore f 'append)
20339 lfeat)))
20340 (if load-uncore
20341 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20342 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20343 (if load-misses
20344 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20345 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20346 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20348 ;;;###autoload
20349 (defun org-customize ()
20350 "Call the customize function with org as argument."
20351 (interactive)
20352 (org-load-modules-maybe)
20353 (org-require-autoloaded-modules)
20354 (customize-browse 'org))
20356 (defun org-create-customize-menu ()
20357 "Create a full customization menu for Org-mode, insert it into the menu."
20358 (interactive)
20359 (org-load-modules-maybe)
20360 (org-require-autoloaded-modules)
20361 (if (fboundp 'customize-menu-create)
20362 (progn
20363 (easy-menu-change
20364 '("Org") "Customize"
20365 `(["Browse Org group" org-customize t]
20366 "--"
20367 ,(customize-menu-create 'org)
20368 ["Set" Custom-set t]
20369 ["Save" Custom-save t]
20370 ["Reset to Current" Custom-reset-current t]
20371 ["Reset to Saved" Custom-reset-saved t]
20372 ["Reset to Standard Settings" Custom-reset-standard t]))
20373 (message "\"Org\"-menu now contains full customization menu"))
20374 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20376 ;;;; Miscellaneous stuff
20378 ;;; Generally useful functions
20380 (defun org-get-at-bol (property)
20381 "Get text property PROPERTY at beginning of line."
20382 (get-text-property (point-at-bol) property))
20384 (defun org-find-text-property-in-string (prop s)
20385 "Return the first non-nil value of property PROP in string S."
20386 (or (get-text-property 0 prop s)
20387 (get-text-property (or (next-single-property-change 0 prop s) 0)
20388 prop s)))
20390 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20391 "Display the given MESSAGE as a warning."
20392 (if (fboundp 'display-warning)
20393 (display-warning 'org message
20394 (if (featurep 'xemacs) 'warning :warning))
20395 (let ((buf (get-buffer-create "*Org warnings*")))
20396 (with-current-buffer buf
20397 (goto-char (point-max))
20398 (insert "Warning (Org): " message)
20399 (unless (bolp)
20400 (newline)))
20401 (display-buffer buf)
20402 (sit-for 0))))
20404 (defun org-eval (form)
20405 "Eval FORM and return result."
20406 (condition-case error
20407 (eval form)
20408 (error (format "%%![Error: %s]" error))))
20410 (defun org-in-clocktable-p ()
20411 "Check if the cursor is in a clocktable."
20412 (let ((pos (point)) start)
20413 (save-excursion
20414 (end-of-line 1)
20415 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20416 (setq start (match-beginning 0))
20417 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20418 (>= (match-end 0) pos)
20419 start))))
20421 (defun org-in-commented-line ()
20422 "Is point in a line starting with `#'?"
20423 (equal (char-after (point-at-bol)) ?#))
20425 (defun org-in-indented-comment-line ()
20426 "Is point in a line starting with `#' after some white space?"
20427 (save-excursion
20428 (save-match-data
20429 (goto-char (point-at-bol))
20430 (looking-at "[ \t]*#"))))
20432 (defun org-in-verbatim-emphasis ()
20433 (save-match-data
20434 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20436 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20437 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20438 (if (and marker (marker-buffer marker)
20439 (buffer-live-p (marker-buffer marker)))
20440 (progn
20441 (org-pop-to-buffer-same-window (marker-buffer marker))
20442 (if (or (> marker (point-max)) (< marker (point-min)))
20443 (widen))
20444 (goto-char marker)
20445 (org-show-context 'org-goto))
20446 (if bookmark
20447 (bookmark-jump bookmark)
20448 (error "Cannot find location"))))
20450 (defun org-quote-csv-field (s)
20451 "Quote field for inclusion in CSV material."
20452 (if (string-match "[\",]" s)
20453 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20456 (defun org-force-self-insert (N)
20457 "Needed to enforce self-insert under remapping."
20458 (interactive "p")
20459 (self-insert-command N))
20461 (defun org-string-width (s)
20462 "Compute width of string, ignoring invisible characters.
20463 This ignores character with invisibility property `org-link', and also
20464 characters with property `org-cwidth', because these will become invisible
20465 upon the next fontification round."
20466 (let (b l)
20467 (when (or (eq t buffer-invisibility-spec)
20468 (assq 'org-link buffer-invisibility-spec))
20469 (while (setq b (text-property-any 0 (length s)
20470 'invisible 'org-link s))
20471 (setq s (concat (substring s 0 b)
20472 (substring s (or (next-single-property-change
20473 b 'invisible s) (length s)))))))
20474 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20475 (setq s (concat (substring s 0 b)
20476 (substring s (or (next-single-property-change
20477 b 'org-cwidth s) (length s))))))
20478 (setq l (string-width s) b -1)
20479 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20480 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20483 (defun org-shorten-string (s maxlength)
20484 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20485 If the string is shorter or has length MAXLENGTH, just return the
20486 original string. If it is longer, the functions finds a space in the
20487 string, breaks this string off at that locations and adds three dots
20488 as ellipsis. Including the ellipsis, the string will not be longer
20489 than MAXLENGTH. If finding a good breaking point in the string does
20490 not work, the string is just chopped off in the middle of a word
20491 if necessary."
20492 (if (<= (length s) maxlength)
20494 (let* ((n (max (- maxlength 4) 1))
20495 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20496 (if (string-match re s)
20497 (concat (match-string 1 s) "...")
20498 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20500 (defun org-get-indentation (&optional line)
20501 "Get the indentation of the current line, interpreting tabs.
20502 When LINE is given, assume it represents a line and compute its indentation."
20503 (if line
20504 (if (string-match "^ *" (org-remove-tabs line))
20505 (match-end 0))
20506 (save-excursion
20507 (beginning-of-line 1)
20508 (skip-chars-forward " \t")
20509 (current-column))))
20511 (defun org-get-string-indentation (s)
20512 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20513 (let ((n -1) (i 0) (w tab-width) c)
20514 (catch 'exit
20515 (while (< (setq n (1+ n)) (length s))
20516 (setq c (aref s n))
20517 (cond ((= c ?\ ) (setq i (1+ i)))
20518 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20519 (t (throw 'exit t)))))
20522 (defun org-remove-tabs (s &optional width)
20523 "Replace tabulators in S with spaces.
20524 Assumes that s is a single line, starting in column 0."
20525 (setq width (or width tab-width))
20526 (while (string-match "\t" s)
20527 (setq s (replace-match
20528 (make-string
20529 (- (* width (/ (+ (match-beginning 0) width) width))
20530 (match-beginning 0)) ?\ )
20531 t t s)))
20534 (defun org-fix-indentation (line ind)
20535 "Fix indentation in LINE.
20536 IND is a cons cell with target and minimum indentation.
20537 If the current indentation in LINE is smaller than the minimum,
20538 leave it alone. If it is larger than ind, set it to the target."
20539 (let* ((l (org-remove-tabs line))
20540 (i (org-get-indentation l))
20541 (i1 (car ind)) (i2 (cdr ind)))
20542 (if (>= i i2) (setq l (substring line i2)))
20543 (if (> i1 0)
20544 (concat (make-string i1 ?\ ) l)
20545 l)))
20547 (defun org-remove-indentation (code &optional n)
20548 "Remove the maximum common indentation from the lines in CODE.
20549 N may optionally be the number of spaces to remove."
20550 (with-temp-buffer
20551 (insert code)
20552 (org-do-remove-indentation n)
20553 (buffer-string)))
20555 (defun org-do-remove-indentation (&optional n)
20556 "Remove the maximum common indentation from the buffer."
20557 (untabify (point-min) (point-max))
20558 (let ((min 10000) re)
20559 (if n
20560 (setq min n)
20561 (goto-char (point-min))
20562 (while (re-search-forward "^ *[^ \n]" nil t)
20563 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20564 (unless (or (= min 0) (= min 10000))
20565 (setq re (format "^ \\{%d\\}" min))
20566 (goto-char (point-min))
20567 (while (re-search-forward re nil t)
20568 (replace-match "")
20569 (end-of-line 1))
20570 min)))
20572 (defun org-fill-template (template alist)
20573 "Find each %key of ALIST in TEMPLATE and replace it."
20574 (let ((case-fold-search nil)
20575 entry key value)
20576 (setq alist (sort (copy-sequence alist)
20577 (lambda (a b) (< (length (car a)) (length (car b))))))
20578 (while (setq entry (pop alist))
20579 (setq template
20580 (replace-regexp-in-string
20581 (concat "%" (regexp-quote (car entry)))
20582 (or (cdr entry) "") template t t)))
20583 template))
20585 (defun org-base-buffer (buffer)
20586 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20587 (if (not buffer)
20588 buffer
20589 (or (buffer-base-buffer buffer)
20590 buffer)))
20592 (defun org-trim (s)
20593 "Remove whitespace at beginning and end of string."
20594 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20595 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20598 (defun org-wrap (string &optional width lines)
20599 "Wrap string to either a number of lines, or a width in characters.
20600 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20601 that costs. If there is a word longer than WIDTH, the text is actually
20602 wrapped to the length of that word.
20603 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20604 many lines, whatever width that takes.
20605 The return value is a list of lines, without newlines at the end."
20606 (let* ((words (org-split-string string "[ \t\n]+"))
20607 (maxword (apply 'max (mapcar 'org-string-width words)))
20608 w ll)
20609 (cond (width
20610 (org-do-wrap words (max maxword width)))
20611 (lines
20612 (setq w maxword)
20613 (setq ll (org-do-wrap words maxword))
20614 (if (<= (length ll) lines)
20616 (setq ll words)
20617 (while (> (length ll) lines)
20618 (setq w (1+ w))
20619 (setq ll (org-do-wrap words w)))
20620 ll))
20621 (t (error "Cannot wrap this")))))
20623 (defun org-do-wrap (words width)
20624 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20625 (let (lines line)
20626 (while words
20627 (setq line (pop words))
20628 (while (and words (< (+ (length line) (length (car words))) width))
20629 (setq line (concat line " " (pop words))))
20630 (setq lines (push line lines)))
20631 (nreverse lines)))
20633 (defun org-split-string (string &optional separators)
20634 "Splits STRING into substrings at SEPARATORS.
20635 No empty strings are returned if there are matches at the beginning
20636 and end of string."
20637 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20638 (start 0)
20639 notfirst
20640 (list nil))
20641 (while (and (string-match rexp string
20642 (if (and notfirst
20643 (= start (match-beginning 0))
20644 (< start (length string)))
20645 (1+ start) start))
20646 (< (match-beginning 0) (length string)))
20647 (setq notfirst t)
20648 (or (eq (match-beginning 0) 0)
20649 (and (eq (match-beginning 0) (match-end 0))
20650 (eq (match-beginning 0) start))
20651 (setq list
20652 (cons (substring string start (match-beginning 0))
20653 list)))
20654 (setq start (match-end 0)))
20655 (or (eq start (length string))
20656 (setq list
20657 (cons (substring string start)
20658 list)))
20659 (nreverse list)))
20661 (defun org-quote-vert (s)
20662 "Replace \"|\" with \"\\vert\"."
20663 (while (string-match "|" s)
20664 (setq s (replace-match "\\vert" t t s)))
20667 (defun org-uuidgen-p (s)
20668 "Is S an ID created by UUIDGEN?"
20669 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20671 (defun org-in-src-block-p (&optional inside)
20672 "Whether point is in a code source block.
20673 When INSIDE is non-nil, don't consider we are within a src block
20674 when point is at #+BEGIN_SRC or #+END_SRC."
20675 (let ((case-fold-search t) ov)
20676 (or (and (setq ov (overlays-at (point)))
20677 (memq 'org-block-background
20678 (overlay-properties (car ov))))
20679 (and (not inside)
20680 (save-match-data
20681 (save-excursion
20682 (beginning-of-line)
20683 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20685 (defun org-context ()
20686 "Return a list of contexts of the current cursor position.
20687 If several contexts apply, all are returned.
20688 Each context entry is a list with a symbol naming the context, and
20689 two positions indicating start and end of the context. Possible
20690 contexts are:
20692 :headline anywhere in a headline
20693 :headline-stars on the leading stars in a headline
20694 :todo-keyword on a TODO keyword (including DONE) in a headline
20695 :tags on the TAGS in a headline
20696 :priority on the priority cookie in a headline
20697 :item on the first line of a plain list item
20698 :item-bullet on the bullet/number of a plain list item
20699 :checkbox on the checkbox in a plain list item
20700 :table in an org-mode table
20701 :table-special on a special filed in a table
20702 :table-table in a table.el table
20703 :clocktable in a clocktable
20704 :src-block in a source block
20705 :link on a hyperlink
20706 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20707 :target on a <<target>>
20708 :radio-target on a <<<radio-target>>>
20709 :latex-fragment on a LaTeX fragment
20710 :latex-preview on a LaTeX fragment with overlaid preview image
20712 This function expects the position to be visible because it uses font-lock
20713 faces as a help to recognize the following contexts: :table-special, :link,
20714 and :keyword."
20715 (let* ((f (get-text-property (point) 'face))
20716 (faces (if (listp f) f (list f)))
20717 (case-fold-search t)
20718 (p (point)) clist o)
20719 ;; First the large context
20720 (cond
20721 ((org-at-heading-p t)
20722 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20723 (when (progn
20724 (beginning-of-line 1)
20725 (looking-at org-todo-line-tags-regexp))
20726 (push (org-point-in-group p 1 :headline-stars) clist)
20727 (push (org-point-in-group p 2 :todo-keyword) clist)
20728 (push (org-point-in-group p 4 :tags) clist))
20729 (goto-char p)
20730 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20731 (if (looking-at "\\[#[A-Z0-9]\\]")
20732 (push (org-point-in-group p 0 :priority) clist)))
20734 ((org-at-item-p)
20735 (push (org-point-in-group p 2 :item-bullet) clist)
20736 (push (list :item (point-at-bol)
20737 (save-excursion (org-end-of-item) (point)))
20738 clist)
20739 (and (org-at-item-checkbox-p)
20740 (push (org-point-in-group p 0 :checkbox) clist)))
20742 ((org-at-table-p)
20743 (push (list :table (org-table-begin) (org-table-end)) clist)
20744 (if (memq 'org-formula faces)
20745 (push (list :table-special
20746 (previous-single-property-change p 'face)
20747 (next-single-property-change p 'face)) clist)))
20748 ((org-at-table-p 'any)
20749 (push (list :table-table) clist)))
20750 (goto-char p)
20752 (let ((case-fold-search t))
20753 ;; New the "medium" contexts: clocktables, source blocks
20754 (cond ((org-in-clocktable-p)
20755 (push (list :clocktable
20756 (and (or (looking-at "#\\+BEGIN: clocktable")
20757 (search-backward "#+BEGIN: clocktable" nil t))
20758 (match-beginning 0))
20759 (and (re-search-forward "#\\+END:?" nil t)
20760 (match-end 0))) clist))
20761 ((org-in-src-block-p)
20762 (push (list :src-block
20763 (and (or (looking-at "#\\+BEGIN_SRC")
20764 (search-backward "#+BEGIN_SRC" nil t))
20765 (match-beginning 0))
20766 (and (search-forward "#+END_SRC" nil t)
20767 (match-beginning 0))) clist))))
20768 (goto-char p)
20770 ;; Now the small context
20771 (cond
20772 ((org-at-timestamp-p)
20773 (push (org-point-in-group p 0 :timestamp) clist))
20774 ((memq 'org-link faces)
20775 (push (list :link
20776 (previous-single-property-change p 'face)
20777 (next-single-property-change p 'face)) clist))
20778 ((memq 'org-special-keyword faces)
20779 (push (list :keyword
20780 (previous-single-property-change p 'face)
20781 (next-single-property-change p 'face)) clist))
20782 ((org-at-target-p)
20783 (push (org-point-in-group p 0 :target) clist)
20784 (goto-char (1- (match-beginning 0)))
20785 (if (looking-at org-radio-target-regexp)
20786 (push (org-point-in-group p 0 :radio-target) clist))
20787 (goto-char p))
20788 ((setq o (car (delq nil
20789 (mapcar
20790 (lambda (x)
20791 (if (memq x org-latex-fragment-image-overlays) x))
20792 (overlays-at (point))))))
20793 (push (list :latex-fragment
20794 (overlay-start o) (overlay-end o)) clist)
20795 (push (list :latex-preview
20796 (overlay-start o) (overlay-end o)) clist))
20797 ((org-inside-LaTeX-fragment-p)
20798 ;; FIXME: positions wrong.
20799 (push (list :latex-fragment (point) (point)) clist)))
20801 (setq clist (nreverse (delq nil clist)))
20802 clist))
20804 ;; FIXME: Compare with at-regexp-p Do we need both?
20805 (defun org-in-regexp (re &optional nlines visually)
20806 "Check if point is inside a match of regexp.
20807 Normally only the current line is checked, but you can include NLINES extra
20808 lines both before and after point into the search.
20809 If VISUALLY is set, require that the cursor is not after the match but
20810 really on, so that the block visually is on the match."
20811 (catch 'exit
20812 (let ((pos (point))
20813 (eol (point-at-eol (+ 1 (or nlines 0))))
20814 (inc (if visually 1 0)))
20815 (save-excursion
20816 (beginning-of-line (- 1 (or nlines 0)))
20817 (while (re-search-forward re eol t)
20818 (if (and (<= (match-beginning 0) pos)
20819 (>= (+ inc (match-end 0)) pos))
20820 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20822 (defun org-at-regexp-p (regexp)
20823 "Is point inside a match of REGEXP in the current line?"
20824 (catch 'exit
20825 (save-excursion
20826 (let ((pos (point)) (end (point-at-eol)))
20827 (beginning-of-line 1)
20828 (while (re-search-forward regexp end t)
20829 (if (and (<= (match-beginning 0) pos)
20830 (>= (match-end 0) pos))
20831 (throw 'exit t)))
20832 nil))))
20834 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20835 "Non-nil when point is between matches of START-RE and END-RE.
20837 Also return a non-nil value when point is on one of the matches.
20839 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20840 buffer positions. Default values are the positions of headlines
20841 surrounding the point.
20843 The functions returns a cons cell whose car (resp. cdr) is the
20844 position before START-RE (resp. after END-RE)."
20845 (save-match-data
20846 (let ((pos (point))
20847 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20848 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20849 beg end)
20850 (save-excursion
20851 ;; Point is on a block when on START-RE or if START-RE can be
20852 ;; found before it...
20853 (and (or (org-at-regexp-p start-re)
20854 (re-search-backward start-re limit-up t))
20855 (setq beg (match-beginning 0))
20856 ;; ... and END-RE after it...
20857 (goto-char (match-end 0))
20858 (re-search-forward end-re limit-down t)
20859 (> (setq end (match-end 0)) pos)
20860 ;; ... without another START-RE in-between.
20861 (goto-char (match-beginning 0))
20862 (not (re-search-backward start-re (1+ beg) t))
20863 ;; Return value.
20864 (cons beg end))))))
20866 (defun org-in-block-p (names)
20867 "Non-nil when point belongs to a block whose name belongs to NAMES.
20869 NAMES is a list of strings containing names of blocks.
20871 Return first block name matched, or nil. Beware that in case of
20872 nested blocks, the returned name may not belong to the closest
20873 block from point."
20874 (save-match-data
20875 (catch 'exit
20876 (let ((case-fold-search t)
20877 (lim-up (save-excursion (outline-previous-heading)))
20878 (lim-down (save-excursion (outline-next-heading))))
20879 (mapc (lambda (name)
20880 (let ((n (regexp-quote name)))
20881 (when (org-between-regexps-p
20882 (concat "^[ \t]*#\\+begin_" n)
20883 (concat "^[ \t]*#\\+end_" n)
20884 lim-up lim-down)
20885 (throw 'exit n))))
20886 names))
20887 nil)))
20889 (defun org-occur-in-agenda-files (regexp &optional nlines)
20890 "Call `multi-occur' with buffers for all agenda files."
20891 (interactive "sOrg-files matching: \np")
20892 (let* ((files (org-agenda-files))
20893 (tnames (mapcar 'file-truename files))
20894 (extra org-agenda-text-search-extra-files)
20896 (when (eq (car extra) 'agenda-archives)
20897 (setq extra (cdr extra))
20898 (setq files (org-add-archive-files files)))
20899 (while (setq f (pop extra))
20900 (unless (member (file-truename f) tnames)
20901 (add-to-list 'files f 'append)
20902 (add-to-list 'tnames (file-truename f) 'append)))
20903 (multi-occur
20904 (mapcar (lambda (x)
20905 (with-current-buffer
20906 (or (get-file-buffer x) (find-file-noselect x))
20907 (widen)
20908 (current-buffer)))
20909 files)
20910 regexp)))
20912 (if (boundp 'occur-mode-find-occurrence-hook)
20913 ;; Emacs 23
20914 (add-hook 'occur-mode-find-occurrence-hook
20915 (lambda ()
20916 (when (derived-mode-p 'org-mode)
20917 (org-reveal))))
20918 ;; Emacs 22
20919 (defadvice occur-mode-goto-occurrence
20920 (after org-occur-reveal activate)
20921 (and (derived-mode-p 'org-mode) (org-reveal)))
20922 (defadvice occur-mode-goto-occurrence-other-window
20923 (after org-occur-reveal activate)
20924 (and (derived-mode-p 'org-mode) (org-reveal)))
20925 (defadvice occur-mode-display-occurrence
20926 (after org-occur-reveal activate)
20927 (when (derived-mode-p 'org-mode)
20928 (let ((pos (occur-mode-find-occurrence)))
20929 (with-current-buffer (marker-buffer pos)
20930 (save-excursion
20931 (goto-char pos)
20932 (org-reveal)))))))
20934 (defun org-occur-link-in-agenda-files ()
20935 "Create a link and search for it in the agendas.
20936 The link is not stored in `org-stored-links', it is just created
20937 for the search purpose."
20938 (interactive)
20939 (let ((link (condition-case nil
20940 (org-store-link nil)
20941 (error "Unable to create a link to here"))))
20942 (org-occur-in-agenda-files (regexp-quote link))))
20944 (defun org-uniquify (list)
20945 "Remove duplicate elements from LIST."
20946 (let (res)
20947 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20948 res))
20950 (defun org-delete-all (elts list)
20951 "Remove all elements in ELTS from LIST."
20952 (while elts
20953 (setq list (delete (pop elts) list)))
20954 list)
20956 (defun org-count (cl-item cl-seq)
20957 "Count the number of occurrences of ITEM in SEQ.
20958 Taken from `count' in cl-seq.el with all keyword arguments removed."
20959 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20960 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20961 (while (< cl-start cl-end)
20962 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20963 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20964 (setq cl-start (1+ cl-start)))
20965 cl-count))
20967 (defun org-remove-if (predicate seq)
20968 "Remove everything from SEQ that fulfills PREDICATE."
20969 (let (res e)
20970 (while seq
20971 (setq e (pop seq))
20972 (if (not (funcall predicate e)) (push e res)))
20973 (nreverse res)))
20975 (defun org-remove-if-not (predicate seq)
20976 "Remove everything from SEQ that does not fulfill PREDICATE."
20977 (let (res e)
20978 (while seq
20979 (setq e (pop seq))
20980 (if (funcall predicate e) (push e res)))
20981 (nreverse res)))
20983 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20984 "Reduce two-argument FUNCTION across SEQ.
20985 Taken from `reduce' in cl-seq.el with all keyword arguments but
20986 \":initial-value\" removed."
20987 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20988 (cadr (memq :initial-value cl-keys)))
20989 (cl-seq (pop cl-seq))
20990 (t (funcall cl-func)))))
20991 (while cl-seq
20992 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20993 cl-accum))
20995 (defun org-back-over-empty-lines ()
20996 "Move backwards over whitespace, to the beginning of the first empty line.
20997 Returns the number of empty lines passed."
20998 (let ((pos (point)))
20999 (if (cdr (assoc 'heading org-blank-before-new-entry))
21000 (skip-chars-backward " \t\n\r")
21001 (unless (eobp)
21002 (forward-line -1)))
21003 (beginning-of-line 2)
21004 (goto-char (min (point) pos))
21005 (count-lines (point) pos)))
21007 (defun org-skip-whitespace ()
21008 (skip-chars-forward " \t\n\r"))
21010 (defun org-point-in-group (point group &optional context)
21011 "Check if POINT is in match-group GROUP.
21012 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21013 match. If the match group does not exist or point is not inside it,
21014 return nil."
21015 (and (match-beginning group)
21016 (>= point (match-beginning group))
21017 (<= point (match-end group))
21018 (if context
21019 (list context (match-beginning group) (match-end group))
21020 t)))
21022 (defun org-switch-to-buffer-other-window (&rest args)
21023 "Switch to buffer in a second window on the current frame.
21024 In particular, do not allow pop-up frames.
21025 Returns the newly created buffer."
21026 (org-no-popups
21027 (apply 'switch-to-buffer-other-window args)))
21029 (defun org-combine-plists (&rest plists)
21030 "Create a single property list from all plists in PLISTS.
21031 The process starts by copying the first list, and then setting properties
21032 from the other lists. Settings in the last list are the most significant
21033 ones and overrule settings in the other lists."
21034 (let ((rtn (copy-sequence (pop plists)))
21035 p v ls)
21036 (while plists
21037 (setq ls (pop plists))
21038 (while ls
21039 (setq p (pop ls) v (pop ls))
21040 (setq rtn (plist-put rtn p v))))
21041 rtn))
21043 (defun org-replace-escapes (string table)
21044 "Replace %-escapes in STRING with values in TABLE.
21045 TABLE is an association list with keys like \"%a\" and string values.
21046 The sequences in STRING may contain normal field width and padding information,
21047 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21048 so values can contain further %-escapes if they are define later in TABLE."
21049 (let ((tbl (copy-alist table))
21050 (case-fold-search nil)
21051 (pchg 0)
21052 e re rpl)
21053 (while (setq e (pop tbl))
21054 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21055 (when (and (cdr e) (string-match re (cdr e)))
21056 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21057 (safe "SREF"))
21058 (add-text-properties 0 3 (list 'sref sref) safe)
21059 (setcdr e (replace-match safe t t (cdr e)))))
21060 (while (string-match re string)
21061 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21062 (cdr e)))
21063 (setq string (replace-match rpl t t string))))
21064 (while (setq pchg (next-property-change pchg string))
21065 (let ((sref (get-text-property pchg 'sref string)))
21066 (when (and sref (string-match "SREF" string pchg))
21067 (setq string (replace-match sref t t string)))))
21068 string))
21070 (defun org-sublist (list start end)
21071 "Return a section of LIST, from START to END.
21072 Counting starts at 1."
21073 (let (rtn (c start))
21074 (setq list (nthcdr (1- start) list))
21075 (while (and list (<= c end))
21076 (push (pop list) rtn)
21077 (setq c (1+ c)))
21078 (nreverse rtn)))
21080 (defun org-find-base-buffer-visiting (file)
21081 "Like `find-buffer-visiting' but always return the base buffer and
21082 not an indirect buffer."
21083 (let ((buf (or (get-file-buffer file)
21084 (find-buffer-visiting file))))
21085 (if buf
21086 (or (buffer-base-buffer buf) buf)
21087 nil)))
21089 (defun org-image-file-name-regexp (&optional extensions)
21090 "Return regexp matching the file names of images.
21091 If EXTENSIONS is given, only match these."
21092 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21093 (image-file-name-regexp)
21094 (let ((image-file-name-extensions
21095 (or extensions
21096 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21097 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21098 (concat "\\."
21099 (regexp-opt (nconc (mapcar 'upcase
21100 image-file-name-extensions)
21101 image-file-name-extensions)
21103 "\\'"))))
21105 (defun org-file-image-p (file &optional extensions)
21106 "Return non-nil if FILE is an image."
21107 (save-match-data
21108 (string-match (org-image-file-name-regexp extensions) file)))
21110 (defun org-get-cursor-date (&optional with-time)
21111 "Return the date at cursor in as a time.
21112 This works in the calendar and in the agenda, anywhere else it just
21113 returns the current time.
21114 If WITH-TIME is non-nil, returns the time of the event at point (in
21115 the agenda) or the current time of the day."
21116 (let (date day defd tp tm hod mod)
21117 (when with-time
21118 (setq tp (get-text-property (point) 'time))
21119 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21120 (setq hod (string-to-number (match-string 1 tp))
21121 mod (string-to-number (match-string 2 tp))))
21122 (or tp (setq hod (nth 2 (decode-time (current-time)))
21123 mod (nth 1 (decode-time (current-time))))))
21124 (cond
21125 ((eq major-mode 'calendar-mode)
21126 (setq date (calendar-cursor-to-date)
21127 defd (encode-time 0 (or mod 0) (or hod 0)
21128 (nth 1 date) (nth 0 date) (nth 2 date))))
21129 ((eq major-mode 'org-agenda-mode)
21130 (setq day (get-text-property (point) 'day))
21131 (if day
21132 (setq date (calendar-gregorian-from-absolute day)
21133 defd (encode-time 0 (or mod 0) (or hod 0)
21134 (nth 1 date) (nth 0 date) (nth 2 date))))))
21135 (or defd (current-time))))
21137 (defun org-mark-subtree (&optional up)
21138 "Mark the current subtree.
21139 This puts point at the start of the current subtree, and mark at
21140 the end. If a numeric prefix UP is given, move up into the
21141 hierarchy of headlines by UP levels before marking the subtree."
21142 (interactive "P")
21143 (org-with-limited-levels
21144 (cond ((org-at-heading-p) (beginning-of-line))
21145 ((org-before-first-heading-p) (error "Not in a subtree"))
21146 (t (outline-previous-visible-heading 1))))
21147 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21148 (if (org-called-interactively-p 'any)
21149 (call-interactively 'org-mark-element)
21150 (org-mark-element)))
21153 ;;; Macros
21155 ;; Macros are expanded with `org-macro-replace-all', which relies
21156 ;; internally on `org-macro-expand'.
21158 ;; Default templates for expansion are stored in the buffer-local
21159 ;; variable `org-macro-templates'. This variable is updated by
21160 ;; `org-macro-initialize-templates'.
21162 ;; Along with macros defined through #+MACRO: keyword, default
21163 ;; templates include the following hard-coded macros:
21164 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21165 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21167 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21168 ;; {{{title}}} will also be provided.
21171 (defvar org-macro-templates nil
21172 "Alist containing all macro templates in current buffer.
21173 Associations are in the shape of (NAME . TEMPLATE) where NAME
21174 stands for macro's name and template for its replacement value,
21175 both as strings. This is an internal variable. Do not set it
21176 directly, use instead:
21178 #+MACRO: name template")
21179 (make-variable-buffer-local 'org-macro-templates)
21181 (defun org-macro-expand (macro templates)
21182 "Return expanded MACRO, as a string.
21183 MACRO is an object, obtained, for example, with
21184 `org-element-context'. TEMPLATES is an alist of templates used
21185 for expansion. See `org-macro-templates' for a buffer-local
21186 default value. Return nil if no template was found."
21187 (let ((template
21188 ;; Macro names are case-insensitive.
21189 (cdr (assoc-string (org-element-property :key macro) templates t))))
21190 (when template
21191 (let ((value (replace-regexp-in-string
21192 "\\$[0-9]+"
21193 (lambda (arg)
21194 (or (nth (1- (string-to-number (substring arg 1)))
21195 (org-element-property :args macro))
21196 ;; No argument provided: remove
21197 ;; place-holder.
21198 ""))
21199 template)))
21200 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21201 (when (string-match "\\`(eval\\>" value)
21202 (setq value (eval (read value))))
21203 ;; Return string.
21204 (format "%s" (or value ""))))))
21206 (defun org-macro-replace-all (templates)
21207 "Replace all macros in current buffer by their expansion.
21208 TEMPLATES is an alist of templates used for expansion. See
21209 `org-macro-templates' for a buffer-local default value."
21210 (save-excursion
21211 (goto-char (point-min))
21212 (let (record)
21213 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21214 (let ((object (org-element-context)))
21215 (when (eq (org-element-type object) 'macro)
21216 (let* ((value (org-macro-expand object templates))
21217 (begin (org-element-property :begin object))
21218 (signature (list begin
21219 object
21220 (org-element-property :args object))))
21221 ;; Avoid circular dependencies by checking if the same
21222 ;; macro with the same arguments is expanded at the same
21223 ;; position twice.
21224 (if (member signature record)
21225 (error "Circular macro expansion: %s"
21226 (org-element-property :key object))
21227 (when value
21228 (push signature record)
21229 (delete-region
21230 begin
21231 ;; Preserve white spaces after the macro.
21232 (progn (goto-char (org-element-property :end object))
21233 (skip-chars-backward " \t")
21234 (point)))
21235 ;; Leave point before replacement in case of recursive
21236 ;; expansions.
21237 (save-excursion (insert value)))))))))))
21239 (defun org-macro-initialize-templates ()
21240 "Collect macro templates defined in current buffer.
21241 Templates are stored in buffer-local variable
21242 `org-macro-templates'. In addition to buffer-defined macros, the
21243 function installs the following ones: \"property\",
21244 \"time\". and, if the buffer is associated to a file,
21245 \"input-file\" and \"modification-time\"."
21246 (let ((case-fold-search t)
21247 (set-template
21248 (lambda (cell)
21249 ;; Add CELL to `org-macro-templates' if there's no
21250 ;; association matching its name already. Otherwise,
21251 ;; replace old association with the new one in that
21252 ;; variable.
21253 (let ((old-template (assoc (car cell) org-macro-templates)))
21254 (if old-template (setcdr old-template (cdr cell))
21255 (push cell org-macro-templates))))))
21256 ;; Install buffer-local macros.
21257 (org-with-wide-buffer
21258 (goto-char (point-min))
21259 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21260 (let ((element (org-element-at-point)))
21261 (when (eq (org-element-type element) 'keyword)
21262 (let ((value (org-element-property :value element)))
21263 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21264 (funcall set-template
21265 (cons (match-string 1 value)
21266 (or (match-string 2 value) "")))))))))
21267 ;; Install hard-coded macros.
21268 (mapc (lambda (cell) (funcall set-template cell))
21269 (list
21270 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21271 (cons "time" "(eval (format-time-string \"$1\"))")))
21272 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21273 (when (and visited-file (file-exists-p visited-file))
21274 (mapc (lambda (cell) (funcall set-template cell))
21275 (list
21276 (cons "input-file" (file-name-nondirectory visited-file))
21277 (cons "modification-time"
21278 (format "(eval (format-time-string \"$1\" '%s))"
21279 (prin1-to-string
21280 (nth 5 (file-attributes visited-file)))))))))))
21283 ;;; Indentation
21285 (defun org-indent-line ()
21286 "Indent line depending on context."
21287 (interactive)
21288 (let* ((pos (point))
21289 (itemp (org-at-item-p))
21290 (case-fold-search t)
21291 (org-drawer-regexp (or org-drawer-regexp "\000"))
21292 (inline-task-p (and (featurep 'org-inlinetask)
21293 (org-inlinetask-in-task-p)))
21294 (inline-re (and inline-task-p
21295 (org-inlinetask-outline-regexp)))
21296 column)
21297 (if (and orgstruct-is-++ (eq pos (point)))
21298 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21299 (indent-according-to-mode))
21300 (beginning-of-line 1)
21301 (cond
21302 ;; Headings
21303 ((looking-at org-outline-regexp) (setq column 0))
21304 ;; Included files
21305 ((looking-at "#\\+include:") (setq column 0))
21306 ;; Footnote definition
21307 ((looking-at org-footnote-definition-re) (setq column 0))
21308 ;; Literal examples
21309 ((looking-at "[ \t]*:\\( \\|$\\)")
21310 (setq column (org-get-indentation))) ; do nothing
21311 ;; Lists
21312 ((ignore-errors (goto-char (org-in-item-p)))
21313 (setq column (if itemp
21314 (org-get-indentation)
21315 (org-list-item-body-column (point))))
21316 (goto-char pos))
21317 ;; Drawers
21318 ((and (looking-at "[ \t]*:END:")
21319 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21320 (save-excursion
21321 (goto-char (1- (match-beginning 1)))
21322 (setq column (current-column))))
21323 ;; Special blocks
21324 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21325 (save-excursion
21326 (re-search-backward
21327 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21328 (setq column (org-get-indentation (match-string 0))))
21329 ((and (not (looking-at "[ \t]*#\\+begin_"))
21330 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21331 (save-excursion
21332 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21333 (setq column
21334 (cond ((equal (downcase (match-string 1)) "src")
21335 ;; src blocks: let `org-edit-src-exit' handle them
21336 (org-get-indentation))
21337 ((equal (downcase (match-string 1)) "example")
21338 (max (org-get-indentation)
21339 (org-get-indentation (match-string 0))))
21341 (org-get-indentation (match-string 0))))))
21342 ;; This line has nothing special, look at the previous relevant
21343 ;; line to compute indentation
21345 (beginning-of-line 0)
21346 (while (and (not (bobp))
21347 (not (looking-at org-drawer-regexp))
21348 ;; When point started in an inline task, do not move
21349 ;; above task starting line.
21350 (not (and inline-task-p (looking-at inline-re)))
21351 ;; Skip drawers, blocks, empty lines, verbatim,
21352 ;; comments, tables, footnotes definitions, lists,
21353 ;; inline tasks.
21354 (or (and (looking-at "[ \t]*:END:")
21355 (re-search-backward org-drawer-regexp nil t))
21356 (and (looking-at "[ \t]*#\\+end_")
21357 (re-search-backward "[ \t]*#\\+begin_"nil t))
21358 (looking-at "[ \t]*[\n:#|]")
21359 (looking-at org-footnote-definition-re)
21360 (and (ignore-errors (goto-char (org-in-item-p)))
21361 (goto-char
21362 (org-list-get-top-point (org-list-struct))))
21363 (and (not inline-task-p)
21364 (featurep 'org-inlinetask)
21365 (org-inlinetask-in-task-p)
21366 (or (org-inlinetask-goto-beginning) t))))
21367 (beginning-of-line 0))
21368 (cond
21369 ;; There was an heading above.
21370 ((looking-at "\\*+[ \t]+")
21371 (if (not org-adapt-indentation)
21372 (setq column 0)
21373 (goto-char (match-end 0))
21374 (setq column (current-column))))
21375 ;; A drawer had started and is unfinished
21376 ((looking-at org-drawer-regexp)
21377 (goto-char (1- (match-beginning 1)))
21378 (setq column (current-column)))
21379 ;; Else, nothing noticeable found: get indentation and go on.
21380 (t (setq column (org-get-indentation))))))
21381 ;; Now apply indentation and move cursor accordingly
21382 (goto-char pos)
21383 (if (<= (current-column) (current-indentation))
21384 (org-indent-line-to column)
21385 (save-excursion (org-indent-line-to column)))
21386 ;; Special polishing for properties, see `org-property-format'
21387 (setq column (current-column))
21388 (beginning-of-line 1)
21389 (if (looking-at
21390 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21391 (replace-match (concat (match-string 1)
21392 (format org-property-format
21393 (match-string 2) (match-string 3)))
21394 t t))
21395 (org-move-to-column column))))
21397 (defun org-indent-drawer ()
21398 "Indent the drawer at point."
21399 (interactive)
21400 (let ((p (point))
21401 (e (and (save-excursion (re-search-forward ":END:" nil t))
21402 (match-end 0)))
21403 (folded
21404 (save-excursion
21405 (end-of-line)
21406 (when (overlays-at (point))
21407 (member 'invisible (overlay-properties
21408 (car (overlays-at (point)))))))))
21409 (when folded (org-cycle))
21410 (indent-for-tab-command)
21411 (while (and (move-beginning-of-line 2) (< (point) e))
21412 (indent-for-tab-command))
21413 (goto-char p)
21414 (when folded (org-cycle)))
21415 (message "Drawer at point indented"))
21417 (defun org-indent-block ()
21418 "Indent the block at point."
21419 (interactive)
21420 (let ((p (point))
21421 (case-fold-search t)
21422 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21423 (match-end 0)))
21424 (folded
21425 (save-excursion
21426 (end-of-line)
21427 (when (overlays-at (point))
21428 (member 'invisible (overlay-properties
21429 (car (overlays-at (point)))))))))
21430 (when folded (org-cycle))
21431 (indent-for-tab-command)
21432 (while (and (move-beginning-of-line 2) (< (point) e))
21433 (indent-for-tab-command))
21434 (goto-char p)
21435 (when folded (org-cycle)))
21436 (message "Block at point indented"))
21438 (defun org-indent-region (start end)
21439 "Indent region."
21440 (interactive "r")
21441 (save-excursion
21442 (let ((line-end (org-current-line end)))
21443 (goto-char start)
21444 (while (< (org-current-line) line-end)
21445 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21446 (t (call-interactively 'org-indent-line)))
21447 (move-beginning-of-line 2)))))
21450 ;;; Filling
21452 ;; We use our own fill-paragraph and auto-fill functions.
21454 ;; `org-fill-paragraph' relies on adaptive filling and context
21455 ;; checking. Appropriate `fill-prefix' is computed with
21456 ;; `org-adaptive-fill-function'.
21458 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21459 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21460 ;; `org-adaptive-fill-function' value. Internally,
21461 ;; `org-comment-line-break-function' breaks the line.
21463 ;; `org-setup-filling' installs filling and auto-filling related
21464 ;; variables during `org-mode' initialization.
21466 (defun org-setup-filling ()
21467 (interactive)
21468 ;; Prevent auto-fill from inserting unwanted new items.
21469 (when (boundp 'fill-nobreak-predicate)
21470 (org-set-local
21471 'fill-nobreak-predicate
21472 (org-uniquify
21473 (append fill-nobreak-predicate
21474 '(org-fill-paragraph-separate-nobreak-p
21475 org-fill-line-break-nobreak-p)))))
21476 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21477 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21478 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21479 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21481 (defvar org-element-paragraph-separate) ; org-element.el
21482 (defun org-fill-paragraph-separate-nobreak-p ()
21483 "Non-nil when a line break at point would insert a new item."
21484 (looking-at (substring org-element-paragraph-separate 1)))
21486 (defun org-fill-line-break-nobreak-p ()
21487 "Non-nil when a line break at point would create an Org line break."
21488 (save-excursion
21489 (skip-chars-backward "[ \t]")
21490 (skip-chars-backward "\\\\")
21491 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21493 (declare-function message-in-body-p "message" ())
21494 (defun org-adaptive-fill-function ()
21495 "Compute a fill prefix for the current line.
21496 Return fill prefix, as a string, or nil if current line isn't
21497 meant to be filled."
21498 (org-with-wide-buffer
21499 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21500 ;; FIXME: This is really the job of orgstruct++-mode
21501 (let* ((p (line-beginning-position))
21502 (element (save-excursion (beginning-of-line)
21503 (org-element-at-point)))
21504 (type (org-element-type element))
21505 (post-affiliated (org-element-property :post-affiliated element)))
21506 (unless (and post-affiliated (< p post-affiliated))
21507 (case type
21508 (comment (looking-at "[ \t]*# ?") (match-string 0))
21509 (footnote-definition "")
21510 ((item plain-list)
21511 (make-string (org-list-item-body-column
21512 (or post-affiliated
21513 (org-element-property :begin element)))
21514 ? ))
21515 (paragraph
21516 ;; Fill prefix is usually the same as the current line,
21517 ;; except if the paragraph is at the beginning of an item.
21518 (let ((parent (org-element-property :parent element)))
21519 (cond ((eq (org-element-type parent) 'item)
21520 (make-string (org-list-item-body-column
21521 (org-element-property :begin parent))
21522 ? ))
21523 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21524 (match-string 0))
21525 (t ""))))
21526 (comment-block
21527 ;; Only fill contents if P is within block boundaries.
21528 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21529 (forward-line)
21530 (point)))
21531 (cend (save-excursion
21532 (goto-char (org-element-property :end element))
21533 (skip-chars-backward " \r\t\n")
21534 (line-beginning-position))))
21535 (when (and (>= p cbeg) (< p cend))
21536 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21537 (match-string 0)
21538 ""))))))))))
21540 (declare-function message-goto-body "message" ())
21541 (defvar message-cite-prefix-regexp) ; From message.el
21542 (defvar org-element-all-objects) ; From org-element.el
21543 (defun org-fill-paragraph (&optional justify)
21544 "Fill element at point, when applicable.
21546 This function only applies to comment blocks, comments, example
21547 blocks and paragraphs. Also, as a special case, re-align table
21548 when point is at one.
21550 If JUSTIFY is non-nil (interactively, with prefix argument),
21551 justify as well. If `sentence-end-double-space' is non-nil, then
21552 period followed by one space does not end a sentence, so don't
21553 break a line there. The variable `fill-column' controls the
21554 width for filling.
21556 For convenience, when point is at a plain list, an item or
21557 a footnote definition, try to fill the first paragraph within."
21558 (interactive)
21559 (if (and (derived-mode-p 'message-mode)
21560 (or (not (message-in-body-p))
21561 (save-excursion (move-beginning-of-line 1)
21562 (looking-at message-cite-prefix-regexp))))
21563 ;; First ensure filling is correct in message-mode.
21564 (let ((fill-paragraph-function
21565 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21566 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21567 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21568 (paragraph-separate
21569 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21570 (fill-paragraph nil))
21571 (save-excursion
21572 ;; Move to end of line in order to get the first paragraph
21573 ;; within a plain list or a footnote definition.
21574 (end-of-line)
21575 (let ((element (org-element-at-point)))
21576 ;; First check if point is in a blank line at the beginning of
21577 ;; the buffer. In that case, ignore filling.
21578 (if (< (point) (org-element-property :begin element)) t
21579 (case (org-element-type element)
21580 ;; Use major mode filling function is src blocks.
21581 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21582 ;; Align Org tables, leave table.el tables as-is.
21583 (table-row (org-table-align) t)
21584 (table
21585 (when (eq (org-element-property :type element) 'org)
21586 (org-table-align))
21588 (paragraph
21589 ;; Paragraphs may contain `line-break' type objects.
21590 (let ((beg (max (point-min)
21591 (org-element-property :contents-begin element)))
21592 (end (min (point-max)
21593 (org-element-property :contents-end element))))
21594 ;; Do nothing if point is at an affiliated keyword.
21595 (if (< (point) beg) t
21596 (when (derived-mode-p 'message-mode)
21597 ;; In `message-mode', do not fill following
21598 ;; citation in current paragraph nor text before
21599 ;; message body.
21600 (let ((body-start (save-excursion (message-goto-body))))
21601 (when body-start (setq beg (max body-start beg))))
21602 (when (save-excursion
21603 (re-search-forward
21604 (concat "^" message-cite-prefix-regexp) end t))
21605 (setq end (match-beginning 0))))
21606 ;; Fill paragraph, taking line breaks into
21607 ;; consideration. For that, slice the paragraph
21608 ;; using line breaks as separators, and fill the
21609 ;; parts in reverse order to avoid messing with
21610 ;; markers.
21611 (save-excursion
21612 (goto-char end)
21613 (mapc
21614 (lambda (pos)
21615 (fill-region-as-paragraph pos (point) justify)
21616 (goto-char pos))
21617 ;; Find the list of ending positions for line
21618 ;; breaks in the current paragraph. Add paragraph
21619 ;; beginning to include first slice.
21620 (nreverse
21621 (cons
21623 (org-element-map
21624 (org-element--parse-objects
21625 beg end nil org-element-all-objects)
21626 'line-break
21627 (lambda (lb) (org-element-property :end lb)))))))
21628 t)))
21629 ;; Contents of `comment-block' type elements should be
21630 ;; filled as plain text, but only if point is within block
21631 ;; markers.
21632 (comment-block
21633 (let* ((case-fold-search t)
21634 (beg (save-excursion
21635 (goto-char (org-element-property :begin element))
21636 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21637 (forward-line)
21638 (point)))
21639 (end (save-excursion
21640 (goto-char (org-element-property :end element))
21641 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21642 (line-beginning-position))))
21643 (when (and (>= (point) beg) (< (point) end))
21644 (fill-region-as-paragraph
21645 (save-excursion
21646 (end-of-line)
21647 (re-search-backward "^[ \t]*$" beg 'move)
21648 (line-beginning-position))
21649 (save-excursion
21650 (beginning-of-line)
21651 (re-search-forward "^[ \t]*$" end 'move)
21652 (line-beginning-position))
21653 justify)))
21655 ;; Fill comments.
21656 (comment (fill-comment-paragraph justify))
21657 ;; Ignore every other element.
21658 (otherwise t)))))))
21660 (defun org-auto-fill-function ()
21661 "Auto-fill function."
21662 ;; Check if auto-filling is meaningful.
21663 (let ((fc (current-fill-column)))
21664 (when (and fc (> (current-column) fc))
21665 (let* ((fill-prefix (org-adaptive-fill-function))
21666 ;; Enforce empty fill prefix, if required. Otherwise, it
21667 ;; will be computed again.
21668 (adaptive-fill-mode (not (equal fill-prefix ""))))
21669 (when fill-prefix (do-auto-fill))))))
21671 (defun org-comment-line-break-function (&optional soft)
21672 "Break line at point and indent, continuing comment if within one.
21673 The inserted newline is marked hard if variable
21674 `use-hard-newlines' is true, unless optional argument SOFT is
21675 non-nil."
21676 (if soft (insert-and-inherit ?\n) (newline 1))
21677 (save-excursion (forward-char -1) (delete-horizontal-space))
21678 (delete-horizontal-space)
21679 (indent-to-left-margin)
21680 (insert-before-markers-and-inherit fill-prefix))
21683 ;;; Comments
21685 ;; Org comments syntax is quite complex. It requires the entire line
21686 ;; to be just a comment. Also, even with the right syntax at the
21687 ;; beginning of line, some some elements (i.e. verse-block or
21688 ;; example-block) don't accept comments. Usual Emacs comment commands
21689 ;; cannot cope with those requirements. Therefore, Org replaces them.
21691 ;; Org still relies on `comment-dwim', but cannot trust
21692 ;; `comment-only-p'. So, `comment-region-function' and
21693 ;; `uncomment-region-function' both point
21694 ;; to`org-comment-or-uncomment-region'. Eventually,
21695 ;; `org-insert-comment' takes care of insertion of comments at the
21696 ;; beginning of line.
21698 ;; `org-setup-comments-handling' install comments related variables
21699 ;; during `org-mode' initialization.
21701 (defun org-setup-comments-handling ()
21702 (interactive)
21703 (org-set-local 'comment-use-syntax nil)
21704 (org-set-local 'comment-start "# ")
21705 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21706 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21707 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21708 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21710 (defun org-insert-comment ()
21711 "Insert an empty comment above current line.
21712 If the line is empty, insert comment at its beginning."
21713 (beginning-of-line)
21714 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21715 (org-indent-line)
21716 (insert "# "))
21718 (defvar comment-empty-lines) ; From newcomment.el.
21719 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21720 "Comment or uncomment each non-blank line in the region.
21721 Uncomment each non-blank line between BEG and END if it only
21722 contains commented lines. Otherwise, comment them."
21723 (save-restriction
21724 ;; Restrict region
21725 (narrow-to-region (save-excursion (goto-char beg)
21726 (skip-chars-forward " \r\t\n" end)
21727 (line-beginning-position))
21728 (save-excursion (goto-char end)
21729 (skip-chars-backward " \r\t\n" beg)
21730 (line-end-position)))
21731 (let ((uncommentp
21732 ;; UNCOMMENTP is non-nil when every non blank line between
21733 ;; BEG and END is a comment.
21734 (save-excursion
21735 (goto-char (point-min))
21736 (while (and (not (eobp))
21737 (let ((element (org-element-at-point)))
21738 (and (eq (org-element-type element) 'comment)
21739 (goto-char (min (point-max)
21740 (org-element-property
21741 :end element)))))))
21742 (eobp))))
21743 (if uncommentp
21744 ;; Only blank lines and comments in region: uncomment it.
21745 (save-excursion
21746 (goto-char (point-min))
21747 (while (not (eobp))
21748 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21749 (replace-match "" nil nil nil 1))
21750 (forward-line)))
21751 ;; Comment each line in region.
21752 (let ((min-indent (point-max)))
21753 ;; First find the minimum indentation across all lines.
21754 (save-excursion
21755 (goto-char (point-min))
21756 (while (and (not (eobp)) (not (zerop min-indent)))
21757 (unless (looking-at "[ \t]*$")
21758 (setq min-indent (min min-indent (current-indentation))))
21759 (forward-line)))
21760 ;; Then loop over all lines.
21761 (save-excursion
21762 (goto-char (point-min))
21763 (while (not (eobp))
21764 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21765 (org-move-to-column min-indent t)
21766 (insert comment-start))
21767 (forward-line))))))))
21770 ;;; Other stuff.
21772 (defun org-toggle-fixed-width-section (arg)
21773 "Toggle the fixed-width export.
21774 If there is no active region, the QUOTE keyword at the current headline is
21775 inserted or removed. When present, it causes the text between this headline
21776 and the next to be exported as fixed-width text, and unmodified.
21777 If there is an active region, this command adds or removes a colon as the
21778 first character of this line. If the first character of a line is a colon,
21779 this line is also exported in fixed-width font."
21780 (interactive "P")
21781 (let* ((cc 0)
21782 (regionp (org-region-active-p))
21783 (beg (if regionp (region-beginning) (point)))
21784 (end (if regionp (region-end)))
21785 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21786 (case-fold-search nil)
21787 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21788 off)
21789 (if regionp
21790 (save-excursion
21791 (goto-char beg)
21792 (setq cc (current-column))
21793 (beginning-of-line 1)
21794 (setq off (looking-at re))
21795 (while (> nlines 0)
21796 (setq nlines (1- nlines))
21797 (beginning-of-line 1)
21798 (cond
21799 (arg
21800 (org-move-to-column cc t)
21801 (insert ": \n")
21802 (forward-line -1))
21803 ((and off (looking-at re))
21804 (replace-match "" t t nil 1))
21805 ((not off) (org-move-to-column cc t) (insert ": ")))
21806 (forward-line 1)))
21807 (save-excursion
21808 (org-back-to-heading)
21809 (cond
21810 ((looking-at (format org-heading-keyword-regexp-format
21811 org-quote-string))
21812 (goto-char (match-end 1))
21813 (looking-at (concat " +" org-quote-string))
21814 (replace-match "" t t)
21815 (when (eolp) (insert " ")))
21816 ((looking-at org-outline-regexp)
21817 (goto-char (match-end 0))
21818 (insert org-quote-string " ")))))))
21820 (defun org-reftex-citation ()
21821 "Use reftex-citation to insert a citation into the buffer.
21822 This looks for a line like
21824 #+BIBLIOGRAPHY: foo plain option:-d
21826 and derives from it that foo.bib is the bibliography file relevant
21827 for this document. It then installs the necessary environment for RefTeX
21828 to work in this buffer and calls `reftex-citation' to insert a citation
21829 into the buffer.
21831 Export of such citations to both LaTeX and HTML is handled by the contributed
21832 package org-exp-bibtex by Taru Karttunen."
21833 (interactive)
21834 (let ((reftex-docstruct-symbol 'rds)
21835 (reftex-cite-format "\\cite{%l}")
21836 rds bib)
21837 (save-excursion
21838 (save-restriction
21839 (widen)
21840 (let ((case-fold-search t)
21841 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21842 (if (not (save-excursion
21843 (or (re-search-forward re nil t)
21844 (re-search-backward re nil t))))
21845 (error "No bibliography defined in file")
21846 (setq bib (concat (match-string 1) ".bib")
21847 rds (list (list 'bib bib)))))))
21848 (call-interactively 'reftex-citation)))
21850 ;;;; Functions extending outline functionality
21852 (defun org-beginning-of-line (&optional arg)
21853 "Go to the beginning of the current line. If that is invisible, continue
21854 to a visible line beginning. This makes the function of C-a more intuitive.
21855 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21856 first attempt, and only move to after the tags when the cursor is already
21857 beyond the end of the headline."
21858 (interactive "P")
21859 (let ((pos (point))
21860 (special (if (consp org-special-ctrl-a/e)
21861 (car org-special-ctrl-a/e)
21862 org-special-ctrl-a/e))
21863 refpos)
21864 (if (org-bound-and-true-p visual-line-mode)
21865 (beginning-of-visual-line 1)
21866 (beginning-of-line 1))
21867 (if (and arg (fboundp 'move-beginning-of-line))
21868 (call-interactively 'move-beginning-of-line)
21869 (if (bobp)
21871 (backward-char 1)
21872 (if (org-truely-invisible-p)
21873 (while (and (not (bobp)) (org-truely-invisible-p))
21874 (backward-char 1)
21875 (beginning-of-line 1))
21876 (forward-char 1))))
21877 (when special
21878 (cond
21879 ((and (looking-at org-complex-heading-regexp)
21880 (= (char-after (match-end 1)) ?\ ))
21881 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21882 (point-at-eol)))
21883 (goto-char
21884 (if (eq special t)
21885 (cond ((> pos refpos) refpos)
21886 ((= pos (point)) refpos)
21887 (t (point)))
21888 (cond ((> pos (point)) (point))
21889 ((not (eq last-command this-command)) (point))
21890 (t refpos)))))
21891 ((org-at-item-p)
21892 ;; Being at an item and not looking at an the item means point
21893 ;; was previously moved to beginning of a visual line, which
21894 ;; doesn't contain the item. Therefore, do nothing special,
21895 ;; just stay here.
21896 (when (looking-at org-list-full-item-re)
21897 ;; Set special position at first white space character after
21898 ;; bullet, and check-box, if any.
21899 (let ((after-bullet
21900 (let ((box (match-end 3)))
21901 (if (not box) (match-end 1)
21902 (let ((after (char-after box)))
21903 (if (and after (= after ? )) (1+ box) box))))))
21904 ;; Special case: Move point to special position when
21905 ;; currently after it or at beginning of line.
21906 (if (eq special t)
21907 (when (or (> pos after-bullet) (= (point) pos))
21908 (goto-char after-bullet))
21909 ;; Reversed case: Move point to special position when
21910 ;; point was already at beginning of line and command is
21911 ;; repeated.
21912 (when (and (= (point) pos) (eq last-command this-command))
21913 (goto-char after-bullet))))))))
21914 (org-no-warnings
21915 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21917 (defun org-end-of-line (&optional arg)
21918 "Go to the end of the line.
21919 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21920 tags on the first attempt, and only move to after the tags when
21921 the cursor is already beyond the end of the headline."
21922 (interactive "P")
21923 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21924 org-special-ctrl-a/e))
21925 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21926 'end-of-visual-line)
21927 ((fboundp 'move-end-of-line) 'move-end-of-line)
21928 (t 'end-of-line))))
21929 (if (or (not special) arg) (call-interactively move-fun)
21930 (let* ((element (save-excursion (beginning-of-line)
21931 (org-element-at-point)))
21932 (type (org-element-type element)))
21933 (cond
21934 ((memq type '(headline inlinetask))
21935 (let ((pos (point)))
21936 (beginning-of-line 1)
21937 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21938 (if (eq special t)
21939 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21940 (goto-char (match-beginning 1))
21941 (goto-char (match-end 0)))
21942 (if (or (< pos (match-end 0))
21943 (not (eq this-command last-command)))
21944 (goto-char (match-end 0))
21945 (goto-char (match-beginning 1))))
21946 (call-interactively move-fun))))
21947 ((org-element-property :hiddenp element)
21948 ;; If element is hidden, `move-end-of-line' would put point
21949 ;; after it. Use `end-of-line' to stay on current line.
21950 (call-interactively 'end-of-line))
21951 (t (call-interactively move-fun)))))
21952 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21954 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21955 (define-key org-mode-map "\C-e" 'org-end-of-line)
21957 (defun org-backward-sentence (&optional arg)
21958 "Go to beginning of sentence, or beginning of table field.
21959 This will call `backward-sentence' or `org-table-beginning-of-field',
21960 depending on context."
21961 (interactive "P")
21962 (cond
21963 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21964 (t (call-interactively 'backward-sentence))))
21966 (defun org-forward-sentence (&optional arg)
21967 "Go to end of sentence, or end of table field.
21968 This will call `forward-sentence' or `org-table-end-of-field',
21969 depending on context."
21970 (interactive "P")
21971 (cond
21972 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21973 (t (call-interactively 'forward-sentence))))
21975 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21976 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21978 (defun org-kill-line (&optional arg)
21979 "Kill line, to tags or end of line."
21980 (interactive "P")
21981 (cond
21982 ((or (not org-special-ctrl-k)
21983 (bolp)
21984 (not (org-at-heading-p)))
21985 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21986 org-ctrl-k-protect-subtree)
21987 (if (or (eq org-ctrl-k-protect-subtree 'error)
21988 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21989 (error "C-k aborted - would kill hidden subtree")))
21990 (call-interactively
21991 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21992 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21993 (kill-region (point) (match-beginning 1))
21994 (org-set-tags nil t))
21995 (t (kill-region (point) (point-at-eol)))))
21997 (define-key org-mode-map "\C-k" 'org-kill-line)
21999 (defun org-yank (&optional arg)
22000 "Yank. If the kill is a subtree, treat it specially.
22001 This command will look at the current kill and check if is a single
22002 subtree, or a series of subtrees[1]. If it passes the test, and if the
22003 cursor is at the beginning of a line or after the stars of a currently
22004 empty headline, then the yank is handled specially. How exactly depends
22005 on the value of the following variables, both set by default.
22007 org-yank-folded-subtrees
22008 When set, the subtree(s) will be folded after insertion, but only
22009 if doing so would now swallow text after the yanked text.
22011 org-yank-adjusted-subtrees
22012 When set, the subtree will be promoted or demoted in order to
22013 fit into the local outline tree structure, which means that the level
22014 will be adjusted so that it becomes the smaller one of the two
22015 *visible* surrounding headings.
22017 Any prefix to this command will cause `yank' to be called directly with
22018 no special treatment. In particular, a simple \\[universal-argument] prefix \
22019 will just
22020 plainly yank the text as it is.
22022 \[1] The test checks if the first non-white line is a heading
22023 and if there are no other headings with fewer stars."
22024 (interactive "P")
22025 (org-yank-generic 'yank arg))
22027 (defun org-yank-generic (command arg)
22028 "Perform some yank-like command.
22030 This function implements the behavior described in the `org-yank'
22031 documentation. However, it has been generalized to work for any
22032 interactive command with similar behavior."
22034 ;; pretend to be command COMMAND
22035 (setq this-command command)
22037 (if arg
22038 (call-interactively command)
22040 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22041 (and (org-kill-is-subtree-p)
22042 (or (bolp)
22043 (and (looking-at "[ \t]*$")
22044 (string-match
22045 "\\`\\*+\\'"
22046 (buffer-substring (point-at-bol) (point)))))))
22047 swallowp)
22048 (cond
22049 ((and subtreep org-yank-folded-subtrees)
22050 (let ((beg (point))
22051 end)
22052 (if (and subtreep org-yank-adjusted-subtrees)
22053 (org-paste-subtree nil nil 'for-yank)
22054 (call-interactively command))
22056 (setq end (point))
22057 (goto-char beg)
22058 (when (and (bolp) subtreep
22059 (not (setq swallowp
22060 (org-yank-folding-would-swallow-text beg end))))
22061 (org-with-limited-levels
22062 (or (looking-at org-outline-regexp)
22063 (re-search-forward org-outline-regexp-bol end t))
22064 (while (and (< (point) end) (looking-at org-outline-regexp))
22065 (hide-subtree)
22066 (org-cycle-show-empty-lines 'folded)
22067 (condition-case nil
22068 (outline-forward-same-level 1)
22069 (error (goto-char end))))))
22070 (when swallowp
22071 (message
22072 "Inserted text not folded because that would swallow text"))
22074 (goto-char end)
22075 (skip-chars-forward " \t\n\r")
22076 (beginning-of-line 1)
22077 (push-mark beg 'nomsg)))
22078 ((and subtreep org-yank-adjusted-subtrees)
22079 (let ((beg (point-at-bol)))
22080 (org-paste-subtree nil nil 'for-yank)
22081 (push-mark beg 'nomsg)))
22083 (call-interactively command))))))
22085 (defun org-yank-folding-would-swallow-text (beg end)
22086 "Would hide-subtree at BEG swallow any text after END?"
22087 (let (level)
22088 (org-with-limited-levels
22089 (save-excursion
22090 (goto-char beg)
22091 (when (or (looking-at org-outline-regexp)
22092 (re-search-forward org-outline-regexp-bol end t))
22093 (setq level (org-outline-level)))
22094 (goto-char end)
22095 (skip-chars-forward " \t\r\n\v\f")
22096 (if (or (eobp)
22097 (and (bolp) (looking-at org-outline-regexp)
22098 (<= (org-outline-level) level)))
22099 nil ; Nothing would be swallowed
22100 t))))) ; something would swallow
22102 (define-key org-mode-map "\C-y" 'org-yank)
22104 (defun org-truely-invisible-p ()
22105 "Check if point is at a character currently not visible.
22106 This version does not only check the character property, but also
22107 `visible-mode'."
22108 ;; Early versions of noutline don't have `outline-invisible-p'.
22109 (if (org-bound-and-true-p visible-mode)
22111 (outline-invisible-p)))
22113 (defun org-invisible-p2 ()
22114 "Check if point is at a character currently not visible."
22115 (save-excursion
22116 (if (and (eolp) (not (bobp))) (backward-char 1))
22117 ;; Early versions of noutline don't have `outline-invisible-p'.
22118 (outline-invisible-p)))
22120 (defun org-back-to-heading (&optional invisible-ok)
22121 "Call `outline-back-to-heading', but provide a better error message."
22122 (condition-case nil
22123 (outline-back-to-heading invisible-ok)
22124 (error (error "Before first headline at position %d in buffer %s"
22125 (point) (current-buffer)))))
22127 (defun org-before-first-heading-p ()
22128 "Before first heading?"
22129 (save-excursion
22130 (end-of-line)
22131 (null (re-search-backward org-outline-regexp-bol nil t))))
22133 (defun org-at-heading-p (&optional ignored)
22134 (outline-on-heading-p t))
22135 ;; Compatibility alias with Org versions < 7.8.03
22136 (defalias 'org-on-heading-p 'org-at-heading-p)
22138 (defun org-at-comment-p nil
22139 "Is cursor in a line starting with a # character?"
22140 (save-excursion
22141 (beginning-of-line)
22142 (looking-at "^#")))
22144 (defun org-at-drawer-p nil
22145 "Is cursor at a drawer keyword?"
22146 (save-excursion
22147 (move-beginning-of-line 1)
22148 (looking-at org-drawer-regexp)))
22150 (defun org-at-block-p nil
22151 "Is cursor at a block keyword?"
22152 (save-excursion
22153 (move-beginning-of-line 1)
22154 (looking-at org-block-regexp)))
22156 (defun org-point-at-end-of-empty-headline ()
22157 "If point is at the end of an empty headline, return t, else nil.
22158 If the heading only contains a TODO keyword, it is still still considered
22159 empty."
22160 (and (looking-at "[ \t]*$")
22161 (when org-todo-line-regexp
22162 (save-excursion
22163 (beginning-of-line 1)
22164 (let ((case-fold-search nil))
22165 (looking-at org-todo-line-regexp)
22166 (string= (match-string 3) ""))))))
22168 (defun org-at-heading-or-item-p ()
22169 (or (org-at-heading-p) (org-at-item-p)))
22171 (defun org-at-target-p ()
22172 (or (org-in-regexp org-radio-target-regexp)
22173 (org-in-regexp org-target-regexp)))
22174 ;; Compatibility alias with Org versions < 7.8.03
22175 (defalias 'org-on-target-p 'org-at-target-p)
22177 (defun org-up-heading-all (arg)
22178 "Move to the heading line of which the present line is a subheading.
22179 This function considers both visible and invisible heading lines.
22180 With argument, move up ARG levels."
22181 (if (fboundp 'outline-up-heading-all)
22182 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22183 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22185 (defun org-up-heading-safe ()
22186 "Move to the heading line of which the present line is a subheading.
22187 This version will not throw an error. It will return the level of the
22188 headline found, or nil if no higher level is found.
22190 Also, this function will be a lot faster than `outline-up-heading',
22191 because it relies on stars being the outline starters. This can really
22192 make a significant difference in outlines with very many siblings."
22193 (let (start-level re)
22194 (org-back-to-heading t)
22195 (setq start-level (funcall outline-level))
22196 (if (equal start-level 1)
22198 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22199 (if (re-search-backward re nil t)
22200 (funcall outline-level)))))
22202 (defun org-first-sibling-p ()
22203 "Is this heading the first child of its parents?"
22204 (interactive)
22205 (let ((re org-outline-regexp-bol)
22206 level l)
22207 (unless (org-at-heading-p t)
22208 (error "Not at a heading"))
22209 (setq level (funcall outline-level))
22210 (save-excursion
22211 (if (not (re-search-backward re nil t))
22213 (setq l (funcall outline-level))
22214 (< l level)))))
22216 (defun org-goto-sibling (&optional previous)
22217 "Goto the next sibling, even if it is invisible.
22218 When PREVIOUS is set, go to the previous sibling instead. Returns t
22219 when a sibling was found. When none is found, return nil and don't
22220 move point."
22221 (let ((fun (if previous 're-search-backward 're-search-forward))
22222 (pos (point))
22223 (re org-outline-regexp-bol)
22224 level l)
22225 (when (condition-case nil (org-back-to-heading t) (error nil))
22226 (setq level (funcall outline-level))
22227 (catch 'exit
22228 (or previous (forward-char 1))
22229 (while (funcall fun re nil t)
22230 (setq l (funcall outline-level))
22231 (when (< l level) (goto-char pos) (throw 'exit nil))
22232 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22233 (goto-char pos)
22234 nil))))
22236 (defun org-show-siblings ()
22237 "Show all siblings of the current headline."
22238 (save-excursion
22239 (while (org-goto-sibling) (org-flag-heading nil)))
22240 (save-excursion
22241 (while (org-goto-sibling 'previous)
22242 (org-flag-heading nil))))
22244 (defun org-goto-first-child ()
22245 "Goto the first child, even if it is invisible.
22246 Return t when a child was found. Otherwise don't move point and
22247 return nil."
22248 (let (level (pos (point)) (re org-outline-regexp-bol))
22249 (when (condition-case nil (org-back-to-heading t) (error nil))
22250 (setq level (outline-level))
22251 (forward-char 1)
22252 (if (and (re-search-forward re nil t) (> (outline-level) level))
22253 (progn (goto-char (match-beginning 0)) t)
22254 (goto-char pos) nil))))
22256 (defun org-show-hidden-entry ()
22257 "Show an entry where even the heading is hidden."
22258 (save-excursion
22259 (org-show-entry)))
22261 (defun org-flag-heading (flag &optional entry)
22262 "Flag the current heading. FLAG non-nil means make invisible.
22263 When ENTRY is non-nil, show the entire entry."
22264 (save-excursion
22265 (org-back-to-heading t)
22266 ;; Check if we should show the entire entry
22267 (if entry
22268 (progn
22269 (org-show-entry)
22270 (save-excursion
22271 (and (outline-next-heading)
22272 (org-flag-heading nil))))
22273 (outline-flag-region (max (point-min) (1- (point)))
22274 (save-excursion (outline-end-of-heading) (point))
22275 flag))))
22277 (defun org-get-next-sibling ()
22278 "Move to next heading of the same level, and return point.
22279 If there is no such heading, return nil.
22280 This is like outline-next-sibling, but invisible headings are ok."
22281 (let ((level (funcall outline-level)))
22282 (outline-next-heading)
22283 (while (and (not (eobp)) (> (funcall outline-level) level))
22284 (outline-next-heading))
22285 (if (or (eobp) (< (funcall outline-level) level))
22287 (point))))
22289 (defun org-get-last-sibling ()
22290 "Move to previous heading of the same level, and return point.
22291 If there is no such heading, return nil."
22292 (let ((opoint (point))
22293 (level (funcall outline-level)))
22294 (outline-previous-heading)
22295 (when (and (/= (point) opoint) (outline-on-heading-p t))
22296 (while (and (> (funcall outline-level) level)
22297 (not (bobp)))
22298 (outline-previous-heading))
22299 (if (< (funcall outline-level) level)
22301 (point)))))
22303 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22304 "Goto to the end of a subtree."
22305 ;; This contains an exact copy of the original function, but it uses
22306 ;; `org-back-to-heading', to make it work also in invisible
22307 ;; trees. And is uses an invisible-ok argument.
22308 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22309 ;; Furthermore, when used inside Org, finding the end of a large subtree
22310 ;; with many children and grandchildren etc, this can be much faster
22311 ;; than the outline version.
22312 (org-back-to-heading invisible-ok)
22313 (let ((first t)
22314 (level (funcall outline-level)))
22315 (if (and (derived-mode-p 'org-mode) (< level 1000))
22316 ;; A true heading (not a plain list item), in Org-mode
22317 ;; This means we can easily find the end by looking
22318 ;; only for the right number of stars. Using a regexp to do
22319 ;; this is so much faster than using a Lisp loop.
22320 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22321 (forward-char 1)
22322 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22323 ;; something else, do it the slow way
22324 (while (and (not (eobp))
22325 (or first (> (funcall outline-level) level)))
22326 (setq first nil)
22327 (outline-next-heading)))
22328 (unless to-heading
22329 (if (memq (preceding-char) '(?\n ?\^M))
22330 (progn
22331 ;; Go to end of line before heading
22332 (forward-char -1)
22333 (if (memq (preceding-char) '(?\n ?\^M))
22334 ;; leave blank line before heading
22335 (forward-char -1))))))
22336 (point))
22338 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22339 "Use Org version in org-mode, for dramatic speed-up."
22340 (if (derived-mode-p 'org-mode)
22341 (progn
22342 (org-end-of-subtree nil t)
22343 (unless (eobp) (backward-char 1)))
22344 ad-do-it))
22346 (defun org-end-of-meta-data-and-drawers ()
22347 "Jump to the first text after meta data and drawers in the current entry.
22348 This will move over empty lines, lines with planning time stamps,
22349 clocking lines, and drawers."
22350 (org-back-to-heading t)
22351 (let ((end (save-excursion (outline-next-heading) (point)))
22352 (re (concat "\\(" org-drawer-regexp "\\)"
22353 "\\|" "[ \t]*" org-keyword-time-regexp)))
22354 (forward-line 1)
22355 (while (re-search-forward re end t)
22356 (if (not (match-end 1))
22357 ;; empty or planning line
22358 (forward-line 1)
22359 ;; a drawer, find the end
22360 (re-search-forward "^[ \t]*:END:" end 'move)
22361 (forward-line 1)))
22362 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22363 (point)))
22365 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22366 "Move forward to the arg'th subheading at same level as this one.
22367 Stop at the first and last subheadings of a superior heading.
22368 Normally this only looks at visible headings, but when INVISIBLE-OK is
22369 non-nil it will also look at invisible ones."
22370 (interactive "p")
22371 (org-back-to-heading invisible-ok)
22372 (org-at-heading-p)
22373 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22374 (re (format "^\\*\\{1,%d\\} " level))
22376 (forward-char 1)
22377 (while (> arg 0)
22378 (while (and (re-search-forward re nil 'move)
22379 (setq l (- (match-end 0) (match-beginning 0) 1))
22380 (= l level)
22381 (not invisible-ok)
22382 (progn (backward-char 1) (outline-invisible-p)))
22383 (if (< l level) (setq arg 1)))
22384 (setq arg (1- arg)))
22385 (beginning-of-line 1)))
22387 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22388 "Move backward to the arg'th subheading at same level as this one.
22389 Stop at the first and last subheadings of a superior heading."
22390 (interactive "p")
22391 (org-back-to-heading)
22392 (org-at-heading-p)
22393 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22394 (re (format "^\\*\\{1,%d\\} " level))
22396 (while (> arg 0)
22397 (while (and (re-search-backward re nil 'move)
22398 (setq l (- (match-end 0) (match-beginning 0) 1))
22399 (= l level)
22400 (not invisible-ok)
22401 (outline-invisible-p))
22402 (if (< l level) (setq arg 1)))
22403 (setq arg (1- arg)))))
22405 (defun org-forward-element ()
22406 "Move forward by one element.
22407 Move to the next element at the same level, when possible."
22408 (interactive)
22409 (cond ((eobp) (error "Cannot move further down"))
22410 ((org-with-limited-levels (org-at-heading-p))
22411 (let ((origin (point)))
22412 (org-forward-heading-same-level 1)
22413 (unless (org-with-limited-levels (org-at-heading-p))
22414 (goto-char origin)
22415 (error "Cannot move further down"))))
22417 (let* ((elem (org-element-at-point))
22418 (end (org-element-property :end elem))
22419 (parent (org-element-property :parent elem)))
22420 (if (and parent (= (org-element-property :contents-end parent) end))
22421 (goto-char (org-element-property :end parent))
22422 (goto-char end))))))
22424 (defun org-backward-element ()
22425 "Move backward by one element.
22426 Move to the previous element at the same level, when possible."
22427 (interactive)
22428 (cond ((bobp) (error "Cannot move further up"))
22429 ((org-with-limited-levels (org-at-heading-p))
22430 ;; At an headline, move to the previous one, if any, or stay
22431 ;; here.
22432 (let ((origin (point)))
22433 (org-backward-heading-same-level 1)
22434 (unless (org-with-limited-levels (org-at-heading-p))
22435 (goto-char origin)
22436 (error "Cannot move further up"))))
22438 (let* ((trail (org-element-at-point 'keep-trail))
22439 (elem (car trail))
22440 (prev-elem (nth 1 trail))
22441 (beg (org-element-property :begin elem)))
22442 (cond
22443 ;; Move to beginning of current element if point isn't
22444 ;; there already.
22445 ((/= (point) beg) (goto-char beg))
22446 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22447 ((org-before-first-heading-p) (goto-char (point-min)))
22448 (t (org-back-to-heading)))))))
22450 (defun org-up-element ()
22451 "Move to upper element."
22452 (interactive)
22453 (if (org-with-limited-levels (org-at-heading-p))
22454 (unless (org-up-heading-safe) (error "No surrounding element"))
22455 (let* ((elem (org-element-at-point))
22456 (parent (org-element-property :parent elem)))
22457 (if parent (goto-char (org-element-property :begin parent))
22458 (if (org-with-limited-levels (org-before-first-heading-p))
22459 (error "No surrounding element")
22460 (org-with-limited-levels (org-back-to-heading)))))))
22462 (defvar org-element-greater-elements)
22463 (defun org-down-element ()
22464 "Move to inner element."
22465 (interactive)
22466 (let ((element (org-element-at-point)))
22467 (cond
22468 ((memq (org-element-type element) '(plain-list table))
22469 (goto-char (org-element-property :contents-begin element))
22470 (forward-char))
22471 ((memq (org-element-type element) org-element-greater-elements)
22472 ;; If contents are hidden, first disclose them.
22473 (when (org-element-property :hiddenp element) (org-cycle))
22474 (goto-char (or (org-element-property :contents-begin element)
22475 (error "No content for this element"))))
22476 (t (error "No inner element")))))
22478 (defun org-drag-element-backward ()
22479 "Move backward element at point."
22480 (interactive)
22481 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22482 (let* ((trail (org-element-at-point 'keep-trail))
22483 (elem (car trail))
22484 (prev-elem (nth 1 trail)))
22485 ;; Error out if no previous element or previous element is
22486 ;; a parent of the current one.
22487 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22488 (error "Cannot drag element backward")
22489 (let ((pos (point)))
22490 (org-element-swap-A-B prev-elem elem)
22491 (goto-char (+ (org-element-property :begin prev-elem)
22492 (- pos (org-element-property :begin elem)))))))))
22494 (defun org-drag-element-forward ()
22495 "Move forward element at point."
22496 (interactive)
22497 (let* ((pos (point))
22498 (elem (org-element-at-point)))
22499 (when (= (point-max) (org-element-property :end elem))
22500 (error "Cannot drag element forward"))
22501 (goto-char (org-element-property :end elem))
22502 (let ((next-elem (org-element-at-point)))
22503 (when (or (org-element-nested-p elem next-elem)
22504 (and (eq (org-element-type next-elem) 'headline)
22505 (not (eq (org-element-type elem) 'headline))))
22506 (goto-char pos)
22507 (error "Cannot drag element forward"))
22508 ;; Compute new position of point: it's shifted by NEXT-ELEM
22509 ;; body's length (without final blanks) and by the length of
22510 ;; blanks between ELEM and NEXT-ELEM.
22511 (let ((size-next (- (save-excursion
22512 (goto-char (org-element-property :end next-elem))
22513 (skip-chars-backward " \r\t\n")
22514 (forward-line)
22515 ;; Small correction if buffer doesn't end
22516 ;; with a newline character.
22517 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22518 (org-element-property :begin next-elem)))
22519 (size-blank (- (org-element-property :end elem)
22520 (save-excursion
22521 (goto-char (org-element-property :end elem))
22522 (skip-chars-backward " \r\t\n")
22523 (forward-line)
22524 (point)))))
22525 (org-element-swap-A-B elem next-elem)
22526 (goto-char (+ pos size-next size-blank))))))
22528 (defun org-mark-element ()
22529 "Put point at beginning of this element, mark at end.
22531 Interactively, if this command is repeated or (in Transient Mark
22532 mode) if the mark is active, it marks the next element after the
22533 ones already marked."
22534 (interactive)
22535 (let (deactivate-mark)
22536 (if (and (org-called-interactively-p 'any)
22537 (or (and (eq last-command this-command) (mark t))
22538 (and transient-mark-mode mark-active)))
22539 (set-mark
22540 (save-excursion
22541 (goto-char (mark))
22542 (goto-char (org-element-property :end (org-element-at-point)))))
22543 (let ((element (org-element-at-point)))
22544 (end-of-line)
22545 (push-mark (org-element-property :end element) t t)
22546 (goto-char (org-element-property :begin element))))))
22548 (defun org-narrow-to-element ()
22549 "Narrow buffer to current element."
22550 (interactive)
22551 (let ((elem (org-element-at-point)))
22552 (cond
22553 ((eq (car elem) 'headline)
22554 (narrow-to-region
22555 (org-element-property :begin elem)
22556 (org-element-property :end elem)))
22557 ((memq (car elem) org-element-greater-elements)
22558 (narrow-to-region
22559 (org-element-property :contents-begin elem)
22560 (org-element-property :contents-end elem)))
22562 (narrow-to-region
22563 (org-element-property :begin elem)
22564 (org-element-property :end elem))))))
22566 (defun org-transpose-words ()
22567 "Transpose words, using `org-mode' syntax table."
22568 (interactive)
22569 (with-syntax-table org-syntax-table
22570 (call-interactively 'transpose-words)))
22571 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22573 (defun org-transpose-element ()
22574 "Transpose current and previous elements, keeping blank lines between.
22575 Point is moved after both elements."
22576 (interactive)
22577 (org-skip-whitespace)
22578 (let ((end (org-element-property :end (org-element-at-point))))
22579 (org-drag-element-backward)
22580 (goto-char end)))
22582 (defun org-unindent-buffer ()
22583 "Un-indent the visible part of the buffer.
22584 Relative indentation (between items, inside blocks, etc.) isn't
22585 modified."
22586 (interactive)
22587 (unless (eq major-mode 'org-mode)
22588 (error "Cannot un-indent a buffer not in Org mode"))
22589 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22590 unindent-tree ; For byte-compiler.
22591 (unindent-tree
22592 (function
22593 (lambda (contents)
22594 (mapc
22595 (lambda (element)
22596 (if (memq (org-element-type element) '(headline section))
22597 (funcall unindent-tree (org-element-contents element))
22598 (save-excursion
22599 (save-restriction
22600 (narrow-to-region
22601 (org-element-property :begin element)
22602 (org-element-property :end element))
22603 (org-do-remove-indentation)))))
22604 (reverse contents))))))
22605 (funcall unindent-tree (org-element-contents parse-tree))))
22607 (defun org-show-subtree ()
22608 "Show everything after this heading at deeper levels."
22609 (interactive)
22610 (outline-flag-region
22611 (point)
22612 (save-excursion
22613 (org-end-of-subtree t t))
22614 nil))
22616 (defun org-show-entry ()
22617 "Show the body directly following this heading.
22618 Show the heading too, if it is currently invisible."
22619 (interactive)
22620 (save-excursion
22621 (condition-case nil
22622 (progn
22623 (org-back-to-heading t)
22624 (outline-flag-region
22625 (max (point-min) (1- (point)))
22626 (save-excursion
22627 (if (re-search-forward
22628 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22629 (match-beginning 1)
22630 (point-max)))
22631 nil)
22632 (org-cycle-hide-drawers 'children))
22633 (error nil))))
22635 (defun org-make-options-regexp (kwds &optional extra)
22636 "Make a regular expression for keyword lines."
22637 (concat
22638 "^#\\+\\("
22639 (mapconcat 'regexp-quote kwds "\\|")
22640 (if extra (concat "\\|" extra))
22641 "\\):[ \t]*\\(.*\\)"))
22643 ;; Make isearch reveal the necessary context
22644 (defun org-isearch-end ()
22645 "Reveal context after isearch exits."
22646 (when isearch-success ; only if search was successful
22647 (if (featurep 'xemacs)
22648 ;; Under XEmacs, the hook is run in the correct place,
22649 ;; we directly show the context.
22650 (org-show-context 'isearch)
22651 ;; In Emacs the hook runs *before* restoring the overlays.
22652 ;; So we have to use a one-time post-command-hook to do this.
22653 ;; (Emacs 22 has a special variable, see function `org-mode')
22654 (unless (and (boundp 'isearch-mode-end-hook-quit)
22655 isearch-mode-end-hook-quit)
22656 ;; Only when the isearch was not quitted.
22657 (org-add-hook 'post-command-hook 'org-isearch-post-command
22658 'append 'local)))))
22660 (defun org-isearch-post-command ()
22661 "Remove self from hook, and show context."
22662 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22663 (org-show-context 'isearch))
22666 ;;;; Integration with and fixes for other packages
22668 ;;; Imenu support
22670 (defvar org-imenu-markers nil
22671 "All markers currently used by Imenu.")
22672 (make-variable-buffer-local 'org-imenu-markers)
22674 (defun org-imenu-new-marker (&optional pos)
22675 "Return a new marker for use by Imenu, and remember the marker."
22676 (let ((m (make-marker)))
22677 (move-marker m (or pos (point)))
22678 (push m org-imenu-markers)
22681 (defun org-imenu-get-tree ()
22682 "Produce the index for Imenu."
22683 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22684 (setq org-imenu-markers nil)
22685 (let* ((n org-imenu-depth)
22686 (re (concat "^" (org-get-limited-outline-regexp)))
22687 (subs (make-vector (1+ n) nil))
22688 (last-level 0)
22689 m level head)
22690 (save-excursion
22691 (save-restriction
22692 (widen)
22693 (goto-char (point-max))
22694 (while (re-search-backward re nil t)
22695 (setq level (org-reduced-level (funcall outline-level)))
22696 (when (and (<= level n)
22697 (looking-at org-complex-heading-regexp))
22698 (setq head (org-link-display-format
22699 (org-match-string-no-properties 4))
22700 m (org-imenu-new-marker))
22701 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22702 (if (>= level last-level)
22703 (push (cons head m) (aref subs level))
22704 (push (cons head (aref subs (1+ level))) (aref subs level))
22705 (loop for i from (1+ level) to n do (aset subs i nil)))
22706 (setq last-level level)))))
22707 (aref subs 1)))
22709 (eval-after-load "imenu"
22710 '(progn
22711 (add-hook 'imenu-after-jump-hook
22712 (lambda ()
22713 (if (derived-mode-p 'org-mode)
22714 (org-show-context 'org-goto))))))
22716 (defun org-link-display-format (link)
22717 "Replace a link with either the description, or the link target
22718 if no description is present"
22719 (save-match-data
22720 (if (string-match org-bracket-link-analytic-regexp link)
22721 (replace-match (if (match-end 5)
22722 (match-string 5 link)
22723 (concat (match-string 1 link)
22724 (match-string 3 link)))
22725 nil t link)
22726 link)))
22728 (defun org-toggle-link-display ()
22729 "Toggle the literal or descriptive display of links."
22730 (interactive)
22731 (if org-descriptive-links
22732 (progn (org-remove-from-invisibility-spec '(org-link))
22733 (org-restart-font-lock)
22734 (setq org-descriptive-links nil))
22735 (progn (add-to-invisibility-spec '(org-link))
22736 (org-restart-font-lock)
22737 (setq org-descriptive-links t))))
22739 ;; Speedbar support
22741 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22742 "Overlay marking the agenda restriction line in speedbar.")
22743 (overlay-put org-speedbar-restriction-lock-overlay
22744 'face 'org-agenda-restriction-lock)
22745 (overlay-put org-speedbar-restriction-lock-overlay
22746 'help-echo "Agendas are currently limited to this item.")
22747 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22749 (defun org-speedbar-set-agenda-restriction ()
22750 "Restrict future agenda commands to the location at point in speedbar.
22751 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22752 (interactive)
22753 (require 'org-agenda)
22754 (let (p m tp np dir txt)
22755 (cond
22756 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22757 'org-imenu t))
22758 (setq m (get-text-property p 'org-imenu-marker))
22759 (with-current-buffer (marker-buffer m)
22760 (goto-char m)
22761 (org-agenda-set-restriction-lock 'subtree)))
22762 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22763 'speedbar-function 'speedbar-find-file))
22764 (setq tp (previous-single-property-change
22765 (1+ p) 'speedbar-function)
22766 np (next-single-property-change
22767 tp 'speedbar-function)
22768 dir (speedbar-line-directory)
22769 txt (buffer-substring-no-properties (or tp (point-min))
22770 (or np (point-max))))
22771 (with-current-buffer (find-file-noselect
22772 (let ((default-directory dir))
22773 (expand-file-name txt)))
22774 (unless (derived-mode-p 'org-mode)
22775 (error "Cannot restrict to non-Org-mode file"))
22776 (org-agenda-set-restriction-lock 'file)))
22777 (t (error "Don't know how to restrict Org-mode's agenda")))
22778 (move-overlay org-speedbar-restriction-lock-overlay
22779 (point-at-bol) (point-at-eol))
22780 (setq current-prefix-arg nil)
22781 (org-agenda-maybe-redo)))
22783 (eval-after-load "speedbar"
22784 '(progn
22785 (speedbar-add-supported-extension ".org")
22786 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22787 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22788 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22789 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22790 (add-hook 'speedbar-visiting-tag-hook
22791 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22793 ;;; Fixes and Hacks for problems with other packages
22795 ;; Make flyspell not check words in links, to not mess up our keymap
22796 (defun org-mode-flyspell-verify ()
22797 "Don't let flyspell put overlays at active buttons, or on
22798 {todo,all-time,additional-option-like}-keywords."
22799 (let ((pos (max (1- (point)) (point-min)))
22800 (word (thing-at-point 'word)))
22801 (and (not (get-text-property pos 'keymap))
22802 (not (get-text-property pos 'org-no-flyspell))
22803 (not (member word org-todo-keywords-1))
22804 (not (member word org-all-time-keywords))
22805 (not (member word org-options-keywords))
22806 (not (member word (mapcar 'car org-startup-options)))
22807 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22809 (defun org-remove-flyspell-overlays-in (beg end)
22810 "Remove flyspell overlays in region."
22811 (and (org-bound-and-true-p flyspell-mode)
22812 (fboundp 'flyspell-delete-region-overlays)
22813 (flyspell-delete-region-overlays beg end))
22814 (add-text-properties beg end '(org-no-flyspell t)))
22816 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22817 (eval-after-load "bookmark"
22818 '(if (boundp 'bookmark-after-jump-hook)
22819 ;; We can use the hook
22820 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22821 ;; Hook not available, use advice
22822 (defadvice bookmark-jump (after org-make-visible activate)
22823 "Make the position visible."
22824 (org-bookmark-jump-unhide))))
22826 ;; Make sure saveplace shows the location if it was hidden
22827 (eval-after-load "saveplace"
22828 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22829 "Make the position visible."
22830 (org-bookmark-jump-unhide)))
22832 ;; Make sure ecb shows the location if it was hidden
22833 (eval-after-load "ecb"
22834 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22835 "Make hierarchy visible when jumping into location from ECB tree buffer."
22836 (if (derived-mode-p 'org-mode)
22837 (org-show-context))))
22839 (defun org-bookmark-jump-unhide ()
22840 "Unhide the current position, to show the bookmark location."
22841 (and (derived-mode-p 'org-mode)
22842 (or (outline-invisible-p)
22843 (save-excursion (goto-char (max (point-min) (1- (point))))
22844 (outline-invisible-p)))
22845 (org-show-context 'bookmark-jump)))
22847 ;; Make session.el ignore our circular variable
22848 (eval-after-load "session"
22849 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22851 ;;;; Experimental code
22853 (defun org-closed-in-range ()
22854 "Sparse tree of items closed in a certain time range.
22855 Still experimental, may disappear in the future."
22856 (interactive)
22857 ;; Get the time interval from the user.
22858 (let* ((time1 (org-float-time
22859 (org-read-date nil 'to-time nil "Starting date: ")))
22860 (time2 (org-float-time
22861 (org-read-date nil 'to-time nil "End date:")))
22862 ;; callback function
22863 (callback (lambda ()
22864 (let ((time
22865 (org-float-time
22866 (apply 'encode-time
22867 (org-parse-time-string
22868 (match-string 1))))))
22869 ;; check if time in interval
22870 (and (>= time time1) (<= time time2))))))
22871 ;; make tree, check each match with the callback
22872 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22874 ;;;; Finish up
22876 (provide 'org)
22878 (run-hooks 'org-load-hook)
22880 ;;; org.el ends here