Fix commit de3380
[org-mode.git] / lisp / org.el
blobd4f1866595af52fa657b92c8f149aea766b254f5
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro org-with-limited-levels.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches an headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-at-clock-log-p "org-clock" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function orgtbl-mode "org-table" (&optional arg))
127 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
128 (declare-function org-beamer-mode "org-beamer" ())
129 (declare-function org-table-edit-field "org-table" (arg))
130 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
131 (declare-function org-id-get-create "org-id" (&optional force))
132 (declare-function org-id-find-id-file "org-id" (id))
133 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
134 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (autoload 'org-element-at-point "org-element")
141 (autoload 'org-element-type "org-element")
143 (declare-function org-element-at-point "org-element" (&optional keep-trail))
144 (declare-function org-element-type "org-element" (element))
145 (declare-function org-element-context "org-element" (&optional element))
146 (declare-function org-element-contents "org-element" (element))
147 (declare-function org-element-property "org-element" (property element))
148 (declare-function org-element-put-property "org-element"
149 (element property value))
150 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
151 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
152 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
153 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
154 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
155 (declare-function org-element-interpret-data "org-element" (data &optional parent))
157 ;; load languages based on value of `org-babel-load-languages'
158 (defvar org-babel-load-languages)
160 ;;;###autoload
161 (defun org-babel-do-load-languages (sym value)
162 "Load the languages defined in `org-babel-load-languages'."
163 (set-default sym value)
164 (mapc (lambda (pair)
165 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
166 (if active
167 (progn
168 (require (intern (concat "ob-" lang))))
169 (progn
170 (funcall 'fmakunbound
171 (intern (concat "org-babel-execute:" lang)))
172 (funcall 'fmakunbound
173 (intern (concat "org-babel-expand-body:" lang)))))))
174 org-babel-load-languages))
176 (defcustom org-babel-load-languages '((emacs-lisp . t))
177 "Languages which can be evaluated in Org-mode buffers.
178 This list can be used to load support for any of the languages
179 below, note that each language will depend on a different set of
180 system executables and/or Emacs modes. When a language is
181 \"loaded\", then code blocks in that language can be evaluated
182 with `org-babel-execute-src-block' bound by default to C-c
183 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
184 be set to remove code block evaluation from the C-c C-c
185 keybinding. By default only Emacs Lisp (which has no
186 requirements) is loaded."
187 :group 'org-babel
188 :set 'org-babel-do-load-languages
189 :version "24.1"
190 :type '(alist :tag "Babel Languages"
191 :key-type
192 (choice
193 (const :tag "Awk" awk)
194 (const :tag "C" C)
195 (const :tag "R" R)
196 (const :tag "Asymptote" asymptote)
197 (const :tag "Calc" calc)
198 (const :tag "Clojure" clojure)
199 (const :tag "CSS" css)
200 (const :tag "Ditaa" ditaa)
201 (const :tag "Dot" dot)
202 (const :tag "Emacs Lisp" emacs-lisp)
203 (const :tag "Fortran" fortran)
204 (const :tag "Gnuplot" gnuplot)
205 (const :tag "Haskell" haskell)
206 (const :tag "IO" io)
207 (const :tag "Java" java)
208 (const :tag "Javascript" js)
209 (const :tag "LaTeX" latex)
210 (const :tag "Ledger" ledger)
211 (const :tag "Lilypond" lilypond)
212 (const :tag "Lisp" lisp)
213 (const :tag "Makefile" makefile)
214 (const :tag "Maxima" maxima)
215 (const :tag "Matlab" matlab)
216 (const :tag "Mscgen" mscgen)
217 (const :tag "Ocaml" ocaml)
218 (const :tag "Octave" octave)
219 (const :tag "Org" org)
220 (const :tag "Perl" perl)
221 (const :tag "Pico Lisp" picolisp)
222 (const :tag "PlantUML" plantuml)
223 (const :tag "Python" python)
224 (const :tag "Ruby" ruby)
225 (const :tag "Sass" sass)
226 (const :tag "Scala" scala)
227 (const :tag "Scheme" scheme)
228 (const :tag "Screen" screen)
229 (const :tag "Shell Script" sh)
230 (const :tag "Shen" shen)
231 (const :tag "Sql" sql)
232 (const :tag "Sqlite" sqlite))
233 :value-type (boolean :tag "Activate" :value t)))
235 ;;;; Customization variables
236 (defcustom org-clone-delete-id nil
237 "Remove ID property of clones of a subtree.
238 When non-nil, clones of a subtree don't inherit the ID property.
239 Otherwise they inherit the ID property with a new unique
240 identifier."
241 :type 'boolean
242 :version "24.1"
243 :group 'org-id)
245 ;;; Version
246 (org-check-version)
248 ;;;###autoload
249 (defun org-version (&optional here full message)
250 "Show the org-mode version in the echo area.
251 With prefix argument HERE, insert it at point.
252 When FULL is non-nil, use a verbose version string.
253 When MESSAGE is non-nil, display a message with the version."
254 (interactive "P")
255 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
256 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
257 (load-suffixes (list ".el"))
258 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
259 (org-trash (or
260 (and (fboundp 'org-release) (fboundp 'org-git-version))
261 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
262 (load-suffixes save-load-suffixes)
263 (org-version (org-release))
264 (git-version (org-git-version))
265 (version (format "Org-mode version %s (%s @ %s)"
266 org-version
267 git-version
268 (if org-install-dir
269 (if (string= org-dir org-install-dir)
270 org-install-dir
271 (concat "mixed installation! " org-install-dir " and " org-dir))
272 "org-loaddefs.el can not be found!")))
273 (_version (if full version org-version)))
274 (if (org-called-interactively-p 'interactive)
275 (if here
276 (insert version)
277 (message version))
278 (if message (message _version))
279 _version)))
281 (defconst org-version (org-version))
283 ;;; Compatibility constants
285 ;;; The custom variables
287 (defgroup org nil
288 "Outline-based notes management and organizer."
289 :tag "Org"
290 :group 'outlines
291 :group 'calendar)
293 (defcustom org-mode-hook nil
294 "Mode hook for Org-mode, run after the mode was turned on."
295 :group 'org
296 :type 'hook)
298 (defcustom org-load-hook nil
299 "Hook that is run after org.el has been loaded."
300 :group 'org
301 :type 'hook)
303 (defcustom org-log-buffer-setup-hook nil
304 "Hook that is run after an Org log buffer is created."
305 :group 'org
306 :version "24.1"
307 :type 'hook)
309 (defvar org-modules) ; defined below
310 (defvar org-modules-loaded nil
311 "Have the modules been loaded already?")
313 (defun org-load-modules-maybe (&optional force)
314 "Load all extensions listed in `org-modules'."
315 (when (or force (not org-modules-loaded))
316 (mapc (lambda (ext)
317 (condition-case nil (require ext)
318 (error (message "Problems while trying to load feature `%s'" ext))))
319 org-modules)
320 (setq org-modules-loaded t)))
322 (defun org-set-modules (var value)
323 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
324 (set var value)
325 (when (featurep 'org)
326 (org-load-modules-maybe 'force)))
328 (when (org-bound-and-true-p org-modules)
329 (let ((a (member 'org-infojs org-modules)))
330 (and a (setcar a 'org-jsinfo))))
332 (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)
333 "Modules that should always be loaded together with org.el.
334 If a description starts with <C>, the file is not part of Emacs
335 and loading it will require that you have downloaded and properly installed
336 the org-mode distribution.
338 You can also use this system to load external packages (i.e. neither Org
339 core modules, nor modules from the CONTRIB directory). Just add symbols
340 to the end of the list. If the package is called org-xyz.el, then you need
341 to add the symbol `xyz', and the package must have a call to
343 (provide 'org-xyz)"
344 :group 'org
345 :set 'org-set-modules
346 :type
347 '(set :greedy t
348 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
349 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
350 (const :tag " crypt: Encryption of subtrees" org-crypt)
351 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
352 (const :tag " docview: Links to doc-view buffers" org-docview)
353 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
354 (const :tag " id: Global IDs for identifying entries" org-id)
355 (const :tag " info: Links to Info nodes" org-info)
356 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
357 (const :tag " habit: Track your consistency with habits" org-habit)
358 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
359 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
360 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
361 (const :tag " mew Links to Mew folders/messages" org-mew)
362 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
363 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
364 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
365 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
366 (const :tag " vm: Links to VM folders/messages" org-vm)
367 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
368 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
369 (const :tag " mouse: Additional mouse support" org-mouse)
370 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
372 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
373 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
374 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
375 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
376 (const :tag "C collector: Collect properties into tables" org-collector)
377 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
378 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
379 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
380 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
381 (const :tag "C eval: Include command output as text" org-eval)
382 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
383 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
384 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
385 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
386 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
388 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
390 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
391 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
392 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
393 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
394 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
395 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
396 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
397 (const :tag "C mtags: Support for muse-like tags" org-mtags)
398 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
399 (const :tag "C registry: A registry for Org-mode links" org-registry)
400 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
401 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
402 (const :tag "C secretary: Team management with org-mode" org-secretary)
403 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
404 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
405 (const :tag "C track: Keep up with Org-mode development" org-track)
406 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
407 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
408 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
410 (defcustom org-support-shift-select nil
411 "Non-nil means make shift-cursor commands select text when possible.
413 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
414 start selecting a region, or enlarge regions started in this way.
415 In Org-mode, in special contexts, these same keys are used for
416 other purposes, important enough to compete with shift selection.
417 Org tries to balance these needs by supporting `shift-select-mode'
418 outside these special contexts, under control of this variable.
420 The default of this variable is nil, to avoid confusing behavior. Shifted
421 cursor keys will then execute Org commands in the following contexts:
422 - on a headline, changing TODO state (left/right) and priority (up/down)
423 - on a time stamp, changing the time
424 - in a plain list item, changing the bullet type
425 - in a property definition line, switching between allowed values
426 - in the BEGIN line of a clock table (changing the time block).
427 Outside these contexts, the commands will throw an error.
429 When this variable is t and the cursor is not in a special
430 context, Org-mode will support shift-selection for making and
431 enlarging regions. To make this more effective, the bullet
432 cycling will no longer happen anywhere in an item line, but only
433 if the cursor is exactly on the bullet.
435 If you set this variable to the symbol `always', then the keys
436 will not be special in headlines, property lines, and item lines,
437 to make shift selection work there as well. If this is what you
438 want, you can use the following alternative commands: `C-c C-t'
439 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
440 can be used to switch TODO sets, `C-c -' to cycle item bullet
441 types, and properties can be edited by hand or in column view.
443 However, when the cursor is on a timestamp, shift-cursor commands
444 will still edit the time stamp - this is just too good to give up.
446 XEmacs user should have this variable set to nil, because
447 `shift-select-mode' is in Emacs 23 or later only."
448 :group 'org
449 :type '(choice
450 (const :tag "Never" nil)
451 (const :tag "When outside special context" t)
452 (const :tag "Everywhere except timestamps" always)))
454 (defcustom org-loop-over-headlines-in-active-region nil
455 "Shall some commands act upon headlines in the active region?
457 When set to `t', some commands will be performed in all headlines
458 within the active region.
460 When set to `start-level', some commands will be performed in all
461 headlines within the active region, provided that these headlines
462 are of the same level than the first one.
464 When set to a string, those commands will be performed on the
465 matching headlines within the active region. Such string must be
466 a tags/property/todo match as it is used in the agenda tags view.
468 The list of commands is: `org-schedule', `org-deadline',
469 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
470 `org-archive-to-archive-sibling'. The archiving commands skip
471 already archived entries."
472 :type '(choice (const :tag "Don't loop" nil)
473 (const :tag "All headlines in active region" t)
474 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
475 (string :tag "Tags/Property/Todo matcher"))
476 :version "24.1"
477 :group 'org-todo
478 :group 'org-archive)
480 (defgroup org-startup nil
481 "Options concerning startup of Org-mode."
482 :tag "Org Startup"
483 :group 'org)
485 (defcustom org-startup-folded t
486 "Non-nil means entering Org-mode will switch to OVERVIEW.
487 This can also be configured on a per-file basis by adding one of
488 the following lines anywhere in the buffer:
490 #+STARTUP: fold (or `overview', this is equivalent)
491 #+STARTUP: nofold (or `showall', this is equivalent)
492 #+STARTUP: content
493 #+STARTUP: showeverything"
494 :group 'org-startup
495 :type '(choice
496 (const :tag "nofold: show all" nil)
497 (const :tag "fold: overview" t)
498 (const :tag "content: all headlines" content)
499 (const :tag "show everything, even drawers" showeverything)))
501 (defcustom org-startup-truncated t
502 "Non-nil means entering Org-mode will set `truncate-lines'.
503 This is useful since some lines containing links can be very long and
504 uninteresting. Also tables look terrible when wrapped."
505 :group 'org-startup
506 :type 'boolean)
508 (defcustom org-startup-indented nil
509 "Non-nil means turn on `org-indent-mode' on startup.
510 This can also be configured on a per-file basis by adding one of
511 the following lines anywhere in the buffer:
513 #+STARTUP: indent
514 #+STARTUP: noindent"
515 :group 'org-structure
516 :type '(choice
517 (const :tag "Not" nil)
518 (const :tag "Globally (slow on startup in large files)" t)))
520 (defcustom org-use-sub-superscripts t
521 "Non-nil means interpret \"_\" and \"^\" for export.
522 When this option is turned on, you can use TeX-like syntax for sub- and
523 superscripts. Several characters after \"_\" or \"^\" will be
524 considered as a single item - so grouping with {} is normally not
525 needed. For example, the following things will be parsed as single
526 sub- or superscripts.
528 10^24 or 10^tau several digits will be considered 1 item.
529 10^-12 or 10^-tau a leading sign with digits or a word
530 x^2-y^3 will be read as x^2 - y^3, because items are
531 terminated by almost any nonword/nondigit char.
532 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
534 Still, ambiguity is possible - so when in doubt use {} to enclose the
535 sub/superscript. If you set this variable to the symbol `{}',
536 the braces are *required* in order to trigger interpretations as
537 sub/superscript. This can be helpful in documents that need \"_\"
538 frequently in plain text.
540 Not all export backends support this, but HTML does.
542 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
543 :group 'org-startup
544 :group 'org-export-translation
545 :version "24.1"
546 :type '(choice
547 (const :tag "Always interpret" t)
548 (const :tag "Only with braces" {})
549 (const :tag "Never interpret" nil)))
551 (if (fboundp 'defvaralias)
552 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
555 (defcustom org-startup-with-beamer-mode nil
556 "Non-nil means turn on `org-beamer-mode' on startup.
557 This can also be configured on a per-file basis by adding one of
558 the following lines anywhere in the buffer:
560 #+STARTUP: beamer"
561 :group 'org-startup
562 :version "24.1"
563 :type 'boolean)
565 (defcustom org-startup-align-all-tables nil
566 "Non-nil means align all tables when visiting a file.
567 This is useful when the column width in tables is forced with <N> cookies
568 in table fields. Such tables will look correct only after the first re-align.
569 This can also be configured on a per-file basis by adding one of
570 the following lines anywhere in the buffer:
571 #+STARTUP: align
572 #+STARTUP: noalign"
573 :group 'org-startup
574 :type 'boolean)
576 (defcustom org-startup-with-inline-images nil
577 "Non-nil means show inline images when loading a new Org file.
578 This can also be configured on a per-file basis by adding one of
579 the following lines anywhere in the buffer:
580 #+STARTUP: inlineimages
581 #+STARTUP: noinlineimages"
582 :group 'org-startup
583 :version "24.1"
584 :type 'boolean)
586 (defcustom org-insert-mode-line-in-empty-file nil
587 "Non-nil means insert the first line setting Org-mode in empty files.
588 When the function `org-mode' is called interactively in an empty file, this
589 normally means that the file name does not automatically trigger Org-mode.
590 To ensure that the file will always be in Org-mode in the future, a
591 line enforcing Org-mode will be inserted into the buffer, if this option
592 has been set."
593 :group 'org-startup
594 :type 'boolean)
596 (defcustom org-replace-disputed-keys nil
597 "Non-nil means use alternative key bindings for some keys.
598 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
599 These keys are also used by other packages like shift-selection-mode'
600 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
601 If you want to use Org-mode together with one of these other modes,
602 or more generally if you would like to move some Org-mode commands to
603 other keys, set this variable and configure the keys with the variable
604 `org-disputed-keys'.
606 This option is only relevant at load-time of Org-mode, and must be set
607 *before* org.el is loaded. Changing it requires a restart of Emacs to
608 become effective."
609 :group 'org-startup
610 :type 'boolean)
612 (defcustom org-use-extra-keys nil
613 "Non-nil means use extra key sequence definitions for certain commands.
614 This happens automatically if you run XEmacs or if `window-system'
615 is nil. This variable lets you do the same manually. You must
616 set it before loading org.
618 Example: on Carbon Emacs 22 running graphically, with an external
619 keyboard on a Powerbook, the default way of setting M-left might
620 not work for either Alt or ESC. Setting this variable will make
621 it work for ESC."
622 :group 'org-startup
623 :type 'boolean)
625 (if (fboundp 'defvaralias)
626 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
628 (defcustom org-disputed-keys
629 '(([(shift up)] . [(meta p)])
630 ([(shift down)] . [(meta n)])
631 ([(shift left)] . [(meta -)])
632 ([(shift right)] . [(meta +)])
633 ([(control shift right)] . [(meta shift +)])
634 ([(control shift left)] . [(meta shift -)]))
635 "Keys for which Org-mode and other modes compete.
636 This is an alist, cars are the default keys, second element specifies
637 the alternative to use when `org-replace-disputed-keys' is t.
639 Keys can be specified in any syntax supported by `define-key'.
640 The value of this option takes effect only at Org-mode's startup,
641 therefore you'll have to restart Emacs to apply it after changing."
642 :group 'org-startup
643 :type 'alist)
645 (defun org-key (key)
646 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
647 Or return the original if not disputed.
648 Also apply the translations defined in `org-xemacs-key-equivalents'."
649 (when org-replace-disputed-keys
650 (let* ((nkey (key-description key))
651 (x (org-find-if (lambda (x)
652 (equal (key-description (car x)) nkey))
653 org-disputed-keys)))
654 (setq key (if x (cdr x) key))))
655 (when (featurep 'xemacs)
656 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
657 key)
659 (defun org-find-if (predicate seq)
660 (catch 'exit
661 (while seq
662 (if (funcall predicate (car seq))
663 (throw 'exit (car seq))
664 (pop seq)))))
666 (defun org-defkey (keymap key def)
667 "Define a key, possibly translated, as returned by `org-key'."
668 (define-key keymap (org-key key) def))
670 (defcustom org-ellipsis nil
671 "The ellipsis to use in the Org-mode outline.
672 When nil, just use the standard three dots. When a string, use that instead,
673 When a face, use the standard 3 dots, but with the specified face.
674 The change affects only Org-mode (which will then use its own display table).
675 Changing this requires executing `M-x org-mode' in a buffer to become
676 effective."
677 :group 'org-startup
678 :type '(choice (const :tag "Default" nil)
679 (face :tag "Face" :value org-warning)
680 (string :tag "String" :value "...#")))
682 (defvar org-display-table nil
683 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
685 (defgroup org-keywords nil
686 "Keywords in Org-mode."
687 :tag "Org Keywords"
688 :group 'org)
690 (defcustom org-deadline-string "DEADLINE:"
691 "String to mark deadline entries.
692 A deadline is this string, followed by a time stamp. Should be a word,
693 terminated by a colon. You can insert a schedule keyword and
694 a timestamp with \\[org-deadline].
695 Changes become only effective after restarting Emacs."
696 :group 'org-keywords
697 :type 'string)
699 (defcustom org-scheduled-string "SCHEDULED:"
700 "String to mark scheduled TODO entries.
701 A schedule is this string, followed by a time stamp. Should be a word,
702 terminated by a colon. You can insert a schedule keyword and
703 a timestamp with \\[org-schedule].
704 Changes become only effective after restarting Emacs."
705 :group 'org-keywords
706 :type 'string)
708 (defcustom org-closed-string "CLOSED:"
709 "String used as the prefix for timestamps logging closing a TODO entry."
710 :group 'org-keywords
711 :type 'string)
713 (defcustom org-clock-string "CLOCK:"
714 "String used as prefix for timestamps clocking work hours on an item."
715 :group 'org-keywords
716 :type 'string)
718 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
719 org-scheduled-string "\\|"
720 org-deadline-string "\\|"
721 org-closed-string "\\|"
722 org-clock-string "\\)")
723 "Matches a line with planning or clock info.")
725 (defcustom org-comment-string "COMMENT"
726 "Entries starting with this keyword will never be exported.
727 An entry can be toggled between COMMENT and normal with
728 \\[org-toggle-comment].
729 Changes become only effective after restarting Emacs."
730 :group 'org-keywords
731 :type 'string)
733 (defcustom org-quote-string "QUOTE"
734 "Entries starting with this keyword will be exported in fixed-width font.
735 Quoting applies only to the text in the entry following the headline, and does
736 not extend beyond the next headline, even if that is lower level.
737 An entry can be toggled between QUOTE and normal with
738 \\[org-toggle-fixed-width-section]."
739 :group 'org-keywords
740 :type 'string)
742 (defconst org-repeat-re
743 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
744 "Regular expression for specifying repeated events.
745 After a match, group 1 contains the repeat expression.")
747 (defgroup org-structure nil
748 "Options concerning the general structure of Org-mode files."
749 :tag "Org Structure"
750 :group 'org)
752 (defgroup org-reveal-location nil
753 "Options about how to make context of a location visible."
754 :tag "Org Reveal Location"
755 :group 'org-structure)
757 (defconst org-context-choice
758 '(choice
759 (const :tag "Always" t)
760 (const :tag "Never" nil)
761 (repeat :greedy t :tag "Individual contexts"
762 (cons
763 (choice :tag "Context"
764 (const agenda)
765 (const org-goto)
766 (const occur-tree)
767 (const tags-tree)
768 (const link-search)
769 (const mark-goto)
770 (const bookmark-jump)
771 (const isearch)
772 (const default))
773 (boolean))))
774 "Contexts for the reveal options.")
776 (defcustom org-show-hierarchy-above '((default . t))
777 "Non-nil means show full hierarchy when revealing a location.
778 Org-mode often shows locations in an org-mode file which might have
779 been invisible before. When this is set, the hierarchy of headings
780 above the exposed location is shown.
781 Turning this off for example for sparse trees makes them very compact.
782 Instead of t, this can also be an alist specifying this option for different
783 contexts. Valid contexts are
784 agenda when exposing an entry from the agenda
785 org-goto when using the command `org-goto' on key C-c C-j
786 occur-tree when using the command `org-occur' on key C-c /
787 tags-tree when constructing a sparse tree based on tags matches
788 link-search when exposing search matches associated with a link
789 mark-goto when exposing the jump goal of a mark
790 bookmark-jump when exposing a bookmark location
791 isearch when exiting from an incremental search
792 default default for all contexts not set explicitly"
793 :group 'org-reveal-location
794 :type org-context-choice)
796 (defcustom org-show-following-heading '((default . nil))
797 "Non-nil means show following heading when revealing a location.
798 Org-mode often shows locations in an org-mode file which might have
799 been invisible before. When this is set, the heading following the
800 match is shown.
801 Turning this off for example for sparse trees makes them very compact,
802 but makes it harder to edit the location of the match. In such a case,
803 use the command \\[org-reveal] to show more context.
804 Instead of t, this can also be an alist specifying this option for different
805 contexts. See `org-show-hierarchy-above' for valid contexts."
806 :group 'org-reveal-location
807 :type org-context-choice)
809 (defcustom org-show-siblings '((default . nil) (isearch t))
810 "Non-nil means show all sibling heading when revealing a location.
811 Org-mode often shows locations in an org-mode file which might have
812 been invisible before. When this is set, the sibling of the current entry
813 heading are all made visible. If `org-show-hierarchy-above' is t,
814 the same happens on each level of the hierarchy above the current entry.
816 By default this is on for the isearch context, off for all other contexts.
817 Turning this off for example for sparse trees makes them very compact,
818 but makes it harder to edit the location of the match. In such a case,
819 use the command \\[org-reveal] to show more context.
820 Instead of t, this can also be an alist specifying this option for different
821 contexts. See `org-show-hierarchy-above' for valid contexts."
822 :group 'org-reveal-location
823 :type org-context-choice)
825 (defcustom org-show-entry-below '((default . nil))
826 "Non-nil means show the entry below a headline when revealing a location.
827 Org-mode often shows locations in an org-mode file which might have
828 been invisible before. When this is set, the text below the headline that is
829 exposed is also shown.
831 By default this is off for all contexts.
832 Instead of t, this can also be an alist specifying this option for different
833 contexts. See `org-show-hierarchy-above' for valid contexts."
834 :group 'org-reveal-location
835 :type org-context-choice)
837 (defcustom org-indirect-buffer-display 'other-window
838 "How should indirect tree buffers be displayed?
839 This applies to indirect buffers created with the commands
840 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
841 Valid values are:
842 current-window Display in the current window
843 other-window Just display in another window.
844 dedicated-frame Create one new frame, and re-use it each time.
845 new-frame Make a new frame each time. Note that in this case
846 previously-made indirect buffers are kept, and you need to
847 kill these buffers yourself."
848 :group 'org-structure
849 :group 'org-agenda-windows
850 :type '(choice
851 (const :tag "In current window" current-window)
852 (const :tag "In current frame, other window" other-window)
853 (const :tag "Each time a new frame" new-frame)
854 (const :tag "One dedicated frame" dedicated-frame)))
856 (defcustom org-use-speed-commands nil
857 "Non-nil means activate single letter commands at beginning of a headline.
858 This may also be a function to test for appropriate locations where speed
859 commands should be active."
860 :group 'org-structure
861 :type '(choice
862 (const :tag "Never" nil)
863 (const :tag "At beginning of headline stars" t)
864 (function)))
866 (defcustom org-speed-commands-user nil
867 "Alist of additional speed commands.
868 This list will be checked before `org-speed-commands-default'
869 when the variable `org-use-speed-commands' is non-nil
870 and when the cursor is at the beginning of a headline.
871 The car if each entry is a string with a single letter, which must
872 be assigned to `self-insert-command' in the global map.
873 The cdr is either a command to be called interactively, a function
874 to be called, or a form to be evaluated.
875 An entry that is just a list with a single string will be interpreted
876 as a descriptive headline that will be added when listing the speed
877 commands in the Help buffer using the `?' speed command."
878 :group 'org-structure
879 :type '(repeat :value ("k" . ignore)
880 (choice :value ("k" . ignore)
881 (list :tag "Descriptive Headline" (string :tag "Headline"))
882 (cons :tag "Letter and Command"
883 (string :tag "Command letter")
884 (choice
885 (function)
886 (sexp))))))
888 (defgroup org-cycle nil
889 "Options concerning visibility cycling in Org-mode."
890 :tag "Org Cycle"
891 :group 'org-structure)
893 (defcustom org-cycle-skip-children-state-if-no-children t
894 "Non-nil means skip CHILDREN state in entries that don't have any."
895 :group 'org-cycle
896 :type 'boolean)
898 (defcustom org-cycle-max-level nil
899 "Maximum level which should still be subject to visibility cycling.
900 Levels higher than this will, for cycling, be treated as text, not a headline.
901 When `org-odd-levels-only' is set, a value of N in this variable actually
902 means 2N-1 stars as the limiting headline.
903 When nil, cycle all levels.
904 Note that the limiting level of cycling is also influenced by
905 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
906 `org-inlinetask-min-level' is, cycling will be limited to levels one less
907 than its value."
908 :group 'org-cycle
909 :type '(choice
910 (const :tag "No limit" nil)
911 (integer :tag "Maximum level")))
913 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
914 "Names of drawers. Drawers are not opened by cycling on the headline above.
915 Drawers only open with a TAB on the drawer line itself. A drawer looks like
916 this:
917 :DRAWERNAME:
918 .....
919 :END:
920 The drawer \"PROPERTIES\" is special for capturing properties through
921 the property API.
923 Drawers can be defined on the per-file basis with a line like:
925 #+DRAWERS: HIDDEN STATE PROPERTIES"
926 :group 'org-structure
927 :group 'org-cycle
928 :type '(repeat (string :tag "Drawer Name")))
930 (defcustom org-hide-block-startup nil
931 "Non-nil means entering Org-mode will fold all blocks.
932 This can also be set in on a per-file basis with
934 #+STARTUP: hideblocks
935 #+STARTUP: showblocks"
936 :group 'org-startup
937 :group 'org-cycle
938 :type 'boolean)
940 (defcustom org-cycle-global-at-bob nil
941 "Cycle globally if cursor is at beginning of buffer and not at a headline.
942 This makes it possible to do global cycling without having to use S-TAB or
943 \\[universal-argument] TAB. For this special case to work, the first line
944 of the buffer must not be a headline -- it may be empty or some other text.
945 When used in this way, `org-cycle-hook' is disabled temporarily to make
946 sure the cursor stays at the beginning of the buffer. When this option is
947 nil, don't do anything special at the beginning of the buffer."
948 :group 'org-cycle
949 :type 'boolean)
951 (defcustom org-cycle-level-after-item/entry-creation t
952 "Non-nil means cycle entry level or item indentation in new empty entries.
954 When the cursor is at the end of an empty headline, i.e with only stars
955 and maybe a TODO keyword, TAB will then switch the entry to become a child,
956 and then all possible ancestor states, before returning to the original state.
957 This makes data entry extremely fast: M-RET to create a new headline,
958 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
960 When the cursor is at the end of an empty plain list item, one TAB will
961 make it a subitem, two or more tabs will back up to make this an item
962 higher up in the item hierarchy."
963 :group 'org-cycle
964 :type 'boolean)
966 (defcustom org-cycle-emulate-tab t
967 "Where should `org-cycle' emulate TAB.
968 nil Never
969 white Only in completely white lines
970 whitestart Only at the beginning of lines, before the first non-white char
971 t Everywhere except in headlines
972 exc-hl-bol Everywhere except at the start of a headline
973 If TAB is used in a place where it does not emulate TAB, the current subtree
974 visibility is cycled."
975 :group 'org-cycle
976 :type '(choice (const :tag "Never" nil)
977 (const :tag "Only in completely white lines" white)
978 (const :tag "Before first char in a line" whitestart)
979 (const :tag "Everywhere except in headlines" t)
980 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
983 (defcustom org-cycle-separator-lines 2
984 "Number of empty lines needed to keep an empty line between collapsed trees.
985 If you leave an empty line between the end of a subtree and the following
986 headline, this empty line is hidden when the subtree is folded.
987 Org-mode will leave (exactly) one empty line visible if the number of
988 empty lines is equal or larger to the number given in this variable.
989 So the default 2 means at least 2 empty lines after the end of a subtree
990 are needed to produce free space between a collapsed subtree and the
991 following headline.
993 If the number is negative, and the number of empty lines is at least -N,
994 all empty lines are shown.
996 Special case: when 0, never leave empty lines in collapsed view."
997 :group 'org-cycle
998 :type 'integer)
999 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1001 (defcustom org-pre-cycle-hook nil
1002 "Hook that is run before visibility cycling is happening.
1003 The function(s) in this hook must accept a single argument which indicates
1004 the new state that will be set right after running this hook. The
1005 argument is a symbol. Before a global state change, it can have the values
1006 `overview', `content', or `all'. Before a local state change, it can have
1007 the values `folded', `children', or `subtree'."
1008 :group 'org-cycle
1009 :type 'hook)
1011 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1012 org-cycle-hide-drawers
1013 org-cycle-hide-inline-tasks
1014 org-cycle-show-empty-lines
1015 org-optimize-window-after-visibility-change)
1016 "Hook that is run after `org-cycle' has changed the buffer visibility.
1017 The function(s) in this hook must accept a single argument which indicates
1018 the new state that was set by the most recent `org-cycle' command. The
1019 argument is a symbol. After a global state change, it can have the values
1020 `overview', `contents', or `all'. After a local state change, it can have
1021 the values `folded', `children', or `subtree'."
1022 :group 'org-cycle
1023 :type 'hook)
1025 (defgroup org-edit-structure nil
1026 "Options concerning structure editing in Org-mode."
1027 :tag "Org Edit Structure"
1028 :group 'org-structure)
1030 (defcustom org-odd-levels-only nil
1031 "Non-nil means skip even levels and only use odd levels for the outline.
1032 This has the effect that two stars are being added/taken away in
1033 promotion/demotion commands. It also influences how levels are
1034 handled by the exporters.
1035 Changing it requires restart of `font-lock-mode' to become effective
1036 for fontification also in regions already fontified.
1037 You may also set this on a per-file basis by adding one of the following
1038 lines to the buffer:
1040 #+STARTUP: odd
1041 #+STARTUP: oddeven"
1042 :group 'org-edit-structure
1043 :group 'org-appearance
1044 :type 'boolean)
1046 (defcustom org-adapt-indentation t
1047 "Non-nil means adapt indentation to outline node level.
1049 When this variable is set, Org assumes that you write outlines by
1050 indenting text in each node to align with the headline (after the stars).
1051 The following issues are influenced by this variable:
1053 - When this is set and the *entire* text in an entry is indented, the
1054 indentation is increased by one space in a demotion command, and
1055 decreased by one in a promotion command. If any line in the entry
1056 body starts with text at column 0, indentation is not changed at all.
1058 - Property drawers and planning information is inserted indented when
1059 this variable s set. When nil, they will not be indented.
1061 - TAB indents a line relative to context. The lines below a headline
1062 will be indented when this variable is set.
1064 Note that this is all about true indentation, by adding and removing
1065 space characters. See also `org-indent.el' which does level-dependent
1066 indentation in a virtual way, i.e. at display time in Emacs."
1067 :group 'org-edit-structure
1068 :type 'boolean)
1070 (defcustom org-special-ctrl-a/e nil
1071 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1073 When t, `C-a' will bring back the cursor to the beginning of the
1074 headline text, i.e. after the stars and after a possible TODO
1075 keyword. In an item, this will be the position after bullet and
1076 check-box, if any. When the cursor is already at that position,
1077 another `C-a' will bring it to the beginning of the line.
1079 `C-e' will jump to the end of the headline, ignoring the presence
1080 of tags in the headline. A second `C-e' will then jump to the
1081 true end of the line, after any tags. This also means that, when
1082 this variable is non-nil, `C-e' also will never jump beyond the
1083 end of the heading of a folded section, i.e. not after the
1084 ellipses.
1086 When set to the symbol `reversed', the first `C-a' or `C-e' works
1087 normally, going to the true line boundary first. Only a directly
1088 following, identical keypress will bring the cursor to the
1089 special positions.
1091 This may also be a cons cell where the behavior for `C-a' and
1092 `C-e' is set separately."
1093 :group 'org-edit-structure
1094 :type '(choice
1095 (const :tag "off" nil)
1096 (const :tag "on: after stars/bullet and before tags first" t)
1097 (const :tag "reversed: true line boundary first" reversed)
1098 (cons :tag "Set C-a and C-e separately"
1099 (choice :tag "Special C-a"
1100 (const :tag "off" nil)
1101 (const :tag "on: after stars/bullet first" t)
1102 (const :tag "reversed: before stars/bullet first" reversed))
1103 (choice :tag "Special C-e"
1104 (const :tag "off" nil)
1105 (const :tag "on: before tags first" t)
1106 (const :tag "reversed: after tags first" reversed)))))
1107 (if (fboundp 'defvaralias)
1108 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1110 (defcustom org-special-ctrl-k nil
1111 "Non-nil means `C-k' will behave specially in headlines.
1112 When nil, `C-k' will call the default `kill-line' command.
1113 When t, the following will happen while the cursor is in the headline:
1115 - When the cursor is at the beginning of a headline, kill the entire
1116 line and possible the folded subtree below the line.
1117 - When in the middle of the headline text, kill the headline up to the tags.
1118 - When after the headline text, kill the tags."
1119 :group 'org-edit-structure
1120 :type 'boolean)
1122 (defcustom org-ctrl-k-protect-subtree nil
1123 "Non-nil means, do not delete a hidden subtree with C-k.
1124 When set to the symbol `error', simply throw an error when C-k is
1125 used to kill (part-of) a headline that has hidden text behind it.
1126 Any other non-nil value will result in a query to the user, if it is
1127 OK to kill that hidden subtree. When nil, kill without remorse."
1128 :group 'org-edit-structure
1129 :version "24.1"
1130 :type '(choice
1131 (const :tag "Do not protect hidden subtrees" nil)
1132 (const :tag "Protect hidden subtrees with a security query" t)
1133 (const :tag "Never kill a hidden subtree with C-k" error)))
1135 (defcustom org-catch-invisible-edits nil
1136 "Check if in invisible region before inserting or deleting a character.
1137 Valid values are:
1139 nil Do not check, so just do invisible edits.
1140 error Throw an error and do nothing.
1141 show Make point visible, and do the requested edit.
1142 show-and-error Make point visible, then throw an error and abort the edit.
1143 smart Make point visible, and do insertion/deletion if it is
1144 adjacent to visible text and the change feels predictable.
1145 Never delete a previously invisible character or add in the
1146 middle or right after an invisible region. Basically, this
1147 allows insertion and backward-delete right before ellipses.
1148 FIXME: maybe in this case we should not even show?"
1149 :group 'org-edit-structure
1150 :version "24.1"
1151 :type '(choice
1152 (const :tag "Do not check" nil)
1153 (const :tag "Throw error when trying to edit" error)
1154 (const :tag "Unhide, but do not do the edit" show-and-error)
1155 (const :tag "Show invisible part and do the edit" show)
1156 (const :tag "Be smart and do the right thing" smart)))
1158 (defcustom org-yank-folded-subtrees t
1159 "Non-nil means when yanking subtrees, fold them.
1160 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1161 it starts with a heading and all other headings in it are either children
1162 or siblings, then fold all the subtrees. However, do this only if no
1163 text after the yank would be swallowed into a folded tree by this action."
1164 :group 'org-edit-structure
1165 :type 'boolean)
1167 (defcustom org-yank-adjusted-subtrees nil
1168 "Non-nil means when yanking subtrees, adjust the level.
1169 With this setting, `org-paste-subtree' is used to insert the subtree, see
1170 this function for details."
1171 :group 'org-edit-structure
1172 :type 'boolean)
1174 (defcustom org-M-RET-may-split-line '((default . t))
1175 "Non-nil means M-RET will split the line at the cursor position.
1176 When nil, it will go to the end of the line before making a
1177 new line.
1178 You may also set this option in a different way for different
1179 contexts. Valid contexts are:
1181 headline when creating a new headline
1182 item when creating a new item
1183 table in a table field
1184 default the value to be used for all contexts not explicitly
1185 customized"
1186 :group 'org-structure
1187 :group 'org-table
1188 :type '(choice
1189 (const :tag "Always" t)
1190 (const :tag "Never" nil)
1191 (repeat :greedy t :tag "Individual contexts"
1192 (cons
1193 (choice :tag "Context"
1194 (const headline)
1195 (const item)
1196 (const table)
1197 (const default))
1198 (boolean)))))
1201 (defcustom org-insert-heading-respect-content nil
1202 "Non-nil means insert new headings after the current subtree.
1203 When nil, the new heading is created directly after the current line.
1204 The commands \\[org-insert-heading-respect-content] and
1205 \\[org-insert-todo-heading-respect-content] turn this variable on
1206 for the duration of the command."
1207 :group 'org-structure
1208 :type 'boolean)
1210 (defcustom org-blank-before-new-entry '((heading . auto)
1211 (plain-list-item . auto))
1212 "Should `org-insert-heading' leave a blank line before new heading/item?
1213 The value is an alist, with `heading' and `plain-list-item' as CAR,
1214 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1215 which case Org will look at the surrounding headings/items and try to
1216 make an intelligent decision whether to insert a blank line or not.
1218 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1219 set, the setting here is ignored and no empty line is inserted, to avoid
1220 breaking the list structure."
1221 :group 'org-edit-structure
1222 :type '(list
1223 (cons (const heading)
1224 (choice (const :tag "Never" nil)
1225 (const :tag "Always" t)
1226 (const :tag "Auto" auto)))
1227 (cons (const plain-list-item)
1228 (choice (const :tag "Never" nil)
1229 (const :tag "Always" t)
1230 (const :tag "Auto" auto)))))
1232 (defcustom org-insert-heading-hook nil
1233 "Hook being run after inserting a new heading."
1234 :group 'org-edit-structure
1235 :type 'hook)
1237 (defcustom org-enable-fixed-width-editor t
1238 "Non-nil means lines starting with \":\" are treated as fixed-width.
1239 This currently only means they are never auto-wrapped.
1240 When nil, such lines will be treated like ordinary lines.
1241 See also the QUOTE keyword."
1242 :group 'org-edit-structure
1243 :type 'boolean)
1245 (defcustom org-goto-auto-isearch t
1246 "Non-nil means typing characters in `org-goto' starts incremental search.
1247 When nil, you can use these keybindings to navigate the buffer:
1249 q Quit the org-goto interface
1250 n Go to the next visible heading
1251 p Go to the previous visible heading
1252 f Go one heading forward on same level
1253 b Go one heading backward on same level
1254 u Go one heading up"
1255 :group 'org-edit-structure
1256 :type 'boolean)
1258 (defgroup org-sparse-trees nil
1259 "Options concerning sparse trees in Org-mode."
1260 :tag "Org Sparse Trees"
1261 :group 'org-structure)
1263 (defcustom org-highlight-sparse-tree-matches t
1264 "Non-nil means highlight all matches that define a sparse tree.
1265 The highlights will automatically disappear the next time the buffer is
1266 changed by an edit command."
1267 :group 'org-sparse-trees
1268 :type 'boolean)
1270 (defcustom org-remove-highlights-with-change t
1271 "Non-nil means any change to the buffer will remove temporary highlights.
1272 Such highlights are created by `org-occur' and `org-clock-display'.
1273 When nil, `C-c C-c needs to be used to get rid of the highlights.
1274 The highlights created by `org-preview-latex-fragment' always need
1275 `C-c C-c' to be removed."
1276 :group 'org-sparse-trees
1277 :group 'org-time
1278 :type 'boolean)
1281 (defcustom org-occur-hook '(org-first-headline-recenter)
1282 "Hook that is run after `org-occur' has constructed a sparse tree.
1283 This can be used to recenter the window to show as much of the structure
1284 as possible."
1285 :group 'org-sparse-trees
1286 :type 'hook)
1288 (defgroup org-imenu-and-speedbar nil
1289 "Options concerning imenu and speedbar in Org-mode."
1290 :tag "Org Imenu and Speedbar"
1291 :group 'org-structure)
1293 (defcustom org-imenu-depth 2
1294 "The maximum level for Imenu access to Org-mode headlines.
1295 This also applied for speedbar access."
1296 :group 'org-imenu-and-speedbar
1297 :type 'integer)
1299 (defgroup org-table nil
1300 "Options concerning tables in Org-mode."
1301 :tag "Org Table"
1302 :group 'org)
1304 (defcustom org-enable-table-editor 'optimized
1305 "Non-nil means lines starting with \"|\" are handled by the table editor.
1306 When nil, such lines will be treated like ordinary lines.
1308 When equal to the symbol `optimized', the table editor will be optimized to
1309 do the following:
1310 - Automatic overwrite mode in front of whitespace in table fields.
1311 This makes the structure of the table stay in tact as long as the edited
1312 field does not exceed the column width.
1313 - Minimize the number of realigns. Normally, the table is aligned each time
1314 TAB or RET are pressed to move to another field. With optimization this
1315 happens only if changes to a field might have changed the column width.
1316 Optimization requires replacing the functions `self-insert-command',
1317 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1318 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1319 very good at guessing when a re-align will be necessary, but you can always
1320 force one with \\[org-ctrl-c-ctrl-c].
1322 If you would like to use the optimized version in Org-mode, but the
1323 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1325 This variable can be used to turn on and off the table editor during a session,
1326 but in order to toggle optimization, a restart is required.
1328 See also the variable `org-table-auto-blank-field'."
1329 :group 'org-table
1330 :type '(choice
1331 (const :tag "off" nil)
1332 (const :tag "on" t)
1333 (const :tag "on, optimized" optimized)))
1335 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1336 (version<= emacs-version "24.1"))
1337 "Non-nil means cluster self-insert commands for undo when possible.
1338 If this is set, then, like in the Emacs command loop, 20 consecutive
1339 characters will be undone together.
1340 This is configurable, because there is some impact on typing performance."
1341 :group 'org-table
1342 :type 'boolean)
1344 (defcustom org-table-tab-recognizes-table.el t
1345 "Non-nil means TAB will automatically notice a table.el table.
1346 When it sees such a table, it moves point into it and - if necessary -
1347 calls `table-recognize-table'."
1348 :group 'org-table-editing
1349 :type 'boolean)
1351 (defgroup org-link nil
1352 "Options concerning links in Org-mode."
1353 :tag "Org Link"
1354 :group 'org)
1356 (defvar org-link-abbrev-alist-local nil
1357 "Buffer-local version of `org-link-abbrev-alist', which see.
1358 The value of this is taken from the #+LINK lines.")
1359 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1361 (defcustom org-link-abbrev-alist nil
1362 "Alist of link abbreviations.
1363 The car of each element is a string, to be replaced at the start of a link.
1364 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1365 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1367 [[linkkey:tag][description]]
1369 The 'linkkey' must be a word word, starting with a letter, followed
1370 by letters, numbers, '-' or '_'.
1372 If REPLACE is a string, the tag will simply be appended to create the link.
1373 If the string contains \"%s\", the tag will be inserted there. If the string
1374 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1375 at that point (see the function `url-hexify-string'). If the string contains
1376 the specifier \"%(my-function)\", then the custom function `my-function' will
1377 be invoked: this function takes the tag as its only argument and must return
1378 a string.
1380 REPLACE may also be a function that will be called with the tag as the
1381 only argument to create the link, which should be returned as a string.
1383 See the manual for examples."
1384 :group 'org-link
1385 :type '(repeat
1386 (cons
1387 (string :tag "Protocol")
1388 (choice
1389 (string :tag "Format")
1390 (function)))))
1392 (defcustom org-descriptive-links t
1393 "Non-nil means Org will display descriptive links.
1394 E.g. [[http://orgmode.org][Org website]] will be displayed as
1395 \"Org Website\", hiding the link itself and just displaying its
1396 description. When set to `nil', Org will display the full links
1397 literally.
1399 You can interactively set the value of this variable by calling
1400 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1401 :group 'org-link
1402 :type 'boolean)
1404 (defcustom org-link-file-path-type 'adaptive
1405 "How the path name in file links should be stored.
1406 Valid values are:
1408 relative Relative to the current directory, i.e. the directory of the file
1409 into which the link is being inserted.
1410 absolute Absolute path, if possible with ~ for home directory.
1411 noabbrev Absolute path, no abbreviation of home directory.
1412 adaptive Use relative path for files in the current directory and sub-
1413 directories of it. For other files, use an absolute path."
1414 :group 'org-link
1415 :type '(choice
1416 (const relative)
1417 (const absolute)
1418 (const noabbrev)
1419 (const adaptive)))
1421 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1422 "Types of links that should be activated in Org-mode files.
1423 This is a list of symbols, each leading to the activation of a certain link
1424 type. In principle, it does not hurt to turn on most link types - there may
1425 be a small gain when turning off unused link types. The types are:
1427 bracket The recommended [[link][description]] or [[link]] links with hiding.
1428 angle Links in angular brackets that may contain whitespace like
1429 <bbdb:Carsten Dominik>.
1430 plain Plain links in normal text, no whitespace, like http://google.com.
1431 radio Text that is matched by a radio target, see manual for details.
1432 tag Tag settings in a headline (link to tag search).
1433 date Time stamps (link to calendar).
1434 footnote Footnote labels.
1436 Changing this variable requires a restart of Emacs to become effective."
1437 :group 'org-link
1438 :type '(set :greedy t
1439 (const :tag "Double bracket links" bracket)
1440 (const :tag "Angular bracket links" angle)
1441 (const :tag "Plain text links" plain)
1442 (const :tag "Radio target matches" radio)
1443 (const :tag "Tags" tag)
1444 (const :tag "Timestamps" date)
1445 (const :tag "Footnotes" footnote)))
1447 (defcustom org-make-link-description-function nil
1448 "Function to use for generating link descriptions from links.
1449 When nil, the link location will be used. This function must take
1450 two parameters: the first one is the link, the second one is the
1451 description generated by `org-insert-link'. The function should
1452 return the description to use."
1453 :group 'org-link
1454 :type 'function)
1456 (defgroup org-link-store nil
1457 "Options concerning storing links in Org-mode."
1458 :tag "Org Store Link"
1459 :group 'org-link)
1461 (defcustom org-url-hexify-p t
1462 "When non-nil, hexify URL when creating a link."
1463 :type 'boolean
1464 :version "24.3"
1465 :group 'org-link-store)
1467 (defcustom org-email-link-description-format "Email %c: %.30s"
1468 "Format of the description part of a link to an email or usenet message.
1469 The following %-escapes will be replaced by corresponding information:
1471 %F full \"From\" field
1472 %f name, taken from \"From\" field, address if no name
1473 %T full \"To\" field
1474 %t first name in \"To\" field, address if no name
1475 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1476 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1477 %s subject
1478 %d date
1479 %m message-id.
1481 You may use normal field width specification between the % and the letter.
1482 This is for example useful to limit the length of the subject.
1484 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1485 :group 'org-link-store
1486 :type 'string)
1488 (defcustom org-from-is-user-regexp
1489 (let (r1 r2)
1490 (when (and user-mail-address (not (string= user-mail-address "")))
1491 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1492 (when (and user-full-name (not (string= user-full-name "")))
1493 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1494 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1495 "Regexp matched against the \"From:\" header of an email or usenet message.
1496 It should match if the message is from the user him/herself."
1497 :group 'org-link-store
1498 :type 'regexp)
1500 (defcustom org-context-in-file-links t
1501 "Non-nil means file links from `org-store-link' contain context.
1502 A search string will be added to the file name with :: as separator and
1503 used to find the context when the link is activated by the command
1504 `org-open-at-point'. When this option is t, the entire active region
1505 will be placed in the search string of the file link. If set to a
1506 positive integer, only the first n lines of context will be stored.
1508 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1509 negates this setting for the duration of the command."
1510 :group 'org-link-store
1511 :type '(choice boolean integer))
1513 (defcustom org-keep-stored-link-after-insertion nil
1514 "Non-nil means keep link in list for entire session.
1516 The command `org-store-link' adds a link pointing to the current
1517 location to an internal list. These links accumulate during a session.
1518 The command `org-insert-link' can be used to insert links into any
1519 Org-mode file (offering completion for all stored links). When this
1520 option is nil, every link which has been inserted once using \\[org-insert-link]
1521 will be removed from the list, to make completing the unused links
1522 more efficient."
1523 :group 'org-link-store
1524 :type 'boolean)
1526 (defgroup org-link-follow nil
1527 "Options concerning following links in Org-mode."
1528 :tag "Org Follow Link"
1529 :group 'org-link)
1531 (defcustom org-link-translation-function nil
1532 "Function to translate links with different syntax to Org syntax.
1533 This can be used to translate links created for example by the Planner
1534 or emacs-wiki packages to Org syntax.
1535 The function must accept two parameters, a TYPE containing the link
1536 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1537 which is everything after the link protocol. It should return a cons
1538 with possibly modified values of type and path.
1539 Org contains a function for this, so if you set this variable to
1540 `org-translate-link-from-planner', you should be able follow many
1541 links created by planner."
1542 :group 'org-link-follow
1543 :type 'function)
1545 (defcustom org-follow-link-hook nil
1546 "Hook that is run after a link has been followed."
1547 :group 'org-link-follow
1548 :type 'hook)
1550 (defcustom org-tab-follows-link nil
1551 "Non-nil means on links TAB will follow the link.
1552 Needs to be set before org.el is loaded.
1553 This really should not be used, it does not make sense, and the
1554 implementation is bad."
1555 :group 'org-link-follow
1556 :type 'boolean)
1558 (defcustom org-return-follows-link nil
1559 "Non-nil means on links RET will follow the link."
1560 :group 'org-link-follow
1561 :type 'boolean)
1563 (defcustom org-mouse-1-follows-link
1564 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1565 "Non-nil means mouse-1 on a link will follow the link.
1566 A longer mouse click will still set point. Does not work on XEmacs.
1567 Needs to be set before org.el is loaded."
1568 :group 'org-link-follow
1569 :type 'boolean)
1571 (defcustom org-mark-ring-length 4
1572 "Number of different positions to be recorded in the ring.
1573 Changing this requires a restart of Emacs to work correctly."
1574 :group 'org-link-follow
1575 :type 'integer)
1577 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1578 "Non-nil means internal links in Org files must exactly match a headline.
1579 When nil, the link search tries to match a phrase with all words
1580 in the search text."
1581 :group 'org-link-follow
1582 :version "24.1"
1583 :type '(choice
1584 (const :tag "Use fuzzy text search" nil)
1585 (const :tag "Match only exact headline" t)
1586 (const :tag "Match exact headline or query to create it"
1587 query-to-create)))
1589 (defcustom org-link-frame-setup
1590 '((vm . vm-visit-folder-other-frame)
1591 (vm-imap . vm-visit-imap-folder-other-frame)
1592 (gnus . org-gnus-no-new-news)
1593 (file . find-file-other-window)
1594 (wl . wl-other-frame))
1595 "Setup the frame configuration for following links.
1596 When following a link with Emacs, it may often be useful to display
1597 this link in another window or frame. This variable can be used to
1598 set this up for the different types of links.
1599 For VM, use any of
1600 `vm-visit-folder'
1601 `vm-visit-folder-other-window'
1602 `vm-visit-folder-other-frame'
1603 For Gnus, use any of
1604 `gnus'
1605 `gnus-other-frame'
1606 `org-gnus-no-new-news'
1607 For FILE, use any of
1608 `find-file'
1609 `find-file-other-window'
1610 `find-file-other-frame'
1611 For Wanderlust use any of
1612 `wl'
1613 `wl-other-frame'
1614 For the calendar, use the variable `calendar-setup'.
1615 For BBDB, it is currently only possible to display the matches in
1616 another window."
1617 :group 'org-link-follow
1618 :type '(list
1619 (cons (const vm)
1620 (choice
1621 (const vm-visit-folder)
1622 (const vm-visit-folder-other-window)
1623 (const vm-visit-folder-other-frame)))
1624 (cons (const gnus)
1625 (choice
1626 (const gnus)
1627 (const gnus-other-frame)
1628 (const org-gnus-no-new-news)))
1629 (cons (const file)
1630 (choice
1631 (const find-file)
1632 (const find-file-other-window)
1633 (const find-file-other-frame)))
1634 (cons (const wl)
1635 (choice
1636 (const wl)
1637 (const wl-other-frame)))))
1639 (defcustom org-display-internal-link-with-indirect-buffer nil
1640 "Non-nil means use indirect buffer to display infile links.
1641 Activating internal links (from one location in a file to another location
1642 in the same file) normally just jumps to the location. When the link is
1643 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1644 is displayed in
1645 another window. When this option is set, the other window actually displays
1646 an indirect buffer clone of the current buffer, to avoid any visibility
1647 changes to the current buffer."
1648 :group 'org-link-follow
1649 :type 'boolean)
1651 (defcustom org-open-non-existing-files nil
1652 "Non-nil means `org-open-file' will open non-existing files.
1653 When nil, an error will be generated.
1654 This variable applies only to external applications because they
1655 might choke on non-existing files. If the link is to a file that
1656 will be opened in Emacs, the variable is ignored."
1657 :group 'org-link-follow
1658 :type 'boolean)
1660 (defcustom org-open-directory-means-index-dot-org nil
1661 "Non-nil means a link to a directory really means to index.org.
1662 When nil, following a directory link will run dired or open a finder/explorer
1663 window on that directory."
1664 :group 'org-link-follow
1665 :type 'boolean)
1667 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1668 "Function and arguments to call for following mailto links.
1669 This is a list with the first element being a Lisp function, and the
1670 remaining elements being arguments to the function. In string arguments,
1671 %a will be replaced by the address, and %s will be replaced by the subject
1672 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1673 :group 'org-link-follow
1674 :type '(choice
1675 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1676 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1677 (const :tag "message-mail" (message-mail "%a" "%s"))
1678 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1680 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1681 "Non-nil means ask for confirmation before executing shell links.
1682 Shell links can be dangerous: just think about a link
1684 [[shell:rm -rf ~/*][Google Search]]
1686 This link would show up in your Org-mode document as \"Google Search\",
1687 but really it would remove your entire home directory.
1688 Therefore we advise against setting this variable to nil.
1689 Just change it to `y-or-n-p' if you want to confirm with a
1690 single keystroke rather than having to type \"yes\"."
1691 :group 'org-link-follow
1692 :type '(choice
1693 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1694 (const :tag "with y-or-n (faster)" y-or-n-p)
1695 (const :tag "no confirmation (dangerous)" nil)))
1696 (put 'org-confirm-shell-link-function
1697 'safe-local-variable
1698 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1700 (defcustom org-confirm-shell-link-not-regexp ""
1701 "A regexp to skip confirmation for shell links."
1702 :group 'org-link-follow
1703 :version "24.1"
1704 :type 'regexp)
1706 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1707 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1708 Elisp links can be dangerous: just think about a link
1710 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1712 This link would show up in your Org-mode document as \"Google Search\",
1713 but really it would remove your entire home directory.
1714 Therefore we advise against setting this variable to nil.
1715 Just change it to `y-or-n-p' if you want to confirm with a
1716 single keystroke rather than having to type \"yes\"."
1717 :group 'org-link-follow
1718 :type '(choice
1719 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1720 (const :tag "with y-or-n (faster)" y-or-n-p)
1721 (const :tag "no confirmation (dangerous)" nil)))
1722 (put 'org-confirm-shell-link-function
1723 'safe-local-variable
1724 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1726 (defcustom org-confirm-elisp-link-not-regexp ""
1727 "A regexp to skip confirmation for Elisp links."
1728 :group 'org-link-follow
1729 :version "24.1"
1730 :type 'regexp)
1732 (defconst org-file-apps-defaults-gnu
1733 '((remote . emacs)
1734 (system . mailcap)
1735 (t . mailcap))
1736 "Default file applications on a UNIX or GNU/Linux system.
1737 See `org-file-apps'.")
1739 (defconst org-file-apps-defaults-macosx
1740 '((remote . emacs)
1741 (t . "open %s")
1742 (system . "open %s")
1743 ("ps.gz" . "gv %s")
1744 ("eps.gz" . "gv %s")
1745 ("dvi" . "xdvi %s")
1746 ("fig" . "xfig %s"))
1747 "Default file applications on a MacOS X system.
1748 The system \"open\" is known as a default, but we use X11 applications
1749 for some files for which the OS does not have a good default.
1750 See `org-file-apps'.")
1752 (defconst org-file-apps-defaults-windowsnt
1753 (list
1754 '(remote . emacs)
1755 (cons t
1756 (list (if (featurep 'xemacs)
1757 'mswindows-shell-execute
1758 'w32-shell-execute)
1759 "open" 'file))
1760 (cons 'system
1761 (list (if (featurep 'xemacs)
1762 'mswindows-shell-execute
1763 'w32-shell-execute)
1764 "open" 'file)))
1765 "Default file applications on a Windows NT system.
1766 The system \"open\" is used for most files.
1767 See `org-file-apps'.")
1769 (defcustom org-file-apps
1771 (auto-mode . emacs)
1772 ("\\.mm\\'" . default)
1773 ("\\.x?html?\\'" . default)
1774 ("\\.pdf\\'" . default)
1776 "External applications for opening `file:path' items in a document.
1777 Org-mode uses system defaults for different file types, but
1778 you can use this variable to set the application for a given file
1779 extension. The entries in this list are cons cells where the car identifies
1780 files and the cdr the corresponding command. Possible values for the
1781 file identifier are
1782 \"string\" A string as a file identifier can be interpreted in different
1783 ways, depending on its contents:
1785 - Alphanumeric characters only:
1786 Match links with this file extension.
1787 Example: (\"pdf\" . \"evince %s\")
1788 to open PDFs with evince.
1790 - Regular expression: Match links where the
1791 filename matches the regexp. If you want to
1792 use groups here, use shy groups.
1794 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1795 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1796 to open *.html and *.xhtml with firefox.
1798 - Regular expression which contains (non-shy) groups:
1799 Match links where the whole link, including \"::\", and
1800 anything after that, matches the regexp.
1801 In a custom command string, %1, %2, etc. are replaced with
1802 the parts of the link that were matched by the groups.
1803 For backwards compatibility, if a command string is given
1804 that does not use any of the group matches, this case is
1805 handled identically to the second one (i.e. match against
1806 file name only).
1807 In a custom lisp form, you can access the group matches with
1808 (match-string n link).
1810 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1811 to open [[file:document.pdf::5]] with evince at page 5.
1813 `directory' Matches a directory
1814 `remote' Matches a remote file, accessible through tramp or efs.
1815 Remote files most likely should be visited through Emacs
1816 because external applications cannot handle such paths.
1817 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1818 so all files Emacs knows how to handle. Using this with
1819 command `emacs' will open most files in Emacs. Beware that this
1820 will also open html files inside Emacs, unless you add
1821 (\"html\" . default) to the list as well.
1822 t Default for files not matched by any of the other options.
1823 `system' The system command to open files, like `open' on Windows
1824 and Mac OS X, and mailcap under GNU/Linux. This is the command
1825 that will be selected if you call `C-c C-o' with a double
1826 \\[universal-argument] \\[universal-argument] prefix.
1828 Possible values for the command are:
1829 `emacs' The file will be visited by the current Emacs process.
1830 `default' Use the default application for this file type, which is the
1831 association for t in the list, most likely in the system-specific
1832 part.
1833 This can be used to overrule an unwanted setting in the
1834 system-specific variable.
1835 `system' Use the system command for opening files, like \"open\".
1836 This command is specified by the entry whose car is `system'.
1837 Most likely, the system-specific version of this variable
1838 does define this command, but you can overrule/replace it
1839 here.
1840 string A command to be executed by a shell; %s will be replaced
1841 by the path to the file.
1842 sexp A Lisp form which will be evaluated. The file path will
1843 be available in the Lisp variable `file'.
1844 For more examples, see the system specific constants
1845 `org-file-apps-defaults-macosx'
1846 `org-file-apps-defaults-windowsnt'
1847 `org-file-apps-defaults-gnu'."
1848 :group 'org-link-follow
1849 :type '(repeat
1850 (cons (choice :value ""
1851 (string :tag "Extension")
1852 (const :tag "System command to open files" system)
1853 (const :tag "Default for unrecognized files" t)
1854 (const :tag "Remote file" remote)
1855 (const :tag "Links to a directory" directory)
1856 (const :tag "Any files that have Emacs modes"
1857 auto-mode))
1858 (choice :value ""
1859 (const :tag "Visit with Emacs" emacs)
1860 (const :tag "Use default" default)
1861 (const :tag "Use the system command" system)
1862 (string :tag "Command")
1863 (sexp :tag "Lisp form")))))
1865 (defcustom org-doi-server-url "http://dx.doi.org/"
1866 "The URL of the DOI server."
1867 :type 'string
1868 :version "24.3"
1869 :group 'org-link-follow)
1871 (defgroup org-refile nil
1872 "Options concerning refiling entries in Org-mode."
1873 :tag "Org Refile"
1874 :group 'org)
1876 (defcustom org-directory "~/org"
1877 "Directory with org files.
1878 This is just a default location to look for Org files. There is no need
1879 at all to put your files into this directory. It is only used in the
1880 following situations:
1882 1. When a capture template specifies a target file that is not an
1883 absolute path. The path will then be interpreted relative to
1884 `org-directory'
1885 2. When a capture note is filed away in an interactive way (when exiting the
1886 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1887 with `org-directory' as the default path."
1888 :group 'org-refile
1889 :group 'org-remember
1890 :group 'org-capture
1891 :type 'directory)
1893 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1894 "Default target for storing notes.
1895 Used as a fall back file for org-remember.el and org-capture.el, for
1896 templates that do not specify a target file."
1897 :group 'org-refile
1898 :group 'org-remember
1899 :group 'org-capture
1900 :type '(choice
1901 (const :tag "Default from remember-data-file" nil)
1902 file))
1904 (defcustom org-goto-interface 'outline
1905 "The default interface to be used for `org-goto'.
1906 Allowed values are:
1907 outline The interface shows an outline of the relevant file
1908 and the correct heading is found by moving through
1909 the outline or by searching with incremental search.
1910 outline-path-completion Headlines in the current buffer are offered via
1911 completion. This is the interface also used by
1912 the refile command."
1913 :group 'org-refile
1914 :type '(choice
1915 (const :tag "Outline" outline)
1916 (const :tag "Outline-path-completion" outline-path-completion)))
1918 (defcustom org-goto-max-level 5
1919 "Maximum target level when running `org-goto' with refile interface."
1920 :group 'org-refile
1921 :type 'integer)
1923 (defcustom org-reverse-note-order nil
1924 "Non-nil means store new notes at the beginning of a file or entry.
1925 When nil, new notes will be filed to the end of a file or entry.
1926 This can also be a list with cons cells of regular expressions that
1927 are matched against file names, and values."
1928 :group 'org-remember
1929 :group 'org-capture
1930 :group 'org-refile
1931 :type '(choice
1932 (const :tag "Reverse always" t)
1933 (const :tag "Reverse never" nil)
1934 (repeat :tag "By file name regexp"
1935 (cons regexp boolean))))
1937 (defcustom org-log-refile nil
1938 "Information to record when a task is refiled.
1940 Possible values are:
1942 nil Don't add anything
1943 time Add a time stamp to the task
1944 note Prompt for a note and add it with template `org-log-note-headings'
1946 This option can also be set with on a per-file-basis with
1948 #+STARTUP: nologrefile
1949 #+STARTUP: logrefile
1950 #+STARTUP: lognoterefile
1952 You can have local logging settings for a subtree by setting the LOGGING
1953 property to one or more of these keywords.
1955 When bulk-refiling from the agenda, the value `note' is forbidden and
1956 will temporarily be changed to `time'."
1957 :group 'org-refile
1958 :group 'org-progress
1959 :version "24.1"
1960 :type '(choice
1961 (const :tag "No logging" nil)
1962 (const :tag "Record timestamp" time)
1963 (const :tag "Record timestamp with note." note)))
1965 (defcustom org-refile-targets nil
1966 "Targets for refiling entries with \\[org-refile].
1967 This is a list of cons cells. Each cell contains:
1968 - a specification of the files to be considered, either a list of files,
1969 or a symbol whose function or variable value will be used to retrieve
1970 a file name or a list of file names. If you use `org-agenda-files' for
1971 that, all agenda files will be scanned for targets. Nil means consider
1972 headings in the current buffer.
1973 - A specification of how to find candidate refile targets. This may be
1974 any of:
1975 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1976 This tag has to be present in all target headlines, inheritance will
1977 not be considered.
1978 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1979 todo keyword.
1980 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1981 headlines that are refiling targets.
1982 - a cons cell (:level . N). Any headline of level N is considered a target.
1983 Note that, when `org-odd-levels-only' is set, level corresponds to
1984 order in hierarchy, not to the number of stars.
1985 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1986 Note that, when `org-odd-levels-only' is set, level corresponds to
1987 order in hierarchy, not to the number of stars.
1989 Each element of this list generates a set of possible targets.
1990 The union of these sets is presented (with completion) to
1991 the user by `org-refile'.
1993 You can set the variable `org-refile-target-verify-function' to a function
1994 to verify each headline found by the simple criteria above.
1996 When this variable is nil, all top-level headlines in the current buffer
1997 are used, equivalent to the value `((nil . (:level . 1))'."
1998 :group 'org-refile
1999 :type '(repeat
2000 (cons
2001 (choice :value org-agenda-files
2002 (const :tag "All agenda files" org-agenda-files)
2003 (const :tag "Current buffer" nil)
2004 (function) (variable) (file))
2005 (choice :tag "Identify target headline by"
2006 (cons :tag "Specific tag" (const :value :tag) (string))
2007 (cons :tag "TODO keyword" (const :value :todo) (string))
2008 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2009 (cons :tag "Level number" (const :value :level) (integer))
2010 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2012 (defcustom org-refile-target-verify-function nil
2013 "Function to verify if the headline at point should be a refile target.
2014 The function will be called without arguments, with point at the
2015 beginning of the headline. It should return t and leave point
2016 where it is if the headline is a valid target for refiling.
2018 If the target should not be selected, the function must return nil.
2019 In addition to this, it may move point to a place from where the search
2020 should be continued. For example, the function may decide that the entire
2021 subtree of the current entry should be excluded and move point to the end
2022 of the subtree."
2023 :group 'org-refile
2024 :type 'function)
2026 (defcustom org-refile-use-cache nil
2027 "Non-nil means cache refile targets to speed up the process.
2028 The cache for a particular file will be updated automatically when
2029 the buffer has been killed, or when any of the marker used for flagging
2030 refile targets no longer points at a live buffer.
2031 If you have added new entries to a buffer that might themselves be targets,
2032 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2033 find that easier, `C-u C-u C-u C-c C-w'."
2034 :group 'org-refile
2035 :version "24.1"
2036 :type 'boolean)
2038 (defcustom org-refile-use-outline-path nil
2039 "Non-nil means provide refile targets as paths.
2040 So a level 3 headline will be available as level1/level2/level3.
2042 When the value is `file', also include the file name (without directory)
2043 into the path. In this case, you can also stop the completion after
2044 the file name, to get entries inserted as top level in the file.
2046 When `full-file-path', include the full file path."
2047 :group 'org-refile
2048 :type '(choice
2049 (const :tag "Not" nil)
2050 (const :tag "Yes" t)
2051 (const :tag "Start with file name" file)
2052 (const :tag "Start with full file path" full-file-path)))
2054 (defcustom org-outline-path-complete-in-steps t
2055 "Non-nil means complete the outline path in hierarchical steps.
2056 When Org-mode uses the refile interface to select an outline path
2057 \(see variable `org-refile-use-outline-path'), the completion of
2058 the path can be done is a single go, or if can be done in steps down
2059 the headline hierarchy. Going in steps is probably the best if you
2060 do not use a special completion package like `ido' or `icicles'.
2061 However, when using these packages, going in one step can be very
2062 fast, while still showing the whole path to the entry."
2063 :group 'org-refile
2064 :type 'boolean)
2066 (defcustom org-refile-allow-creating-parent-nodes nil
2067 "Non-nil means allow to create new nodes as refile targets.
2068 New nodes are then created by adding \"/new node name\" to the completion
2069 of an existing node. When the value of this variable is `confirm',
2070 new node creation must be confirmed by the user (recommended)
2071 When nil, the completion must match an existing entry.
2073 Note that, if the new heading is not seen by the criteria
2074 listed in `org-refile-targets', multiple instances of the same
2075 heading would be created by trying again to file under the new
2076 heading."
2077 :group 'org-refile
2078 :type '(choice
2079 (const :tag "Never" nil)
2080 (const :tag "Always" t)
2081 (const :tag "Prompt for confirmation" confirm)))
2083 (defcustom org-refile-active-region-within-subtree nil
2084 "Non-nil means also refile active region within a subtree.
2086 By default `org-refile' doesn't allow refiling regions if they
2087 don't contain a set of subtrees, but it might be convenient to
2088 do so sometimes: in that case, the first line of the region is
2089 converted to a headline before refiling."
2090 :group 'org-refile
2091 :version "24.1"
2092 :type 'boolean)
2094 (defgroup org-todo nil
2095 "Options concerning TODO items in Org-mode."
2096 :tag "Org TODO"
2097 :group 'org)
2099 (defgroup org-progress nil
2100 "Options concerning Progress logging in Org-mode."
2101 :tag "Org Progress"
2102 :group 'org-time)
2104 (defvar org-todo-interpretation-widgets
2105 '((:tag "Sequence (cycling hits every state)" sequence)
2106 (:tag "Type (cycling directly to DONE)" type))
2107 "The available interpretation symbols for customizing `org-todo-keywords'.
2108 Interested libraries should add to this list.")
2110 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2111 "List of TODO entry keyword sequences and their interpretation.
2112 \\<org-mode-map>This is a list of sequences.
2114 Each sequence starts with a symbol, either `sequence' or `type',
2115 indicating if the keywords should be interpreted as a sequence of
2116 action steps, or as different types of TODO items. The first
2117 keywords are states requiring action - these states will select a headline
2118 for inclusion into the global TODO list Org-mode produces. If one of
2119 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2120 signify that no further action is necessary. If \"|\" is not found,
2121 the last keyword is treated as the only DONE state of the sequence.
2123 The command \\[org-todo] cycles an entry through these states, and one
2124 additional state where no keyword is present. For details about this
2125 cycling, see the manual.
2127 TODO keywords and interpretation can also be set on a per-file basis with
2128 the special #+SEQ_TODO and #+TYP_TODO lines.
2130 Each keyword can optionally specify a character for fast state selection
2131 \(in combination with the variable `org-use-fast-todo-selection')
2132 and specifiers for state change logging, using the same syntax that
2133 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2134 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2135 indicates to record a time stamp each time this state is selected.
2137 Each keyword may also specify if a timestamp or a note should be
2138 recorded when entering or leaving the state, by adding additional
2139 characters in the parenthesis after the keyword. This looks like this:
2140 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2141 record only the time of the state change. With X and Y being either
2142 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2143 Y when leaving the state if and only if the *target* state does not
2144 define X. You may omit any of the fast-selection key or X or /Y,
2145 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2147 For backward compatibility, this variable may also be just a list
2148 of keywords. In this case the interpretation (sequence or type) will be
2149 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2150 :group 'org-todo
2151 :group 'org-keywords
2152 :type '(choice
2153 (repeat :tag "Old syntax, just keywords"
2154 (string :tag "Keyword"))
2155 (repeat :tag "New syntax"
2156 (cons
2157 (choice
2158 :tag "Interpretation"
2159 ;;Quick and dirty way to see
2160 ;;`org-todo-interpretations'. This takes the
2161 ;;place of item arguments
2162 :convert-widget
2163 (lambda (widget)
2164 (widget-put widget
2165 :args (mapcar
2166 #'(lambda (x)
2167 (widget-convert
2168 (cons 'const x)))
2169 org-todo-interpretation-widgets))
2170 widget))
2171 (repeat
2172 (string :tag "Keyword"))))))
2174 (defvar org-todo-keywords-1 nil
2175 "All TODO and DONE keywords active in a buffer.")
2176 (make-variable-buffer-local 'org-todo-keywords-1)
2177 (defvar org-todo-keywords-for-agenda nil)
2178 (defvar org-done-keywords-for-agenda nil)
2179 (defvar org-drawers-for-agenda nil)
2180 (defvar org-todo-keyword-alist-for-agenda nil)
2181 (defvar org-tag-alist-for-agenda nil)
2182 (defvar org-agenda-contributing-files nil)
2183 (defvar org-not-done-keywords nil)
2184 (make-variable-buffer-local 'org-not-done-keywords)
2185 (defvar org-done-keywords nil)
2186 (make-variable-buffer-local 'org-done-keywords)
2187 (defvar org-todo-heads nil)
2188 (make-variable-buffer-local 'org-todo-heads)
2189 (defvar org-todo-sets nil)
2190 (make-variable-buffer-local 'org-todo-sets)
2191 (defvar org-todo-log-states nil)
2192 (make-variable-buffer-local 'org-todo-log-states)
2193 (defvar org-todo-kwd-alist nil)
2194 (make-variable-buffer-local 'org-todo-kwd-alist)
2195 (defvar org-todo-key-alist nil)
2196 (make-variable-buffer-local 'org-todo-key-alist)
2197 (defvar org-todo-key-trigger nil)
2198 (make-variable-buffer-local 'org-todo-key-trigger)
2200 (defcustom org-todo-interpretation 'sequence
2201 "Controls how TODO keywords are interpreted.
2202 This variable is in principle obsolete and is only used for
2203 backward compatibility, if the interpretation of todo keywords is
2204 not given already in `org-todo-keywords'. See that variable for
2205 more information."
2206 :group 'org-todo
2207 :group 'org-keywords
2208 :type '(choice (const sequence)
2209 (const type)))
2211 (defcustom org-use-fast-todo-selection t
2212 "Non-nil means use the fast todo selection scheme with C-c C-t.
2213 This variable describes if and under what circumstances the cycling
2214 mechanism for TODO keywords will be replaced by a single-key, direct
2215 selection scheme.
2217 When nil, fast selection is never used.
2219 When the symbol `prefix', it will be used when `org-todo' is called
2220 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2221 `C-u t' in an agenda buffer.
2223 When t, fast selection is used by default. In this case, the prefix
2224 argument forces cycling instead.
2226 In all cases, the special interface is only used if access keys have
2227 actually been assigned by the user, i.e. if keywords in the configuration
2228 are followed by a letter in parenthesis, like TODO(t)."
2229 :group 'org-todo
2230 :type '(choice
2231 (const :tag "Never" nil)
2232 (const :tag "By default" t)
2233 (const :tag "Only with C-u C-c C-t" prefix)))
2235 (defcustom org-provide-todo-statistics t
2236 "Non-nil means update todo statistics after insert and toggle.
2237 ALL-HEADLINES means update todo statistics by including headlines
2238 with no TODO keyword as well, counting them as not done.
2239 A list of TODO keywords means the same, but skip keywords that are
2240 not in this list.
2242 When this is set, todo statistics is updated in the parent of the
2243 current entry each time a todo state is changed."
2244 :group 'org-todo
2245 :type '(choice
2246 (const :tag "Yes, only for TODO entries" t)
2247 (const :tag "Yes, including all entries" 'all-headlines)
2248 (repeat :tag "Yes, for TODOs in this list"
2249 (string :tag "TODO keyword"))
2250 (other :tag "No TODO statistics" nil)))
2252 (defcustom org-hierarchical-todo-statistics t
2253 "Non-nil means TODO statistics covers just direct children.
2254 When nil, all entries in the subtree are considered.
2255 This has only an effect if `org-provide-todo-statistics' is set.
2256 To set this to nil for only a single subtree, use a COOKIE_DATA
2257 property and include the word \"recursive\" into the value."
2258 :group 'org-todo
2259 :type 'boolean)
2261 (defcustom org-after-todo-state-change-hook nil
2262 "Hook which is run after the state of a TODO item was changed.
2263 The new state (a string with a TODO keyword, or nil) is available in the
2264 Lisp variable `org-state'."
2265 :group 'org-todo
2266 :type 'hook)
2268 (defvar org-blocker-hook nil
2269 "Hook for functions that are allowed to block a state change.
2271 Functions in this hook should not modify the buffer.
2272 Each function gets as its single argument a property list,
2273 see `org-trigger-hook' for more information about this list.
2275 If any of the functions in this hook returns nil, the state change
2276 is blocked.")
2278 (defvar org-trigger-hook nil
2279 "Hook for functions that are triggered by a state change.
2281 Each function gets as its single argument a property list with at
2282 least the following elements:
2284 (:type type-of-change :position pos-at-entry-start
2285 :from old-state :to new-state)
2287 Depending on the type, more properties may be present.
2289 This mechanism is currently implemented for:
2291 TODO state changes
2292 ------------------
2293 :type todo-state-change
2294 :from previous state (keyword as a string), or nil, or a symbol
2295 'todo' or 'done', to indicate the general type of state.
2296 :to new state, like in :from")
2298 (defcustom org-enforce-todo-dependencies nil
2299 "Non-nil means undone TODO entries will block switching the parent to DONE.
2300 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2301 be blocked if any prior sibling is not yet done.
2302 Finally, if the parent is blocked because of ordered siblings of its own,
2303 the child will also be blocked."
2304 :set (lambda (var val)
2305 (set var val)
2306 (if val
2307 (add-hook 'org-blocker-hook
2308 'org-block-todo-from-children-or-siblings-or-parent)
2309 (remove-hook 'org-blocker-hook
2310 'org-block-todo-from-children-or-siblings-or-parent)))
2311 :group 'org-todo
2312 :type 'boolean)
2314 (defcustom org-enforce-todo-checkbox-dependencies nil
2315 "Non-nil means unchecked boxes will block switching the parent to DONE.
2316 When this is nil, checkboxes have no influence on switching TODO states.
2317 When non-nil, you first need to check off all check boxes before the TODO
2318 entry can be switched to DONE.
2319 This variable needs to be set before org.el is loaded, and you need to
2320 restart Emacs after a change to make the change effective. The only way
2321 to change is while Emacs is running is through the customize interface."
2322 :set (lambda (var val)
2323 (set var val)
2324 (if val
2325 (add-hook 'org-blocker-hook
2326 'org-block-todo-from-checkboxes)
2327 (remove-hook 'org-blocker-hook
2328 'org-block-todo-from-checkboxes)))
2329 :group 'org-todo
2330 :type 'boolean)
2332 (defcustom org-treat-insert-todo-heading-as-state-change nil
2333 "Non-nil means inserting a TODO heading is treated as state change.
2334 So when the command \\[org-insert-todo-heading] is used, state change
2335 logging will apply if appropriate. When nil, the new TODO item will
2336 be inserted directly, and no logging will take place."
2337 :group 'org-todo
2338 :type 'boolean)
2340 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2341 "Non-nil means switching TODO states with S-cursor counts as state change.
2342 This is the default behavior. However, setting this to nil allows a
2343 convenient way to select a TODO state and bypass any logging associated
2344 with that."
2345 :group 'org-todo
2346 :type 'boolean)
2348 (defcustom org-todo-state-tags-triggers nil
2349 "Tag changes that should be triggered by TODO state changes.
2350 This is a list. Each entry is
2352 (state-change (tag . flag) .......)
2354 State-change can be a string with a state, and empty string to indicate the
2355 state that has no TODO keyword, or it can be one of the symbols `todo'
2356 or `done', meaning any not-done or done state, respectively."
2357 :group 'org-todo
2358 :group 'org-tags
2359 :type '(repeat
2360 (cons (choice :tag "When changing to"
2361 (const :tag "Not-done state" todo)
2362 (const :tag "Done state" done)
2363 (string :tag "State"))
2364 (repeat
2365 (cons :tag "Tag action"
2366 (string :tag "Tag")
2367 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2369 (defcustom org-log-done nil
2370 "Information to record when a task moves to the DONE state.
2372 Possible values are:
2374 nil Don't add anything, just change the keyword
2375 time Add a time stamp to the task
2376 note Prompt for a note and add it with template `org-log-note-headings'
2378 This option can also be set with on a per-file-basis with
2380 #+STARTUP: nologdone
2381 #+STARTUP: logdone
2382 #+STARTUP: lognotedone
2384 You can have local logging settings for a subtree by setting the LOGGING
2385 property to one or more of these keywords."
2386 :group 'org-todo
2387 :group 'org-progress
2388 :type '(choice
2389 (const :tag "No logging" nil)
2390 (const :tag "Record CLOSED timestamp" time)
2391 (const :tag "Record CLOSED timestamp with note." note)))
2393 ;; Normalize old uses of org-log-done.
2394 (cond
2395 ((eq org-log-done t) (setq org-log-done 'time))
2396 ((and (listp org-log-done) (memq 'done org-log-done))
2397 (setq org-log-done 'note)))
2399 (defcustom org-log-reschedule nil
2400 "Information to record when the scheduling date of a tasks is modified.
2402 Possible values are:
2404 nil Don't add anything, just change the date
2405 time Add a time stamp to the task
2406 note Prompt for a note and add it with template `org-log-note-headings'
2408 This option can also be set with on a per-file-basis with
2410 #+STARTUP: nologreschedule
2411 #+STARTUP: logreschedule
2412 #+STARTUP: lognotereschedule"
2413 :group 'org-todo
2414 :group 'org-progress
2415 :type '(choice
2416 (const :tag "No logging" nil)
2417 (const :tag "Record timestamp" time)
2418 (const :tag "Record timestamp with note." note)))
2420 (defcustom org-log-redeadline nil
2421 "Information to record when the deadline date of a tasks is modified.
2423 Possible values are:
2425 nil Don't add anything, just change the date
2426 time Add a time stamp to the task
2427 note Prompt for a note and add it with template `org-log-note-headings'
2429 This option can also be set with on a per-file-basis with
2431 #+STARTUP: nologredeadline
2432 #+STARTUP: logredeadline
2433 #+STARTUP: lognoteredeadline
2435 You can have local logging settings for a subtree by setting the LOGGING
2436 property to one or more of these keywords."
2437 :group 'org-todo
2438 :group 'org-progress
2439 :type '(choice
2440 (const :tag "No logging" nil)
2441 (const :tag "Record timestamp" time)
2442 (const :tag "Record timestamp with note." note)))
2444 (defcustom org-log-note-clock-out nil
2445 "Non-nil means record a note when clocking out of an item.
2446 This can also be configured on a per-file basis by adding one of
2447 the following lines anywhere in the buffer:
2449 #+STARTUP: lognoteclock-out
2450 #+STARTUP: nolognoteclock-out"
2451 :group 'org-todo
2452 :group 'org-progress
2453 :type 'boolean)
2455 (defcustom org-log-done-with-time t
2456 "Non-nil means the CLOSED time stamp will contain date and time.
2457 When nil, only the date will be recorded."
2458 :group 'org-progress
2459 :type 'boolean)
2461 (defcustom org-log-note-headings
2462 '((done . "CLOSING NOTE %t")
2463 (state . "State %-12s from %-12S %t")
2464 (note . "Note taken on %t")
2465 (reschedule . "Rescheduled from %S on %t")
2466 (delschedule . "Not scheduled, was %S on %t")
2467 (redeadline . "New deadline from %S on %t")
2468 (deldeadline . "Removed deadline, was %S on %t")
2469 (refile . "Refiled on %t")
2470 (clock-out . ""))
2471 "Headings for notes added to entries.
2472 The value is an alist, with the car being a symbol indicating the note
2473 context, and the cdr is the heading to be used. The heading may also be the
2474 empty string.
2475 %t in the heading will be replaced by a time stamp.
2476 %T will be an active time stamp instead the default inactive one
2477 %d will be replaced by a short-format time stamp.
2478 %D will be replaced by an active short-format time stamp.
2479 %s will be replaced by the new TODO state, in double quotes.
2480 %S will be replaced by the old TODO state, in double quotes.
2481 %u will be replaced by the user name.
2482 %U will be replaced by the full user name.
2484 In fact, it is not a good idea to change the `state' entry, because
2485 agenda log mode depends on the format of these entries."
2486 :group 'org-todo
2487 :group 'org-progress
2488 :type '(list :greedy t
2489 (cons (const :tag "Heading when closing an item" done) string)
2490 (cons (const :tag
2491 "Heading when changing todo state (todo sequence only)"
2492 state) string)
2493 (cons (const :tag "Heading when just taking a note" note) string)
2494 (cons (const :tag "Heading when clocking out" clock-out) string)
2495 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2496 (cons (const :tag "Heading when rescheduling" reschedule) string)
2497 (cons (const :tag "Heading when changing deadline" redeadline) string)
2498 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2499 (cons (const :tag "Heading when refiling" refile) string)))
2501 (unless (assq 'note org-log-note-headings)
2502 (push '(note . "%t") org-log-note-headings))
2504 (defcustom org-log-into-drawer nil
2505 "Non-nil means insert state change notes and time stamps into a drawer.
2506 When nil, state changes notes will be inserted after the headline and
2507 any scheduling and clock lines, but not inside a drawer.
2509 The value of this variable should be the name of the drawer to use.
2510 LOGBOOK is proposed as the default drawer for this purpose, you can
2511 also set this to a string to define the drawer of your choice.
2513 A value of t is also allowed, representing \"LOGBOOK\".
2515 A value of t or nil can also be set with on a per-file-basis with
2517 #+STARTUP: logdrawer
2518 #+STARTUP: nologdrawer
2520 If this variable is set, `org-log-state-notes-insert-after-drawers'
2521 will be ignored.
2523 You can set the property LOG_INTO_DRAWER to overrule this setting for
2524 a subtree."
2525 :group 'org-todo
2526 :group 'org-progress
2527 :type '(choice
2528 (const :tag "Not into a drawer" nil)
2529 (const :tag "LOGBOOK" t)
2530 (string :tag "Other")))
2532 (if (fboundp 'defvaralias)
2533 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2535 (defun org-log-into-drawer ()
2536 "Return the value of `org-log-into-drawer', but let properties overrule.
2537 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2538 used instead of the default value."
2539 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2540 (cond
2541 ((not p) org-log-into-drawer)
2542 ((equal p "nil") nil)
2543 ((equal p "t") "LOGBOOK")
2544 (t p))))
2546 (defcustom org-log-state-notes-insert-after-drawers nil
2547 "Non-nil means insert state change notes after any drawers in entry.
2548 Only the drawers that *immediately* follow the headline and the
2549 deadline/scheduled line are skipped.
2550 When nil, insert notes right after the heading and perhaps the line
2551 with deadline/scheduling if present.
2553 This variable will have no effect if `org-log-into-drawer' is
2554 set."
2555 :group 'org-todo
2556 :group 'org-progress
2557 :type 'boolean)
2559 (defcustom org-log-states-order-reversed t
2560 "Non-nil means the latest state note will be directly after heading.
2561 When nil, the state change notes will be ordered according to time.
2563 This option can also be set with on a per-file-basis with
2565 #+STARTUP: logstatesreversed
2566 #+STARTUP: nologstatesreversed"
2567 :group 'org-todo
2568 :group 'org-progress
2569 :type 'boolean)
2571 (defcustom org-todo-repeat-to-state nil
2572 "The TODO state to which a repeater should return the repeating task.
2573 By default this is the first task in a TODO sequence, or the previous state
2574 in a TODO_TYP set. But you can specify another task here.
2575 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2576 :group 'org-todo
2577 :version "24.1"
2578 :type '(choice (const :tag "Head of sequence" nil)
2579 (string :tag "Specific state")))
2581 (defcustom org-log-repeat 'time
2582 "Non-nil means record moving through the DONE state when triggering repeat.
2583 An auto-repeating task is immediately switched back to TODO when
2584 marked DONE. If you are not logging state changes (by adding \"@\"
2585 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2586 record a closing note, there will be no record of the task moving
2587 through DONE. This variable forces taking a note anyway.
2589 nil Don't force a record
2590 time Record a time stamp
2591 note Prompt for a note and add it with template `org-log-note-headings'
2593 This option can also be set with on a per-file-basis with
2595 #+STARTUP: nologrepeat
2596 #+STARTUP: logrepeat
2597 #+STARTUP: lognoterepeat
2599 You can have local logging settings for a subtree by setting the LOGGING
2600 property to one or more of these keywords."
2601 :group 'org-todo
2602 :group 'org-progress
2603 :type '(choice
2604 (const :tag "Don't force a record" nil)
2605 (const :tag "Force recording the DONE state" time)
2606 (const :tag "Force recording a note with the DONE state" note)))
2609 (defgroup org-priorities nil
2610 "Priorities in Org-mode."
2611 :tag "Org Priorities"
2612 :group 'org-todo)
2614 (defcustom org-enable-priority-commands t
2615 "Non-nil means priority commands are active.
2616 When nil, these commands will be disabled, so that you never accidentally
2617 set a priority."
2618 :group 'org-priorities
2619 :type 'boolean)
2621 (defcustom org-highest-priority ?A
2622 "The highest priority of TODO items. A character like ?A, ?B etc.
2623 Must have a smaller ASCII number than `org-lowest-priority'."
2624 :group 'org-priorities
2625 :type 'character)
2627 (defcustom org-lowest-priority ?C
2628 "The lowest priority of TODO items. A character like ?A, ?B etc.
2629 Must have a larger ASCII number than `org-highest-priority'."
2630 :group 'org-priorities
2631 :type 'character)
2633 (defcustom org-default-priority ?B
2634 "The default priority of TODO items.
2635 This is the priority an item gets if no explicit priority is given.
2636 When starting to cycle on an empty priority the first step in the cycle
2637 depends on `org-priority-start-cycle-with-default'. The resulting first
2638 step priority must not exceed the range from `org-highest-priority' to
2639 `org-lowest-priority' which means that `org-default-priority' has to be
2640 in this range exclusive or inclusive the range boundaries. Else the
2641 first step refuses to set the default and the second will fall back
2642 to (depending on the command used) the highest or lowest priority."
2643 :group 'org-priorities
2644 :type 'character)
2646 (defcustom org-priority-start-cycle-with-default t
2647 "Non-nil means start with default priority when starting to cycle.
2648 When this is nil, the first step in the cycle will be (depending on the
2649 command used) one higher or lower than the default priority.
2650 See also `org-default-priority'."
2651 :group 'org-priorities
2652 :type 'boolean)
2654 (defcustom org-get-priority-function nil
2655 "Function to extract the priority from a string.
2656 The string is normally the headline. If this is nil Org computes the
2657 priority from the priority cookie like [#A] in the headline. It returns
2658 an integer, increasing by 1000 for each priority level.
2659 The user can set a different function here, which should take a string
2660 as an argument and return the numeric priority."
2661 :group 'org-priorities
2662 :version "24.1"
2663 :type 'function)
2665 (defgroup org-time nil
2666 "Options concerning time stamps and deadlines in Org-mode."
2667 :tag "Org Time"
2668 :group 'org)
2670 (defcustom org-insert-labeled-timestamps-at-point nil
2671 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2672 When nil, these labeled time stamps are forces into the second line of an
2673 entry, just after the headline. When scheduling from the global TODO list,
2674 the time stamp will always be forced into the second line."
2675 :group 'org-time
2676 :type 'boolean)
2678 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2679 "Formats for `format-time-string' which are used for time stamps.
2680 It is not recommended to change this constant.")
2682 (defcustom org-time-stamp-rounding-minutes '(0 5)
2683 "Number of minutes to round time stamps to.
2684 These are two values, the first applies when first creating a time stamp.
2685 The second applies when changing it with the commands `S-up' and `S-down'.
2686 When changing the time stamp, this means that it will change in steps
2687 of N minutes, as given by the second value.
2689 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2690 numbers should be factors of 60, so for example 5, 10, 15.
2692 When this is larger than 1, you can still force an exact time stamp by using
2693 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2694 and by using a prefix arg to `S-up/down' to specify the exact number
2695 of minutes to shift."
2696 :group 'org-time
2697 :get #'(lambda (var) ; Make sure both elements are there
2698 (if (integerp (default-value var))
2699 (list (default-value var) 5)
2700 (default-value var)))
2701 :type '(list
2702 (integer :tag "when inserting times")
2703 (integer :tag "when modifying times")))
2705 ;; Normalize old customizations of this variable.
2706 (when (integerp org-time-stamp-rounding-minutes)
2707 (setq org-time-stamp-rounding-minutes
2708 (list org-time-stamp-rounding-minutes
2709 org-time-stamp-rounding-minutes)))
2711 (defcustom org-display-custom-times nil
2712 "Non-nil means overlay custom formats over all time stamps.
2713 The formats are defined through the variable `org-time-stamp-custom-formats'.
2714 To turn this on on a per-file basis, insert anywhere in the file:
2715 #+STARTUP: customtime"
2716 :group 'org-time
2717 :set 'set-default
2718 :type 'sexp)
2719 (make-variable-buffer-local 'org-display-custom-times)
2721 (defcustom org-time-stamp-custom-formats
2722 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2723 "Custom formats for time stamps. See `format-time-string' for the syntax.
2724 These are overlaid over the default ISO format if the variable
2725 `org-display-custom-times' is set. Time like %H:%M should be at the
2726 end of the second format. The custom formats are also honored by export
2727 commands, if custom time display is turned on at the time of export."
2728 :group 'org-time
2729 :type 'sexp)
2731 (defun org-time-stamp-format (&optional long inactive)
2732 "Get the right format for a time string."
2733 (let ((f (if long (cdr org-time-stamp-formats)
2734 (car org-time-stamp-formats))))
2735 (if inactive
2736 (concat "[" (substring f 1 -1) "]")
2737 f)))
2739 (defcustom org-time-clocksum-format
2740 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2741 "The format string used when creating CLOCKSUM lines.
2742 This is also used when Org mode generates a time duration.
2744 The value can be a single format string containing two
2745 %-sequences, which will be filled with the number of hours and
2746 minutes in that order.
2748 Alternatively, the value can be a plist associating any of the
2749 keys :years, :months, :weeks, :days, :hours or :minutes with
2750 format strings. The time duration is formatted using only the
2751 time components that are needed and concatenating the results.
2752 If a time unit in absent, it falls back to the next smallest
2753 unit.
2755 The keys :require-years, :require-months, :require-days,
2756 :require-weeks, :require-hours, :require-minutes are also
2757 meaningful. A non-nil value for these keys indicates that the
2758 corresponding time component should always be included, even if
2759 its value is 0.
2762 For example,
2764 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2765 :require-minutes t)
2767 means durations longer than a day will be expressed in days,
2768 hours and minutes, and durations less than a day will always be
2769 expressed in hours and minutes (even for durations less than an
2770 hour).
2772 The value
2774 \(:days \"%dd\" :minutes \"%dm\")
2776 means durations longer than a day will be expressed in days and
2777 minutes, and durations less than a day will be expressed entirely
2778 in minutes (even for durations longer than an hour)."
2779 :group 'org-time
2780 :group 'org-clock
2781 :version "24.3"
2782 :type '(choice (string :tag "Format string")
2783 (set :tag "Plist"
2784 (group :inline t (const :tag "Years" :years)
2785 (string :tag "Format string"))
2786 (group :inline t
2787 (const :tag "Always show years" :require-years)
2788 (const t))
2789 (group :inline t (const :tag "Months" :months)
2790 (string :tag "Format string"))
2791 (group :inline t
2792 (const :tag "Always show months" :require-months)
2793 (const t))
2794 (group :inline t (const :tag "Weeks" :weeks)
2795 (string :tag "Format string"))
2796 (group :inline t
2797 (const :tag "Always show weeks" :require-weeks)
2798 (const t))
2799 (group :inline t (const :tag "Days" :days)
2800 (string :tag "Format string"))
2801 (group :inline t
2802 (const :tag "Always show days" :require-days)
2803 (const t))
2804 (group :inline t (const :tag "Hours" :hours)
2805 (string :tag "Format string"))
2806 (group :inline t
2807 (const :tag "Always show hours" :require-hours)
2808 (const t))
2809 (group :inline t (const :tag "Minutes" :minutes)
2810 (string :tag "Format string"))
2811 (group :inline t
2812 (const :tag "Always show minutes" :require-minutes)
2813 (const t)))))
2815 (defcustom org-time-clocksum-use-fractional nil
2816 "When non-nil, \\[org-clock-display] uses fractional times.
2817 See `org-time-clocksum-format' for more on time clock formats."
2818 :group 'org-time
2819 :group 'org-clock
2820 :version "24.3"
2821 :type 'boolean)
2823 (defcustom org-time-clocksum-use-effort-durations t
2824 "When non-nil, \\[org-clock-display] uses effort durations.
2825 E.g. by default, one day is considered to be a 8 hours effort,
2826 so a task that has been clocked for 16 hours will be displayed
2827 as during 2 days in the clock display or in the clocktable.
2829 See `org-effort-durations' on how to set effort durations
2830 and `org-time-clocksum-format' for more on time clock formats."
2831 :group 'org-time
2832 :group 'org-clock
2833 :version "24.3"
2834 :type 'boolean)
2836 (defcustom org-time-clocksum-fractional-format "%.2f"
2837 "The format string used when creating CLOCKSUM lines,
2838 or when Org mode generates a time duration, if
2839 `org-time-clocksum-use-fractional' is enabled.
2841 The value can be a single format string containing one
2842 %-sequence, which will be filled with the number of hours as
2843 a float.
2845 Alternatively, the value can be a plist associating any of the
2846 keys :years, :months, :weeks, :days, :hours or :minutes with
2847 a format string. The time duration is formatted using the
2848 largest time unit which gives a non-zero integer part. If all
2849 specified formats have zero integer part, the smallest time unit
2850 is used."
2851 :group 'org-time
2852 :type '(choice (string :tag "Format string")
2853 (set (group :inline t (const :tag "Years" :years)
2854 (string :tag "Format string"))
2855 (group :inline t (const :tag "Months" :months)
2856 (string :tag "Format string"))
2857 (group :inline t (const :tag "Weeks" :weeks)
2858 (string :tag "Format string"))
2859 (group :inline t (const :tag "Days" :days)
2860 (string :tag "Format string"))
2861 (group :inline t (const :tag "Hours" :hours)
2862 (string :tag "Format string"))
2863 (group :inline t (const :tag "Minutes" :minutes)
2864 (string :tag "Format string")))))
2866 (defcustom org-deadline-warning-days 14
2867 "No. of days before expiration during which a deadline becomes active.
2868 This variable governs the display in sparse trees and in the agenda.
2869 When 0 or negative, it means use this number (the absolute value of it)
2870 even if a deadline has a different individual lead time specified.
2872 Custom commands can set this variable in the options section."
2873 :group 'org-time
2874 :group 'org-agenda-daily/weekly
2875 :type 'integer)
2877 (defcustom org-read-date-prefer-future t
2878 "Non-nil means assume future for incomplete date input from user.
2879 This affects the following situations:
2880 1. The user gives a month but not a year.
2881 For example, if it is April and you enter \"feb 2\", this will be read
2882 as Feb 2, *next* year. \"May 5\", however, will be this year.
2883 2. The user gives a day, but no month.
2884 For example, if today is the 15th, and you enter \"3\", Org-mode will
2885 read this as the third of *next* month. However, if you enter \"17\",
2886 it will be considered as *this* month.
2888 If you set this variable to the symbol `time', then also the following
2889 will work:
2891 3. If the user gives a time.
2892 If the time is before now, it will be interpreted as tomorrow.
2894 Currently none of this works for ISO week specifications.
2896 When this option is nil, the current day, month and year will always be
2897 used as defaults.
2899 See also `org-agenda-jump-prefer-future'."
2900 :group 'org-time
2901 :type '(choice
2902 (const :tag "Never" nil)
2903 (const :tag "Check month and day" t)
2904 (const :tag "Check month, day, and time" time)))
2906 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2907 "Should the agenda jump command prefer the future for incomplete dates?
2908 The default is to do the same as configured in `org-read-date-prefer-future'.
2909 But you can also set a deviating value here.
2910 This may t or nil, or the symbol `org-read-date-prefer-future'."
2911 :group 'org-agenda
2912 :group 'org-time
2913 :version "24.1"
2914 :type '(choice
2915 (const :tag "Use org-read-date-prefer-future"
2916 org-read-date-prefer-future)
2917 (const :tag "Never" nil)
2918 (const :tag "Always" t)))
2920 (defcustom org-read-date-force-compatible-dates t
2921 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2923 Depending on the system Emacs is running on, certain dates cannot
2924 be represented with the type used internally to represent time.
2925 Dates between 1970-1-1 and 2038-1-1 can always be represented
2926 correctly. Some systems allow for earlier dates, some for later,
2927 some for both. One way to find out it to insert any date into an
2928 Org buffer, putting the cursor on the year and hitting S-up and
2929 S-down to test the range.
2931 When this variable is set to t, the date/time prompt will not let
2932 you specify dates outside the 1970-2037 range, so it is certain that
2933 these dates will work in whatever version of Emacs you are
2934 running, and also that you can move a file from one Emacs implementation
2935 to another. WHenever Org is forcing the year for you, it will display
2936 a message and beep.
2938 When this variable is nil, Org will check if the date is
2939 representable in the specific Emacs implementation you are using.
2940 If not, it will force a year, usually the current year, and beep
2941 to remind you. Currently this setting is not recommended because
2942 the likelihood that you will open your Org files in an Emacs that
2943 has limited date range is not negligible.
2945 A workaround for this problem is to use diary sexp dates for time
2946 stamps outside of this range."
2947 :group 'org-time
2948 :version "24.1"
2949 :type 'boolean)
2951 (defcustom org-read-date-display-live t
2952 "Non-nil means display current interpretation of date prompt live.
2953 This display will be in an overlay, in the minibuffer."
2954 :group 'org-time
2955 :type 'boolean)
2957 (defcustom org-read-date-popup-calendar t
2958 "Non-nil means pop up a calendar when prompting for a date.
2959 In the calendar, the date can be selected with mouse-1. However, the
2960 minibuffer will also be active, and you can simply enter the date as well.
2961 When nil, only the minibuffer will be available."
2962 :group 'org-time
2963 :type 'boolean)
2964 (if (fboundp 'defvaralias)
2965 (defvaralias 'org-popup-calendar-for-date-prompt
2966 'org-read-date-popup-calendar))
2968 (make-obsolete-variable
2969 'org-read-date-minibuffer-setup-hook
2970 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
2971 (defcustom org-read-date-minibuffer-setup-hook nil
2972 "Hook to be used to set up keys for the date/time interface.
2973 Add key definitions to `minibuffer-local-map', which will be a
2974 temporary copy.
2976 WARNING: This option is obsolete, you should use
2977 `org-read-date-minibuffer-local-map' to set up keys."
2978 :group 'org-time
2979 :type 'hook)
2981 (defcustom org-extend-today-until 0
2982 "The hour when your day really ends. Must be an integer.
2983 This has influence for the following applications:
2984 - When switching the agenda to \"today\". It it is still earlier than
2985 the time given here, the day recognized as TODAY is actually yesterday.
2986 - When a date is read from the user and it is still before the time given
2987 here, the current date and time will be assumed to be yesterday, 23:59.
2988 Also, timestamps inserted in capture templates follow this rule.
2990 IMPORTANT: This is a feature whose implementation is and likely will
2991 remain incomplete. Really, it is only here because past midnight seems to
2992 be the favorite working time of John Wiegley :-)"
2993 :group 'org-time
2994 :type 'integer)
2996 (defcustom org-use-effective-time nil
2997 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2998 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2999 \"effective time\" of any timestamps between midnight and 8am will be
3000 23:59 of the previous day."
3001 :group 'org-time
3002 :version "24.1"
3003 :type 'boolean)
3005 (defcustom org-use-last-clock-out-time-as-effective-time nil
3006 "When non-nil, use the last clock out time for `org-todo'.
3007 Note that this option has precedence over the combined use of
3008 `org-use-effective-time' and `org-extend-today-until'."
3009 :group 'org-time
3010 ;; :version "24.3"
3011 :type 'boolean)
3013 (defcustom org-edit-timestamp-down-means-later nil
3014 "Non-nil means S-down will increase the time in a time stamp.
3015 When nil, S-up will increase."
3016 :group 'org-time
3017 :type 'boolean)
3019 (defcustom org-calendar-follow-timestamp-change t
3020 "Non-nil means make the calendar window follow timestamp changes.
3021 When a timestamp is modified and the calendar window is visible, it will be
3022 moved to the new date."
3023 :group 'org-time
3024 :type 'boolean)
3026 (defgroup org-tags nil
3027 "Options concerning tags in Org-mode."
3028 :tag "Org Tags"
3029 :group 'org)
3031 (defcustom org-tag-alist nil
3032 "List of tags allowed in Org-mode files.
3033 When this list is nil, Org-mode will base TAG input on what is already in the
3034 buffer.
3035 The value of this variable is an alist, the car of each entry must be a
3036 keyword as a string, the cdr may be a character that is used to select
3037 that tag through the fast-tag-selection interface.
3038 See the manual for details."
3039 :group 'org-tags
3040 :type '(repeat
3041 (choice
3042 (cons (string :tag "Tag name")
3043 (character :tag "Access char"))
3044 (list :tag "Start radio group"
3045 (const :startgroup)
3046 (option (string :tag "Group description")))
3047 (list :tag "End radio group"
3048 (const :endgroup)
3049 (option (string :tag "Group description")))
3050 (const :tag "New line" (:newline)))))
3052 (defcustom org-tag-persistent-alist nil
3053 "List of tags that will always appear in all Org-mode files.
3054 This is in addition to any in buffer settings or customizations
3055 of `org-tag-alist'.
3056 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3057 The value of this variable is an alist, the car of each entry must be a
3058 keyword as a string, the cdr may be a character that is used to select
3059 that tag through the fast-tag-selection interface.
3060 See the manual for details.
3061 To disable these tags on a per-file basis, insert anywhere in the file:
3062 #+STARTUP: noptag"
3063 :group 'org-tags
3064 :type '(repeat
3065 (choice
3066 (cons (string :tag "Tag name")
3067 (character :tag "Access char"))
3068 (const :tag "Start radio group" (:startgroup))
3069 (const :tag "End radio group" (:endgroup))
3070 (const :tag "New line" (:newline)))))
3072 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3073 "If non-nil, always offer completion for all tags of all agenda files.
3074 Instead of customizing this variable directly, you might want to
3075 set it locally for capture buffers, because there no list of
3076 tags in that file can be created dynamically (there are none).
3078 (add-hook 'org-capture-mode-hook
3079 (lambda ()
3080 (set (make-local-variable
3081 'org-complete-tags-always-offer-all-agenda-tags)
3082 t)))"
3083 :group 'org-tags
3084 :version "24.1"
3085 :type 'boolean)
3087 (defvar org-file-tags nil
3088 "List of tags that can be inherited by all entries in the file.
3089 The tags will be inherited if the variable `org-use-tag-inheritance'
3090 says they should be.
3091 This variable is populated from #+FILETAGS lines.")
3093 (defcustom org-use-fast-tag-selection 'auto
3094 "Non-nil means use fast tag selection scheme.
3095 This is a special interface to select and deselect tags with single keys.
3096 When nil, fast selection is never used.
3097 When the symbol `auto', fast selection is used if and only if selection
3098 characters for tags have been configured, either through the variable
3099 `org-tag-alist' or through a #+TAGS line in the buffer.
3100 When t, fast selection is always used and selection keys are assigned
3101 automatically if necessary."
3102 :group 'org-tags
3103 :type '(choice
3104 (const :tag "Always" t)
3105 (const :tag "Never" nil)
3106 (const :tag "When selection characters are configured" 'auto)))
3108 (defcustom org-fast-tag-selection-single-key nil
3109 "Non-nil means fast tag selection exits after first change.
3110 When nil, you have to press RET to exit it.
3111 During fast tag selection, you can toggle this flag with `C-c'.
3112 This variable can also have the value `expert'. In this case, the window
3113 displaying the tags menu is not even shown, until you press C-c again."
3114 :group 'org-tags
3115 :type '(choice
3116 (const :tag "No" nil)
3117 (const :tag "Yes" t)
3118 (const :tag "Expert" expert)))
3120 (defvar org-fast-tag-selection-include-todo nil
3121 "Non-nil means fast tags selection interface will also offer TODO states.
3122 This is an undocumented feature, you should not rely on it.")
3124 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3125 "The column to which tags should be indented in a headline.
3126 If this number is positive, it specifies the column. If it is negative,
3127 it means that the tags should be flushright to that column. For example,
3128 -80 works well for a normal 80 character screen.
3129 When 0, place tags directly after headline text, with only one space in
3130 between."
3131 :group 'org-tags
3132 :type 'integer)
3134 (defcustom org-auto-align-tags t
3135 "Non-nil keeps tags aligned when modifying headlines.
3136 Some operations (i.e. demoting) change the length of a headline and
3137 therefore shift the tags around. With this option turned on, after
3138 each such operation the tags are again aligned to `org-tags-column'."
3139 :group 'org-tags
3140 :type 'boolean)
3142 (defcustom org-use-tag-inheritance t
3143 "Non-nil means tags in levels apply also for sublevels.
3144 When nil, only the tags directly given in a specific line apply there.
3145 This may also be a list of tags that should be inherited, or a regexp that
3146 matches tags that should be inherited. Additional control is possible
3147 with the variable `org-tags-exclude-from-inheritance' which gives an
3148 explicit list of tags to be excluded from inheritance, even if the value of
3149 `org-use-tag-inheritance' would select it for inheritance.
3151 If this option is t, a match early-on in a tree can lead to a large
3152 number of matches in the subtree when constructing the agenda or creating
3153 a sparse tree. If you only want to see the first match in a tree during
3154 a search, check out the variable `org-tags-match-list-sublevels'."
3155 :group 'org-tags
3156 :type '(choice
3157 (const :tag "Not" nil)
3158 (const :tag "Always" t)
3159 (repeat :tag "Specific tags" (string :tag "Tag"))
3160 (regexp :tag "Tags matched by regexp")))
3162 (defcustom org-tags-exclude-from-inheritance nil
3163 "List of tags that should never be inherited.
3164 This is a way to exclude a few tags from inheritance. For way to do
3165 the opposite, to actively allow inheritance for selected tags,
3166 see the variable `org-use-tag-inheritance'."
3167 :group 'org-tags
3168 :type '(repeat (string :tag "Tag")))
3170 (defun org-tag-inherit-p (tag)
3171 "Check if TAG is one that should be inherited."
3172 (cond
3173 ((member tag org-tags-exclude-from-inheritance) nil)
3174 ((eq org-use-tag-inheritance t) t)
3175 ((not org-use-tag-inheritance) nil)
3176 ((stringp org-use-tag-inheritance)
3177 (string-match org-use-tag-inheritance tag))
3178 ((listp org-use-tag-inheritance)
3179 (member tag org-use-tag-inheritance))
3180 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3182 (defcustom org-tags-match-list-sublevels t
3183 "Non-nil means list also sublevels of headlines matching a search.
3184 This variable applies to tags/property searches, and also to stuck
3185 projects because this search is based on a tags match as well.
3187 When set to the symbol `indented', sublevels are indented with
3188 leading dots.
3190 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3191 the sublevels of a headline matching a tag search often also match
3192 the same search. Listing all of them can create very long lists.
3193 Setting this variable to nil causes subtrees of a match to be skipped.
3195 This variable is semi-obsolete and probably should always be true. It
3196 is better to limit inheritance to certain tags using the variables
3197 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3198 :group 'org-tags
3199 :type '(choice
3200 (const :tag "No, don't list them" nil)
3201 (const :tag "Yes, do list them" t)
3202 (const :tag "List them, indented with leading dots" indented)))
3204 (defcustom org-tags-sort-function nil
3205 "When set, tags are sorted using this function as a comparator."
3206 :group 'org-tags
3207 :type '(choice
3208 (const :tag "No sorting" nil)
3209 (const :tag "Alphabetical" string<)
3210 (const :tag "Reverse alphabetical" string>)
3211 (function :tag "Custom function" nil)))
3213 (defvar org-tags-history nil
3214 "History of minibuffer reads for tags.")
3215 (defvar org-last-tags-completion-table nil
3216 "The last used completion table for tags.")
3217 (defvar org-after-tags-change-hook nil
3218 "Hook that is run after the tags in a line have changed.")
3220 (defgroup org-properties nil
3221 "Options concerning properties in Org-mode."
3222 :tag "Org Properties"
3223 :group 'org)
3225 (defcustom org-property-format "%-10s %s"
3226 "How property key/value pairs should be formatted by `indent-line'.
3227 When `indent-line' hits a property definition, it will format the line
3228 according to this format, mainly to make sure that the values are
3229 lined-up with respect to each other."
3230 :group 'org-properties
3231 :type 'string)
3233 (defcustom org-properties-postprocess-alist nil
3234 "Alist of properties and functions to adjust inserted values.
3235 Elements of this alist must be of the form
3237 ([string] [function])
3239 where [string] must be a property name and [function] must be a
3240 lambda expression: this lambda expression must take one argument,
3241 the value to adjust, and return the new value as a string.
3243 For example, this element will allow the property \"Remaining\"
3244 to be updated wrt the relation between the \"Effort\" property
3245 and the clock summary:
3247 ((\"Remaining\" (lambda(value)
3248 (let ((clocksum (org-clock-sum-current-item))
3249 (effort (org-duration-string-to-minutes
3250 (org-entry-get (point) \"Effort\"))))
3251 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3252 :group 'org-properties
3253 :version "24.1"
3254 :type '(alist :key-type (string :tag "Property")
3255 :value-type (function :tag "Function")))
3257 (defcustom org-use-property-inheritance nil
3258 "Non-nil means properties apply also for sublevels.
3260 This setting is chiefly used during property searches. Turning it on can
3261 cause significant overhead when doing a search, which is why it is not
3262 on by default.
3264 When nil, only the properties directly given in the current entry count.
3265 When t, every property is inherited. The value may also be a list of
3266 properties that should have inheritance, or a regular expression matching
3267 properties that should be inherited.
3269 However, note that some special properties use inheritance under special
3270 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3271 and the properties ending in \"_ALL\" when they are used as descriptor
3272 for valid values of a property.
3274 Note for programmers:
3275 When querying an entry with `org-entry-get', you can control if inheritance
3276 should be used. By default, `org-entry-get' looks only at the local
3277 properties. You can request inheritance by setting the inherit argument
3278 to t (to force inheritance) or to `selective' (to respect the setting
3279 in this variable)."
3280 :group 'org-properties
3281 :type '(choice
3282 (const :tag "Not" nil)
3283 (const :tag "Always" t)
3284 (repeat :tag "Specific properties" (string :tag "Property"))
3285 (regexp :tag "Properties matched by regexp")))
3287 (defun org-property-inherit-p (property)
3288 "Check if PROPERTY is one that should be inherited."
3289 (cond
3290 ((eq org-use-property-inheritance t) t)
3291 ((not org-use-property-inheritance) nil)
3292 ((stringp org-use-property-inheritance)
3293 (string-match org-use-property-inheritance property))
3294 ((listp org-use-property-inheritance)
3295 (member property org-use-property-inheritance))
3296 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3298 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3299 "The default column format, if no other format has been defined.
3300 This variable can be set on the per-file basis by inserting a line
3302 #+COLUMNS: %25ITEM ....."
3303 :group 'org-properties
3304 :type 'string)
3306 (defcustom org-columns-ellipses ".."
3307 "The ellipses to be used when a field in column view is truncated.
3308 When this is the empty string, as many characters as possible are shown,
3309 but then there will be no visual indication that the field has been truncated.
3310 When this is a string of length N, the last N characters of a truncated
3311 field are replaced by this string. If the column is narrower than the
3312 ellipses string, only part of the ellipses string will be shown."
3313 :group 'org-properties
3314 :type 'string)
3316 (defcustom org-columns-modify-value-for-display-function nil
3317 "Function that modifies values for display in column view.
3318 For example, it can be used to cut out a certain part from a time stamp.
3319 The function must take 2 arguments:
3321 column-title The title of the column (*not* the property name)
3322 value The value that should be modified.
3324 The function should return the value that should be displayed,
3325 or nil if the normal value should be used."
3326 :group 'org-properties
3327 :type 'function)
3329 (defcustom org-effort-property "Effort"
3330 "The property that is being used to keep track of effort estimates.
3331 Effort estimates given in this property need to have the format H:MM."
3332 :group 'org-properties
3333 :group 'org-progress
3334 :type '(string :tag "Property"))
3336 (defconst org-global-properties-fixed
3337 '(("VISIBILITY_ALL" . "folded children content all")
3338 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3339 "List of property/value pairs that can be inherited by any entry.
3341 These are fixed values, for the preset properties. The user variable
3342 that can be used to add to this list is `org-global-properties'.
3344 The entries in this list are cons cells where the car is a property
3345 name and cdr is a string with the value. If the value represents
3346 multiple items like an \"_ALL\" property, separate the items by
3347 spaces.")
3349 (defcustom org-global-properties nil
3350 "List of property/value pairs that can be inherited by any entry.
3352 This list will be combined with the constant `org-global-properties-fixed'.
3354 The entries in this list are cons cells where the car is a property
3355 name and cdr is a string with the value.
3357 You can set buffer-local values for the same purpose in the variable
3358 `org-file-properties' this by adding lines like
3360 #+PROPERTY: NAME VALUE"
3361 :group 'org-properties
3362 :type '(repeat
3363 (cons (string :tag "Property")
3364 (string :tag "Value"))))
3366 (defvar org-file-properties nil
3367 "List of property/value pairs that can be inherited by any entry.
3368 Valid for the current buffer.
3369 This variable is populated from #+PROPERTY lines.")
3370 (make-variable-buffer-local 'org-file-properties)
3372 (defgroup org-agenda nil
3373 "Options concerning agenda views in Org-mode."
3374 :tag "Org Agenda"
3375 :group 'org)
3377 (defvar org-category nil
3378 "Variable used by org files to set a category for agenda display.
3379 Such files should use a file variable to set it, for example
3381 # -*- mode: org; org-category: \"ELisp\"
3383 or contain a special line
3385 #+CATEGORY: ELisp
3387 If the file does not specify a category, then file's base name
3388 is used instead.")
3389 (make-variable-buffer-local 'org-category)
3390 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3392 (defcustom org-agenda-files nil
3393 "The files to be used for agenda display.
3394 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3395 \\[org-remove-file]. You can also use customize to edit the list.
3397 If an entry is a directory, all files in that directory that are matched by
3398 `org-agenda-file-regexp' will be part of the file list.
3400 If the value of the variable is not a list but a single file name, then
3401 the list of agenda files is actually stored and maintained in that file, one
3402 agenda file per line. In this file paths can be given relative to
3403 `org-directory'. Tilde expansion and environment variable substitution
3404 are also made."
3405 :group 'org-agenda
3406 :type '(choice
3407 (repeat :tag "List of files and directories" file)
3408 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3410 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3411 "Regular expression to match files for `org-agenda-files'.
3412 If any element in the list in that variable contains a directory instead
3413 of a normal file, all files in that directory that are matched by this
3414 regular expression will be included."
3415 :group 'org-agenda
3416 :type 'regexp)
3418 (defcustom org-agenda-text-search-extra-files nil
3419 "List of extra files to be searched by text search commands.
3420 These files will be search in addition to the agenda files by the
3421 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3422 Note that these files will only be searched for text search commands,
3423 not for the other agenda views like todo lists, tag searches or the weekly
3424 agenda. This variable is intended to list notes and possibly archive files
3425 that should also be searched by these two commands.
3426 In fact, if the first element in the list is the symbol `agenda-archives',
3427 than all archive files of all agenda files will be added to the search
3428 scope."
3429 :group 'org-agenda
3430 :type '(set :greedy t
3431 (const :tag "Agenda Archives" agenda-archives)
3432 (repeat :inline t (file))))
3434 (if (fboundp 'defvaralias)
3435 (defvaralias 'org-agenda-multi-occur-extra-files
3436 'org-agenda-text-search-extra-files))
3438 (defcustom org-agenda-skip-unavailable-files nil
3439 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3440 A nil value means to remove them, after a query, from the list."
3441 :group 'org-agenda
3442 :type 'boolean)
3444 (defcustom org-calendar-to-agenda-key [?c]
3445 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3446 The command `org-calendar-goto-agenda' will be bound to this key. The
3447 default is the character `c' because then `c' can be used to switch back and
3448 forth between agenda and calendar."
3449 :group 'org-agenda
3450 :type 'sexp)
3452 (defcustom org-calendar-insert-diary-entry-key [?i]
3453 "The key to be installed in `calendar-mode-map' for adding diary entries.
3454 This option is irrelevant until `org-agenda-diary-file' has been configured
3455 to point to an Org-mode file. When that is the case, the command
3456 `org-agenda-diary-entry' will be bound to the key given here, by default
3457 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3458 if you want to continue doing this, you need to change this to a different
3459 key."
3460 :group 'org-agenda
3461 :type 'sexp)
3463 (defcustom org-agenda-diary-file 'diary-file
3464 "File to which to add new entries with the `i' key in agenda and calendar.
3465 When this is the symbol `diary-file', the functionality in the Emacs
3466 calendar will be used to add entries to the `diary-file'. But when this
3467 points to a file, `org-agenda-diary-entry' will be used instead."
3468 :group 'org-agenda
3469 :type '(choice
3470 (const :tag "The standard Emacs diary file" diary-file)
3471 (file :tag "Special Org file diary entries")))
3473 (eval-after-load "calendar"
3474 '(progn
3475 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3476 'org-calendar-goto-agenda)
3477 (add-hook 'calendar-mode-hook
3478 (lambda ()
3479 (unless (eq org-agenda-diary-file 'diary-file)
3480 (define-key calendar-mode-map
3481 org-calendar-insert-diary-entry-key
3482 'org-agenda-diary-entry))))))
3484 (defgroup org-latex nil
3485 "Options for embedding LaTeX code into Org-mode."
3486 :tag "Org LaTeX"
3487 :group 'org)
3489 (defcustom org-format-latex-options
3490 '(:foreground default :background default :scale 1.0
3491 :html-foreground "Black" :html-background "Transparent"
3492 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3493 "Options for creating images from LaTeX fragments.
3494 This is a property list with the following properties:
3495 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3496 `default' means use the foreground of the default face.
3497 `auto' means use the foreground from the text face.
3498 :background the background color, or \"Transparent\".
3499 `default' means use the background of the default face.
3500 `auto' means use the background from the text face.
3501 :scale a scaling factor for the size of the images, to get more pixels
3502 :html-foreground, :html-background, :html-scale
3503 the same numbers for HTML export.
3504 :matchers a list indicating which matchers should be used to
3505 find LaTeX fragments. Valid members of this list are:
3506 \"begin\" find environments
3507 \"$1\" find single characters surrounded by $.$
3508 \"$\" find math expressions surrounded by $...$
3509 \"$$\" find math expressions surrounded by $$....$$
3510 \"\\(\" find math expressions surrounded by \\(...\\)
3511 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3512 :group 'org-latex
3513 :type 'plist)
3515 (defcustom org-format-latex-signal-error t
3516 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3517 When nil, just push out a message."
3518 :group 'org-latex
3519 :version "24.1"
3520 :type 'boolean)
3522 (defcustom org-latex-to-mathml-jar-file nil
3523 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3524 Use this to specify additional executable file say a jar file.
3526 When using MathToWeb as the converter, specify the full-path to
3527 your mathtoweb.jar file."
3528 :group 'org-latex
3529 :version "24.1"
3530 :type '(choice
3531 (const :tag "None" nil)
3532 (file :tag "JAR file" :must-match t)))
3534 (defcustom org-latex-to-mathml-convert-command nil
3535 "Command to convert LaTeX fragments to MathML.
3536 Replace format-specifiers in the command as noted below and use
3537 `shell-command' to convert LaTeX to MathML.
3538 %j: Executable file in fully expanded form as specified by
3539 `org-latex-to-mathml-jar-file'.
3540 %I: Input LaTeX file in fully expanded form
3541 %o: Output MathML file
3542 This command is used by `org-create-math-formula'.
3544 When using MathToWeb as the converter, set this to
3545 \"java -jar %j -unicode -force -df %o %I\"."
3546 :group 'org-latex
3547 :version "24.1"
3548 :type '(choice
3549 (const :tag "None" nil)
3550 (string :tag "\nShell command")))
3552 (defcustom org-latex-create-formula-image-program 'dvipng
3553 "Program to convert LaTeX fragments with.
3555 dvipng Process the LaTeX fragments to dvi file, then convert
3556 dvi files to png files using dvipng.
3557 This will also include processing of non-math environments.
3558 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3559 to convert pdf files to png files"
3560 :group 'org-latex
3561 :version "24.1"
3562 :type '(choice
3563 (const :tag "dvipng" dvipng)
3564 (const :tag "imagemagick" imagemagick)))
3566 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3567 "Path to store latex preview images.
3568 A relative path here creates many directories relative to the
3569 processed org files paths. An absolute path puts all preview
3570 images at the same place."
3571 :group 'org-latex
3572 :version "24.3"
3573 :type 'string)
3575 (defun org-format-latex-mathml-available-p ()
3576 "Return t if `org-latex-to-mathml-convert-command' is usable."
3577 (save-match-data
3578 (when (and (boundp 'org-latex-to-mathml-convert-command)
3579 org-latex-to-mathml-convert-command)
3580 (let ((executable (car (split-string
3581 org-latex-to-mathml-convert-command))))
3582 (when (executable-find executable)
3583 (if (string-match
3584 "%j" org-latex-to-mathml-convert-command)
3585 (file-readable-p org-latex-to-mathml-jar-file)
3586 t))))))
3588 (defcustom org-format-latex-header "\\documentclass{article}
3589 \\usepackage[usenames]{color}
3590 \\usepackage{amsmath}
3591 \\usepackage[mathscr]{eucal}
3592 \\pagestyle{empty} % do not remove
3593 \[PACKAGES]
3594 \[DEFAULT-PACKAGES]
3595 % The settings below are copied from fullpage.sty
3596 \\setlength{\\textwidth}{\\paperwidth}
3597 \\addtolength{\\textwidth}{-3cm}
3598 \\setlength{\\oddsidemargin}{1.5cm}
3599 \\addtolength{\\oddsidemargin}{-2.54cm}
3600 \\setlength{\\evensidemargin}{\\oddsidemargin}
3601 \\setlength{\\textheight}{\\paperheight}
3602 \\addtolength{\\textheight}{-\\headheight}
3603 \\addtolength{\\textheight}{-\\headsep}
3604 \\addtolength{\\textheight}{-\\footskip}
3605 \\addtolength{\\textheight}{-3cm}
3606 \\setlength{\\topmargin}{1.5cm}
3607 \\addtolength{\\topmargin}{-2.54cm}"
3608 "The document header used for processing LaTeX fragments.
3609 It is imperative that this header make sure that no page number
3610 appears on the page. The package defined in the variables
3611 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3612 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3613 will be appended."
3614 :group 'org-latex
3615 :type 'string)
3617 (defvar org-format-latex-header-extra nil)
3619 (defun org-set-packages-alist (var val)
3620 "Set the packages alist and make sure it has 3 elements per entry."
3621 (set var (mapcar (lambda (x)
3622 (if (and (consp x) (= (length x) 2))
3623 (list (car x) (nth 1 x) t)
3625 val)))
3627 (defun org-get-packages-alist (var)
3629 "Get the packages alist and make sure it has 3 elements per entry."
3630 (mapcar (lambda (x)
3631 (if (and (consp x) (= (length x) 2))
3632 (list (car x) (nth 1 x) t)
3634 (default-value var)))
3636 ;; The following variables are defined here because is it also used
3637 ;; when formatting latex fragments. Originally it was part of the
3638 ;; LaTeX exporter, which is why the name includes "export".
3639 (defcustom org-export-latex-default-packages-alist
3640 '(("AUTO" "inputenc" t)
3641 ("T1" "fontenc" t)
3642 ("" "fixltx2e" nil)
3643 ("" "graphicx" t)
3644 ("" "longtable" nil)
3645 ("" "float" nil)
3646 ("" "wrapfig" nil)
3647 ("" "soul" t)
3648 ("" "textcomp" t)
3649 ("" "marvosym" t)
3650 ("" "wasysym" t)
3651 ("" "latexsym" t)
3652 ("" "amssymb" t)
3653 ("" "hyperref" nil)
3654 "\\tolerance=1000"
3656 "Alist of default packages to be inserted in the header.
3657 Change this only if one of the packages here causes an incompatibility
3658 with another package you are using.
3659 The packages in this list are needed by one part or another of Org-mode
3660 to function properly.
3662 - inputenc, fontenc: for basic font and character selection
3663 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3664 for interpreting the entities in `org-entities'. You can skip some of these
3665 packages if you don't use any of the symbols in it.
3666 - graphicx: for including images
3667 - float, wrapfig: for figure placement
3668 - longtable: for long tables
3669 - hyperref: for cross references
3671 Therefore you should not modify this variable unless you know what you
3672 are doing. The one reason to change it anyway is that you might be loading
3673 some other package that conflicts with one of the default packages.
3674 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3675 If SNIPPET-FLAG is t, the package also needs to be included when
3676 compiling LaTeX snippets into images for inclusion into HTML."
3677 :group 'org-export-latex
3678 :set 'org-set-packages-alist
3679 :get 'org-get-packages-alist
3680 :version "24.1"
3681 :type '(repeat
3682 (choice
3683 (list :tag "options/package pair"
3684 (string :tag "options")
3685 (string :tag "package")
3686 (boolean :tag "Snippet"))
3687 (string :tag "A line of LaTeX"))))
3689 (defcustom org-export-latex-packages-alist nil
3690 "Alist of packages to be inserted in every LaTeX header.
3691 These will be inserted after `org-export-latex-default-packages-alist'.
3692 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3693 SNIPPET-FLAG, when t, indicates that this package is also needed when
3694 turning LaTeX snippets into images for inclusion into HTML.
3695 Make sure that you only list packages here which:
3696 - you want in every file
3697 - do not conflict with the default packages in
3698 `org-export-latex-default-packages-alist'
3699 - do not conflict with the setup in `org-format-latex-header'."
3700 :group 'org-export-latex
3701 :set 'org-set-packages-alist
3702 :get 'org-get-packages-alist
3703 :type '(repeat
3704 (choice
3705 (list :tag "options/package pair"
3706 (string :tag "options")
3707 (string :tag "package")
3708 (boolean :tag "Snippet"))
3709 (string :tag "A line of LaTeX"))))
3712 (defgroup org-appearance nil
3713 "Settings for Org-mode appearance."
3714 :tag "Org Appearance"
3715 :group 'org)
3717 (defcustom org-level-color-stars-only nil
3718 "Non-nil means fontify only the stars in each headline.
3719 When nil, the entire headline is fontified.
3720 Changing it requires restart of `font-lock-mode' to become effective
3721 also in regions already fontified."
3722 :group 'org-appearance
3723 :type 'boolean)
3725 (defcustom org-hide-leading-stars nil
3726 "Non-nil means hide the first N-1 stars in a headline.
3727 This works by using the face `org-hide' for these stars. This
3728 face is white for a light background, and black for a dark
3729 background. You may have to customize the face `org-hide' to
3730 make this work.
3731 Changing it requires restart of `font-lock-mode' to become effective
3732 also in regions already fontified.
3733 You may also set this on a per-file basis by adding one of the following
3734 lines to the buffer:
3736 #+STARTUP: hidestars
3737 #+STARTUP: showstars"
3738 :group 'org-appearance
3739 :type 'boolean)
3741 (defcustom org-hidden-keywords nil
3742 "List of symbols corresponding to keywords to be hidden the org buffer.
3743 For example, a value '(title) for this list will make the document's title
3744 appear in the buffer without the initial #+TITLE: keyword."
3745 :group 'org-appearance
3746 :version "24.1"
3747 :type '(set (const :tag "#+AUTHOR" author)
3748 (const :tag "#+DATE" date)
3749 (const :tag "#+EMAIL" email)
3750 (const :tag "#+TITLE" title)))
3752 (defcustom org-custom-properties nil
3753 "List of properties (as strings) with a special meaning.
3754 The default use of these custom properties is to let the user
3755 hide them with `org-toggle-custom-properties-visibility'."
3756 :group 'org-properties
3757 :group 'org-appearance
3758 :version "24.3"
3759 :type '(repeat (string :tag "Property Name")))
3761 (defcustom org-fontify-done-headline nil
3762 "Non-nil means change the face of a headline if it is marked DONE.
3763 Normally, only the TODO/DONE keyword indicates the state of a headline.
3764 When this is non-nil, the headline after the keyword is set to the
3765 `org-headline-done' as an additional indication."
3766 :group 'org-appearance
3767 :type 'boolean)
3769 (defcustom org-fontify-emphasized-text t
3770 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3771 Changing this variable requires a restart of Emacs to take effect."
3772 :group 'org-appearance
3773 :type 'boolean)
3775 (defcustom org-fontify-whole-heading-line nil
3776 "Non-nil means fontify the whole line for headings.
3777 This is useful when setting a background color for the
3778 org-level-* faces."
3779 :group 'org-appearance
3780 :type 'boolean)
3782 (defcustom org-highlight-latex-fragments-and-specials nil
3783 "Non-nil means fontify what is treated specially by the exporters."
3784 :group 'org-appearance
3785 :type 'boolean)
3787 (defcustom org-hide-emphasis-markers nil
3788 "Non-nil mean font-lock should hide the emphasis marker characters."
3789 :group 'org-appearance
3790 :type 'boolean)
3792 (defcustom org-pretty-entities nil
3793 "Non-nil means show entities as UTF8 characters.
3794 When nil, the \\name form remains in the buffer."
3795 :group 'org-appearance
3796 :version "24.1"
3797 :type 'boolean)
3799 (defcustom org-pretty-entities-include-sub-superscripts t
3800 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3801 :group 'org-appearance
3802 :version "24.1"
3803 :type 'boolean)
3805 (defvar org-emph-re nil
3806 "Regular expression for matching emphasis.
3807 After a match, the match groups contain these elements:
3808 0 The match of the full regular expression, including the characters
3809 before and after the proper match
3810 1 The character before the proper match, or empty at beginning of line
3811 2 The proper match, including the leading and trailing markers
3812 3 The leading marker like * or /, indicating the type of highlighting
3813 4 The text between the emphasis markers, not including the markers
3814 5 The character after the match, empty at the end of a line")
3815 (defvar org-verbatim-re nil
3816 "Regular expression for matching verbatim text.")
3817 (defvar org-emphasis-regexp-components) ; defined just below
3818 (defvar org-emphasis-alist) ; defined just below
3819 (defun org-set-emph-re (var val)
3820 "Set variable and compute the emphasis regular expression."
3821 (set var val)
3822 (when (and (boundp 'org-emphasis-alist)
3823 (boundp 'org-emphasis-regexp-components)
3824 org-emphasis-alist org-emphasis-regexp-components)
3825 (let* ((e org-emphasis-regexp-components)
3826 (pre (car e))
3827 (post (nth 1 e))
3828 (border (nth 2 e))
3829 (body (nth 3 e))
3830 (nl (nth 4 e))
3831 (body1 (concat body "*?"))
3832 (markers (mapconcat 'car org-emphasis-alist ""))
3833 (vmarkers (mapconcat
3834 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3835 org-emphasis-alist "")))
3836 ;; make sure special characters appear at the right position in the class
3837 (if (string-match "\\^" markers)
3838 (setq markers (concat (replace-match "" t t markers) "^")))
3839 (if (string-match "-" markers)
3840 (setq markers (concat (replace-match "" t t markers) "-")))
3841 (if (string-match "\\^" vmarkers)
3842 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3843 (if (string-match "-" vmarkers)
3844 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3845 (if (> nl 0)
3846 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3847 (int-to-string nl) "\\}")))
3848 ;; Make the regexp
3849 (setq org-emph-re
3850 (concat "\\([" pre "]\\|^\\)"
3851 "\\("
3852 "\\([" markers "]\\)"
3853 "\\("
3854 "[^" border "]\\|"
3855 "[^" border "]"
3856 body1
3857 "[^" border "]"
3858 "\\)"
3859 "\\3\\)"
3860 "\\([" post "]\\|$\\)"))
3861 (setq org-verbatim-re
3862 (concat "\\([" pre "]\\|^\\)"
3863 "\\("
3864 "\\([" vmarkers "]\\)"
3865 "\\("
3866 "[^" border "]\\|"
3867 "[^" border "]"
3868 body1
3869 "[^" border "]"
3870 "\\)"
3871 "\\3\\)"
3872 "\\([" post "]\\|$\\)")))))
3874 (defcustom org-emphasis-regexp-components
3875 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3876 "Components used to build the regular expression for emphasis.
3877 This is a list with five entries. Terminology: In an emphasis string
3878 like \" *strong word* \", we call the initial space PREMATCH, the final
3879 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3880 and \"trong wor\" is the body. The different components in this variable
3881 specify what is allowed/forbidden in each part:
3883 pre Chars allowed as prematch. Beginning of line will be allowed too.
3884 post Chars allowed as postmatch. End of line will be allowed too.
3885 border The chars *forbidden* as border characters.
3886 body-regexp A regexp like \".\" to match a body character. Don't use
3887 non-shy groups here, and don't allow newline here.
3888 newline The maximum number of newlines allowed in an emphasis exp.
3890 Use customize to modify this, or restart Emacs after changing it."
3891 :group 'org-appearance
3892 :set 'org-set-emph-re
3893 :type '(list
3894 (sexp :tag "Allowed chars in pre ")
3895 (sexp :tag "Allowed chars in post ")
3896 (sexp :tag "Forbidden chars in border ")
3897 (sexp :tag "Regexp for body ")
3898 (integer :tag "number of newlines allowed")
3899 (option (boolean :tag "Please ignore this button"))))
3901 (defcustom org-emphasis-alist
3902 `(("*" bold "<b>" "</b>")
3903 ("/" italic "<i>" "</i>")
3904 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3905 ("=" org-code "<code>" "</code>" verbatim)
3906 ("~" org-verbatim "<code>" "</code>" verbatim)
3907 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3908 "<del>" "</del>")
3910 "Special syntax for emphasized text.
3911 Text starting and ending with a special character will be emphasized, for
3912 example *bold*, _underlined_ and /italic/. This variable sets the marker
3913 characters, the face to be used by font-lock for highlighting in Org-mode
3914 Emacs buffers, and the HTML tags to be used for this.
3915 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3916 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3917 Use customize to modify this, or restart Emacs after changing it."
3918 :group 'org-appearance
3919 :set 'org-set-emph-re
3920 :type '(repeat
3921 (list
3922 (string :tag "Marker character")
3923 (choice
3924 (face :tag "Font-lock-face")
3925 (plist :tag "Face property list"))
3926 (string :tag "HTML start tag")
3927 (string :tag "HTML end tag")
3928 (option (const verbatim)))))
3930 (defvar org-syntax-table
3931 (let ((st (make-syntax-table)))
3932 (mapc (lambda(c) (modify-syntax-entry
3933 (string-to-char (car c)) "w p" st))
3934 org-emphasis-alist)
3935 st))
3937 (defvar org-protecting-blocks
3938 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3939 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3940 This is needed for font-lock setup.")
3942 ;;; Miscellaneous options
3944 (defgroup org-completion nil
3945 "Completion in Org-mode."
3946 :tag "Org Completion"
3947 :group 'org)
3949 (defcustom org-completion-use-ido nil
3950 "Non-nil means use ido completion wherever possible.
3951 Note that `ido-mode' must be active for this variable to be relevant.
3952 If you decide to turn this variable on, you might well want to turn off
3953 `org-outline-path-complete-in-steps'.
3954 See also `org-completion-use-iswitchb'."
3955 :group 'org-completion
3956 :type 'boolean)
3958 (defcustom org-completion-use-iswitchb nil
3959 "Non-nil means use iswitchb completion wherever possible.
3960 Note that `iswitchb-mode' must be active for this variable to be relevant.
3961 If you decide to turn this variable on, you might well want to turn off
3962 `org-outline-path-complete-in-steps'.
3963 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3964 :group 'org-completion
3965 :type 'boolean)
3967 (defcustom org-completion-fallback-command 'hippie-expand
3968 "The expansion command called by \\[pcomplete] in normal context.
3969 Normal means, no org-mode-specific context."
3970 :group 'org-completion
3971 :type 'function)
3973 ;;; Functions and variables from their packages
3974 ;; Declared here to avoid compiler warnings
3976 ;; XEmacs only
3977 (defvar outline-mode-menu-heading)
3978 (defvar outline-mode-menu-show)
3979 (defvar outline-mode-menu-hide)
3980 (defvar zmacs-regions) ; XEmacs regions
3982 ;; Emacs only
3983 (defvar mark-active)
3985 ;; Various packages
3986 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3987 (declare-function calendar-forward-day "cal-move" (arg))
3988 (declare-function calendar-goto-date "cal-move" (date))
3989 (declare-function calendar-goto-today "cal-move" ())
3990 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3991 (defvar calc-embedded-close-formula)
3992 (defvar calc-embedded-open-formula)
3993 (declare-function cdlatex-tab "ext:cdlatex" ())
3994 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3995 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3996 (defvar font-lock-unfontify-region-function)
3997 (declare-function iswitchb-read-buffer "iswitchb"
3998 (prompt &optional default require-match start matches-set))
3999 (defvar iswitchb-temp-buflist)
4000 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4001 (defvar org-agenda-tags-todo-honor-ignore-options)
4002 (declare-function org-agenda-skip "org-agenda" ())
4003 (declare-function
4004 org-agenda-format-item "org-agenda"
4005 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4006 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4007 (declare-function org-agenda-change-all-lines "org-agenda"
4008 (newhead hdmarker &optional fixface just-this))
4009 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4010 (declare-function org-agenda-maybe-redo "org-agenda" ())
4011 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4012 (beg end))
4013 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4014 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4015 "org-agenda" (&optional end))
4016 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4017 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4018 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4019 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4020 (declare-function org-indent-mode "org-indent" (&optional arg))
4021 (declare-function parse-time-string "parse-time" (string))
4022 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4023 (declare-function org-export-latex-fix-inputenc "org-latex" ())
4024 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4025 (defvar remember-data-file)
4026 (defvar texmathp-why)
4027 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4028 (declare-function table--at-cell-p "table" (position &optional object at-column))
4030 (defvar org-latex-regexps)
4032 ;;; Autoload and prepare some org modules
4034 ;; Some table stuff that needs to be defined here, because it is used
4035 ;; by the functions setting up org-mode or checking for table context.
4037 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4038 "Detect an org-type or table-type table.")
4039 (defconst org-table-line-regexp "^[ \t]*|"
4040 "Detect an org-type table line.")
4041 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4042 "Detect an org-type table line.")
4043 (defconst org-table-hline-regexp "^[ \t]*|-"
4044 "Detect an org-type table hline.")
4045 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4046 "Detect a table-type table hline.")
4047 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4048 "Detect the first line outside a table when searching from within it.
4049 This works for both table types.")
4051 ;; Autoload the functions in org-table.el that are needed by functions here.
4053 (eval-and-compile
4054 (org-autoload "org-table"
4055 '(org-table-begin org-table-blank-field org-table-end)))
4057 ;;;###autoload
4058 (defun turn-on-orgtbl ()
4059 "Unconditionally turn on `orgtbl-mode'."
4060 (require 'org-table)
4061 (orgtbl-mode 1))
4063 (defun org-at-table-p (&optional table-type)
4064 "Return t if the cursor is inside an org-type table.
4065 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4066 (if org-enable-table-editor
4067 (save-excursion
4068 (beginning-of-line 1)
4069 (looking-at (if table-type org-table-any-line-regexp
4070 org-table-line-regexp)))
4071 nil))
4072 (defsubst org-table-p () (org-at-table-p))
4074 (defun org-at-table.el-p ()
4075 "Return t if and only if we are at a table.el table."
4076 (and (org-at-table-p 'any)
4077 (save-excursion
4078 (goto-char (org-table-begin 'any))
4079 (looking-at org-table1-hline-regexp))))
4080 (defun org-table-recognize-table.el ()
4081 "If there is a table.el table nearby, recognize it and move into it."
4082 (if org-table-tab-recognizes-table.el
4083 (if (org-at-table.el-p)
4084 (progn
4085 (beginning-of-line 1)
4086 (if (looking-at org-table-dataline-regexp)
4088 (if (looking-at org-table1-hline-regexp)
4089 (progn
4090 (beginning-of-line 2)
4091 (if (looking-at org-table-any-border-regexp)
4092 (beginning-of-line -1)))))
4093 (if (re-search-forward "|" (org-table-end t) t)
4094 (progn
4095 (require 'table)
4096 (if (table--at-cell-p (point))
4098 (message "recognizing table.el table...")
4099 (table-recognize-table)
4100 (message "recognizing table.el table...done")))
4101 (error "This should not happen"))
4103 nil)
4104 nil))
4106 (defun org-at-table-hline-p ()
4107 "Return t if the cursor is inside a hline in a table."
4108 (if org-enable-table-editor
4109 (save-excursion
4110 (beginning-of-line 1)
4111 (looking-at org-table-hline-regexp))
4112 nil))
4114 (defvar org-table-clean-did-remove-column nil)
4116 (defun org-table-map-tables (function &optional quietly)
4117 "Apply FUNCTION to the start of all tables in the buffer."
4118 (save-excursion
4119 (save-restriction
4120 (widen)
4121 (goto-char (point-min))
4122 (while (re-search-forward org-table-any-line-regexp nil t)
4123 (unless quietly
4124 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4125 (beginning-of-line 1)
4126 (when (and (looking-at org-table-line-regexp)
4127 ;; Exclude tables in src/example/verbatim/clocktable blocks
4128 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4129 (save-excursion (funcall function))
4130 (or (looking-at org-table-line-regexp)
4131 (forward-char 1)))
4132 (re-search-forward org-table-any-border-regexp nil 1))))
4133 (unless quietly (message "Mapping tables: done")))
4135 ;; Declare and autoload functions from org-exp.el & Co
4137 (declare-function org-default-export-plist "org-exp")
4138 (declare-function org-infile-export-plist "org-exp")
4139 (declare-function org-get-current-options "org-exp")
4141 ;; Declare and autoload functions from org-agenda.el
4143 (eval-and-compile
4144 (org-autoload "org-agenda"
4145 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4147 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4148 (declare-function org-clock-update-mode-line "org-clock" ())
4149 (declare-function org-resolve-clocks "org-clock"
4150 (&optional also-non-dangling-p prompt last-valid))
4151 (defvar org-clock-start-time)
4152 (defvar org-clock-marker (make-marker)
4153 "Marker recording the last clock-in.")
4154 (defvar org-clock-hd-marker (make-marker)
4155 "Marker recording the last clock-in, but the headline position.")
4156 (defvar org-clock-heading ""
4157 "The heading of the current clock entry.")
4158 (defun org-clock-is-active ()
4159 "Return non-nil if clock is currently running.
4160 The return value is actually the clock marker."
4161 (marker-buffer org-clock-marker))
4163 (eval-and-compile
4164 (org-autoload "org-clock" '(org-clock-remove-overlays
4165 org-clock-update-time-maybe
4166 org-clocktable-shift)))
4168 (defun org-check-running-clock ()
4169 "Check if the current buffer contains the running clock.
4170 If yes, offer to stop it and to save the buffer with the changes."
4171 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4172 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4173 (buffer-name))))
4174 (org-clock-out)
4175 (when (y-or-n-p "Save changed buffer?")
4176 (save-buffer))))
4178 (defun org-clocktable-try-shift (dir n)
4179 "Check if this line starts a clock table, if yes, shift the time block."
4180 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4181 (org-clocktable-shift dir n)))
4183 ;;;###autoload
4184 (defun org-clock-persistence-insinuate ()
4185 "Set up hooks for clock persistence."
4186 (require 'org-clock)
4187 (add-hook 'org-mode-hook 'org-clock-load)
4188 (add-hook 'kill-emacs-hook 'org-clock-save))
4190 ;; Define the variable already here, to make sure we have it.
4191 (defvar org-indent-mode nil
4192 "Non-nil if Org-Indent mode is enabled.
4193 Use the command `org-indent-mode' to change this variable.")
4195 ;; Autoload archiving code
4196 ;; The stuff that is needed for cycling and tags has to be defined here.
4198 (defgroup org-archive nil
4199 "Options concerning archiving in Org-mode."
4200 :tag "Org Archive"
4201 :group 'org-structure)
4203 (defcustom org-archive-location "%s_archive::"
4204 "The location where subtrees should be archived.
4206 The value of this variable is a string, consisting of two parts,
4207 separated by a double-colon. The first part is a filename and
4208 the second part is a headline.
4210 When the filename is omitted, archiving happens in the same file.
4211 %s in the filename will be replaced by the current file
4212 name (without the directory part). Archiving to a different file
4213 is useful to keep archived entries from contributing to the
4214 Org-mode Agenda.
4216 The archived entries will be filed as subtrees of the specified
4217 headline. When the headline is omitted, the subtrees are simply
4218 filed away at the end of the file, as top-level entries. Also in
4219 the heading you can use %s to represent the file name, this can be
4220 useful when using the same archive for a number of different files.
4222 Here are a few examples:
4223 \"%s_archive::\"
4224 If the current file is Projects.org, archive in file
4225 Projects.org_archive, as top-level trees. This is the default.
4227 \"::* Archived Tasks\"
4228 Archive in the current file, under the top-level headline
4229 \"* Archived Tasks\".
4231 \"~/org/archive.org::\"
4232 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4234 \"~/org/archive.org::* From %s\"
4235 Archive in file ~/org/archive.org (absolute path), under headlines
4236 \"From FILENAME\" where file name is the current file name.
4238 \"~/org/datetree.org::datetree/* Finished Tasks\"
4239 The \"datetree/\" string is special, signifying to archive
4240 items to the datetree. Items are placed in either the CLOSED
4241 date of the item, or the current date if there is no CLOSED date.
4242 The heading will be a subentry to the current date. There doesn't
4243 need to be a heading, but there always needs to be a slash after
4244 datetree. For example, to store archived items directly in the
4245 datetree, use \"~/org/datetree.org::datetree/\".
4247 \"basement::** Finished Tasks\"
4248 Archive in file ./basement (relative path), as level 3 trees
4249 below the level 2 heading \"** Finished Tasks\".
4251 You may set this option on a per-file basis by adding to the buffer a
4252 line like
4254 #+ARCHIVE: basement::** Finished Tasks
4256 You may also define it locally for a subtree by setting an ARCHIVE property
4257 in the entry. If such a property is found in an entry, or anywhere up
4258 the hierarchy, it will be used."
4259 :group 'org-archive
4260 :type 'string)
4262 (defcustom org-archive-tag "ARCHIVE"
4263 "The tag that marks a subtree as archived.
4264 An archived subtree does not open during visibility cycling, and does
4265 not contribute to the agenda listings.
4266 After changing this, font-lock must be restarted in the relevant buffers to
4267 get the proper fontification."
4268 :group 'org-archive
4269 :group 'org-keywords
4270 :type 'string)
4272 (defcustom org-agenda-skip-archived-trees t
4273 "Non-nil means the agenda will skip any items located in archived trees.
4274 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4275 variable is no longer recommended, you should leave it at the value t.
4276 Instead, use the key `v' to cycle the archives-mode in the agenda."
4277 :group 'org-archive
4278 :group 'org-agenda-skip
4279 :type 'boolean)
4281 (defcustom org-columns-skip-archived-trees t
4282 "Non-nil means ignore archived trees when creating column view."
4283 :group 'org-archive
4284 :group 'org-properties
4285 :type 'boolean)
4287 (defcustom org-cycle-open-archived-trees nil
4288 "Non-nil means `org-cycle' will open archived trees.
4289 An archived tree is a tree marked with the tag ARCHIVE.
4290 When nil, archived trees will stay folded. You can still open them with
4291 normal outline commands like `show-all', but not with the cycling commands."
4292 :group 'org-archive
4293 :group 'org-cycle
4294 :type 'boolean)
4296 (defcustom org-sparse-tree-open-archived-trees nil
4297 "Non-nil means sparse tree construction shows matches in archived trees.
4298 When nil, matches in these trees are highlighted, but the trees are kept in
4299 collapsed state."
4300 :group 'org-archive
4301 :group 'org-sparse-trees
4302 :type 'boolean)
4304 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4305 "The default date type when building a sparse tree.
4306 When this is nil, a date is a scheduled or a deadline timestamp.
4307 Otherwise, these types are allowed:
4309 all: all timestamps
4310 active: only active timestamps (<...>)
4311 inactive: only inactive timestamps (<...)
4312 scheduled: only scheduled timestamps
4313 deadline: only deadline timestamps"
4314 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4315 (const :tag "All timestamps" all)
4316 (const :tag "Only active timestamps" active)
4317 (const :tag "Only inactive timestamps" inactive)
4318 (const :tag "Only scheduled timestamps" scheduled)
4319 (const :tag "Only deadline timestamps" deadline))
4320 :version "24.3"
4321 :group 'org-sparse-trees)
4323 (defun org-cycle-hide-archived-subtrees (state)
4324 "Re-hide all archived subtrees after a visibility state change."
4325 (when (and (not org-cycle-open-archived-trees)
4326 (not (memq state '(overview folded))))
4327 (save-excursion
4328 (let* ((globalp (memq state '(contents all)))
4329 (beg (if globalp (point-min) (point)))
4330 (end (if globalp (point-max) (org-end-of-subtree t))))
4331 (org-hide-archived-subtrees beg end)
4332 (goto-char beg)
4333 (if (looking-at (concat ".*:" org-archive-tag ":"))
4334 (message "%s" (substitute-command-keys
4335 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4337 (defun org-force-cycle-archived ()
4338 "Cycle subtree even if it is archived."
4339 (interactive)
4340 (setq this-command 'org-cycle)
4341 (let ((org-cycle-open-archived-trees t))
4342 (call-interactively 'org-cycle)))
4344 (defun org-hide-archived-subtrees (beg end)
4345 "Re-hide all archived subtrees after a visibility state change."
4346 (save-excursion
4347 (let* ((re (concat ":" org-archive-tag ":")))
4348 (goto-char beg)
4349 (while (re-search-forward re end t)
4350 (when (org-at-heading-p)
4351 (org-flag-subtree t)
4352 (org-end-of-subtree t))))))
4354 (declare-function outline-end-of-heading "outline" ())
4355 (declare-function outline-flag-region "outline" (from to flag))
4356 (defun org-flag-subtree (flag)
4357 (save-excursion
4358 (org-back-to-heading t)
4359 (outline-end-of-heading)
4360 (outline-flag-region (point)
4361 (progn (org-end-of-subtree t) (point))
4362 flag)))
4364 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4366 (eval-and-compile
4367 (org-autoload "org-archive"
4368 '(org-add-archive-files)))
4370 ;; Autoload Column View Code
4372 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4373 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4374 (declare-function org-columns-compute "org-colview" (property))
4376 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4377 '(org-columns-number-to-string
4378 org-columns-get-format-and-top-level
4379 org-columns-compute
4380 org-columns-remove-overlays))
4382 ;; Autoload ID code
4384 (declare-function org-id-store-link "org-id")
4385 (declare-function org-id-locations-load "org-id")
4386 (declare-function org-id-locations-save "org-id")
4387 (defvar org-id-track-globally)
4388 (org-autoload "org-id"
4389 '(org-id-new
4390 org-id-copy
4391 org-id-get-with-outline-path-completion
4392 org-id-get-with-outline-drilling))
4394 ;;; Variables for pre-computed regular expressions, all buffer local
4396 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4397 "Matches first line of a hidden block.")
4398 (make-variable-buffer-local 'org-drawer-regexp)
4399 (defvar org-todo-regexp nil
4400 "Matches any of the TODO state keywords.")
4401 (make-variable-buffer-local 'org-todo-regexp)
4402 (defvar org-not-done-regexp nil
4403 "Matches any of the TODO state keywords except the last one.")
4404 (make-variable-buffer-local 'org-not-done-regexp)
4405 (defvar org-not-done-heading-regexp nil
4406 "Matches a TODO headline that is not done.")
4407 (make-variable-buffer-local 'org-not-done-regexp)
4408 (defvar org-todo-line-regexp nil
4409 "Matches a headline and puts TODO state into group 2 if present.")
4410 (make-variable-buffer-local 'org-todo-line-regexp)
4411 (defvar org-complex-heading-regexp nil
4412 "Matches a headline and puts everything into groups:
4413 group 1: the stars
4414 group 2: The todo keyword, maybe
4415 group 3: Priority cookie
4416 group 4: True headline
4417 group 5: Tags")
4418 (make-variable-buffer-local 'org-complex-heading-regexp)
4419 (defvar org-complex-heading-regexp-format nil
4420 "Printf format to make regexp to match an exact headline.
4421 This regexp will match the headline of any node which has the
4422 exact headline text that is put into the format, but may have any
4423 TODO state, priority and tags.")
4424 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4425 (defvar org-todo-line-tags-regexp nil
4426 "Matches a headline and puts TODO state into group 2 if present.
4427 Also put tags into group 4 if tags are present.")
4428 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4429 (defvar org-ds-keyword-length 12
4430 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4431 (make-variable-buffer-local 'org-ds-keyword-length)
4432 (defvar org-deadline-regexp nil
4433 "Matches the DEADLINE keyword.")
4434 (make-variable-buffer-local 'org-deadline-regexp)
4435 (defvar org-deadline-time-regexp nil
4436 "Matches the DEADLINE keyword together with a time stamp.")
4437 (make-variable-buffer-local 'org-deadline-time-regexp)
4438 (defvar org-deadline-line-regexp nil
4439 "Matches the DEADLINE keyword and the rest of the line.")
4440 (make-variable-buffer-local 'org-deadline-line-regexp)
4441 (defvar org-scheduled-regexp nil
4442 "Matches the SCHEDULED keyword.")
4443 (make-variable-buffer-local 'org-scheduled-regexp)
4444 (defvar org-scheduled-time-regexp nil
4445 "Matches the SCHEDULED keyword together with a time stamp.")
4446 (make-variable-buffer-local 'org-scheduled-time-regexp)
4447 (defvar org-closed-time-regexp nil
4448 "Matches the CLOSED keyword together with a time stamp.")
4449 (make-variable-buffer-local 'org-closed-time-regexp)
4451 (defvar org-keyword-time-regexp nil
4452 "Matches any of the 4 keywords, together with the time stamp.")
4453 (make-variable-buffer-local 'org-keyword-time-regexp)
4454 (defvar org-keyword-time-not-clock-regexp nil
4455 "Matches any of the 3 keywords, together with the time stamp.")
4456 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4457 (defvar org-maybe-keyword-time-regexp nil
4458 "Matches a timestamp, possibly preceded by a keyword.")
4459 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4460 (defvar org-all-time-keywords nil
4461 "List of time keywords.")
4462 (make-variable-buffer-local 'org-all-time-keywords)
4464 (defconst org-plain-time-of-day-regexp
4465 (concat
4466 "\\(\\<[012]?[0-9]"
4467 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4468 "\\(--?"
4469 "\\(\\<[012]?[0-9]"
4470 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4471 "\\)?")
4472 "Regular expression to match a plain time or time range.
4473 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4474 groups carry important information:
4475 0 the full match
4476 1 the first time, range or not
4477 8 the second time, if it is a range.")
4479 (defconst org-plain-time-extension-regexp
4480 (concat
4481 "\\(\\<[012]?[0-9]"
4482 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4483 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4484 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4485 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4486 groups carry important information:
4487 0 the full match
4488 7 hours of duration
4489 9 minutes of duration")
4491 (defconst org-stamp-time-of-day-regexp
4492 (concat
4493 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4494 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4495 "\\(--?"
4496 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4497 "Regular expression to match a timestamp time or time range.
4498 After a match, the following groups carry important information:
4499 0 the full match
4500 1 date plus weekday, for back referencing to make sure both times are on the same day
4501 2 the first time, range or not
4502 4 the second time, if it is a range.")
4504 (defconst org-startup-options
4505 '(("fold" org-startup-folded t)
4506 ("overview" org-startup-folded t)
4507 ("nofold" org-startup-folded nil)
4508 ("showall" org-startup-folded nil)
4509 ("showeverything" org-startup-folded showeverything)
4510 ("content" org-startup-folded content)
4511 ("indent" org-startup-indented t)
4512 ("noindent" org-startup-indented nil)
4513 ("hidestars" org-hide-leading-stars t)
4514 ("showstars" org-hide-leading-stars nil)
4515 ("odd" org-odd-levels-only t)
4516 ("oddeven" org-odd-levels-only nil)
4517 ("align" org-startup-align-all-tables t)
4518 ("noalign" org-startup-align-all-tables nil)
4519 ("inlineimages" org-startup-with-inline-images t)
4520 ("noinlineimages" org-startup-with-inline-images nil)
4521 ("customtime" org-display-custom-times t)
4522 ("logdone" org-log-done time)
4523 ("lognotedone" org-log-done note)
4524 ("nologdone" org-log-done nil)
4525 ("lognoteclock-out" org-log-note-clock-out t)
4526 ("nolognoteclock-out" org-log-note-clock-out nil)
4527 ("logrepeat" org-log-repeat state)
4528 ("lognoterepeat" org-log-repeat note)
4529 ("logdrawer" org-log-into-drawer t)
4530 ("nologdrawer" org-log-into-drawer nil)
4531 ("logstatesreversed" org-log-states-order-reversed t)
4532 ("nologstatesreversed" org-log-states-order-reversed nil)
4533 ("nologrepeat" org-log-repeat nil)
4534 ("logreschedule" org-log-reschedule time)
4535 ("lognotereschedule" org-log-reschedule note)
4536 ("nologreschedule" org-log-reschedule nil)
4537 ("logredeadline" org-log-redeadline time)
4538 ("lognoteredeadline" org-log-redeadline note)
4539 ("nologredeadline" org-log-redeadline nil)
4540 ("logrefile" org-log-refile time)
4541 ("lognoterefile" org-log-refile note)
4542 ("nologrefile" org-log-refile nil)
4543 ("fninline" org-footnote-define-inline t)
4544 ("nofninline" org-footnote-define-inline nil)
4545 ("fnlocal" org-footnote-section nil)
4546 ("fnauto" org-footnote-auto-label t)
4547 ("fnprompt" org-footnote-auto-label nil)
4548 ("fnconfirm" org-footnote-auto-label confirm)
4549 ("fnplain" org-footnote-auto-label plain)
4550 ("fnadjust" org-footnote-auto-adjust t)
4551 ("nofnadjust" org-footnote-auto-adjust nil)
4552 ("constcgs" constants-unit-system cgs)
4553 ("constSI" constants-unit-system SI)
4554 ("noptag" org-tag-persistent-alist nil)
4555 ("hideblocks" org-hide-block-startup t)
4556 ("nohideblocks" org-hide-block-startup nil)
4557 ("beamer" org-startup-with-beamer-mode t)
4558 ("entitiespretty" org-pretty-entities t)
4559 ("entitiesplain" org-pretty-entities nil))
4560 "Variable associated with STARTUP options for org-mode.
4561 Each element is a list of three items: the startup options (as written
4562 in the #+STARTUP line), the corresponding variable, and the value to set
4563 this variable to if the option is found. An optional forth element PUSH
4564 means to push this value onto the list in the variable.")
4566 (defun org-update-property-plist (key val props)
4567 "Update PROPS with KEY and VAL."
4568 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4569 (key (if appending (substring key 0 (- (length key) 1)) key))
4570 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4571 (previous (cdr (assoc key props))))
4572 (if appending
4573 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4574 (cons (cons key val) remainder))))
4576 (defconst org-block-regexp
4577 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4578 "Regular expression for hiding blocks.")
4579 (defconst org-heading-keyword-regexp-format
4580 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4581 "Printf format for a regexp matching an headline with some keyword.
4582 This regexp will match the headline of any node which has the
4583 exact keyword that is put into the format. The keyword isn't in
4584 any group by default, but the stars and the body are.")
4585 (defconst org-heading-keyword-maybe-regexp-format
4586 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4587 "Printf format for a regexp matching an headline, possibly with some keyword.
4588 This regexp can match any headline with the specified keyword, or
4589 without a keyword. The keyword isn't in any group by default,
4590 but the stars and the body are.")
4592 (defun org-set-regexps-and-options ()
4593 "Precompute regular expressions for current buffer."
4594 (when (derived-mode-p 'org-mode)
4595 (org-set-local 'org-todo-kwd-alist nil)
4596 (org-set-local 'org-todo-key-alist nil)
4597 (org-set-local 'org-todo-key-trigger nil)
4598 (org-set-local 'org-todo-keywords-1 nil)
4599 (org-set-local 'org-done-keywords nil)
4600 (org-set-local 'org-todo-heads nil)
4601 (org-set-local 'org-todo-sets nil)
4602 (org-set-local 'org-todo-log-states nil)
4603 (org-set-local 'org-file-properties nil)
4604 (org-set-local 'org-file-tags nil)
4605 (let ((re (org-make-options-regexp
4606 '("CATEGORY" "TODO" "COLUMNS"
4607 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4608 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4609 "OPTIONS")
4610 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4611 (splitre "[ \t]+")
4612 (scripts org-use-sub-superscripts)
4613 kwds kws0 kwsa key log value cat arch tags const links hw dws
4614 tail sep kws1 prio props ftags drawers beamer-p
4615 ext-setup-or-nil setup-contents (start 0))
4616 (save-excursion
4617 (save-restriction
4618 (widen)
4619 (goto-char (point-min))
4620 (while (or (and ext-setup-or-nil
4621 (string-match re ext-setup-or-nil start)
4622 (setq start (match-end 0)))
4623 (and (setq ext-setup-or-nil nil start 0)
4624 (re-search-forward re nil t)))
4625 (setq key (upcase (match-string 1 ext-setup-or-nil))
4626 value (org-match-string-no-properties 2 ext-setup-or-nil))
4627 (if (stringp value) (setq value (org-trim value)))
4628 (cond
4629 ((equal key "CATEGORY")
4630 (setq cat value))
4631 ((member key '("SEQ_TODO" "TODO"))
4632 (push (cons 'sequence (org-split-string value splitre)) kwds))
4633 ((equal key "TYP_TODO")
4634 (push (cons 'type (org-split-string value splitre)) kwds))
4635 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4636 ;; general TODO-like setup
4637 (push (cons (intern (downcase (match-string 1 key)))
4638 (org-split-string value splitre)) kwds))
4639 ((equal key "TAGS")
4640 (setq tags (append tags (if tags '("\\n") nil)
4641 (org-split-string value splitre))))
4642 ((equal key "COLUMNS")
4643 (org-set-local 'org-columns-default-format value))
4644 ((equal key "LINK")
4645 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4646 (push (cons (match-string 1 value)
4647 (org-trim (match-string 2 value)))
4648 links)))
4649 ((equal key "PRIORITIES")
4650 (setq prio (org-split-string value " +")))
4651 ((equal key "PROPERTY")
4652 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4653 (setq props (org-update-property-plist (match-string 1 value)
4654 (match-string 2 value)
4655 props))))
4656 ((equal key "FILETAGS")
4657 (when (string-match "\\S-" value)
4658 (setq ftags
4659 (append
4660 ftags
4661 (apply 'append
4662 (mapcar (lambda (x) (org-split-string x ":"))
4663 (org-split-string value)))))))
4664 ((equal key "DRAWERS")
4665 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4666 ((equal key "CONSTANTS")
4667 (setq const (append const (org-split-string value splitre))))
4668 ((equal key "STARTUP")
4669 (let ((opts (org-split-string value splitre))
4670 l var val)
4671 (while (setq l (pop opts))
4672 (when (setq l (assoc l org-startup-options))
4673 (setq var (nth 1 l) val (nth 2 l))
4674 (if (not (nth 3 l))
4675 (set (make-local-variable var) val)
4676 (if (not (listp (symbol-value var)))
4677 (set (make-local-variable var) nil))
4678 (set (make-local-variable var) (symbol-value var))
4679 (add-to-list var val))))))
4680 ((equal key "ARCHIVE")
4681 (setq arch value)
4682 (remove-text-properties 0 (length arch)
4683 '(face t fontified t) arch))
4684 ((equal key "LATEX_CLASS")
4685 (setq beamer-p (equal value "beamer")))
4686 ((equal key "OPTIONS")
4687 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4688 (setq scripts (read (match-string 2 value)))))
4689 ((equal key "SETUPFILE")
4690 (setq setup-contents (org-file-contents
4691 (expand-file-name
4692 (org-remove-double-quotes value))
4693 'noerror))
4694 (if (not ext-setup-or-nil)
4695 (setq ext-setup-or-nil setup-contents start 0)
4696 (setq ext-setup-or-nil
4697 (concat (substring ext-setup-or-nil 0 start)
4698 "\n" setup-contents "\n"
4699 (substring ext-setup-or-nil start)))))))
4700 ;; search for property blocks
4701 (goto-char (point-min))
4702 (while (re-search-forward org-block-regexp nil t)
4703 (when (equal "PROPERTY" (upcase (match-string 1)))
4704 (setq value (replace-regexp-in-string
4705 "[\n\r]" " " (match-string 4)))
4706 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4707 (setq props (org-update-property-plist (match-string 1 value)
4708 (match-string 2 value)
4709 props)))))))
4710 (org-set-local 'org-use-sub-superscripts scripts)
4711 (when cat
4712 (org-set-local 'org-category (intern cat))
4713 (push (cons "CATEGORY" cat) props))
4714 (when prio
4715 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4716 (setq prio (mapcar 'string-to-char prio))
4717 (org-set-local 'org-highest-priority (nth 0 prio))
4718 (org-set-local 'org-lowest-priority (nth 1 prio))
4719 (org-set-local 'org-default-priority (nth 2 prio)))
4720 (and props (org-set-local 'org-file-properties (nreverse props)))
4721 (and ftags (org-set-local 'org-file-tags
4722 (mapcar 'org-add-prop-inherited ftags)))
4723 (and drawers (org-set-local 'org-drawers drawers))
4724 (and arch (org-set-local 'org-archive-location arch))
4725 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4726 ;; Process the TODO keywords
4727 (unless kwds
4728 ;; Use the global values as if they had been given locally.
4729 (setq kwds (default-value 'org-todo-keywords))
4730 (if (stringp (car kwds))
4731 (setq kwds (list (cons org-todo-interpretation
4732 (default-value 'org-todo-keywords)))))
4733 (setq kwds (reverse kwds)))
4734 (setq kwds (nreverse kwds))
4735 (let (inter kws kw)
4736 (while (setq kws (pop kwds))
4737 (let ((kws (or
4738 (run-hook-with-args-until-success
4739 'org-todo-setup-filter-hook kws)
4740 kws)))
4741 (setq inter (pop kws) sep (member "|" kws)
4742 kws0 (delete "|" (copy-sequence kws))
4743 kwsa nil
4744 kws1 (mapcar
4745 (lambda (x)
4746 ;; 1 2
4747 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4748 (progn
4749 (setq kw (match-string 1 x)
4750 key (and (match-end 2) (match-string 2 x))
4751 log (org-extract-log-state-settings x))
4752 (push (cons kw (and key (string-to-char key))) kwsa)
4753 (and log (push log org-todo-log-states))
4755 (error "Invalid TODO keyword %s" x)))
4756 kws0)
4757 kwsa (if kwsa (append '((:startgroup))
4758 (nreverse kwsa)
4759 '((:endgroup))))
4760 hw (car kws1)
4761 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4762 tail (list inter hw (car dws) (org-last dws))))
4763 (add-to-list 'org-todo-heads hw 'append)
4764 (push kws1 org-todo-sets)
4765 (setq org-done-keywords (append org-done-keywords dws nil))
4766 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4767 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4768 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4769 (setq org-todo-sets (nreverse org-todo-sets)
4770 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4771 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4772 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4773 ;; Process the constants
4774 (when const
4775 (let (e cst)
4776 (while (setq e (pop const))
4777 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4778 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4779 (setq org-table-formula-constants-local cst)))
4781 ;; Process the tags.
4782 (when tags
4783 (let (e tgs)
4784 (while (setq e (pop tags))
4785 (cond
4786 ((equal e "{") (push '(:startgroup) tgs))
4787 ((equal e "}") (push '(:endgroup) tgs))
4788 ((equal e "\\n") (push '(:newline) tgs))
4789 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4790 (push (cons (match-string 1 e)
4791 (string-to-char (match-string 2 e)))
4792 tgs))
4793 (t (push (list e) tgs))))
4794 (org-set-local 'org-tag-alist nil)
4795 (while (setq e (pop tgs))
4796 (or (and (stringp (car e))
4797 (assoc (car e) org-tag-alist))
4798 (push e org-tag-alist)))))
4800 ;; Compute the regular expressions and other local variables.
4801 ;; Using `org-outline-regexp-bol' would complicate them much,
4802 ;; because of the fixed white space at the end of that string.
4803 (if (not org-done-keywords)
4804 (setq org-done-keywords (and org-todo-keywords-1
4805 (list (org-last org-todo-keywords-1)))))
4806 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4807 (length org-scheduled-string)
4808 (length org-clock-string)
4809 (length org-closed-string)))
4810 org-drawer-regexp
4811 (concat "^[ \t]*:\\("
4812 (mapconcat 'regexp-quote org-drawers "\\|")
4813 "\\):[ \t]*$")
4814 org-not-done-keywords
4815 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4816 org-todo-regexp
4817 (concat "\\("
4818 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4819 "\\)")
4820 org-not-done-regexp
4821 (concat "\\("
4822 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4823 "\\)")
4824 org-not-done-heading-regexp
4825 (format org-heading-keyword-regexp-format org-not-done-regexp)
4826 org-todo-line-regexp
4827 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4828 org-complex-heading-regexp
4829 (concat "^\\(\\*+\\)"
4830 "\\(?: +" org-todo-regexp "\\)?"
4831 "\\(?: +\\(\\[#.\\]\\)\\)?"
4832 "\\(?: +\\(.*?\\)\\)??"
4833 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4834 "[ \t]*$")
4835 org-complex-heading-regexp-format
4836 (concat "^\\(\\*+\\)"
4837 "\\(?: +" org-todo-regexp "\\)?"
4838 "\\(?: +\\(\\[#.\\]\\)\\)?"
4839 "\\(?: +"
4840 ;; Stats cookies can be stuck to body.
4841 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4842 "\\(%s\\)"
4843 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4844 "\\)"
4845 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4846 "[ \t]*$")
4847 org-todo-line-tags-regexp
4848 (concat "^\\(\\*+\\)"
4849 "\\(?: +" org-todo-regexp "\\)?"
4850 "\\(?: +\\(.*?\\)\\)??"
4851 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4852 "[ \t]*$")
4853 org-deadline-regexp (concat "\\<" org-deadline-string)
4854 org-deadline-time-regexp
4855 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4856 org-deadline-line-regexp
4857 (concat "\\<\\(" org-deadline-string "\\).*")
4858 org-scheduled-regexp
4859 (concat "\\<" org-scheduled-string)
4860 org-scheduled-time-regexp
4861 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4862 org-closed-time-regexp
4863 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4864 org-keyword-time-regexp
4865 (concat "\\<\\(" org-scheduled-string
4866 "\\|" org-deadline-string
4867 "\\|" org-closed-string
4868 "\\|" org-clock-string "\\)"
4869 " *[[<]\\([^]>]+\\)[]>]")
4870 org-keyword-time-not-clock-regexp
4871 (concat "\\<\\(" org-scheduled-string
4872 "\\|" org-deadline-string
4873 "\\|" org-closed-string
4874 "\\)"
4875 " *[[<]\\([^]>]+\\)[]>]")
4876 org-maybe-keyword-time-regexp
4877 (concat "\\(\\<\\(" org-scheduled-string
4878 "\\|" org-deadline-string
4879 "\\|" org-closed-string
4880 "\\|" org-clock-string "\\)\\)?"
4881 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4882 org-all-time-keywords
4883 (mapcar (lambda (w) (substring w 0 -1))
4884 (list org-scheduled-string org-deadline-string
4885 org-clock-string org-closed-string))
4887 (org-compute-latex-and-specials-regexp)
4888 (org-set-font-lock-defaults))))
4890 (defun org-file-contents (file &optional noerror)
4891 "Return the contents of FILE, as a string."
4892 (if (or (not file)
4893 (not (file-readable-p file)))
4894 (if noerror
4895 (progn
4896 (message "Cannot read file \"%s\"" file)
4897 (ding) (sit-for 2)
4899 (error "Cannot read file \"%s\"" file))
4900 (with-temp-buffer
4901 (insert-file-contents file)
4902 (buffer-string))))
4904 (defun org-extract-log-state-settings (x)
4905 "Extract the log state setting from a TODO keyword string.
4906 This will extract info from a string like \"WAIT(w@/!)\"."
4907 (let (kw key log1 log2)
4908 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4909 (setq kw (match-string 1 x)
4910 key (and (match-end 2) (match-string 2 x))
4911 log1 (and (match-end 3) (match-string 3 x))
4912 log2 (and (match-end 4) (match-string 4 x)))
4913 (and (or log1 log2)
4914 (list kw
4915 (and log1 (if (equal log1 "!") 'time 'note))
4916 (and log2 (if (equal log2 "!") 'time 'note)))))))
4918 (defun org-remove-keyword-keys (list)
4919 "Remove a pair of parenthesis at the end of each string in LIST."
4920 (mapcar (lambda (x)
4921 (if (string-match "(.*)$" x)
4922 (substring x 0 (match-beginning 0))
4924 list))
4926 (defun org-assign-fast-keys (alist)
4927 "Assign fast keys to a keyword-key alist.
4928 Respect keys that are already there."
4929 (let (new e (alt ?0))
4930 (while (setq e (pop alist))
4931 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4932 (cdr e)) ;; Key already assigned.
4933 (push e new)
4934 (let ((clist (string-to-list (downcase (car e))))
4935 (used (append new alist)))
4936 (when (= (car clist) ?@)
4937 (pop clist))
4938 (while (and clist (rassoc (car clist) used))
4939 (pop clist))
4940 (unless clist
4941 (while (rassoc alt used)
4942 (incf alt)))
4943 (push (cons (car e) (or (car clist) alt)) new))))
4944 (nreverse new)))
4946 ;;; Some variables used in various places
4948 (defvar org-window-configuration nil
4949 "Used in various places to store a window configuration.")
4950 (defvar org-selected-window nil
4951 "Used in various places to store a window configuration.")
4952 (defvar org-finish-function nil
4953 "Function to be called when `C-c C-c' is used.
4954 This is for getting out of special buffers like capture.")
4957 ;; FIXME: Occasionally check by commenting these, to make sure
4958 ;; no other functions uses these, forgetting to let-bind them.
4959 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4960 (defvar org-last-state)
4961 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4963 ;; Defined somewhere in this file, but used before definition.
4964 (defvar org-entities) ;; defined in org-entities.el
4965 (defvar org-struct-menu)
4966 (defvar org-org-menu)
4967 (defvar org-tbl-menu)
4969 ;;;; Define the Org-mode
4971 ;; We use a before-change function to check if a table might need
4972 ;; an update.
4973 (defvar org-table-may-need-update t
4974 "Indicates that a table might need an update.
4975 This variable is set by `org-before-change-function'.
4976 `org-table-align' sets it back to nil.")
4977 (defun org-before-change-function (beg end)
4978 "Every change indicates that a table might need an update."
4979 (setq org-table-may-need-update t))
4980 (defvar org-mode-map)
4981 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4982 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4983 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4984 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4985 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4986 (defvar org-table-buffer-is-an nil)
4988 (defvar bidi-paragraph-direction)
4989 (defvar buffer-face-mode-face)
4991 (require 'outline)
4992 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4993 (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"))
4994 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4996 ;; Other stuff we need.
4997 (require 'time-date)
4998 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4999 (require 'easymenu)
5000 (require 'overlay)
5002 ;; (require 'org-macs) moved higher up in the file before it is first used
5003 (require 'org-entities)
5004 ;; (require 'org-compat) moved higher up in the file before it is first used
5005 (require 'org-faces)
5006 (require 'org-list)
5007 (require 'org-pcomplete)
5008 (require 'org-src)
5009 (require 'org-footnote)
5011 ;; babel
5012 (require 'ob)
5014 ;;;###autoload
5015 (define-derived-mode org-mode outline-mode "Org"
5016 "Outline-based notes management and organizer, alias
5017 \"Carsten's outline-mode for keeping track of everything.\"
5019 Org-mode develops organizational tasks around a NOTES file which
5020 contains information about projects as plain text. Org-mode is
5021 implemented on top of outline-mode, which is ideal to keep the content
5022 of large files well structured. It supports ToDo items, deadlines and
5023 time stamps, which magically appear in the diary listing of the Emacs
5024 calendar. Tables are easily created with a built-in table editor.
5025 Plain text URL-like links connect to websites, emails (VM), Usenet
5026 messages (Gnus), BBDB entries, and any files related to the project.
5027 For printing and sharing of notes, an Org-mode file (or a part of it)
5028 can be exported as a structured ASCII or HTML file.
5030 The following commands are available:
5032 \\{org-mode-map}"
5034 ;; Get rid of Outline menus, they are not needed
5035 ;; Need to do this here because define-derived-mode sets up
5036 ;; the keymap so late. Still, it is a waste to call this each time
5037 ;; we switch another buffer into org-mode.
5038 (if (featurep 'xemacs)
5039 (when (boundp 'outline-mode-menu-heading)
5040 ;; Assume this is Greg's port, it uses easymenu
5041 (easy-menu-remove outline-mode-menu-heading)
5042 (easy-menu-remove outline-mode-menu-show)
5043 (easy-menu-remove outline-mode-menu-hide))
5044 (define-key org-mode-map [menu-bar headings] 'undefined)
5045 (define-key org-mode-map [menu-bar hide] 'undefined)
5046 (define-key org-mode-map [menu-bar show] 'undefined))
5048 (org-load-modules-maybe)
5049 (easy-menu-add org-org-menu)
5050 (easy-menu-add org-tbl-menu)
5051 (org-install-agenda-files-menu)
5052 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5053 (add-to-invisibility-spec '(org-cwidth))
5054 (add-to-invisibility-spec '(org-hide-block . t))
5055 (when (featurep 'xemacs)
5056 (org-set-local 'line-move-ignore-invisible t))
5057 (org-set-local 'outline-regexp org-outline-regexp)
5058 (org-set-local 'outline-level 'org-outline-level)
5059 (setq bidi-paragraph-direction 'left-to-right)
5060 (when (and org-ellipsis
5061 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5062 (fboundp 'make-glyph-code))
5063 (unless org-display-table
5064 (setq org-display-table (make-display-table)))
5065 (set-display-table-slot
5066 org-display-table 4
5067 (vconcat (mapcar
5068 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5069 org-ellipsis)))
5070 (if (stringp org-ellipsis) org-ellipsis "..."))))
5071 (setq buffer-display-table org-display-table))
5072 (org-set-regexps-and-options)
5073 (when (and org-tag-faces (not org-tags-special-faces-re))
5074 ;; tag faces set outside customize.... force initialization.
5075 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5076 ;; Calc embedded
5077 (org-set-local 'calc-embedded-open-mode "# ")
5078 (modify-syntax-entry ?@ "w")
5079 (modify-syntax-entry ?\" "\"")
5080 (if org-startup-truncated (setq truncate-lines t))
5081 (org-set-local 'font-lock-unfontify-region-function
5082 'org-unfontify-region)
5083 ;; Activate before-change-function
5084 (org-set-local 'org-table-may-need-update t)
5085 (org-add-hook 'before-change-functions 'org-before-change-function nil
5086 'local)
5087 ;; Check for running clock before killing a buffer
5088 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5089 ;; Initialize macros templates.
5090 (org-macro-initialize-templates)
5091 ;; Initialize radio targets.
5092 (org-update-radio-target-regexp)
5093 ;; Indentation.
5094 (org-set-local 'indent-line-function 'org-indent-line)
5095 (org-set-local 'indent-region-function 'org-indent-region)
5096 ;; Filling and auto-filling.
5097 (org-setup-filling)
5098 ;; Comments.
5099 (org-setup-comments-handling)
5100 ;; Beginning/end of defun
5101 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5102 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5103 ;; Next error for sparse trees
5104 (org-set-local 'next-error-function 'org-occur-next-match)
5105 ;; Make sure dependence stuff works reliably, even for users who set it
5106 ;; too late :-(
5107 (if org-enforce-todo-dependencies
5108 (add-hook 'org-blocker-hook
5109 'org-block-todo-from-children-or-siblings-or-parent)
5110 (remove-hook 'org-blocker-hook
5111 'org-block-todo-from-children-or-siblings-or-parent))
5112 (if org-enforce-todo-checkbox-dependencies
5113 (add-hook 'org-blocker-hook
5114 'org-block-todo-from-checkboxes)
5115 (remove-hook 'org-blocker-hook
5116 'org-block-todo-from-checkboxes))
5118 ;; Align options lines
5119 (org-set-local
5120 'align-mode-rules-list
5121 '((org-in-buffer-settings
5122 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5123 (modes . '(org-mode)))))
5125 ;; Imenu
5126 (org-set-local 'imenu-create-index-function
5127 'org-imenu-get-tree)
5129 ;; Make isearch reveal context
5130 (if (or (featurep 'xemacs)
5131 (not (boundp 'outline-isearch-open-invisible-function)))
5132 ;; Emacs 21 and XEmacs make use of the hook
5133 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5134 ;; Emacs 22 deals with this through a special variable
5135 (org-set-local 'outline-isearch-open-invisible-function
5136 (lambda (&rest ignore) (org-show-context 'isearch))))
5138 ;; Setup the pcomplete hooks
5139 (set (make-local-variable 'pcomplete-command-completion-function)
5140 'org-pcomplete-initial)
5141 (set (make-local-variable 'pcomplete-command-name-function)
5142 'org-command-at-point)
5143 (set (make-local-variable 'pcomplete-default-completion-function)
5144 'ignore)
5145 (set (make-local-variable 'pcomplete-parse-arguments-function)
5146 'org-parse-arguments)
5147 (set (make-local-variable 'pcomplete-termination-string) "")
5148 (when (>= emacs-major-version 23)
5149 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5151 ;; If empty file that did not turn on org-mode automatically, make it to.
5152 (if (and org-insert-mode-line-in-empty-file
5153 (org-called-interactively-p 'any)
5154 (= (point-min) (point-max)))
5155 (insert "# -*- mode: org -*-\n\n"))
5156 (unless org-inhibit-startup
5157 (and org-startup-with-beamer-mode (org-beamer-mode))
5158 (when org-startup-align-all-tables
5159 (let ((bmp (buffer-modified-p)))
5160 (org-table-map-tables 'org-table-align 'quietly)
5161 (set-buffer-modified-p bmp)))
5162 (when org-startup-with-inline-images
5163 (org-display-inline-images))
5164 (when org-startup-indented
5165 (require 'org-indent)
5166 (org-indent-mode 1))
5167 (unless org-inhibit-startup-visibility-stuff
5168 (org-set-startup-visibility)))
5169 ;; Try to set org-hide correctly
5170 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5172 (when (fboundp 'abbrev-table-put)
5173 (abbrev-table-put org-mode-abbrev-table
5174 :parents (list text-mode-abbrev-table)))
5176 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5179 (defun org-find-invisible-foreground ()
5180 (let ((candidates (remove
5181 "unspecified-bg"
5182 (nconc
5183 (list (face-background 'default)
5184 (face-background 'org-default))
5185 (mapcar
5186 (lambda (alist)
5187 (when (boundp alist)
5188 (cdr (assoc 'background-color (symbol-value alist)))))
5189 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5190 (list (face-foreground 'org-hide))))))
5191 (car (remove nil candidates))))
5193 (defun org-current-time (&optional rounding-minutes)
5194 "Current time, possibly rounded to ROUNDING-MINUTES.
5195 When ROUNDING-MINUTES is not an integer, fall back on the car of
5196 `org-time-stamp-rounding-minutes'."
5197 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5198 (car org-time-stamp-rounding-minutes)))
5199 (time (decode-time)))
5200 (if (> r 1)
5201 (apply 'encode-time
5202 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5203 (nthcdr 2 time)))
5204 (current-time))))
5206 (defun org-today ()
5207 "Return today date, considering `org-extend-today-until'."
5208 (time-to-days
5209 (time-subtract (current-time)
5210 (list 0 (* 3600 org-extend-today-until) 0))))
5212 ;;;; Font-Lock stuff, including the activators
5214 (defvar org-mouse-map (make-sparse-keymap))
5215 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5216 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5217 (when org-mouse-1-follows-link
5218 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5219 (when org-tab-follows-link
5220 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5221 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5223 (require 'font-lock)
5225 (defconst org-non-link-chars "]\t\n\r<>")
5226 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5227 "shell" "elisp" "doi" "message"))
5228 (defvar org-link-types-re nil
5229 "Matches a link that has a url-like prefix like \"http:\"")
5230 (defvar org-link-re-with-space nil
5231 "Matches a link with spaces, optional angular brackets around it.")
5232 (defvar org-link-re-with-space2 nil
5233 "Matches a link with spaces, optional angular brackets around it.")
5234 (defvar org-link-re-with-space3 nil
5235 "Matches a link with spaces, only for internal part in bracket links.")
5236 (defvar org-angle-link-re nil
5237 "Matches link with angular brackets, spaces are allowed.")
5238 (defvar org-plain-link-re nil
5239 "Matches plain link, without spaces.")
5240 (defvar org-bracket-link-regexp nil
5241 "Matches a link in double brackets.")
5242 (defvar org-bracket-link-analytic-regexp nil
5243 "Regular expression used to analyze links.
5244 Here is what the match groups contain after a match:
5245 1: http:
5246 2: http
5247 3: path
5248 4: [desc]
5249 5: desc")
5250 (defvar org-bracket-link-analytic-regexp++ nil
5251 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5252 (defvar org-any-link-re nil
5253 "Regular expression matching any link.")
5255 (defcustom org-match-sexp-depth 3
5256 "Number of stacked braces for sub/superscript matching.
5257 This has to be set before loading org.el to be effective."
5258 :group 'org-export-translation ; ??????????????????????????/
5259 :type 'integer)
5261 (defun org-create-multibrace-regexp (left right n)
5262 "Create a regular expression which will match a balanced sexp.
5263 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5264 as single character strings.
5265 The regexp returned will match the entire expression including the
5266 delimiters. It will also define a single group which contains the
5267 match except for the outermost delimiters. The maximum depth of
5268 stacked delimiters is N. Escaping delimiters is not possible."
5269 (let* ((nothing (concat "[^" left right "]*?"))
5270 (or "\\|")
5271 (re nothing)
5272 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5273 (while (> n 1)
5274 (setq n (1- n)
5275 re (concat re or next)
5276 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5277 (concat left "\\(" re "\\)" right)))
5279 (defvar org-match-substring-regexp
5280 (concat
5281 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5282 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5283 "\\|"
5284 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5285 "\\|"
5286 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5287 "The regular expression matching a sub- or superscript.")
5289 (defvar org-match-substring-with-braces-regexp
5290 (concat
5291 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5292 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5293 "\\)")
5294 "The regular expression matching a sub- or superscript, forcing braces.")
5296 (defun org-make-link-regexps ()
5297 "Update the link regular expressions.
5298 This should be called after the variable `org-link-types' has changed."
5299 (setq org-link-types-re
5300 (concat
5301 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5302 org-link-re-with-space
5303 (concat
5304 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5305 "\\([^" org-non-link-chars " ]"
5306 "[^" org-non-link-chars "]*"
5307 "[^" org-non-link-chars " ]\\)>?")
5308 org-link-re-with-space2
5309 (concat
5310 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5311 "\\([^" org-non-link-chars " ]"
5312 "[^\t\n\r]*"
5313 "[^" org-non-link-chars " ]\\)>?")
5314 org-link-re-with-space3
5315 (concat
5316 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5317 "\\([^" org-non-link-chars " ]"
5318 "[^\t\n\r]*\\)")
5319 org-angle-link-re
5320 (concat
5321 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5322 "\\([^" org-non-link-chars " ]"
5323 "[^" org-non-link-chars "]*"
5324 "\\)>")
5325 org-plain-link-re
5326 (concat
5327 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5328 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5329 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5330 org-bracket-link-regexp
5331 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5332 org-bracket-link-analytic-regexp
5333 (concat
5334 "\\[\\["
5335 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5336 "\\([^]]+\\)"
5337 "\\]"
5338 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5339 "\\]")
5340 org-bracket-link-analytic-regexp++
5341 (concat
5342 "\\[\\["
5343 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5344 "\\([^]]+\\)"
5345 "\\]"
5346 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5347 "\\]")
5348 org-any-link-re
5349 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5350 org-angle-link-re "\\)\\|\\("
5351 org-plain-link-re "\\)")))
5353 (org-make-link-regexps)
5355 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5356 "Regular expression for fast time stamp matching.")
5357 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5358 "Regular expression for fast time stamp matching.")
5359 (defconst org-ts-regexp0
5360 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5361 "Regular expression matching time strings for analysis.
5362 This one does not require the space after the date, so it can be used
5363 on a string that terminates immediately after the date.")
5364 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5365 "Regular expression matching time strings for analysis.")
5366 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5367 "Regular expression matching time stamps, with groups.")
5368 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5369 "Regular expression matching time stamps (also [..]), with groups.")
5370 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5371 "Regular expression matching a time stamp range.")
5372 (defconst org-tr-regexp-both
5373 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5374 "Regular expression matching a time stamp range.")
5375 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5376 org-ts-regexp "\\)?")
5377 "Regular expression matching a time stamp or time stamp range.")
5378 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5379 org-ts-regexp-both "\\)?")
5380 "Regular expression matching a time stamp or time stamp range.
5381 The time stamps may be either active or inactive.")
5383 (defvar org-emph-face nil)
5385 (defun org-do-emphasis-faces (limit)
5386 "Run through the buffer and add overlays to emphasized strings."
5387 (let (rtn a)
5388 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5389 (if (not (= (char-after (match-beginning 3))
5390 (char-after (match-beginning 4))))
5391 (progn
5392 (setq rtn t)
5393 (setq a (assoc (match-string 3) org-emphasis-alist))
5394 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5395 'face
5396 (nth 1 a))
5397 (and (nth 4 a)
5398 (org-remove-flyspell-overlays-in
5399 (match-beginning 0) (match-end 0)))
5400 (add-text-properties (match-beginning 2) (match-end 2)
5401 '(font-lock-multiline t org-emphasis t))
5402 (when org-hide-emphasis-markers
5403 (add-text-properties (match-end 4) (match-beginning 5)
5404 '(invisible org-link))
5405 (add-text-properties (match-beginning 3) (match-end 3)
5406 '(invisible org-link)))))
5407 (backward-char 1))
5408 rtn))
5410 (defun org-emphasize (&optional char)
5411 "Insert or change an emphasis, i.e. a font like bold or italic.
5412 If there is an active region, change that region to a new emphasis.
5413 If there is no region, just insert the marker characters and position
5414 the cursor between them.
5415 CHAR should be either the marker character, or the first character of the
5416 HTML tag associated with that emphasis. If CHAR is a space, the means
5417 to remove the emphasis of the selected region.
5418 If char is not given (for example in an interactive call) it
5419 will be prompted for."
5420 (interactive)
5421 (let ((eal org-emphasis-alist) e det
5422 (erc org-emphasis-regexp-components)
5423 (prompt "")
5424 (string "") beg end move tag c s)
5425 (if (org-region-active-p)
5426 (setq beg (region-beginning) end (region-end)
5427 string (buffer-substring beg end))
5428 (setq move t))
5430 (while (setq e (pop eal))
5431 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5432 c (aref tag 0))
5433 (push (cons c (string-to-char (car e))) det)
5434 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5435 (substring tag 1)))))
5436 (setq det (nreverse det))
5437 (unless char
5438 (message "%s" (concat "Emphasis marker or tag:" prompt))
5439 (setq char (read-char-exclusive)))
5440 (setq char (or (cdr (assoc char det)) char))
5441 (if (equal char ?\ )
5442 (setq s "" move nil)
5443 (unless (assoc (char-to-string char) org-emphasis-alist)
5444 (error "No such emphasis marker: \"%c\"" char))
5445 (setq s (char-to-string char)))
5446 (while (and (> (length string) 1)
5447 (equal (substring string 0 1) (substring string -1))
5448 (assoc (substring string 0 1) org-emphasis-alist))
5449 (setq string (substring string 1 -1)))
5450 (setq string (concat s string s))
5451 (if beg (delete-region beg end))
5452 (unless (or (bolp)
5453 (string-match (concat "[" (nth 0 erc) "\n]")
5454 (char-to-string (char-before (point)))))
5455 (insert " "))
5456 (unless (or (eobp)
5457 (string-match (concat "[" (nth 1 erc) "\n]")
5458 (char-to-string (char-after (point)))))
5459 (insert " ") (backward-char 1))
5460 (insert string)
5461 (and move (backward-char 1))))
5463 (defconst org-nonsticky-props
5464 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5466 (defsubst org-rear-nonsticky-at (pos)
5467 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5469 (defun org-activate-plain-links (limit)
5470 "Run through the buffer and add overlays to links."
5471 (catch 'exit
5472 (let (f hl)
5473 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5474 (not (org-in-src-block-p)))
5475 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5476 (setq f (get-text-property (match-beginning 0) 'face))
5477 (setq hl (org-match-string-no-properties 0))
5478 (if (or (eq f 'org-tag)
5479 (and (listp f) (memq 'org-tag f)))
5481 (add-text-properties (match-beginning 0) (match-end 0)
5482 (list 'mouse-face 'highlight
5483 'face 'org-link
5484 'htmlize-link `(:uri ,hl)
5485 'keymap org-mouse-map))
5486 (org-rear-nonsticky-at (match-end 0)))
5487 t))))
5489 (defun org-activate-code (limit)
5490 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5491 (progn
5492 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5493 (remove-text-properties (match-beginning 0) (match-end 0)
5494 '(display t invisible t intangible t))
5495 t)))
5497 (defcustom org-src-fontify-natively nil
5498 "When non-nil, fontify code in code blocks."
5499 :type 'boolean
5500 :version "24.1"
5501 :group 'org-appearance
5502 :group 'org-babel)
5504 (defcustom org-allow-promoting-top-level-subtree nil
5505 "When non-nil, allow promoting a top level subtree.
5506 The leading star of the top level headline will be replaced
5507 by a #."
5508 :type 'boolean
5509 :version "24.1"
5510 :group 'org-appearance)
5512 (defun org-fontify-meta-lines-and-blocks (limit)
5513 (condition-case nil
5514 (org-fontify-meta-lines-and-blocks-1 limit)
5515 (error (message "org-mode fontification error"))))
5517 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5518 "Fontify #+ lines and blocks, in the correct ways."
5519 (let ((case-fold-search t))
5520 (if (re-search-forward
5521 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5522 limit t)
5523 (let ((beg (match-beginning 0))
5524 (block-start (match-end 0))
5525 (block-end nil)
5526 (lang (match-string 7))
5527 (beg1 (line-beginning-position 2))
5528 (dc1 (downcase (match-string 2)))
5529 (dc3 (downcase (match-string 3)))
5530 end end1 quoting block-type ovl)
5531 (cond
5532 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5533 ;; a single line of backend-specific content
5534 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5535 (remove-text-properties (match-beginning 0) (match-end 0)
5536 '(display t invisible t intangible t))
5537 (add-text-properties (match-beginning 1) (match-end 3)
5538 '(font-lock-fontified t face org-meta-line))
5539 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5540 '(font-lock-fontified t face org-block))
5541 ; for backend-specific code
5543 ((and (match-end 4) (equal dc3 "+begin"))
5544 ;; Truly a block
5545 (setq block-type (downcase (match-string 5))
5546 quoting (member block-type org-protecting-blocks))
5547 (when (re-search-forward
5548 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5549 nil t) ;; on purpose, we look further than LIMIT
5550 (setq end (min (point-max) (match-end 0))
5551 end1 (min (point-max) (1- (match-beginning 0))))
5552 (setq block-end (match-beginning 0))
5553 (when quoting
5554 (remove-text-properties beg end
5555 '(display t invisible t intangible t)))
5556 (add-text-properties
5557 beg end
5558 '(font-lock-fontified t font-lock-multiline t))
5559 (add-text-properties beg beg1 '(face org-meta-line))
5560 (add-text-properties end1 (min (point-max) (1+ end))
5561 '(face org-meta-line)) ; for end_src
5562 (cond
5563 ((and lang (not (string= lang "")) org-src-fontify-natively)
5564 (org-src-font-lock-fontify-block lang block-start block-end)
5565 ;; remove old background overlays
5566 (mapc (lambda (ov)
5567 (if (eq (overlay-get ov 'face) 'org-block-background)
5568 (delete-overlay ov)))
5569 (overlays-at (/ (+ beg1 block-end) 2)))
5570 ;; add a background overlay
5571 (setq ovl (make-overlay beg1 block-end))
5572 (overlay-put ovl 'face 'org-block-background)
5573 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5574 (quoting
5575 (add-text-properties beg1 (min (point-max) (1+ end1))
5576 '(face org-block))) ; end of source block
5577 ((not org-fontify-quote-and-verse-blocks))
5578 ((string= block-type "quote")
5579 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5580 ((string= block-type "verse")
5581 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5582 (add-text-properties beg beg1 '(face org-block-begin-line))
5583 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5584 '(face org-block-end-line))
5586 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5587 (add-text-properties
5588 beg (match-end 3)
5589 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5590 '(font-lock-fontified t invisible t)
5591 '(font-lock-fontified t face org-document-info-keyword)))
5592 (add-text-properties
5593 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5594 (if (string-equal dc1 "+title:")
5595 '(font-lock-fontified t face org-document-title)
5596 '(font-lock-fontified t face org-document-info))))
5597 ((or (equal dc1 "+results")
5598 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5599 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5600 "+call:" "+header:" "+headers:" "+name:"))
5601 (and (match-end 4) (equal dc3 "+attr")))
5602 (add-text-properties
5603 beg (match-end 0)
5604 '(font-lock-fontified t face org-meta-line))
5606 ((member dc3 '(" " ""))
5607 (add-text-properties
5608 beg (match-end 0)
5609 '(font-lock-fontified t face font-lock-comment-face)))
5610 ((not (member (char-after beg) '(?\ ?\t)))
5611 ;; just any other in-buffer setting, but not indented
5612 (add-text-properties
5613 beg (match-end 0)
5614 '(font-lock-fontified t face org-meta-line))
5616 (t nil))))))
5618 (defun org-activate-angle-links (limit)
5619 "Run through the buffer and add overlays to links."
5620 (if (and (re-search-forward org-angle-link-re limit t)
5621 (not (org-in-src-block-p)))
5622 (progn
5623 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5624 (add-text-properties (match-beginning 0) (match-end 0)
5625 (list 'mouse-face 'highlight
5626 'keymap org-mouse-map))
5627 (org-rear-nonsticky-at (match-end 0))
5628 t)))
5630 (defun org-activate-footnote-links (limit)
5631 "Run through the buffer and add overlays to footnotes."
5632 (let ((fn (org-footnote-next-reference-or-definition limit)))
5633 (when fn
5634 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5635 (org-remove-flyspell-overlays-in beg end)
5636 (add-text-properties beg end
5637 (list 'mouse-face 'highlight
5638 'keymap org-mouse-map
5639 'help-echo
5640 (if (= (point-at-bol) beg)
5641 "Footnote definition"
5642 "Footnote reference")
5643 'font-lock-fontified t
5644 'font-lock-multiline t
5645 'face 'org-footnote))))))
5647 (defun org-activate-bracket-links (limit)
5648 "Run through the buffer and add overlays to bracketed links."
5649 (if (and (re-search-forward org-bracket-link-regexp limit t)
5650 (not (org-in-src-block-p)))
5651 (let* ((hl (org-match-string-no-properties 1))
5652 (help (concat "LINK: " hl))
5653 ;; FIXME: Above we should remove the escapes. But that
5654 ;; requires another match, protecting match data, a lot
5655 ;; of overhead for font-lock.
5656 (ip (org-maybe-intangible
5657 (list 'invisible 'org-link
5658 'keymap org-mouse-map 'mouse-face 'highlight
5659 'font-lock-multiline t 'help-echo help
5660 'htmlize-link `(:uri ,hl))))
5661 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5662 'font-lock-multiline t 'help-echo help
5663 'htmlize-link `(:uri ,hl))))
5664 ;; We need to remove the invisible property here. Table narrowing
5665 ;; may have made some of this invisible.
5666 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5667 (remove-text-properties (match-beginning 0) (match-end 0)
5668 '(invisible nil))
5669 (if (match-end 3)
5670 (progn
5671 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5672 (org-rear-nonsticky-at (match-beginning 3))
5673 (add-text-properties (match-beginning 3) (match-end 3) vp)
5674 (org-rear-nonsticky-at (match-end 3))
5675 (add-text-properties (match-end 3) (match-end 0) ip)
5676 (org-rear-nonsticky-at (match-end 0)))
5677 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5678 (org-rear-nonsticky-at (match-beginning 1))
5679 (add-text-properties (match-beginning 1) (match-end 1) vp)
5680 (org-rear-nonsticky-at (match-end 1))
5681 (add-text-properties (match-end 1) (match-end 0) ip)
5682 (org-rear-nonsticky-at (match-end 0)))
5683 t)))
5685 (defun org-activate-dates (limit)
5686 "Run through the buffer and add overlays to dates."
5687 (if (re-search-forward org-tsr-regexp-both limit t)
5688 (progn
5689 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5690 (add-text-properties (match-beginning 0) (match-end 0)
5691 (list 'mouse-face 'highlight
5692 'keymap org-mouse-map))
5693 (org-rear-nonsticky-at (match-end 0))
5694 (when org-display-custom-times
5695 (if (match-end 3)
5696 (org-display-custom-time (match-beginning 3) (match-end 3)))
5697 (org-display-custom-time (match-beginning 1) (match-end 1)))
5698 t)))
5700 (defvar org-target-link-regexp nil
5701 "Regular expression matching radio targets in plain text.")
5702 (make-variable-buffer-local 'org-target-link-regexp)
5703 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5704 "Regular expression matching a link target.")
5705 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5706 "Regular expression matching a radio target.")
5707 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5708 "Regular expression matching any target.")
5710 (defun org-activate-target-links (limit)
5711 "Run through the buffer and add overlays to target matches."
5712 (when org-target-link-regexp
5713 (let ((case-fold-search t))
5714 (if (re-search-forward org-target-link-regexp limit t)
5715 (progn
5716 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5717 (add-text-properties (match-beginning 0) (match-end 0)
5718 (list 'mouse-face 'highlight
5719 'keymap org-mouse-map
5720 'help-echo "Radio target link"
5721 'org-linked-text t))
5722 (org-rear-nonsticky-at (match-end 0))
5723 t)))))
5725 (defun org-update-radio-target-regexp ()
5726 "Find all radio targets in this file and update the regular expression."
5727 (interactive)
5728 (when (memq 'radio org-activate-links)
5729 (setq org-target-link-regexp
5730 (org-make-target-link-regexp (org-all-targets 'radio)))
5731 (org-restart-font-lock)))
5733 (defun org-hide-wide-columns (limit)
5734 (let (s e)
5735 (setq s (text-property-any (point) (or limit (point-max))
5736 'org-cwidth t))
5737 (when s
5738 (setq e (next-single-property-change s 'org-cwidth))
5739 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5740 (goto-char e)
5741 t)))
5743 (defvar org-latex-and-specials-regexp nil
5744 "Regular expression for highlighting export special stuff.")
5745 (defvar org-match-substring-regexp)
5746 (defvar org-match-substring-with-braces-regexp)
5748 ;; This should be with the exporter code, but we also use if for font-locking
5749 (defconst org-export-html-special-string-regexps
5750 '(("\\\\-" . "&shy;")
5751 ("---\\([^-]\\)" . "&mdash;\\1")
5752 ("--\\([^-]\\)" . "&ndash;\\1")
5753 ("\\.\\.\\." . "&hellip;"))
5754 "Regular expressions for special string conversion.")
5757 (defun org-compute-latex-and-specials-regexp ()
5758 "Compute regular expression for stuff treated specially by exporters."
5759 (if (not org-highlight-latex-fragments-and-specials)
5760 (org-set-local 'org-latex-and-specials-regexp nil)
5761 (require 'org-exp)
5762 (let*
5763 ((matchers (plist-get org-format-latex-options :matchers))
5764 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5765 org-latex-regexps)))
5766 (org-export-allow-BIND nil)
5767 (options (org-combine-plists (org-default-export-plist)
5768 (org-infile-export-plist)))
5769 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5770 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5771 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5772 (org-export-html-expand (plist-get options :expand-quoted-html))
5773 (org-export-with-special-strings (plist-get options :special-strings))
5774 (re-sub
5775 (cond
5776 ((equal org-export-with-sub-superscripts '{})
5777 (list org-match-substring-with-braces-regexp))
5778 (org-export-with-sub-superscripts
5779 (list org-match-substring-regexp))))
5780 (re-latex
5781 (if org-export-with-LaTeX-fragments
5782 (mapcar (lambda (x) (nth 1 x)) latexs)))
5783 (re-macros
5784 (if org-export-with-TeX-macros
5785 (list (concat "\\\\"
5786 (regexp-opt
5787 (append
5789 (delq nil
5790 (mapcar 'car-safe
5791 (append org-entities-user
5792 org-entities)))
5793 (if (boundp 'org-latex-entities)
5794 (mapcar (lambda (x)
5795 (or (car-safe x) x))
5796 org-latex-entities)
5797 nil))
5798 'words))) ; FIXME
5800 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5801 (re-special (if org-export-with-special-strings
5802 (mapcar (lambda (x) (car x))
5803 org-export-html-special-string-regexps)))
5804 (re-rest
5805 (delq nil
5806 (list
5807 (if org-export-html-expand "@<[^>\n]+>")
5808 ))))
5809 (org-set-local
5810 'org-latex-and-specials-regexp
5811 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5812 re-rest) "\\|")))))
5814 (defun org-do-latex-and-special-faces (limit)
5815 "Run through the buffer and add overlays to links."
5816 (when org-latex-and-specials-regexp
5817 (let (rtn d)
5818 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5819 limit t))
5820 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5821 'face))
5822 '(org-code org-verbatim underline)))
5823 (progn
5824 (setq rtn t
5825 d (cond ((member (char-after (1+ (match-beginning 0)))
5826 '(?_ ?^)) 1)
5827 (t 0)))
5828 (font-lock-prepend-text-property
5829 (+ d (match-beginning 0)) (match-end 0)
5830 'face 'org-latex-and-export-specials)
5831 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5832 '(font-lock-multiline t)))))
5833 rtn)))
5835 (defun org-restart-font-lock ()
5836 "Restart `font-lock-mode', to force refontification."
5837 (when (and (boundp 'font-lock-mode) font-lock-mode)
5838 (font-lock-mode -1)
5839 (font-lock-mode 1)))
5841 (defun org-all-targets (&optional radio)
5842 "Return a list of all targets in this file.
5843 When optional argument RADIO is non-nil, only find radio
5844 targets."
5845 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5846 (save-excursion
5847 (goto-char (point-min))
5848 (while (re-search-forward re nil t)
5849 ;; Make sure point is really within the object.
5850 (backward-char)
5851 (let ((obj (org-element-context)))
5852 (when (memq (org-element-type obj) '(radio-target target))
5853 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5854 rtn)))
5856 (defun org-make-target-link-regexp (targets)
5857 "Make regular expression matching all strings in TARGETS.
5858 The regular expression finds the targets also if there is a line break
5859 between words."
5860 (and targets
5861 (concat
5862 "\\<\\("
5863 (mapconcat
5864 (lambda (x)
5865 (setq x (regexp-quote x))
5866 (while (string-match " +" x)
5867 (setq x (replace-match "\\s-+" t t x)))
5869 targets
5870 "\\|")
5871 "\\)\\>")))
5873 (defun org-activate-tags (limit)
5874 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5875 (progn
5876 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5877 (add-text-properties (match-beginning 1) (match-end 1)
5878 (list 'mouse-face 'highlight
5879 'keymap org-mouse-map))
5880 (org-rear-nonsticky-at (match-end 1))
5881 t)))
5883 (defun org-outline-level ()
5884 "Compute the outline level of the heading at point.
5885 If this is called at a normal headline, the level is the number of stars.
5886 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5887 (save-excursion
5888 (if (not (condition-case nil
5889 (org-back-to-heading t)
5890 (error nil)))
5892 (looking-at org-outline-regexp)
5893 (1- (- (match-end 0) (match-beginning 0))))))
5895 (defvar org-font-lock-keywords nil)
5897 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5898 "Regular expression matching a property line.")
5900 (defvar org-font-lock-hook nil
5901 "Functions to be called for special font lock stuff.")
5903 (defvar org-font-lock-set-keywords-hook nil
5904 "Functions that can manipulate `org-font-lock-extra-keywords'.
5905 This is called after `org-font-lock-extra-keywords' is defined, but before
5906 it is installed to be used by font lock. This can be useful if something
5907 needs to be inserted at a specific position in the font-lock sequence.")
5909 (defun org-font-lock-hook (limit)
5910 "Run `org-font-lock-hook' within LIMIT."
5911 (run-hook-with-args 'org-font-lock-hook limit))
5913 (defun org-set-font-lock-defaults ()
5914 "Set font lock defaults for the current buffer."
5915 (let* ((em org-fontify-emphasized-text)
5916 (lk org-activate-links)
5917 (org-font-lock-extra-keywords
5918 (list
5919 ;; Call the hook
5920 '(org-font-lock-hook)
5921 ;; Headlines
5922 `(,(if org-fontify-whole-heading-line
5923 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5924 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5925 (1 (org-get-level-face 1))
5926 (2 (org-get-level-face 2))
5927 (3 (org-get-level-face 3)))
5928 ;; Table lines
5929 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5930 (1 'org-table t))
5931 ;; Table internals
5932 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5933 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5934 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5935 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5936 ;; Drawers
5937 (list org-drawer-regexp '(0 'org-special-keyword t))
5938 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5939 ;; Properties
5940 (list org-property-re
5941 '(1 'org-special-keyword t)
5942 '(3 'org-property-value t))
5943 ;; Links
5944 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5945 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5946 (if (memq 'plain lk) '(org-activate-plain-links))
5947 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5948 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5949 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5950 (if (memq 'footnote lk) '(org-activate-footnote-links))
5951 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5952 '(org-hide-wide-columns (0 nil append))
5953 ;; TODO keyword
5954 (list (format org-heading-keyword-regexp-format
5955 org-todo-regexp)
5956 '(2 (org-get-todo-face 2) t))
5957 ;; DONE
5958 (if org-fontify-done-headline
5959 (list (format org-heading-keyword-regexp-format
5960 (concat
5961 "\\(?:"
5962 (mapconcat 'regexp-quote org-done-keywords "\\|")
5963 "\\)"))
5964 '(2 'org-headline-done t))
5965 nil)
5966 ;; Priorities
5967 '(org-font-lock-add-priority-faces)
5968 ;; Tags
5969 '(org-font-lock-add-tag-faces)
5970 ;; Special keywords
5971 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5972 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5973 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5974 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5975 ;; Emphasis
5976 (if em
5977 (if (featurep 'xemacs)
5978 '(org-do-emphasis-faces (0 nil append))
5979 '(org-do-emphasis-faces)))
5980 ;; Checkboxes
5981 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5982 1 'org-checkbox prepend)
5983 (if (cdr (assq 'checkbox org-list-automatic-rules))
5984 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5985 (0 (org-get-checkbox-statistics-face) t)))
5986 ;; Description list items
5987 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5988 1 'org-list-dt prepend)
5989 ;; ARCHIVEd headings
5990 (list (concat
5991 org-outline-regexp-bol
5992 "\\(.*:" org-archive-tag ":.*\\)")
5993 '(1 'org-archived prepend))
5994 ;; Specials
5995 '(org-do-latex-and-special-faces)
5996 '(org-fontify-entities)
5997 '(org-raise-scripts)
5998 ;; Code
5999 '(org-activate-code (1 'org-code t))
6000 ;; COMMENT
6001 (list (format org-heading-keyword-regexp-format
6002 (concat "\\("
6003 org-comment-string "\\|" org-quote-string
6004 "\\)"))
6005 '(2 'org-special-keyword t))
6006 ;; Blocks and meta lines
6007 '(org-fontify-meta-lines-and-blocks)
6009 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6010 (run-hooks 'org-font-lock-set-keywords-hook)
6011 ;; Now set the full font-lock-keywords
6012 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6013 (org-set-local 'font-lock-defaults
6014 '(org-font-lock-keywords t nil nil backward-paragraph))
6015 (kill-local-variable 'font-lock-keywords) nil))
6017 (defun org-toggle-pretty-entities ()
6018 "Toggle the composition display of entities as UTF8 characters."
6019 (interactive)
6020 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6021 (org-restart-font-lock)
6022 (if org-pretty-entities
6023 (message "Entities are displayed as UTF8 characters")
6024 (save-restriction
6025 (widen)
6026 (org-decompose-region (point-min) (point-max))
6027 (message "Entities are displayed plain"))))
6029 (defvar org-custom-properties-overlays nil
6030 "List of overlays used for custom properties.")
6031 (make-variable-buffer-local 'org-custom-properties-overlays)
6033 (defun org-toggle-custom-properties-visibility ()
6034 "Display or hide properties in `org-custom-properties'."
6035 (interactive)
6036 (if org-custom-properties-overlays
6037 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6038 (setq org-custom-properties-overlays nil))
6039 (unless (not org-custom-properties)
6040 (save-excursion
6041 (save-restriction
6042 (widen)
6043 (goto-char (point-min))
6044 (while (re-search-forward org-property-re nil t)
6045 (mapc (lambda(p)
6046 (when (equal p (substring (match-string 1) 1 -1))
6047 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6048 (overlay-put o 'invisible t)
6049 (overlay-put o 'org-custom-property t)
6050 (push o org-custom-properties-overlays))))
6051 org-custom-properties)))))))
6053 (defun org-fontify-entities (limit)
6054 "Find an entity to fontify."
6055 (let (ee)
6056 (when org-pretty-entities
6057 (catch 'match
6058 (while (re-search-forward
6059 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6060 limit t)
6061 (if (and (not (org-in-indented-comment-line))
6062 (setq ee (org-entity-get (match-string 1)))
6063 (= (length (nth 6 ee)) 1))
6064 (let*
6065 ((end (if (equal (match-string 2) "{}")
6066 (match-end 2)
6067 (match-end 1))))
6068 (add-text-properties
6069 (match-beginning 0) end
6070 (list 'font-lock-fontified t))
6071 (compose-region (match-beginning 0) end
6072 (nth 6 ee) nil)
6073 (backward-char 1)
6074 (throw 'match t))))
6075 nil))))
6077 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6078 "Fontify string S like in Org-mode."
6079 (with-temp-buffer
6080 (insert s)
6081 (let ((org-odd-levels-only odd-levels))
6082 (org-mode)
6083 (font-lock-fontify-buffer)
6084 (buffer-string))))
6086 (defvar org-m nil)
6087 (defvar org-l nil)
6088 (defvar org-f nil)
6089 (defun org-get-level-face (n)
6090 "Get the right face for match N in font-lock matching of headlines."
6091 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6092 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6093 (if org-cycle-level-faces
6094 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6095 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6096 (cond
6097 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6098 ((eq n 2) org-f)
6099 (t (if org-level-color-stars-only nil org-f))))
6102 (defun org-get-todo-face (kwd)
6103 "Get the right face for a TODO keyword KWD.
6104 If KWD is a number, get the corresponding match group."
6105 (if (numberp kwd) (setq kwd (match-string kwd)))
6106 (or (org-face-from-face-or-color
6107 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6108 (and (member kwd org-done-keywords) 'org-done)
6109 'org-todo))
6111 (defun org-face-from-face-or-color (context inherit face-or-color)
6112 "Create a face list that inherits INHERIT, but sets the foreground color.
6113 When FACE-OR-COLOR is not a string, just return it."
6114 (if (stringp face-or-color)
6115 (list :inherit inherit
6116 (cdr (assoc context org-faces-easy-properties))
6117 face-or-color)
6118 face-or-color))
6120 (defun org-font-lock-add-tag-faces (limit)
6121 "Add the special tag faces."
6122 (when (and org-tag-faces org-tags-special-faces-re)
6123 (while (re-search-forward org-tags-special-faces-re limit t)
6124 (add-text-properties (match-beginning 1) (match-end 1)
6125 (list 'face (org-get-tag-face 1)
6126 'font-lock-fontified t))
6127 (backward-char 1))))
6129 (defun org-font-lock-add-priority-faces (limit)
6130 "Add the special priority faces."
6131 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6132 (when (save-match-data (org-at-heading-p))
6133 (add-text-properties
6134 (match-beginning 0) (match-end 0)
6135 (list 'face (or (org-face-from-face-or-color
6136 'priority 'org-priority
6137 (cdr (assoc (char-after (match-beginning 1))
6138 org-priority-faces)))
6139 'org-priority)
6140 'font-lock-fontified t)))))
6142 (defun org-get-tag-face (kwd)
6143 "Get the right face for a TODO keyword KWD.
6144 If KWD is a number, get the corresponding match group."
6145 (if (numberp kwd) (setq kwd (match-string kwd)))
6146 (or (org-face-from-face-or-color
6147 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6148 'org-tag))
6150 (defun org-unfontify-region (beg end &optional maybe_loudly)
6151 "Remove fontification and activation overlays from links."
6152 (font-lock-default-unfontify-region beg end)
6153 (let* ((buffer-undo-list t)
6154 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6155 (inhibit-modification-hooks t)
6156 deactivate-mark buffer-file-name buffer-file-truename)
6157 (org-decompose-region beg end)
6158 (remove-text-properties beg end
6159 '(mouse-face t keymap t org-linked-text t
6160 invisible t intangible t
6161 org-no-flyspell t org-emphasis t))
6162 (org-remove-font-lock-display-properties beg end)))
6164 (defconst org-script-display '(((raise -0.3) (height 0.7))
6165 ((raise 0.3) (height 0.7))
6166 ((raise -0.5))
6167 ((raise 0.5)))
6168 "Display properties for showing superscripts and subscripts.")
6170 (defun org-remove-font-lock-display-properties (beg end)
6171 "Remove specific display properties that have been added by font lock.
6172 The will remove the raise properties that are used to show superscripts
6173 and subscripts."
6174 (let (next prop)
6175 (while (< beg end)
6176 (setq next (next-single-property-change beg 'display nil end)
6177 prop (get-text-property beg 'display))
6178 (if (member prop org-script-display)
6179 (put-text-property beg next 'display nil))
6180 (setq beg next))))
6182 (defun org-raise-scripts (limit)
6183 "Add raise properties to sub/superscripts."
6184 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6185 (if (re-search-forward
6186 (if (eq org-use-sub-superscripts t)
6187 org-match-substring-regexp
6188 org-match-substring-with-braces-regexp)
6189 limit t)
6190 (let* ((pos (point)) table-p comment-p
6191 (mpos (match-beginning 3))
6192 (emph-p (get-text-property mpos 'org-emphasis))
6193 (link-p (get-text-property mpos 'mouse-face))
6194 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6195 (goto-char (point-at-bol))
6196 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6197 comment-p (org-looking-at-p "[ \t]*#"))
6198 (goto-char pos)
6199 ;; FIXME: Should we go back one character here, for a_b^c
6200 ;; (goto-char (1- pos)) ;????????????????????
6201 (if (or comment-p emph-p link-p keyw-p)
6203 (put-text-property (match-beginning 3) (match-end 0)
6204 'display
6205 (if (equal (char-after (match-beginning 2)) ?^)
6206 (nth (if table-p 3 1) org-script-display)
6207 (nth (if table-p 2 0) org-script-display)))
6208 (add-text-properties (match-beginning 2) (match-end 2)
6209 (list 'invisible t
6210 'org-dwidth t 'org-dwidth-n 1))
6211 (if (and (eq (char-after (match-beginning 3)) ?{)
6212 (eq (char-before (match-end 3)) ?}))
6213 (progn
6214 (add-text-properties
6215 (match-beginning 3) (1+ (match-beginning 3))
6216 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6217 (add-text-properties
6218 (1- (match-end 3)) (match-end 3)
6219 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6220 t)))))
6222 ;;;; Visibility cycling, including org-goto and indirect buffer
6224 ;;; Cycling
6226 (defvar org-cycle-global-status nil)
6227 (make-variable-buffer-local 'org-cycle-global-status)
6228 (defvar org-cycle-subtree-status nil)
6229 (make-variable-buffer-local 'org-cycle-subtree-status)
6231 (defvar org-inlinetask-min-level)
6233 ;;;###autoload
6234 (defun org-cycle (&optional arg)
6235 "TAB-action and visibility cycling for Org-mode.
6237 This is the command invoked in Org-mode by the TAB key. Its main purpose
6238 is outline visibility cycling, but it also invokes other actions
6239 in special contexts.
6241 - When this function is called with a prefix argument, rotate the entire
6242 buffer through 3 states (global cycling)
6243 1. OVERVIEW: Show only top-level headlines.
6244 2. CONTENTS: Show all headlines of all levels, but no body text.
6245 3. SHOW ALL: Show everything.
6246 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6247 determined by the variable `org-startup-folded', and by any VISIBILITY
6248 properties in the buffer.
6249 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6250 including any drawers.
6252 - When inside a table, re-align the table and move to the next field.
6254 - When point is at the beginning of a headline, rotate the subtree started
6255 by this line through 3 different states (local cycling)
6256 1. FOLDED: Only the main headline is shown.
6257 2. CHILDREN: The main headline and the direct children are shown.
6258 From this state, you can move to one of the children
6259 and zoom in further.
6260 3. SUBTREE: Show the entire subtree, including body text.
6261 If there is no subtree, switch directly from CHILDREN to FOLDED.
6263 - When point is at the beginning of an empty headline and the variable
6264 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6265 of the headline by demoting and promoting it to likely levels. This
6266 speeds up creation document structure by pressing TAB once or several
6267 times right after creating a new headline.
6269 - When there is a numeric prefix, go up to a heading with level ARG, do
6270 a `show-subtree' and return to the previous cursor position. If ARG
6271 is negative, go up that many levels.
6273 - When point is not at the beginning of a headline, execute the global
6274 binding for TAB, which is re-indenting the line. See the option
6275 `org-cycle-emulate-tab' for details.
6277 - Special case: if point is at the beginning of the buffer and there is
6278 no headline in line 1, this function will act as if called with prefix arg
6279 (C-u TAB, same as S-TAB) also when called without prefix arg.
6280 But only if also the variable `org-cycle-global-at-bob' is t."
6281 (interactive "P")
6282 (org-load-modules-maybe)
6283 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6284 (and org-cycle-level-after-item/entry-creation
6285 (or (org-cycle-level)
6286 (org-cycle-item-indentation))))
6287 (let* (message-log-max ; Don't populate the *Messages* buffer
6288 (limit-level
6289 (or org-cycle-max-level
6290 (and (boundp 'org-inlinetask-min-level)
6291 org-inlinetask-min-level
6292 (1- org-inlinetask-min-level))))
6293 (nstars (and limit-level
6294 (if org-odd-levels-only
6295 (and limit-level (1- (* limit-level 2)))
6296 limit-level)))
6297 (org-outline-regexp
6298 (if (not (derived-mode-p 'org-mode))
6299 outline-regexp
6300 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6301 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6302 (not (looking-at org-outline-regexp))))
6303 (org-cycle-hook
6304 (if bob-special
6305 (delq 'org-optimize-window-after-visibility-change
6306 (copy-sequence org-cycle-hook))
6307 org-cycle-hook))
6308 (pos (point)))
6310 (if (or bob-special (equal arg '(4)))
6311 ;; special case: use global cycling
6312 (setq arg t))
6314 (cond
6316 ((equal arg '(16))
6317 (setq last-command 'dummy)
6318 (org-set-startup-visibility)
6319 (message "Startup visibility, plus VISIBILITY properties"))
6321 ((equal arg '(64))
6322 (show-all)
6323 (message "Entire buffer visible, including drawers"))
6325 ;; Table: enter it or move to the next field.
6326 ((org-at-table-p 'any)
6327 (if (org-at-table.el-p)
6328 (message "Use C-c ' to edit table.el tables")
6329 (if arg (org-table-edit-field t)
6330 (org-table-justify-field-maybe)
6331 (call-interactively 'org-table-next-field))))
6333 ((run-hook-with-args-until-success
6334 'org-tab-after-check-for-table-hook))
6336 ;; Global cycling: delegate to `org-cycle-internal-global'.
6337 ((eq arg t) (org-cycle-internal-global))
6339 ;; Drawers: delegate to `org-flag-drawer'.
6340 ((and org-drawers org-drawer-regexp
6341 (save-excursion
6342 (beginning-of-line 1)
6343 (looking-at org-drawer-regexp)))
6344 (org-flag-drawer ; toggle block visibility
6345 (not (get-char-property (match-end 0) 'invisible))))
6347 ;; Show-subtree, ARG levels up from here.
6348 ((integerp arg)
6349 (save-excursion
6350 (org-back-to-heading)
6351 (outline-up-heading (if (< arg 0) (- arg)
6352 (- (funcall outline-level) arg)))
6353 (org-show-subtree)))
6355 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6356 ((and (featurep 'org-inlinetask)
6357 (org-inlinetask-at-task-p)
6358 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6359 (org-inlinetask-toggle-visibility))
6361 ((org-try-cdlatex-tab))
6363 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6364 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6365 (save-excursion (beginning-of-line 1)
6366 (looking-at org-outline-regexp)))
6367 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6368 (org-cycle-internal-local))
6370 ;; From there: TAB emulation and template completion.
6371 (buffer-read-only (org-back-to-heading))
6373 ((run-hook-with-args-until-success
6374 'org-tab-after-check-for-cycling-hook))
6376 ((org-try-structure-completion))
6378 ((run-hook-with-args-until-success
6379 'org-tab-before-tab-emulation-hook))
6381 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6382 (or (not (bolp))
6383 (not (looking-at org-outline-regexp))))
6384 (call-interactively (global-key-binding "\t")))
6386 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6387 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6388 (or (and (eq org-cycle-emulate-tab 'white)
6389 (= (match-end 0) (point-at-eol)))
6390 (and (eq org-cycle-emulate-tab 'whitestart)
6391 (>= (match-end 0) pos))))
6393 (eq org-cycle-emulate-tab t))
6394 (call-interactively (global-key-binding "\t")))
6396 (t (save-excursion
6397 (org-back-to-heading)
6398 (org-cycle)))))))
6400 (defun org-cycle-internal-global ()
6401 "Do the global cycling action."
6402 ;; Hack to avoid display of messages for .org attachments in Gnus
6403 (let (message-log-max ; Don't populate the *Messages* buffer
6404 (ga (string-match "\\*fontification" (buffer-name))))
6405 (cond
6406 ((and (eq last-command this-command)
6407 (eq org-cycle-global-status 'overview))
6408 ;; We just created the overview - now do table of contents
6409 ;; This can be slow in very large buffers, so indicate action
6410 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6411 (unless ga (message "CONTENTS..."))
6412 (org-content)
6413 (unless ga (message "CONTENTS...done"))
6414 (setq org-cycle-global-status 'contents)
6415 (run-hook-with-args 'org-cycle-hook 'contents))
6417 ((and (eq last-command this-command)
6418 (eq org-cycle-global-status 'contents))
6419 ;; We just showed the table of contents - now show everything
6420 (run-hook-with-args 'org-pre-cycle-hook 'all)
6421 (show-all)
6422 (unless ga (message "SHOW ALL"))
6423 (setq org-cycle-global-status 'all)
6424 (run-hook-with-args 'org-cycle-hook 'all))
6427 ;; Default action: go to overview
6428 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6429 (org-overview)
6430 (unless ga (message "OVERVIEW"))
6431 (setq org-cycle-global-status 'overview)
6432 (run-hook-with-args 'org-cycle-hook 'overview)))))
6434 (defun org-cycle-internal-local ()
6435 "Do the local cycling action."
6436 (let (message-log-max ; Don't populate the *Messages* buffer
6437 (goal-column 0) eoh eol eos has-children children-skipped struct)
6438 ;; First, determine end of headline (EOH), end of subtree or item
6439 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6440 (save-excursion
6441 (if (org-at-item-p)
6442 (progn
6443 (beginning-of-line)
6444 (setq struct (org-list-struct))
6445 (setq eoh (point-at-eol))
6446 (setq eos (org-list-get-item-end-before-blank (point) struct))
6447 (setq has-children (org-list-has-child-p (point) struct)))
6448 (org-back-to-heading)
6449 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6450 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6451 (setq has-children
6452 (or (save-excursion
6453 (let ((level (funcall outline-level)))
6454 (outline-next-heading)
6455 (and (org-at-heading-p t)
6456 (> (funcall outline-level) level))))
6457 (save-excursion
6458 (org-list-search-forward (org-item-beginning-re) eos t)))))
6459 ;; Determine end invisible part of buffer (EOL)
6460 (beginning-of-line 2)
6461 ;; XEmacs doesn't have `next-single-char-property-change'
6462 (if (featurep 'xemacs)
6463 (while (and (not (eobp)) ;; this is like `next-line'
6464 (get-char-property (1- (point)) 'invisible))
6465 (beginning-of-line 2))
6466 (while (and (not (eobp)) ;; this is like `next-line'
6467 (get-char-property (1- (point)) 'invisible))
6468 (goto-char (next-single-char-property-change (point) 'invisible))
6469 (and (eolp) (beginning-of-line 2))))
6470 (setq eol (point)))
6471 ;; Find out what to do next and set `this-command'
6472 (cond
6473 ((= eos eoh)
6474 ;; Nothing is hidden behind this heading
6475 (unless (org-before-first-heading-p)
6476 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6477 (message "EMPTY ENTRY")
6478 (setq org-cycle-subtree-status nil)
6479 (save-excursion
6480 (goto-char eos)
6481 (outline-next-heading)
6482 (if (outline-invisible-p) (org-flag-heading nil))))
6483 ((and (or (>= eol eos)
6484 (not (string-match "\\S-" (buffer-substring eol eos))))
6485 (or has-children
6486 (not (setq children-skipped
6487 org-cycle-skip-children-state-if-no-children))))
6488 ;; Entire subtree is hidden in one line: children view
6489 (unless (org-before-first-heading-p)
6490 (run-hook-with-args 'org-pre-cycle-hook 'children))
6491 (if (org-at-item-p)
6492 (org-list-set-item-visibility (point-at-bol) struct 'children)
6493 (org-show-entry)
6494 (org-with-limited-levels (show-children))
6495 ;; FIXME: This slows down the func way too much.
6496 ;; How keep drawers hidden in subtree anyway?
6497 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6498 ;; (org-cycle-hide-drawers 'subtree))
6500 ;; Fold every list in subtree to top-level items.
6501 (when (eq org-cycle-include-plain-lists 'integrate)
6502 (save-excursion
6503 (org-back-to-heading)
6504 (while (org-list-search-forward (org-item-beginning-re) eos t)
6505 (beginning-of-line 1)
6506 (let* ((struct (org-list-struct))
6507 (prevs (org-list-prevs-alist struct))
6508 (end (org-list-get-bottom-point struct)))
6509 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6510 (org-list-get-all-items (point) struct prevs))
6511 (goto-char end))))))
6512 (message "CHILDREN")
6513 (save-excursion
6514 (goto-char eos)
6515 (outline-next-heading)
6516 (if (outline-invisible-p) (org-flag-heading nil)))
6517 (setq org-cycle-subtree-status 'children)
6518 (unless (org-before-first-heading-p)
6519 (run-hook-with-args 'org-cycle-hook 'children)))
6520 ((or children-skipped
6521 (and (eq last-command this-command)
6522 (eq org-cycle-subtree-status 'children)))
6523 ;; We just showed the children, or no children are there,
6524 ;; now show everything.
6525 (unless (org-before-first-heading-p)
6526 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6527 (outline-flag-region eoh eos nil)
6528 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6529 (setq org-cycle-subtree-status 'subtree)
6530 (unless (org-before-first-heading-p)
6531 (run-hook-with-args 'org-cycle-hook 'subtree)))
6533 ;; Default action: hide the subtree.
6534 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6535 (outline-flag-region eoh eos t)
6536 (message "FOLDED")
6537 (setq org-cycle-subtree-status 'folded)
6538 (unless (org-before-first-heading-p)
6539 (run-hook-with-args 'org-cycle-hook 'folded))))))
6541 ;;;###autoload
6542 (defun org-global-cycle (&optional arg)
6543 "Cycle the global visibility. For details see `org-cycle'.
6544 With \\[universal-argument] prefix arg, switch to startup visibility.
6545 With a numeric prefix, show all headlines up to that level."
6546 (interactive "P")
6547 (let ((org-cycle-include-plain-lists
6548 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6549 (cond
6550 ((integerp arg)
6551 (show-all)
6552 (hide-sublevels arg)
6553 (setq org-cycle-global-status 'contents))
6554 ((equal arg '(4))
6555 (org-set-startup-visibility)
6556 (message "Startup visibility, plus VISIBILITY properties."))
6558 (org-cycle '(4))))))
6560 (defun org-set-startup-visibility ()
6561 "Set the visibility required by startup options and properties."
6562 (cond
6563 ((eq org-startup-folded t)
6564 (org-cycle '(4)))
6565 ((eq org-startup-folded 'content)
6566 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6567 (org-cycle '(4)) (org-cycle '(4)))))
6568 (unless (eq org-startup-folded 'showeverything)
6569 (if org-hide-block-startup (org-hide-block-all))
6570 (org-set-visibility-according-to-property 'no-cleanup)
6571 (org-cycle-hide-archived-subtrees 'all)
6572 (org-cycle-hide-drawers 'all)
6573 (org-cycle-show-empty-lines t)))
6575 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6576 "Switch subtree visibilities according to :VISIBILITY: property."
6577 (interactive)
6578 (let (org-show-entry-below state)
6579 (save-excursion
6580 (goto-char (point-min))
6581 (while (re-search-forward
6582 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6583 nil t)
6584 (setq state (match-string 1))
6585 (save-excursion
6586 (org-back-to-heading t)
6587 (hide-subtree)
6588 (org-reveal)
6589 (cond
6590 ((equal state '("fold" "folded"))
6591 (hide-subtree))
6592 ((equal state "children")
6593 (org-show-hidden-entry)
6594 (show-children))
6595 ((equal state "content")
6596 (save-excursion
6597 (save-restriction
6598 (org-narrow-to-subtree)
6599 (org-content))))
6600 ((member state '("all" "showall"))
6601 (show-subtree)))))
6602 (unless no-cleanup
6603 (org-cycle-hide-archived-subtrees 'all)
6604 (org-cycle-hide-drawers 'all)
6605 (org-cycle-show-empty-lines 'all)))))
6607 ;; This function uses outline-regexp instead of the more fundamental
6608 ;; org-outline-regexp so that org-cycle-global works outside of Org
6609 ;; buffers, where outline-regexp is needed.
6610 (defun org-overview ()
6611 "Switch to overview mode, showing only top-level headlines.
6612 Really, this shows all headlines with level equal or greater than the level
6613 of the first headline in the buffer. This is important, because if the
6614 first headline is not level one, then (hide-sublevels 1) gives confusing
6615 results."
6616 (interactive)
6617 (let ((level (save-excursion
6618 (goto-char (point-min))
6619 (if (re-search-forward (concat "^" outline-regexp) nil t)
6620 (progn
6621 (goto-char (match-beginning 0))
6622 (funcall outline-level))))))
6623 (and level (hide-sublevels level))))
6625 (defun org-content (&optional arg)
6626 "Show all headlines in the buffer, like a table of contents.
6627 With numerical argument N, show content up to level N."
6628 (interactive "P")
6629 (save-excursion
6630 ;; Visit all headings and show their offspring
6631 (and (integerp arg) (org-overview))
6632 (goto-char (point-max))
6633 (catch 'exit
6634 (while (and (progn (condition-case nil
6635 (outline-previous-visible-heading 1)
6636 (error (goto-char (point-min))))
6638 (looking-at org-outline-regexp))
6639 (if (integerp arg)
6640 (show-children (1- arg))
6641 (show-branches))
6642 (if (bobp) (throw 'exit nil))))))
6645 (defun org-optimize-window-after-visibility-change (state)
6646 "Adjust the window after a change in outline visibility.
6647 This function is the default value of the hook `org-cycle-hook'."
6648 (when (get-buffer-window (current-buffer))
6649 (cond
6650 ((eq state 'content) nil)
6651 ((eq state 'all) nil)
6652 ((eq state 'folded) nil)
6653 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6654 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6656 (defun org-remove-empty-overlays-at (pos)
6657 "Remove outline overlays that do not contain non-white stuff."
6658 (mapc
6659 (lambda (o)
6660 (and (eq 'outline (overlay-get o 'invisible))
6661 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6662 (overlay-end o))))
6663 (delete-overlay o)))
6664 (overlays-at pos)))
6666 (defun org-clean-visibility-after-subtree-move ()
6667 "Fix visibility issues after moving a subtree."
6668 ;; First, find a reasonable region to look at:
6669 ;; Start two siblings above, end three below
6670 (let* ((beg (save-excursion
6671 (and (org-get-last-sibling)
6672 (org-get-last-sibling))
6673 (point)))
6674 (end (save-excursion
6675 (and (org-get-next-sibling)
6676 (org-get-next-sibling)
6677 (org-get-next-sibling))
6678 (if (org-at-heading-p)
6679 (point-at-eol)
6680 (point))))
6681 (level (looking-at "\\*+"))
6682 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6683 (save-excursion
6684 (save-restriction
6685 (narrow-to-region beg end)
6686 (when re
6687 ;; Properly fold already folded siblings
6688 (goto-char (point-min))
6689 (while (re-search-forward re nil t)
6690 (if (and (not (outline-invisible-p))
6691 (save-excursion
6692 (goto-char (point-at-eol)) (outline-invisible-p)))
6693 (hide-entry))))
6694 (org-cycle-show-empty-lines 'overview)
6695 (org-cycle-hide-drawers 'overview)))))
6697 (defun org-cycle-show-empty-lines (state)
6698 "Show empty lines above all visible headlines.
6699 The region to be covered depends on STATE when called through
6700 `org-cycle-hook'. Lisp program can use t for STATE to get the
6701 entire buffer covered. Note that an empty line is only shown if there
6702 are at least `org-cycle-separator-lines' empty lines before the headline."
6703 (when (not (= org-cycle-separator-lines 0))
6704 (save-excursion
6705 (let* ((n (abs org-cycle-separator-lines))
6706 (re (cond
6707 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6708 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6709 (t (let ((ns (number-to-string (- n 2))))
6710 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6711 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6712 beg end b e)
6713 (cond
6714 ((memq state '(overview contents t))
6715 (setq beg (point-min) end (point-max)))
6716 ((memq state '(children folded))
6717 (setq beg (point) end (progn (org-end-of-subtree t t)
6718 (beginning-of-line 2)
6719 (point)))))
6720 (when beg
6721 (goto-char beg)
6722 (while (re-search-forward re end t)
6723 (unless (get-char-property (match-end 1) 'invisible)
6724 (setq e (match-end 1))
6725 (if (< org-cycle-separator-lines 0)
6726 (setq b (save-excursion
6727 (goto-char (match-beginning 0))
6728 (org-back-over-empty-lines)
6729 (if (save-excursion
6730 (goto-char (max (point-min) (1- (point))))
6731 (org-at-heading-p))
6732 (1- (point))
6733 (point))))
6734 (setq b (match-beginning 1)))
6735 (outline-flag-region b e nil)))))))
6736 ;; Never hide empty lines at the end of the file.
6737 (save-excursion
6738 (goto-char (point-max))
6739 (outline-previous-heading)
6740 (outline-end-of-heading)
6741 (if (and (looking-at "[ \t\n]+")
6742 (= (match-end 0) (point-max)))
6743 (outline-flag-region (point) (match-end 0) nil))))
6745 (defun org-show-empty-lines-in-parent ()
6746 "Move to the parent and re-show empty lines before visible headlines."
6747 (save-excursion
6748 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6749 (org-cycle-show-empty-lines context))))
6751 (defun org-files-list ()
6752 "Return `org-agenda-files' list, plus all open org-mode files.
6753 This is useful for operations that need to scan all of a user's
6754 open and agenda-wise Org files."
6755 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6756 (dolist (buf (buffer-list))
6757 (with-current-buffer buf
6758 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6759 (let ((file (expand-file-name (buffer-file-name))))
6760 (unless (member file files)
6761 (push file files))))))
6762 files))
6764 (defsubst org-entry-beginning-position ()
6765 "Return the beginning position of the current entry."
6766 (save-excursion (outline-back-to-heading t) (point)))
6768 (defsubst org-entry-end-position ()
6769 "Return the end position of the current entry."
6770 (save-excursion (outline-next-heading) (point)))
6772 (defun org-cycle-hide-drawers (state)
6773 "Re-hide all drawers after a visibility state change."
6774 (when (and (derived-mode-p 'org-mode)
6775 (not (memq state '(overview folded contents))))
6776 (save-excursion
6777 (let* ((globalp (memq state '(contents all)))
6778 (beg (if globalp (point-min) (point)))
6779 (end (if globalp (point-max)
6780 (if (eq state 'children)
6781 (save-excursion (outline-next-heading) (point))
6782 (org-end-of-subtree t)))))
6783 (goto-char beg)
6784 (while (re-search-forward org-drawer-regexp end t)
6785 (org-flag-drawer t))))))
6787 (defun org-cycle-hide-inline-tasks (state)
6788 "Re-hide inline task when switching to 'contents visibility state."
6789 (when (and (eq state 'contents)
6790 (boundp 'org-inlinetask-min-level)
6791 org-inlinetask-min-level)
6792 (hide-sublevels (1- org-inlinetask-min-level))))
6794 (defun org-flag-drawer (flag)
6795 "When FLAG is non-nil, hide the drawer we are within.
6796 Otherwise make it visible."
6797 (save-excursion
6798 (beginning-of-line 1)
6799 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6800 (let ((b (match-end 0)))
6801 (if (re-search-forward
6802 "^[ \t]*:END:"
6803 (save-excursion (outline-next-heading) (point)) t)
6804 (outline-flag-region b (point-at-eol) flag)
6805 (error ":END: line missing at position %s" b))))))
6807 (defun org-subtree-end-visible-p ()
6808 "Is the end of the current subtree visible?"
6809 (pos-visible-in-window-p
6810 (save-excursion (org-end-of-subtree t) (point))))
6812 (defun org-first-headline-recenter (&optional N)
6813 "Move cursor to the first headline and recenter the headline.
6814 Optional argument N means put the headline into the Nth line of the window."
6815 (goto-char (point-min))
6816 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6817 (beginning-of-line)
6818 (recenter (prefix-numeric-value N))))
6820 ;;; Saving and restoring visibility
6822 (defun org-outline-overlay-data (&optional use-markers)
6823 "Return a list of the locations of all outline overlays.
6824 These are overlays with the `invisible' property value `outline'.
6825 The return value is a list of cons cells, with start and stop
6826 positions for each overlay.
6827 If USE-MARKERS is set, return the positions as markers."
6828 (let (beg end)
6829 (save-excursion
6830 (save-restriction
6831 (widen)
6832 (delq nil
6833 (mapcar (lambda (o)
6834 (when (eq (overlay-get o 'invisible) 'outline)
6835 (setq beg (overlay-start o)
6836 end (overlay-end o))
6837 (and beg end (> end beg)
6838 (if use-markers
6839 (cons (move-marker (make-marker) beg)
6840 (move-marker (make-marker) end))
6841 (cons beg end)))))
6842 (overlays-in (point-min) (point-max))))))))
6844 (defun org-set-outline-overlay-data (data)
6845 "Create visibility overlays for all positions in DATA.
6846 DATA should have been made by `org-outline-overlay-data'."
6847 (let (o)
6848 (save-excursion
6849 (save-restriction
6850 (widen)
6851 (show-all)
6852 (mapc (lambda (c)
6853 (outline-flag-region (car c) (cdr c) t))
6854 data)))))
6856 ;;; Folding of blocks
6858 (defvar org-hide-block-overlays nil
6859 "Overlays hiding blocks.")
6860 (make-variable-buffer-local 'org-hide-block-overlays)
6862 (defun org-block-map (function &optional start end)
6863 "Call FUNCTION at the head of all source blocks in the current buffer.
6864 Optional arguments START and END can be used to limit the range."
6865 (let ((start (or start (point-min)))
6866 (end (or end (point-max))))
6867 (save-excursion
6868 (goto-char start)
6869 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6870 (save-excursion
6871 (save-match-data
6872 (goto-char (match-beginning 0))
6873 (funcall function)))))))
6875 (defun org-hide-block-toggle-all ()
6876 "Toggle the visibility of all blocks in the current buffer."
6877 (org-block-map #'org-hide-block-toggle))
6879 (defun org-hide-block-all ()
6880 "Fold all blocks in the current buffer."
6881 (interactive)
6882 (org-show-block-all)
6883 (org-block-map #'org-hide-block-toggle-maybe))
6885 (defun org-show-block-all ()
6886 "Unfold all blocks in the current buffer."
6887 (interactive)
6888 (mapc 'delete-overlay org-hide-block-overlays)
6889 (setq org-hide-block-overlays nil))
6891 (defun org-hide-block-toggle-maybe ()
6892 "Toggle visibility of block at point."
6893 (interactive)
6894 (let ((case-fold-search t))
6895 (if (save-excursion
6896 (beginning-of-line 1)
6897 (looking-at org-block-regexp))
6898 (progn (org-hide-block-toggle)
6899 t) ;; to signal that we took action
6900 nil))) ;; to signal that we did not
6902 (defun org-hide-block-toggle (&optional force)
6903 "Toggle the visibility of the current block."
6904 (interactive)
6905 (save-excursion
6906 (beginning-of-line)
6907 (if (re-search-forward org-block-regexp nil t)
6908 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6909 (end (match-end 0)) ;; end of entire body
6911 (if (memq t (mapcar (lambda (overlay)
6912 (eq (overlay-get overlay 'invisible)
6913 'org-hide-block))
6914 (overlays-at start)))
6915 (if (or (not force) (eq force 'off))
6916 (mapc (lambda (ov)
6917 (when (member ov org-hide-block-overlays)
6918 (setq org-hide-block-overlays
6919 (delq ov org-hide-block-overlays)))
6920 (when (eq (overlay-get ov 'invisible)
6921 'org-hide-block)
6922 (delete-overlay ov)))
6923 (overlays-at start)))
6924 (setq ov (make-overlay start end))
6925 (overlay-put ov 'invisible 'org-hide-block)
6926 ;; make the block accessible to isearch
6927 (overlay-put
6928 ov 'isearch-open-invisible
6929 (lambda (ov)
6930 (when (member ov org-hide-block-overlays)
6931 (setq org-hide-block-overlays
6932 (delq ov org-hide-block-overlays)))
6933 (when (eq (overlay-get ov 'invisible)
6934 'org-hide-block)
6935 (delete-overlay ov))))
6936 (push ov org-hide-block-overlays)))
6937 (error "Not looking at a source block"))))
6939 ;; org-tab-after-check-for-cycling-hook
6940 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6941 ;; Remove overlays when changing major mode
6942 (add-hook 'org-mode-hook
6943 (lambda () (org-add-hook 'change-major-mode-hook
6944 'org-show-block-all 'append 'local)))
6946 ;;; Org-goto
6948 (defvar org-goto-window-configuration nil)
6949 (defvar org-goto-marker nil)
6950 (defvar org-goto-map)
6951 (defun org-goto-map ()
6952 "Set the keymap `org-goto'."
6953 (setq org-goto-map
6954 (let ((map (make-sparse-keymap)))
6955 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6956 mouse-drag-region universal-argument org-occur))
6957 cmd)
6958 (while (setq cmd (pop cmds))
6959 (substitute-key-definition cmd cmd map global-map)))
6960 (suppress-keymap map)
6961 (org-defkey map "\C-m" 'org-goto-ret)
6962 (org-defkey map [(return)] 'org-goto-ret)
6963 (org-defkey map [(left)] 'org-goto-left)
6964 (org-defkey map [(right)] 'org-goto-right)
6965 (org-defkey map [(control ?g)] 'org-goto-quit)
6966 (org-defkey map "\C-i" 'org-cycle)
6967 (org-defkey map [(tab)] 'org-cycle)
6968 (org-defkey map [(down)] 'outline-next-visible-heading)
6969 (org-defkey map [(up)] 'outline-previous-visible-heading)
6970 (if org-goto-auto-isearch
6971 (if (fboundp 'define-key-after)
6972 (define-key-after map [t] 'org-goto-local-auto-isearch)
6973 nil)
6974 (org-defkey map "q" 'org-goto-quit)
6975 (org-defkey map "n" 'outline-next-visible-heading)
6976 (org-defkey map "p" 'outline-previous-visible-heading)
6977 (org-defkey map "f" 'outline-forward-same-level)
6978 (org-defkey map "b" 'outline-backward-same-level)
6979 (org-defkey map "u" 'outline-up-heading))
6980 (org-defkey map "/" 'org-occur)
6981 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6982 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6983 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6984 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6985 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6986 map)))
6988 (defconst org-goto-help
6989 "Browse buffer copy, to find location or copy text.%s
6990 RET=jump to location C-g=quit and return to previous location
6991 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6993 (defvar org-goto-start-pos) ; dynamically scoped parameter
6995 ;; FIXME: Docstring does not mention both interfaces
6996 (defun org-goto (&optional alternative-interface)
6997 "Look up a different location in the current file, keeping current visibility.
6999 When you want look-up or go to a different location in a
7000 document, the fastest way is often to fold the entire buffer and
7001 then dive into the tree. This method has the disadvantage, that
7002 the previous location will be folded, which may not be what you
7003 want.
7005 This command works around this by showing a copy of the current
7006 buffer in an indirect buffer, in overview mode. You can dive
7007 into the tree in that copy, use org-occur and incremental search
7008 to find a location. When pressing RET or `Q', the command
7009 returns to the original buffer in which the visibility is still
7010 unchanged. After RET it will also jump to the location selected
7011 in the indirect buffer and expose the headline hierarchy above.
7013 With a prefix argument, use the alternative interface: e.g. if
7014 `org-goto-interface' is 'outline use 'outline-path-completion."
7015 (interactive "P")
7016 (org-goto-map)
7017 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7018 (org-refile-use-outline-path t)
7019 (org-refile-target-verify-function nil)
7020 (interface
7021 (if (not alternative-interface)
7022 org-goto-interface
7023 (if (eq org-goto-interface 'outline)
7024 'outline-path-completion
7025 'outline)))
7026 (org-goto-start-pos (point))
7027 (selected-point
7028 (if (eq interface 'outline)
7029 (car (org-get-location (current-buffer) org-goto-help))
7030 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7031 (org-refile-check-position pa)
7032 (nth 3 pa)))))
7033 (if selected-point
7034 (progn
7035 (org-mark-ring-push org-goto-start-pos)
7036 (goto-char selected-point)
7037 (if (or (outline-invisible-p) (org-invisible-p2))
7038 (org-show-context 'org-goto)))
7039 (message "Quit"))))
7041 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7042 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7043 (defvar org-goto-local-auto-isearch-map) ; defined below
7045 (defun org-get-location (buf help)
7046 "Let the user select a location in the Org-mode buffer BUF.
7047 This function uses a recursive edit. It returns the selected position
7048 or nil."
7049 (org-no-popups
7050 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7051 (isearch-hide-immediately nil)
7052 (isearch-search-fun-function
7053 (lambda () 'org-goto-local-search-headings))
7054 (org-goto-selected-point org-goto-exit-command))
7055 (save-excursion
7056 (save-window-excursion
7057 (delete-other-windows)
7058 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7059 (org-pop-to-buffer-same-window
7060 (condition-case nil
7061 (make-indirect-buffer (current-buffer) "*org-goto*")
7062 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7063 (with-output-to-temp-buffer "*Org Help*"
7064 (princ (format help (if org-goto-auto-isearch
7065 " Just type for auto-isearch."
7066 " n/p/f/b/u to navigate, q to quit."))))
7067 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7068 (setq buffer-read-only nil)
7069 (let ((org-startup-truncated t)
7070 (org-startup-folded nil)
7071 (org-startup-align-all-tables nil))
7072 (org-mode)
7073 (org-overview))
7074 (setq buffer-read-only t)
7075 (if (and (boundp 'org-goto-start-pos)
7076 (integer-or-marker-p org-goto-start-pos))
7077 (let ((org-show-hierarchy-above t)
7078 (org-show-siblings t)
7079 (org-show-following-heading t))
7080 (goto-char org-goto-start-pos)
7081 (and (outline-invisible-p) (org-show-context)))
7082 (goto-char (point-min)))
7083 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7084 (message "Select location and press RET")
7085 (use-local-map org-goto-map)
7086 (recursive-edit)))
7087 (kill-buffer "*org-goto*")
7088 (cons org-goto-selected-point org-goto-exit-command))))
7090 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7091 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7092 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7093 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7095 (defun org-goto-local-search-headings (string bound noerror)
7096 "Search and make sure that any matches are in headlines."
7097 (catch 'return
7098 (while (if isearch-forward
7099 (search-forward string bound noerror)
7100 (search-backward string bound noerror))
7101 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7102 (and (member :headline context)
7103 (not (member :tags context))))
7104 (throw 'return (point))))))
7106 (defun org-goto-local-auto-isearch ()
7107 "Start isearch."
7108 (interactive)
7109 (goto-char (point-min))
7110 (let ((keys (this-command-keys)))
7111 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7112 (isearch-mode t)
7113 (isearch-process-search-char (string-to-char keys)))))
7115 (defun org-goto-ret (&optional arg)
7116 "Finish `org-goto' by going to the new location."
7117 (interactive "P")
7118 (setq org-goto-selected-point (point)
7119 org-goto-exit-command 'return)
7120 (throw 'exit nil))
7122 (defun org-goto-left ()
7123 "Finish `org-goto' by going to the new location."
7124 (interactive)
7125 (if (org-at-heading-p)
7126 (progn
7127 (beginning-of-line 1)
7128 (setq org-goto-selected-point (point)
7129 org-goto-exit-command 'left)
7130 (throw 'exit nil))
7131 (error "Not on a heading")))
7133 (defun org-goto-right ()
7134 "Finish `org-goto' by going to the new location."
7135 (interactive)
7136 (if (org-at-heading-p)
7137 (progn
7138 (setq org-goto-selected-point (point)
7139 org-goto-exit-command 'right)
7140 (throw 'exit nil))
7141 (error "Not on a heading")))
7143 (defun org-goto-quit ()
7144 "Finish `org-goto' without cursor motion."
7145 (interactive)
7146 (setq org-goto-selected-point nil)
7147 (setq org-goto-exit-command 'quit)
7148 (throw 'exit nil))
7150 ;;; Indirect buffer display of subtrees
7152 (defvar org-indirect-dedicated-frame nil
7153 "This is the frame being used for indirect tree display.")
7154 (defvar org-last-indirect-buffer nil)
7156 (defun org-tree-to-indirect-buffer (&optional arg)
7157 "Create indirect buffer and narrow it to current subtree.
7158 With a numerical prefix ARG, go up to this level and then take that tree.
7159 If ARG is negative, go up that many levels.
7161 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7162 indirect buffer previously made with this command, to avoid proliferation of
7163 indirect buffers. However, when you call the command with a \
7164 \\[universal-argument] prefix, or
7165 when `org-indirect-buffer-display' is `new-frame', the last buffer
7166 is kept so that you can work with several indirect buffers at the same time.
7167 If `org-indirect-buffer-display' is `dedicated-frame', the \
7168 \\[universal-argument] prefix also
7169 requests that a new frame be made for the new buffer, so that the dedicated
7170 frame is not changed."
7171 (interactive "P")
7172 (let ((cbuf (current-buffer))
7173 (cwin (selected-window))
7174 (pos (point))
7175 beg end level heading ibuf)
7176 (save-excursion
7177 (org-back-to-heading t)
7178 (when (numberp arg)
7179 (setq level (org-outline-level))
7180 (if (< arg 0) (setq arg (+ level arg)))
7181 (while (> (setq level (org-outline-level)) arg)
7182 (org-up-heading-safe)))
7183 (setq beg (point)
7184 heading (org-get-heading))
7185 (org-end-of-subtree t t)
7186 (if (org-at-heading-p) (backward-char 1))
7187 (setq end (point)))
7188 (if (and (buffer-live-p org-last-indirect-buffer)
7189 (not (eq org-indirect-buffer-display 'new-frame))
7190 (not arg))
7191 (kill-buffer org-last-indirect-buffer))
7192 (setq ibuf (org-get-indirect-buffer cbuf)
7193 org-last-indirect-buffer ibuf)
7194 (cond
7195 ((or (eq org-indirect-buffer-display 'new-frame)
7196 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7197 (select-frame (make-frame))
7198 (delete-other-windows)
7199 (org-pop-to-buffer-same-window ibuf)
7200 (org-set-frame-title heading))
7201 ((eq org-indirect-buffer-display 'dedicated-frame)
7202 (raise-frame
7203 (select-frame (or (and org-indirect-dedicated-frame
7204 (frame-live-p org-indirect-dedicated-frame)
7205 org-indirect-dedicated-frame)
7206 (setq org-indirect-dedicated-frame (make-frame)))))
7207 (delete-other-windows)
7208 (org-pop-to-buffer-same-window ibuf)
7209 (org-set-frame-title (concat "Indirect: " heading)))
7210 ((eq org-indirect-buffer-display 'current-window)
7211 (org-pop-to-buffer-same-window ibuf))
7212 ((eq org-indirect-buffer-display 'other-window)
7213 (pop-to-buffer ibuf))
7214 (t (error "Invalid value")))
7215 (if (featurep 'xemacs)
7216 (save-excursion (org-mode) (turn-on-font-lock)))
7217 (narrow-to-region beg end)
7218 (show-all)
7219 (goto-char pos)
7220 (run-hook-with-args 'org-cycle-hook 'all)
7221 (and (window-live-p cwin) (select-window cwin))))
7223 (defun org-get-indirect-buffer (&optional buffer)
7224 (setq buffer (or buffer (current-buffer)))
7225 (let ((n 1) (base (buffer-name buffer)) bname)
7226 (while (buffer-live-p
7227 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7228 (setq n (1+ n)))
7229 (condition-case nil
7230 (make-indirect-buffer buffer bname 'clone)
7231 (error (make-indirect-buffer buffer bname)))))
7233 (defun org-set-frame-title (title)
7234 "Set the title of the current frame to the string TITLE."
7235 ;; FIXME: how to name a single frame in XEmacs???
7236 (unless (featurep 'xemacs)
7237 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7239 ;;;; Structure editing
7241 ;;; Inserting headlines
7243 (defun org-previous-line-empty-p ()
7244 (save-excursion
7245 (and (not (bobp))
7246 (or (beginning-of-line 0) t)
7247 (save-match-data
7248 (looking-at "[ \t]*$")))))
7250 (defun org-insert-heading (&optional force-heading invisible-ok)
7251 "Insert a new heading or item with same depth at point.
7252 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7253 If point is at the beginning of a headline, insert a sibling before the
7254 current headline. If point is not at the beginning, split the line,
7255 create the new headline with the text in the current line after point
7256 \(but see also the variable `org-M-RET-may-split-line').
7258 With a double prefix arg, force the heading to be inserted at the
7259 end of the parent subtree.
7261 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7262 This is important for non-interactive uses of the command."
7263 (interactive "P")
7264 (if (or (= (buffer-size) 0)
7265 (and (not (save-excursion
7266 (and (ignore-errors (org-back-to-heading invisible-ok))
7267 (org-at-heading-p))))
7268 (or force-heading (not (org-in-item-p)))))
7269 (progn
7270 (insert "\n* ")
7271 (run-hooks 'org-insert-heading-hook))
7272 (when (or force-heading (not (org-insert-item)))
7273 (let* ((empty-line-p nil)
7274 (level nil)
7275 (on-heading (org-at-heading-p))
7276 (head (save-excursion
7277 (condition-case nil
7278 (progn
7279 (org-back-to-heading invisible-ok)
7280 (when (and (not on-heading)
7281 (featurep 'org-inlinetask)
7282 (integerp org-inlinetask-min-level)
7283 (>= (length (match-string 0))
7284 org-inlinetask-min-level))
7285 ;; Find a heading level before the inline task
7286 (while (and (setq level (org-up-heading-safe))
7287 (>= level org-inlinetask-min-level)))
7288 (if (org-at-heading-p)
7289 (org-back-to-heading invisible-ok)
7290 (error "This should not happen")))
7291 (setq empty-line-p (org-previous-line-empty-p))
7292 (match-string 0))
7293 (error "*"))))
7294 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7295 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7296 pos hide-previous previous-pos)
7297 (cond
7298 ((and (org-at-heading-p) (bolp)
7299 (or (bobp)
7300 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7301 ;; insert before the current line
7302 (open-line (if blank 2 1)))
7303 ((and (bolp)
7304 (not org-insert-heading-respect-content)
7305 (or (bobp)
7306 (save-excursion
7307 (backward-char 1) (not (outline-invisible-p)))))
7308 ;; insert right here
7309 nil)
7311 ;; somewhere in the line
7312 (save-excursion
7313 (setq previous-pos (point-at-bol))
7314 (end-of-line)
7315 (setq hide-previous (outline-invisible-p)))
7316 (and org-insert-heading-respect-content (org-show-subtree))
7317 (let ((split
7318 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7319 (save-excursion
7320 (let ((p (point)))
7321 (goto-char (point-at-bol))
7322 (and (looking-at org-complex-heading-regexp)
7323 (match-beginning 4)
7324 (> p (match-beginning 4)))))))
7325 tags pos)
7326 (cond
7327 (org-insert-heading-respect-content
7328 (if (not (equal force-heading '(16)))
7329 (org-end-of-subtree nil t)
7330 (org-up-heading-safe)
7331 (org-end-of-subtree nil t))
7332 (when (featurep 'org-inlinetask)
7333 (while (and (not (eobp))
7334 (looking-at "\\(\\*+\\)[ \t]+")
7335 (>= (length (match-string 1))
7336 org-inlinetask-min-level))
7337 (org-end-of-subtree nil t)))
7338 (or (bolp) (newline))
7339 (or (org-previous-line-empty-p)
7340 (and blank (newline)))
7341 (open-line 1))
7342 ((org-at-heading-p)
7343 (when hide-previous
7344 (show-children)
7345 (org-show-entry))
7346 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7347 (setq tags (and (match-end 2) (match-string 2)))
7348 (and (match-end 1)
7349 (delete-region (match-beginning 1) (match-end 1)))
7350 (setq pos (point-at-bol))
7351 (or split (end-of-line 1))
7352 (delete-horizontal-space)
7353 (if (string-match "\\`\\*+\\'"
7354 (buffer-substring (point-at-bol) (point)))
7355 (insert " "))
7356 (newline (if blank 2 1))
7357 (when tags
7358 (save-excursion
7359 (goto-char pos)
7360 (end-of-line 1)
7361 (insert " " tags)
7362 (org-set-tags nil 'align))))
7364 (or split (end-of-line 1))
7365 (newline (if blank 2 1)))))))
7366 (insert head) (just-one-space)
7367 (setq pos (point))
7368 (end-of-line 1)
7369 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7370 (when (and org-insert-heading-respect-content hide-previous)
7371 (save-excursion
7372 (goto-char previous-pos)
7373 (hide-subtree)))
7374 (run-hooks 'org-insert-heading-hook)))))
7376 (defun org-get-heading (&optional no-tags no-todo)
7377 "Return the heading of the current entry, without the stars.
7378 When NO-TAGS is non-nil, don't include tags.
7379 When NO-TODO is non-nil, don't include TODO keywords."
7380 (save-excursion
7381 (org-back-to-heading t)
7382 (cond
7383 ((and no-tags no-todo)
7384 (looking-at org-complex-heading-regexp)
7385 (match-string 4))
7386 (no-tags
7387 (looking-at (concat org-outline-regexp
7388 "\\(.*?\\)"
7389 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7390 (match-string 1))
7391 (no-todo
7392 (looking-at org-todo-line-regexp)
7393 (match-string 3))
7394 (t (looking-at org-heading-regexp)
7395 (match-string 2)))))
7397 (defun org-heading-components ()
7398 "Return the components of the current heading.
7399 This is a list with the following elements:
7400 - the level as an integer
7401 - the reduced level, different if `org-odd-levels-only' is set.
7402 - the TODO keyword, or nil
7403 - the priority character, like ?A, or nil if no priority is given
7404 - the headline text itself, or the tags string if no headline text
7405 - the tags string, or nil."
7406 (save-excursion
7407 (org-back-to-heading t)
7408 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7409 (list (length (match-string 1))
7410 (org-reduced-level (length (match-string 1)))
7411 (org-match-string-no-properties 2)
7412 (and (match-end 3) (aref (match-string 3) 2))
7413 (org-match-string-no-properties 4)
7414 (org-match-string-no-properties 5)))))
7416 (defun org-get-entry ()
7417 "Get the entry text, after heading, entire subtree."
7418 (save-excursion
7419 (org-back-to-heading t)
7420 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7422 (defun org-insert-heading-after-current ()
7423 "Insert a new heading with same level as current, after current subtree."
7424 (interactive)
7425 (org-back-to-heading)
7426 (org-insert-heading)
7427 (org-move-subtree-down)
7428 (end-of-line 1))
7430 (defun org-insert-heading-respect-content ()
7431 (interactive)
7432 (let ((org-insert-heading-respect-content t))
7433 (org-insert-heading t)))
7435 (defun org-insert-todo-heading-respect-content (&optional force-state)
7436 (interactive "P")
7437 (let ((org-insert-heading-respect-content t))
7438 (org-insert-todo-heading force-state t)))
7440 (defun org-insert-todo-heading (arg &optional force-heading)
7441 "Insert a new heading with the same level and TODO state as current heading.
7442 If the heading has no TODO state, or if the state is DONE, use the first
7443 state (TODO by default). Also one prefix arg, force first state. With two
7444 prefix args, force inserting at the end of the parent subtree."
7445 (interactive "P")
7446 (when (or force-heading (not (org-insert-item 'checkbox)))
7447 (org-insert-heading (or (and (equal arg '(16)) '(16))
7448 force-heading))
7449 (save-excursion
7450 (org-back-to-heading)
7451 (outline-previous-heading)
7452 (looking-at org-todo-line-regexp))
7453 (let*
7454 ((new-mark-x
7455 (if (or arg
7456 (not (match-beginning 2))
7457 (member (match-string 2) org-done-keywords))
7458 (car org-todo-keywords-1)
7459 (match-string 2)))
7460 (new-mark
7462 (run-hook-with-args-until-success
7463 'org-todo-get-default-hook new-mark-x nil)
7464 new-mark-x)))
7465 (beginning-of-line 1)
7466 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7467 (if org-treat-insert-todo-heading-as-state-change
7468 (org-todo new-mark)
7469 (insert new-mark " "))))
7470 (when org-provide-todo-statistics
7471 (org-update-parent-todo-statistics))))
7473 (defun org-insert-subheading (arg)
7474 "Insert a new subheading and demote it.
7475 Works for outline headings and for plain lists alike."
7476 (interactive "P")
7477 (org-insert-heading arg)
7478 (cond
7479 ((org-at-heading-p) (org-do-demote))
7480 ((org-at-item-p) (org-indent-item))))
7482 (defun org-insert-todo-subheading (arg)
7483 "Insert a new subheading with TODO keyword or checkbox and demote it.
7484 Works for outline headings and for plain lists alike."
7485 (interactive "P")
7486 (org-insert-todo-heading arg)
7487 (cond
7488 ((org-at-heading-p) (org-do-demote))
7489 ((org-at-item-p) (org-indent-item))))
7491 ;;; Promotion and Demotion
7493 (defvar org-after-demote-entry-hook nil
7494 "Hook run after an entry has been demoted.
7495 The cursor will be at the beginning of the entry.
7496 When a subtree is being demoted, the hook will be called for each node.")
7498 (defvar org-after-promote-entry-hook nil
7499 "Hook run after an entry has been promoted.
7500 The cursor will be at the beginning of the entry.
7501 When a subtree is being promoted, the hook will be called for each node.")
7503 (defun org-promote-subtree ()
7504 "Promote the entire subtree.
7505 See also `org-promote'."
7506 (interactive)
7507 (save-excursion
7508 (org-with-limited-levels (org-map-tree 'org-promote)))
7509 (org-fix-position-after-promote))
7511 (defun org-demote-subtree ()
7512 "Demote the entire subtree. See `org-demote'.
7513 See also `org-promote'."
7514 (interactive)
7515 (save-excursion
7516 (org-with-limited-levels (org-map-tree 'org-demote)))
7517 (org-fix-position-after-promote))
7520 (defun org-do-promote ()
7521 "Promote the current heading higher up the tree.
7522 If the region is active in `transient-mark-mode', promote all headings
7523 in the region."
7524 (interactive)
7525 (save-excursion
7526 (if (org-region-active-p)
7527 (org-map-region 'org-promote (region-beginning) (region-end))
7528 (org-promote)))
7529 (org-fix-position-after-promote))
7531 (defun org-do-demote ()
7532 "Demote the current heading lower down the tree.
7533 If the region is active in `transient-mark-mode', demote all headings
7534 in the region."
7535 (interactive)
7536 (save-excursion
7537 (if (org-region-active-p)
7538 (org-map-region 'org-demote (region-beginning) (region-end))
7539 (org-demote)))
7540 (org-fix-position-after-promote))
7542 (defun org-fix-position-after-promote ()
7543 "Make sure that after pro/demotion cursor position is right."
7544 (let ((pos (point)))
7545 (when (save-excursion
7546 (beginning-of-line 1)
7547 (looking-at org-todo-line-regexp)
7548 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7549 (cond ((eobp) (insert " "))
7550 ((eolp) (insert " "))
7551 ((equal (char-after) ?\ ) (forward-char 1))))))
7553 (defun org-current-level ()
7554 "Return the level of the current entry, or nil if before the first headline.
7555 The level is the number of stars at the beginning of the headline."
7556 (save-excursion
7557 (org-with-limited-levels
7558 (if (ignore-errors (org-back-to-heading t))
7559 (funcall outline-level)))))
7561 (defun org-get-previous-line-level ()
7562 "Return the outline depth of the last headline before the current line.
7563 Returns 0 for the first headline in the buffer, and nil if before the
7564 first headline."
7565 (let ((current-level (org-current-level))
7566 (prev-level (when (> (line-number-at-pos) 1)
7567 (save-excursion
7568 (beginning-of-line 0)
7569 (org-current-level)))))
7570 (cond ((null current-level) nil) ; Before first headline
7571 ((null prev-level) 0) ; At first headline
7572 (prev-level))))
7574 (defun org-reduced-level (l)
7575 "Compute the effective level of a heading.
7576 This takes into account the setting of `org-odd-levels-only'."
7577 (cond
7578 ((zerop l) 0)
7579 (org-odd-levels-only (1+ (floor (/ l 2))))
7580 (t l)))
7582 (defun org-level-increment ()
7583 "Return the number of stars that will be added or removed at a
7584 time to headlines when structure editing, based on the value of
7585 `org-odd-levels-only'."
7586 (if org-odd-levels-only 2 1))
7588 (defun org-get-valid-level (level &optional change)
7589 "Rectify a level change under the influence of `org-odd-levels-only'
7590 LEVEL is a current level, CHANGE is by how much the level should be
7591 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7592 even level numbers will become the next higher odd number."
7593 (if org-odd-levels-only
7594 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7595 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7596 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7597 (max 1 (+ level (or change 0)))))
7599 (if (boundp 'define-obsolete-function-alias)
7600 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7601 (define-obsolete-function-alias 'org-get-legal-level
7602 'org-get-valid-level)
7603 (define-obsolete-function-alias 'org-get-legal-level
7604 'org-get-valid-level "23.1")))
7606 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7607 ;; ̀org-with-limited-levels'
7608 (defun org-promote ()
7609 "Promote the current heading higher up the tree.
7610 If the region is active in `transient-mark-mode', promote all headings
7611 in the region."
7612 (org-back-to-heading t)
7613 (let* ((level (save-match-data (funcall outline-level)))
7614 (after-change-functions (remove 'flyspell-after-change-function
7615 after-change-functions))
7616 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7617 (diff (abs (- level (length up-head) -1))))
7618 (cond ((and (= level 1) org-called-with-limited-levels
7619 org-allow-promoting-top-level-subtree)
7620 (replace-match "# " nil t))
7621 ((= level 1)
7622 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7623 (t (replace-match up-head nil t)))
7624 ;; Fixup tag positioning
7625 (unless (= level 1)
7626 (and org-auto-align-tags (org-set-tags nil t))
7627 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7628 (run-hooks 'org-after-promote-entry-hook)))
7630 (defun org-demote ()
7631 "Demote the current heading lower down the tree.
7632 If the region is active in `transient-mark-mode', demote all headings
7633 in the region."
7634 (org-back-to-heading t)
7635 (let* ((level (save-match-data (funcall outline-level)))
7636 (after-change-functions (remove 'flyspell-after-change-function
7637 after-change-functions))
7638 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7639 (diff (abs (- level (length down-head) -1))))
7640 (replace-match down-head nil t)
7641 ;; Fixup tag positioning
7642 (and org-auto-align-tags (org-set-tags nil t))
7643 (if org-adapt-indentation (org-fixup-indentation diff))
7644 (run-hooks 'org-after-demote-entry-hook)))
7646 (defun org-cycle-level ()
7647 "Cycle the level of an empty headline through possible states.
7648 This goes first to child, then to parent, level, then up the hierarchy.
7649 After top level, it switches back to sibling level."
7650 (interactive)
7651 (let ((org-adapt-indentation nil))
7652 (when (org-point-at-end-of-empty-headline)
7653 (setq this-command 'org-cycle-level) ; Only needed for caching
7654 (let ((cur-level (org-current-level))
7655 (prev-level (org-get-previous-line-level)))
7656 (cond
7657 ;; If first headline in file, promote to top-level.
7658 ((= prev-level 0)
7659 (loop repeat (/ (- cur-level 1) (org-level-increment))
7660 do (org-do-promote)))
7661 ;; If same level as prev, demote one.
7662 ((= prev-level cur-level)
7663 (org-do-demote))
7664 ;; If parent is top-level, promote to top level if not already.
7665 ((= prev-level 1)
7666 (loop repeat (/ (- cur-level 1) (org-level-increment))
7667 do (org-do-promote)))
7668 ;; If top-level, return to prev-level.
7669 ((= cur-level 1)
7670 (loop repeat (/ (- prev-level 1) (org-level-increment))
7671 do (org-do-demote)))
7672 ;; If less than prev-level, promote one.
7673 ((< cur-level prev-level)
7674 (org-do-promote))
7675 ;; If deeper than prev-level, promote until higher than
7676 ;; prev-level.
7677 ((> cur-level prev-level)
7678 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7679 do (org-do-promote))))
7680 t))))
7682 (defun org-map-tree (fun)
7683 "Call FUN for every heading underneath the current one."
7684 (org-back-to-heading)
7685 (let ((level (funcall outline-level)))
7686 (save-excursion
7687 (funcall fun)
7688 (while (and (progn
7689 (outline-next-heading)
7690 (> (funcall outline-level) level))
7691 (not (eobp)))
7692 (funcall fun)))))
7694 (defun org-map-region (fun beg end)
7695 "Call FUN for every heading between BEG and END."
7696 (let ((org-ignore-region t))
7697 (save-excursion
7698 (setq end (copy-marker end))
7699 (goto-char beg)
7700 (if (and (re-search-forward org-outline-regexp-bol nil t)
7701 (< (point) end))
7702 (funcall fun))
7703 (while (and (progn
7704 (outline-next-heading)
7705 (< (point) end))
7706 (not (eobp)))
7707 (funcall fun)))))
7709 (defvar org-property-end-re) ; silence byte-compiler
7710 (defun org-fixup-indentation (diff)
7711 "Change the indentation in the current entry by DIFF.
7712 However, if any line in the current entry has no indentation, or if it
7713 would end up with no indentation after the change, nothing at all is done."
7714 (save-excursion
7715 (let ((end (save-excursion (outline-next-heading)
7716 (point-marker)))
7717 (prohibit (if (> diff 0)
7718 "^\\S-"
7719 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7720 col)
7721 (unless (save-excursion (end-of-line 1)
7722 (re-search-forward prohibit end t))
7723 (while (and (< (point) end)
7724 (re-search-forward "^[ \t]+" end t))
7725 (goto-char (match-end 0))
7726 (setq col (current-column))
7727 (if (< diff 0) (replace-match ""))
7728 (org-indent-to-column (+ diff col))))
7729 (move-marker end nil))))
7731 (defun org-convert-to-odd-levels ()
7732 "Convert an org-mode file with all levels allowed to one with odd levels.
7733 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7734 level 5 etc."
7735 (interactive)
7736 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7737 (let ((outline-level 'org-outline-level)
7738 (org-odd-levels-only nil) n)
7739 (save-excursion
7740 (goto-char (point-min))
7741 (while (re-search-forward "^\\*\\*+ " nil t)
7742 (setq n (- (length (match-string 0)) 2))
7743 (while (>= (setq n (1- n)) 0)
7744 (org-demote))
7745 (end-of-line 1))))))
7747 (defun org-convert-to-oddeven-levels ()
7748 "Convert an org-mode file with only odd levels to one with odd/even levels.
7749 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7750 file contains a section with an even level, conversion would
7751 destroy the structure of the file. An error is signaled in this
7752 case."
7753 (interactive)
7754 (goto-char (point-min))
7755 ;; First check if there are no even levels
7756 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7757 (org-show-context t)
7758 (error "Not all levels are odd in this file. Conversion not possible"))
7759 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7760 (let ((outline-regexp org-outline-regexp)
7761 (outline-level 'org-outline-level)
7762 (org-odd-levels-only nil) n)
7763 (save-excursion
7764 (goto-char (point-min))
7765 (while (re-search-forward "^\\*\\*+ " nil t)
7766 (setq n (/ (1- (length (match-string 0))) 2))
7767 (while (>= (setq n (1- n)) 0)
7768 (org-promote))
7769 (end-of-line 1))))))
7771 (defun org-tr-level (n)
7772 "Make N odd if required."
7773 (if org-odd-levels-only (1+ (/ n 2)) n))
7775 ;;; Vertical tree motion, cutting and pasting of subtrees
7777 (defun org-move-subtree-up (&optional arg)
7778 "Move the current subtree up past ARG headlines of the same level."
7779 (interactive "p")
7780 (org-move-subtree-down (- (prefix-numeric-value arg))))
7782 (defun org-move-subtree-down (&optional arg)
7783 "Move the current subtree down past ARG headlines of the same level."
7784 (interactive "p")
7785 (setq arg (prefix-numeric-value arg))
7786 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7787 'org-get-last-sibling))
7788 (ins-point (make-marker))
7789 (cnt (abs arg))
7790 (col (current-column))
7791 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7792 ;; Select the tree
7793 (org-back-to-heading)
7794 (setq beg0 (point))
7795 (save-excursion
7796 (setq ne-beg (org-back-over-empty-lines))
7797 (setq beg (point)))
7798 (save-match-data
7799 (save-excursion (outline-end-of-heading)
7800 (setq folded (outline-invisible-p)))
7801 (outline-end-of-subtree))
7802 (outline-next-heading)
7803 (setq ne-end (org-back-over-empty-lines))
7804 (setq end (point))
7805 (goto-char beg0)
7806 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7807 ;; include less whitespace
7808 (save-excursion
7809 (goto-char beg)
7810 (forward-line (- ne-beg ne-end))
7811 (setq beg (point))))
7812 ;; Find insertion point, with error handling
7813 (while (> cnt 0)
7814 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7815 (progn (goto-char beg0)
7816 (error "Cannot move past superior level or buffer limit")))
7817 (setq cnt (1- cnt)))
7818 (if (> arg 0)
7819 ;; Moving forward - still need to move over subtree
7820 (progn (org-end-of-subtree t t)
7821 (save-excursion
7822 (org-back-over-empty-lines)
7823 (or (bolp) (newline)))))
7824 (setq ne-ins (org-back-over-empty-lines))
7825 (move-marker ins-point (point))
7826 (setq txt (buffer-substring beg end))
7827 (org-save-markers-in-region beg end)
7828 (delete-region beg end)
7829 (org-remove-empty-overlays-at beg)
7830 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7831 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7832 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7833 (let ((bbb (point)))
7834 (insert-before-markers txt)
7835 (org-reinstall-markers-in-region bbb)
7836 (move-marker ins-point bbb))
7837 (or (bolp) (insert "\n"))
7838 (setq ins-end (point))
7839 (goto-char ins-point)
7840 (org-skip-whitespace)
7841 (when (and (< arg 0)
7842 (org-first-sibling-p)
7843 (> ne-ins ne-beg))
7844 ;; Move whitespace back to beginning
7845 (save-excursion
7846 (goto-char ins-end)
7847 (let ((kill-whole-line t))
7848 (kill-line (- ne-ins ne-beg)) (point)))
7849 (insert (make-string (- ne-ins ne-beg) ?\n)))
7850 (move-marker ins-point nil)
7851 (if folded
7852 (hide-subtree)
7853 (org-show-entry)
7854 (show-children)
7855 (org-cycle-hide-drawers 'children))
7856 (org-clean-visibility-after-subtree-move)
7857 ;; move back to the initial column we were at
7858 (move-to-column col)))
7860 (defvar org-subtree-clip ""
7861 "Clipboard for cut and paste of subtrees.
7862 This is actually only a copy of the kill, because we use the normal kill
7863 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7865 (defvar org-subtree-clip-folded nil
7866 "Was the last copied subtree folded?
7867 This is used to fold the tree back after pasting.")
7869 (defun org-cut-subtree (&optional n)
7870 "Cut the current subtree into the clipboard.
7871 With prefix arg N, cut this many sequential subtrees.
7872 This is a short-hand for marking the subtree and then cutting it."
7873 (interactive "p")
7874 (org-copy-subtree n 'cut))
7876 (defun org-copy-subtree (&optional n cut force-store-markers)
7877 "Cut the current subtree into the clipboard.
7878 With prefix arg N, cut this many sequential subtrees.
7879 This is a short-hand for marking the subtree and then copying it.
7880 If CUT is non-nil, actually cut the subtree.
7881 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7882 of some markers in the region, even if CUT is non-nil. This is
7883 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7884 (interactive "p")
7885 (let (beg end folded (beg0 (point)))
7886 (if (org-called-interactively-p 'any)
7887 (org-back-to-heading nil) ; take what looks like a subtree
7888 (org-back-to-heading t)) ; take what is really there
7889 (setq beg (point))
7890 (skip-chars-forward " \t\r\n")
7891 (save-match-data
7892 (save-excursion (outline-end-of-heading)
7893 (setq folded (outline-invisible-p)))
7894 (condition-case nil
7895 (org-forward-heading-same-level (1- n) t)
7896 (error nil))
7897 (org-end-of-subtree t t))
7898 (setq end (point))
7899 (goto-char beg0)
7900 (when (> end beg)
7901 (setq org-subtree-clip-folded folded)
7902 (when (or cut force-store-markers)
7903 (org-save-markers-in-region beg end))
7904 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7905 (setq org-subtree-clip (current-kill 0))
7906 (message "%s: Subtree(s) with %d characters"
7907 (if cut "Cut" "Copied")
7908 (length org-subtree-clip)))))
7910 (defun org-paste-subtree (&optional level tree for-yank)
7911 "Paste the clipboard as a subtree, with modification of headline level.
7912 The entire subtree is promoted or demoted in order to match a new headline
7913 level.
7915 If the cursor is at the beginning of a headline, the same level as
7916 that headline is used to paste the tree
7918 If not, the new level is derived from the *visible* headings
7919 before and after the insertion point, and taken to be the inferior headline
7920 level of the two. So if the previous visible heading is level 3 and the
7921 next is level 4 (or vice versa), level 4 will be used for insertion.
7922 This makes sure that the subtree remains an independent subtree and does
7923 not swallow low level entries.
7925 You can also force a different level, either by using a numeric prefix
7926 argument, or by inserting the heading marker by hand. For example, if the
7927 cursor is after \"*****\", then the tree will be shifted to level 5.
7929 If optional TREE is given, use this text instead of the kill ring.
7931 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7932 move back over whitespace before inserting, and move point to the end of
7933 the inserted text when done."
7934 (interactive "P")
7935 (setq tree (or tree (and kill-ring (current-kill 0))))
7936 (unless (org-kill-is-subtree-p tree)
7937 (error "%s"
7938 (substitute-command-keys
7939 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7940 (org-with-limited-levels
7941 (let* ((visp (not (outline-invisible-p)))
7942 (txt tree)
7943 (^re_ "\\(\\*+\\)[ \t]*")
7944 (old-level (if (string-match org-outline-regexp-bol txt)
7945 (- (match-end 0) (match-beginning 0) 1)
7946 -1))
7947 (force-level (cond (level (prefix-numeric-value level))
7948 ((and (looking-at "[ \t]*$")
7949 (string-match
7950 "^\\*+$" (buffer-substring
7951 (point-at-bol) (point))))
7952 (- (match-end 1) (match-beginning 1)))
7953 ((and (bolp)
7954 (looking-at org-outline-regexp))
7955 (- (match-end 0) (point) 1))))
7956 (previous-level (save-excursion
7957 (condition-case nil
7958 (progn
7959 (outline-previous-visible-heading 1)
7960 (if (looking-at ^re_)
7961 (- (match-end 0) (match-beginning 0) 1)
7963 (error 1))))
7964 (next-level (save-excursion
7965 (condition-case nil
7966 (progn
7967 (or (looking-at org-outline-regexp)
7968 (outline-next-visible-heading 1))
7969 (if (looking-at ^re_)
7970 (- (match-end 0) (match-beginning 0) 1)
7972 (error 1))))
7973 (new-level (or force-level (max previous-level next-level)))
7974 (shift (if (or (= old-level -1)
7975 (= new-level -1)
7976 (= old-level new-level))
7978 (- new-level old-level)))
7979 (delta (if (> shift 0) -1 1))
7980 (func (if (> shift 0) 'org-demote 'org-promote))
7981 (org-odd-levels-only nil)
7982 beg end newend)
7983 ;; Remove the forced level indicator
7984 (if force-level
7985 (delete-region (point-at-bol) (point)))
7986 ;; Paste
7987 (beginning-of-line (if (bolp) 1 2))
7988 (setq beg (point))
7989 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7990 (insert-before-markers txt)
7991 (unless (string-match "\n\\'" txt) (insert "\n"))
7992 (setq newend (point))
7993 (org-reinstall-markers-in-region beg)
7994 (setq end (point))
7995 (goto-char beg)
7996 (skip-chars-forward " \t\n\r")
7997 (setq beg (point))
7998 (if (and (outline-invisible-p) visp)
7999 (save-excursion (outline-show-heading)))
8000 ;; Shift if necessary
8001 (unless (= shift 0)
8002 (save-restriction
8003 (narrow-to-region beg end)
8004 (while (not (= shift 0))
8005 (org-map-region func (point-min) (point-max))
8006 (setq shift (+ delta shift)))
8007 (goto-char (point-min))
8008 (setq newend (point-max))))
8009 (when (or (org-called-interactively-p 'interactive) for-yank)
8010 (message "Clipboard pasted as level %d subtree" new-level))
8011 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8012 kill-ring
8013 (eq org-subtree-clip (current-kill 0))
8014 org-subtree-clip-folded)
8015 ;; The tree was folded before it was killed/copied
8016 (hide-subtree))
8017 (and for-yank (goto-char newend)))))
8019 (defun org-kill-is-subtree-p (&optional txt)
8020 "Check if the current kill is an outline subtree, or a set of trees.
8021 Returns nil if kill does not start with a headline, or if the first
8022 headline level is not the largest headline level in the tree.
8023 So this will actually accept several entries of equal levels as well,
8024 which is OK for `org-paste-subtree'.
8025 If optional TXT is given, check this string instead of the current kill."
8026 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8027 (re (org-get-limited-outline-regexp))
8028 (^re (concat "^" re))
8029 (start-level (and kill
8030 (string-match
8031 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8032 kill)
8033 (- (match-end 2) (match-beginning 2) 1)))
8034 (start (1+ (or (match-beginning 2) -1))))
8035 (if (not start-level)
8036 (progn
8037 nil) ;; does not even start with a heading
8038 (catch 'exit
8039 (while (setq start (string-match ^re kill (1+ start)))
8040 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8041 (throw 'exit nil)))
8042 t))))
8044 (defvar org-markers-to-move nil
8045 "Markers that should be moved with a cut-and-paste operation.
8046 Those markers are stored together with their positions relative to
8047 the start of the region.")
8049 (defun org-save-markers-in-region (beg end)
8050 "Check markers in region.
8051 If these markers are between BEG and END, record their position relative
8052 to BEG, so that after moving the block of text, we can put the markers back
8053 into place.
8054 This function gets called just before an entry or tree gets cut from the
8055 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8056 called immediately, to move the markers with the entries."
8057 (setq org-markers-to-move nil)
8058 (when (featurep 'org-clock)
8059 (org-clock-save-markers-for-cut-and-paste beg end))
8060 (when (featurep 'org-agenda)
8061 (org-agenda-save-markers-for-cut-and-paste beg end)))
8063 (defun org-check-and-save-marker (marker beg end)
8064 "Check if MARKER is between BEG and END.
8065 If yes, remember the marker and the distance to BEG."
8066 (when (and (marker-buffer marker)
8067 (equal (marker-buffer marker) (current-buffer)))
8068 (if (and (>= marker beg) (< marker end))
8069 (push (cons marker (- marker beg)) org-markers-to-move))))
8071 (defun org-reinstall-markers-in-region (beg)
8072 "Move all remembered markers to their position relative to BEG."
8073 (mapc (lambda (x)
8074 (move-marker (car x) (+ beg (cdr x))))
8075 org-markers-to-move)
8076 (setq org-markers-to-move nil))
8078 (defun org-narrow-to-subtree ()
8079 "Narrow buffer to the current subtree."
8080 (interactive)
8081 (save-excursion
8082 (save-match-data
8083 (org-with-limited-levels
8084 (narrow-to-region
8085 (progn (org-back-to-heading t) (point))
8086 (progn (org-end-of-subtree t t)
8087 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8088 (point)))))))
8090 (defun org-narrow-to-block ()
8091 "Narrow buffer to the current block."
8092 (interactive)
8093 (let* ((case-fold-search t)
8094 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8095 "^[ \t]*#\\+end_.*")))
8096 (if blockp
8097 (narrow-to-region (car blockp) (cdr blockp))
8098 (error "Not in a block"))))
8100 (eval-when-compile
8101 (defvar org-property-drawer-re))
8103 (defvar org-property-start-re) ;; defined below
8104 (defun org-clone-subtree-with-time-shift (n &optional shift)
8105 "Clone the task (subtree) at point N times.
8106 The clones will be inserted as siblings.
8108 In interactive use, the user will be prompted for the number of
8109 clones to be produced, and for a time SHIFT, which may be a
8110 repeater as used in time stamps, for example `+3d'.
8112 When a valid repeater is given and the entry contains any time
8113 stamps, the clones will become a sequence in time, with time
8114 stamps in the subtree shifted for each clone produced. If SHIFT
8115 is nil or the empty string, time stamps will be left alone. The
8116 ID property of the original subtree is removed.
8118 If the original subtree did contain time stamps with a repeater,
8119 the following will happen:
8120 - the repeater will be removed in each clone
8121 - an additional clone will be produced, with the current, unshifted
8122 date(s) in the entry.
8123 - the original entry will be placed *after* all the clones, with
8124 repeater intact.
8125 - the start days in the repeater in the original entry will be shifted
8126 to past the last clone.
8127 In this way you can spell out a number of instances of a repeating task,
8128 and still retain the repeater to cover future instances of the task."
8129 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8130 (let (beg end template task idprop
8131 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8132 (drawer-re org-drawer-regexp))
8133 (if (not (and (integerp n) (> n 0)))
8134 (error "Invalid number of replications %s" n))
8135 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8136 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8137 shift)))
8138 (error "Invalid shift specification %s" shift))
8139 (when doshift
8140 (setq shift-n (string-to-number (match-string 1 shift))
8141 shift-what (cdr (assoc (match-string 2 shift)
8142 '(("d" . day) ("w" . week)
8143 ("m" . month) ("y" . year))))))
8144 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8145 (setq nmin 1 nmax n)
8146 (org-back-to-heading t)
8147 (setq beg (point))
8148 (setq idprop (org-entry-get nil "ID"))
8149 (org-end-of-subtree t t)
8150 (or (bolp) (insert "\n"))
8151 (setq end (point))
8152 (setq template (buffer-substring beg end))
8153 (when (and doshift
8154 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8155 (delete-region beg end)
8156 (setq end beg)
8157 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8158 (goto-char end)
8159 (loop for n from nmin to nmax do
8160 ;; prepare clone
8161 (with-temp-buffer
8162 (insert template)
8163 (org-mode)
8164 (goto-char (point-min))
8165 (org-show-subtree)
8166 (and idprop (if org-clone-delete-id
8167 (org-entry-delete nil "ID")
8168 (org-id-get-create t)))
8169 (unless (= n 0)
8170 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8171 (kill-whole-line))
8172 (goto-char (point-min))
8173 (while (re-search-forward drawer-re nil t)
8174 (mapc (lambda (d)
8175 (org-remove-empty-drawer-at d (point))) org-drawers)))
8176 (goto-char (point-min))
8177 (when doshift
8178 (while (re-search-forward org-ts-regexp-both nil t)
8179 (org-timestamp-change (* n shift-n) shift-what))
8180 (unless (= n n-no-remove)
8181 (goto-char (point-min))
8182 (while (re-search-forward org-ts-regexp nil t)
8183 (save-excursion
8184 (goto-char (match-beginning 0))
8185 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8186 (delete-region (match-beginning 1) (match-end 1)))))))
8187 (setq task (buffer-string)))
8188 (insert task))
8189 (goto-char beg)))
8191 ;;; Outline Sorting
8193 (defun org-sort (with-case)
8194 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8195 Optional argument WITH-CASE means sort case-sensitively."
8196 (interactive "P")
8197 (cond
8198 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8199 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8201 (org-call-with-arg 'org-sort-entries with-case))))
8203 (defun org-sort-remove-invisible (s)
8204 (remove-text-properties 0 (length s) org-rm-props s)
8205 (while (string-match org-bracket-link-regexp s)
8206 (setq s (replace-match (if (match-end 2)
8207 (match-string 3 s)
8208 (match-string 1 s)) t t s)))
8211 (defvar org-priority-regexp) ; defined later in the file
8213 (defvar org-after-sorting-entries-or-items-hook nil
8214 "Hook that is run after a bunch of entries or items have been sorted.
8215 When children are sorted, the cursor is in the parent line when this
8216 hook gets called. When a region or a plain list is sorted, the cursor
8217 will be in the first entry of the sorted region/list.")
8219 (defun org-sort-entries
8220 (&optional with-case sorting-type getkey-func compare-func property)
8221 "Sort entries on a certain level of an outline tree.
8222 If there is an active region, the entries in the region are sorted.
8223 Else, if the cursor is before the first entry, sort the top-level items.
8224 Else, the children of the entry at point are sorted.
8226 Sorting can be alphabetically, numerically, by date/time as given by
8227 a time stamp, by a property or by priority.
8229 The command prompts for the sorting type unless it has been given to the
8230 function through the SORTING-TYPE argument, which needs to be a character,
8231 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8232 precise meaning of each character:
8234 n Numerically, by converting the beginning of the entry/item to a number.
8235 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8236 o By order of TODO keywords.
8237 t By date/time, either the first active time stamp in the entry, or, if
8238 none exist, by the first inactive one.
8239 s By the scheduled date/time.
8240 d By deadline date/time.
8241 c By creation time, which is assumed to be the first inactive time stamp
8242 at the beginning of a line.
8243 p By priority according to the cookie.
8244 r By the value of a property.
8246 Capital letters will reverse the sort order.
8248 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8249 called with point at the beginning of the record. It must return either
8250 a string or a number that should serve as the sorting key for that record.
8252 Comparing entries ignores case by default. However, with an optional argument
8253 WITH-CASE, the sorting considers case as well."
8254 (interactive "P")
8255 (let ((case-func (if with-case 'identity 'downcase))
8256 (cmstr
8257 ;; The clock marker is lost when using `sort-subr', let's
8258 ;; store the clocking string.
8259 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8260 (save-excursion
8261 (goto-char org-clock-marker)
8262 (looking-back "^.*") (match-string-no-properties 0))))
8263 start beg end stars re re2
8264 txt what tmp)
8265 ;; Find beginning and end of region to sort
8266 (cond
8267 ((org-region-active-p)
8268 ;; we will sort the region
8269 (setq end (region-end)
8270 what "region")
8271 (goto-char (region-beginning))
8272 (if (not (org-at-heading-p)) (outline-next-heading))
8273 (setq start (point)))
8274 ((or (org-at-heading-p)
8275 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8276 ;; we will sort the children of the current headline
8277 (org-back-to-heading)
8278 (setq start (point)
8279 end (progn (org-end-of-subtree t t)
8280 (or (bolp) (insert "\n"))
8281 (org-back-over-empty-lines)
8282 (point))
8283 what "children")
8284 (goto-char start)
8285 (show-subtree)
8286 (outline-next-heading))
8288 ;; we will sort the top-level entries in this file
8289 (goto-char (point-min))
8290 (or (org-at-heading-p) (outline-next-heading))
8291 (setq start (point))
8292 (goto-char (point-max))
8293 (beginning-of-line 1)
8294 (when (looking-at ".*?\\S-")
8295 ;; File ends in a non-white line
8296 (end-of-line 1)
8297 (insert "\n"))
8298 (setq end (point-max))
8299 (setq what "top-level")
8300 (goto-char start)
8301 (show-all)))
8303 (setq beg (point))
8304 (if (>= beg end) (error "Nothing to sort"))
8306 (looking-at "\\(\\*+\\)")
8307 (setq stars (match-string 1)
8308 re (concat "^" (regexp-quote stars) " +")
8309 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8310 txt (buffer-substring beg end))
8311 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8312 (if (and (not (equal stars "*")) (string-match re2 txt))
8313 (error "Region to sort contains a level above the first entry"))
8315 (unless sorting-type
8316 (message
8317 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8318 [t]ime [s]cheduled [d]eadline [c]reated
8319 A/N/P/R/O/F/T/S/D/C means reversed:"
8320 what)
8321 (setq sorting-type (read-char-exclusive))
8323 (unless getkey-func
8324 (and (= (downcase sorting-type) ?f)
8325 (setq getkey-func
8326 (org-icompleting-read "Sort using function: "
8327 obarray 'fboundp t nil nil))
8328 (setq getkey-func (intern getkey-func))))
8330 (and (= (downcase sorting-type) ?r)
8331 (not property)
8332 (setq property
8333 (org-icompleting-read "Property: "
8334 (mapcar 'list (org-buffer-property-keys t))
8335 nil t))))
8337 (message "Sorting entries...")
8339 (save-restriction
8340 (narrow-to-region start end)
8341 (let ((dcst (downcase sorting-type))
8342 (case-fold-search nil)
8343 (now (current-time)))
8344 (sort-subr
8345 (/= dcst sorting-type)
8346 ;; This function moves to the beginning character of the "record" to
8347 ;; be sorted.
8348 (lambda nil
8349 (if (re-search-forward re nil t)
8350 (goto-char (match-beginning 0))
8351 (goto-char (point-max))))
8352 ;; This function moves to the last character of the "record" being
8353 ;; sorted.
8354 (lambda nil
8355 (save-match-data
8356 (condition-case nil
8357 (outline-forward-same-level 1)
8358 (error
8359 (goto-char (point-max))))))
8360 ;; This function returns the value that gets sorted against.
8361 (lambda nil
8362 (cond
8363 ((= dcst ?n)
8364 (if (looking-at org-complex-heading-regexp)
8365 (string-to-number (match-string 4))
8366 nil))
8367 ((= dcst ?a)
8368 (if (looking-at org-complex-heading-regexp)
8369 (funcall case-func (match-string 4))
8370 nil))
8371 ((= dcst ?t)
8372 (let ((end (save-excursion (outline-next-heading) (point))))
8373 (if (or (re-search-forward org-ts-regexp end t)
8374 (re-search-forward org-ts-regexp-both end t))
8375 (org-time-string-to-seconds (match-string 0))
8376 (org-float-time now))))
8377 ((= dcst ?c)
8378 (let ((end (save-excursion (outline-next-heading) (point))))
8379 (if (re-search-forward
8380 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8381 end t)
8382 (org-time-string-to-seconds (match-string 0))
8383 (org-float-time now))))
8384 ((= dcst ?s)
8385 (let ((end (save-excursion (outline-next-heading) (point))))
8386 (if (re-search-forward org-scheduled-time-regexp end t)
8387 (org-time-string-to-seconds (match-string 1))
8388 (org-float-time now))))
8389 ((= dcst ?d)
8390 (let ((end (save-excursion (outline-next-heading) (point))))
8391 (if (re-search-forward org-deadline-time-regexp end t)
8392 (org-time-string-to-seconds (match-string 1))
8393 (org-float-time now))))
8394 ((= dcst ?p)
8395 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8396 (string-to-char (match-string 2))
8397 org-default-priority))
8398 ((= dcst ?r)
8399 (or (org-entry-get nil property) ""))
8400 ((= dcst ?o)
8401 (if (looking-at org-complex-heading-regexp)
8402 (- 9999 (length (member (match-string 2)
8403 org-todo-keywords-1)))))
8404 ((= dcst ?f)
8405 (if getkey-func
8406 (progn
8407 (setq tmp (funcall getkey-func))
8408 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8409 tmp)
8410 (error "Invalid key function `%s'" getkey-func)))
8411 (t (error "Invalid sorting type `%c'" sorting-type))))
8413 (cond
8414 ((= dcst ?a) 'string<)
8415 ((= dcst ?f) compare-func)
8416 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8417 (run-hooks 'org-after-sorting-entries-or-items-hook)
8418 ;; Reset the clock marker if needed
8419 (when cmstr
8420 (save-excursion
8421 (goto-char start)
8422 (search-forward cmstr nil t)
8423 (move-marker org-clock-marker (point))))
8424 (message "Sorting entries...done")))
8426 (defun org-do-sort (table what &optional with-case sorting-type)
8427 "Sort TABLE of WHAT according to SORTING-TYPE.
8428 The user will be prompted for the SORTING-TYPE if the call to this
8429 function does not specify it. WHAT is only for the prompt, to indicate
8430 what is being sorted. The sorting key will be extracted from
8431 the car of the elements of the table.
8432 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8433 (unless sorting-type
8434 (message
8435 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8436 what)
8437 (setq sorting-type (read-char-exclusive)))
8438 (let ((dcst (downcase sorting-type))
8439 extractfun comparefun)
8440 ;; Define the appropriate functions
8441 (cond
8442 ((= dcst ?n)
8443 (setq extractfun 'string-to-number
8444 comparefun (if (= dcst sorting-type) '< '>)))
8445 ((= dcst ?a)
8446 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8447 (lambda(x) (downcase (org-sort-remove-invisible x))))
8448 comparefun (if (= dcst sorting-type)
8449 'string<
8450 (lambda (a b) (and (not (string< a b))
8451 (not (string= a b)))))))
8452 ((= dcst ?t)
8453 (setq extractfun
8454 (lambda (x)
8455 (if (or (string-match org-ts-regexp x)
8456 (string-match org-ts-regexp-both x))
8457 (org-float-time
8458 (org-time-string-to-time (match-string 0 x)))
8460 comparefun (if (= dcst sorting-type) '< '>)))
8461 (t (error "Invalid sorting type `%c'" sorting-type)))
8463 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8464 table)
8465 (lambda (a b) (funcall comparefun (car a) (car b))))))
8468 ;;; The orgstruct minor mode
8470 ;; Define a minor mode which can be used in other modes in order to
8471 ;; integrate the org-mode structure editing commands.
8473 ;; This is really a hack, because the org-mode structure commands use
8474 ;; keys which normally belong to the major mode. Here is how it
8475 ;; works: The minor mode defines all the keys necessary to operate the
8476 ;; structure commands, but wraps the commands into a function which
8477 ;; tests if the cursor is currently at a headline or a plain list
8478 ;; item. If that is the case, the structure command is used,
8479 ;; temporarily setting many Org-mode variables like regular
8480 ;; expressions for filling etc. However, when any of those keys is
8481 ;; used at a different location, function uses `key-binding' to look
8482 ;; up if the key has an associated command in another currently active
8483 ;; keymap (minor modes, major mode, global), and executes that
8484 ;; command. There might be problems if any of the keys is otherwise
8485 ;; used as a prefix key.
8487 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8488 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8489 ;; addresses this by checking explicitly for both bindings.
8491 (defvar orgstruct-mode-map (make-sparse-keymap)
8492 "Keymap for the minor `orgstruct-mode'.")
8494 (defvar org-local-vars nil
8495 "List of local variables, for use by `orgstruct-mode'.")
8497 ;;;###autoload
8498 (define-minor-mode orgstruct-mode
8499 "Toggle the minor mode `orgstruct-mode'.
8500 This mode is for using Org-mode structure commands in other
8501 modes. The following keys behave as if Org-mode were active, if
8502 the cursor is on a headline, or on a plain list item (both as
8503 defined by Org-mode).
8505 M-up Move entry/item up
8506 M-down Move entry/item down
8507 M-left Promote
8508 M-right Demote
8509 M-S-up Move entry/item up
8510 M-S-down Move entry/item down
8511 M-S-left Promote subtree
8512 M-S-right Demote subtree
8513 M-q Fill paragraph and items like in Org-mode
8514 C-c ^ Sort entries
8515 C-c - Cycle list bullet
8516 TAB Cycle item visibility
8517 M-RET Insert new heading/item
8518 S-M-RET Insert new TODO heading / Checkbox item
8519 C-c C-c Set tags / toggle checkbox"
8520 nil " OrgStruct" nil
8521 (org-load-modules-maybe)
8522 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8524 ;;;###autoload
8525 (defun turn-on-orgstruct ()
8526 "Unconditionally turn on `orgstruct-mode'."
8527 (orgstruct-mode 1))
8529 (defvar org-fb-vars nil)
8530 (make-variable-buffer-local 'org-fb-vars)
8531 (defun orgstruct++-mode (&optional arg)
8532 "Toggle `orgstruct-mode', the enhanced version of it.
8533 In addition to setting orgstruct-mode, this also exports all
8534 indentation and autofilling variables from org-mode into the
8535 buffer. It will also recognize item context in multiline items."
8536 (interactive "P")
8537 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8538 (if (< arg 1)
8539 (progn (orgstruct-mode -1)
8540 (mapc (lambda(v)
8541 (org-set-local (car v)
8542 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8543 org-fb-vars))
8544 (orgstruct-mode 1)
8545 (setq org-fb-vars nil)
8546 (let (var val)
8547 (mapc
8548 (lambda (x)
8549 (when (string-match
8550 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8551 (symbol-name (car x)))
8552 (setq var (car x) val (nth 1 x))
8553 (push (list var `(quote ,(eval var))) org-fb-vars)
8554 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8555 org-local-vars)
8556 (org-set-local 'orgstruct-is-++ t))))
8558 (defvar orgstruct-is-++ nil
8559 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8560 (make-variable-buffer-local 'orgstruct-is-++)
8562 ;;;###autoload
8563 (defun turn-on-orgstruct++ ()
8564 "Unconditionally turn on `orgstruct++-mode'."
8565 (orgstruct++-mode 1))
8567 (defun orgstruct-error ()
8568 "Error when there is no default binding for a structure key."
8569 (interactive)
8570 (error "This key has no function outside structure elements"))
8572 (defun orgstruct-setup ()
8573 "Setup orgstruct keymaps."
8574 (let ((nfunc 0)
8575 (bindings
8576 (list
8577 '([(meta up)] org-metaup)
8578 '([(meta down)] org-metadown)
8579 '([(meta left)] org-metaleft)
8580 '([(meta right)] org-metaright)
8581 '([(meta shift up)] org-shiftmetaup)
8582 '([(meta shift down)] org-shiftmetadown)
8583 '([(meta shift left)] org-shiftmetaleft)
8584 '([(meta shift right)] org-shiftmetaright)
8585 '([?\e (up)] org-metaup)
8586 '([?\e (down)] org-metadown)
8587 '([?\e (left)] org-metaleft)
8588 '([?\e (right)] org-metaright)
8589 '([?\e (shift up)] org-shiftmetaup)
8590 '([?\e (shift down)] org-shiftmetadown)
8591 '([?\e (shift left)] org-shiftmetaleft)
8592 '([?\e (shift right)] org-shiftmetaright)
8593 '([(shift up)] org-shiftup)
8594 '([(shift down)] org-shiftdown)
8595 '([(shift left)] org-shiftleft)
8596 '([(shift right)] org-shiftright)
8597 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8598 '("\M-q" fill-paragraph)
8599 '("\C-c^" org-sort)
8600 '("\C-c-" org-cycle-list-bullet)))
8601 elt key fun cmd)
8602 (while (setq elt (pop bindings))
8603 (setq nfunc (1+ nfunc))
8604 (setq key (org-key (car elt))
8605 fun (nth 1 elt)
8606 cmd (orgstruct-make-binding fun nfunc key))
8607 (org-defkey orgstruct-mode-map key cmd))
8609 ;; Prevent an error for users who forgot to make autoloads
8610 (require 'org-element)
8612 ;; Special treatment needed for TAB and RET
8613 (org-defkey orgstruct-mode-map [(tab)]
8614 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8615 (org-defkey orgstruct-mode-map "\C-i"
8616 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8618 (org-defkey orgstruct-mode-map "\M-\C-m"
8619 (orgstruct-make-binding 'org-insert-heading 105
8620 "\M-\C-m" [(meta return)]))
8621 (org-defkey orgstruct-mode-map [(meta return)]
8622 (orgstruct-make-binding 'org-insert-heading 106
8623 [(meta return)] "\M-\C-m"))
8625 (org-defkey orgstruct-mode-map [(shift meta return)]
8626 (orgstruct-make-binding 'org-insert-todo-heading 107
8627 [(meta return)] "\M-\C-m"))
8629 (org-defkey orgstruct-mode-map "\e\C-m"
8630 (orgstruct-make-binding 'org-insert-heading 108
8631 "\e\C-m" [?\e (return)]))
8632 (org-defkey orgstruct-mode-map [?\e (return)]
8633 (orgstruct-make-binding 'org-insert-heading 109
8634 [?\e (return)] "\e\C-m"))
8635 (org-defkey orgstruct-mode-map [?\e (shift return)]
8636 (orgstruct-make-binding 'org-insert-todo-heading 110
8637 [?\e (return)] "\e\C-m"))
8639 (unless org-local-vars
8640 (setq org-local-vars (org-get-local-variables)))
8644 (defun orgstruct-make-binding (fun n &rest keys)
8645 "Create a function for binding in the structure minor mode.
8646 FUN is the command to call inside a table. N is used to create a unique
8647 command name. KEYS are keys that should be checked in for a command
8648 to execute outside of tables."
8649 (eval
8650 (list 'defun
8651 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8652 '(arg)
8653 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8654 "Outside of structure, run the binding of `"
8655 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8656 "'.")
8657 '(interactive "p")
8658 (list 'if
8659 `(org-context-p 'headline 'item
8660 (and orgstruct-is-++
8661 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8662 'item-body))
8663 (list 'org-run-like-in-org-mode (list 'quote fun))
8664 (list 'let '(orgstruct-mode)
8665 (list 'call-interactively
8666 (append '(or)
8667 (mapcar (lambda (k)
8668 (list 'key-binding k))
8669 keys)
8670 '('orgstruct-error))))))))
8672 (defun org-contextualize-keys (alist contexts)
8673 "Return valid elements in ALIST depending on CONTEXTS.
8675 `org-agenda-custom-commands' or `org-capture-templates' are the
8676 values used for ALIST, and `org-agenda-custom-commands-contexts'
8677 or `org-capture-templates-contexts' are the associated contexts
8678 definitions."
8679 (let ((contexts
8680 ;; normalize contexts
8681 (mapcar
8682 (lambda(c) (cond ((listp (cadr c))
8683 (list (car c) (car c) (cadr c)))
8684 ((string= "" (cadr c))
8685 (list (car c) (car c) (caddr c)))
8686 (t c))) contexts))
8687 (a alist) c r s)
8688 ;; loop over all commands or templates
8689 (while (setq c (pop a))
8690 (let (vrules repl)
8691 (cond
8692 ((not (assoc (car c) contexts))
8693 (push c r))
8694 ((and (assoc (car c) contexts)
8695 (setq vrules (org-contextualize-validate-key
8696 (car c) contexts)))
8697 (mapc (lambda (vr)
8698 (when (not (equal (car vr) (cadr vr)))
8699 (setq repl vr))) vrules)
8700 (if (not repl) (push c r)
8701 (push (cadr repl) s)
8702 (push
8703 (cons (car c)
8704 (cdr (or (assoc (cadr repl) alist)
8705 (error "Undefined key `%s' as contextual replacement for `%s'"
8706 (cadr repl) (car c)))))
8707 r))))))
8708 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8709 (delq
8711 (delete-dups
8712 (mapcar (lambda (x)
8713 (let ((tpl (car x)))
8714 (when (not (delq
8716 (mapcar (lambda(y)
8717 (equal y tpl)) s))) x)))
8718 (reverse r))))))
8720 (defun org-contextualize-validate-key (key contexts)
8721 "Check CONTEXTS for agenda or capture KEY."
8722 (let (r rr res)
8723 (while (setq r (pop contexts))
8724 (mapc
8725 (lambda (rr)
8726 (when
8727 (and (equal key (car r))
8728 (if (functionp rr) (funcall rr)
8729 (or (and (eq (car rr) 'in-file)
8730 (buffer-file-name)
8731 (string-match (cdr rr) (buffer-file-name)))
8732 (and (eq (car rr) 'in-mode)
8733 (string-match (cdr rr) (symbol-name major-mode)))
8734 (when (and (eq (car rr) 'not-in-file)
8735 (buffer-file-name))
8736 (not (string-match (cdr rr) (buffer-file-name))))
8737 (when (eq (car rr) 'not-in-mode)
8738 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8739 (push r res)))
8740 (car (last r))))
8741 (delete-dups (delq nil res))))
8743 (defun org-context-p (&rest contexts)
8744 "Check if local context is any of CONTEXTS.
8745 Possible values in the list of contexts are `table', `headline', and `item'."
8746 (let ((pos (point)))
8747 (goto-char (point-at-bol))
8748 (prog1 (or (and (memq 'table contexts)
8749 (looking-at "[ \t]*|"))
8750 (and (memq 'headline contexts)
8751 (looking-at org-outline-regexp))
8752 (and (memq 'item contexts)
8753 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8754 (and (memq 'item-body contexts)
8755 (org-in-item-p)))
8756 (goto-char pos))))
8758 (defun org-get-local-variables ()
8759 "Return a list of all local variables in an Org mode buffer."
8760 (let (varlist)
8761 (with-current-buffer (get-buffer-create "*Org tmp*")
8762 (erase-buffer)
8763 (org-mode)
8764 (setq varlist (buffer-local-variables)))
8765 (kill-buffer "*Org tmp*")
8766 (delq nil
8767 (mapcar
8768 (lambda (x)
8769 (setq x
8770 (if (symbolp x)
8771 (list x)
8772 (list (car x) (list 'quote (cdr x)))))
8773 (if (string-match
8774 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8775 (symbol-name (car x)))
8776 x nil))
8777 varlist))))
8779 (defun org-clone-local-variables (from-buffer &optional regexp)
8780 "Clone local variables from FROM-BUFFER.
8781 Optional argument REGEXP selects variables to clone."
8782 (mapc
8783 (lambda (pair)
8784 (and (symbolp (car pair))
8785 (or (null regexp)
8786 (string-match regexp (symbol-name (car pair))))
8787 (set (make-local-variable (car pair))
8788 (cdr pair))))
8789 (buffer-local-variables from-buffer)))
8791 ;;;###autoload
8792 (defun org-run-like-in-org-mode (cmd)
8793 "Run a command, pretending that the current buffer is in Org-mode.
8794 This will temporarily bind local variables that are typically bound in
8795 Org-mode to the values they have in Org-mode, and then interactively
8796 call CMD."
8797 (org-load-modules-maybe)
8798 (unless org-local-vars
8799 (setq org-local-vars (org-get-local-variables)))
8800 (eval (list 'let org-local-vars
8801 (list 'call-interactively (list 'quote cmd)))))
8803 ;;;; Archiving
8805 (defun org-get-category (&optional pos force-refresh)
8806 "Get the category applying to position POS."
8807 (save-match-data
8808 (if force-refresh (org-refresh-category-properties))
8809 (let ((pos (or pos (point))))
8810 (or (get-text-property pos 'org-category)
8811 (progn (org-refresh-category-properties)
8812 (get-text-property pos 'org-category))))))
8814 (defun org-refresh-category-properties ()
8815 "Refresh category text properties in the buffer."
8816 (let ((case-fold-search t)
8817 (inhibit-read-only t)
8818 (def-cat (cond
8819 ((null org-category)
8820 (if buffer-file-name
8821 (file-name-sans-extension
8822 (file-name-nondirectory buffer-file-name))
8823 "???"))
8824 ((symbolp org-category) (symbol-name org-category))
8825 (t org-category)))
8826 beg end cat pos optionp)
8827 (org-unmodified
8828 (save-excursion
8829 (save-restriction
8830 (widen)
8831 (goto-char (point-min))
8832 (put-text-property (point) (point-max) 'org-category def-cat)
8833 (while (re-search-forward
8834 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8835 (setq pos (match-end 0)
8836 optionp (equal (char-after (match-beginning 0)) ?#)
8837 cat (org-trim (match-string 2)))
8838 (if optionp
8839 (setq beg (point-at-bol) end (point-max))
8840 (org-back-to-heading t)
8841 (setq beg (point) end (org-end-of-subtree t t)))
8842 (put-text-property beg end 'org-category cat)
8843 (put-text-property beg end 'org-category-position beg)
8844 (goto-char pos)))))))
8846 (defun org-refresh-properties (dprop tprop)
8847 "Refresh buffer text properties.
8848 DPROP is the drawer property and TPROP is the corresponding text
8849 property to set."
8850 (let ((case-fold-search t)
8851 (inhibit-read-only t) p)
8852 (org-unmodified
8853 (save-excursion
8854 (save-restriction
8855 (widen)
8856 (goto-char (point-min))
8857 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8858 (setq p (org-match-string-no-properties 1))
8859 (save-excursion
8860 (org-back-to-heading t)
8861 (put-text-property
8862 (point-at-bol) (point-at-eol) tprop p))))))))
8865 ;;;; Link Stuff
8867 ;;; Link abbreviations
8869 (defun org-link-expand-abbrev (link)
8870 "Apply replacements as defined in `org-link-abbrev-alist'."
8871 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8872 (let* ((key (match-string 1 link))
8873 (as (or (assoc key org-link-abbrev-alist-local)
8874 (assoc key org-link-abbrev-alist)))
8875 (tag (and (match-end 2) (match-string 3 link)))
8876 rpl)
8877 (if (not as)
8878 link
8879 (setq rpl (cdr as))
8880 (cond
8881 ((symbolp rpl) (funcall rpl tag))
8882 ((string-match "%(\\([^)]+\\))" rpl)
8883 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8884 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8885 ((string-match "%h" rpl)
8886 (replace-match (url-hexify-string (or tag "")) t t rpl))
8887 (t (concat rpl tag)))))
8888 link))
8890 ;;; Storing and inserting links
8892 (defvar org-insert-link-history nil
8893 "Minibuffer history for links inserted with `org-insert-link'.")
8895 (defvar org-stored-links nil
8896 "Contains the links stored with `org-store-link'.")
8898 (defvar org-store-link-plist nil
8899 "Plist with info about the most recently link created with `org-store-link'.")
8901 (defvar org-link-protocols nil
8902 "Link protocols added to Org-mode using `org-add-link-type'.")
8904 (defvar org-store-link-functions nil
8905 "List of functions that are called to create and store a link.
8906 Each function will be called in turn until one returns a non-nil
8907 value. Each function should check if it is responsible for creating
8908 this link (for example by looking at the major mode).
8909 If not, it must exit and return nil.
8910 If yes, it should return a non-nil value after a calling
8911 `org-store-link-props' with a list of properties and values.
8912 Special properties are:
8914 :type The link prefix, like \"http\". This must be given.
8915 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8916 This is obligatory as well.
8917 :description Optional default description for the second pair
8918 of brackets in an Org-mode link. The user can still change
8919 this when inserting this link into an Org-mode buffer.
8921 In addition to these, any additional properties can be specified
8922 and then used in capture templates.")
8924 (defun org-add-link-type (type &optional follow export)
8925 "Add TYPE to the list of `org-link-types'.
8926 Re-compute all regular expressions depending on `org-link-types'
8928 FOLLOW and EXPORT are two functions.
8930 FOLLOW should take the link path as the single argument and do whatever
8931 is necessary to follow the link, for example find a file or display
8932 a mail message.
8934 EXPORT should format the link path for export to one of the export formats.
8935 It should be a function accepting three arguments:
8937 path the path of the link, the text after the prefix (like \"http:\")
8938 desc the description of the link, if any, or a description added by
8939 org-export-normalize-links if there is none
8940 format the export format, a symbol like `html' or `latex' or `ascii'..
8942 The function may use the FORMAT information to return different values
8943 depending on the format. The return value will be put literally into
8944 the exported file. If the return value is nil, this means Org should
8945 do what it normally does with links which do not have EXPORT defined.
8947 Org-mode has a built-in default for exporting links. If you are happy with
8948 this default, there is no need to define an export function for the link
8949 type. For a simple example of an export function, see `org-bbdb.el'."
8950 (add-to-list 'org-link-types type t)
8951 (org-make-link-regexps)
8952 (if (assoc type org-link-protocols)
8953 (setcdr (assoc type org-link-protocols) (list follow export))
8954 (push (list type follow export) org-link-protocols)))
8956 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8957 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8959 ;;;###autoload
8960 (defun org-store-link (arg)
8961 "\\<org-mode-map>Store an org-link to the current location.
8962 This link is added to `org-stored-links' and can later be inserted
8963 into an org-buffer with \\[org-insert-link].
8965 For some link types, a prefix arg is interpreted.
8966 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8967 For file links, arg negates `org-context-in-file-links'.
8969 A double prefix arg force skipping storing functions that are not
8970 part of Org's core."
8971 (interactive "P")
8972 (org-load-modules-maybe)
8973 (setq org-store-link-plist nil) ; reset
8974 (org-with-limited-levels
8975 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8976 (cond
8977 ((and (not (equal arg '(16)))
8978 (setq sfuns
8979 (delq
8980 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8981 org-store-link-functions))
8982 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8983 (or (and (cdr sfuns)
8984 (funcall (intern
8985 (completing-read "Which function for creating the link? "
8986 sfunsn t (car sfunsn)))))
8987 (funcall (caar sfuns)))
8988 (setq link (plist-get org-store-link-plist :link)
8989 desc (or (plist-get org-store-link-plist :description) link))))
8990 ((org-src-edit-buffer-p)
8991 (let (label gc)
8992 (while (or (not label)
8993 (save-excursion
8994 (save-restriction
8995 (widen)
8996 (goto-char (point-min))
8997 (re-search-forward
8998 (regexp-quote (format org-coderef-label-format label))
8999 nil t))))
9000 (when label (message "Label exists already") (sit-for 2))
9001 (setq label (read-string "Code line label: " label)))
9002 (end-of-line 1)
9003 (setq link (format org-coderef-label-format label))
9004 (setq gc (- 79 (length link)))
9005 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9006 (insert link)
9007 (setq link (concat "(" label ")") desc nil)))
9009 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9010 ;; We are in the agenda, link to referenced location
9011 (let ((m (or (get-text-property (point) 'org-hd-marker)
9012 (get-text-property (point) 'org-marker))))
9013 (when m
9014 (org-with-point-at m
9015 (setq agenda-link
9016 (if (org-called-interactively-p 'any)
9017 (call-interactively 'org-store-link)
9018 (org-store-link nil)))))))
9020 ((eq major-mode 'calendar-mode)
9021 (let ((cd (calendar-cursor-to-date)))
9022 (setq link
9023 (format-time-string
9024 (car org-time-stamp-formats)
9025 (apply 'encode-time
9026 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9027 nil nil nil))))
9028 (org-store-link-props :type "calendar" :date cd)))
9030 ((eq major-mode 'help-mode)
9031 (setq link (concat "help:" (save-excursion
9032 (goto-char (point-min))
9033 (looking-at "^[^ ]+")
9034 (match-string 0))))
9035 (org-store-link-props :type "help"))
9037 ((eq major-mode 'w3-mode)
9038 (setq cpltxt (if (and (buffer-name)
9039 (not (string-match "Untitled" (buffer-name))))
9040 (buffer-name)
9041 (url-view-url t))
9042 link (url-view-url t))
9043 (org-store-link-props :type "w3" :url (url-view-url t)))
9045 ((setq search (run-hook-with-args-until-success
9046 'org-create-file-search-functions))
9047 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9048 "::" search))
9049 (setq cpltxt (or description link)))
9051 ((eq major-mode 'image-mode)
9052 (setq cpltxt (concat "file:"
9053 (abbreviate-file-name buffer-file-name))
9054 link cpltxt)
9055 (org-store-link-props :type "image" :file buffer-file-name))
9057 ((eq major-mode 'dired-mode)
9058 ;; link to the file in the current line
9059 (let ((file (dired-get-filename nil t)))
9060 (setq file (if file
9061 (abbreviate-file-name
9062 (expand-file-name (dired-get-filename nil t)))
9063 ;; otherwise, no file so use current directory.
9064 default-directory))
9065 (setq cpltxt (concat "file:" file)
9066 link cpltxt)))
9068 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9069 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9070 (cond
9071 ((org-in-regexp "<<\\(.*?\\)>>")
9072 (setq cpltxt
9073 (concat "file:"
9074 (abbreviate-file-name
9075 (buffer-file-name (buffer-base-buffer)))
9076 "::" (match-string 1))
9077 link cpltxt))
9078 ((and (featurep 'org-id)
9079 (or (eq org-id-link-to-org-use-id t)
9080 (and (org-called-interactively-p 'any)
9081 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9082 (and (eq org-id-link-to-org-use-id
9083 'create-if-interactive-and-no-custom-id)
9084 (not custom-id))))
9085 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9086 ;; We can make a link using the ID.
9087 (setq link (condition-case nil
9088 (prog1 (org-id-store-link)
9089 (setq desc (plist-get org-store-link-plist :description)))
9090 (error
9091 ;; probably before first headline, link to file only
9092 (concat "file:"
9093 (abbreviate-file-name
9094 (buffer-file-name (buffer-base-buffer))))))))
9096 ;; Just link to current headline
9097 (setq cpltxt (concat "file:"
9098 (abbreviate-file-name
9099 (buffer-file-name (buffer-base-buffer)))))
9100 ;; Add a context search string
9101 (when (org-xor org-context-in-file-links arg)
9102 (let* ((ee (org-element-at-point))
9103 (et (org-element-type ee))
9104 (ev (plist-get (cadr ee) :value)))
9105 (setq txt (cond
9106 ((org-at-heading-p) nil)
9107 ((eq et 'keyword) ev)
9108 ((org-region-active-p)
9109 (buffer-substring (region-beginning) (region-end)))))
9110 (when (or (null txt) (string-match "\\S-" txt))
9111 (setq cpltxt
9112 (concat cpltxt "::"
9113 (condition-case nil
9114 (org-make-org-heading-search-string txt)
9115 (error "")))
9116 desc (or (and (eq et 'keyword) ev)
9117 (nth 4 (ignore-errors (org-heading-components)))
9118 "NONE")))))
9119 (if (string-match "::\\'" cpltxt)
9120 (setq cpltxt (substring cpltxt 0 -2)))
9121 (setq link cpltxt))))
9123 ((buffer-file-name (buffer-base-buffer))
9124 ;; Just link to this file here.
9125 (setq cpltxt (concat "file:"
9126 (abbreviate-file-name
9127 (buffer-file-name (buffer-base-buffer)))))
9128 ;; Add a context string
9129 (when (org-xor org-context-in-file-links arg)
9130 (setq txt (if (org-region-active-p)
9131 (buffer-substring (region-beginning) (region-end))
9132 (buffer-substring (point-at-bol) (point-at-eol))))
9133 ;; Only use search option if there is some text.
9134 (when (string-match "\\S-" txt)
9135 (setq cpltxt
9136 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9137 desc "NONE")))
9138 (setq link cpltxt))
9140 ((org-called-interactively-p 'interactive)
9141 (user-error "No method for storing a link from this buffer"))
9143 (t (setq link nil)))
9145 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9146 (setq link (or link cpltxt)
9147 desc (or desc cpltxt))
9148 (cond ((equal desc "NONE") (setq desc nil))
9149 ((string-match org-bracket-link-regexp desc)
9150 (setq desc (replace-regexp-in-string
9151 org-bracket-link-regexp
9152 (concat "\\3" (if (equal (length (match-string 0 desc))
9153 (length desc)) "*" "")) desc))))
9155 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9156 (progn
9157 (setq org-stored-links
9158 (cons (list link desc) org-stored-links))
9159 (message "Stored: %s" (or desc link))
9160 (when custom-id
9161 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9162 "::#" custom-id))
9163 (setq org-stored-links
9164 (cons (list link desc) org-stored-links))))
9165 (or agenda-link (and link (org-make-link-string link desc)))))))
9167 (defun org-store-link-props (&rest plist)
9168 "Store link properties, extract names and addresses."
9169 (let (x adr)
9170 (when (setq x (plist-get plist :from))
9171 (setq adr (mail-extract-address-components x))
9172 (setq plist (plist-put plist :fromname (car adr)))
9173 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9174 (when (setq x (plist-get plist :to))
9175 (setq adr (mail-extract-address-components x))
9176 (setq plist (plist-put plist :toname (car adr)))
9177 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9178 (let ((from (plist-get plist :from))
9179 (to (plist-get plist :to)))
9180 (when (and from to org-from-is-user-regexp)
9181 (setq plist
9182 (plist-put plist :fromto
9183 (if (string-match org-from-is-user-regexp from)
9184 (concat "to %t")
9185 (concat "from %f"))))))
9186 (setq org-store-link-plist plist))
9188 (defun org-add-link-props (&rest plist)
9189 "Add these properties to the link property list."
9190 (let (key value)
9191 (while plist
9192 (setq key (pop plist) value (pop plist))
9193 (setq org-store-link-plist
9194 (plist-put org-store-link-plist key value)))))
9196 (defun org-email-link-description (&optional fmt)
9197 "Return the description part of an email link.
9198 This takes information from `org-store-link-plist' and formats it
9199 according to FMT (default from `org-email-link-description-format')."
9200 (setq fmt (or fmt org-email-link-description-format))
9201 (let* ((p org-store-link-plist)
9202 (to (plist-get p :toaddress))
9203 (from (plist-get p :fromaddress))
9204 (table
9205 (list
9206 (cons "%c" (plist-get p :fromto))
9207 (cons "%F" (plist-get p :from))
9208 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9209 (cons "%T" (plist-get p :to))
9210 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9211 (cons "%s" (plist-get p :subject))
9212 (cons "%d" (plist-get p :date))
9213 (cons "%m" (plist-get p :message-id)))))
9214 (when (string-match "%c" fmt)
9215 ;; Check if the user wrote this message
9216 (if (and org-from-is-user-regexp from to
9217 (save-match-data (string-match org-from-is-user-regexp from)))
9218 (setq fmt (replace-match "to %t" t t fmt))
9219 (setq fmt (replace-match "from %f" t t fmt))))
9220 (org-replace-escapes fmt table)))
9222 (defun org-make-org-heading-search-string (&optional string)
9223 "Make search string for the current headline or STRING."
9224 (let ((s (or string
9225 (and (derived-mode-p 'org-mode)
9226 (save-excursion
9227 (org-back-to-heading t)
9228 (plist-get (cadr (org-element-at-point))
9229 :raw-value)))))
9230 (lines org-context-in-file-links))
9231 (or string (setq s (concat "*" s))) ; Add * for headlines
9232 (when (and string (integerp lines) (> lines 0))
9233 (let ((slines (org-split-string s "\n")))
9234 (when (< lines (length slines))
9235 (setq s (mapconcat
9236 'identity
9237 (reverse (nthcdr (- (length slines) lines)
9238 (reverse slines))) "\n")))))
9239 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9241 (defun org-make-link-string (link &optional description)
9242 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9243 (unless (string-match "\\S-" link)
9244 (error "Empty link"))
9245 (when (and description
9246 (stringp description)
9247 (not (string-match "\\S-" description)))
9248 (setq description nil))
9249 (when (stringp description)
9250 ;; Remove brackets from the description, they are fatal.
9251 (while (string-match "\\[" description)
9252 (setq description (replace-match "{" t t description)))
9253 (while (string-match "\\]" description)
9254 (setq description (replace-match "}" t t description))))
9255 (when (equal link description)
9256 ;; No description needed, it is identical
9257 (setq description nil))
9258 (when (and (not description)
9259 (not (string-match (org-image-file-name-regexp) link))
9260 (not (equal link (org-link-escape link))))
9261 (setq description (org-extract-attributes link)))
9262 (setq link
9263 (cond ((string-match (org-image-file-name-regexp) link) link)
9264 ((string-match org-link-types-re link)
9265 (concat (match-string 1 link)
9266 (org-link-escape (substring link (match-end 1)))))
9267 (t (org-link-escape link))))
9268 (concat "[[" link "]"
9269 (if description (concat "[" description "]") "")
9270 "]"))
9272 (defconst org-link-escape-chars
9273 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9274 "List of characters that should be escaped in link.
9275 This is the list that is used for internal purposes.")
9277 (defconst org-link-escape-chars-browser
9278 '(?\ )
9279 "List of escapes for characters that are problematic in links.
9280 This is the list that is used before handing over to the browser.")
9282 (defun org-link-escape (text &optional table merge)
9283 "Return percent escaped representation of TEXT.
9284 TEXT is a string with the text to escape.
9285 Optional argument TABLE is a list with characters that should be
9286 escaped. When nil, `org-link-escape-chars' is used.
9287 If optional argument MERGE is set, merge TABLE into
9288 `org-link-escape-chars'."
9289 (cond
9290 ((and table merge)
9291 (mapc (lambda (defchr)
9292 (unless (member defchr table)
9293 (setq table (cons defchr table)))) org-link-escape-chars))
9294 ((null table)
9295 (setq table org-link-escape-chars)))
9296 (mapconcat
9297 (lambda (char)
9298 (if (or (member char table)
9299 (and (or (< char 32) (= char 37) (> char 126))
9300 org-url-hexify-p))
9301 (mapconcat (lambda (sequence-element)
9302 (format "%%%.2X" sequence-element))
9303 (or (encode-coding-char char 'utf-8)
9304 (error "Unable to percent escape character: %s"
9305 (char-to-string char))) "")
9306 (char-to-string char))) text ""))
9308 (defun org-link-unescape (str)
9309 "Unhex hexified Unicode strings as returned from the JavaScript function
9310 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9311 (unless (and (null str) (string= "" str))
9312 (let ((pos 0) (case-fold-search t) unhexed)
9313 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9314 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9315 (setq str (replace-match unhexed t t str))
9316 (setq pos (+ pos (length unhexed))))))
9317 str)
9319 (defun org-link-unescape-compound (hex)
9320 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9321 Note: this function also decodes single byte encodings like
9322 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9323 (save-match-data
9324 (let* ((bytes (cdr (split-string hex "%")))
9325 (ret "")
9326 (eat 0)
9327 (sum 0))
9328 (while bytes
9329 (let* ((val (string-to-number (pop bytes) 16))
9330 (shift-xor
9331 (if (= 0 eat)
9332 (cond
9333 ((>= val 252) (cons 6 252))
9334 ((>= val 248) (cons 5 248))
9335 ((>= val 240) (cons 4 240))
9336 ((>= val 224) (cons 3 224))
9337 ((>= val 192) (cons 2 192))
9338 (t (cons 0 0)))
9339 (cons 6 128))))
9340 (if (>= val 192) (setq eat (car shift-xor)))
9341 (setq val (logxor val (cdr shift-xor)))
9342 (setq sum (+ (lsh sum (car shift-xor)) val))
9343 (if (> eat 0) (setq eat (- eat 1)))
9344 (cond
9345 ((= 0 eat) ;multi byte
9346 (setq ret (concat ret (org-char-to-string sum)))
9347 (setq sum 0))
9348 ((not bytes) ; single byte(s)
9349 (setq ret (org-link-unescape-single-byte-sequence hex))))
9350 )) ;; end (while bytes
9351 ret )))
9353 (defun org-link-unescape-single-byte-sequence (hex)
9354 "Unhexify hex-encoded single byte character sequences."
9355 (mapconcat (lambda (byte)
9356 (char-to-string (string-to-number byte 16)))
9357 (cdr (split-string hex "%")) ""))
9359 (defun org-xor (a b)
9360 "Exclusive or."
9361 (if a (not b) b))
9363 (defun org-fixup-message-id-for-http (s)
9364 "Replace special characters in a message id, so it can be used in an http query."
9365 (when (string-match "%" s)
9366 (setq s (mapconcat (lambda (c)
9367 (if (eq c ?%)
9368 "%25"
9369 (char-to-string c)))
9370 s "")))
9371 (while (string-match "<" s)
9372 (setq s (replace-match "%3C" t t s)))
9373 (while (string-match ">" s)
9374 (setq s (replace-match "%3E" t t s)))
9375 (while (string-match "@" s)
9376 (setq s (replace-match "%40" t t s)))
9379 (defun org-link-prettify (link)
9380 "Return a human-readable representation of LINK.
9381 The car of LINK must be a raw link the cdr of LINK must be either
9382 a link description or nil."
9383 (let ((desc (or (cadr link) "<no description>")))
9384 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9385 "<" (car link) ">")))
9387 ;;;###autoload
9388 (defun org-insert-link-global ()
9389 "Insert a link like Org-mode does.
9390 This command can be called in any mode to insert a link in Org-mode syntax."
9391 (interactive)
9392 (org-load-modules-maybe)
9393 (org-run-like-in-org-mode 'org-insert-link))
9395 (defun org-insert-all-links (&optional keep)
9396 "Insert all links in `org-stored-links'."
9397 (interactive "P")
9398 (let ((links (copy-sequence org-stored-links)) l)
9399 (while (setq l (if keep (pop links) (pop org-stored-links)))
9400 (insert "- ")
9401 (org-insert-link nil (car l) (cadr l))
9402 (insert "\n"))))
9404 (defun org-link-fontify-links-to-this-file ()
9405 "Fontify links to the current file in `org-stored-links'."
9406 (let ((f (buffer-file-name)) a b)
9407 (setq a (mapcar (lambda(l)
9408 (let ((ll (car l)))
9409 (when (and (string-match "^file:\\(.+\\)::" ll)
9410 (equal f (expand-file-name (match-string 1 ll))))
9411 ll)))
9412 org-stored-links))
9413 (when (featurep 'org-id)
9414 (setq b (mapcar (lambda(l)
9415 (let ((ll (car l)))
9416 (when (and (string-match "^id:\\(.+\\)$" ll)
9417 (equal f (expand-file-name
9418 (or (org-id-find-id-file
9419 (match-string 1 ll)) ""))))
9420 ll)))
9421 org-stored-links)))
9422 (mapcar (lambda(l)
9423 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9424 (delq nil (append a b)))))
9426 (defvar org-link-links-in-this-file nil)
9427 (defun org-insert-link (&optional complete-file link-location default-description)
9428 "Insert a link. At the prompt, enter the link.
9430 Completion can be used to insert any of the link protocol prefixes like
9431 http or ftp in use.
9433 The history can be used to select a link previously stored with
9434 `org-store-link'. When the empty string is entered (i.e. if you just
9435 press RET at the prompt), the link defaults to the most recently
9436 stored link. As SPC triggers completion in the minibuffer, you need to
9437 use M-SPC or C-q SPC to force the insertion of a space character.
9439 You will also be prompted for a description, and if one is given, it will
9440 be displayed in the buffer instead of the link.
9442 If there is already a link at point, this command will allow you to edit link
9443 and description parts.
9445 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9446 be selected using completion. The path to the file will be relative to the
9447 current directory if the file is in the current directory or a subdirectory.
9448 Otherwise, the link will be the absolute path as completed in the minibuffer
9449 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9450 option `org-link-file-path-type'.
9452 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9453 the current directory or below.
9455 With three \\[universal-argument] prefixes, negate the meaning of
9456 `org-keep-stored-link-after-insertion'.
9458 If `org-make-link-description-function' is non-nil, this function will be
9459 called with the link target, and the result will be the default
9460 link description.
9462 If the LINK-LOCATION parameter is non-nil, this value will be
9463 used as the link location instead of reading one interactively.
9465 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9466 be used as the default description."
9467 (interactive "P")
9468 (let* ((wcf (current-window-configuration))
9469 (origbuf (current-buffer))
9470 (region (if (org-region-active-p)
9471 (buffer-substring (region-beginning) (region-end))))
9472 (remove (and region (list (region-beginning) (region-end))))
9473 (desc region)
9474 tmphist ; byte-compile incorrectly complains about this
9475 (link link-location)
9476 (abbrevs org-link-abbrev-alist-local)
9477 entry file all-prefixes auto-desc)
9478 (cond
9479 (link-location) ; specified by arg, just use it.
9480 ((org-in-regexp org-bracket-link-regexp 1)
9481 ;; We do have a link at point, and we are going to edit it.
9482 (setq remove (list (match-beginning 0) (match-end 0)))
9483 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9484 (setq link (read-string "Link: "
9485 (org-link-unescape
9486 (org-match-string-no-properties 1)))))
9487 ((or (org-in-regexp org-angle-link-re)
9488 (org-in-regexp org-plain-link-re))
9489 ;; Convert to bracket link
9490 (setq remove (list (match-beginning 0) (match-end 0))
9491 link (read-string "Link: "
9492 (org-remove-angle-brackets (match-string 0)))))
9493 ((member complete-file '((4) (16)))
9494 ;; Completing read for file names.
9495 (setq link (org-file-complete-link complete-file)))
9497 ;; Read link, with completion for stored links.
9498 (org-link-fontify-links-to-this-file)
9499 (org-switch-to-buffer-other-window "*Org Links*")
9500 (with-current-buffer "*Org Links*"
9501 (erase-buffer)
9502 (insert "Insert a link.
9503 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9504 (when org-stored-links
9505 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9506 (insert (mapconcat 'org-link-prettify
9507 (reverse org-stored-links) "\n")))
9508 (goto-char (point-min)))
9509 (let ((cw (selected-window)))
9510 (select-window (get-buffer-window "*Org Links*" 'visible))
9511 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9512 (unless (pos-visible-in-window-p (point-max))
9513 (org-fit-window-to-buffer))
9514 (and (window-live-p cw) (select-window cw)))
9515 ;; Fake a link history, containing the stored links.
9516 (setq tmphist (append (mapcar 'car org-stored-links)
9517 org-insert-link-history))
9518 (setq all-prefixes (append (mapcar 'car abbrevs)
9519 (mapcar 'car org-link-abbrev-alist)
9520 org-link-types))
9521 (unwind-protect
9522 (progn
9523 (setq link
9524 (org-completing-read
9525 "Link: "
9526 (append
9527 (mapcar (lambda (x) (concat x ":"))
9528 all-prefixes)
9529 (mapcar 'car org-stored-links))
9530 nil nil nil
9531 'tmphist
9532 (caar org-stored-links)))
9533 (if (not (string-match "\\S-" link))
9534 (error "No link selected"))
9535 (mapc (lambda(l)
9536 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9537 org-stored-links)
9538 (if (or (member link all-prefixes)
9539 (and (equal ":" (substring link -1))
9540 (member (substring link 0 -1) all-prefixes)
9541 (setq link (substring link 0 -1))))
9542 (setq link (with-current-buffer origbuf
9543 (org-link-try-special-completion link)))))
9544 (set-window-configuration wcf)
9545 (kill-buffer "*Org Links*"))
9546 (setq entry (assoc link org-stored-links))
9547 (or entry (push link org-insert-link-history))
9548 (setq desc (or desc (nth 1 entry)))))
9550 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9551 (not org-keep-stored-link-after-insertion))
9552 (setq org-stored-links (delq (assoc link org-stored-links)
9553 org-stored-links)))
9555 (if (string-match org-plain-link-re link)
9556 ;; URL-like link, normalize the use of angular brackets.
9557 (setq link (org-remove-angle-brackets link)))
9559 ;; Check if we are linking to the current file with a search
9560 ;; option If yes, simplify the link by using only the search
9561 ;; option.
9562 (when (and buffer-file-name
9563 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9564 (let* ((path (match-string 1 link))
9565 (case-fold-search nil)
9566 (search (match-string 2 link)))
9567 (save-match-data
9568 (if (equal (file-truename buffer-file-name) (file-truename path))
9569 ;; We are linking to this same file, with a search option
9570 (setq link search)))))
9572 ;; Check if we can/should use a relative path. If yes, simplify the link
9573 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9574 (let* ((type (match-string 1 link))
9575 (path (match-string 2 link))
9576 (origpath path)
9577 (case-fold-search nil))
9578 (cond
9579 ((or (eq org-link-file-path-type 'absolute)
9580 (equal complete-file '(16)))
9581 (setq path (abbreviate-file-name (expand-file-name path))))
9582 ((eq org-link-file-path-type 'noabbrev)
9583 (setq path (expand-file-name path)))
9584 ((eq org-link-file-path-type 'relative)
9585 (setq path (file-relative-name path)))
9587 (save-match-data
9588 (if (string-match (concat "^" (regexp-quote
9589 (expand-file-name
9590 (file-name-as-directory
9591 default-directory))))
9592 (expand-file-name path))
9593 ;; We are linking a file with relative path name.
9594 (setq path (substring (expand-file-name path)
9595 (match-end 0)))
9596 (setq path (abbreviate-file-name (expand-file-name path)))))))
9597 (setq link (concat type path))
9598 (if (equal desc origpath)
9599 (setq desc path))))
9601 (if org-make-link-description-function
9602 (setq desc
9603 (or (condition-case nil
9604 (funcall org-make-link-description-function link desc)
9605 (error (progn (message "Can't get link description from `%s'"
9606 (symbol-name org-make-link-description-function))
9607 (sit-for 2) nil)))
9608 (read-string "Description: " default-description)))
9609 (if default-description (setq desc default-description)
9610 (setq desc (or (and auto-desc desc)
9611 (read-string "Description: " desc)))))
9613 (unless (string-match "\\S-" desc) (setq desc nil))
9614 (if remove (apply 'delete-region remove))
9615 (insert (org-make-link-string link desc))))
9617 (defun org-link-try-special-completion (type)
9618 "If there is completion support for link type TYPE, offer it."
9619 (let ((fun (intern (concat "org-" type "-complete-link"))))
9620 (if (functionp fun)
9621 (funcall fun)
9622 (read-string "Link (no completion support): " (concat type ":")))))
9624 (defun org-file-complete-link (&optional arg)
9625 "Create a file link using completion."
9626 (let (file link)
9627 (setq file (org-iread-file-name "File: "))
9628 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9629 (pwd1 (file-name-as-directory (abbreviate-file-name
9630 (expand-file-name ".")))))
9631 (cond
9632 ((equal arg '(16))
9633 (setq link (concat
9634 "file:"
9635 (abbreviate-file-name (expand-file-name file)))))
9636 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9637 (setq link (concat "file:" (match-string 1 file))))
9638 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9639 (expand-file-name file))
9640 (setq link (concat
9641 "file:" (match-string 1 (expand-file-name file)))))
9642 (t (setq link (concat "file:" file)))))
9643 link))
9645 (defun org-iread-file-name (&rest args)
9646 "Read-file-name using `ido-mode' speedup if available.
9647 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9648 See `read-file-name' for a description of parameters."
9649 (org-without-partial-completion
9650 (if (and org-completion-use-ido
9651 (fboundp 'ido-read-file-name)
9652 (boundp 'ido-mode) ido-mode
9653 (listp (second args)))
9654 (let ((ido-enter-matching-directory nil))
9655 (apply 'ido-read-file-name args))
9656 (apply 'read-file-name args))))
9658 (defun org-completing-read (&rest args)
9659 "Completing-read with SPACE being a normal character."
9660 (let ((enable-recursive-minibuffers t)
9661 (minibuffer-local-completion-map
9662 (copy-keymap minibuffer-local-completion-map)))
9663 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9664 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9665 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9666 (apply 'org-icompleting-read args)))
9668 (defun org-completing-read-no-i (&rest args)
9669 (let (org-completion-use-ido org-completion-use-iswitchb)
9670 (apply 'org-completing-read args)))
9672 (defun org-iswitchb-completing-read (prompt choices &rest args)
9673 "Use iswitch as a completing-read replacement to choose from choices.
9674 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9675 from."
9676 (let* ((iswitchb-use-virtual-buffers nil)
9677 (iswitchb-make-buflist-hook
9678 (lambda ()
9679 (setq iswitchb-temp-buflist choices))))
9680 (iswitchb-read-buffer prompt)))
9682 (defun org-icompleting-read (&rest args)
9683 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9684 (org-without-partial-completion
9685 (if (and org-completion-use-ido
9686 (fboundp 'ido-completing-read)
9687 (boundp 'ido-mode) ido-mode
9688 (listp (second args)))
9689 (let ((ido-enter-matching-directory nil))
9690 (apply 'ido-completing-read (concat (car args))
9691 (if (consp (car (nth 1 args)))
9692 (mapcar 'car (nth 1 args))
9693 (nth 1 args))
9694 (cddr args)))
9695 (if (and org-completion-use-iswitchb
9696 (boundp 'iswitchb-mode) iswitchb-mode
9697 (listp (second args)))
9698 (apply 'org-iswitchb-completing-read (concat (car args))
9699 (if (consp (car (nth 1 args)))
9700 (mapcar 'car (nth 1 args))
9701 (nth 1 args))
9702 (cddr args))
9703 (apply 'completing-read args)))))
9705 (defun org-extract-attributes (s)
9706 "Extract the attributes cookie from a string and set as text property."
9707 (let (a attr (start 0) key value)
9708 (save-match-data
9709 (when (string-match "{{\\([^}]+\\)}}$" s)
9710 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9711 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9712 (setq key (match-string 1 a) value (match-string 2 a)
9713 start (match-end 0)
9714 attr (plist-put attr (intern key) value))))
9715 (org-add-props s nil 'org-attr attr))
9718 (defun org-extract-attributes-from-string (tag)
9719 (let (key value attr)
9720 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9721 (setq key (match-string 1 tag) value (match-string 2 tag)
9722 tag (replace-match "" t t tag)
9723 attr (plist-put attr (intern key) value)))
9724 (cons tag attr)))
9726 (defun org-attributes-to-string (plist)
9727 "Format a property list into an HTML attribute list."
9728 (let ((s "") key value)
9729 (while plist
9730 (setq key (pop plist) value (pop plist))
9731 (and value
9732 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9735 ;;; Opening/following a link
9737 (defvar org-link-search-failed nil)
9739 (defvar org-open-link-functions nil
9740 "Hook for functions finding a plain text link.
9741 These functions must take a single argument, the link content.
9742 They will be called for links that look like [[link text][description]]
9743 when LINK TEXT does not have a protocol like \"http:\" and does not look
9744 like a filename (e.g. \"./blue.png\").
9746 These functions will be called *before* Org attempts to resolve the
9747 link by doing text searches in the current buffer - so if you want a
9748 link \"[[target]]\" to still find \"<<target>>\", your function should
9749 handle this as a special case.
9751 When the function does handle the link, it must return a non-nil value.
9752 If it decides that it is not responsible for this link, it must return
9753 nil to indicate that that Org-mode can continue with other options
9754 like exact and fuzzy text search.")
9756 (defun org-next-link ()
9757 "Move forward to the next link.
9758 If the link is in hidden text, expose it."
9759 (interactive)
9760 (when (and org-link-search-failed (eq this-command last-command))
9761 (goto-char (point-min))
9762 (message "Link search wrapped back to beginning of buffer"))
9763 (setq org-link-search-failed nil)
9764 (let* ((pos (point))
9765 (ct (org-context))
9766 (a (assoc :link ct)))
9767 (if a (goto-char (nth 2 a)))
9768 (if (re-search-forward org-any-link-re nil t)
9769 (progn
9770 (goto-char (match-beginning 0))
9771 (if (outline-invisible-p) (org-show-context)))
9772 (goto-char pos)
9773 (setq org-link-search-failed t)
9774 (error "No further link found"))))
9776 (defun org-previous-link ()
9777 "Move backward to the previous link.
9778 If the link is in hidden text, expose it."
9779 (interactive)
9780 (when (and org-link-search-failed (eq this-command last-command))
9781 (goto-char (point-max))
9782 (message "Link search wrapped back to end of buffer"))
9783 (setq org-link-search-failed nil)
9784 (let* ((pos (point))
9785 (ct (org-context))
9786 (a (assoc :link ct)))
9787 (if a (goto-char (nth 1 a)))
9788 (if (re-search-backward org-any-link-re nil t)
9789 (progn
9790 (goto-char (match-beginning 0))
9791 (if (outline-invisible-p) (org-show-context)))
9792 (goto-char pos)
9793 (setq org-link-search-failed t)
9794 (error "No further link found"))))
9796 (defun org-translate-link (s)
9797 "Translate a link string if a translation function has been defined."
9798 (if (and org-link-translation-function
9799 (fboundp org-link-translation-function)
9800 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9801 (progn
9802 (setq s (funcall org-link-translation-function
9803 (match-string 1 s) (match-string 2 s)))
9804 (concat (car s) ":" (cdr s)))
9807 (defun org-translate-link-from-planner (type path)
9808 "Translate a link from Emacs Planner syntax so that Org can follow it.
9809 This is still an experimental function, your mileage may vary."
9810 (cond
9811 ((member type '("http" "https" "news" "ftp"))
9812 ;; standard Internet links are the same.
9813 nil)
9814 ((and (equal type "irc") (string-match "^//" path))
9815 ;; Planner has two / at the beginning of an irc link, we have 1.
9816 ;; We should have zero, actually....
9817 (setq path (substring path 1)))
9818 ((and (equal type "lisp") (string-match "^/" path))
9819 ;; Planner has a slash, we do not.
9820 (setq type "elisp" path (substring path 1)))
9821 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9822 ;; A typical message link. Planner has the id after the final slash,
9823 ;; we separate it with a hash mark
9824 (setq path (concat (match-string 1 path) "#"
9825 (org-remove-angle-brackets (match-string 2 path)))))
9827 (cons type path))
9829 (defun org-find-file-at-mouse (ev)
9830 "Open file link or URL at mouse."
9831 (interactive "e")
9832 (mouse-set-point ev)
9833 (org-open-at-point 'in-emacs))
9835 (defun org-open-at-mouse (ev)
9836 "Open file link or URL at mouse.
9837 See the docstring of `org-open-file' for details."
9838 (interactive "e")
9839 (mouse-set-point ev)
9840 (if (eq major-mode 'org-agenda-mode)
9841 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9842 (org-open-at-point))
9844 (defvar org-window-config-before-follow-link nil
9845 "The window configuration before following a link.
9846 This is saved in case the need arises to restore it.")
9848 (defvar org-open-link-marker (make-marker)
9849 "Marker pointing to the location where `org-open-at-point; was called.")
9851 ;;;###autoload
9852 (defun org-open-at-point-global ()
9853 "Follow a link like Org-mode does.
9854 This command can be called in any mode to follow a link that has
9855 Org-mode syntax."
9856 (interactive)
9857 (org-run-like-in-org-mode 'org-open-at-point))
9859 ;;;###autoload
9860 (defun org-open-link-from-string (s &optional arg reference-buffer)
9861 "Open a link in the string S, as if it was in Org-mode."
9862 (interactive "sLink: \nP")
9863 (let ((reference-buffer (or reference-buffer (current-buffer))))
9864 (with-temp-buffer
9865 (let ((org-inhibit-startup (not reference-buffer)))
9866 (org-mode)
9867 (insert s)
9868 (goto-char (point-min))
9869 (when reference-buffer
9870 (setq org-link-abbrev-alist-local
9871 (with-current-buffer reference-buffer
9872 org-link-abbrev-alist-local)))
9873 (org-open-at-point arg reference-buffer)))))
9875 (defvar org-open-at-point-functions nil
9876 "Hook that is run when following a link at point.
9878 Functions in this hook must return t if they identify and follow
9879 a link at point. If they don't find anything interesting at point,
9880 they must return nil.")
9882 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9883 (defun org-open-at-point (&optional arg reference-buffer)
9884 "Open link at or after point.
9885 If there is no link at point, this function will search forward up to
9886 the end of the current line.
9887 Normally, files will be opened by an appropriate application. If the
9888 optional prefix argument ARG is non-nil, Emacs will visit the file.
9889 With a double prefix argument, try to open outside of Emacs, in the
9890 application the system uses for this file type."
9891 (interactive "P")
9892 ;; if in a code block, then open the block's results
9893 (unless (call-interactively #'org-babel-open-src-block-result)
9894 (org-load-modules-maybe)
9895 (move-marker org-open-link-marker (point))
9896 (setq org-window-config-before-follow-link (current-window-configuration))
9897 (org-remove-occur-highlights nil nil t)
9898 (cond
9899 ((and (org-at-heading-p)
9900 (not (org-at-timestamp-p t))
9901 (not (org-in-regexp
9902 (concat org-plain-link-re "\\|"
9903 org-bracket-link-regexp "\\|"
9904 org-angle-link-re "\\|"
9905 "[ \t]:[^ \t\n]+:[ \t]*$")))
9906 (not (get-text-property (point) 'org-linked-text)))
9907 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9908 (lk0 (car lkall))
9909 (lk (if (stringp lk0) (list lk0) lk0))
9910 (lkend (cdr lkall)))
9911 (mapcar (lambda(l)
9912 (search-forward l nil lkend)
9913 (goto-char (match-beginning 0))
9914 (org-open-at-point))
9915 lk))
9916 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9917 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9918 ((and (org-at-timestamp-p t)
9919 (not (org-in-regexp org-bracket-link-regexp)))
9920 (org-follow-timestamp-link))
9921 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9922 (not (org-in-regexp org-any-link-re)))
9923 (org-footnote-action))
9925 (let (type path link line search (pos (point)))
9926 (catch 'match
9927 (save-excursion
9928 (skip-chars-forward "^]\n\r")
9929 (when (org-in-regexp org-bracket-link-regexp 1)
9930 (setq link (org-extract-attributes
9931 (org-link-unescape (org-match-string-no-properties 1))))
9932 (while (string-match " *\n *" link)
9933 (setq link (replace-match " " t t link)))
9934 (setq link (org-link-expand-abbrev link))
9935 (cond
9936 ((or (file-name-absolute-p link)
9937 (string-match "^\\.\\.?/" link))
9938 (setq type "file" path link))
9939 ((string-match org-link-re-with-space3 link)
9940 (setq type (match-string 1 link) path (match-string 2 link)))
9941 ((string-match "^help:+\\(.+\\)" link)
9942 (setq type "help" path (match-string 1 link)))
9943 (t (setq type "thisfile" path link)))
9944 (throw 'match t)))
9946 (when (get-text-property (point) 'org-linked-text)
9947 (setq type "thisfile"
9948 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9949 (1+ (point)) (point))
9950 path (buffer-substring
9951 (or (previous-single-property-change pos 'org-linked-text)
9952 (point-min))
9953 (or (next-single-property-change pos 'org-linked-text)
9954 (point-max))))
9955 (throw 'match t))
9957 (save-excursion
9958 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9959 (when (or (org-in-regexp org-angle-link-re)
9960 (and plinkpos (goto-char (car plinkpos))
9961 (save-match-data (not (looking-back "\\[\\[")))))
9962 (setq type (match-string 1)
9963 path (org-link-unescape (match-string 2)))
9964 (throw 'match t))))
9965 (save-excursion
9966 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9967 (setq type "tags"
9968 path (match-string 1))
9969 (while (string-match ":" path)
9970 (setq path (replace-match "+" t t path)))
9971 (throw 'match t)))
9972 (when (org-in-regexp "<\\([^><\n]+\\)>")
9973 (setq type "tree-match"
9974 path (match-string 1))
9975 (throw 'match t)))
9976 (unless path
9977 (user-error "No link found"))
9979 ;; switch back to reference buffer
9980 ;; needed when if called in a temporary buffer through
9981 ;; org-open-link-from-string
9982 (with-current-buffer (or reference-buffer (current-buffer))
9984 ;; Remove any trailing spaces in path
9985 (if (string-match " +\\'" path)
9986 (setq path (replace-match "" t t path)))
9987 (if (and org-link-translation-function
9988 (fboundp org-link-translation-function))
9989 ;; Check if we need to translate the link
9990 (let ((tmp (funcall org-link-translation-function type path)))
9991 (setq type (car tmp) path (cdr tmp))))
9993 (cond
9995 ((assoc type org-link-protocols)
9996 (funcall (nth 1 (assoc type org-link-protocols)) path))
9998 ((equal type "help")
9999 (let ((f-or-v (intern path)))
10000 (cond ((fboundp f-or-v)
10001 (describe-function f-or-v))
10002 ((boundp f-or-v)
10003 (describe-variable f-or-v))
10004 (t (error "Not a known function or variable")))))
10006 ((equal type "mailto")
10007 (let ((cmd (car org-link-mailto-program))
10008 (args (cdr org-link-mailto-program)) args1
10009 (address path) (subject "") a)
10010 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10011 (setq address (match-string 1 path)
10012 subject (org-link-escape (match-string 2 path))))
10013 (while args
10014 (cond
10015 ((not (stringp (car args))) (push (pop args) args1))
10016 (t (setq a (pop args))
10017 (if (string-match "%a" a)
10018 (setq a (replace-match address t t a)))
10019 (if (string-match "%s" a)
10020 (setq a (replace-match subject t t a)))
10021 (push a args1))))
10022 (apply cmd (nreverse args1))))
10024 ((member type '("http" "https" "ftp" "news"))
10025 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10026 (org-link-escape
10027 path org-link-escape-chars-browser)
10028 path))))
10030 ((string= type "doi")
10031 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10032 (org-link-escape
10033 path org-link-escape-chars-browser)
10034 path))))
10036 ((member type '("message"))
10037 (browse-url (concat type ":" path)))
10039 ((string= type "tags")
10040 (org-tags-view arg path))
10042 ((string= type "tree-match")
10043 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10045 ((string= type "file")
10046 (if (string-match "::\\([0-9]+\\)\\'" path)
10047 (setq line (string-to-number (match-string 1 path))
10048 path (substring path 0 (match-beginning 0)))
10049 (if (string-match "::\\(.+\\)\\'" path)
10050 (setq search (match-string 1 path)
10051 path (substring path 0 (match-beginning 0)))))
10052 (if (string-match "[*?{]" (file-name-nondirectory path))
10053 (dired path)
10054 (org-open-file path arg line search)))
10056 ((string= type "shell")
10057 (let ((buf (generate-new-buffer "*Org Shell Output"))
10058 (cmd path))
10059 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10060 (string-match org-confirm-shell-link-not-regexp cmd))
10061 (not org-confirm-shell-link-function)
10062 (funcall org-confirm-shell-link-function
10063 (format "Execute \"%s\" in shell? "
10064 (org-add-props cmd nil
10065 'face 'org-warning))))
10066 (progn
10067 (message "Executing %s" cmd)
10068 (shell-command cmd buf)
10069 (if (featurep 'midnight)
10070 (setq clean-buffer-list-kill-buffer-names
10071 (cons buf clean-buffer-list-kill-buffer-names))))
10072 (error "Abort"))))
10074 ((string= type "elisp")
10075 (let ((cmd path))
10076 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10077 (string-match org-confirm-elisp-link-not-regexp cmd))
10078 (not org-confirm-elisp-link-function)
10079 (funcall org-confirm-elisp-link-function
10080 (format "Execute \"%s\" as elisp? "
10081 (org-add-props cmd nil
10082 'face 'org-warning))))
10083 (message "%s => %s" cmd
10084 (if (equal (string-to-char cmd) ?\()
10085 (eval (read cmd))
10086 (call-interactively (read cmd))))
10087 (error "Abort"))))
10089 ((and (string= type "thisfile")
10090 (run-hook-with-args-until-success
10091 'org-open-link-functions path)))
10093 ((string= type "thisfile")
10094 (if arg
10095 (switch-to-buffer-other-window
10096 (org-get-buffer-for-internal-link (current-buffer)))
10097 (org-mark-ring-push))
10098 (let ((cmd `(org-link-search
10099 ,path
10100 ,(cond ((equal arg '(4)) ''occur)
10101 ((equal arg '(16)) ''org-occur))
10102 ,pos)))
10103 (condition-case nil (let ((org-link-search-inhibit-query t))
10104 (eval cmd))
10105 (error (progn (widen) (eval cmd))))))
10107 (t (browse-url-at-point)))))))
10108 (move-marker org-open-link-marker nil)
10109 (run-hook-with-args 'org-follow-link-hook)))
10111 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10112 "Offer links in the current entry and return the selected link.
10113 If there is only one link, return it.
10114 If NTH is an integer, return the NTH link found.
10115 If ZERO is a string, check also this string for a link, and if
10116 there is one, return it."
10117 (with-current-buffer buffer
10118 (save-excursion
10119 (save-restriction
10120 (widen)
10121 (goto-char marker)
10122 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10123 "\\(" org-angle-link-re "\\)\\|"
10124 "\\(" org-plain-link-re "\\)"))
10125 (cnt ?0)
10126 (in-emacs (if (integerp nth) nil nth))
10127 have-zero end links link c)
10128 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10129 (push (match-string 0 zero) links)
10130 (setq cnt (1- cnt) have-zero t))
10131 (save-excursion
10132 (org-back-to-heading t)
10133 (setq end (save-excursion (outline-next-heading) (point)))
10134 (while (re-search-forward re end t)
10135 (push (match-string 0) links))
10136 (setq links (org-uniquify (reverse links))))
10137 (cond
10138 ((null links)
10139 (message "No links"))
10140 ((equal (length links) 1)
10141 (setq link (car links)))
10142 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10143 (setq link (nth (if have-zero nth (1- nth)) links)))
10144 (t ; we have to select a link
10145 (save-excursion
10146 (save-window-excursion
10147 (delete-other-windows)
10148 (with-output-to-temp-buffer "*Select Link*"
10149 (mapc (lambda (l)
10150 (if (not (string-match org-bracket-link-regexp l))
10151 (princ (format "[%c] %s\n" (incf cnt)
10152 (org-remove-angle-brackets l)))
10153 (if (match-end 3)
10154 (princ (format "[%c] %s (%s)\n" (incf cnt)
10155 (match-string 3 l) (match-string 1 l)))
10156 (princ (format "[%c] %s\n" (incf cnt)
10157 (match-string 1 l))))))
10158 links))
10159 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10160 (message "Select link to open, RET to open all:")
10161 (setq c (read-char-exclusive))
10162 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10163 (when (equal c ?q) (error "Abort"))
10164 (if (equal c ?\C-m)
10165 (setq link links)
10166 (setq nth (- c ?0))
10167 (if have-zero (setq nth (1+ nth)))
10168 (unless (and (integerp nth) (>= (length links) nth))
10169 (error "Invalid link selection"))
10170 (setq link (nth (1- nth) links)))))
10171 (cons link end))))))
10173 ;; Add special file links that specify the way of opening
10175 (org-add-link-type "file+sys" 'org-open-file-with-system)
10176 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10177 (defun org-open-file-with-system (path)
10178 "Open file at PATH using the system way of opening it."
10179 (org-open-file path 'system))
10180 (defun org-open-file-with-emacs (path)
10181 "Open file at PATH in Emacs."
10182 (org-open-file path 'emacs))
10183 (defun org-remove-file-link-modifiers ()
10184 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10185 (goto-char (point-min))
10186 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10187 (org-if-unprotected
10188 (replace-match "file:" t t))))
10189 (eval-after-load "org-exp"
10190 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10191 'org-remove-file-link-modifiers))
10193 ;;; File search
10195 (defvar org-create-file-search-functions nil
10196 "List of functions to construct the right search string for a file link.
10197 These functions are called in turn with point at the location to
10198 which the link should point.
10200 A function in the hook should first test if it would like to
10201 handle this file type, for example by checking the `major-mode'
10202 or the file extension. If it decides not to handle this file, it
10203 should just return nil to give other functions a chance. If it
10204 does handle the file, it must return the search string to be used
10205 when following the link. The search string will be part of the
10206 file link, given after a double colon, and `org-open-at-point'
10207 will automatically search for it. If special measures must be
10208 taken to make the search successful, another function should be
10209 added to the companion hook `org-execute-file-search-functions',
10210 which see.
10212 A function in this hook may also use `setq' to set the variable
10213 `description' to provide a suggestion for the descriptive text to
10214 be used for this link when it gets inserted into an Org-mode
10215 buffer with \\[org-insert-link].")
10217 (defvar org-execute-file-search-functions nil
10218 "List of functions to execute a file search triggered by a link.
10220 Functions added to this hook must accept a single argument, the
10221 search string that was part of the file link, the part after the
10222 double colon. The function must first check if it would like to
10223 handle this search, for example by checking the `major-mode' or
10224 the file extension. If it decides not to handle this search, it
10225 should just return nil to give other functions a chance. If it
10226 does handle the search, it must return a non-nil value to keep
10227 other functions from trying.
10229 Each function can access the current prefix argument through the
10230 variable `current-prefix-argument'. Note that a single prefix is
10231 used to force opening a link in Emacs, so it may be good to only
10232 use a numeric or double prefix to guide the search function.
10234 In case this is needed, a function in this hook can also restore
10235 the window configuration before `org-open-at-point' was called using:
10237 (set-window-configuration org-window-config-before-follow-link)")
10239 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10240 (defun org-link-search (s &optional type avoid-pos stealth)
10241 "Search for a link search option.
10242 If S is surrounded by forward slashes, it is interpreted as a
10243 regular expression. In org-mode files, this will create an `org-occur'
10244 sparse tree. In ordinary files, `occur' will be used to list matches.
10245 If the current buffer is in `dired-mode', grep will be used to search
10246 in all files. If AVOID-POS is given, ignore matches near that position.
10248 When optional argument STEALTH is non-nil, do not modify
10249 visibility around point, thus ignoring
10250 `org-show-hierarchy-above', `org-show-following-heading' and
10251 `org-show-siblings' variables."
10252 (let ((case-fold-search t)
10253 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10254 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10255 (append '(("") (" ") ("\t") ("\n"))
10256 org-emphasis-alist)
10257 "\\|") "\\)"))
10258 (pos (point))
10259 (pre nil) (post nil)
10260 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10261 (cond
10262 ;; First check if there are any special search functions
10263 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10264 ;; Now try the builtin stuff
10265 ((and (equal (string-to-char s0) ?#)
10266 (> (length s0) 1)
10267 (save-excursion
10268 (goto-char (point-min))
10269 (and
10270 (re-search-forward
10271 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10272 (setq type 'dedicated
10273 pos (match-beginning 0))))
10274 ;; There is an exact target for this
10275 (goto-char pos)
10276 (org-back-to-heading t)))
10277 ((save-excursion
10278 (goto-char (point-min))
10279 (and
10280 (re-search-forward
10281 (concat "<<" (regexp-quote s0) ">>") nil t)
10282 (setq type 'dedicated
10283 pos (match-beginning 0))))
10284 ;; There is an exact target for this
10285 (goto-char pos))
10286 ((save-excursion
10287 (goto-char (point-min))
10288 (and
10289 (re-search-forward
10290 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10291 (setq type 'dedicated pos (match-beginning 0))))
10292 ;; Found an invisible target.
10293 (goto-char pos))
10294 ((save-excursion
10295 (goto-char (point-min))
10296 (and
10297 (re-search-forward
10298 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10299 (setq type 'dedicated pos (match-beginning 0))))
10300 ;; Found an element with a matching #+name affiliated keyword.
10301 (goto-char pos))
10302 ((and (string-match "^(\\(.*\\))$" s0)
10303 (save-excursion
10304 (goto-char (point-min))
10305 (and
10306 (re-search-forward
10307 (concat "[^[]" (regexp-quote
10308 (format org-coderef-label-format
10309 (match-string 1 s0))))
10310 nil t)
10311 (setq type 'dedicated
10312 pos (1+ (match-beginning 0))))))
10313 ;; There is a coderef target for this
10314 (goto-char pos))
10315 ((string-match "^/\\(.*\\)/$" s)
10316 ;; A regular expression
10317 (cond
10318 ((derived-mode-p 'org-mode)
10319 (org-occur (match-string 1 s)))
10320 ;;((eq major-mode 'dired-mode)
10321 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10322 (t (org-do-occur (match-string 1 s)))))
10323 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10324 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10325 (goto-char (point-min))
10326 (cond
10327 ((let (case-fold-search)
10328 (re-search-forward (format org-complex-heading-regexp-format
10329 (regexp-quote s))
10330 nil t))
10331 ;; OK, found a match
10332 (setq type 'dedicated)
10333 (goto-char (match-beginning 0)))
10334 ((and (not org-link-search-inhibit-query)
10335 (eq org-link-search-must-match-exact-headline 'query-to-create)
10336 (y-or-n-p "No match - create this as a new heading? "))
10337 (goto-char (point-max))
10338 (or (bolp) (newline))
10339 (insert "* " s "\n")
10340 (beginning-of-line 0))
10342 (goto-char pos)
10343 (error "No match"))))
10345 ;; A normal search string
10346 (when (equal (string-to-char s) ?*)
10347 ;; Anchor on headlines, post may include tags.
10348 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10349 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10350 s (substring s 1)))
10351 (remove-text-properties
10352 0 (length s)
10353 '(face nil mouse-face nil keymap nil fontified nil) s)
10354 ;; Make a series of regular expressions to find a match
10355 (setq words (org-split-string s "[ \n\r\t]+")
10357 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10358 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10359 "\\)" markers)
10360 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10361 re2a (concat "[ \t\r\n]" re2a_)
10362 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10363 re4 (concat "[^a-zA-Z_]" re4_)
10365 re1 (concat pre re2 post)
10366 re3 (concat pre (if pre re4_ re4) post)
10367 re5 (concat pre ".*" re4)
10368 re2 (concat pre re2)
10369 re2a (concat pre (if pre re2a_ re2a))
10370 re4 (concat pre (if pre re4_ re4))
10371 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10372 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10373 re5 "\\)"
10375 (cond
10376 ((eq type 'org-occur) (org-occur reall))
10377 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10378 (t (goto-char (point-min))
10379 (setq type 'fuzzy)
10380 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10381 (org-search-not-self 1 re1 nil t)
10382 (org-search-not-self 1 re2 nil t)
10383 (org-search-not-self 1 re2a nil t)
10384 (org-search-not-self 1 re3 nil t)
10385 (org-search-not-self 1 re4 nil t)
10386 (org-search-not-self 1 re5 nil t)
10388 (goto-char (match-beginning 1))
10389 (goto-char pos)
10390 (error "No match"))))))
10391 (and (derived-mode-p 'org-mode)
10392 (not stealth)
10393 (org-show-context 'link-search))
10394 type))
10396 (defun org-search-not-self (group &rest args)
10397 "Execute `re-search-forward', but only accept matches that do not
10398 enclose the position of `org-open-link-marker'."
10399 (let ((m org-open-link-marker))
10400 (catch 'exit
10401 (while (apply 're-search-forward args)
10402 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10403 (goto-char (match-end group))
10404 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10405 (> (match-beginning 0) (marker-position m))
10406 (< (match-end 0) (marker-position m)))
10407 (save-match-data
10408 (or (not (org-in-regexp
10409 org-bracket-link-analytic-regexp 1))
10410 (not (match-end 4)) ; no description
10411 (and (<= (match-beginning 4) (point))
10412 (>= (match-end 4) (point))))))
10413 (throw 'exit (point))))))))
10415 (defun org-get-buffer-for-internal-link (buffer)
10416 "Return a buffer to be used for displaying the link target of internal links."
10417 (cond
10418 ((not org-display-internal-link-with-indirect-buffer)
10419 buffer)
10420 ((string-match "(Clone)$" (buffer-name buffer))
10421 (message "Buffer is already a clone, not making another one")
10422 ;; we also do not modify visibility in this case
10423 buffer)
10424 (t ; make a new indirect buffer for displaying the link
10425 (let* ((bn (buffer-name buffer))
10426 (ibn (concat bn "(Clone)"))
10427 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10428 (with-current-buffer ib (org-overview))
10429 ib))))
10431 (defun org-do-occur (regexp &optional cleanup)
10432 "Call the Emacs command `occur'.
10433 If CLEANUP is non-nil, remove the printout of the regular expression
10434 in the *Occur* buffer. This is useful if the regex is long and not useful
10435 to read."
10436 (occur regexp)
10437 (when cleanup
10438 (let ((cwin (selected-window)) win beg end)
10439 (when (setq win (get-buffer-window "*Occur*"))
10440 (select-window win))
10441 (goto-char (point-min))
10442 (when (re-search-forward "match[a-z]+" nil t)
10443 (setq beg (match-end 0))
10444 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10445 (setq end (1- (match-beginning 0)))))
10446 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10447 (goto-char (point-min))
10448 (select-window cwin))))
10450 ;;; The mark ring for links jumps
10452 (defvar org-mark-ring nil
10453 "Mark ring for positions before jumps in Org-mode.")
10454 (defvar org-mark-ring-last-goto nil
10455 "Last position in the mark ring used to go back.")
10456 ;; Fill and close the ring
10457 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10458 (loop for i from 1 to org-mark-ring-length do
10459 (push (make-marker) org-mark-ring))
10460 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10461 org-mark-ring)
10463 (defun org-mark-ring-push (&optional pos buffer)
10464 "Put the current position or POS into the mark ring and rotate it."
10465 (interactive)
10466 (setq pos (or pos (point)))
10467 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10468 (move-marker (car org-mark-ring)
10469 (or pos (point))
10470 (or buffer (current-buffer)))
10471 (message "%s"
10472 (substitute-command-keys
10473 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10475 (defun org-mark-ring-goto (&optional n)
10476 "Jump to the previous position in the mark ring.
10477 With prefix arg N, jump back that many stored positions. When
10478 called several times in succession, walk through the entire ring.
10479 Org-mode commands jumping to a different position in the current file,
10480 or to another Org-mode file, automatically push the old position
10481 onto the ring."
10482 (interactive "p")
10483 (let (p m)
10484 (if (eq last-command this-command)
10485 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10486 (setq p org-mark-ring))
10487 (setq org-mark-ring-last-goto p)
10488 (setq m (car p))
10489 (org-pop-to-buffer-same-window (marker-buffer m))
10490 (goto-char m)
10491 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10493 (defun org-remove-angle-brackets (s)
10494 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10495 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10497 (defun org-add-angle-brackets (s)
10498 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10499 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10501 (defun org-remove-double-quotes (s)
10502 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10503 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10506 ;;; Following specific links
10508 (defun org-follow-timestamp-link ()
10509 "Open an agenda view for the time-stamp date/range at point."
10510 (cond
10511 ((org-at-date-range-p t)
10512 (let ((org-agenda-start-on-weekday)
10513 (t1 (match-string 1))
10514 (t2 (match-string 2)) tt1 tt2)
10515 (setq tt1 (time-to-days (org-time-string-to-time t1))
10516 tt2 (time-to-days (org-time-string-to-time t2)))
10517 (let ((org-agenda-buffer-tmp-name
10518 (format "*Org Agenda(a:%s)"
10519 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10520 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10521 ((org-at-timestamp-p t)
10522 (let ((org-agenda-buffer-tmp-name
10523 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10524 (org-agenda-list nil (time-to-days (org-time-string-to-time
10525 (substring (match-string 1) 0 10)))
10526 1)))
10527 (t (error "This should not happen"))))
10530 ;;; Following file links
10531 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10532 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10533 (declare-function mailcap-mime-info
10534 "mailcap" (string &optional request no-decode))
10535 (defvar org-wait nil)
10536 (defun org-open-file (path &optional in-emacs line search)
10537 "Open the file at PATH.
10538 First, this expands any special file name abbreviations. Then the
10539 configuration variable `org-file-apps' is checked if it contains an
10540 entry for this file type, and if yes, the corresponding command is launched.
10542 If no application is found, Emacs simply visits the file.
10544 With optional prefix argument IN-EMACS, Emacs will visit the file.
10545 With a double \\[universal-argument] \\[universal-argument] \
10546 prefix arg, Org tries to avoid opening in Emacs
10547 and to use an external application to visit the file.
10549 Optional LINE specifies a line to go to, optional SEARCH a string
10550 to search for. If LINE or SEARCH is given, the file will be
10551 opened in Emacs, unless an entry from org-file-apps that makes
10552 use of groups in a regexp matches.
10554 If you want to change the way frames are used when following a
10555 link, please customize `org-link-frame-setup'.
10557 If the file does not exist, an error is thrown."
10558 (let* ((file (if (equal path "")
10559 buffer-file-name
10560 (substitute-in-file-name (expand-file-name path))))
10561 (file-apps (append org-file-apps (org-default-apps)))
10562 (apps (org-remove-if
10563 'org-file-apps-entry-match-against-dlink-p file-apps))
10564 (apps-dlink (org-remove-if-not
10565 'org-file-apps-entry-match-against-dlink-p file-apps))
10566 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10567 (dirp (if remp nil (file-directory-p file)))
10568 (file (if (and dirp org-open-directory-means-index-dot-org)
10569 (concat (file-name-as-directory file) "index.org")
10570 file))
10571 (a-m-a-p (assq 'auto-mode apps))
10572 (dfile (downcase file))
10573 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10574 (link (cond ((and (eq line nil)
10575 (eq search nil))
10576 file)
10577 (line
10578 (concat file "::" (number-to-string line)))
10579 (search
10580 (concat file "::" search))))
10581 (dlink (downcase link))
10582 (old-buffer (current-buffer))
10583 (old-pos (point))
10584 (old-mode major-mode)
10585 ext cmd link-match-data)
10586 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10587 (setq ext (match-string 1 dfile))
10588 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10589 (setq ext (match-string 1 dfile))))
10590 (cond
10591 ((member in-emacs '((16) system))
10592 (setq cmd (cdr (assoc 'system apps))))
10593 (in-emacs (setq cmd 'emacs))
10595 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10596 (and dirp (cdr (assoc 'directory apps)))
10597 ; first, try matching against apps-dlink
10598 ; if we get a match here, store the match data for later
10599 (let ((match (assoc-default dlink apps-dlink
10600 'string-match)))
10601 (if match
10602 (progn (setq link-match-data (match-data))
10603 match)
10604 (progn (setq in-emacs (or in-emacs line search))
10605 nil))) ; if we have no match in apps-dlink,
10606 ; always open the file in emacs if line or search
10607 ; is given (for backwards compatibility)
10608 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10609 'string-match)
10610 (cdr (assoc ext apps))
10611 (cdr (assoc t apps))))))
10612 (when (eq cmd 'system)
10613 (setq cmd (cdr (assoc 'system apps))))
10614 (when (eq cmd 'default)
10615 (setq cmd (cdr (assoc t apps))))
10616 (when (eq cmd 'mailcap)
10617 (require 'mailcap)
10618 (mailcap-parse-mailcaps)
10619 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10620 (command (mailcap-mime-info mime-type)))
10621 (if (stringp command)
10622 (setq cmd command)
10623 (setq cmd 'emacs))))
10624 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10625 (not (file-exists-p file))
10626 (not org-open-non-existing-files))
10627 (error "No such file: %s" file))
10628 (cond
10629 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10630 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10631 (while (string-match "['\"]%s['\"]" cmd)
10632 (setq cmd (replace-match "%s" t t cmd)))
10633 (while (string-match "%s" cmd)
10634 (setq cmd (replace-match
10635 (save-match-data
10636 (shell-quote-argument
10637 (convert-standard-filename file)))
10638 t t cmd)))
10640 ;; Replace "%1", "%2" etc. in command with group matches from regex
10641 (save-match-data
10642 (let ((match-index 1)
10643 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10644 (set-match-data link-match-data)
10645 (while (<= match-index number-of-groups)
10646 (let ((regex (concat "%" (number-to-string match-index)))
10647 (replace-with (match-string match-index dlink)))
10648 (while (string-match regex cmd)
10649 (setq cmd (replace-match replace-with t t cmd))))
10650 (setq match-index (+ match-index 1)))))
10652 (save-window-excursion
10653 (message "Running %s...done" cmd)
10654 (start-process-shell-command cmd nil cmd)
10655 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10656 ((or (stringp cmd)
10657 (eq cmd 'emacs))
10658 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10659 (widen)
10660 (if line (org-goto-line line)
10661 (if search (org-link-search search))))
10662 ((consp cmd)
10663 (let ((file (convert-standard-filename file)))
10664 (save-match-data
10665 (set-match-data link-match-data)
10666 (eval cmd))))
10667 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10668 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10669 (or (not (equal old-buffer (current-buffer)))
10670 (not (equal old-pos (point))))
10671 (org-mark-ring-push old-pos old-buffer))))
10673 (defun org-file-apps-entry-match-against-dlink-p (entry)
10674 "This function returns non-nil if `entry' uses a regular
10675 expression which should be matched against the whole link by
10676 org-open-file.
10678 It assumes that is the case when the entry uses a regular
10679 expression which has at least one grouping construct and the
10680 action is either a lisp form or a command string containing
10681 '%1', i.e. using at least one subexpression match as a
10682 parameter."
10683 (let ((selector (car entry))
10684 (action (cdr entry)))
10685 (if (stringp selector)
10686 (and (> (regexp-opt-depth selector) 0)
10687 (or (and (stringp action)
10688 (string-match "%[0-9]" action))
10689 (consp action)))
10690 nil)))
10692 (defun org-default-apps ()
10693 "Return the default applications for this operating system."
10694 (cond
10695 ((eq system-type 'darwin)
10696 org-file-apps-defaults-macosx)
10697 ((eq system-type 'windows-nt)
10698 org-file-apps-defaults-windowsnt)
10699 (t org-file-apps-defaults-gnu)))
10701 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10702 "Convert extensions to regular expressions in the cars of LIST.
10703 Also, weed out any non-string entries, because the return value is used
10704 only for regexp matching.
10705 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10706 point to the symbol `emacs', indicating that the file should
10707 be opened in Emacs."
10708 (append
10709 (delq nil
10710 (mapcar (lambda (x)
10711 (if (not (stringp (car x)))
10713 (if (string-match "\\W" (car x))
10715 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10716 list))
10717 (if add-auto-mode
10718 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10720 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10721 (defun org-file-remote-p (file)
10722 "Test whether FILE specifies a location on a remote system.
10723 Return non-nil if the location is indeed remote.
10725 For example, the filename \"/user@host:/foo\" specifies a location
10726 on the system \"/user@host:\"."
10727 (cond ((fboundp 'file-remote-p)
10728 (file-remote-p file))
10729 ((fboundp 'tramp-handle-file-remote-p)
10730 (tramp-handle-file-remote-p file))
10731 ((and (boundp 'ange-ftp-name-format)
10732 (string-match (car ange-ftp-name-format) file))
10733 t)))
10736 ;;;; Refiling
10738 (defun org-get-org-file ()
10739 "Read a filename, with default directory `org-directory'."
10740 (let ((default (or org-default-notes-file remember-data-file)))
10741 (read-file-name (format "File name [%s]: " default)
10742 (file-name-as-directory org-directory)
10743 default)))
10745 (defun org-notes-order-reversed-p ()
10746 "Check if the current file should receive notes in reversed order."
10747 (cond
10748 ((not org-reverse-note-order) nil)
10749 ((eq t org-reverse-note-order) t)
10750 ((not (listp org-reverse-note-order)) nil)
10751 (t (catch 'exit
10752 (let ((all org-reverse-note-order)
10753 entry)
10754 (while (setq entry (pop all))
10755 (if (string-match (car entry) buffer-file-name)
10756 (throw 'exit (cdr entry))))
10757 nil)))))
10759 (defvar org-refile-target-table nil
10760 "The list of refile targets, created by `org-refile'.")
10762 (defvar org-agenda-new-buffers nil
10763 "Buffers created to visit agenda files.")
10765 (defvar org-refile-cache nil
10766 "Cache for refile targets.")
10768 (defvar org-refile-markers nil
10769 "All the markers used for caching refile locations.")
10771 (defun org-refile-marker (pos)
10772 "Get a new refile marker, but only if caching is in use."
10773 (if (not org-refile-use-cache)
10775 (let ((m (make-marker)))
10776 (move-marker m pos)
10777 (push m org-refile-markers)
10778 m)))
10780 (defun org-refile-cache-clear ()
10781 "Clear the refile cache and disable all the markers."
10782 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10783 (setq org-refile-markers nil)
10784 (setq org-refile-cache nil)
10785 (message "Refile cache has been cleared"))
10787 (defun org-refile-cache-check-set (set)
10788 "Check if all the markers in the cache still have live buffers."
10789 (let (marker)
10790 (catch 'exit
10791 (while (and set (setq marker (nth 3 (pop set))))
10792 ;; if org-refile-use-outline-path is 'file, marker may be nil
10793 (when (and marker (null (marker-buffer marker)))
10794 (message "not found") (sit-for 3)
10795 (throw 'exit nil)))
10796 t)))
10798 (defun org-refile-cache-put (set &rest identifiers)
10799 "Push the refile targets SET into the cache, under IDENTIFIERS."
10800 (let* ((key (sha1 (prin1-to-string identifiers)))
10801 (entry (assoc key org-refile-cache)))
10802 (if entry
10803 (setcdr entry set)
10804 (push (cons key set) org-refile-cache))))
10806 (defun org-refile-cache-get (&rest identifiers)
10807 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10808 (cond
10809 ((not org-refile-cache) nil)
10810 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10812 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10813 org-refile-cache))))
10814 (and set (org-refile-cache-check-set set) set)))))
10816 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10817 "Produce a table with refile targets."
10818 (let ((case-fold-search nil)
10819 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10820 (entries (or org-refile-targets '((nil . (:level . 1)))))
10821 targets tgs txt re files f desc descre fast-path-p level pos0)
10822 (message "Getting targets...")
10823 (with-current-buffer (or default-buffer (current-buffer))
10824 (while (setq entry (pop entries))
10825 (setq files (car entry) desc (cdr entry))
10826 (setq fast-path-p nil)
10827 (cond
10828 ((null files) (setq files (list (current-buffer))))
10829 ((eq files 'org-agenda-files)
10830 (setq files (org-agenda-files 'unrestricted)))
10831 ((and (symbolp files) (fboundp files))
10832 (setq files (funcall files)))
10833 ((and (symbolp files) (boundp files))
10834 (setq files (symbol-value files))))
10835 (if (stringp files) (setq files (list files)))
10836 (cond
10837 ((eq (car desc) :tag)
10838 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10839 ((eq (car desc) :todo)
10840 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10841 ((eq (car desc) :regexp)
10842 (setq descre (cdr desc)))
10843 ((eq (car desc) :level)
10844 (setq descre (concat "^\\*\\{" (number-to-string
10845 (if org-odd-levels-only
10846 (1- (* 2 (cdr desc)))
10847 (cdr desc)))
10848 "\\}[ \t]")))
10849 ((eq (car desc) :maxlevel)
10850 (setq fast-path-p t)
10851 (setq descre (concat "^\\*\\{1," (number-to-string
10852 (if org-odd-levels-only
10853 (1- (* 2 (cdr desc)))
10854 (cdr desc)))
10855 "\\}[ \t]")))
10856 (t (error "Bad refiling target description %s" desc)))
10857 (while (setq f (pop files))
10858 (with-current-buffer
10859 (if (bufferp f) f (org-get-agenda-file-buffer f))
10861 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10862 (progn
10863 (if (bufferp f) (setq f (buffer-file-name
10864 (buffer-base-buffer f))))
10865 (setq f (and f (expand-file-name f)))
10866 (if (eq org-refile-use-outline-path 'file)
10867 (push (list (file-name-nondirectory f) f nil nil) tgs))
10868 (save-excursion
10869 (save-restriction
10870 (widen)
10871 (goto-char (point-min))
10872 (while (re-search-forward descre nil t)
10873 (goto-char (setq pos0 (point-at-bol)))
10874 (catch 'next
10875 (when org-refile-target-verify-function
10876 (save-match-data
10877 (or (funcall org-refile-target-verify-function)
10878 (throw 'next t))))
10879 (when (and (looking-at org-complex-heading-regexp)
10880 (not (member (match-string 4) excluded-entries))
10881 (match-string 4))
10882 (setq level (org-reduced-level
10883 (- (match-end 1) (match-beginning 1)))
10884 txt (org-link-display-format (match-string 4))
10885 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10886 re (format org-complex-heading-regexp-format
10887 (regexp-quote (match-string 4))))
10888 (when org-refile-use-outline-path
10889 (setq txt (mapconcat
10890 'org-protect-slash
10891 (append
10892 (if (eq org-refile-use-outline-path
10893 'file)
10894 (list (file-name-nondirectory
10895 (buffer-file-name
10896 (buffer-base-buffer))))
10897 (if (eq org-refile-use-outline-path
10898 'full-file-path)
10899 (list (buffer-file-name
10900 (buffer-base-buffer)))))
10901 (org-get-outline-path fast-path-p
10902 level txt)
10903 (list txt))
10904 "/")))
10905 (push (list txt f re (org-refile-marker (point)))
10906 tgs)))
10907 (when (= (point) pos0)
10908 ;; verification function has not moved point
10909 (goto-char (point-at-eol))))))))
10910 (when org-refile-use-cache
10911 (org-refile-cache-put tgs (buffer-file-name) descre))
10912 (setq targets (append tgs targets))
10913 ))))
10914 (message "Getting targets...done")
10915 (nreverse targets)))
10917 (defun org-protect-slash (s)
10918 (while (string-match "/" s)
10919 (setq s (replace-match "\\" t t s)))
10922 (defvar org-olpa (make-vector 20 nil))
10924 (defun org-get-outline-path (&optional fastp level heading)
10925 "Return the outline path to the current entry, as a list.
10927 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10928 routine which makes outline path derivations for an entire file,
10929 avoiding backtracing. Refile target collection makes use of that."
10930 (if fastp
10931 (progn
10932 (if (> level 19)
10933 (error "Outline path failure, more than 19 levels"))
10934 (loop for i from level upto 19 do
10935 (aset org-olpa i nil))
10936 (prog1
10937 (delq nil (append org-olpa nil))
10938 (aset org-olpa level heading)))
10939 (let (rtn case-fold-search)
10940 (save-excursion
10941 (save-restriction
10942 (widen)
10943 (while (org-up-heading-safe)
10944 (when (looking-at org-complex-heading-regexp)
10945 (push (org-match-string-no-properties 4) rtn)))
10946 rtn)))))
10948 (defun org-format-outline-path (path &optional width prefix separator)
10949 "Format the outline path PATH for display.
10950 WIDTH is the maximum number of characters that is available.
10951 PREFIX is a prefix to be included in the returned string,
10952 such as the file name.
10953 SEPARATOR is inserted between the different parts of the path,
10954 the default is \"/\"."
10955 (setq width (or width 79))
10956 (if prefix (setq width (- width (length prefix))))
10957 (if (not path)
10958 (or prefix "")
10959 (let* ((nsteps (length path))
10960 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10961 (maxwidth (if (<= total-width width)
10962 10000 ;; everything fits
10963 ;; we need to shorten the level headings
10964 (/ (- width nsteps) nsteps)))
10965 (org-odd-levels-only nil)
10966 (n 0)
10967 (total (1+ (length prefix))))
10968 (setq maxwidth (max maxwidth 10))
10969 (concat prefix
10970 (if prefix (or separator "/"))
10971 (mapconcat
10972 (lambda (h)
10973 (setq n (1+ n))
10974 (if (and (= n nsteps) (< maxwidth 10000))
10975 (setq maxwidth (- total-width total)))
10976 (if (< (length h) maxwidth)
10977 (progn (setq total (+ total (length h) 1)) h)
10978 (setq h (substring h 0 (- maxwidth 2))
10979 total (+ total maxwidth 1))
10980 (if (string-match "[ \t]+\\'" h)
10981 (setq h (substring h 0 (match-beginning 0))))
10982 (setq h (concat h "..")))
10983 (org-add-props h nil 'face
10984 (nth (% (1- n) org-n-level-faces)
10985 org-level-faces))
10987 path (or separator "/"))))))
10989 (defun org-display-outline-path (&optional file current separator just-return-string)
10990 "Display the current outline path in the echo area.
10992 If FILE is non-nil, prepend the output with the file name.
10993 If CURRENT is non-nil, append the current heading to the output.
10994 SEPARATOR is passed through to `org-format-outline-path'. It separates
10995 the different parts of the path and defaults to \"/\".
10996 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10997 (interactive "P")
10998 (let* (case-fold-search
10999 message-log-max ; Don't populate the *Messages* buffer
11000 (bfn (buffer-file-name (buffer-base-buffer)))
11001 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11002 res)
11003 (if current (setq path (append path
11004 (save-excursion
11005 (org-back-to-heading t)
11006 (if (looking-at org-complex-heading-regexp)
11007 (list (match-string 4)))))))
11008 (setq res
11009 (org-format-outline-path
11010 path
11011 (1- (frame-width))
11012 (and file bfn (concat (file-name-nondirectory bfn) separator))
11013 separator))
11014 (if just-return-string
11015 (org-no-properties res)
11016 (message "%s" res))))
11018 (defvar org-refile-history nil
11019 "History for refiling operations.")
11021 (defvar org-after-refile-insert-hook nil
11022 "Hook run after `org-refile' has inserted its stuff at the new location.
11023 Note that this is still *before* the stuff will be removed from
11024 the *old* location.")
11026 (defvar org-capture-last-stored-marker)
11027 (defvar org-refile-keep nil
11028 "Non-nil means `org-refile' will copy instead of refile.")
11030 (defun org-copy ()
11031 "Like `org-refile', but copy."
11032 (interactive)
11033 (let ((org-refile-keep t))
11034 (funcall 'org-refile nil nil nil "Copy")))
11036 (defun org-refile (&optional goto default-buffer rfloc msg)
11037 "Move the entry or entries at point to another heading.
11038 The list of target headings is compiled using the information in
11039 `org-refile-targets', which see.
11041 At the target location, the entry is filed as a subitem of the target
11042 heading. Depending on `org-reverse-note-order', the new subitem will
11043 either be the first or the last subitem.
11045 If there is an active region, all entries in that region will be moved.
11046 However, the region must fulfill the requirement that the first heading
11047 is the first one sets the top-level of the moved text - at most siblings
11048 below it are allowed.
11050 With prefix arg GOTO, the command will only visit the target location
11051 and not actually move anything.
11053 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11054 go to the location where the last refiling operation has put the subtree.
11055 With a prefix argument of `2', refile to the running clock.
11057 RFLOC can be a refile location obtained in a different way.
11059 MSG is a string to replace \"Refile\" in the default prompt with
11060 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11062 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11064 If you are using target caching (see `org-refile-use-cache'),
11065 you have to clear the target cache in order to find new targets.
11066 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11067 prefix argument (`C-u C-u C-u C-c C-w')."
11069 (interactive "P")
11070 (if (member goto '(0 (64)))
11071 (org-refile-cache-clear)
11072 (let* ((actionmsg (or msg "Refile"))
11073 (cbuf (current-buffer))
11074 (regionp (org-region-active-p))
11075 (region-start (and regionp (region-beginning)))
11076 (region-end (and regionp (region-end)))
11077 (region-length (and regionp (- region-end region-start)))
11078 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11079 pos it nbuf file re level reversed)
11080 (setq last-command nil)
11081 (when regionp
11082 (goto-char region-start)
11083 (or (bolp) (goto-char (point-at-bol)))
11084 (setq region-start (point))
11085 (unless (or (org-kill-is-subtree-p
11086 (buffer-substring region-start region-end))
11087 (prog1 org-refile-active-region-within-subtree
11088 (org-toggle-heading)))
11089 (error "The region is not a (sequence of) subtree(s)")))
11090 (if (equal goto '(16))
11091 (org-refile-goto-last-stored)
11092 (when (or
11093 (and (equal goto 2)
11094 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11095 (prog1
11096 (setq it (list (or org-clock-heading "running clock")
11097 (buffer-file-name
11098 (marker-buffer org-clock-hd-marker))
11100 (marker-position org-clock-hd-marker)))
11101 (setq goto nil)))
11102 (setq it (or rfloc
11103 (let (heading-text)
11104 (save-excursion
11105 (unless goto
11106 (org-back-to-heading t)
11107 (setq heading-text
11108 (nth 4 (org-heading-components))))
11110 (org-refile-get-location
11111 (cond (goto "Goto")
11112 (regionp (concat actionmsg " region to"))
11113 (t (concat actionmsg " subtree \""
11114 heading-text "\" to")))
11115 default-buffer
11116 (and (not (equal '(4) goto))
11117 org-refile-allow-creating-parent-nodes)
11118 goto))))))
11119 (setq file (nth 1 it)
11120 re (nth 2 it)
11121 pos (nth 3 it))
11122 (if (and (not goto)
11124 (equal (buffer-file-name) file)
11125 (if regionp
11126 (and (>= pos region-start)
11127 (<= pos region-end))
11128 (and (>= pos (point))
11129 (< pos (save-excursion
11130 (org-end-of-subtree t t))))))
11131 (error "Cannot refile to position inside the tree or region"))
11133 (setq nbuf (or (find-buffer-visiting file)
11134 (find-file-noselect file)))
11135 (if goto
11136 (progn
11137 (org-pop-to-buffer-same-window nbuf)
11138 (goto-char pos)
11139 (org-show-context 'org-goto))
11140 (if regionp
11141 (progn
11142 (org-kill-new (buffer-substring region-start region-end))
11143 (org-save-markers-in-region region-start region-end))
11144 (org-copy-subtree 1 nil t))
11145 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11146 (find-file-noselect file)))
11147 (setq reversed (org-notes-order-reversed-p))
11148 (save-excursion
11149 (save-restriction
11150 (widen)
11151 (if pos
11152 (progn
11153 (goto-char pos)
11154 (looking-at org-outline-regexp)
11155 (setq level (org-get-valid-level (funcall outline-level) 1))
11156 (goto-char
11157 (if reversed
11158 (or (outline-next-heading) (point-max))
11159 (or (save-excursion (org-get-next-sibling))
11160 (org-end-of-subtree t t)
11161 (point-max)))))
11162 (setq level 1)
11163 (if (not reversed)
11164 (goto-char (point-max))
11165 (goto-char (point-min))
11166 (or (outline-next-heading) (goto-char (point-max)))))
11167 (if (not (bolp)) (newline))
11168 (org-paste-subtree level)
11169 (when org-log-refile
11170 (org-add-log-setup 'refile nil nil 'findpos
11171 org-log-refile)
11172 (unless (eq org-log-refile 'note)
11173 (save-excursion (org-add-log-note))))
11174 (and org-auto-align-tags
11175 (let ((org-loop-over-headlines-in-active-region nil))
11176 (org-set-tags nil t)))
11177 (with-demoted-errors
11178 (bookmark-set "org-refile-last-stored"))
11179 ;; If we are refiling for capture, make sure that the
11180 ;; last-capture pointers point here
11181 (when (org-bound-and-true-p org-refile-for-capture)
11182 (with-demoted-errors
11183 (bookmark-set "org-capture-last-stored-marker"))
11184 (move-marker org-capture-last-stored-marker (point)))
11185 (if (fboundp 'deactivate-mark) (deactivate-mark))
11186 (run-hooks 'org-after-refile-insert-hook))))
11187 (unless org-refile-keep
11188 (if regionp
11189 (delete-region (point) (+ (point) region-length))
11190 (org-cut-subtree)))
11191 (when (featurep 'org-inlinetask)
11192 (org-inlinetask-remove-END-maybe))
11193 (setq org-markers-to-move nil)
11194 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11196 (defun org-refile-goto-last-stored ()
11197 "Go to the location where the last refile was stored."
11198 (interactive)
11199 (bookmark-jump "org-refile-last-stored")
11200 (message "This is the location of the last refile"))
11202 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11203 no-exclude)
11204 "Prompt the user for a refile location, using PROMPT.
11205 PROMPT should not be suffixed with a colon and a space, because
11206 this function appends the default value from
11207 `org-refile-history' automatically, if that is not empty.
11208 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11209 this is used for the GOTO interface."
11210 (let ((org-refile-targets org-refile-targets)
11211 (org-refile-use-outline-path org-refile-use-outline-path)
11212 excluded-entries)
11213 (when (and (derived-mode-p 'org-mode)
11214 (not org-refile-use-cache)
11215 (not no-exclude))
11216 (org-map-tree
11217 (lambda()
11218 (setq excluded-entries
11219 (append excluded-entries (list (org-get-heading t t)))))))
11220 (setq org-refile-target-table
11221 (org-refile-get-targets default-buffer excluded-entries)))
11222 (unless org-refile-target-table
11223 (error "No refile targets"))
11224 (let* ((cbuf (current-buffer))
11225 (partial-completion-mode nil)
11226 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11227 (cfunc (if (and org-refile-use-outline-path
11228 org-outline-path-complete-in-steps)
11229 'org-olpath-completing-read
11230 'org-icompleting-read))
11231 (extra (if org-refile-use-outline-path "/" ""))
11232 (cbnex (concat (buffer-name) extra))
11233 (filename (and cfn (expand-file-name cfn)))
11234 (tbl (mapcar
11235 (lambda (x)
11236 (if (and (not (member org-refile-use-outline-path
11237 '(file full-file-path)))
11238 (not (equal filename (nth 1 x))))
11239 (cons (concat (car x) extra " ("
11240 (file-name-nondirectory (nth 1 x)) ")")
11241 (cdr x))
11242 (cons (concat (car x) extra) (cdr x))))
11243 org-refile-target-table))
11244 (completion-ignore-case t)
11245 cdef
11246 (prompt (concat prompt
11247 (or (and (car org-refile-history)
11248 (concat " (default " (car org-refile-history) ")"))
11249 (and (assoc cbnex tbl) (setq cdef cbnex)
11250 (concat " (default " cbnex ")"))) ": "))
11251 pa answ parent-target child parent old-hist)
11252 (setq old-hist org-refile-history)
11253 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11254 nil 'org-refile-history (or cdef (car org-refile-history))))
11255 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11256 (org-refile-check-position pa)
11257 (if pa
11258 (progn
11259 (when (or (not org-refile-history)
11260 (not (eq old-hist org-refile-history))
11261 (not (equal (car pa) (car org-refile-history))))
11262 (setq org-refile-history
11263 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11264 org-refile-history
11265 (cdr org-refile-history))))
11266 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11267 (pop org-refile-history)))
11269 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11270 (progn
11271 (setq parent (match-string 1 answ)
11272 child (match-string 2 answ))
11273 (setq parent-target (or (assoc parent tbl)
11274 (assoc (concat parent "/") tbl)))
11275 (when (and parent-target
11276 (or (eq new-nodes t)
11277 (and (eq new-nodes 'confirm)
11278 (y-or-n-p (format "Create new node \"%s\"? "
11279 child)))))
11280 (org-refile-new-child parent-target child)))
11281 (error "Invalid target location")))))
11283 (declare-function org-string-nw-p "org-macs" (s))
11284 (defun org-refile-check-position (refile-pointer)
11285 "Check if the refile pointer matches the headline to which it points."
11286 (let* ((file (nth 1 refile-pointer))
11287 (re (nth 2 refile-pointer))
11288 (pos (nth 3 refile-pointer))
11289 buffer)
11290 (if (and (not (markerp pos)) (not file))
11291 (error "Please save the buffer to a file before refiling")
11292 (when (org-string-nw-p re)
11293 (setq buffer (if (markerp pos)
11294 (marker-buffer pos)
11295 (or (find-buffer-visiting file)
11296 (find-file-noselect file))))
11297 (with-current-buffer buffer
11298 (save-excursion
11299 (save-restriction
11300 (widen)
11301 (goto-char pos)
11302 (beginning-of-line 1)
11303 (unless (org-looking-at-p re)
11304 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11306 (defun org-refile-new-child (parent-target child)
11307 "Use refile target PARENT-TARGET to add new CHILD below it."
11308 (unless parent-target
11309 (error "Cannot find parent for new node"))
11310 (let ((file (nth 1 parent-target))
11311 (pos (nth 3 parent-target))
11312 level)
11313 (with-current-buffer (or (find-buffer-visiting file)
11314 (find-file-noselect file))
11315 (save-excursion
11316 (save-restriction
11317 (widen)
11318 (if pos
11319 (goto-char pos)
11320 (goto-char (point-max))
11321 (if (not (bolp)) (newline)))
11322 (when (looking-at org-outline-regexp)
11323 (setq level (funcall outline-level))
11324 (org-end-of-subtree t t))
11325 (org-back-over-empty-lines)
11326 (insert "\n" (make-string
11327 (if pos (org-get-valid-level level 1) 1) ?*)
11328 " " child "\n")
11329 (beginning-of-line 0)
11330 (list (concat (car parent-target) "/" child) file "" (point)))))))
11332 (defun org-olpath-completing-read (prompt collection &rest args)
11333 "Read an outline path like a file name."
11334 (let ((thetable collection)
11335 (org-completion-use-ido nil) ; does not work with ido.
11336 (org-completion-use-iswitchb nil)) ; or iswitchb
11337 (apply
11338 'org-icompleting-read prompt
11339 (lambda (string predicate &optional flag)
11340 (let (rtn r f (l (length string)))
11341 (cond
11342 ((eq flag nil)
11343 ;; try completion
11344 (try-completion string thetable))
11345 ((eq flag t)
11346 ;; all-completions
11347 (setq rtn (all-completions string thetable predicate))
11348 (mapcar
11349 (lambda (x)
11350 (setq r (substring x l))
11351 (if (string-match " ([^)]*)$" x)
11352 (setq f (match-string 0 x))
11353 (setq f ""))
11354 (if (string-match "/" r)
11355 (concat string (substring r 0 (match-end 0)) f)
11357 rtn))
11358 ((eq flag 'lambda)
11359 ;; exact match?
11360 (assoc string thetable)))))
11361 args)))
11363 ;;;; Dynamic blocks
11365 (defun org-find-dblock (name)
11366 "Find the first dynamic block with name NAME in the buffer.
11367 If not found, stay at current position and return nil."
11368 (let ((case-fold-search t) pos)
11369 (save-excursion
11370 (goto-char (point-min))
11371 (setq pos (and (re-search-forward
11372 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11373 (match-beginning 0))))
11374 (if pos (goto-char pos))
11375 pos))
11377 (defconst org-dblock-start-re
11378 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11379 "Matches the start line of a dynamic block, with parameters.")
11381 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11382 "Matches the end of a dynamic block.")
11384 (defun org-create-dblock (plist)
11385 "Create a dynamic block section, with parameters taken from PLIST.
11386 PLIST must contain a :name entry which is used as name of the block."
11387 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11388 (end-of-line 1)
11389 (newline))
11390 (let ((col (current-column))
11391 (name (plist-get plist :name)))
11392 (insert "#+BEGIN: " name)
11393 (while plist
11394 (if (eq (car plist) :name)
11395 (setq plist (cddr plist))
11396 (insert " " (prin1-to-string (pop plist)))))
11397 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11398 (beginning-of-line -2)))
11400 (defun org-prepare-dblock ()
11401 "Prepare dynamic block for refresh.
11402 This empties the block, puts the cursor at the insert position and returns
11403 the property list including an extra property :name with the block name."
11404 (unless (looking-at org-dblock-start-re)
11405 (error "Not at a dynamic block"))
11406 (let* ((begdel (1+ (match-end 0)))
11407 (name (org-no-properties (match-string 1)))
11408 (params (append (list :name name)
11409 (read (concat "(" (match-string 3) ")")))))
11410 (save-excursion
11411 (beginning-of-line 1)
11412 (skip-chars-forward " \t")
11413 (setq params (plist-put params :indentation-column (current-column))))
11414 (unless (re-search-forward org-dblock-end-re nil t)
11415 (error "Dynamic block not terminated"))
11416 (setq params
11417 (append params
11418 (list :content (buffer-substring
11419 begdel (match-beginning 0)))))
11420 (delete-region begdel (match-beginning 0))
11421 (goto-char begdel)
11422 (open-line 1)
11423 params))
11425 (defun org-map-dblocks (&optional command)
11426 "Apply COMMAND to all dynamic blocks in the current buffer.
11427 If COMMAND is not given, use `org-update-dblock'."
11428 (let ((cmd (or command 'org-update-dblock)))
11429 (save-excursion
11430 (goto-char (point-min))
11431 (while (re-search-forward org-dblock-start-re nil t)
11432 (goto-char (match-beginning 0))
11433 (save-excursion
11434 (condition-case nil
11435 (funcall cmd)
11436 (error (message "Error during update of dynamic block"))))
11437 (unless (re-search-forward org-dblock-end-re nil t)
11438 (error "Dynamic block not terminated"))))))
11440 (defun org-dblock-update (&optional arg)
11441 "User command for updating dynamic blocks.
11442 Update the dynamic block at point. With prefix ARG, update all dynamic
11443 blocks in the buffer."
11444 (interactive "P")
11445 (if arg
11446 (org-update-all-dblocks)
11447 (or (looking-at org-dblock-start-re)
11448 (org-beginning-of-dblock))
11449 (org-update-dblock)))
11451 (defun org-update-dblock ()
11452 "Update the dynamic block at point.
11453 This means to empty the block, parse for parameters and then call
11454 the correct writing function."
11455 (interactive)
11456 (save-window-excursion
11457 (let* ((pos (point))
11458 (line (org-current-line))
11459 (params (org-prepare-dblock))
11460 (name (plist-get params :name))
11461 (indent (plist-get params :indentation-column))
11462 (cmd (intern (concat "org-dblock-write:" name))))
11463 (message "Updating dynamic block `%s' at line %d..." name line)
11464 (funcall cmd params)
11465 (message "Updating dynamic block `%s' at line %d...done" name line)
11466 (goto-char pos)
11467 (when (and indent (> indent 0))
11468 (setq indent (make-string indent ?\ ))
11469 (save-excursion
11470 (org-beginning-of-dblock)
11471 (forward-line 1)
11472 (while (not (looking-at org-dblock-end-re))
11473 (insert indent)
11474 (beginning-of-line 2))
11475 (when (looking-at org-dblock-end-re)
11476 (and (looking-at "[ \t]+")
11477 (replace-match ""))
11478 (insert indent)))))))
11480 (defun org-beginning-of-dblock ()
11481 "Find the beginning of the dynamic block at point.
11482 Error if there is no such block at point."
11483 (let ((pos (point))
11484 beg)
11485 (end-of-line 1)
11486 (if (and (re-search-backward org-dblock-start-re nil t)
11487 (setq beg (match-beginning 0))
11488 (re-search-forward org-dblock-end-re nil t)
11489 (> (match-end 0) pos))
11490 (goto-char beg)
11491 (goto-char pos)
11492 (error "Not in a dynamic block"))))
11494 (defun org-update-all-dblocks ()
11495 "Update all dynamic blocks in the buffer.
11496 This function can be used in a hook."
11497 (interactive)
11498 (when (derived-mode-p 'org-mode)
11499 (org-map-dblocks 'org-update-dblock)))
11502 ;;;; Completion
11504 (defconst org-additional-option-like-keywords
11505 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11506 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11507 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11508 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11509 "BEGIN:" "END:"
11510 "ORGTBL" "TBLFM:" "TBLNAME:"
11511 "BEGIN_EXAMPLE" "END_EXAMPLE"
11512 "BEGIN_VERBATIM" "END_VERBATIM"
11513 "BEGIN_QUOTE" "END_QUOTE"
11514 "BEGIN_VERSE" "END_VERSE"
11515 "BEGIN_CENTER" "END_CENTER"
11516 "BEGIN_SRC" "END_SRC"
11517 "BEGIN_RESULT" "END_RESULT"
11518 "BEGIN_lstlisting" "END_lstlisting"
11519 "NAME:" "RESULTS:"
11520 "HEADER:" "HEADERS:"
11521 "COLUMNS:" "PROPERTY:"
11522 "CAPTION:" "LABEL:"
11523 "SETUPFILE:"
11524 "INCLUDE:" "INDEX:"
11525 "BIND:"
11526 "MACRO:"))
11528 (defconst org-options-keywords
11529 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11530 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11531 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11532 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11533 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11534 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11535 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11537 (defconst org-additional-option-like-keywords-for-flyspell
11538 (delete-dups
11539 (split-string
11540 (mapconcat (lambda(k)
11541 (replace-regexp-in-string
11542 "_\\|:" " "
11543 (concat k " " (downcase k) " " (upcase k))))
11544 (append org-options-keywords org-additional-option-like-keywords)
11545 " ")
11546 " +" t)))
11548 (defcustom org-structure-template-alist
11549 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11550 "<src lang=\"?\">\n\n</src>")
11551 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11552 "<example>\n?\n</example>")
11553 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11554 "<quote>\n?\n</quote>")
11555 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11556 "<verse>\n?\n</verse>")
11557 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11558 "<verbatim>\n?\n</verbatim>")
11559 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11560 "<center>\n?\n</center>")
11561 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11562 "<literal style=\"latex\">\n?\n</literal>")
11563 ("L" "#+LaTeX: "
11564 "<literal style=\"latex\">?</literal>")
11565 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11566 "<literal style=\"html\">\n?\n</literal>")
11567 ("H" "#+HTML: "
11568 "<literal style=\"html\">?</literal>")
11569 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11570 ("A" "#+ASCII: ")
11571 ("i" "#+INDEX: ?"
11572 "#+INDEX: ?")
11573 ("I" "#+INCLUDE: %file ?"
11574 "<include file=%file markup=\"?\">"))
11575 "Structure completion elements.
11576 This is a list of abbreviation keys and values. The value gets inserted
11577 if you type `<' followed by the key and then press the completion key,
11578 usually `M-TAB'. %file will be replaced by a file name after prompting
11579 for the file using completion. The cursor will be placed at the position
11580 of the `?` in the template.
11581 There are two templates for each key, the first uses the original Org syntax,
11582 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11583 the default when the /org-mtags.el/ module has been loaded. See also the
11584 variable `org-mtags-prefer-muse-templates'."
11585 :group 'org-completion
11586 :type '(repeat
11587 (string :tag "Key")
11588 (string :tag "Template")
11589 (string :tag "Muse Template")))
11591 (defun org-try-structure-completion ()
11592 "Try to complete a structure template before point.
11593 This looks for strings like \"<e\" on an otherwise empty line and
11594 expands them."
11595 (let ((l (buffer-substring (point-at-bol) (point)))
11597 (when (and (looking-at "[ \t]*$")
11598 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11599 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11600 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11601 (match-beginning 1)) a)
11602 t)))
11604 (defun org-complete-expand-structure-template (start cell)
11605 "Expand a structure template."
11606 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11607 (rpl (nth (if musep 2 1) cell))
11608 (ind ""))
11609 (delete-region start (point))
11610 (when (string-match "\\`#\\+" rpl)
11611 (cond
11612 ((bolp))
11613 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11614 (setq ind (buffer-substring (point-at-bol) (point))))
11615 (t (newline))))
11616 (setq start (point))
11617 (if (string-match "%file" rpl)
11618 (setq rpl (replace-match
11619 (concat
11620 "\""
11621 (save-match-data
11622 (abbreviate-file-name (read-file-name "Include file: ")))
11623 "\"")
11624 t t rpl)))
11625 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11626 (concat "\n" ind)))
11627 (insert rpl)
11628 (if (re-search-backward "\\?" start t) (delete-char 1))))
11630 ;;;; TODO, DEADLINE, Comments
11632 (defun org-toggle-comment ()
11633 "Change the COMMENT state of an entry."
11634 (interactive)
11635 (save-excursion
11636 (org-back-to-heading)
11637 (let (case-fold-search)
11638 (cond
11639 ((looking-at (format org-heading-keyword-regexp-format
11640 org-comment-string))
11641 (goto-char (match-end 1))
11642 (looking-at (concat " +" org-comment-string))
11643 (replace-match "" t t)
11644 (when (eolp) (insert " ")))
11645 ((looking-at org-outline-regexp)
11646 (goto-char (match-end 0))
11647 (insert org-comment-string " "))))))
11649 (defvar org-last-todo-state-is-todo nil
11650 "This is non-nil when the last TODO state change led to a TODO state.
11651 If the last change removed the TODO tag or switched to DONE, then
11652 this is nil.")
11654 (defvar org-setting-tags nil) ; dynamically skipped
11656 (defvar org-todo-setup-filter-hook nil
11657 "Hook for functions that pre-filter todo specs.
11658 Each function takes a todo spec and returns either nil or the spec
11659 transformed into canonical form." )
11661 (defvar org-todo-get-default-hook nil
11662 "Hook for functions that get a default item for todo.
11663 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11664 nil or a string to be used for the todo mark." )
11666 (defvar org-agenda-headline-snapshot-before-repeat)
11668 (defun org-current-effective-time ()
11669 "Return current time adjusted for `org-extend-today-until' variable."
11670 (let* ((ct (org-current-time))
11671 (dct (decode-time ct))
11672 (ct1
11673 (cond
11674 (org-use-last-clock-out-time-as-effective-time
11675 (or (org-clock-get-last-clock-out-time) ct))
11676 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11677 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11678 (t ct))))
11679 ct1))
11681 (defun org-todo-yesterday (&optional arg)
11682 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11683 (interactive "P")
11684 (if (eq major-mode 'org-agenda-mode)
11685 (apply 'org-agenda-todo-yesterday arg)
11686 (let* ((hour (third (decode-time
11687 (org-current-time))))
11688 (org-extend-today-until (1+ hour)))
11689 (org-todo arg))))
11691 (defvar org-block-entry-blocking ""
11692 "First entry preventing the TODO state change.")
11694 (defun org-todo (&optional arg)
11695 "Change the TODO state of an item.
11696 The state of an item is given by a keyword at the start of the heading,
11697 like
11698 *** TODO Write paper
11699 *** DONE Call mom
11701 The different keywords are specified in the variable `org-todo-keywords'.
11702 By default the available states are \"TODO\" and \"DONE\".
11703 So for this example: when the item starts with TODO, it is changed to DONE.
11704 When it starts with DONE, the DONE is removed. And when neither TODO nor
11705 DONE are present, add TODO at the beginning of the heading.
11707 With \\[universal-argument] prefix arg, use completion to determine the new \
11708 state.
11709 With numeric prefix arg, switch to that state.
11710 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11711 keywords (nextset).
11712 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11713 With a numeric prefix arg of 0, inhibit note taking for the change.
11715 For calling through lisp, arg is also interpreted in the following way:
11716 'none -> empty state
11717 \"\"(empty string) -> switch to empty state
11718 'done -> switch to DONE
11719 'nextset -> switch to the next set of keywords
11720 'previousset -> switch to the previous set of keywords
11721 \"WAITING\" -> switch to the specified keyword, but only if it
11722 really is a member of `org-todo-keywords'."
11723 (interactive "P")
11724 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11725 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11726 'region-start-level 'region))
11727 org-loop-over-headlines-in-active-region)
11728 (org-map-entries
11729 `(org-todo ,arg)
11730 org-loop-over-headlines-in-active-region
11731 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11732 (if (equal arg '(16)) (setq arg 'nextset))
11733 (let ((org-blocker-hook org-blocker-hook)
11734 commentp
11735 case-fold-search)
11736 (when (equal arg '(64))
11737 (setq arg nil org-blocker-hook nil))
11738 (when (and org-blocker-hook
11739 (or org-inhibit-blocking
11740 (org-entry-get nil "NOBLOCKING")))
11741 (setq org-blocker-hook nil))
11742 (save-excursion
11743 (catch 'exit
11744 (org-back-to-heading t)
11745 (when (looking-at (concat "^\\*+ " org-comment-string))
11746 (org-toggle-comment)
11747 (setq commentp t))
11748 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11749 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11750 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11751 (let* ((match-data (match-data))
11752 (startpos (point-at-bol))
11753 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11754 (org-log-done org-log-done)
11755 (org-log-repeat org-log-repeat)
11756 (org-todo-log-states org-todo-log-states)
11757 (org-inhibit-logging
11758 (if (equal arg 0)
11759 (progn (setq arg nil) 'note) org-inhibit-logging))
11760 (this (match-string 1))
11761 (hl-pos (match-beginning 0))
11762 (head (org-get-todo-sequence-head this))
11763 (ass (assoc head org-todo-kwd-alist))
11764 (interpret (nth 1 ass))
11765 (done-word (nth 3 ass))
11766 (final-done-word (nth 4 ass))
11767 (org-last-state (or this ""))
11768 (completion-ignore-case t)
11769 (member (member this org-todo-keywords-1))
11770 (tail (cdr member))
11771 (org-state (cond
11772 ((and org-todo-key-trigger
11773 (or (and (equal arg '(4))
11774 (eq org-use-fast-todo-selection 'prefix))
11775 (and (not arg) org-use-fast-todo-selection
11776 (not (eq org-use-fast-todo-selection
11777 'prefix)))))
11778 ;; Use fast selection
11779 (org-fast-todo-selection))
11780 ((and (equal arg '(4))
11781 (or (not org-use-fast-todo-selection)
11782 (not org-todo-key-trigger)))
11783 ;; Read a state with completion
11784 (org-icompleting-read
11785 "State: " (mapcar (lambda(x) (list x))
11786 org-todo-keywords-1)
11787 nil t))
11788 ((eq arg 'right)
11789 (if this
11790 (if tail (car tail) nil)
11791 (car org-todo-keywords-1)))
11792 ((eq arg 'left)
11793 (if (equal member org-todo-keywords-1)
11795 (if this
11796 (nth (- (length org-todo-keywords-1)
11797 (length tail) 2)
11798 org-todo-keywords-1)
11799 (org-last org-todo-keywords-1))))
11800 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11801 (setq arg nil))) ; hack to fall back to cycling
11802 (arg
11803 ;; user or caller requests a specific state
11804 (cond
11805 ((equal arg "") nil)
11806 ((eq arg 'none) nil)
11807 ((eq arg 'done) (or done-word (car org-done-keywords)))
11808 ((eq arg 'nextset)
11809 (or (car (cdr (member head org-todo-heads)))
11810 (car org-todo-heads)))
11811 ((eq arg 'previousset)
11812 (let ((org-todo-heads (reverse org-todo-heads)))
11813 (or (car (cdr (member head org-todo-heads)))
11814 (car org-todo-heads))))
11815 ((car (member arg org-todo-keywords-1)))
11816 ((stringp arg)
11817 (error "State `%s' not valid in this file" arg))
11818 ((nth (1- (prefix-numeric-value arg))
11819 org-todo-keywords-1))))
11820 ((null member) (or head (car org-todo-keywords-1)))
11821 ((equal this final-done-word) nil) ;; -> make empty
11822 ((null tail) nil) ;; -> first entry
11823 ((memq interpret '(type priority))
11824 (if (eq this-command last-command)
11825 (car tail)
11826 (if (> (length tail) 0)
11827 (or done-word (car org-done-keywords))
11828 nil)))
11830 (car tail))))
11831 (org-state (or
11832 (run-hook-with-args-until-success
11833 'org-todo-get-default-hook org-state org-last-state)
11834 org-state))
11835 (next (if org-state (concat " " org-state " ") " "))
11836 (change-plist (list :type 'todo-state-change :from this :to org-state
11837 :position startpos))
11838 dolog now-done-p)
11839 (when org-blocker-hook
11840 (setq org-last-todo-state-is-todo
11841 (not (member this org-done-keywords)))
11842 (unless (save-excursion
11843 (save-match-data
11844 (org-with-wide-buffer
11845 (run-hook-with-args-until-failure
11846 'org-blocker-hook change-plist))))
11847 (if (org-called-interactively-p 'interactive)
11848 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11849 this org-state org-block-entry-blocking)
11850 ;; fail silently
11851 (message "TODO state change from %s to %s blocked (by \"%s\")"
11852 this org-state org-block-entry-blocking)
11853 (throw 'exit nil))))
11854 (store-match-data match-data)
11855 (replace-match next t t)
11856 (unless (pos-visible-in-window-p hl-pos)
11857 (message "TODO state changed to %s" (org-trim next)))
11858 (unless head
11859 (setq head (org-get-todo-sequence-head org-state)
11860 ass (assoc head org-todo-kwd-alist)
11861 interpret (nth 1 ass)
11862 done-word (nth 3 ass)
11863 final-done-word (nth 4 ass)))
11864 (when (memq arg '(nextset previousset))
11865 (message "Keyword-Set %d/%d: %s"
11866 (- (length org-todo-sets) -1
11867 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11868 (length org-todo-sets)
11869 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11870 (setq org-last-todo-state-is-todo
11871 (not (member org-state org-done-keywords)))
11872 (setq now-done-p (and (member org-state org-done-keywords)
11873 (not (member this org-done-keywords))))
11874 (and logging (org-local-logging logging))
11875 (when (and (or org-todo-log-states org-log-done)
11876 (not (eq org-inhibit-logging t))
11877 (not (memq arg '(nextset previousset))))
11878 ;; we need to look at recording a time and note
11879 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11880 (nth 2 (assoc this org-todo-log-states))))
11881 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11882 (setq dolog 'time))
11883 (when (and org-state
11884 (member org-state org-not-done-keywords)
11885 (not (member this org-not-done-keywords)))
11886 ;; This is now a todo state and was not one before
11887 ;; If there was a CLOSED time stamp, get rid of it.
11888 (org-add-planning-info nil nil 'closed))
11889 (when (and now-done-p org-log-done)
11890 ;; It is now done, and it was not done before
11891 (org-add-planning-info 'closed (org-current-effective-time))
11892 (if (and (not dolog) (eq 'note org-log-done))
11893 (org-add-log-setup 'done org-state this 'findpos 'note)))
11894 (when (and org-state dolog)
11895 ;; This is a non-nil state, and we need to log it
11896 (org-add-log-setup 'state org-state this 'findpos dolog)))
11897 ;; Fixup tag positioning
11898 (org-todo-trigger-tag-changes org-state)
11899 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11900 (when org-provide-todo-statistics
11901 (org-update-parent-todo-statistics))
11902 (run-hooks 'org-after-todo-state-change-hook)
11903 (if (and arg (not (member org-state org-done-keywords)))
11904 (setq head (org-get-todo-sequence-head org-state)))
11905 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11906 ;; Do we need to trigger a repeat?
11907 (when now-done-p
11908 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11909 ;; This is for the agenda, take a snapshot of the headline.
11910 (save-match-data
11911 (setq org-agenda-headline-snapshot-before-repeat
11912 (org-get-heading))))
11913 (org-auto-repeat-maybe org-state))
11914 ;; Fixup cursor location if close to the keyword
11915 (if (and (outline-on-heading-p)
11916 (not (bolp))
11917 (save-excursion (beginning-of-line 1)
11918 (looking-at org-todo-line-regexp))
11919 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11920 (progn
11921 (goto-char (or (match-end 2) (match-end 1)))
11922 (and (looking-at " ") (just-one-space))))
11923 (when org-trigger-hook
11924 (save-excursion
11925 (run-hook-with-args 'org-trigger-hook change-plist)))
11926 (when commentp (org-toggle-comment))))))))
11928 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11929 "Block turning an entry into a TODO, using the hierarchy.
11930 This checks whether the current task should be blocked from state
11931 changes. Such blocking occurs when:
11933 1. The task has children which are not all in a completed state.
11935 2. A task has a parent with the property :ORDERED:, and there
11936 are siblings prior to the current task with incomplete
11937 status.
11939 3. The parent of the task is blocked because it has siblings that should
11940 be done first, or is child of a block grandparent TODO entry."
11942 (if (not org-enforce-todo-dependencies)
11943 t ; if locally turned off don't block
11944 (catch 'dont-block
11945 ;; If this is not a todo state change, or if this entry is already DONE,
11946 ;; do not block
11947 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11948 (member (plist-get change-plist :from)
11949 (cons 'done org-done-keywords))
11950 (member (plist-get change-plist :to)
11951 (cons 'todo org-not-done-keywords))
11952 (not (plist-get change-plist :to)))
11953 (throw 'dont-block t))
11954 ;; If this task has children, and any are undone, it's blocked
11955 (save-excursion
11956 (org-back-to-heading t)
11957 (let ((this-level (funcall outline-level)))
11958 (outline-next-heading)
11959 (let ((child-level (funcall outline-level)))
11960 (while (and (not (eobp))
11961 (> child-level this-level))
11962 ;; this todo has children, check whether they are all
11963 ;; completed
11964 (if (and (not (org-entry-is-done-p))
11965 (org-entry-is-todo-p))
11966 (progn (setq org-block-entry-blocking (org-get-heading))
11967 (throw 'dont-block nil)))
11968 (outline-next-heading)
11969 (setq child-level (funcall outline-level))))))
11970 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11971 ;; any previous siblings are undone, it's blocked
11972 (save-excursion
11973 (org-back-to-heading t)
11974 (let* ((pos (point))
11975 (parent-pos (and (org-up-heading-safe) (point))))
11976 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11977 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11978 (forward-line 1)
11979 (re-search-forward org-not-done-heading-regexp pos t))
11980 (setq org-block-entry-blocking (match-string 0))
11981 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11982 ;; Search further up the hierarchy, to see if an ancestor is blocked
11983 (while t
11984 (goto-char parent-pos)
11985 (if (not (looking-at org-not-done-heading-regexp))
11986 (throw 'dont-block t)) ; do not block, parent is not a TODO
11987 (setq pos (point))
11988 (setq parent-pos (and (org-up-heading-safe) (point)))
11989 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11990 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11991 (forward-line 1)
11992 (re-search-forward org-not-done-heading-regexp pos t)
11993 (setq org-block-entry-blocking (org-get-heading)))
11994 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11996 (defcustom org-track-ordered-property-with-tag nil
11997 "Should the ORDERED property also be shown as a tag?
11998 The ORDERED property decides if an entry should require subtasks to be
11999 completed in sequence. Since a property is not very visible, setting
12000 this option means that toggling the ORDERED property with the command
12001 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12002 not relevant for the behavior, but it makes things more visible.
12004 Note that toggling the tag with tags commands will not change the property
12005 and therefore not influence behavior!
12007 This can be t, meaning the tag ORDERED should be used, It can also be a
12008 string to select a different tag for this task."
12009 :group 'org-todo
12010 :type '(choice
12011 (const :tag "No tracking" nil)
12012 (const :tag "Track with ORDERED tag" t)
12013 (string :tag "Use other tag")))
12015 (defun org-toggle-ordered-property ()
12016 "Toggle the ORDERED property of the current entry.
12017 For better visibility, you can track the value of this property with a tag.
12018 See variable `org-track-ordered-property-with-tag'."
12019 (interactive)
12020 (let* ((t1 org-track-ordered-property-with-tag)
12021 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12022 (save-excursion
12023 (org-back-to-heading)
12024 (if (org-entry-get nil "ORDERED")
12025 (progn
12026 (org-delete-property "ORDERED")
12027 (and tag (org-toggle-tag tag 'off))
12028 (message "Subtasks can be completed in arbitrary order"))
12029 (org-entry-put nil "ORDERED" "t")
12030 (and tag (org-toggle-tag tag 'on))
12031 (message "Subtasks must be completed in sequence")))))
12033 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12034 (defun org-block-todo-from-checkboxes (change-plist)
12035 "Block turning an entry into a TODO, using checkboxes.
12036 This checks whether the current task should be blocked from state
12037 changes because there are unchecked boxes in this entry."
12038 (if (not org-enforce-todo-checkbox-dependencies)
12039 t ; if locally turned off don't block
12040 (catch 'dont-block
12041 ;; If this is not a todo state change, or if this entry is already DONE,
12042 ;; do not block
12043 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12044 (member (plist-get change-plist :from)
12045 (cons 'done org-done-keywords))
12046 (member (plist-get change-plist :to)
12047 (cons 'todo org-not-done-keywords))
12048 (not (plist-get change-plist :to)))
12049 (throw 'dont-block t))
12050 ;; If this task has checkboxes that are not checked, it's blocked
12051 (save-excursion
12052 (org-back-to-heading t)
12053 (let ((beg (point)) end)
12054 (outline-next-heading)
12055 (setq end (point))
12056 (goto-char beg)
12057 (if (org-list-search-forward
12058 (concat (org-item-beginning-re)
12059 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12060 "\\[[- ]\\]")
12061 end t)
12062 (progn
12063 (if (boundp 'org-blocked-by-checkboxes)
12064 (setq org-blocked-by-checkboxes t))
12065 (throw 'dont-block nil)))))
12066 t))) ; do not block
12068 (defun org-entry-blocked-p ()
12069 "Is the current entry blocked?"
12070 (org-with-buffer-modified-unmodified
12071 (if (org-entry-get nil "NOBLOCKING")
12072 nil ;; Never block this entry
12073 (not
12074 (run-hook-with-args-until-failure
12075 'org-blocker-hook
12076 (list :type 'todo-state-change
12077 :position (point)
12078 :from 'todo
12079 :to 'done))))))
12081 (defun org-update-statistics-cookies (all)
12082 "Update the statistics cookie, either from TODO or from checkboxes.
12083 This should be called with the cursor in a line with a statistics cookie."
12084 (interactive "P")
12085 (if all
12086 (progn
12087 (org-update-checkbox-count 'all)
12088 (org-map-entries 'org-update-parent-todo-statistics))
12089 (if (not (org-at-heading-p))
12090 (org-update-checkbox-count)
12091 (let ((pos (point-marker))
12092 end l1 l2)
12093 (ignore-errors (org-back-to-heading t))
12094 (if (not (org-at-heading-p))
12095 (org-update-checkbox-count)
12096 (setq l1 (org-outline-level))
12097 (setq end (save-excursion
12098 (outline-next-heading)
12099 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12100 (point)))
12101 (if (and (save-excursion
12102 (re-search-forward
12103 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12104 (not (save-excursion (re-search-forward
12105 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12106 (org-update-checkbox-count)
12107 (if (and l2 (> l2 l1))
12108 (progn
12109 (goto-char end)
12110 (org-update-parent-todo-statistics))
12111 (goto-char pos)
12112 (beginning-of-line 1)
12113 (while (re-search-forward
12114 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12115 (point-at-eol) t)
12116 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12117 (goto-char pos)
12118 (move-marker pos nil)))))
12120 (defvar org-entry-property-inherited-from) ;; defined below
12121 (defun org-update-parent-todo-statistics ()
12122 "Update any statistics cookie in the parent of the current headline.
12123 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12124 the entire subtree and this will travel up the hierarchy and update
12125 statistics everywhere."
12126 (let* ((prop (save-excursion (org-up-heading-safe)
12127 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12128 (recursive (or (not org-hierarchical-todo-statistics)
12129 (and prop (string-match "\\<recursive\\>" prop))))
12130 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12132 (first t)
12133 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12134 level ltoggle l1 new ndel
12135 (cnt-all 0) (cnt-done 0) is-percent kwd
12136 checkbox-beg ov ovs ove cookie-present)
12137 (catch 'exit
12138 (save-excursion
12139 (beginning-of-line 1)
12140 (setq ltoggle (funcall outline-level))
12141 ;; Three situations are to consider:
12143 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12144 ;; to the top-level ancestor on the headline;
12146 ;; 2. If parent has "recursive" property, repeat up to the
12147 ;; headline setting that property, taking inheritance into
12148 ;; account;
12150 ;; 3. Else, move up to direct parent and proceed only once.
12151 (while (and (setq level (org-up-heading-safe))
12152 (or recursive first)
12153 (>= (point) lim))
12154 (setq first nil cookie-present nil)
12155 (unless (and level
12156 (not (string-match
12157 "\\<checkbox\\>"
12158 (downcase (or (org-entry-get nil "COOKIE_DATA")
12159 "")))))
12160 (throw 'exit nil))
12161 (while (re-search-forward box-re (point-at-eol) t)
12162 (setq cnt-all 0 cnt-done 0 cookie-present t)
12163 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12164 (save-match-data
12165 (unless (outline-next-heading) (throw 'exit nil))
12166 (while (and (looking-at org-complex-heading-regexp)
12167 (> (setq l1 (length (match-string 1))) level))
12168 (setq kwd (and (or recursive (= l1 ltoggle))
12169 (match-string 2)))
12170 (if (or (eq org-provide-todo-statistics 'all-headlines)
12171 (and (listp org-provide-todo-statistics)
12172 (or (member kwd org-provide-todo-statistics)
12173 (member kwd org-done-keywords))))
12174 (setq cnt-all (1+ cnt-all))
12175 (if (eq org-provide-todo-statistics t)
12176 (and kwd (setq cnt-all (1+ cnt-all)))))
12177 (and (member kwd org-done-keywords)
12178 (setq cnt-done (1+ cnt-done)))
12179 (outline-next-heading)))
12180 (setq new
12181 (if is-percent
12182 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12183 (format "[%d/%d]" cnt-done cnt-all))
12184 ndel (- (match-end 0) checkbox-beg))
12185 ;; handle overlays when updating cookie from column view
12186 (when (setq ov (car (overlays-at checkbox-beg)))
12187 (setq ovs (overlay-start ov) ove (overlay-end ov))
12188 (delete-overlay ov))
12189 (goto-char checkbox-beg)
12190 (insert new)
12191 (delete-region (point) (+ (point) ndel))
12192 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12193 (when ov (move-overlay ov ovs ove)))
12194 (when cookie-present
12195 (run-hook-with-args 'org-after-todo-statistics-hook
12196 cnt-done (- cnt-all cnt-done))))))
12197 (run-hooks 'org-todo-statistics-hook)))
12199 (defvar org-after-todo-statistics-hook nil
12200 "Hook that is called after a TODO statistics cookie has been updated.
12201 Each function is called with two arguments: the number of not-done entries
12202 and the number of done entries.
12204 For example, the following function, when added to this hook, will switch
12205 an entry to DONE when all children are done, and back to TODO when new
12206 entries are set to a TODO status. Note that this hook is only called
12207 when there is a statistics cookie in the headline!
12209 (defun org-summary-todo (n-done n-not-done)
12210 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12211 (let (org-log-done org-log-states) ; turn off logging
12212 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12215 (defvar org-todo-statistics-hook nil
12216 "Hook that is run whenever Org thinks TODO statistics should be updated.
12217 This hook runs even if there is no statistics cookie present, in which case
12218 `org-after-todo-statistics-hook' would not run.")
12220 (defun org-todo-trigger-tag-changes (state)
12221 "Apply the changes defined in `org-todo-state-tags-triggers'."
12222 (let ((l org-todo-state-tags-triggers)
12223 changes)
12224 (when (or (not state) (equal state ""))
12225 (setq changes (append changes (cdr (assoc "" l)))))
12226 (when (and (stringp state) (> (length state) 0))
12227 (setq changes (append changes (cdr (assoc state l)))))
12228 (when (member state org-not-done-keywords)
12229 (setq changes (append changes (cdr (assoc 'todo l)))))
12230 (when (member state org-done-keywords)
12231 (setq changes (append changes (cdr (assoc 'done l)))))
12232 (dolist (c changes)
12233 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12235 (defun org-local-logging (value)
12236 "Get logging settings from a property VALUE."
12237 (let* (words w a)
12238 ;; directly set the variables, they are already local.
12239 (setq org-log-done nil
12240 org-log-repeat nil
12241 org-todo-log-states nil)
12242 (setq words (org-split-string value))
12243 (while (setq w (pop words))
12244 (cond
12245 ((setq a (assoc w org-startup-options))
12246 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12247 (set (nth 1 a) (nth 2 a))))
12248 ((setq a (org-extract-log-state-settings w))
12249 (and (member (car a) org-todo-keywords-1)
12250 (push a org-todo-log-states)))))))
12252 (defun org-get-todo-sequence-head (kwd)
12253 "Return the head of the TODO sequence to which KWD belongs.
12254 If KWD is not set, check if there is a text property remembering the
12255 right sequence."
12256 (let (p)
12257 (cond
12258 ((not kwd)
12259 (or (get-text-property (point-at-bol) 'org-todo-head)
12260 (progn
12261 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12262 nil (point-at-eol)))
12263 (get-text-property p 'org-todo-head))))
12264 ((not (member kwd org-todo-keywords-1))
12265 (car org-todo-keywords-1))
12266 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12268 (defun org-fast-todo-selection ()
12269 "Fast TODO keyword selection with single keys.
12270 Returns the new TODO keyword, or nil if no state change should occur."
12271 (let* ((fulltable org-todo-key-alist)
12272 (done-keywords org-done-keywords) ;; needed for the faces.
12273 (maxlen (apply 'max (mapcar
12274 (lambda (x)
12275 (if (stringp (car x)) (string-width (car x)) 0))
12276 fulltable)))
12277 (expert nil)
12278 (fwidth (+ maxlen 3 1 3))
12279 (ncol (/ (- (window-width) 4) fwidth))
12280 tg cnt e c tbl
12281 groups ingroup)
12282 (save-excursion
12283 (save-window-excursion
12284 (if expert
12285 (set-buffer (get-buffer-create " *Org todo*"))
12286 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12287 (erase-buffer)
12288 (org-set-local 'org-done-keywords done-keywords)
12289 (setq tbl fulltable cnt 0)
12290 (while (setq e (pop tbl))
12291 (cond
12292 ((equal e '(:startgroup))
12293 (push '() groups) (setq ingroup t)
12294 (when (not (= cnt 0))
12295 (setq cnt 0)
12296 (insert "\n"))
12297 (insert "{ "))
12298 ((equal e '(:endgroup))
12299 (setq ingroup nil cnt 0)
12300 (insert "}\n"))
12301 ((equal e '(:newline))
12302 (when (not (= cnt 0))
12303 (setq cnt 0)
12304 (insert "\n")
12305 (setq e (car tbl))
12306 (while (equal (car tbl) '(:newline))
12307 (insert "\n")
12308 (setq tbl (cdr tbl)))))
12310 (setq tg (car e) c (cdr e))
12311 (if ingroup (push tg (car groups)))
12312 (setq tg (org-add-props tg nil 'face
12313 (org-get-todo-face tg)))
12314 (if (and (= cnt 0) (not ingroup)) (insert " "))
12315 (insert "[" c "] " tg (make-string
12316 (- fwidth 4 (length tg)) ?\ ))
12317 (when (= (setq cnt (1+ cnt)) ncol)
12318 (insert "\n")
12319 (if ingroup (insert " "))
12320 (setq cnt 0)))))
12321 (insert "\n")
12322 (goto-char (point-min))
12323 (if (not expert) (org-fit-window-to-buffer))
12324 (message "[a-z..]:Set [SPC]:clear")
12325 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12326 (cond
12327 ((or (= c ?\C-g)
12328 (and (= c ?q) (not (rassoc c fulltable))))
12329 (setq quit-flag t))
12330 ((= c ?\ ) nil)
12331 ((setq e (rassoc c fulltable) tg (car e))
12333 (t (setq quit-flag t)))))))
12335 (defun org-entry-is-todo-p ()
12336 (member (org-get-todo-state) org-not-done-keywords))
12338 (defun org-entry-is-done-p ()
12339 (member (org-get-todo-state) org-done-keywords))
12341 (defun org-get-todo-state ()
12342 (save-excursion
12343 (org-back-to-heading t)
12344 (and (looking-at org-todo-line-regexp)
12345 (match-end 2)
12346 (match-string 2))))
12348 (defun org-at-date-range-p (&optional inactive-ok)
12349 "Is the cursor inside a date range?"
12350 (interactive)
12351 (save-excursion
12352 (catch 'exit
12353 (let ((pos (point)))
12354 (skip-chars-backward "^[<\r\n")
12355 (skip-chars-backward "<[")
12356 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12357 (>= (match-end 0) pos)
12358 (throw 'exit t))
12359 (skip-chars-backward "^<[\r\n")
12360 (skip-chars-backward "<[")
12361 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12362 (>= (match-end 0) pos)
12363 (throw 'exit t)))
12364 nil)))
12366 (defun org-get-repeat (&optional tagline)
12367 "Check if there is a deadline/schedule with repeater in this entry."
12368 (save-match-data
12369 (save-excursion
12370 (org-back-to-heading t)
12371 (and (re-search-forward (if tagline
12372 (concat tagline "\\s-*" org-repeat-re)
12373 org-repeat-re)
12374 (org-entry-end-position) t)
12375 (match-string-no-properties 1)))))
12377 (defvar org-last-changed-timestamp)
12378 (defvar org-last-inserted-timestamp)
12379 (defvar org-log-post-message)
12380 (defvar org-log-note-purpose)
12381 (defvar org-log-note-how)
12382 (defvar org-log-note-extra)
12383 (defun org-auto-repeat-maybe (done-word)
12384 "Check if the current headline contains a repeated deadline/schedule.
12385 If yes, set TODO state back to what it was and change the base date
12386 of repeating deadline/scheduled time stamps to new date.
12387 This function is run automatically after each state change to a DONE state."
12388 ;; last-state is dynamically scoped into this function
12389 (let* ((repeat (org-get-repeat))
12390 (aa (assoc org-last-state org-todo-kwd-alist))
12391 (interpret (nth 1 aa))
12392 (head (nth 2 aa))
12393 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12394 (msg "Entry repeats: ")
12395 (org-log-done nil)
12396 (org-todo-log-states nil)
12397 re type n what ts time to-state)
12398 (when repeat
12399 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12400 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12401 org-todo-repeat-to-state))
12402 (unless (and to-state (member to-state org-todo-keywords-1))
12403 (setq to-state (if (eq interpret 'type) org-last-state head)))
12404 (org-todo to-state)
12405 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12406 (org-entry-put nil "LAST_REPEAT" (format-time-string
12407 (org-time-stamp-format t t))))
12408 (when org-log-repeat
12409 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12410 (memq 'org-add-log-note post-command-hook))
12411 ;; OK, we are already setup for some record
12412 (if (eq org-log-repeat 'note)
12413 ;; make sure we take a note, not only a time stamp
12414 (setq org-log-note-how 'note))
12415 ;; Set up for taking a record
12416 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12417 org-last-state
12418 'findpos org-log-repeat)))
12419 (org-back-to-heading t)
12420 (org-add-planning-info nil nil 'closed)
12421 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12422 org-deadline-time-regexp "\\)\\|\\("
12423 org-ts-regexp "\\)"))
12424 (while (re-search-forward
12425 re (save-excursion (outline-next-heading) (point)) t)
12426 (setq type (if (match-end 1) org-scheduled-string
12427 (if (match-end 3) org-deadline-string "Plain:"))
12428 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12429 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12430 (setq n (string-to-number (match-string 2 ts))
12431 what (match-string 3 ts))
12432 (if (equal what "w") (setq n (* n 7) what "d"))
12433 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12434 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12435 ;; Preparation, see if we need to modify the start date for the change
12436 (when (match-end 1)
12437 (setq time (save-match-data (org-time-string-to-time ts)))
12438 (cond
12439 ((equal (match-string 1 ts) ".")
12440 ;; Shift starting date to today
12441 (org-timestamp-change
12442 (- (org-today) (time-to-days time))
12443 'day))
12444 ((equal (match-string 1 ts) "+")
12445 (let ((nshiftmax 10) (nshift 0))
12446 (while (or (= nshift 0)
12447 (<= (time-to-days time)
12448 (time-to-days (current-time))))
12449 (when (= (incf nshift) nshiftmax)
12450 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12451 (error "Abort")))
12452 (org-timestamp-change n (cdr (assoc what whata)))
12453 (org-at-timestamp-p t)
12454 (setq ts (match-string 1))
12455 (setq time (save-match-data (org-time-string-to-time ts)))))
12456 (org-timestamp-change (- n) (cdr (assoc what whata)))
12457 ;; rematch, so that we have everything in place for the real shift
12458 (org-at-timestamp-p t)
12459 (setq ts (match-string 1))
12460 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12461 (org-timestamp-change n (cdr (assoc what whata)))
12462 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12463 (setq org-log-post-message msg)
12464 (message "%s" msg))))
12466 (defun org-show-todo-tree (arg)
12467 "Make a compact tree which shows all headlines marked with TODO.
12468 The tree will show the lines where the regexp matches, and all higher
12469 headlines above the match.
12470 With a \\[universal-argument] prefix, prompt for a regexp to match.
12471 With a numeric prefix N, construct a sparse tree for the Nth element
12472 of `org-todo-keywords-1'."
12473 (interactive "P")
12474 (let ((case-fold-search nil)
12475 (kwd-re
12476 (cond ((null arg) org-not-done-regexp)
12477 ((equal arg '(4))
12478 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12479 (mapcar 'list org-todo-keywords-1))))
12480 (concat "\\("
12481 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12482 "\\)\\>")))
12483 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12484 (regexp-quote (nth (1- (prefix-numeric-value arg))
12485 org-todo-keywords-1)))
12486 (t (error "Invalid prefix argument: %s" arg)))))
12487 (message "%d TODO entries found"
12488 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12490 (defun org-deadline (&optional remove time)
12491 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12492 With argument REMOVE, remove any deadline from the item.
12493 With argument TIME, set the deadline at the corresponding date. TIME
12494 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12495 (interactive "P")
12496 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12497 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12498 'region-start-level 'region))
12499 org-loop-over-headlines-in-active-region)
12500 (org-map-entries
12501 `(org-deadline ',remove ,time)
12502 org-loop-over-headlines-in-active-region
12503 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12504 (let* ((old-date (org-entry-get nil "DEADLINE"))
12505 (repeater (and old-date
12506 (string-match
12507 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12508 old-date)
12509 (match-string 1 old-date))))
12510 (if remove
12511 (progn
12512 (when (and old-date org-log-redeadline)
12513 (org-add-log-setup 'deldeadline nil old-date 'findpos
12514 org-log-redeadline))
12515 (org-remove-timestamp-with-keyword org-deadline-string)
12516 (message "Item no longer has a deadline."))
12517 (org-add-planning-info 'deadline time 'closed)
12518 (when (and old-date org-log-redeadline
12519 (not (equal old-date
12520 (substring org-last-inserted-timestamp 1 -1))))
12521 (org-add-log-setup 'redeadline nil old-date 'findpos
12522 org-log-redeadline))
12523 (when repeater
12524 (save-excursion
12525 (org-back-to-heading t)
12526 (when (re-search-forward (concat org-deadline-string " "
12527 org-last-inserted-timestamp)
12528 (save-excursion
12529 (outline-next-heading) (point)) t)
12530 (goto-char (1- (match-end 0)))
12531 (insert " " repeater)
12532 (setq org-last-inserted-timestamp
12533 (concat (substring org-last-inserted-timestamp 0 -1)
12534 " " repeater
12535 (substring org-last-inserted-timestamp -1))))))
12536 (message "Deadline on %s" org-last-inserted-timestamp)))))
12538 (defun org-schedule (&optional remove time)
12539 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12540 With argument REMOVE, remove any scheduling date from the item.
12541 With argument TIME, scheduled at the corresponding date. TIME can
12542 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12543 (interactive "P")
12544 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12545 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12546 'region-start-level 'region))
12547 org-loop-over-headlines-in-active-region)
12548 (org-map-entries
12549 `(org-schedule ',remove ,time)
12550 org-loop-over-headlines-in-active-region
12551 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12552 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12553 (repeater (and old-date
12554 (string-match
12555 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12556 old-date)
12557 (match-string 1 old-date))))
12558 (if remove
12559 (progn
12560 (when (and old-date org-log-reschedule)
12561 (org-add-log-setup 'delschedule nil old-date 'findpos
12562 org-log-reschedule))
12563 (org-remove-timestamp-with-keyword org-scheduled-string)
12564 (message "Item is no longer scheduled."))
12565 (org-add-planning-info 'scheduled time 'closed)
12566 (when (and old-date org-log-reschedule
12567 (not (equal old-date
12568 (substring org-last-inserted-timestamp 1 -1))))
12569 (org-add-log-setup 'reschedule nil old-date 'findpos
12570 org-log-reschedule))
12571 (when repeater
12572 (save-excursion
12573 (org-back-to-heading t)
12574 (when (re-search-forward (concat org-scheduled-string " "
12575 org-last-inserted-timestamp)
12576 (save-excursion
12577 (outline-next-heading) (point)) t)
12578 (goto-char (1- (match-end 0)))
12579 (insert " " repeater)
12580 (setq org-last-inserted-timestamp
12581 (concat (substring org-last-inserted-timestamp 0 -1)
12582 " " repeater
12583 (substring org-last-inserted-timestamp -1))))))
12584 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12586 (defun org-get-scheduled-time (pom &optional inherit)
12587 "Get the scheduled time as a time tuple, of a format suitable
12588 for calling org-schedule with, or if there is no scheduling,
12589 returns nil."
12590 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12591 (when time
12592 (apply 'encode-time (org-parse-time-string time)))))
12594 (defun org-get-deadline-time (pom &optional inherit)
12595 "Get the deadline as a time tuple, of a format suitable for
12596 calling org-deadline with, or if there is no scheduling, returns
12597 nil."
12598 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12599 (when time
12600 (apply 'encode-time (org-parse-time-string time)))))
12602 (defun org-remove-timestamp-with-keyword (keyword)
12603 "Remove all time stamps with KEYWORD in the current entry."
12604 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12605 beg)
12606 (save-excursion
12607 (org-back-to-heading t)
12608 (setq beg (point))
12609 (outline-next-heading)
12610 (while (re-search-backward re beg t)
12611 (replace-match "")
12612 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12613 (equal (char-before) ?\ ))
12614 (backward-delete-char 1)
12615 (if (string-match "^[ \t]*$" (buffer-substring
12616 (point-at-bol) (point-at-eol)))
12617 (delete-region (point-at-bol)
12618 (min (point-max) (1+ (point-at-eol))))))))))
12620 (defun org-add-planning-info (what &optional time &rest remove)
12621 "Insert new timestamp with keyword in the line directly after the headline.
12622 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12623 If non is given, the user is prompted for a date.
12624 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12625 be removed."
12626 (interactive)
12627 (let (org-time-was-given org-end-time-was-given ts
12628 end default-time default-input)
12630 (catch 'exit
12631 (when (and (memq what '(scheduled deadline))
12632 (or (not time)
12633 (and (stringp time)
12634 (string-match "^[-+]+[0-9]" time))))
12635 ;; Try to get a default date/time from existing timestamp
12636 (save-excursion
12637 (org-back-to-heading t)
12638 (setq end (save-excursion (outline-next-heading) (point)))
12639 (when (re-search-forward (if (eq what 'scheduled)
12640 org-scheduled-time-regexp
12641 org-deadline-time-regexp)
12642 end t)
12643 (setq ts (match-string 1)
12644 default-time
12645 (apply 'encode-time (org-parse-time-string ts))
12646 default-input (and ts (org-get-compact-tod ts))))))
12647 (when what
12648 (setq time
12649 (if (stringp time)
12650 ;; This is a string (relative or absolute), set proper date
12651 (apply 'encode-time
12652 (org-read-date-analyze
12653 time default-time (decode-time default-time)))
12654 ;; If necessary, get the time from the user
12655 (or time (org-read-date nil 'to-time nil nil
12656 default-time default-input)))))
12658 (when (and org-insert-labeled-timestamps-at-point
12659 (member what '(scheduled deadline)))
12660 (insert
12661 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12662 (org-insert-time-stamp time org-time-was-given
12663 nil nil nil (list org-end-time-was-given))
12664 (setq what nil))
12665 (save-excursion
12666 (save-restriction
12667 (let (col list elt ts buffer-invisibility-spec)
12668 (org-back-to-heading t)
12669 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12670 (goto-char (match-end 1))
12671 (setq col (current-column))
12672 (goto-char (match-end 0))
12673 (if (eobp) (insert "\n") (forward-char 1))
12674 (when (and (not what)
12675 (not (looking-at
12676 (concat "[ \t]*"
12677 org-keyword-time-not-clock-regexp))))
12678 ;; Nothing to add, nothing to remove...... :-)
12679 (throw 'exit nil))
12680 (if (and (not (looking-at org-outline-regexp))
12681 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12682 "[^\r\n]*"))
12683 (not (equal (match-string 1) org-clock-string)))
12684 (narrow-to-region (match-beginning 0) (match-end 0))
12685 (insert-before-markers "\n")
12686 (backward-char 1)
12687 (narrow-to-region (point) (point))
12688 (and org-adapt-indentation (org-indent-to-column col)))
12689 ;; Check if we have to remove something.
12690 (setq list (cons what remove))
12691 (while list
12692 (setq elt (pop list))
12693 (when (or (and (eq elt 'scheduled)
12694 (re-search-forward org-scheduled-time-regexp nil t))
12695 (and (eq elt 'deadline)
12696 (re-search-forward org-deadline-time-regexp nil t))
12697 (and (eq elt 'closed)
12698 (re-search-forward org-closed-time-regexp nil t)))
12699 (replace-match "")
12700 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12701 (and (looking-at "[ \t]+") (replace-match ""))
12702 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12703 (when what
12704 (insert
12705 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12706 (cond ((eq what 'scheduled) org-scheduled-string)
12707 ((eq what 'deadline) org-deadline-string)
12708 ((eq what 'closed) org-closed-string))
12709 " ")
12710 (setq ts (org-insert-time-stamp
12711 time
12712 (or org-time-was-given
12713 (and (eq what 'closed) org-log-done-with-time))
12714 (eq what 'closed)
12715 nil nil (list org-end-time-was-given)))
12716 (insert
12717 (if (not (or (bolp) (eq (char-before) ?\ )
12718 (memq (char-after) '(32 10))
12719 (eobp))) " " ""))
12720 (end-of-line 1))
12721 (goto-char (point-min))
12722 (widen)
12723 (if (and (looking-at "[ \t]*\n")
12724 (equal (char-before) ?\n))
12725 (delete-region (1- (point)) (point-at-eol)))
12726 ts))))))
12728 (defvar org-log-note-marker (make-marker))
12729 (defvar org-log-note-purpose nil)
12730 (defvar org-log-note-state nil)
12731 (defvar org-log-note-previous-state nil)
12732 (defvar org-log-note-how nil)
12733 (defvar org-log-note-extra nil)
12734 (defvar org-log-note-window-configuration nil)
12735 (defvar org-log-note-return-to (make-marker))
12736 (defvar org-log-note-effective-time nil
12737 "Remembered current time so that dynamically scoped
12738 `org-extend-today-until' affects tha timestamps in state change
12739 log")
12741 (defvar org-log-post-message nil
12742 "Message to be displayed after a log note has been stored.
12743 The auto-repeater uses this.")
12745 (defun org-add-note ()
12746 "Add a note to the current entry.
12747 This is done in the same way as adding a state change note."
12748 (interactive)
12749 (org-add-log-setup 'note nil nil 'findpos nil))
12751 (defvar org-property-end-re)
12752 (defun org-add-log-setup (&optional purpose state prev-state
12753 findpos how extra)
12754 "Set up the post command hook to take a note.
12755 If this is about to TODO state change, the new state is expected in STATE.
12756 When FINDPOS is non-nil, find the correct position for the note in
12757 the current entry. If not, assume that it can be inserted at point.
12758 HOW is an indicator what kind of note should be created.
12759 EXTRA is additional text that will be inserted into the notes buffer."
12760 (let* ((org-log-into-drawer (org-log-into-drawer))
12761 (drawer (cond ((stringp org-log-into-drawer)
12762 org-log-into-drawer)
12763 (org-log-into-drawer "LOGBOOK"))))
12764 (save-restriction
12765 (save-excursion
12766 (when findpos
12767 (org-back-to-heading t)
12768 (narrow-to-region (point) (save-excursion
12769 (outline-next-heading) (point)))
12770 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12771 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12772 "[^\r\n]*\\)?"))
12773 (goto-char (match-end 0))
12774 (cond
12775 (drawer
12776 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12777 nil t)
12778 (progn
12779 (goto-char (match-end 0))
12780 (or org-log-states-order-reversed
12781 (and (re-search-forward org-property-end-re nil t)
12782 (goto-char (1- (match-beginning 0))))))
12783 (insert "\n:" drawer ":\n:END:")
12784 (beginning-of-line 0)
12785 (org-indent-line)
12786 (beginning-of-line 2)
12787 (org-indent-line)
12788 (end-of-line 0)))
12789 ((and org-log-state-notes-insert-after-drawers
12790 (save-excursion
12791 (forward-line) (looking-at org-drawer-regexp)))
12792 (forward-line)
12793 (while (looking-at org-drawer-regexp)
12794 (goto-char (match-end 0))
12795 (re-search-forward org-property-end-re (point-max) t)
12796 (forward-line))
12797 (forward-line -1)))
12798 (unless org-log-states-order-reversed
12799 (and (= (char-after) ?\n) (forward-char 1))
12800 (org-skip-over-state-notes)
12801 (skip-chars-backward " \t\n\r")))
12802 (move-marker org-log-note-marker (point))
12803 (setq org-log-note-purpose purpose
12804 org-log-note-state state
12805 org-log-note-previous-state prev-state
12806 org-log-note-how how
12807 org-log-note-extra extra
12808 org-log-note-effective-time (org-current-effective-time))
12809 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12811 (defun org-skip-over-state-notes ()
12812 "Skip past the list of State notes in an entry."
12813 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12814 (when (ignore-errors (goto-char (org-in-item-p)))
12815 (let* ((struct (org-list-struct))
12816 (prevs (org-list-prevs-alist struct)))
12817 (while (looking-at "[ \t]*- State")
12818 (goto-char (or (org-list-get-next-item (point) struct prevs)
12819 (org-list-get-item-end (point) struct)))))))
12821 (defun org-add-log-note (&optional purpose)
12822 "Pop up a window for taking a note, and add this note later at point."
12823 (remove-hook 'post-command-hook 'org-add-log-note)
12824 (setq org-log-note-window-configuration (current-window-configuration))
12825 (delete-other-windows)
12826 (move-marker org-log-note-return-to (point))
12827 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12828 (goto-char org-log-note-marker)
12829 (org-switch-to-buffer-other-window "*Org Note*")
12830 (erase-buffer)
12831 (if (memq org-log-note-how '(time state))
12832 (let (current-prefix-arg) (org-store-log-note))
12833 (let ((org-inhibit-startup t)) (org-mode))
12834 (insert (format "# Insert note for %s.
12835 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12836 (cond
12837 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12838 ((eq org-log-note-purpose 'done) "closed todo item")
12839 ((eq org-log-note-purpose 'state)
12840 (format "state change from \"%s\" to \"%s\""
12841 (or org-log-note-previous-state "")
12842 (or org-log-note-state "")))
12843 ((eq org-log-note-purpose 'reschedule)
12844 "rescheduling")
12845 ((eq org-log-note-purpose 'delschedule)
12846 "no longer scheduled")
12847 ((eq org-log-note-purpose 'redeadline)
12848 "changing deadline")
12849 ((eq org-log-note-purpose 'deldeadline)
12850 "removing deadline")
12851 ((eq org-log-note-purpose 'refile)
12852 "refiling")
12853 ((eq org-log-note-purpose 'note)
12854 "this entry")
12855 (t (error "This should not happen")))))
12856 (if org-log-note-extra (insert org-log-note-extra))
12857 (org-set-local 'org-finish-function 'org-store-log-note)
12858 (run-hooks 'org-log-buffer-setup-hook)))
12860 (defvar org-note-abort nil) ; dynamically scoped
12861 (defun org-store-log-note ()
12862 "Finish taking a log note, and insert it to where it belongs."
12863 (let ((txt (buffer-string)))
12864 (kill-buffer (current-buffer))
12865 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12866 lines ind bul)
12867 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12868 (setq txt (replace-match "" t t txt)))
12869 (if (string-match "\\s-+\\'" txt)
12870 (setq txt (replace-match "" t t txt)))
12871 (setq lines (org-split-string txt "\n"))
12872 (when (and note (string-match "\\S-" note))
12873 (setq note
12874 (org-replace-escapes
12875 note
12876 (list (cons "%u" (user-login-name))
12877 (cons "%U" user-full-name)
12878 (cons "%t" (format-time-string
12879 (org-time-stamp-format 'long 'inactive)
12880 org-log-note-effective-time))
12881 (cons "%T" (format-time-string
12882 (org-time-stamp-format 'long nil)
12883 org-log-note-effective-time))
12884 (cons "%d" (format-time-string
12885 (org-time-stamp-format nil 'inactive)
12886 org-log-note-effective-time))
12887 (cons "%D" (format-time-string
12888 (org-time-stamp-format nil nil)
12889 org-log-note-effective-time))
12890 (cons "%s" (if org-log-note-state
12891 (concat "\"" org-log-note-state "\"")
12892 ""))
12893 (cons "%S" (if org-log-note-previous-state
12894 (concat "\"" org-log-note-previous-state "\"")
12895 "\"\"")))))
12896 (if lines (setq note (concat note " \\\\")))
12897 (push note lines))
12898 (when (or current-prefix-arg org-note-abort)
12899 (when org-log-into-drawer
12900 (org-remove-empty-drawer-at
12901 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12902 org-log-note-marker))
12903 (setq lines nil))
12904 (when lines
12905 (with-current-buffer (marker-buffer org-log-note-marker)
12906 (save-excursion
12907 (goto-char org-log-note-marker)
12908 (move-marker org-log-note-marker nil)
12909 (end-of-line 1)
12910 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12911 (setq ind (save-excursion
12912 (if (ignore-errors (goto-char (org-in-item-p)))
12913 (let ((struct (org-list-struct)))
12914 (org-list-get-ind
12915 (org-list-get-top-point struct) struct))
12916 (skip-chars-backward " \r\t\n")
12917 (cond
12918 ((and (org-at-heading-p)
12919 org-adapt-indentation)
12920 (1+ (org-current-level)))
12921 ((org-at-heading-p) 0)
12922 (t (org-get-indentation))))))
12923 (setq bul (org-list-bullet-string "-"))
12924 (org-indent-line-to ind)
12925 (insert bul (pop lines))
12926 (let ((ind-body (+ (length bul) ind)))
12927 (while lines
12928 (insert "\n")
12929 (org-indent-line-to ind-body)
12930 (insert (pop lines))))
12931 (message "Note stored")
12932 (org-back-to-heading t)
12933 (org-cycle-hide-drawers 'children))))))
12934 (set-window-configuration org-log-note-window-configuration)
12935 (with-current-buffer (marker-buffer org-log-note-return-to)
12936 (goto-char org-log-note-return-to))
12937 (move-marker org-log-note-return-to nil)
12938 (and org-log-post-message (message "%s" org-log-post-message)))
12940 (defun org-remove-empty-drawer-at (drawer pos)
12941 "Remove an empty drawer DRAWER at position POS.
12942 POS may also be a marker."
12943 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12944 (save-excursion
12945 (save-restriction
12946 (widen)
12947 (goto-char pos)
12948 (if (org-in-regexp
12949 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12950 (replace-match ""))))))
12952 (defvar org-ts-type nil)
12953 (defun org-sparse-tree (&optional arg type)
12954 "Create a sparse tree, prompt for the details.
12955 This command can create sparse trees. You first need to select the type
12956 of match used to create the tree:
12958 t Show all TODO entries.
12959 T Show entries with a specific TODO keyword.
12960 m Show entries selected by a tags/property match.
12961 p Enter a property name and its value (both with completion on existing
12962 names/values) and show entries with that property.
12963 r Show entries matching a regular expression (`/' can be used as well).
12964 b Show deadlines and scheduled items before a date.
12965 a Show deadlines and scheduled items after a date.
12966 d Show deadlines due within `org-deadline-warning-days'.
12967 D Show deadlines and scheduled items between a date range."
12968 (interactive "P")
12969 (let (ans kwd value ts-type)
12970 (setq type (or type org-sparse-tree-default-date-type))
12971 (setq org-ts-type type)
12972 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12973 (cond ((eq type 'all) "all timestamps")
12974 ((eq type 'scheduled) "only scheduled")
12975 ((eq type 'deadline) "only deadline")
12976 ((eq type 'active) "only active timestamps")
12977 ((eq type 'inactive) "only inactive timestamps")
12978 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12979 (t "scheduled/deadline")))
12980 (setq ans (read-char-exclusive))
12981 (cond
12982 ((equal ans ?c)
12983 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12984 ((equal ans ?d)
12985 (call-interactively 'org-check-deadlines))
12986 ((equal ans ?b)
12987 (call-interactively 'org-check-before-date))
12988 ((equal ans ?a)
12989 (call-interactively 'org-check-after-date))
12990 ((equal ans ?D)
12991 (call-interactively 'org-check-dates-range))
12992 ((equal ans ?t)
12993 (call-interactively 'org-show-todo-tree))
12994 ((equal ans ?T)
12995 (org-show-todo-tree '(4)))
12996 ((member ans '(?T ?m))
12997 (call-interactively 'org-match-sparse-tree))
12998 ((member ans '(?p ?P))
12999 (setq kwd (org-icompleting-read "Property: "
13000 (mapcar 'list (org-buffer-property-keys))))
13001 (setq value (org-icompleting-read "Value: "
13002 (mapcar 'list (org-property-values kwd))))
13003 (unless (string-match "\\`{.*}\\'" value)
13004 (setq value (concat "\"" value "\"")))
13005 (org-match-sparse-tree arg (concat kwd "=" value)))
13006 ((member ans '(?r ?R ?/))
13007 (call-interactively 'org-occur))
13008 (t (error "No such sparse tree command \"%c\"" ans)))))
13010 (defvar org-occur-highlights nil
13011 "List of overlays used for occur matches.")
13012 (make-variable-buffer-local 'org-occur-highlights)
13013 (defvar org-occur-parameters nil
13014 "Parameters of the active org-occur calls.
13015 This is a list, each call to org-occur pushes as cons cell,
13016 containing the regular expression and the callback, onto the list.
13017 The list can contain several entries if `org-occur' has been called
13018 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13019 will only contain one set of parameters. When the highlights are
13020 removed (for example with `C-c C-c', or with the next edit (depending
13021 on `org-remove-highlights-with-change'), this variable is emptied
13022 as well.")
13023 (make-variable-buffer-local 'org-occur-parameters)
13025 (defun org-occur (regexp &optional keep-previous callback)
13026 "Make a compact tree which shows all matches of REGEXP.
13027 The tree will show the lines where the regexp matches, and all higher
13028 headlines above the match. It will also show the heading after the match,
13029 to make sure editing the matching entry is easy.
13030 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13031 call to `org-occur' will be kept, to allow stacking of calls to this
13032 command.
13033 If CALLBACK is non-nil, it is a function which is called to confirm
13034 that the match should indeed be shown."
13035 (interactive "sRegexp: \nP")
13036 (when (equal regexp "")
13037 (error "Regexp cannot be empty"))
13038 (unless keep-previous
13039 (org-remove-occur-highlights nil nil t))
13040 (push (cons regexp callback) org-occur-parameters)
13041 (let ((cnt 0))
13042 (save-excursion
13043 (goto-char (point-min))
13044 (if (or (not keep-previous) ; do not want to keep
13045 (not org-occur-highlights)) ; no previous matches
13046 ;; hide everything
13047 (org-overview))
13048 (while (re-search-forward regexp nil t)
13049 (when (or (not callback)
13050 (save-match-data (funcall callback)))
13051 (setq cnt (1+ cnt))
13052 (when org-highlight-sparse-tree-matches
13053 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13054 (org-show-context 'occur-tree))))
13055 (when org-remove-highlights-with-change
13056 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13057 nil 'local))
13058 (unless org-sparse-tree-open-archived-trees
13059 (org-hide-archived-subtrees (point-min) (point-max)))
13060 (run-hooks 'org-occur-hook)
13061 (if (org-called-interactively-p 'interactive)
13062 (message "%d match(es) for regexp %s" cnt regexp))
13063 cnt))
13065 (defun org-occur-next-match (&optional n reset)
13066 "Function for `next-error-function' to find sparse tree matches.
13067 N is the number of matches to move, when negative move backwards.
13068 RESET is entirely ignored - this function always goes back to the
13069 starting point when no match is found."
13070 (let* ((limit (if (< n 0) (point-min) (point-max)))
13071 (search-func (if (< n 0)
13072 'previous-single-char-property-change
13073 'next-single-char-property-change))
13074 (n (abs n))
13075 (pos (point))
13077 (catch 'exit
13078 (while (setq p1 (funcall search-func (point) 'org-type))
13079 (when (equal p1 limit)
13080 (goto-char pos)
13081 (error "No more matches"))
13082 (when (equal (get-char-property p1 'org-type) 'org-occur)
13083 (setq n (1- n))
13084 (when (= n 0)
13085 (goto-char p1)
13086 (throw 'exit (point))))
13087 (goto-char p1))
13088 (goto-char p1)
13089 (error "No more matches"))))
13091 (defun org-show-context (&optional key)
13092 "Make sure point and context are visible.
13093 How much context is shown depends upon the variables
13094 `org-show-hierarchy-above', `org-show-following-heading',
13095 `org-show-entry-below' and `org-show-siblings'."
13096 (let ((heading-p (org-at-heading-p t))
13097 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13098 (following-p (org-get-alist-option org-show-following-heading key))
13099 (entry-p (org-get-alist-option org-show-entry-below key))
13100 (siblings-p (org-get-alist-option org-show-siblings key)))
13101 (catch 'exit
13102 ;; Show heading or entry text
13103 (if (and heading-p (not entry-p))
13104 (org-flag-heading nil) ; only show the heading
13105 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13106 (org-show-hidden-entry))) ; show entire entry
13107 (when following-p
13108 ;; Show next sibling, or heading below text
13109 (save-excursion
13110 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13111 (org-flag-heading nil))))
13112 (when siblings-p (org-show-siblings))
13113 (when hierarchy-p
13114 ;; show all higher headings, possibly with siblings
13115 (save-excursion
13116 (while (and (condition-case nil
13117 (progn (org-up-heading-all 1) t)
13118 (error nil))
13119 (not (bobp)))
13120 (org-flag-heading nil)
13121 (when siblings-p (org-show-siblings))))))))
13123 (defvar org-reveal-start-hook nil
13124 "Hook run before revealing a location.")
13126 (defun org-reveal (&optional siblings)
13127 "Show current entry, hierarchy above it, and the following headline.
13128 This can be used to show a consistent set of context around locations
13129 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13130 not t for the search context.
13132 With optional argument SIBLINGS, on each level of the hierarchy all
13133 siblings are shown. This repairs the tree structure to what it would
13134 look like when opened with hierarchical calls to `org-cycle'.
13135 With double optional argument \\[universal-argument] \\[universal-argument], \
13136 go to the parent and show the
13137 entire tree."
13138 (interactive "P")
13139 (run-hooks 'org-reveal-start-hook)
13140 (let ((org-show-hierarchy-above t)
13141 (org-show-following-heading t)
13142 (org-show-siblings (if siblings t org-show-siblings)))
13143 (org-show-context nil))
13144 (when (equal siblings '(16))
13145 (save-excursion
13146 (when (org-up-heading-safe)
13147 (org-show-subtree)
13148 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13150 (defun org-highlight-new-match (beg end)
13151 "Highlight from BEG to END and mark the highlight is an occur headline."
13152 (let ((ov (make-overlay beg end)))
13153 (overlay-put ov 'face 'secondary-selection)
13154 (overlay-put ov 'org-type 'org-occur)
13155 (push ov org-occur-highlights)))
13157 (defun org-remove-occur-highlights (&optional beg end noremove)
13158 "Remove the occur highlights from the buffer.
13159 BEG and END are ignored. If NOREMOVE is nil, remove this function
13160 from the `before-change-functions' in the current buffer."
13161 (interactive)
13162 (unless org-inhibit-highlight-removal
13163 (mapc 'delete-overlay org-occur-highlights)
13164 (setq org-occur-highlights nil)
13165 (setq org-occur-parameters nil)
13166 (unless noremove
13167 (remove-hook 'before-change-functions
13168 'org-remove-occur-highlights 'local))))
13170 ;;;; Priorities
13172 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13173 "Regular expression matching the priority indicator.")
13175 (defvar org-remove-priority-next-time nil)
13177 (defun org-priority-up ()
13178 "Increase the priority of the current item."
13179 (interactive)
13180 (org-priority 'up))
13182 (defun org-priority-down ()
13183 "Decrease the priority of the current item."
13184 (interactive)
13185 (org-priority 'down))
13187 (defun org-priority (&optional action show)
13188 "Change the priority of an item.
13189 ACTION can be `set', `up', `down', or a character."
13190 (interactive "P")
13191 (if (equal action '(4))
13192 (org-show-priority)
13193 (unless org-enable-priority-commands
13194 (error "Priority commands are disabled"))
13195 (setq action (or action 'set))
13196 (let (current new news have remove)
13197 (save-excursion
13198 (org-back-to-heading t)
13199 (if (looking-at org-priority-regexp)
13200 (setq current (string-to-char (match-string 2))
13201 have t))
13202 (cond
13203 ((eq action 'remove)
13204 (setq remove t new ?\ ))
13205 ((or (eq action 'set)
13206 (if (featurep 'xemacs) (characterp action) (integerp action)))
13207 (if (not (eq action 'set))
13208 (setq new action)
13209 (message "Priority %c-%c, SPC to remove: "
13210 org-highest-priority org-lowest-priority)
13211 (save-match-data
13212 (setq new (read-char-exclusive))))
13213 (if (and (= (upcase org-highest-priority) org-highest-priority)
13214 (= (upcase org-lowest-priority) org-lowest-priority))
13215 (setq new (upcase new)))
13216 (cond ((equal new ?\ ) (setq remove t))
13217 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13218 (error "Priority must be between `%c' and `%c'"
13219 org-highest-priority org-lowest-priority))))
13220 ((eq action 'up)
13221 (setq new (if have
13222 (1- current) ; normal cycling
13223 ;; last priority was empty
13224 (if (eq last-command this-command)
13225 org-lowest-priority ; wrap around empty to lowest
13226 ;; default
13227 (if org-priority-start-cycle-with-default
13228 org-default-priority
13229 (1- org-default-priority))))))
13230 ((eq action 'down)
13231 (setq new (if have
13232 (1+ current) ; normal cycling
13233 ;; last priority was empty
13234 (if (eq last-command this-command)
13235 org-highest-priority ; wrap around empty to highest
13236 ;; default
13237 (if org-priority-start-cycle-with-default
13238 org-default-priority
13239 (1+ org-default-priority))))))
13240 (t (error "Invalid action")))
13241 (if (or (< (upcase new) org-highest-priority)
13242 (> (upcase new) org-lowest-priority))
13243 (if (and (memq action '(up down))
13244 (not have) (not (eq last-command this-command)))
13245 ;; `new' is from default priority
13246 (error
13247 "The default can not be set, see `org-default-priority' why")
13248 ;; normal cycling: `new' is beyond highest/lowest priority
13249 ;; and is wrapped around to the empty priority
13250 (setq remove t)))
13251 (setq news (format "%c" new))
13252 (if have
13253 (if remove
13254 (replace-match "" t t nil 1)
13255 (replace-match news t t nil 2))
13256 (if remove
13257 (error "No priority cookie found in line")
13258 (let ((case-fold-search nil))
13259 (looking-at org-todo-line-regexp))
13260 (if (match-end 2)
13261 (progn
13262 (goto-char (match-end 2))
13263 (insert " [#" news "]"))
13264 (goto-char (match-beginning 3))
13265 (insert "[#" news "] "))))
13266 (org-preserve-lc (org-set-tags nil 'align)))
13267 (if remove
13268 (message "Priority removed")
13269 (message "Priority of current item set to %s" news)))))
13271 (defun org-show-priority ()
13272 "Show the priority of the current item.
13273 This priority is composed of the main priority given with the [#A] cookies,
13274 and by additional input from the age of a schedules or deadline entry."
13275 (interactive)
13276 (let ((pri (if (eq major-mode 'org-agenda-mode)
13277 (org-get-at-bol 'priority)
13278 (save-excursion
13279 (save-match-data
13280 (beginning-of-line)
13281 (and (looking-at org-heading-regexp)
13282 (org-get-priority (match-string 0))))))))
13283 (message "Priority is %d" (if pri pri -1000))))
13285 (defun org-get-priority (s)
13286 "Find priority cookie and return priority."
13287 (save-match-data
13288 (if (functionp org-get-priority-function)
13289 (funcall org-get-priority-function)
13290 (if (not (string-match org-priority-regexp s))
13291 (* 1000 (- org-lowest-priority org-default-priority))
13292 (* 1000 (- org-lowest-priority
13293 (string-to-char (match-string 2 s))))))))
13295 ;;;; Tags
13297 (defvar org-agenda-archives-mode)
13298 (defvar org-map-continue-from nil
13299 "Position from where mapping should continue.
13300 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13302 (defvar org-scanner-tags nil
13303 "The current tag list while the tags scanner is running.")
13304 (defvar org-trust-scanner-tags nil
13305 "Should `org-get-tags-at' use the tags for the scanner.
13306 This is for internal dynamical scoping only.
13307 When this is non-nil, the function `org-get-tags-at' will return the value
13308 of `org-scanner-tags' instead of building the list by itself. This
13309 can lead to large speed-ups when the tags scanner is used in a file with
13310 many entries, and when the list of tags is retrieved, for example to
13311 obtain a list of properties. Building the tags list for each entry in such
13312 a file becomes an N^2 operation - but with this variable set, it scales
13313 as N.")
13315 (defun org-scan-tags (action matcher todo-only &optional start-level)
13316 "Scan headline tags with inheritance and produce output ACTION.
13318 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13319 or `agenda' to produce an entry list for an agenda view. It can also be
13320 a Lisp form or a function that should be called at each matched headline, in
13321 this case the return value is a list of all return values from these calls.
13323 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13324 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13325 only lines with a not-done TODO keyword are included in the output.
13326 This should be the same variable that was scoped into
13327 and set by `org-make-tags-matcher' when it constructed MATCHER.
13329 START-LEVEL can be a string with asterisks, reducing the scope to
13330 headlines matching this string."
13331 (require 'org-agenda)
13332 (let* ((re (concat "^"
13333 (if start-level
13334 ;; Get the correct level to match
13335 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13336 org-outline-regexp)
13337 " *\\(\\<\\("
13338 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13339 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13340 (props (list 'face 'default
13341 'done-face 'org-agenda-done
13342 'undone-face 'default
13343 'mouse-face 'highlight
13344 'org-not-done-regexp org-not-done-regexp
13345 'org-todo-regexp org-todo-regexp
13346 'org-complex-heading-regexp org-complex-heading-regexp
13347 'help-echo
13348 (format "mouse-2 or RET jump to org file %s"
13349 (abbreviate-file-name
13350 (or (buffer-file-name (buffer-base-buffer))
13351 (buffer-name (buffer-base-buffer)))))))
13352 (case-fold-search nil)
13353 (org-map-continue-from nil)
13354 lspos tags tags-list
13355 (tags-alist (list (cons 0 org-file-tags)))
13356 (llast 0) rtn rtn1 level category i txt
13357 todo marker entry priority)
13358 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13359 (setq action (list 'lambda nil action)))
13360 (save-excursion
13361 (goto-char (point-min))
13362 (when (eq action 'sparse-tree)
13363 (org-overview)
13364 (org-remove-occur-highlights))
13365 (while (re-search-forward re nil t)
13366 (setq org-map-continue-from nil)
13367 (catch :skip
13368 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13369 tags (if (match-end 4) (org-match-string-no-properties 4)))
13370 (goto-char (setq lspos (match-beginning 0)))
13371 (setq level (org-reduced-level (org-outline-level))
13372 category (org-get-category))
13373 (setq i llast llast level)
13374 ;; remove tag lists from same and sublevels
13375 (while (>= i level)
13376 (when (setq entry (assoc i tags-alist))
13377 (setq tags-alist (delete entry tags-alist)))
13378 (setq i (1- i)))
13379 ;; add the next tags
13380 (when tags
13381 (setq tags (org-split-string tags ":")
13382 tags-alist
13383 (cons (cons level tags) tags-alist)))
13384 ;; compile tags for current headline
13385 (setq tags-list
13386 (if org-use-tag-inheritance
13387 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13388 tags)
13389 org-scanner-tags tags-list)
13390 (when org-use-tag-inheritance
13391 (setcdr (car tags-alist)
13392 (mapcar (lambda (x)
13393 (setq x (copy-sequence x))
13394 (org-add-prop-inherited x))
13395 (cdar tags-alist))))
13396 (when (and tags org-use-tag-inheritance
13397 (or (not (eq t org-use-tag-inheritance))
13398 org-tags-exclude-from-inheritance))
13399 ;; selective inheritance, remove uninherited ones
13400 (setcdr (car tags-alist)
13401 (org-remove-uninherited-tags (cdar tags-alist))))
13402 (when (and
13404 ;; eval matcher only when the todo condition is OK
13405 (and (or (not todo-only) (member todo org-not-done-keywords))
13406 (let ((case-fold-search t) (org-trust-scanner-tags t))
13407 (eval matcher)))
13409 ;; Call the skipper, but return t if it does not skip,
13410 ;; so that the `and' form continues evaluating
13411 (progn
13412 (unless (eq action 'sparse-tree) (org-agenda-skip))
13415 ;; Check if timestamps are deselecting this entry
13416 (or (not todo-only)
13417 (and (member todo org-not-done-keywords)
13418 (or (not org-agenda-tags-todo-honor-ignore-options)
13419 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13421 ;; select this headline
13422 (cond
13423 ((eq action 'sparse-tree)
13424 (and org-highlight-sparse-tree-matches
13425 (org-get-heading) (match-end 0)
13426 (org-highlight-new-match
13427 (match-beginning 1) (match-end 1)))
13428 (org-show-context 'tags-tree))
13429 ((eq action 'agenda)
13430 (setq txt (org-agenda-format-item
13432 (concat
13433 (if (eq org-tags-match-list-sublevels 'indented)
13434 (make-string (1- level) ?.) "")
13435 (org-get-heading))
13436 level category
13437 tags-list)
13438 priority (org-get-priority txt))
13439 (goto-char lspos)
13440 (setq marker (org-agenda-new-marker))
13441 (org-add-props txt props
13442 'org-marker marker 'org-hd-marker marker 'org-category category
13443 'todo-state todo
13444 'priority priority 'type "tagsmatch")
13445 (push txt rtn))
13446 ((functionp action)
13447 (setq org-map-continue-from nil)
13448 (save-excursion
13449 (setq rtn1 (funcall action))
13450 (push rtn1 rtn)))
13451 (t (error "Invalid action")))
13453 ;; if we are to skip sublevels, jump to end of subtree
13454 (unless org-tags-match-list-sublevels
13455 (org-end-of-subtree t)
13456 (backward-char 1))))
13457 ;; Get the correct position from where to continue
13458 (if org-map-continue-from
13459 (goto-char org-map-continue-from)
13460 (and (= (point) lspos) (end-of-line 1)))))
13461 (when (and (eq action 'sparse-tree)
13462 (not org-sparse-tree-open-archived-trees))
13463 (org-hide-archived-subtrees (point-min) (point-max)))
13464 (nreverse rtn)))
13466 (defun org-remove-uninherited-tags (tags)
13467 "Remove all tags that are not inherited from the list TAGS."
13468 (cond
13469 ((eq org-use-tag-inheritance t)
13470 (if org-tags-exclude-from-inheritance
13471 (org-delete-all org-tags-exclude-from-inheritance tags)
13472 tags))
13473 ((not org-use-tag-inheritance) nil)
13474 ((stringp org-use-tag-inheritance)
13475 (delq nil (mapcar
13476 (lambda (x)
13477 (if (and (string-match org-use-tag-inheritance x)
13478 (not (member x org-tags-exclude-from-inheritance)))
13479 x nil))
13480 tags)))
13481 ((listp org-use-tag-inheritance)
13482 (delq nil (mapcar
13483 (lambda (x)
13484 (if (member x org-use-tag-inheritance) x nil))
13485 tags)))))
13487 (defun org-match-sparse-tree (&optional todo-only match)
13488 "Create a sparse tree according to tags string MATCH.
13489 MATCH can contain positive and negative selection of tags, like
13490 \"+WORK+URGENT-WITHBOSS\".
13491 If optional argument TODO-ONLY is non-nil, only select lines that are
13492 also TODO lines."
13493 (interactive "P")
13494 (org-agenda-prepare-buffers (list (current-buffer)))
13495 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13497 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13499 (defvar org-cached-props nil)
13500 (defun org-cached-entry-get (pom property)
13501 (if (or (eq t org-use-property-inheritance)
13502 (and (stringp org-use-property-inheritance)
13503 (string-match org-use-property-inheritance property))
13504 (and (listp org-use-property-inheritance)
13505 (member property org-use-property-inheritance)))
13506 ;; Caching is not possible, check it directly
13507 (org-entry-get pom property 'inherit)
13508 ;; Get all properties, so that we can do complicated checks easily
13509 (cdr (assoc property (or org-cached-props
13510 (setq org-cached-props
13511 (org-entry-properties pom)))))))
13513 (defun org-global-tags-completion-table (&optional files)
13514 "Return the list of all tags in all agenda buffer/files.
13515 Optional FILES argument is a list of files which can be used
13516 instead of the agenda files."
13517 (save-excursion
13518 (org-uniquify
13519 (delq nil
13520 (apply 'append
13521 (mapcar
13522 (lambda (file)
13523 (set-buffer (find-file-noselect file))
13524 (append (org-get-buffer-tags)
13525 (mapcar (lambda (x) (if (stringp (car-safe x))
13526 (list (car-safe x)) nil))
13527 org-tag-alist)))
13528 (if (and files (car files))
13529 files
13530 (org-agenda-files))))))))
13532 (defun org-make-tags-matcher (match)
13533 "Create the TAGS/TODO matcher form for the selection string MATCH.
13535 The variable `todo-only' is scoped dynamically into this function.
13536 It will be set to t if the matcher restricts matching to TODO entries,
13537 otherwise will not be touched.
13539 Returns a cons of the selection string MATCH and the constructed
13540 lisp form implementing the matcher. The matcher is to be evaluated
13541 at an Org entry, with point on the headline, and returns t if the
13542 entry matches the selection string MATCH. The returned lisp form
13543 references two variables with information about the entry, which
13544 must be bound around the form's evaluation: todo, the TODO keyword
13545 at the entry (or nil of none); and tags-list, the list of all tags
13546 at the entry including inherited ones. Additionally, the category
13547 of the entry (if any) must be specified as the text property
13548 'org-category on the headline.
13550 See also `org-scan-tags'.
13552 (declare (special todo-only))
13553 (unless (boundp 'todo-only)
13554 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13555 (unless match
13556 ;; Get a new match request, with completion
13557 (let ((org-last-tags-completion-table
13558 (org-global-tags-completion-table)))
13559 (setq match (org-completing-read-no-i
13560 "Match: " 'org-tags-completion-function nil nil nil
13561 'org-tags-history))))
13563 ;; Parse the string and create a lisp form
13564 (let ((match0 match)
13565 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13566 minus tag mm
13567 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13568 orterms term orlist re-p str-p level-p level-op time-p
13569 prop-p pn pv po gv rest)
13570 (if (string-match "/+" match)
13571 ;; match contains also a todo-matching request
13572 (progn
13573 (setq tagsmatch (substring match 0 (match-beginning 0))
13574 todomatch (substring match (match-end 0)))
13575 (if (string-match "^!" todomatch)
13576 (setq todo-only t todomatch (substring todomatch 1)))
13577 (if (string-match "^\\s-*$" todomatch)
13578 (setq todomatch nil)))
13579 ;; only matching tags
13580 (setq tagsmatch match todomatch nil))
13582 ;; Make the tags matcher
13583 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13584 (setq tagsmatcher t)
13585 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13586 (while (setq term (pop orterms))
13587 (while (and (equal (substring term -1) "\\") orterms)
13588 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13589 (while (string-match re term)
13590 (setq rest (substring term (match-end 0))
13591 minus (and (match-end 1)
13592 (equal (match-string 1 term) "-"))
13593 tag (save-match-data (replace-regexp-in-string
13594 "\\\\-" "-"
13595 (match-string 2 term)))
13596 re-p (equal (string-to-char tag) ?{)
13597 level-p (match-end 4)
13598 prop-p (match-end 5)
13599 mm (cond
13600 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13601 (level-p
13602 (setq level-op (org-op-to-function (match-string 3 term)))
13603 `(,level-op level ,(string-to-number
13604 (match-string 4 term))))
13605 (prop-p
13606 (setq pn (match-string 5 term)
13607 po (match-string 6 term)
13608 pv (match-string 7 term)
13609 re-p (equal (string-to-char pv) ?{)
13610 str-p (equal (string-to-char pv) ?\")
13611 time-p (save-match-data
13612 (string-match "^\"[[<].*[]>]\"$" pv))
13613 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13614 (if time-p (setq pv (org-matcher-time pv)))
13615 (setq po (org-op-to-function po (if time-p 'time str-p)))
13616 (cond
13617 ((equal pn "CATEGORY")
13618 (setq gv '(get-text-property (point) 'org-category)))
13619 ((equal pn "TODO")
13620 (setq gv 'todo))
13622 (setq gv `(org-cached-entry-get nil ,pn))))
13623 (if re-p
13624 (if (eq po 'org<>)
13625 `(not (string-match ,pv (or ,gv "")))
13626 `(string-match ,pv (or ,gv "")))
13627 (if str-p
13628 `(,po (or ,gv "") ,pv)
13629 `(,po (string-to-number (or ,gv ""))
13630 ,(string-to-number pv) ))))
13631 (t `(member ,tag tags-list)))
13632 mm (if minus (list 'not mm) mm)
13633 term rest)
13634 (push mm tagsmatcher))
13635 (push (if (> (length tagsmatcher) 1)
13636 (cons 'and tagsmatcher)
13637 (car tagsmatcher))
13638 orlist)
13639 (setq tagsmatcher nil))
13640 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13641 (setq tagsmatcher
13642 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13643 ;; Make the todo matcher
13644 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13645 (setq todomatcher t)
13646 (setq orterms (org-split-string todomatch "|") orlist nil)
13647 (while (setq term (pop orterms))
13648 (while (string-match re term)
13649 (setq minus (and (match-end 1)
13650 (equal (match-string 1 term) "-"))
13651 kwd (match-string 2 term)
13652 re-p (equal (string-to-char kwd) ?{)
13653 term (substring term (match-end 0))
13654 mm (if re-p
13655 `(string-match ,(substring kwd 1 -1) todo)
13656 (list 'equal 'todo kwd))
13657 mm (if minus (list 'not mm) mm))
13658 (push mm todomatcher))
13659 (push (if (> (length todomatcher) 1)
13660 (cons 'and todomatcher)
13661 (car todomatcher))
13662 orlist)
13663 (setq todomatcher nil))
13664 (setq todomatcher (if (> (length orlist) 1)
13665 (cons 'or orlist) (car orlist))))
13667 ;; Return the string and lisp forms of the matcher
13668 (setq matcher (if todomatcher
13669 (list 'and tagsmatcher todomatcher)
13670 tagsmatcher))
13671 (when todo-only
13672 (setq matcher (list 'and '(member todo org-not-done-keywords)
13673 matcher)))
13674 (cons match0 matcher)))
13676 (defun org-op-to-function (op &optional stringp)
13677 "Turn an operator into the appropriate function."
13678 (setq op
13679 (cond
13680 ((equal op "<" ) '(< string< org-time<))
13681 ((equal op ">" ) '(> org-string> org-time>))
13682 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13683 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13684 ((member op '("=" "==")) '(= string= org-time=))
13685 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13686 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13688 (defun org<> (a b) (not (= a b)))
13689 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13690 (defun org-string>= (a b) (not (string< a b)))
13691 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13692 (defun org-string<> (a b) (not (string= a b)))
13693 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13694 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13695 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13696 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13697 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13698 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13699 (defun org-2ft (s)
13700 "Convert S to a floating point time.
13701 If S is already a number, just return it. If it is a string, parse
13702 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13703 (cond
13704 ((numberp s) s)
13705 ((stringp s)
13706 (condition-case nil
13707 (float-time (apply 'encode-time (org-parse-time-string s)))
13708 (error 0.)))
13709 (t 0.)))
13711 (defun org-time-today ()
13712 "Time in seconds today at 0:00.
13713 Returns the float number of seconds since the beginning of the
13714 epoch to the beginning of today (00:00)."
13715 (float-time (apply 'encode-time
13716 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13718 (defun org-matcher-time (s)
13719 "Interpret a time comparison value."
13720 (save-match-data
13721 (cond
13722 ((string= s "<now>") (float-time))
13723 ((string= s "<today>") (org-time-today))
13724 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13725 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13726 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13727 (+ (org-time-today)
13728 (* (string-to-number (match-string 1 s))
13729 (cdr (assoc (match-string 2 s)
13730 '(("d" . 86400.0) ("w" . 604800.0)
13731 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13732 (t (org-2ft s)))))
13734 (defun org-match-any-p (re list)
13735 "Does re match any element of list?"
13736 (setq list (mapcar (lambda (x) (string-match re x)) list))
13737 (delq nil list))
13739 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13740 (defvar org-tags-overlay (make-overlay 1 1))
13741 (org-detach-overlay org-tags-overlay)
13743 (defun org-get-local-tags-at (&optional pos)
13744 "Get a list of tags defined in the current headline."
13745 (org-get-tags-at pos 'local))
13747 (defun org-get-local-tags ()
13748 "Get a list of tags defined in the current headline."
13749 (org-get-tags-at nil 'local))
13751 (defun org-get-tags-at (&optional pos local)
13752 "Get a list of all headline tags applicable at POS.
13753 POS defaults to point. If tags are inherited, the list contains
13754 the targets in the same sequence as the headlines appear, i.e.
13755 the tags of the current headline come last.
13756 When LOCAL is non-nil, only return tags from the current headline,
13757 ignore inherited ones."
13758 (interactive)
13759 (if (and org-trust-scanner-tags
13760 (or (not pos) (equal pos (point)))
13761 (not local))
13762 org-scanner-tags
13763 (let (tags ltags lastpos parent)
13764 (save-excursion
13765 (save-restriction
13766 (widen)
13767 (goto-char (or pos (point)))
13768 (save-match-data
13769 (catch 'done
13770 (condition-case nil
13771 (progn
13772 (org-back-to-heading t)
13773 (while (not (equal lastpos (point)))
13774 (setq lastpos (point))
13775 (when (looking-at
13776 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13777 (setq ltags (org-split-string
13778 (org-match-string-no-properties 1) ":"))
13779 (when parent
13780 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13781 (setq tags (append
13782 (if parent
13783 (org-remove-uninherited-tags ltags)
13784 ltags)
13785 tags)))
13786 (or org-use-tag-inheritance (throw 'done t))
13787 (if local (throw 'done t))
13788 (or (org-up-heading-safe) (error nil))
13789 (setq parent t)))
13790 (error nil)))))
13791 (if local
13792 tags
13793 (reverse (delete-dups
13794 (reverse (append
13795 (org-remove-uninherited-tags
13796 org-file-tags) tags)))))))))
13798 (defun org-add-prop-inherited (s)
13799 (add-text-properties 0 (length s) '(inherited t) s)
13802 (defun org-toggle-tag (tag &optional onoff)
13803 "Toggle the tag TAG for the current line.
13804 If ONOFF is `on' or `off', don't toggle but set to this state."
13805 (let (res current)
13806 (save-excursion
13807 (org-back-to-heading t)
13808 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13809 (point-at-eol) t)
13810 (progn
13811 (setq current (match-string 1))
13812 (replace-match ""))
13813 (setq current ""))
13814 (setq current (nreverse (org-split-string current ":")))
13815 (cond
13816 ((eq onoff 'on)
13817 (setq res t)
13818 (or (member tag current) (push tag current)))
13819 ((eq onoff 'off)
13820 (or (not (member tag current)) (setq current (delete tag current))))
13821 (t (if (member tag current)
13822 (setq current (delete tag current))
13823 (setq res t)
13824 (push tag current))))
13825 (end-of-line 1)
13826 (if current
13827 (progn
13828 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13829 (org-set-tags nil t))
13830 (delete-horizontal-space))
13831 (run-hooks 'org-after-tags-change-hook))
13832 res))
13834 (defun org-align-tags-here (to-col)
13835 ;; Assumes that this is a headline
13836 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13837 (beginning-of-line 1)
13838 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13839 (< pos (match-beginning 2)))
13840 (progn
13841 (setq tags-l (- (match-end 2) (match-beginning 2)))
13842 (goto-char (match-beginning 1))
13843 (insert " ")
13844 (delete-region (point) (1+ (match-beginning 2)))
13845 (setq ncol (max (current-column)
13846 (1+ col)
13847 (if (> to-col 0)
13848 to-col
13849 (- (abs to-col) tags-l))))
13850 (setq p (point))
13851 (insert (make-string (- ncol (current-column)) ?\ ))
13852 (setq ncol (current-column))
13853 (when indent-tabs-mode (tabify p (point-at-eol)))
13854 (org-move-to-column (min ncol col) t))
13855 (goto-char pos))))
13857 (defun org-set-tags-command (&optional arg just-align)
13858 "Call the set-tags command for the current entry."
13859 (interactive "P")
13860 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13861 (org-set-tags arg just-align)
13862 (save-excursion
13863 (org-back-to-heading t)
13864 (org-set-tags arg just-align))))
13866 (defun org-set-tags-to (data)
13867 "Set the tags of the current entry to DATA, replacing the current tags.
13868 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13869 If DATA is nil or the empty string, any tags will be removed."
13870 (interactive "sTags: ")
13871 (setq data
13872 (cond
13873 ((eq data nil) "")
13874 ((equal data "") "")
13875 ((stringp data)
13876 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13877 ":"))
13878 ((listp data)
13879 (concat ":" (mapconcat 'identity data ":") ":"))))
13880 (when data
13881 (save-excursion
13882 (org-back-to-heading t)
13883 (when (looking-at org-complex-heading-regexp)
13884 (if (match-end 5)
13885 (progn
13886 (goto-char (match-beginning 5))
13887 (insert data)
13888 (delete-region (point) (point-at-eol))
13889 (org-set-tags nil 'align))
13890 (goto-char (point-at-eol))
13891 (insert " " data)
13892 (org-set-tags nil 'align)))
13893 (beginning-of-line 1)
13894 (if (looking-at ".*?\\([ \t]+\\)$")
13895 (delete-region (match-beginning 1) (match-end 1))))))
13897 (defun org-align-all-tags ()
13898 "Align the tags i all headings."
13899 (interactive)
13900 (save-excursion
13901 (or (ignore-errors (org-back-to-heading t))
13902 (outline-next-heading))
13903 (if (org-at-heading-p)
13904 (org-set-tags t)
13905 (message "No headings"))))
13907 (defvar org-indent-indentation-per-level)
13908 (defun org-set-tags (&optional arg just-align)
13909 "Set the tags for the current headline.
13910 With prefix ARG, realign all tags in headings in the current buffer."
13911 (interactive "P")
13912 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13913 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13914 'region-start-level 'region))
13915 org-loop-over-headlines-in-active-region)
13916 (org-map-entries
13917 ;; We don't use ARG and JUST-ALIGN here these args are not
13918 ;; useful when looping over headlines
13919 `(org-set-tags)
13920 org-loop-over-headlines-in-active-region
13921 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13922 (let* ((re org-outline-regexp-bol)
13923 (current (unless arg (org-get-tags-string)))
13924 (col (current-column))
13925 (org-setting-tags t)
13926 table current-tags inherited-tags ; computed below when needed
13927 tags p0 c0 c1 rpl di tc level)
13928 (if arg
13929 (save-excursion
13930 (goto-char (point-min))
13931 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13932 (while (re-search-forward re nil t)
13933 (org-set-tags nil t)
13934 (end-of-line 1)))
13935 (message "All tags realigned to column %d" org-tags-column))
13936 (if just-align
13937 (setq tags current)
13938 ;; Get a new set of tags from the user
13939 (save-excursion
13940 (setq table (append org-tag-persistent-alist
13941 (or org-tag-alist (org-get-buffer-tags))
13942 (and
13943 org-complete-tags-always-offer-all-agenda-tags
13944 (org-global-tags-completion-table
13945 (org-agenda-files))))
13946 org-last-tags-completion-table table
13947 current-tags (org-split-string current ":")
13948 inherited-tags (nreverse
13949 (nthcdr (length current-tags)
13950 (nreverse (org-get-tags-at))))
13951 tags
13952 (if (or (eq t org-use-fast-tag-selection)
13953 (and org-use-fast-tag-selection
13954 (delq nil (mapcar 'cdr table))))
13955 (org-fast-tag-selection
13956 current-tags inherited-tags table
13957 (if org-fast-tag-selection-include-todo
13958 org-todo-key-alist))
13959 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13960 (org-trim
13961 (org-icompleting-read "Tags: "
13962 'org-tags-completion-function
13963 nil nil current 'org-tags-history))))))
13964 (while (string-match "[-+&]+" tags)
13965 ;; No boolean logic, just a list
13966 (setq tags (replace-match ":" t t tags))))
13968 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13970 (if org-tags-sort-function
13971 (setq tags (mapconcat 'identity
13972 (sort (org-split-string
13973 tags (org-re "[^[:alnum:]_@#%]+"))
13974 org-tags-sort-function) ":")))
13976 (if (string-match "\\`[\t ]*\\'" tags)
13977 (setq tags "")
13978 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13979 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13981 ;; Insert new tags at the correct column
13982 (beginning-of-line 1)
13983 (setq level (or (and (looking-at org-outline-regexp)
13984 (- (match-end 0) (point) 1))
13986 (cond
13987 ((and (equal current "") (equal tags "")))
13988 ((re-search-forward
13989 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13990 (point-at-eol) t)
13991 (if (equal tags "")
13992 (setq rpl "")
13993 (goto-char (match-beginning 0))
13994 (setq c0 (current-column)
13995 ;; compute offset for the case of org-indent-mode active
13996 di (if org-indent-mode
13997 (* (1- org-indent-indentation-per-level) (1- level))
13999 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14000 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14001 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14002 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14003 (replace-match rpl t t)
14004 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14005 tags)
14006 (t (error "Tags alignment failed")))
14007 (org-move-to-column col)
14008 (unless just-align
14009 (run-hooks 'org-after-tags-change-hook))))))
14011 (defun org-change-tag-in-region (beg end tag off)
14012 "Add or remove TAG for each entry in the region.
14013 This works in the agenda, and also in an org-mode buffer."
14014 (interactive
14015 (list (region-beginning) (region-end)
14016 (let ((org-last-tags-completion-table
14017 (if (derived-mode-p 'org-mode)
14018 (org-get-buffer-tags)
14019 (org-global-tags-completion-table))))
14020 (org-icompleting-read
14021 "Tag: " 'org-tags-completion-function nil nil nil
14022 'org-tags-history))
14023 (progn
14024 (message "[s]et or [r]emove? ")
14025 (equal (read-char-exclusive) ?r))))
14026 (if (fboundp 'deactivate-mark) (deactivate-mark))
14027 (let ((agendap (equal major-mode 'org-agenda-mode))
14028 l1 l2 m buf pos newhead (cnt 0))
14029 (goto-char end)
14030 (setq l2 (1- (org-current-line)))
14031 (goto-char beg)
14032 (setq l1 (org-current-line))
14033 (loop for l from l1 to l2 do
14034 (org-goto-line l)
14035 (setq m (get-text-property (point) 'org-hd-marker))
14036 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14037 (and agendap m))
14038 (setq buf (if agendap (marker-buffer m) (current-buffer))
14039 pos (if agendap m (point)))
14040 (with-current-buffer buf
14041 (save-excursion
14042 (save-restriction
14043 (goto-char pos)
14044 (setq cnt (1+ cnt))
14045 (org-toggle-tag tag (if off 'off 'on))
14046 (setq newhead (org-get-heading)))))
14047 (and agendap (org-agenda-change-all-lines newhead m))))
14048 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14050 (defun org-tags-completion-function (string predicate &optional flag)
14051 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14052 (confirm (lambda (x) (stringp (car x)))))
14053 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14054 (setq s1 (match-string 1 string)
14055 s2 (match-string 2 string))
14056 (setq s1 "" s2 string))
14057 (cond
14058 ((eq flag nil)
14059 ;; try completion
14060 (setq rtn (try-completion s2 ctable confirm))
14061 (if (stringp rtn)
14062 (setq rtn
14063 (concat s1 s2 (substring rtn (length s2))
14064 (if (and org-add-colon-after-tag-completion
14065 (assoc rtn ctable))
14066 ":" ""))))
14067 rtn)
14068 ((eq flag t)
14069 ;; all-completions
14070 (all-completions s2 ctable confirm)
14072 ((eq flag 'lambda)
14073 ;; exact match?
14074 (assoc s2 ctable)))
14077 (defun org-fast-tag-insert (kwd tags face &optional end)
14078 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14079 (insert (format "%-12s" (concat kwd ":"))
14080 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14081 (or end "")))
14083 (defun org-fast-tag-show-exit (flag)
14084 (save-excursion
14085 (org-goto-line 3)
14086 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14087 (replace-match ""))
14088 (when flag
14089 (end-of-line 1)
14090 (org-move-to-column (- (window-width) 19) t)
14091 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14093 (defun org-set-current-tags-overlay (current prefix)
14094 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14095 (if (featurep 'xemacs)
14096 (org-overlay-display org-tags-overlay (concat prefix s)
14097 'secondary-selection)
14098 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14099 (org-overlay-display org-tags-overlay (concat prefix s)))))
14101 (defvar org-last-tag-selection-key nil)
14102 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14103 "Fast tag selection with single keys.
14104 CURRENT is the current list of tags in the headline, INHERITED is the
14105 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14106 possibly with grouping information. TODO-TABLE is a similar table with
14107 TODO keywords, should these have keys assigned to them.
14108 If the keys are nil, a-z are automatically assigned.
14109 Returns the new tags string, or nil to not change the current settings."
14110 (let* ((fulltable (append table todo-table))
14111 (maxlen (apply 'max (mapcar
14112 (lambda (x)
14113 (if (stringp (car x)) (string-width (car x)) 0))
14114 fulltable)))
14115 (buf (current-buffer))
14116 (expert (eq org-fast-tag-selection-single-key 'expert))
14117 (buffer-tags nil)
14118 (fwidth (+ maxlen 3 1 3))
14119 (ncol (/ (- (window-width) 4) fwidth))
14120 (i-face 'org-done)
14121 (c-face 'org-todo)
14122 tg cnt e c char c1 c2 ntable tbl rtn
14123 ov-start ov-end ov-prefix
14124 (exit-after-next org-fast-tag-selection-single-key)
14125 (done-keywords org-done-keywords)
14126 groups ingroup)
14127 (save-excursion
14128 (beginning-of-line 1)
14129 (if (looking-at
14130 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14131 (setq ov-start (match-beginning 1)
14132 ov-end (match-end 1)
14133 ov-prefix "")
14134 (setq ov-start (1- (point-at-eol))
14135 ov-end (1+ ov-start))
14136 (skip-chars-forward "^\n\r")
14137 (setq ov-prefix
14138 (concat
14139 (buffer-substring (1- (point)) (point))
14140 (if (> (current-column) org-tags-column)
14142 (make-string (- org-tags-column (current-column)) ?\ ))))))
14143 (move-overlay org-tags-overlay ov-start ov-end)
14144 (save-window-excursion
14145 (if expert
14146 (set-buffer (get-buffer-create " *Org tags*"))
14147 (delete-other-windows)
14148 (split-window-vertically)
14149 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14150 (erase-buffer)
14151 (org-set-local 'org-done-keywords done-keywords)
14152 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14153 (org-fast-tag-insert "Current" current c-face "\n\n")
14154 (org-fast-tag-show-exit exit-after-next)
14155 (org-set-current-tags-overlay current ov-prefix)
14156 (setq tbl fulltable char ?a cnt 0)
14157 (while (setq e (pop tbl))
14158 (cond
14159 ((equal (car e) :startgroup)
14160 (push '() groups) (setq ingroup t)
14161 (when (not (= cnt 0))
14162 (setq cnt 0)
14163 (insert "\n"))
14164 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14165 ((equal (car e) :endgroup)
14166 (setq ingroup nil cnt 0)
14167 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14168 ((equal e '(:newline))
14169 (when (not (= cnt 0))
14170 (setq cnt 0)
14171 (insert "\n")
14172 (setq e (car tbl))
14173 (while (equal (car tbl) '(:newline))
14174 (insert "\n")
14175 (setq tbl (cdr tbl)))))
14177 (setq tg (copy-sequence (car e)) c2 nil)
14178 (if (cdr e)
14179 (setq c (cdr e))
14180 ;; automatically assign a character.
14181 (setq c1 (string-to-char
14182 (downcase (substring
14183 tg (if (= (string-to-char tg) ?@) 1 0)))))
14184 (if (or (rassoc c1 ntable) (rassoc c1 table))
14185 (while (or (rassoc char ntable) (rassoc char table))
14186 (setq char (1+ char)))
14187 (setq c2 c1))
14188 (setq c (or c2 char)))
14189 (if ingroup (push tg (car groups)))
14190 (setq tg (org-add-props tg nil 'face
14191 (cond
14192 ((not (assoc tg table))
14193 (org-get-todo-face tg))
14194 ((member tg current) c-face)
14195 ((member tg inherited) i-face))))
14196 (if (and (= cnt 0) (not ingroup)) (insert " "))
14197 (insert "[" c "] " tg (make-string
14198 (- fwidth 4 (length tg)) ?\ ))
14199 (push (cons tg c) ntable)
14200 (when (= (setq cnt (1+ cnt)) ncol)
14201 (insert "\n")
14202 (if ingroup (insert " "))
14203 (setq cnt 0)))))
14204 (setq ntable (nreverse ntable))
14205 (insert "\n")
14206 (goto-char (point-min))
14207 (if (not expert) (org-fit-window-to-buffer))
14208 (setq rtn
14209 (catch 'exit
14210 (while t
14211 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14212 (if (not groups) "no " "")
14213 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14214 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14215 (setq org-last-tag-selection-key c)
14216 (cond
14217 ((= c ?\r) (throw 'exit t))
14218 ((= c ?!)
14219 (setq groups (not groups))
14220 (goto-char (point-min))
14221 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14222 ((= c ?\C-c)
14223 (if (not expert)
14224 (org-fast-tag-show-exit
14225 (setq exit-after-next (not exit-after-next)))
14226 (setq expert nil)
14227 (delete-other-windows)
14228 (set-window-buffer (split-window-vertically) " *Org tags*")
14229 (org-switch-to-buffer-other-window " *Org tags*")
14230 (org-fit-window-to-buffer)))
14231 ((or (= c ?\C-g)
14232 (and (= c ?q) (not (rassoc c ntable))))
14233 (org-detach-overlay org-tags-overlay)
14234 (setq quit-flag t))
14235 ((= c ?\ )
14236 (setq current nil)
14237 (if exit-after-next (setq exit-after-next 'now)))
14238 ((= c ?\t)
14239 (condition-case nil
14240 (setq tg (org-icompleting-read
14241 "Tag: "
14242 (or buffer-tags
14243 (with-current-buffer buf
14244 (org-get-buffer-tags)))))
14245 (quit (setq tg "")))
14246 (when (string-match "\\S-" tg)
14247 (add-to-list 'buffer-tags (list tg))
14248 (if (member tg current)
14249 (setq current (delete tg current))
14250 (push tg current)))
14251 (if exit-after-next (setq exit-after-next 'now)))
14252 ((setq e (rassoc c todo-table) tg (car e))
14253 (with-current-buffer buf
14254 (save-excursion (org-todo tg)))
14255 (if exit-after-next (setq exit-after-next 'now)))
14256 ((setq e (rassoc c ntable) tg (car e))
14257 (if (member tg current)
14258 (setq current (delete tg current))
14259 (loop for g in groups do
14260 (if (member tg g)
14261 (mapc (lambda (x)
14262 (setq current (delete x current)))
14263 g)))
14264 (push tg current))
14265 (if exit-after-next (setq exit-after-next 'now))))
14267 ;; Create a sorted list
14268 (setq current
14269 (sort current
14270 (lambda (a b)
14271 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14272 (if (eq exit-after-next 'now) (throw 'exit t))
14273 (goto-char (point-min))
14274 (beginning-of-line 2)
14275 (delete-region (point) (point-at-eol))
14276 (org-fast-tag-insert "Current" current c-face)
14277 (org-set-current-tags-overlay current ov-prefix)
14278 (while (re-search-forward
14279 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14280 (setq tg (match-string 1))
14281 (add-text-properties
14282 (match-beginning 1) (match-end 1)
14283 (list 'face
14284 (cond
14285 ((member tg current) c-face)
14286 ((member tg inherited) i-face)
14287 (t (get-text-property (match-beginning 1) 'face))))))
14288 (goto-char (point-min)))))
14289 (org-detach-overlay org-tags-overlay)
14290 (if rtn
14291 (mapconcat 'identity current ":")
14292 nil))))
14294 (defun org-get-tags-string ()
14295 "Get the TAGS string in the current headline."
14296 (unless (org-at-heading-p t)
14297 (error "Not on a heading"))
14298 (save-excursion
14299 (beginning-of-line 1)
14300 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14301 (org-match-string-no-properties 1)
14302 "")))
14304 (defun org-get-tags ()
14305 "Get the list of tags specified in the current headline."
14306 (org-split-string (org-get-tags-string) ":"))
14308 (defun org-get-buffer-tags ()
14309 "Get a table of all tags used in the buffer, for completion."
14310 (let (tags)
14311 (save-excursion
14312 (goto-char (point-min))
14313 (while (re-search-forward
14314 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14315 (when (equal (char-after (point-at-bol 0)) ?*)
14316 (mapc (lambda (x) (add-to-list 'tags x))
14317 (org-split-string (org-match-string-no-properties 1) ":")))))
14318 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14319 (mapcar 'list tags)))
14321 ;;;; The mapping API
14323 (defun org-map-entries (func &optional match scope &rest skip)
14324 "Call FUNC at each headline selected by MATCH in SCOPE.
14326 FUNC is a function or a lisp form. The function will be called without
14327 arguments, with the cursor positioned at the beginning of the headline.
14328 The return values of all calls to the function will be collected and
14329 returned as a list.
14331 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14332 does not need to preserve point. After evaluation, the cursor will be
14333 moved to the end of the line (presumably of the headline of the
14334 processed entry) and search continues from there. Under some
14335 circumstances, this may not produce the wanted results. For example,
14336 if you have removed (e.g. archived) the current (sub)tree it could
14337 mean that the next entry will be skipped entirely. In such cases, you
14338 can specify the position from where search should continue by making
14339 FUNC set the variable `org-map-continue-from' to the desired buffer
14340 position.
14342 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14343 Only headlines that are matched by this query will be considered during
14344 the iteration. When MATCH is nil or t, all headlines will be
14345 visited by the iteration.
14347 SCOPE determines the scope of this command. It can be any of:
14349 nil The current buffer, respecting the restriction if any
14350 tree The subtree started with the entry at point
14351 region The entries within the active region, if any
14352 region-start-level
14353 The entries within the active region, but only those at
14354 the same level than the first one.
14355 file The current buffer, without restriction
14356 file-with-archives
14357 The current buffer, and any archives associated with it
14358 agenda All agenda files
14359 agenda-with-archives
14360 All agenda files with any archive files associated with them
14361 \(file1 file2 ...)
14362 If this is a list, all files in the list will be scanned
14364 The remaining args are treated as settings for the skipping facilities of
14365 the scanner. The following items can be given here:
14367 archive skip trees with the archive tag.
14368 comment skip trees with the COMMENT keyword
14369 function or Emacs Lisp form:
14370 will be used as value for `org-agenda-skip-function', so whenever
14371 the function returns t, FUNC will not be called for that
14372 entry and search will continue from the point where the
14373 function leaves it.
14375 If your function needs to retrieve the tags including inherited tags
14376 at the *current* entry, you can use the value of the variable
14377 `org-scanner-tags' which will be much faster than getting the value
14378 with `org-get-tags-at'. If your function gets properties with
14379 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14380 to t around the call to `org-entry-properties' to get the same speedup.
14381 Note that if your function moves around to retrieve tags and properties at
14382 a *different* entry, you cannot use these techniques."
14383 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14384 (not (org-region-active-p)))
14385 (let* ((org-agenda-archives-mode nil) ; just to make sure
14386 (org-agenda-skip-archived-trees (memq 'archive skip))
14387 (org-agenda-skip-comment-trees (memq 'comment skip))
14388 (org-agenda-skip-function
14389 (car (org-delete-all '(comment archive) skip)))
14390 (org-tags-match-list-sublevels t)
14391 (start-level (eq scope 'region-start-level))
14392 matcher file res
14393 org-todo-keywords-for-agenda
14394 org-done-keywords-for-agenda
14395 org-todo-keyword-alist-for-agenda
14396 org-drawers-for-agenda
14397 org-tag-alist-for-agenda
14398 todo-only)
14400 (cond
14401 ((eq match t) (setq matcher t))
14402 ((eq match nil) (setq matcher t))
14403 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14405 (save-excursion
14406 (save-restriction
14407 (cond ((eq scope 'tree)
14408 (org-back-to-heading t)
14409 (org-narrow-to-subtree)
14410 (setq scope nil))
14411 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14412 (org-region-active-p))
14413 ;; If needed, set start-level to a string like "2"
14414 (when start-level
14415 (save-excursion
14416 (goto-char (region-beginning))
14417 (unless (org-at-heading-p) (outline-next-heading))
14418 (setq start-level (org-current-level))))
14419 (narrow-to-region (region-beginning)
14420 (save-excursion
14421 (goto-char (region-end))
14422 (unless (and (bolp) (org-at-heading-p))
14423 (outline-next-heading))
14424 (point)))
14425 (setq scope nil)))
14427 (if (not scope)
14428 (progn
14429 (org-agenda-prepare-buffers
14430 (list (buffer-file-name (current-buffer))))
14431 (setq res (org-scan-tags func matcher todo-only start-level)))
14432 ;; Get the right scope
14433 (cond
14434 ((and scope (listp scope) (symbolp (car scope)))
14435 (setq scope (eval scope)))
14436 ((eq scope 'agenda)
14437 (setq scope (org-agenda-files t)))
14438 ((eq scope 'agenda-with-archives)
14439 (setq scope (org-agenda-files t))
14440 (setq scope (org-add-archive-files scope)))
14441 ((eq scope 'file)
14442 (setq scope (list (buffer-file-name))))
14443 ((eq scope 'file-with-archives)
14444 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14445 (org-agenda-prepare-buffers scope)
14446 (while (setq file (pop scope))
14447 (with-current-buffer (org-find-base-buffer-visiting file)
14448 (save-excursion
14449 (save-restriction
14450 (widen)
14451 (goto-char (point-min))
14452 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14453 res)))
14455 ;;;; Properties
14457 ;;; Setting and retrieving properties
14459 (defconst org-special-properties
14460 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14461 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14462 "The special properties valid in Org-mode.
14464 These are properties that are not defined in the property drawer,
14465 but in some other way.")
14467 (defconst org-default-properties
14468 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14469 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14470 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14471 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14472 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14473 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14474 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14475 "Some properties that are used by Org-mode for various purposes.
14476 Being in this list makes sure that they are offered for completion.")
14478 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14479 "Regular expression matching the first line of a property drawer.")
14481 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14482 "Regular expression matching the last line of a property drawer.")
14484 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14485 "Regular expression matching the first line of a property drawer.")
14487 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14488 "Regular expression matching the first line of a property drawer.")
14490 (defconst org-property-drawer-re
14491 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14492 org-property-end-re "\\)\n?")
14493 "Matches an entire property drawer.")
14495 (defconst org-clock-drawer-re
14496 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14497 org-property-end-re "\\)\n?")
14498 "Matches an entire clock drawer.")
14500 (defsubst org-re-property (property)
14501 "Return a regexp matching a PROPERTY line.
14502 Match group 1 will be set to the value."
14503 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14505 (defsubst org-re-property-keyword (property)
14506 "Return a regexp matching a PROPERTY line, possibly with no
14507 value for the property."
14508 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14510 (defun org-property-action ()
14511 "Do an action on properties."
14512 (interactive)
14513 (let (c)
14514 (org-at-property-p)
14515 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14516 (setq c (read-char-exclusive))
14517 (cond
14518 ((equal c ?s)
14519 (call-interactively 'org-set-property))
14520 ((equal c ?d)
14521 (call-interactively 'org-delete-property))
14522 ((equal c ?D)
14523 (call-interactively 'org-delete-property-globally))
14524 ((equal c ?c)
14525 (call-interactively 'org-compute-property-at-point))
14526 (t (error "No such property action %c" c)))))
14528 (defun org-inc-effort ()
14529 "Increment the value of the effort property in the current entry."
14530 (interactive)
14531 (org-set-effort nil t))
14533 (defun org-set-effort (&optional value increment)
14534 "Set the effort property of the current entry.
14535 With numerical prefix arg, use the nth allowed value, 0 stands for the
14536 10th allowed value.
14538 When INCREMENT is non-nil, set the property to the next allowed value."
14539 (interactive "P")
14540 (if (equal value 0) (setq value 10))
14541 (let* ((completion-ignore-case t)
14542 (prop org-effort-property)
14543 (cur (org-entry-get nil prop))
14544 (allowed (org-property-get-allowed-values nil prop 'table))
14545 (existing (mapcar 'list (org-property-values prop)))
14547 (val (cond
14548 ((stringp value) value)
14549 ((and allowed (integerp value))
14550 (or (car (nth (1- value) allowed))
14551 (car (org-last allowed))))
14552 ((and allowed increment)
14553 (or (caadr (member (list cur) allowed))
14554 (error "Allowed effort values are not set")))
14555 (allowed
14556 (message "Select 1-9,0, [RET%s]: %s"
14557 (if cur (concat "=" cur) "")
14558 (mapconcat 'car allowed " "))
14559 (setq rpl (read-char-exclusive))
14560 (if (equal rpl ?\r)
14562 (setq rpl (- rpl ?0))
14563 (if (equal rpl 0) (setq rpl 10))
14564 (if (and (> rpl 0) (<= rpl (length allowed)))
14565 (car (nth (1- rpl) allowed))
14566 (org-completing-read "Effort: " allowed nil))))
14568 (let (org-completion-use-ido org-completion-use-iswitchb)
14569 (org-completing-read
14570 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14571 (concat "[" cur "]") "")
14572 ": ")
14573 existing nil nil "" nil cur))))))
14574 (unless (equal (org-entry-get nil prop) val)
14575 (org-entry-put nil prop val))
14576 (save-excursion
14577 (org-back-to-heading t)
14578 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14579 (message "%s is now %s" prop val)))
14581 (defun org-at-property-p ()
14582 "Is cursor inside a property drawer?"
14583 (save-excursion
14584 (beginning-of-line 1)
14585 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14586 (save-match-data ;; Used by calling procedures
14587 (let ((p (point))
14588 (range (unless (org-before-first-heading-p)
14589 (org-get-property-block))))
14590 (and range (<= (car range) p) (< p (cdr range))))))))
14592 (defun org-get-property-block (&optional beg end force)
14593 "Return the (beg . end) range of the body of the property drawer.
14594 BEG and END are the beginning and end of the current subtree, or of
14595 the part before the first headline. If they are not given, they will
14596 be found. If the drawer does not exist and FORCE is non-nil, create
14597 the drawer."
14598 (catch 'exit
14599 (save-excursion
14600 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14601 (progn (org-back-to-heading t) (point))))
14602 (end (or end (and (not (outline-next-heading)) (point-max))
14603 (point))))
14604 (goto-char beg)
14605 (if (re-search-forward org-property-start-re end t)
14606 (setq beg (1+ (match-end 0)))
14607 (if force
14608 (save-excursion
14609 (org-insert-property-drawer)
14610 (setq end (progn (outline-next-heading) (point))))
14611 (throw 'exit nil))
14612 (goto-char beg)
14613 (if (re-search-forward org-property-start-re end t)
14614 (setq beg (1+ (match-end 0)))))
14615 (if (re-search-forward org-property-end-re end t)
14616 (setq end (match-beginning 0))
14617 (or force (throw 'exit nil))
14618 (goto-char beg)
14619 (setq end beg)
14620 (org-indent-line)
14621 (insert ":END:\n"))
14622 (cons beg end)))))
14624 (defun org-entry-properties (&optional pom which specific)
14625 "Get all properties of the entry at point-or-marker POM.
14626 This includes the TODO keyword, the tags, time strings for deadline,
14627 scheduled, and clocking, and any additional properties defined in the
14628 entry. The return value is an alist, keys may occur multiple times
14629 if the property key was used several times.
14630 POM may also be nil, in which case the current entry is used.
14631 If WHICH is nil or `all', get all properties. If WHICH is
14632 `special' or `standard', only get that subclass. If WHICH
14633 is a string only get exactly this property. SPECIFIC can be a string, the
14634 specific property we are interested in. Specifying it can speed
14635 things up because then unnecessary parsing is avoided."
14636 (setq which (or which 'all))
14637 (org-with-point-at pom
14638 (let ((clockstr (substring org-clock-string 0 -1))
14639 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14640 (case-fold-search nil)
14641 beg end range props sum-props key key1 value string clocksum clocksumt)
14642 (save-excursion
14643 (when (condition-case nil
14644 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14645 (error nil))
14646 (setq beg (point))
14647 (setq sum-props (get-text-property (point) 'org-summaries))
14648 (setq clocksum (get-text-property (point) :org-clock-minutes)
14649 clocksumt (get-text-property (point) :org-clock-minutes-today))
14650 (outline-next-heading)
14651 (setq end (point))
14652 (when (memq which '(all special))
14653 ;; Get the special properties, like TODO and tags
14654 (goto-char beg)
14655 (when (and (or (not specific) (string= specific "TODO"))
14656 (looking-at org-todo-line-regexp) (match-end 2))
14657 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14658 (when (and (or (not specific) (string= specific "PRIORITY"))
14659 (looking-at org-priority-regexp))
14660 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14661 (when (or (not specific) (string= specific "FILE"))
14662 (push (cons "FILE" buffer-file-name) props))
14663 (when (and (or (not specific) (string= specific "TAGS"))
14664 (setq value (org-get-tags-string))
14665 (string-match "\\S-" value))
14666 (push (cons "TAGS" value) props))
14667 (when (and (or (not specific) (string= specific "ALLTAGS"))
14668 (setq value (org-get-tags-at)))
14669 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14670 ":"))
14671 props))
14672 (when (or (not specific) (string= specific "BLOCKED"))
14673 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14674 (when (or (not specific)
14675 (member specific
14676 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14677 "TIMESTAMP" "TIMESTAMP_IA")))
14678 (catch 'match
14679 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14680 (setq key (if (match-end 1)
14681 (substring (org-match-string-no-properties 1)
14682 0 -1))
14683 string (if (equal key clockstr)
14684 (org-trim
14685 (buffer-substring-no-properties
14686 (match-beginning 3) (goto-char
14687 (point-at-eol))))
14688 (substring (org-match-string-no-properties 3)
14689 1 -1)))
14690 ;; Get the correct property name from the key. This is
14691 ;; necessary if the user has configured time keywords.
14692 (setq key1 (concat key ":"))
14693 (cond
14694 ((not key)
14695 (setq key
14696 (if (= (char-after (match-beginning 3)) ?\[)
14697 "TIMESTAMP_IA" "TIMESTAMP")))
14698 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14699 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14700 ((equal key1 org-closed-string) (setq key "CLOSED"))
14701 ((equal key1 org-clock-string) (setq key "CLOCK")))
14702 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14703 (progn
14704 (push (cons key string) props)
14705 ;; no need to search further if match is found
14706 (throw 'match t))
14707 (when (or (equal key "CLOCK") (not (assoc key props)))
14708 (push (cons key string) props)))))))
14710 (when (memq which '(all standard))
14711 ;; Get the standard properties, like :PROP: ...
14712 (setq range (org-get-property-block beg end))
14713 (when range
14714 (goto-char (car range))
14715 (while (re-search-forward
14716 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14717 (cdr range) t)
14718 (setq key (org-match-string-no-properties 1)
14719 value (org-trim (or (org-match-string-no-properties 2) "")))
14720 (unless (member key excluded)
14721 (push (cons key (or value "")) props)))))
14722 (if clocksum
14723 (push (cons "CLOCKSUM"
14724 (org-columns-number-to-string (/ (float clocksum) 60.)
14725 'add_times))
14726 props))
14727 (if clocksumt
14728 (push (cons "CLOCKSUM_T"
14729 (org-columns-number-to-string (/ (float clocksumt) 60.)
14730 'add_times))
14731 props))
14732 (unless (assoc "CATEGORY" props)
14733 (push (cons "CATEGORY" (org-get-category)) props))
14734 (append sum-props (nreverse props)))))))
14736 (defun org-entry-get (pom property &optional inherit literal-nil)
14737 "Get value of PROPERTY for entry or content at point-or-marker POM.
14738 If INHERIT is non-nil and the entry does not have the property,
14739 then also check higher levels of the hierarchy.
14740 If INHERIT is the symbol `selective', use inheritance only if the setting
14741 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14742 If the property is present but empty, the return value is the empty string.
14743 If the property is not present at all, nil is returned.
14745 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14746 do not interpret it as the list atom nil. This is used for inheritance
14747 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14748 (org-with-point-at pom
14749 (if (and inherit (if (eq inherit 'selective)
14750 (org-property-inherit-p property)
14752 (org-entry-get-with-inheritance property literal-nil)
14753 (if (member property org-special-properties)
14754 ;; We need a special property. Use `org-entry-properties' to
14755 ;; retrieve it, but specify the wanted property
14756 (cdr (assoc property (org-entry-properties nil 'special property)))
14757 (let ((range (org-get-property-block)))
14758 (when (and range (not (eq (car range) (cdr range))))
14759 (let* ((props (list (or (assoc property org-file-properties)
14760 (assoc property org-global-properties)
14761 (assoc property org-global-properties-fixed))))
14762 (ap (lambda (key)
14763 (when (re-search-forward
14764 (org-re-property key) (cdr range) t)
14765 (setq props
14766 (org-update-property-plist
14768 (if (match-end 1)
14769 (org-match-string-no-properties 1) "")
14770 props)))))
14771 val)
14772 (goto-char (car range))
14773 (funcall ap property)
14774 (goto-char (car range))
14775 (while (funcall ap (concat property "+")))
14776 (setq val (cdr (assoc property props)))
14777 (when val (if literal-nil val (org-not-nil val))))))))))
14779 (defun org-property-or-variable-value (var &optional inherit)
14780 "Check if there is a property fixing the value of VAR.
14781 If yes, return this value. If not, return the current value of the variable."
14782 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14783 (if (and prop (stringp prop) (string-match "\\S-" prop))
14784 (read prop)
14785 (symbol-value var))))
14787 (defun org-entry-delete (pom property)
14788 "Delete the property PROPERTY from entry at point-or-marker POM."
14789 (org-with-point-at pom
14790 (if (member property org-special-properties)
14791 nil ; cannot delete these properties.
14792 (let ((range (org-get-property-block)))
14793 (if (and range
14794 (goto-char (car range))
14795 (re-search-forward
14796 (org-re-property property)
14797 (cdr range) t))
14798 (progn
14799 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14801 nil)))))
14803 ;; Multi-values properties are properties that contain multiple values
14804 ;; These values are assumed to be single words, separated by whitespace.
14805 (defun org-entry-add-to-multivalued-property (pom property value)
14806 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14807 (let* ((old (org-entry-get pom property))
14808 (values (and old (org-split-string old "[ \t]"))))
14809 (setq value (org-entry-protect-space value))
14810 (unless (member value values)
14811 (setq values (cons value values))
14812 (org-entry-put pom property
14813 (mapconcat 'identity values " ")))))
14815 (defun org-entry-remove-from-multivalued-property (pom property value)
14816 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14817 (let* ((old (org-entry-get pom property))
14818 (values (and old (org-split-string old "[ \t]"))))
14819 (setq value (org-entry-protect-space value))
14820 (when (member value values)
14821 (setq values (delete value values))
14822 (org-entry-put pom property
14823 (mapconcat 'identity values " ")))))
14825 (defun org-entry-member-in-multivalued-property (pom property value)
14826 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14827 (let* ((old (org-entry-get pom property))
14828 (values (and old (org-split-string old "[ \t]"))))
14829 (setq value (org-entry-protect-space value))
14830 (member value values)))
14832 (defun org-entry-get-multivalued-property (pom property)
14833 "Return a list of values in a multivalued property."
14834 (let* ((value (org-entry-get pom property))
14835 (values (and value (org-split-string value "[ \t]"))))
14836 (mapcar 'org-entry-restore-space values)))
14838 (defun org-entry-put-multivalued-property (pom property &rest values)
14839 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14840 VALUES should be a list of strings. Spaces will be protected."
14841 (org-entry-put pom property
14842 (mapconcat 'org-entry-protect-space values " "))
14843 (let* ((value (org-entry-get pom property))
14844 (values (and value (org-split-string value "[ \t]"))))
14845 (mapcar 'org-entry-restore-space values)))
14847 (defun org-entry-protect-space (s)
14848 "Protect spaces and newline in string S."
14849 (while (string-match " " s)
14850 (setq s (replace-match "%20" t t s)))
14851 (while (string-match "\n" s)
14852 (setq s (replace-match "%0A" t t s)))
14855 (defun org-entry-restore-space (s)
14856 "Restore spaces and newline in string S."
14857 (while (string-match "%20" s)
14858 (setq s (replace-match " " t t s)))
14859 (while (string-match "%0A" s)
14860 (setq s (replace-match "\n" t t s)))
14863 (defvar org-entry-property-inherited-from (make-marker)
14864 "Marker pointing to the entry from where a property was inherited.
14865 Each call to `org-entry-get-with-inheritance' will set this marker to the
14866 location of the entry where the inheritance search matched. If there was
14867 no match, the marker will point nowhere.
14868 Note that also `org-entry-get' calls this function, if the INHERIT flag
14869 is set.")
14871 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14872 "Get PROPERTY of entry or content at point, search higher levels if needed.
14873 The search will stop at the first ancestor which has the property defined.
14874 If the value found is \"nil\", return nil to show that the property
14875 should be considered as undefined (this is the meaning of nil here).
14876 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14877 (move-marker org-entry-property-inherited-from nil)
14878 (let (tmp)
14879 (save-excursion
14880 (save-restriction
14881 (widen)
14882 (catch 'ex
14883 (while t
14884 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14885 (or (ignore-errors (org-back-to-heading t))
14886 (goto-char (point-min)))
14887 (move-marker org-entry-property-inherited-from (point))
14888 (throw 'ex tmp))
14889 (or (ignore-errors (org-up-heading-safe))
14890 (throw 'ex nil))))))
14891 (setq tmp (or tmp
14892 (cdr (assoc property org-file-properties))
14893 (cdr (assoc property org-global-properties))
14894 (cdr (assoc property org-global-properties-fixed))))
14895 (if literal-nil tmp (org-not-nil tmp))))
14897 (defvar org-property-changed-functions nil
14898 "Hook called when the value of a property has changed.
14899 Each hook function should accept two arguments, the name of the property
14900 and the new value.")
14902 (defun org-entry-put (pom property value)
14903 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14904 (org-with-point-at pom
14905 (org-back-to-heading t)
14906 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14907 range)
14908 (cond
14909 ((equal property "TODO")
14910 (when (and (stringp value) (string-match "\\S-" value)
14911 (not (member value org-todo-keywords-1)))
14912 (error "\"%s\" is not a valid TODO state" value))
14913 (if (or (not value)
14914 (not (string-match "\\S-" value)))
14915 (setq value 'none))
14916 (org-todo value)
14917 (org-set-tags nil 'align))
14918 ((equal property "PRIORITY")
14919 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14920 (string-to-char value) ?\ ))
14921 (org-set-tags nil 'align))
14922 ((equal property "CLOCKSUM")
14923 (if (not (re-search-forward
14924 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14925 (error "Cannot find a clock log")
14926 (goto-char (- (match-end 1) 2))
14927 (cond
14928 ((eq value 'earlier) (org-timestamp-down))
14929 ((eq value 'later) (org-timestamp-up)))
14930 (org-clock-sum-current-item)))
14931 ((equal property "SCHEDULED")
14932 (if (re-search-forward org-scheduled-time-regexp end t)
14933 (cond
14934 ((eq value 'earlier) (org-timestamp-change -1 'day))
14935 ((eq value 'later) (org-timestamp-change 1 'day))
14936 (t (call-interactively 'org-schedule)))
14937 (call-interactively 'org-schedule)))
14938 ((equal property "DEADLINE")
14939 (if (re-search-forward org-deadline-time-regexp end t)
14940 (cond
14941 ((eq value 'earlier) (org-timestamp-change -1 'day))
14942 ((eq value 'later) (org-timestamp-change 1 'day))
14943 (t (call-interactively 'org-deadline)))
14944 (call-interactively 'org-deadline)))
14945 ((member property org-special-properties)
14946 (error "The %s property can not yet be set with `org-entry-put'"
14947 property))
14948 (t ; a non-special property
14949 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14950 (setq range (org-get-property-block beg end 'force))
14951 (goto-char (car range))
14952 (if (re-search-forward
14953 (org-re-property-keyword property) (cdr range) t)
14954 (progn
14955 (delete-region (match-beginning 0) (match-end 0))
14956 (goto-char (match-beginning 0)))
14957 (goto-char (cdr range))
14958 (insert "\n")
14959 (backward-char 1)
14960 (org-indent-line))
14961 (insert ":" property ":")
14962 (and value (insert " " value))
14963 (org-indent-line)))))
14964 (run-hook-with-args 'org-property-changed-functions property value)))
14966 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14967 "Get all property keys in the current buffer.
14968 With INCLUDE-SPECIALS, also list the special properties that reflect things
14969 like tags and TODO state.
14970 With INCLUDE-DEFAULTS, also include properties that has special meaning
14971 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14972 and others.
14973 With INCLUDE-COLUMNS, also include property names given in COLUMN
14974 formats in the current buffer."
14975 (let (rtn range cfmt s p)
14976 (save-excursion
14977 (save-restriction
14978 (widen)
14979 (goto-char (point-min))
14980 (while (re-search-forward org-property-start-re nil t)
14981 (setq range (org-get-property-block))
14982 (goto-char (car range))
14983 (while (re-search-forward
14984 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14985 (cdr range) t)
14986 (add-to-list 'rtn (org-match-string-no-properties 1)))
14987 (outline-next-heading))))
14989 (when include-specials
14990 (setq rtn (append org-special-properties rtn)))
14992 (when include-defaults
14993 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14994 (add-to-list 'rtn org-effort-property))
14996 (when include-columns
14997 (save-excursion
14998 (save-restriction
14999 (widen)
15000 (goto-char (point-min))
15001 (while (re-search-forward
15002 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15003 nil t)
15004 (setq cfmt (match-string 2) s 0)
15005 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15006 cfmt s)
15007 (setq s (match-end 0)
15008 p (match-string 1 cfmt))
15009 (unless (or (equal p "ITEM")
15010 (member p org-special-properties))
15011 (add-to-list 'rtn (match-string 1 cfmt))))))))
15013 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15015 (defun org-property-values (key)
15016 "Return a list of all values of property KEY in the current buffer."
15017 (save-excursion
15018 (save-restriction
15019 (widen)
15020 (goto-char (point-min))
15021 (let ((re (org-re-property key))
15022 values)
15023 (while (re-search-forward re nil t)
15024 (add-to-list 'values (org-trim (match-string 1))))
15025 (delete "" values)))))
15027 (defun org-insert-property-drawer ()
15028 "Insert a property drawer into the current entry."
15029 (org-back-to-heading t)
15030 (looking-at org-outline-regexp)
15031 (let ((indent (if org-adapt-indentation
15032 (- (match-end 0) (match-beginning 0))
15034 (beg (point))
15035 (re (concat "^[ \t]*" org-keyword-time-regexp))
15036 end hiddenp)
15037 (outline-next-heading)
15038 (setq end (point))
15039 (goto-char beg)
15040 (while (re-search-forward re end t))
15041 (setq hiddenp (outline-invisible-p))
15042 (end-of-line 1)
15043 (and (equal (char-after) ?\n) (forward-char 1))
15044 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15045 (if (member (match-string 1) '("CLOCK:" ":END:"))
15046 ;; just skip this line
15047 (beginning-of-line 2)
15048 ;; Drawer start, find the end
15049 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15050 (beginning-of-line 1)))
15051 (org-skip-over-state-notes)
15052 (skip-chars-backward " \t\n\r")
15053 (if (eq (char-before) ?*) (forward-char 1))
15054 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15055 (beginning-of-line 0)
15056 (org-indent-to-column indent)
15057 (beginning-of-line 2)
15058 (org-indent-to-column indent)
15059 (beginning-of-line 0)
15060 (if hiddenp
15061 (save-excursion
15062 (org-back-to-heading t)
15063 (hide-entry))
15064 (org-flag-drawer t))))
15066 (defun org-insert-drawer (&optional arg drawer)
15067 "Insert a drawer at point.
15069 Optional argument DRAWER, when non-nil, is a string representing
15070 drawer's name. Otherwise, the user is prompted for a name.
15072 If a region is active, insert the drawer around that region
15073 instead.
15075 Point is left between drawer's boundaries."
15076 (interactive "P")
15077 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15078 "LOGBOOK"))
15079 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15080 ;; internally by Org. They are meant to be inserted
15081 ;; automatically.
15082 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15083 ;; Remove system drawers from list. Note: For some reason,
15084 ;; `org-completing-read' ignores the predicate while
15085 ;; `completing-read' handles it fine.
15086 (drawer (if arg "PROPERTIES"
15087 (or drawer
15088 (completing-read
15089 "Drawer: " org-drawers
15090 (lambda (d) (not (member d system-drawers))))))))
15091 (cond
15092 ;; With C-u, fall back on `org-insert-property-drawer'
15093 (arg (org-insert-property-drawer))
15094 ;; With an active region, insert a drawer at point.
15095 ((not (org-region-active-p))
15096 (progn
15097 (unless (bolp) (insert "\n"))
15098 (insert (format ":%s:\n\n:END:\n" drawer))
15099 (forward-line -2)))
15100 ;; Otherwise, insert the drawer at point
15102 (let ((rbeg (region-beginning))
15103 (rend (copy-marker (region-end))))
15104 (unwind-protect
15105 (progn
15106 (goto-char rbeg)
15107 (beginning-of-line)
15108 (when (save-excursion
15109 (re-search-forward org-outline-regexp-bol rend t))
15110 (error "Drawers cannot contain headlines"))
15111 ;; Position point at the beginning of the first
15112 ;; non-blank line in region. Insert drawer's opening
15113 ;; there, then indent it.
15114 (org-skip-whitespace)
15115 (beginning-of-line)
15116 (insert ":" drawer ":\n")
15117 (forward-line -1)
15118 (indent-for-tab-command)
15119 ;; Move point to the beginning of the first blank line
15120 ;; after the last non-blank line in region. Insert
15121 ;; drawer's closing, then indent it.
15122 (goto-char rend)
15123 (skip-chars-backward " \r\t\n")
15124 (insert "\n:END:")
15125 (deactivate-mark t)
15126 (indent-for-tab-command)
15127 (unless (eolp) (insert "\n")))
15128 ;; Clear marker, whatever the outcome of insertion is.
15129 (set-marker rend nil)))))))
15131 (defvar org-property-set-functions-alist nil
15132 "Property set function alist.
15133 Each entry should have the following format:
15135 (PROPERTY . READ-FUNCTION)
15137 The read function will be called with the same argument as
15138 `org-completing-read'.")
15140 (defun org-set-property-function (property)
15141 "Get the function that should be used to set PROPERTY.
15142 This is computed according to `org-property-set-functions-alist'."
15143 (or (cdr (assoc property org-property-set-functions-alist))
15144 'org-completing-read))
15146 (defun org-read-property-value (property)
15147 "Read PROPERTY value from user."
15148 (let* ((completion-ignore-case t)
15149 (allowed (org-property-get-allowed-values nil property 'table))
15150 (cur (org-entry-get nil property))
15151 (prompt (concat property " value"
15152 (if (and cur (string-match "\\S-" cur))
15153 (concat " [" cur "]") "") ": "))
15154 (set-function (org-set-property-function property))
15155 (val (if allowed
15156 (funcall set-function prompt allowed nil
15157 (not (get-text-property 0 'org-unrestricted
15158 (caar allowed))))
15159 (let (org-completion-use-ido org-completion-use-iswitchb)
15160 (funcall set-function prompt
15161 (mapcar 'list (org-property-values property))
15162 nil nil "" nil cur)))))
15163 (if (equal val "")
15165 val)))
15167 (defvar org-last-set-property nil)
15168 (defvar org-last-set-property-value nil)
15169 (defun org-read-property-name ()
15170 "Read a property name."
15171 (let* ((completion-ignore-case t)
15172 (keys (org-buffer-property-keys nil t t))
15173 (default-prop (or (save-excursion
15174 (save-match-data
15175 (beginning-of-line)
15176 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15177 (null (string= (match-string 1) "END"))
15178 (match-string 1))))
15179 org-last-set-property))
15180 (property (org-icompleting-read
15181 (concat "Property"
15182 (if default-prop (concat " [" default-prop "]") "")
15183 ": ")
15184 (mapcar 'list keys)
15185 nil nil nil nil
15186 default-prop)))
15187 (if (member property keys)
15188 property
15189 (or (cdr (assoc (downcase property)
15190 (mapcar (lambda (x) (cons (downcase x) x))
15191 keys)))
15192 property))))
15194 (defun org-set-property-and-value (use-last)
15195 "Allow to set [PROPERTY]: [value] direction from prompt.
15196 When use-default, don't even ask, just use the last
15197 \"[PROPERTY]: [value]\" string from the history."
15198 (interactive "P")
15199 (let* ((completion-ignore-case t)
15200 (pv (or (and use-last org-last-set-property-value)
15201 (org-completing-read
15202 "Enter a \"[Property]: [value]\" pair: "
15203 nil nil nil nil nil
15204 org-last-set-property-value)))
15205 prop val)
15206 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15207 (setq prop (match-string 1 pv)
15208 val (match-string 2 pv))
15209 (org-set-property prop val))))
15211 (defun org-set-property (property value)
15212 "In the current entry, set PROPERTY to VALUE.
15213 When called interactively, this will prompt for a property name, offering
15214 completion on existing and default properties. And then it will prompt
15215 for a value, offering completion either on allowed values (via an inherited
15216 xxx_ALL property) or on existing values in other instances of this property
15217 in the current file."
15218 (interactive (list nil nil))
15219 (let* ((property (or property (org-read-property-name)))
15220 (value (or value (org-read-property-value property)))
15221 (fn (cdr (assoc property org-properties-postprocess-alist))))
15222 (setq org-last-set-property property)
15223 (setq org-last-set-property-value (concat property ": " value))
15224 ;; Possibly postprocess the inserted value:
15225 (when fn (setq value (funcall fn value)))
15226 (unless (equal (org-entry-get nil property) value)
15227 (org-entry-put nil property value))))
15229 (defun org-delete-property (property)
15230 "In the current entry, delete PROPERTY."
15231 (interactive
15232 (let* ((completion-ignore-case t)
15233 (prop (org-icompleting-read "Property: "
15234 (org-entry-properties nil 'standard))))
15235 (list prop)))
15236 (message "Property %s %s" property
15237 (if (org-entry-delete nil property)
15238 "deleted"
15239 "was not present in the entry")))
15241 (defun org-delete-property-globally (property)
15242 "Remove PROPERTY globally, from all entries."
15243 (interactive
15244 (let* ((completion-ignore-case t)
15245 (prop (org-icompleting-read
15246 "Globally remove property: "
15247 (mapcar 'list (org-buffer-property-keys)))))
15248 (list prop)))
15249 (save-excursion
15250 (save-restriction
15251 (widen)
15252 (goto-char (point-min))
15253 (let ((cnt 0))
15254 (while (re-search-forward
15255 (org-re-property property)
15256 nil t)
15257 (setq cnt (1+ cnt))
15258 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15259 (message "Property \"%s\" removed from %d entries" property cnt)))))
15261 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15263 (defun org-compute-property-at-point ()
15264 "Compute the property at point.
15265 This looks for an enclosing column format, extracts the operator and
15266 then applies it to the property in the column format's scope."
15267 (interactive)
15268 (unless (org-at-property-p)
15269 (error "Not at a property"))
15270 (let ((prop (org-match-string-no-properties 2)))
15271 (org-columns-get-format-and-top-level)
15272 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15273 (error "No operator defined for property %s" prop))
15274 (org-columns-compute prop)))
15276 (defvar org-property-allowed-value-functions nil
15277 "Hook for functions supplying allowed values for a specific property.
15278 The functions must take a single argument, the name of the property, and
15279 return a flat list of allowed values. If \":ETC\" is one of
15280 the values, this means that these values are intended as defaults for
15281 completion, but that other values should be allowed too.
15282 The functions must return nil if they are not responsible for this
15283 property.")
15285 (defun org-property-get-allowed-values (pom property &optional table)
15286 "Get allowed values for the property PROPERTY.
15287 When TABLE is non-nil, return an alist that can directly be used for
15288 completion."
15289 (let (vals)
15290 (cond
15291 ((equal property "TODO")
15292 (setq vals (org-with-point-at pom
15293 (append org-todo-keywords-1 '("")))))
15294 ((equal property "PRIORITY")
15295 (let ((n org-lowest-priority))
15296 (while (>= n org-highest-priority)
15297 (push (char-to-string n) vals)
15298 (setq n (1- n)))))
15299 ((member property org-special-properties))
15300 ((setq vals (run-hook-with-args-until-success
15301 'org-property-allowed-value-functions property)))
15303 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15304 (when (and vals (string-match "\\S-" vals))
15305 (setq vals (car (read-from-string (concat "(" vals ")"))))
15306 (setq vals (mapcar (lambda (x)
15307 (cond ((stringp x) x)
15308 ((numberp x) (number-to-string x))
15309 ((symbolp x) (symbol-name x))
15310 (t "???")))
15311 vals)))))
15312 (when (member ":ETC" vals)
15313 (setq vals (remove ":ETC" vals))
15314 (org-add-props (car vals) '(org-unrestricted t)))
15315 (if table (mapcar 'list vals) vals)))
15317 (defun org-property-previous-allowed-value (&optional previous)
15318 "Switch to the next allowed value for this property."
15319 (interactive)
15320 (org-property-next-allowed-value t))
15322 (defun org-property-next-allowed-value (&optional previous)
15323 "Switch to the next allowed value for this property."
15324 (interactive)
15325 (unless (org-at-property-p)
15326 (error "Not at a property"))
15327 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15328 (key (match-string 2))
15329 (value (match-string 3))
15330 (allowed (or (org-property-get-allowed-values (point) key)
15331 (and (member value '("[ ]" "[-]" "[X]"))
15332 '("[ ]" "[X]"))))
15333 nval)
15334 (unless allowed
15335 (error "Allowed values for this property have not been defined"))
15336 (if previous (setq allowed (reverse allowed)))
15337 (if (member value allowed)
15338 (setq nval (car (cdr (member value allowed)))))
15339 (setq nval (or nval (car allowed)))
15340 (if (equal nval value)
15341 (error "Only one allowed value for this property"))
15342 (org-at-property-p)
15343 (replace-match (concat " :" key ": " nval) t t)
15344 (org-indent-line)
15345 (beginning-of-line 1)
15346 (skip-chars-forward " \t")
15347 (when (equal prop org-effort-property)
15348 (save-excursion
15349 (org-back-to-heading t)
15350 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15351 (run-hook-with-args 'org-property-changed-functions key nval)))
15353 (defun org-find-olp (path &optional this-buffer)
15354 "Return a marker pointing to the entry at outline path OLP.
15355 If anything goes wrong, throw an error.
15356 You can wrap this call to catch the error like this:
15358 (condition-case msg
15359 (org-mobile-locate-entry (match-string 4))
15360 (error (nth 1 msg)))
15362 The return value will then be either a string with the error message,
15363 or a marker if everything is OK.
15365 If THIS-BUFFER is set, the outline path does not contain a file,
15366 only headings."
15367 (let* ((file (if this-buffer buffer-file-name (pop path)))
15368 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15369 (level 1)
15370 (lmin 1)
15371 (lmax 1)
15372 limit re end found pos heading cnt flevel)
15373 (unless buffer (error "File not found :%s" file))
15374 (with-current-buffer buffer
15375 (save-excursion
15376 (save-restriction
15377 (widen)
15378 (setq limit (point-max))
15379 (goto-char (point-min))
15380 (while (setq heading (pop path))
15381 (setq re (format org-complex-heading-regexp-format
15382 (regexp-quote heading)))
15383 (setq cnt 0 pos (point))
15384 (while (re-search-forward re end t)
15385 (setq level (- (match-end 1) (match-beginning 1)))
15386 (if (and (>= level lmin) (<= level lmax))
15387 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15388 (when (= cnt 0) (error "Heading not found on level %d: %s"
15389 lmax heading))
15390 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15391 lmax heading))
15392 (goto-char found)
15393 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15394 (setq end (save-excursion (org-end-of-subtree t t))))
15395 (when (org-at-heading-p)
15396 (point-marker)))))))
15398 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15399 "Find node HEADING in BUFFER.
15400 Return a marker to the heading if it was found, or nil if not.
15401 If POS-ONLY is set, return just the position instead of a marker.
15403 The heading text must match exact, but it may have a TODO keyword,
15404 a priority cookie and tags in the standard locations."
15405 (with-current-buffer (or buffer (current-buffer))
15406 (save-excursion
15407 (save-restriction
15408 (widen)
15409 (goto-char (point-min))
15410 (let (case-fold-search)
15411 (if (re-search-forward
15412 (format org-complex-heading-regexp-format
15413 (regexp-quote heading)) nil t)
15414 (if pos-only
15415 (match-beginning 0)
15416 (move-marker (make-marker) (match-beginning 0)))))))))
15418 (defun org-find-exact-heading-in-directory (heading &optional dir)
15419 "Find Org node headline HEADING in all .org files in directory DIR.
15420 When the target headline is found, return a marker to this location."
15421 (let ((files (directory-files (or dir default-directory)
15422 nil "\\`[^.#].*\\.org\\'"))
15423 file visiting m buffer)
15424 (catch 'found
15425 (while (setq file (pop files))
15426 (message "trying %s" file)
15427 (setq visiting (org-find-base-buffer-visiting file))
15428 (setq buffer (or visiting (find-file-noselect file)))
15429 (setq m (org-find-exact-headline-in-buffer
15430 heading buffer))
15431 (when (and (not m) (not visiting)) (kill-buffer buffer))
15432 (and m (throw 'found m))))))
15434 (defun org-find-entry-with-id (ident)
15435 "Locate the entry that contains the ID property with exact value IDENT.
15436 IDENT can be a string, a symbol or a number, this function will search for
15437 the string representation of it.
15438 Return the position where this entry starts, or nil if there is no such entry."
15439 (interactive "sID: ")
15440 (let ((id (cond
15441 ((stringp ident) ident)
15442 ((symbol-name ident) (symbol-name ident))
15443 ((numberp ident) (number-to-string ident))
15444 (t (error "IDENT %s must be a string, symbol or number" ident))))
15445 (case-fold-search nil))
15446 (save-excursion
15447 (save-restriction
15448 (widen)
15449 (goto-char (point-min))
15450 (when (re-search-forward
15451 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15452 nil t)
15453 (org-back-to-heading t)
15454 (point))))))
15456 ;;;; Timestamps
15458 (defvar org-last-changed-timestamp nil)
15459 (defvar org-last-inserted-timestamp nil
15460 "The last time stamp inserted with `org-insert-time-stamp'.")
15461 (defvar org-time-was-given) ; dynamically scoped parameter
15462 (defvar org-end-time-was-given) ; dynamically scoped parameter
15463 (defvar org-ts-what) ; dynamically scoped parameter
15465 (defun org-time-stamp (arg &optional inactive)
15466 "Prompt for a date/time and insert a time stamp.
15467 If the user specifies a time like HH:MM or if this command is
15468 called with at least one prefix argument, the time stamp contains
15469 the date and the time. Otherwise, only the date is be included.
15471 All parts of a date not specified by the user is filled in from
15472 the current date/time. So if you just press return without
15473 typing anything, the time stamp will represent the current
15474 date/time.
15476 If there is already a timestamp at the cursor, it will be
15477 modified.
15479 With two universal prefix arguments, insert an active timestamp
15480 with the current time without prompting the user."
15481 (interactive "P")
15482 (let* ((ts nil)
15483 (default-time
15484 ;; Default time is either today, or, when entering a range,
15485 ;; the range start.
15486 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15487 (save-excursion
15488 (re-search-backward
15489 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15490 (- (point) 20) t)))
15491 (apply 'encode-time (org-parse-time-string (match-string 1)))
15492 (current-time)))
15493 (default-input (and ts (org-get-compact-tod ts)))
15494 (repeater (save-excursion
15495 (save-match-data
15496 (beginning-of-line)
15497 (when (re-search-forward
15498 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15499 (save-excursion (progn (end-of-line) (point))) t)
15500 (match-string 0)))))
15501 org-time-was-given org-end-time-was-given time)
15502 (cond
15503 ((and (org-at-timestamp-p t)
15504 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15505 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15506 (insert "--")
15507 (setq time (let ((this-command this-command))
15508 (org-read-date arg 'totime nil nil
15509 default-time default-input inactive)))
15510 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15511 ((org-at-timestamp-p t)
15512 (setq time (let ((this-command this-command))
15513 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15514 (when (org-at-timestamp-p t) ; just to get the match data
15515 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15516 (replace-match "")
15517 (setq org-last-changed-timestamp
15518 (org-insert-time-stamp
15519 time (or org-time-was-given arg)
15520 inactive nil nil (list org-end-time-was-given)))
15521 (when repeater (goto-char (1- (point))) (insert " " repeater)
15522 (setq org-last-changed-timestamp
15523 (concat (substring org-last-inserted-timestamp 0 -1)
15524 " " repeater ">"))))
15525 (message "Timestamp updated"))
15526 ((equal arg '(16))
15527 (org-insert-time-stamp (current-time) t))
15529 (setq time (let ((this-command this-command))
15530 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15531 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15532 nil nil (list org-end-time-was-given))))))
15534 ;; FIXME: can we use this for something else, like computing time differences?
15535 (defun org-get-compact-tod (s)
15536 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15537 (let* ((t1 (match-string 1 s))
15538 (h1 (string-to-number (match-string 2 s)))
15539 (m1 (string-to-number (match-string 3 s)))
15540 (t2 (and (match-end 4) (match-string 5 s)))
15541 (h2 (and t2 (string-to-number (match-string 6 s))))
15542 (m2 (and t2 (string-to-number (match-string 7 s))))
15543 dh dm)
15544 (if (not t2)
15546 (setq dh (- h2 h1) dm (- m2 m1))
15547 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15548 (concat t1 "+" (number-to-string dh)
15549 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15551 (defun org-time-stamp-inactive (&optional arg)
15552 "Insert an inactive time stamp.
15553 An inactive time stamp is enclosed in square brackets instead of angle
15554 brackets. It is inactive in the sense that it does not trigger agenda entries,
15555 does not link to the calendar and cannot be changed with the S-cursor keys.
15556 So these are more for recording a certain time/date."
15557 (interactive "P")
15558 (org-time-stamp arg 'inactive))
15560 (defvar org-date-ovl (make-overlay 1 1))
15561 (overlay-put org-date-ovl 'face 'org-date-selected)
15562 (org-detach-overlay org-date-ovl)
15564 (defvar org-ans1) ; dynamically scoped parameter
15565 (defvar org-ans2) ; dynamically scoped parameter
15567 (defvar org-plain-time-of-day-regexp) ; defined below
15569 (defvar org-overriding-default-time nil) ; dynamically scoped
15570 (defvar org-read-date-overlay nil)
15571 (defvar org-dcst nil) ; dynamically scoped
15572 (defvar org-read-date-history nil)
15573 (defvar org-read-date-final-answer nil)
15574 (defvar org-read-date-analyze-futurep nil)
15575 (defvar org-read-date-analyze-forced-year nil)
15576 (defvar org-read-date-inactive)
15578 (defvar org-read-date-minibuffer-local-map
15579 (let ((map (make-sparse-keymap)))
15580 (set-keymap-parent map minibuffer-local-map)
15581 (org-defkey map [(meta shift left)]
15582 (lambda () (interactive)
15583 (org-eval-in-calendar '(calendar-backward-month 1))))
15584 (org-defkey map [(meta shift right)]
15585 (lambda () (interactive)
15586 (org-eval-in-calendar '(calendar-forward-month 1))))
15587 (org-defkey map [(meta shift up)]
15588 (lambda () (interactive)
15589 (org-eval-in-calendar '(calendar-backward-year 1))))
15590 (org-defkey map [(meta shift down)]
15591 (lambda () (interactive)
15592 (org-eval-in-calendar '(calendar-forward-year 1))))
15593 (org-defkey map [?\e (shift left)]
15594 (lambda () (interactive)
15595 (org-eval-in-calendar '(calendar-backward-month 1))))
15596 (org-defkey map [?\e (shift right)]
15597 (lambda () (interactive)
15598 (org-eval-in-calendar '(calendar-forward-month 1))))
15599 (org-defkey map [?\e (shift up)]
15600 (lambda () (interactive)
15601 (org-eval-in-calendar '(calendar-backward-year 1))))
15602 (org-defkey map [?\e (shift down)]
15603 (lambda () (interactive)
15604 (org-eval-in-calendar '(calendar-forward-year 1))))
15605 (org-defkey map [(shift up)]
15606 (lambda () (interactive)
15607 (org-eval-in-calendar '(calendar-backward-week 1))))
15608 (org-defkey map [(shift down)]
15609 (lambda () (interactive)
15610 (org-eval-in-calendar '(calendar-forward-week 1))))
15611 (org-defkey map [(shift left)]
15612 (lambda () (interactive)
15613 (org-eval-in-calendar '(calendar-backward-day 1))))
15614 (org-defkey map [(shift right)]
15615 (lambda () (interactive)
15616 (org-eval-in-calendar '(calendar-forward-day 1))))
15617 (org-defkey map "?"
15618 (lambda () (interactive)
15619 (org-eval-in-calendar '(diary-view-entries))
15620 (message "")))
15621 (org-defkey map ">"
15622 (lambda () (interactive)
15623 (org-eval-in-calendar '(scroll-calendar-left 1))))
15624 (org-defkey map "<"
15625 (lambda () (interactive)
15626 (org-eval-in-calendar '(scroll-calendar-right 1))))
15627 (org-defkey map "\C-v"
15628 (lambda () (interactive)
15629 (org-eval-in-calendar
15630 '(calendar-scroll-left-three-months 1))))
15631 (org-defkey map "\M-v"
15632 (lambda () (interactive)
15633 (org-eval-in-calendar
15634 '(calendar-scroll-right-three-months 1))))
15635 map)
15636 "Keymap for minibuffer commands when using `org-read-date'.")
15638 (defun org-read-date (&optional org-with-time to-time from-string prompt
15639 default-time default-input inactive)
15640 "Read a date, possibly a time, and make things smooth for the user.
15641 The prompt will suggest to enter an ISO date, but you can also enter anything
15642 which will at least partially be understood by `parse-time-string'.
15643 Unrecognized parts of the date will default to the current day, month, year,
15644 hour and minute. If this command is called to replace a timestamp at point,
15645 or to enter the second timestamp of a range, the default time is taken
15646 from the existing stamp. Furthermore, the command prefers the future,
15647 so if you are giving a date where the year is not given, and the day-month
15648 combination is already past in the current year, it will assume you
15649 mean next year. For details, see the manual. A few examples:
15651 3-2-5 --> 2003-02-05
15652 feb 15 --> currentyear-02-15
15653 2/15 --> currentyear-02-15
15654 sep 12 9 --> 2009-09-12
15655 12:45 --> today 12:45
15656 22 sept 0:34 --> currentyear-09-22 0:34
15657 12 --> currentyear-currentmonth-12
15658 Fri --> nearest Friday (today or later)
15659 etc.
15661 Furthermore you can specify a relative date by giving, as the *first* thing
15662 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15663 change in days weeks, months, years.
15664 With a single plus or minus, the date is relative to today. With a double
15665 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15666 +4d --> four days from today
15667 +4 --> same as above
15668 +2w --> two weeks from today
15669 ++5 --> five days from default date
15671 The function understands only English month and weekday abbreviations.
15673 While prompting, a calendar is popped up - you can also select the
15674 date with the mouse (button 1). The calendar shows a period of three
15675 months. To scroll it to other months, use the keys `>' and `<'.
15676 If you don't like the calendar, turn it off with
15677 \(setq org-read-date-popup-calendar nil)
15679 With optional argument TO-TIME, the date will immediately be converted
15680 to an internal time.
15681 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15682 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15683 still enter a time, and this function will inform the calling routine
15684 about this change. The calling routine may then choose to change the
15685 format used to insert the time stamp into the buffer to include the time.
15686 With optional argument FROM-STRING, read from this string instead from
15687 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15688 the time/date that is used for everything that is not specified by the
15689 user."
15690 (require 'parse-time)
15691 (let* ((org-time-stamp-rounding-minutes
15692 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15693 (org-dcst org-display-custom-times)
15694 (ct (org-current-time))
15695 (org-def (or org-overriding-default-time default-time ct))
15696 (org-defdecode (decode-time org-def))
15697 (dummy (progn
15698 (when (< (nth 2 org-defdecode) org-extend-today-until)
15699 (setcar (nthcdr 2 org-defdecode) -1)
15700 (setcar (nthcdr 1 org-defdecode) 59)
15701 (setq org-def (apply 'encode-time org-defdecode)
15702 org-defdecode (decode-time org-def)))))
15703 (mouse-autoselect-window nil) ; Don't let the mouse jump
15704 (calendar-frame-setup nil)
15705 (calendar-setup nil)
15706 (calendar-move-hook nil)
15707 (calendar-view-diary-initially-flag nil)
15708 (calendar-view-holidays-initially-flag nil)
15709 (timestr (format-time-string
15710 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15711 (prompt (concat (if prompt (concat prompt " ") "")
15712 (format "Date+time [%s]: " timestr)))
15713 ans (org-ans0 "") org-ans1 org-ans2 final)
15715 (cond
15716 (from-string (setq ans from-string))
15717 (org-read-date-popup-calendar
15718 (save-excursion
15719 (save-window-excursion
15720 (calendar)
15721 (org-eval-in-calendar '(setq cursor-type nil) t)
15722 (unwind-protect
15723 (progn
15724 (calendar-forward-day (- (time-to-days org-def)
15725 (calendar-absolute-from-gregorian
15726 (calendar-current-date))))
15727 (org-eval-in-calendar nil t)
15728 (let* ((old-map (current-local-map))
15729 (map (copy-keymap calendar-mode-map))
15730 (minibuffer-local-map
15731 (copy-keymap org-read-date-minibuffer-local-map)))
15732 (org-defkey map (kbd "RET") 'org-calendar-select)
15733 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15734 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15735 (unwind-protect
15736 (progn
15737 (use-local-map map)
15738 (setq org-read-date-inactive inactive)
15739 (add-hook 'post-command-hook 'org-read-date-display)
15740 (setq org-ans0 (read-string prompt default-input
15741 'org-read-date-history nil))
15742 ;; org-ans0: from prompt
15743 ;; org-ans1: from mouse click
15744 ;; org-ans2: from calendar motion
15745 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15746 (remove-hook 'post-command-hook 'org-read-date-display)
15747 (use-local-map old-map)
15748 (when org-read-date-overlay
15749 (delete-overlay org-read-date-overlay)
15750 (setq org-read-date-overlay nil)))))
15751 (bury-buffer "*Calendar*")))))
15753 (t ; Naked prompt only
15754 (unwind-protect
15755 (setq ans (read-string prompt default-input
15756 'org-read-date-history timestr))
15757 (when org-read-date-overlay
15758 (delete-overlay org-read-date-overlay)
15759 (setq org-read-date-overlay nil)))))
15761 (setq final (org-read-date-analyze ans org-def org-defdecode))
15763 (when org-read-date-analyze-forced-year
15764 (message "Year was forced into %s"
15765 (if org-read-date-force-compatible-dates
15766 "compatible range (1970-2037)"
15767 "range representable on this machine"))
15768 (ding))
15770 ;; One round trip to get rid of 34th of August and stuff like that....
15771 (setq final (decode-time (apply 'encode-time final)))
15773 (setq org-read-date-final-answer ans)
15775 (if to-time
15776 (apply 'encode-time final)
15777 (if (and (boundp 'org-time-was-given) org-time-was-given)
15778 (format "%04d-%02d-%02d %02d:%02d"
15779 (nth 5 final) (nth 4 final) (nth 3 final)
15780 (nth 2 final) (nth 1 final))
15781 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15783 (defvar org-def)
15784 (defvar org-defdecode)
15785 (defvar org-with-time)
15786 (defun org-read-date-display ()
15787 "Display the current date prompt interpretation in the minibuffer."
15788 (when org-read-date-display-live
15789 (when org-read-date-overlay
15790 (delete-overlay org-read-date-overlay))
15791 (when (minibufferp (current-buffer))
15792 (save-excursion
15793 (end-of-line 1)
15794 (while (not (equal (buffer-substring
15795 (max (point-min) (- (point) 4)) (point))
15796 " "))
15797 (insert " ")))
15798 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15799 " " (or org-ans1 org-ans2)))
15800 (org-end-time-was-given nil)
15801 (f (org-read-date-analyze ans org-def org-defdecode))
15802 (fmts (if org-dcst
15803 org-time-stamp-custom-formats
15804 org-time-stamp-formats))
15805 (fmt (if (or org-with-time
15806 (and (boundp 'org-time-was-given) org-time-was-given))
15807 (cdr fmts)
15808 (car fmts)))
15809 (txt (format-time-string fmt (apply 'encode-time f)))
15810 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15811 (txt (concat "=> " txt)))
15812 (when (and org-end-time-was-given
15813 (string-match org-plain-time-of-day-regexp txt))
15814 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15815 org-end-time-was-given
15816 (substring txt (match-end 0)))))
15817 (when org-read-date-analyze-futurep
15818 (setq txt (concat txt " (=>F)")))
15819 (setq org-read-date-overlay
15820 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15821 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15823 (defun org-read-date-analyze (ans org-def org-defdecode)
15824 "Analyze the combined answer of the date prompt."
15825 ;; FIXME: cleanup and comment
15826 (let ((nowdecode (decode-time (current-time)))
15827 delta deltan deltaw deltadef year month day
15828 hour minute second wday pm h2 m2 tl wday1
15829 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15830 (setq org-read-date-analyze-futurep nil
15831 org-read-date-analyze-forced-year nil)
15832 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15833 (setq ans "+0"))
15835 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15836 (setq ans (replace-match "" t t ans)
15837 deltan (car delta)
15838 deltaw (nth 1 delta)
15839 deltadef (nth 2 delta)))
15841 ;; Check if there is an iso week date in there. If yes, store the
15842 ;; info and postpone interpreting it until the rest of the parsing
15843 ;; is done.
15844 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15845 (setq iso-year (if (match-end 1)
15846 (org-small-year-to-year
15847 (string-to-number (match-string 1 ans))))
15848 iso-weekday (if (match-end 3)
15849 (string-to-number (match-string 3 ans)))
15850 iso-week (string-to-number (match-string 2 ans)))
15851 (setq ans (replace-match "" t t ans)))
15853 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15854 (when (string-match
15855 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15856 (setq year (if (match-end 2)
15857 (string-to-number (match-string 2 ans))
15858 (progn (setq kill-year t)
15859 (string-to-number (format-time-string "%Y"))))
15860 month (string-to-number (match-string 3 ans))
15861 day (string-to-number (match-string 4 ans)))
15862 (if (< year 100) (setq year (+ 2000 year)))
15863 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15864 t nil ans)))
15866 ;; Help matching dotted european dates
15867 (when (string-match
15868 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15869 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15870 (setq kill-year t)
15871 (string-to-number (format-time-string "%Y")))
15872 day (string-to-number (match-string 1 ans))
15873 month (string-to-number (match-string 2 ans))
15874 ans (replace-match (format "%04d-%02d-%02d" year month day)
15875 t nil ans)))
15877 ;; Help matching american dates, like 5/30 or 5/30/7
15878 (when (string-match
15879 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15880 (setq year (if (match-end 4)
15881 (string-to-number (match-string 4 ans))
15882 (progn (setq kill-year t)
15883 (string-to-number (format-time-string "%Y"))))
15884 month (string-to-number (match-string 1 ans))
15885 day (string-to-number (match-string 2 ans)))
15886 (if (< year 100) (setq year (+ 2000 year)))
15887 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15888 t nil ans)))
15889 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15890 ;; If there is a time with am/pm, and *no* time without it, we convert
15891 ;; so that matching will be successful.
15892 (loop for i from 1 to 2 do ; twice, for end time as well
15893 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15894 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15895 (setq hour (string-to-number (match-string 1 ans))
15896 minute (if (match-end 3)
15897 (string-to-number (match-string 3 ans))
15899 pm (equal ?p
15900 (string-to-char (downcase (match-string 4 ans)))))
15901 (if (and (= hour 12) (not pm))
15902 (setq hour 0)
15903 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15904 (setq ans (replace-match (format "%02d:%02d" hour minute)
15905 t t ans))))
15907 ;; Check if a time range is given as a duration
15908 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15909 (setq hour (string-to-number (match-string 1 ans))
15910 h2 (+ hour (string-to-number (match-string 3 ans)))
15911 minute (string-to-number (match-string 2 ans))
15912 m2 (+ minute (if (match-end 5) (string-to-number
15913 (match-string 5 ans))0)))
15914 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15915 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15916 t t ans)))
15918 ;; Check if there is a time range
15919 (when (boundp 'org-end-time-was-given)
15920 (setq org-time-was-given nil)
15921 (when (and (string-match org-plain-time-of-day-regexp ans)
15922 (match-end 8))
15923 (setq org-end-time-was-given (match-string 8 ans))
15924 (setq ans (concat (substring ans 0 (match-beginning 7))
15925 (substring ans (match-end 7))))))
15927 (setq tl (parse-time-string ans)
15928 day (or (nth 3 tl) (nth 3 org-defdecode))
15929 month (or (nth 4 tl)
15930 (if (and org-read-date-prefer-future
15931 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15932 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15933 (nth 4 org-defdecode)))
15934 year (or (and (not kill-year) (nth 5 tl))
15935 (if (and org-read-date-prefer-future
15936 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15937 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15938 (nth 5 org-defdecode)))
15939 hour (or (nth 2 tl) (nth 2 org-defdecode))
15940 minute (or (nth 1 tl) (nth 1 org-defdecode))
15941 second (or (nth 0 tl) 0)
15942 wday (nth 6 tl))
15944 (when (and (eq org-read-date-prefer-future 'time)
15945 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15946 (equal day (nth 3 nowdecode))
15947 (equal month (nth 4 nowdecode))
15948 (equal year (nth 5 nowdecode))
15949 (nth 2 tl)
15950 (or (< (nth 2 tl) (nth 2 nowdecode))
15951 (and (= (nth 2 tl) (nth 2 nowdecode))
15952 (nth 1 tl)
15953 (< (nth 1 tl) (nth 1 nowdecode)))))
15954 (setq day (1+ day)
15955 futurep t))
15957 ;; Special date definitions below
15958 (cond
15959 (iso-week
15960 ;; There was an iso week
15961 (require 'cal-iso)
15962 (setq futurep nil)
15963 (setq year (or iso-year year)
15964 day (or iso-weekday wday 1)
15965 wday nil ; to make sure that the trigger below does not match
15966 iso-date (calendar-gregorian-from-absolute
15967 (calendar-absolute-from-iso
15968 (list iso-week day year))))
15969 ; FIXME: Should we also push ISO weeks into the future?
15970 ; (when (and org-read-date-prefer-future
15971 ; (not iso-year)
15972 ; (< (calendar-absolute-from-gregorian iso-date)
15973 ; (time-to-days (current-time))))
15974 ; (setq year (1+ year)
15975 ; iso-date (calendar-gregorian-from-absolute
15976 ; (calendar-absolute-from-iso
15977 ; (list iso-week day year)))))
15978 (setq month (car iso-date)
15979 year (nth 2 iso-date)
15980 day (nth 1 iso-date)))
15981 (deltan
15982 (setq futurep nil)
15983 (unless deltadef
15984 (let ((now (decode-time (current-time))))
15985 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15986 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15987 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15988 ((equal deltaw "m") (setq month (+ month deltan)))
15989 ((equal deltaw "y") (setq year (+ year deltan)))))
15990 ((and wday (not (nth 3 tl)))
15991 ;; Weekday was given, but no day, so pick that day in the week
15992 ;; on or after the derived date.
15993 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15994 (unless (equal wday wday1)
15995 (setq day (+ day (% (- wday wday1 -7) 7))))))
15996 (if (and (boundp 'org-time-was-given)
15997 (nth 2 tl))
15998 (setq org-time-was-given t))
15999 (if (< year 100) (setq year (+ 2000 year)))
16000 ;; Check of the date is representable
16001 (if org-read-date-force-compatible-dates
16002 (progn
16003 (if (< year 1970)
16004 (setq year 1970 org-read-date-analyze-forced-year t))
16005 (if (> year 2037)
16006 (setq year 2037 org-read-date-analyze-forced-year t)))
16007 (condition-case nil
16008 (ignore (encode-time second minute hour day month year))
16009 (error
16010 (setq year (nth 5 org-defdecode))
16011 (setq org-read-date-analyze-forced-year t))))
16012 (setq org-read-date-analyze-futurep futurep)
16013 (list second minute hour day month year)))
16015 (defvar parse-time-weekdays)
16016 (defun org-read-date-get-relative (s today default)
16017 "Check string S for special relative date string.
16018 TODAY and DEFAULT are internal times, for today and for a default.
16019 Return shift list (N what def-flag)
16020 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16021 N is the number of WHATs to shift.
16022 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16023 the DEFAULT date rather than TODAY."
16024 (require 'parse-time)
16025 (when (and
16026 (string-match
16027 (concat
16028 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16029 "\\([0-9]+\\)?"
16030 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16031 "\\([ \t]\\|$\\)") s)
16032 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16033 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16034 (string-to-char (substring (match-string 1 s) -1))
16035 ?+))
16036 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16037 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16038 (what (if (match-end 3) (match-string 3 s) "d"))
16039 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16040 (date (if rel default today))
16041 (wday (nth 6 (decode-time date)))
16042 delta)
16043 (if wday1
16044 (progn
16045 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16046 (if (= dir ?-) (setq delta (- delta 7)))
16047 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16048 (list delta "d" rel))
16049 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16051 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16052 "Turn a user-specified date into the internal representation.
16053 The internal representation needed by the calendar is (month day year).
16054 This is a wrapper to handle the brain-dead convention in calendar that
16055 user function argument order change dependent on argument order."
16056 (if (boundp 'calendar-date-style)
16057 (cond
16058 ((eq calendar-date-style 'american)
16059 (list arg1 arg2 arg3))
16060 ((eq calendar-date-style 'european)
16061 (list arg2 arg1 arg3))
16062 ((eq calendar-date-style 'iso)
16063 (list arg2 arg3 arg1)))
16064 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16065 (if (org-bound-and-true-p european-calendar-style)
16066 (list arg2 arg1 arg3)
16067 (list arg1 arg2 arg3)))))
16069 (defun org-eval-in-calendar (form &optional keepdate)
16070 "Eval FORM in the calendar window and return to current window.
16071 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16072 otherwise stick to the current value of `org-ans2'."
16073 (let ((sf (selected-frame))
16074 (sw (selected-window)))
16075 (select-window (get-buffer-window "*Calendar*" t))
16076 (eval form)
16077 (when (and (not keepdate) (calendar-cursor-to-date))
16078 (let* ((date (calendar-cursor-to-date))
16079 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16080 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16081 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16082 (select-window sw)
16083 (org-select-frame-set-input-focus sf)))
16085 (defun org-calendar-select ()
16086 "Return to `org-read-date' with the date currently selected.
16087 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16088 (interactive)
16089 (when (calendar-cursor-to-date)
16090 (let* ((date (calendar-cursor-to-date))
16091 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16092 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16093 (if (active-minibuffer-window) (exit-minibuffer))))
16095 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16096 "Insert a date stamp for the date given by the internal TIME.
16097 WITH-HM means use the stamp format that includes the time of the day.
16098 INACTIVE means use square brackets instead of angular ones, so that the
16099 stamp will not contribute to the agenda.
16100 PRE and POST are optional strings to be inserted before and after the
16101 stamp.
16102 The command returns the inserted time stamp."
16103 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16104 stamp)
16105 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16106 (insert-before-markers (or pre ""))
16107 (when (listp extra)
16108 (setq extra (car extra))
16109 (if (and (stringp extra)
16110 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16111 (setq extra (format "-%02d:%02d"
16112 (string-to-number (match-string 1 extra))
16113 (string-to-number (match-string 2 extra))))
16114 (setq extra nil)))
16115 (when extra
16116 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16117 (insert-before-markers (setq stamp (format-time-string fmt time)))
16118 (insert-before-markers (or post ""))
16119 (setq org-last-inserted-timestamp stamp)))
16121 (defun org-toggle-time-stamp-overlays ()
16122 "Toggle the use of custom time stamp formats."
16123 (interactive)
16124 (setq org-display-custom-times (not org-display-custom-times))
16125 (unless org-display-custom-times
16126 (let ((p (point-min)) (bmp (buffer-modified-p)))
16127 (while (setq p (next-single-property-change p 'display))
16128 (if (and (get-text-property p 'display)
16129 (eq (get-text-property p 'face) 'org-date))
16130 (remove-text-properties
16131 p (setq p (next-single-property-change p 'display))
16132 '(display t))))
16133 (set-buffer-modified-p bmp)))
16134 (if (featurep 'xemacs)
16135 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16136 (org-restart-font-lock)
16137 (setq org-table-may-need-update t)
16138 (if org-display-custom-times
16139 (message "Time stamps are overlaid with custom format")
16140 (message "Time stamp overlays removed")))
16142 (defun org-display-custom-time (beg end)
16143 "Overlay modified time stamp format over timestamp between BEG and END."
16144 (let* ((ts (buffer-substring beg end))
16145 t1 w1 with-hm tf time str w2 (off 0))
16146 (save-match-data
16147 (setq t1 (org-parse-time-string ts t))
16148 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16149 (setq off (- (match-end 0) (match-beginning 0)))))
16150 (setq end (- end off))
16151 (setq w1 (- end beg)
16152 with-hm (and (nth 1 t1) (nth 2 t1))
16153 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16154 time (org-fix-decoded-time t1)
16155 str (org-add-props
16156 (format-time-string
16157 (substring tf 1 -1) (apply 'encode-time time))
16158 nil 'mouse-face 'highlight)
16159 w2 (length str))
16160 (if (not (= w2 w1))
16161 (add-text-properties (1+ beg) (+ 2 beg)
16162 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16163 (if (featurep 'xemacs)
16164 (progn
16165 (put-text-property beg end 'invisible t)
16166 (put-text-property beg end 'end-glyph (make-glyph str)))
16167 (put-text-property beg end 'display str))))
16169 (defun org-translate-time (string)
16170 "Translate all timestamps in STRING to custom format.
16171 But do this only if the variable `org-display-custom-times' is set."
16172 (when org-display-custom-times
16173 (save-match-data
16174 (let* ((start 0)
16175 (re org-ts-regexp-both)
16176 t1 with-hm inactive tf time str beg end)
16177 (while (setq start (string-match re string start))
16178 (setq beg (match-beginning 0)
16179 end (match-end 0)
16180 t1 (save-match-data
16181 (org-parse-time-string (substring string beg end) t))
16182 with-hm (and (nth 1 t1) (nth 2 t1))
16183 inactive (equal (substring string beg (1+ beg)) "[")
16184 tf (funcall (if with-hm 'cdr 'car)
16185 org-time-stamp-custom-formats)
16186 time (org-fix-decoded-time t1)
16187 str (format-time-string
16188 (concat
16189 (if inactive "[" "<") (substring tf 1 -1)
16190 (if inactive "]" ">"))
16191 (apply 'encode-time time))
16192 string (replace-match str t t string)
16193 start (+ start (length str)))))))
16194 string)
16196 (defun org-fix-decoded-time (time)
16197 "Set 0 instead of nil for the first 6 elements of time.
16198 Don't touch the rest."
16199 (let ((n 0))
16200 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16202 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16204 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16205 "Difference between TIMESTAMP-STRING and now in days.
16206 If SECONDS is non-nil, return the difference in seconds."
16207 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16208 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16209 (funcall fdiff (current-time)))))
16211 (defun org-deadline-close (timestamp-string &optional ndays)
16212 "Is the time in TIMESTAMP-STRING close to the current date?"
16213 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16214 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16215 (not (org-entry-is-done-p))))
16217 (defun org-get-wdays (ts)
16218 "Get the deadline lead time appropriate for timestring TS."
16219 (cond
16220 ((<= org-deadline-warning-days 0)
16221 ;; 0 or negative, enforce this value no matter what
16222 (- org-deadline-warning-days))
16223 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16224 ;; lead time is specified.
16225 (floor (* (string-to-number (match-string 1 ts))
16226 (cdr (assoc (match-string 2 ts)
16227 '(("d" . 1) ("w" . 7)
16228 ("m" . 30.4) ("y" . 365.25)))))))
16229 ;; go for the default.
16230 (t org-deadline-warning-days)))
16232 (defun org-calendar-select-mouse (ev)
16233 "Return to `org-read-date' with the date currently selected.
16234 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16235 (interactive "e")
16236 (mouse-set-point ev)
16237 (when (calendar-cursor-to-date)
16238 (let* ((date (calendar-cursor-to-date))
16239 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16240 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16241 (if (active-minibuffer-window) (exit-minibuffer))))
16243 (defun org-check-deadlines (ndays)
16244 "Check if there are any deadlines due or past due.
16245 A deadline is considered due if it happens within `org-deadline-warning-days'
16246 days from today's date. If the deadline appears in an entry marked DONE,
16247 it is not shown. The prefix arg NDAYS can be used to test that many
16248 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16249 (interactive "P")
16250 (let* ((org-warn-days
16251 (cond
16252 ((equal ndays '(4)) 100000)
16253 (ndays (prefix-numeric-value ndays))
16254 (t (abs org-deadline-warning-days))))
16255 (case-fold-search nil)
16256 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16257 (callback
16258 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16260 (message "%d deadlines past-due or due within %d days"
16261 (org-occur regexp nil callback)
16262 org-warn-days)))
16264 (defsubst org-re-timestamp (type)
16265 "Return a regexp for timestamp TYPE.
16266 Allowed values for TYPE are:
16268 all: all timestamps
16269 active: only active timestamps (<...>)
16270 inactive: only inactive timestamps ([...])
16271 scheduled: only scheduled timestamps
16272 deadline: only deadline timestamps
16274 When TYPE is nil, fall back on returning a regexp that matches
16275 both scheduled and deadline timestamps."
16276 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16277 ((eq type 'active) org-ts-regexp)
16278 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16279 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16280 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16281 ((eq type 'scheduled-or-deadline)
16282 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16284 (defun org-check-before-date (date)
16285 "Check if there are deadlines or scheduled entries before DATE."
16286 (interactive (list (org-read-date)))
16287 (let ((case-fold-search nil)
16288 (regexp (org-re-timestamp org-ts-type))
16289 (callback
16290 (lambda () (time-less-p
16291 (org-time-string-to-time (match-string 1))
16292 (org-time-string-to-time date)))))
16293 (message "%d entries before %s"
16294 (org-occur regexp nil callback) date)))
16296 (defun org-check-after-date (date)
16297 "Check if there are deadlines or scheduled entries after DATE."
16298 (interactive (list (org-read-date)))
16299 (let ((case-fold-search nil)
16300 (regexp (org-re-timestamp org-ts-type))
16301 (callback
16302 (lambda () (not
16303 (time-less-p
16304 (org-time-string-to-time (match-string 1))
16305 (org-time-string-to-time date))))))
16306 (message "%d entries after %s"
16307 (org-occur regexp nil callback) date)))
16309 (defun org-check-dates-range (start-date end-date)
16310 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16311 (interactive (list (org-read-date nil nil nil "Range starts")
16312 (org-read-date nil nil nil "Range end")))
16313 (let ((case-fold-search nil)
16314 (regexp (org-re-timestamp org-ts-type))
16315 (callback
16316 (lambda ()
16317 (let ((match (match-string 1)))
16318 (and
16319 (not (time-less-p
16320 (org-time-string-to-time match)
16321 (org-time-string-to-time start-date)))
16322 (time-less-p
16323 (org-time-string-to-time match)
16324 (org-time-string-to-time end-date)))))))
16325 (message "%d entries between %s and %s"
16326 (org-occur regexp nil callback) start-date end-date)))
16328 (defun org-evaluate-time-range (&optional to-buffer)
16329 "Evaluate a time range by computing the difference between start and end.
16330 Normally the result is just printed in the echo area, but with prefix arg
16331 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16332 If the time range is actually in a table, the result is inserted into the
16333 next column.
16334 For time difference computation, a year is assumed to be exactly 365
16335 days in order to avoid rounding problems."
16336 (interactive "P")
16338 (org-clock-update-time-maybe)
16339 (save-excursion
16340 (unless (org-at-date-range-p t)
16341 (goto-char (point-at-bol))
16342 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16343 (if (not (org-at-date-range-p t))
16344 (error "Not at a time-stamp range, and none found in current line")))
16345 (let* ((ts1 (match-string 1))
16346 (ts2 (match-string 2))
16347 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16348 (match-end (match-end 0))
16349 (time1 (org-time-string-to-time ts1))
16350 (time2 (org-time-string-to-time ts2))
16351 (t1 (org-float-time time1))
16352 (t2 (org-float-time time2))
16353 (diff (abs (- t2 t1)))
16354 (negative (< (- t2 t1) 0))
16355 ;; (ys (floor (* 365 24 60 60)))
16356 (ds (* 24 60 60))
16357 (hs (* 60 60))
16358 (fy "%dy %dd %02d:%02d")
16359 (fy1 "%dy %dd")
16360 (fd "%dd %02d:%02d")
16361 (fd1 "%dd")
16362 (fh "%02d:%02d")
16363 y d h m align)
16364 (if havetime
16365 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16367 d (floor (/ diff ds)) diff (mod diff ds)
16368 h (floor (/ diff hs)) diff (mod diff hs)
16369 m (floor (/ diff 60)))
16370 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16372 d (floor (+ (/ diff ds) 0.5))
16373 h 0 m 0))
16374 (if (not to-buffer)
16375 (message "%s" (org-make-tdiff-string y d h m))
16376 (if (org-at-table-p)
16377 (progn
16378 (goto-char match-end)
16379 (setq align t)
16380 (and (looking-at " *|") (goto-char (match-end 0))))
16381 (goto-char match-end))
16382 (if (looking-at
16383 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16384 (replace-match ""))
16385 (if negative (insert " -"))
16386 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16387 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16388 (insert " " (format fh h m))))
16389 (if align (org-table-align))
16390 (message "Time difference inserted")))))
16392 (defun org-make-tdiff-string (y d h m)
16393 (let ((fmt "")
16394 (l nil))
16395 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16396 l (push y l)))
16397 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16398 l (push d l)))
16399 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16400 l (push h l)))
16401 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16402 l (push m l)))
16403 (apply 'format fmt (nreverse l))))
16405 (defun org-time-string-to-time (s &optional buffer pos)
16406 "Convert a timestamp string into internal time."
16407 (condition-case errdata
16408 (apply 'encode-time (org-parse-time-string s))
16409 (error (error "Bad timestamp `%s'%s\nError was: %s"
16410 s (if (not (and buffer pos))
16412 (format " at %d in buffer `%s'" pos buffer))
16413 (cdr errdata)))))
16415 (defun org-time-string-to-seconds (s)
16416 "Convert a timestamp string to a number of seconds."
16417 (org-float-time (org-time-string-to-time s)))
16419 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16420 "Convert a time stamp to an absolute day number.
16421 If there is a specifier for a cyclic time stamp, get the closest date to
16422 DAYNR.
16423 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16424 The variable date is bound by the calendar when this is called."
16425 (cond
16426 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16427 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16428 daynr
16429 (+ daynr 1000)))
16430 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16431 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16432 (time-to-days (current-time))) (match-string 0 s)
16433 prefer show-all))
16434 (t (time-to-days
16435 (condition-case errdata
16436 (apply 'encode-time (org-parse-time-string s))
16437 (error (error "Bad timestamp `%s'%s\nError was: %s"
16438 s (if (not (and buffer pos))
16440 (format " at %d in buffer `%s'" pos buffer))
16441 (cdr errdata))))))))
16443 (defun org-days-to-iso-week (days)
16444 "Return the iso week number."
16445 (require 'cal-iso)
16446 (car (calendar-iso-from-absolute days)))
16448 (defun org-small-year-to-year (year)
16449 "Convert 2-digit years into 4-digit years.
16450 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16451 The year 2000 cannot be abbreviated. Any year larger than 99
16452 is returned unchanged."
16453 (if (< year 38)
16454 (setq year (+ 2000 year))
16455 (if (< year 100)
16456 (setq year (+ 1900 year))))
16457 year)
16459 (defun org-time-from-absolute (d)
16460 "Return the time corresponding to date D.
16461 D may be an absolute day number, or a calendar-type list (month day year)."
16462 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16463 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16465 (defun org-calendar-holiday ()
16466 "List of holidays, for Diary display in Org-mode."
16467 (require 'holidays)
16468 (let ((hl (funcall
16469 (if (fboundp 'calendar-check-holidays)
16470 'calendar-check-holidays 'check-calendar-holidays) date)))
16471 (if hl (mapconcat 'identity hl "; "))))
16473 (defun org-diary-sexp-entry (sexp entry date)
16474 "Process a SEXP diary ENTRY for DATE."
16475 (require 'diary-lib)
16476 (let ((result (if calendar-debug-sexp
16477 (let ((stack-trace-on-error t))
16478 (eval (car (read-from-string sexp))))
16479 (condition-case nil
16480 (eval (car (read-from-string sexp)))
16481 (error
16482 (beep)
16483 (message "Bad sexp at line %d in %s: %s"
16484 (org-current-line)
16485 (buffer-file-name) sexp)
16486 (sleep-for 2))))))
16487 (cond ((stringp result) (split-string result "; "))
16488 ((and (consp result)
16489 (not (consp (cdr result)))
16490 (stringp (cdr result))) (cdr result))
16491 ((and (consp result)
16492 (stringp (car result))) result)
16493 (result entry))))
16495 (defun org-diary-to-ical-string (frombuf)
16496 "Get iCalendar entries from diary entries in buffer FROMBUF.
16497 This uses the icalendar.el library."
16498 (let* ((tmpdir (if (featurep 'xemacs)
16499 (temp-directory)
16500 temporary-file-directory))
16501 (tmpfile (make-temp-name
16502 (expand-file-name "orgics" tmpdir)))
16503 buf rtn b e)
16504 (with-current-buffer frombuf
16505 (icalendar-export-region (point-min) (point-max) tmpfile)
16506 (setq buf (find-buffer-visiting tmpfile))
16507 (set-buffer buf)
16508 (goto-char (point-min))
16509 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16510 (setq b (match-beginning 0)))
16511 (goto-char (point-max))
16512 (if (re-search-backward "^END:VEVENT" nil t)
16513 (setq e (match-end 0)))
16514 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16515 (kill-buffer buf)
16516 (delete-file tmpfile)
16517 rtn))
16519 (defun org-closest-date (start current change prefer show-all)
16520 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16521 When PREFER is `past', return a date that is either CURRENT or past.
16522 When PREFER is `future', return a date that is either CURRENT or future.
16523 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16524 ;; Make the proper lists from the dates
16525 (catch 'exit
16526 (let ((a1 '(("h" . hour)
16527 ("d" . day)
16528 ("w" . week)
16529 ("m" . month)
16530 ("y" . year)))
16531 (shour (nth 2 (org-parse-time-string start)))
16532 dn dw sday cday n1 n2 n0
16533 d m y y1 y2 date1 date2 nmonths nm ny m2)
16535 (setq start (org-date-to-gregorian start)
16536 current (org-date-to-gregorian
16537 (if show-all
16538 current
16539 (time-to-days (current-time))))
16540 sday (calendar-absolute-from-gregorian start)
16541 cday (calendar-absolute-from-gregorian current))
16543 (if (<= cday sday) (throw 'exit sday))
16545 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16546 (setq dn (string-to-number (match-string 1 change))
16547 dw (cdr (assoc (match-string 2 change) a1)))
16548 (error "Invalid change specifier: %s" change))
16549 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16550 (cond
16551 ((eq dw 'hour)
16552 (let ((missing-hours
16553 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16554 dn)))
16555 (setq n1 (if (zerop missing-hours) cday
16556 (- cday (1+ (floor (/ missing-hours 24)))))
16557 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16558 ((eq dw 'day)
16559 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16560 n2 (+ n1 dn)))
16561 ((eq dw 'year)
16562 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16563 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16564 (setq date1 (list m d y1)
16565 n1 (calendar-absolute-from-gregorian date1)
16566 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16567 n2 (calendar-absolute-from-gregorian date2)))
16568 ((eq dw 'month)
16569 ;; approx number of month between the two dates
16570 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16571 ;; How often does dn fit in there?
16572 (setq d (nth 1 start) m (car start) y (nth 2 start)
16573 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16574 m (+ m nm)
16575 ny (floor (/ m 12))
16576 y (+ y ny)
16577 m (- m (* ny 12)))
16578 (while (> m 12) (setq m (- m 12) y (1+ y)))
16579 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16580 (setq m2 (+ m dn) y2 y)
16581 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16582 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16583 (while (<= n2 cday)
16584 (setq n1 n2 m m2 y y2)
16585 (setq m2 (+ m dn) y2 y)
16586 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16587 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16588 ;; Make sure n1 is the earlier date
16589 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16590 (if show-all
16591 (cond
16592 ((eq prefer 'past) (if (= cday n2) n2 n1))
16593 ((eq prefer 'future) (if (= cday n1) n1 n2))
16594 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16595 (cond
16596 ((eq prefer 'past) (if (= cday n2) n2 n1))
16597 ((eq prefer 'future) (if (= cday n1) n1 n2))
16598 (t (if (= cday n1) n1 n2)))))))
16600 (defun org-date-to-gregorian (date)
16601 "Turn any specification of DATE into a Gregorian date for the calendar."
16602 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16603 ((and (listp date) (= (length date) 3)) date)
16604 ((stringp date)
16605 (setq date (org-parse-time-string date))
16606 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16607 ((listp date)
16608 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16610 (defun org-parse-time-string (s &optional nodefault)
16611 "Parse the standard Org-mode time string.
16612 This should be a lot faster than the normal `parse-time-string'.
16613 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16614 hour and minute fields will be nil if not given."
16615 (cond ((string-match org-ts-regexp0 s)
16616 (list 0
16617 (if (or (match-beginning 8) (not nodefault))
16618 (string-to-number (or (match-string 8 s) "0")))
16619 (if (or (match-beginning 7) (not nodefault))
16620 (string-to-number (or (match-string 7 s) "0")))
16621 (string-to-number (match-string 4 s))
16622 (string-to-number (match-string 3 s))
16623 (string-to-number (match-string 2 s))
16624 nil nil nil))
16625 ((string-match "^<[^>]+>$" s)
16626 (decode-time (seconds-to-time (org-matcher-time s))))
16627 (t (error "Not a standard Org-mode time string: %s" s))))
16629 (defun org-timestamp-up (&optional arg)
16630 "Increase the date item at the cursor by one.
16631 If the cursor is on the year, change the year. If it is on the month,
16632 the day or the time, change that.
16633 With prefix ARG, change by that many units."
16634 (interactive "p")
16635 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16637 (defun org-timestamp-down (&optional arg)
16638 "Decrease the date item at the cursor by one.
16639 If the cursor is on the year, change the year. If it is on the month,
16640 the day or the time, change that.
16641 With prefix ARG, change by that many units."
16642 (interactive "p")
16643 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16645 (defun org-timestamp-up-day (&optional arg)
16646 "Increase the date in the time stamp by one day.
16647 With prefix ARG, change that many days."
16648 (interactive "p")
16649 (if (and (not (org-at-timestamp-p t))
16650 (org-at-heading-p))
16651 (org-todo 'up)
16652 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16654 (defun org-timestamp-down-day (&optional arg)
16655 "Decrease the date in the time stamp by one day.
16656 With prefix ARG, change that many days."
16657 (interactive "p")
16658 (if (and (not (org-at-timestamp-p t))
16659 (org-at-heading-p))
16660 (org-todo 'down)
16661 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16663 (defun org-at-timestamp-p (&optional inactive-ok)
16664 "Determine if the cursor is in or at a timestamp."
16665 (interactive)
16666 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16667 (pos (point))
16668 (ans (or (looking-at tsr)
16669 (save-excursion
16670 (skip-chars-backward "^[<\n\r\t")
16671 (if (> (point) (point-min)) (backward-char 1))
16672 (and (looking-at tsr)
16673 (> (- (match-end 0) pos) -1))))))
16674 (and ans
16675 (boundp 'org-ts-what)
16676 (setq org-ts-what
16677 (cond
16678 ((= pos (match-beginning 0)) 'bracket)
16679 ;; Point is considered to be "on the bracket" whether
16680 ;; it's really on it or right after it.
16681 ((= pos (1- (match-end 0))) 'bracket)
16682 ((= pos (match-end 0)) 'after)
16683 ((org-pos-in-match-range pos 2) 'year)
16684 ((org-pos-in-match-range pos 3) 'month)
16685 ((org-pos-in-match-range pos 7) 'hour)
16686 ((org-pos-in-match-range pos 8) 'minute)
16687 ((or (org-pos-in-match-range pos 4)
16688 (org-pos-in-match-range pos 5)) 'day)
16689 ((and (> pos (or (match-end 8) (match-end 5)))
16690 (< pos (match-end 0)))
16691 (- pos (or (match-end 8) (match-end 5))))
16692 (t 'day))))
16693 ans))
16695 (defun org-toggle-timestamp-type ()
16696 "Toggle the type (<active> or [inactive]) of a time stamp."
16697 (interactive)
16698 (when (org-at-timestamp-p t)
16699 (let ((beg (match-beginning 0)) (end (match-end 0))
16700 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16701 (save-excursion
16702 (goto-char beg)
16703 (while (re-search-forward "[][<>]" end t)
16704 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16705 t t)))
16706 (message "Timestamp is now %sactive"
16707 (if (equal (char-after beg) ?<) "" "in")))))
16709 (defvar org-clock-history) ; defined in org-clock.el
16710 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16711 (defun org-timestamp-change (n &optional what updown)
16712 "Change the date in the time stamp at point.
16713 The date will be changed by N times WHAT. WHAT can be `day', `month',
16714 `year', `minute', `second'. If WHAT is not given, the cursor position
16715 in the timestamp determines what will be changed."
16716 (let ((origin (point)) origin-cat
16717 with-hm inactive
16718 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16719 org-ts-what
16720 extra rem
16721 ts time time0 fixnext clrgx)
16722 (if (not (org-at-timestamp-p t))
16723 (error "Not at a timestamp"))
16724 (if (and (not what) (eq org-ts-what 'bracket))
16725 (org-toggle-timestamp-type)
16726 ;; Point isn't on brackets. Remember the part of the time-stamp
16727 ;; the point was in. Indeed, size of time-stamps may change,
16728 ;; but point must be kept in the same category nonetheless.
16729 (setq origin-cat org-ts-what)
16730 (if (and (not what) (not (eq org-ts-what 'day))
16731 org-display-custom-times
16732 (get-text-property (point) 'display)
16733 (not (get-text-property (1- (point)) 'display)))
16734 (setq org-ts-what 'day))
16735 (setq org-ts-what (or what org-ts-what)
16736 inactive (= (char-after (match-beginning 0)) ?\[)
16737 ts (match-string 0))
16738 (replace-match "")
16739 (if (string-match
16740 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16742 (setq extra (match-string 1 ts)))
16743 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16744 (setq with-hm t))
16745 (setq time0 (org-parse-time-string ts))
16746 (when (and updown
16747 (eq org-ts-what 'minute)
16748 (not current-prefix-arg))
16749 ;; This looks like s-up and s-down. Change by one rounding step.
16750 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16751 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16752 (setcar (cdr time0) (+ (nth 1 time0)
16753 (if (> n 0) (- rem) (- dm rem))))))
16754 (setq time
16755 (encode-time (or (car time0) 0)
16756 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16757 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16758 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16759 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16760 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16761 (nthcdr 6 time0)))
16762 (when (and (member org-ts-what '(hour minute))
16763 extra
16764 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16765 (setq extra (org-modify-ts-extra
16766 extra
16767 (if (eq org-ts-what 'hour) 2 5)
16768 n dm)))
16769 (when (integerp org-ts-what)
16770 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16771 (if (eq what 'calendar)
16772 (let ((cal-date (org-get-date-from-calendar)))
16773 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16774 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16775 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16776 (setcar time0 (or (car time0) 0))
16777 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16778 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16779 (setq time (apply 'encode-time time0))))
16780 ;; Insert the new time-stamp, and ensure point stays in the same
16781 ;; category as before (i.e. not after the last position in that
16782 ;; category).
16783 (let ((pos (point)))
16784 ;; Stay before inserted string. `save-excursion' is of no use.
16785 (setq org-last-changed-timestamp
16786 (org-insert-time-stamp time with-hm inactive nil nil extra))
16787 (goto-char pos))
16788 (save-match-data
16789 (looking-at org-ts-regexp3)
16790 (goto-char (cond
16791 ;; `day' category ends before `hour' if any, or at
16792 ;; the end of the day name.
16793 ((eq origin-cat 'day)
16794 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16795 ((eq origin-cat 'hour) (min (match-end 7) origin))
16796 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16797 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16798 ;; `year' and `month' have both fixed size: point
16799 ;; couldn't have moved into another part.
16800 (t origin))))
16801 ;; Update clock if on a CLOCK line.
16802 (org-clock-update-time-maybe)
16803 ;; Maybe adjust the closest clock in `org-clock-history'
16804 (when org-clock-adjust-closest
16805 (if (not (and (org-at-clock-log-p)
16806 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16807 org-clock-history))))))
16808 (message "No clock to adjust")
16809 (cond ((save-excursion ; fix previous clock?
16810 (re-search-backward org-ts-regexp0 nil t)
16811 (org-looking-back (concat org-clock-string " \\[")))
16812 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16813 ((save-excursion ; fix next clock?
16814 (re-search-backward org-ts-regexp0 nil t)
16815 (looking-at (concat org-ts-regexp0 "\\] =>")))
16816 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16817 (save-window-excursion
16818 ;; Find closest clock to point, adjust the previous/next one in history
16819 (let* ((p (save-excursion (org-back-to-heading t)))
16820 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16821 (clfixnth
16822 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16823 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16824 (if (not clfixpos)
16825 (message "No clock to adjust")
16826 (save-excursion
16827 (org-goto-marker-or-bmk clfixpos)
16828 (org-show-subtree)
16829 (when (re-search-forward clrgx nil t)
16830 (goto-char (match-beginning 1))
16831 (let (org-clock-adjust-closest)
16832 (org-timestamp-change n org-ts-what updown))
16833 (message "Clock adjusted in %s for heading: %s"
16834 (file-name-nondirectory (buffer-file-name))
16835 (org-get-heading t t)))))))))
16836 ;; Try to recenter the calendar window, if any.
16837 (if (and org-calendar-follow-timestamp-change
16838 (get-buffer-window "*Calendar*" t)
16839 (memq org-ts-what '(day month year)))
16840 (org-recenter-calendar (time-to-days time))))))
16842 (defun org-modify-ts-extra (s pos n dm)
16843 "Change the different parts of the lead-time and repeat fields in timestamp."
16844 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16845 ng h m new rem)
16846 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16847 (cond
16848 ((or (org-pos-in-match-range pos 2)
16849 (org-pos-in-match-range pos 3))
16850 (setq m (string-to-number (match-string 3 s))
16851 h (string-to-number (match-string 2 s)))
16852 (if (org-pos-in-match-range pos 2)
16853 (setq h (+ h n))
16854 (setq n (* dm (org-no-warnings (signum n))))
16855 (when (not (= 0 (setq rem (% m dm))))
16856 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16857 (setq m (+ m n)))
16858 (if (< m 0) (setq m (+ m 60) h (1- h)))
16859 (if (> m 59) (setq m (- m 60) h (1+ h)))
16860 (setq h (min 24 (max 0 h)))
16861 (setq ng 1 new (format "-%02d:%02d" h m)))
16862 ((org-pos-in-match-range pos 6)
16863 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16864 ((org-pos-in-match-range pos 5)
16865 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16867 ((org-pos-in-match-range pos 9)
16868 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16869 ((org-pos-in-match-range pos 8)
16870 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16872 (when ng
16873 (setq s (concat
16874 (substring s 0 (match-beginning ng))
16876 (substring s (match-end ng))))))
16879 (defun org-recenter-calendar (date)
16880 "If the calendar is visible, recenter it to DATE."
16881 (let ((cwin (get-buffer-window "*Calendar*" t)))
16882 (when cwin
16883 (let ((calendar-move-hook nil))
16884 (with-selected-window cwin
16885 (calendar-goto-date (if (listp date) date
16886 (calendar-gregorian-from-absolute date))))))))
16888 (defun org-goto-calendar (&optional arg)
16889 "Go to the Emacs calendar at the current date.
16890 If there is a time stamp in the current line, go to that date.
16891 A prefix ARG can be used to force the current date."
16892 (interactive "P")
16893 (let ((tsr org-ts-regexp) diff
16894 (calendar-move-hook nil)
16895 (calendar-view-holidays-initially-flag nil)
16896 (calendar-view-diary-initially-flag nil))
16897 (if (or (org-at-timestamp-p)
16898 (save-excursion
16899 (beginning-of-line 1)
16900 (looking-at (concat ".*" tsr))))
16901 (let ((d1 (time-to-days (current-time)))
16902 (d2 (time-to-days
16903 (org-time-string-to-time (match-string 1)))))
16904 (setq diff (- d2 d1))))
16905 (calendar)
16906 (calendar-goto-today)
16907 (if (and diff (not arg)) (calendar-forward-day diff))))
16909 (defun org-get-date-from-calendar ()
16910 "Return a list (month day year) of date at point in calendar."
16911 (with-current-buffer "*Calendar*"
16912 (save-match-data
16913 (calendar-cursor-to-date))))
16915 (defun org-date-from-calendar ()
16916 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16917 If there is already a time stamp at the cursor position, update it."
16918 (interactive)
16919 (if (org-at-timestamp-p t)
16920 (org-timestamp-change 0 'calendar)
16921 (let ((cal-date (org-get-date-from-calendar)))
16922 (org-insert-time-stamp
16923 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16925 (defcustom org-effort-durations
16926 `(("h" . 60)
16927 ("d" . ,(* 60 8))
16928 ("w" . ,(* 60 8 5))
16929 ("m" . ,(* 60 8 5 4))
16930 ("y" . ,(* 60 8 5 40)))
16931 "Conversion factor to minutes for an effort modifier.
16933 Each entry has the form (MODIFIER . MINUTES).
16935 In an effort string, a number followed by MODIFIER is multiplied
16936 by the specified number of MINUTES to obtain an effort in
16937 minutes.
16939 For example, if the value of this variable is ((\"hours\" . 60)), then an
16940 effort string \"2hours\" is equivalent to 120 minutes."
16941 :group 'org-agenda
16942 :version "24.1"
16943 :type '(alist :key-type (string :tag "Modifier")
16944 :value-type (number :tag "Minutes")))
16946 (defun org-minutes-to-clocksum-string (m)
16947 "Format number of minutes as a clocksum string.
16948 The format is determined by `org-time-clocksum-format',
16949 `org-time-clocksum-use-fractional' and
16950 `org-time-clocksum-fractional-format' and
16951 `org-time-clocksum-use-effort-durations'."
16952 (let ((clocksum "") h d w mo y fmt n)
16953 (setq h (if org-time-clocksum-use-effort-durations
16954 (cdr (assoc "h" org-effort-durations)) 60)
16955 d (if org-time-clocksum-use-effort-durations
16956 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
16957 w (if org-time-clocksum-use-effort-durations
16958 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
16959 mo (if org-time-clocksum-use-effort-durations
16960 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
16961 y (if org-time-clocksum-use-effort-durations
16962 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
16963 ;; fractional format
16964 (if org-time-clocksum-use-fractional
16965 (cond
16966 ;; single format string
16967 ((stringp org-time-clocksum-fractional-format)
16968 (format org-time-clocksum-fractional-format (/ m (float h))))
16969 ;; choice of fractional formats for different time units
16970 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16971 (> (/ (truncate m) (* y d h)) 0))
16972 (format fmt (/ m (* y d (float h)))))
16973 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16974 (> (/ (truncate m) (* mo d h)) 0))
16975 (format fmt (/ m (* mo d (float h)))))
16976 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16977 (> (/ (truncate m) (* w d h)) 0))
16978 (format fmt (/ m (* w d (float h)))))
16979 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16980 (> (/ (truncate m) (* d h)) 0))
16981 (format fmt (/ m (* d (float h)))))
16982 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16983 (> (/ (truncate m) h) 0))
16984 (format fmt (/ m (float h))))
16985 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16986 (format fmt m))
16987 ;; fall back to smallest time unit with a format
16988 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16989 (format fmt (/ m (float h))))
16990 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16991 (format fmt (/ m (* d (float h)))))
16992 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16993 (format fmt (/ m (* w d (float h)))))
16994 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16995 (format fmt (/ m (* mo d (float h)))))
16996 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16997 (format fmt (/ m (* y d (float h))))))
16998 ;; standard (non-fractional) format, with single format string
16999 (if (stringp org-time-clocksum-format)
17000 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17001 ;; separate formats components
17002 (and (setq fmt (plist-get org-time-clocksum-format :years))
17003 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17004 (plist-get org-time-clocksum-format :require-years))
17005 (setq clocksum (concat clocksum (format fmt n))
17006 m (- m (* n y d h))))
17007 (and (setq fmt (plist-get org-time-clocksum-format :months))
17008 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17009 (plist-get org-time-clocksum-format :require-months))
17010 (setq clocksum (concat clocksum (format fmt n))
17011 m (- m (* n mo d h))))
17012 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17013 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17014 (plist-get org-time-clocksum-format :require-weeks))
17015 (setq clocksum (concat clocksum (format fmt n))
17016 m (- m (* n w d h))))
17017 (and (setq fmt (plist-get org-time-clocksum-format :days))
17018 (or (> (setq n (/ (truncate m) (* d h))) 0)
17019 (plist-get org-time-clocksum-format :require-days))
17020 (setq clocksum (concat clocksum (format fmt n))
17021 m (- m (* n d h))))
17022 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17023 (or (> (setq n (/ (truncate m) h)) 0)
17024 (plist-get org-time-clocksum-format :require-hours))
17025 (setq clocksum (concat clocksum (format fmt n))
17026 m (- m (* n h))))
17027 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17028 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17029 (setq clocksum (concat clocksum (format fmt m))))
17030 ;; return formatted time duration
17031 clocksum))))
17033 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17034 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17035 "Org mode version 8.0")
17037 (defun org-hours-to-clocksum-string (n)
17038 (org-minutes-to-clocksum-string (* n 60)))
17040 (defun org-hh:mm-string-to-minutes (s)
17041 "Convert a string H:MM to a number of minutes.
17042 If the string is just a number, interpret it as minutes.
17043 In fact, the first hh:mm or number in the string will be taken,
17044 there can be extra stuff in the string.
17045 If no number is found, the return value is 0."
17046 (cond
17047 ((integerp s) s)
17048 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17049 (+ (* (string-to-number (match-string 1 s)) 60)
17050 (string-to-number (match-string 2 s))))
17051 ((string-match "\\([0-9]+\\)" s)
17052 (string-to-number (match-string 1 s)))
17053 (t 0)))
17055 (defcustom org-image-actual-width t
17056 "Should we use the actual width of images when inlining them?
17058 When set to `t', always use the image width.
17060 When set to a number, use imagemagick (when available) to set
17061 the image's width to this value.
17063 When set to a number in a list, try to get the width from the
17064 #+ATTR.* keyword if it matches a width specification like
17065 width=\"[0-9]+\", and fall back on that number if none is found.
17067 When set to nil, try to get the width from an #+ATTR.* keyword
17068 and fall back on the original width if none is found.
17070 This requires Emacs >= 24.1, build with imagemagick support."
17071 :group 'org-appearance
17072 :version "24.3"
17073 :type '(choice
17074 (const :tag "Use the image width" t)
17075 (integer :tag "Use a number of pixels")
17076 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17077 (const :tag "Use #+ATTR* or don't resize" nil)))
17079 (defcustom org-agenda-inhibit-startup t
17080 "Inhibit startup when preparing agenda buffers.
17081 When this variable is `t' (the default), the initialization of
17082 the Org agenda buffers is inhibited: e.g. the visibility state
17083 is not set, the tables are not re-aligned, etc."
17084 :type 'boolean
17085 :version "24.3"
17086 :group 'org-agenda)
17088 (defun org-duration-string-to-minutes (s &optional output-to-string)
17089 "Convert a duration string S to minutes.
17091 A bare number is interpreted as minutes, modifiers can be set by
17092 customizing `org-effort-durations' (which see).
17094 Entries containing a colon are interpreted as H:MM by
17095 `org-hh:mm-string-to-minutes'."
17096 (let ((result 0)
17097 (re (concat "\\([0-9.]+\\) *\\("
17098 (regexp-opt (mapcar 'car org-effort-durations))
17099 "\\)")))
17100 (while (string-match re s)
17101 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17102 (string-to-number (match-string 1 s))))
17103 (setq s (replace-match "" nil t s)))
17104 (setq result (floor result))
17105 (incf result (org-hh:mm-string-to-minutes s))
17106 (if output-to-string (number-to-string result) result)))
17108 ;;;; Files
17110 (defun org-save-all-org-buffers ()
17111 "Save all Org-mode buffers without user confirmation."
17112 (interactive)
17113 (message "Saving all Org-mode buffers...")
17114 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17115 (when (featurep 'org-id) (org-id-locations-save))
17116 (message "Saving all Org-mode buffers... done"))
17118 (defun org-revert-all-org-buffers ()
17119 "Revert all Org-mode buffers.
17120 Prompt for confirmation when there are unsaved changes.
17121 Be sure you know what you are doing before letting this function
17122 overwrite your changes.
17124 This function is useful in a setup where one tracks org files
17125 with a version control system, to revert on one machine after pulling
17126 changes from another. I believe the procedure must be like this:
17128 1. M-x org-save-all-org-buffers
17129 2. Pull changes from the other machine, resolve conflicts
17130 3. M-x org-revert-all-org-buffers"
17131 (interactive)
17132 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17133 (error "Abort"))
17134 (save-excursion
17135 (save-window-excursion
17136 (mapc
17137 (lambda (b)
17138 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17139 (with-current-buffer b buffer-file-name))
17140 (org-pop-to-buffer-same-window b)
17141 (revert-buffer t 'no-confirm)))
17142 (buffer-list))
17143 (when (and (featurep 'org-id) org-id-track-globally)
17144 (org-id-locations-load)))))
17146 ;;;; Agenda files
17148 ;;;###autoload
17149 (defun org-switchb (&optional arg)
17150 "Switch between Org buffers.
17151 With one prefix argument, restrict available buffers to files.
17152 With two prefix arguments, restrict available buffers to agenda files.
17154 Defaults to `iswitchb' for buffer name completion.
17155 Set `org-completion-use-ido' to make it use ido instead."
17156 (interactive "P")
17157 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17158 ((equal arg '(16)) (org-buffer-list 'agenda))
17159 (t (org-buffer-list))))
17160 (org-completion-use-iswitchb org-completion-use-iswitchb)
17161 (org-completion-use-ido org-completion-use-ido))
17162 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17163 (setq org-completion-use-iswitchb t))
17164 (org-pop-to-buffer-same-window
17165 (org-icompleting-read "Org buffer: "
17166 (mapcar 'list (mapcar 'buffer-name blist))
17167 nil t))))
17169 ;;; Define some older names previously used for this functionality
17170 ;;;###autoload
17171 (defalias 'org-ido-switchb 'org-switchb)
17172 ;;;###autoload
17173 (defalias 'org-iswitchb 'org-switchb)
17175 (defun org-buffer-list (&optional predicate exclude-tmp)
17176 "Return a list of Org buffers.
17177 PREDICATE can be `export', `files' or `agenda'.
17179 export restrict the list to Export buffers.
17180 files restrict the list to buffers visiting Org files.
17181 agenda restrict the list to buffers visiting agenda files.
17183 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17184 (let* ((bfn nil)
17185 (agenda-files (and (eq predicate 'agenda)
17186 (mapcar 'file-truename (org-agenda-files t))))
17187 (filter
17188 (cond
17189 ((eq predicate 'files)
17190 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17191 ((eq predicate 'export)
17192 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17193 ((eq predicate 'agenda)
17194 (lambda (b)
17195 (with-current-buffer b
17196 (and (derived-mode-p 'org-mode)
17197 (setq bfn (buffer-file-name b))
17198 (member (file-truename bfn) agenda-files)))))
17199 (t (lambda (b) (with-current-buffer b
17200 (or (derived-mode-p 'org-mode)
17201 (string-match "\*Org .*Export"
17202 (buffer-name b)))))))))
17203 (delq nil
17204 (mapcar
17205 (lambda(b)
17206 (if (and (funcall filter b)
17207 (or (not exclude-tmp)
17208 (not (string-match "tmp" (buffer-name b)))))
17210 nil))
17211 (buffer-list)))))
17213 (defun org-agenda-files (&optional unrestricted archives)
17214 "Get the list of agenda files.
17215 Optional UNRESTRICTED means return the full list even if a restriction
17216 is currently in place.
17217 When ARCHIVES is t, include all archive files that are really being
17218 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17219 `org-agenda-archives-mode' is t."
17220 (let ((files
17221 (cond
17222 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17223 ((stringp org-agenda-files) (org-read-agenda-file-list))
17224 ((listp org-agenda-files) org-agenda-files)
17225 (t (error "Invalid value of `org-agenda-files'")))))
17226 (setq files (apply 'append
17227 (mapcar (lambda (f)
17228 (if (file-directory-p f)
17229 (directory-files
17230 f t org-agenda-file-regexp)
17231 (list f)))
17232 files)))
17233 (when org-agenda-skip-unavailable-files
17234 (setq files (delq nil
17235 (mapcar (function
17236 (lambda (file)
17237 (and (file-readable-p file) file)))
17238 files))))
17239 (when (or (eq archives t)
17240 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17241 (setq files (org-add-archive-files files)))
17242 files))
17244 (defun org-agenda-file-p (&optional file)
17245 "Return non-nil, if FILE is an agenda file.
17246 If FILE is omitted, use the file associated with the current
17247 buffer."
17248 (member (or file (buffer-file-name))
17249 (org-agenda-files t)))
17251 (defun org-edit-agenda-file-list ()
17252 "Edit the list of agenda files.
17253 Depending on setup, this either uses customize to edit the variable
17254 `org-agenda-files', or it visits the file that is holding the list. In the
17255 latter case, the buffer is set up in a way that saving it automatically kills
17256 the buffer and restores the previous window configuration."
17257 (interactive)
17258 (if (stringp org-agenda-files)
17259 (let ((cw (current-window-configuration)))
17260 (find-file org-agenda-files)
17261 (org-set-local 'org-window-configuration cw)
17262 (org-add-hook 'after-save-hook
17263 (lambda ()
17264 (set-window-configuration
17265 (prog1 org-window-configuration
17266 (kill-buffer (current-buffer))))
17267 (org-install-agenda-files-menu)
17268 (message "New agenda file list installed"))
17269 nil 'local)
17270 (message "%s" (substitute-command-keys
17271 "Edit list and finish with \\[save-buffer]")))
17272 (customize-variable 'org-agenda-files)))
17274 (defun org-store-new-agenda-file-list (list)
17275 "Set new value for the agenda file list and save it correctly."
17276 (if (stringp org-agenda-files)
17277 (let ((fe (org-read-agenda-file-list t)) b u)
17278 (while (setq b (find-buffer-visiting org-agenda-files))
17279 (kill-buffer b))
17280 (with-temp-file org-agenda-files
17281 (insert
17282 (mapconcat
17283 (lambda (f) ;; Keep un-expanded entries.
17284 (if (setq u (assoc f fe))
17285 (cdr u)
17287 list "\n")
17288 "\n")))
17289 (let ((org-mode-hook nil) (org-inhibit-startup t)
17290 (org-insert-mode-line-in-empty-file nil))
17291 (setq org-agenda-files list)
17292 (customize-save-variable 'org-agenda-files org-agenda-files))))
17294 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17295 "Read the list of agenda files from a file.
17296 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17297 filenames, used by `org-store-new-agenda-file-list' to write back
17298 un-expanded file names."
17299 (when (file-directory-p org-agenda-files)
17300 (error "`org-agenda-files' cannot be a single directory"))
17301 (when (stringp org-agenda-files)
17302 (with-temp-buffer
17303 (insert-file-contents org-agenda-files)
17304 (mapcar
17305 (lambda (f)
17306 (let ((e (expand-file-name (substitute-in-file-name f)
17307 org-directory)))
17308 (if pair-with-expansion
17309 (cons e f)
17310 e)))
17311 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17313 ;;;###autoload
17314 (defun org-cycle-agenda-files ()
17315 "Cycle through the files in `org-agenda-files'.
17316 If the current buffer visits an agenda file, find the next one in the list.
17317 If the current buffer does not, find the first agenda file."
17318 (interactive)
17319 (let* ((fs (org-agenda-files t))
17320 (files (append fs (list (car fs))))
17321 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17322 file)
17323 (unless files (error "No agenda files"))
17324 (catch 'exit
17325 (while (setq file (pop files))
17326 (if (equal (file-truename file) tcf)
17327 (when (car files)
17328 (find-file (car files))
17329 (throw 'exit t))))
17330 (find-file (car fs)))
17331 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17333 (defun org-agenda-file-to-front (&optional to-end)
17334 "Move/add the current file to the top of the agenda file list.
17335 If the file is not present in the list, it is added to the front. If it is
17336 present, it is moved there. With optional argument TO-END, add/move to the
17337 end of the list."
17338 (interactive "P")
17339 (let ((org-agenda-skip-unavailable-files nil)
17340 (file-alist (mapcar (lambda (x)
17341 (cons (file-truename x) x))
17342 (org-agenda-files t)))
17343 (ctf (file-truename
17344 (or buffer-file-name
17345 (error "Please save the current buffer to a file"))))
17346 x had)
17347 (setq x (assoc ctf file-alist) had x)
17349 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17350 (if to-end
17351 (setq file-alist (append (delq x file-alist) (list x)))
17352 (setq file-alist (cons x (delq x file-alist))))
17353 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17354 (org-install-agenda-files-menu)
17355 (message "File %s to %s of agenda file list"
17356 (if had "moved" "added") (if to-end "end" "front"))))
17358 (defun org-remove-file (&optional file)
17359 "Remove current file from the list of files in variable `org-agenda-files'.
17360 These are the files which are being checked for agenda entries.
17361 Optional argument FILE means use this file instead of the current."
17362 (interactive)
17363 (let* ((org-agenda-skip-unavailable-files nil)
17364 (file (or file buffer-file-name
17365 (error "Current buffer does not visit a file")))
17366 (true-file (file-truename file))
17367 (afile (abbreviate-file-name file))
17368 (files (delq nil (mapcar
17369 (lambda (x)
17370 (if (equal true-file
17371 (file-truename x))
17372 nil x))
17373 (org-agenda-files t)))))
17374 (if (not (= (length files) (length (org-agenda-files t))))
17375 (progn
17376 (org-store-new-agenda-file-list files)
17377 (org-install-agenda-files-menu)
17378 (message "Removed file: %s" afile))
17379 (message "File was not in list: %s (not removed)" afile))))
17381 (defun org-file-menu-entry (file)
17382 (vector file (list 'find-file file) t))
17384 (defun org-check-agenda-file (file)
17385 "Make sure FILE exists. If not, ask user what to do."
17386 (when (not (file-exists-p file))
17387 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17388 (abbreviate-file-name file))
17389 (let ((r (downcase (read-char-exclusive))))
17390 (cond
17391 ((equal r ?r)
17392 (org-remove-file file)
17393 (throw 'nextfile t))
17394 (t (error "Abort"))))))
17396 (defun org-get-agenda-file-buffer (file)
17397 "Get a buffer visiting FILE. If the buffer needs to be created, add
17398 it to the list of buffers which might be released later."
17399 (let ((buf (org-find-base-buffer-visiting file)))
17400 (if buf
17401 buf ; just return it
17402 ;; Make a new buffer and remember it
17403 (setq buf (find-file-noselect file))
17404 (if buf (push buf org-agenda-new-buffers))
17405 buf)))
17407 (defun org-release-buffers (blist)
17408 "Release all buffers in list, asking the user for confirmation when needed.
17409 When a buffer is unmodified, it is just killed. When modified, it is saved
17410 \(if the user agrees) and then killed."
17411 (let (buf file)
17412 (while (setq buf (pop blist))
17413 (setq file (buffer-file-name buf))
17414 (when (and (buffer-modified-p buf)
17415 file
17416 (y-or-n-p (format "Save file %s? " file)))
17417 (with-current-buffer buf (save-buffer)))
17418 (kill-buffer buf))))
17420 (defun org-agenda-prepare-buffers (files)
17421 "Create buffers for all agenda files, protect archived trees and comments."
17422 (interactive)
17423 (let ((pa '(:org-archived t))
17424 (pc '(:org-comment t))
17425 (pall '(:org-archived t :org-comment t))
17426 (inhibit-read-only t)
17427 (org-inhibit-startup org-agenda-inhibit-startup)
17428 (rea (concat ":" org-archive-tag ":"))
17429 bmp file re)
17430 (save-excursion
17431 (save-restriction
17432 (while (setq file (pop files))
17433 (catch 'nextfile
17434 (if (bufferp file)
17435 (set-buffer file)
17436 (org-check-agenda-file file)
17437 (set-buffer (org-get-agenda-file-buffer file)))
17438 (widen)
17439 (setq bmp (buffer-modified-p))
17440 (org-refresh-category-properties)
17441 (org-refresh-properties org-effort-property 'org-effort)
17442 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17443 (setq org-todo-keywords-for-agenda
17444 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17445 (setq org-done-keywords-for-agenda
17446 (append org-done-keywords-for-agenda org-done-keywords))
17447 (setq org-todo-keyword-alist-for-agenda
17448 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17449 (setq org-drawers-for-agenda
17450 (append org-drawers-for-agenda org-drawers))
17451 (setq org-tag-alist-for-agenda
17452 (append org-tag-alist-for-agenda org-tag-alist))
17454 (save-excursion
17455 (remove-text-properties (point-min) (point-max) pall)
17456 (when org-agenda-skip-archived-trees
17457 (goto-char (point-min))
17458 (while (re-search-forward rea nil t)
17459 (if (org-at-heading-p t)
17460 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17461 (goto-char (point-min))
17462 (setq re (format org-heading-keyword-regexp-format
17463 org-comment-string))
17464 (while (re-search-forward re nil t)
17465 (add-text-properties
17466 (match-beginning 0) (org-end-of-subtree t) pc)))
17467 (set-buffer-modified-p bmp)))))
17468 (setq org-todo-keywords-for-agenda
17469 (org-uniquify org-todo-keywords-for-agenda))
17470 (setq org-todo-keyword-alist-for-agenda
17471 (org-uniquify org-todo-keyword-alist-for-agenda)
17472 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17474 ;;;; Embedded LaTeX
17476 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17477 "Keymap for the minor `org-cdlatex-mode'.")
17479 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17480 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17481 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17482 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17483 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17485 (defvar org-cdlatex-texmathp-advice-is-done nil
17486 "Flag remembering if we have applied the advice to texmathp already.")
17488 (define-minor-mode org-cdlatex-mode
17489 "Toggle the minor `org-cdlatex-mode'.
17490 This mode supports entering LaTeX environment and math in LaTeX fragments
17491 in Org-mode.
17492 \\{org-cdlatex-mode-map}"
17493 nil " OCDL" nil
17494 (when org-cdlatex-mode
17495 (require 'cdlatex)
17496 (run-hooks 'cdlatex-mode-hook)
17497 (cdlatex-compute-tables))
17498 (unless org-cdlatex-texmathp-advice-is-done
17499 (setq org-cdlatex-texmathp-advice-is-done t)
17500 (defadvice texmathp (around org-math-always-on activate)
17501 "Always return t in org-mode buffers.
17502 This is because we want to insert math symbols without dollars even outside
17503 the LaTeX math segments. If Orgmode thinks that point is actually inside
17504 an embedded LaTeX fragment, let texmathp do its job.
17505 \\[org-cdlatex-mode-map]"
17506 (interactive)
17507 (let (p)
17508 (cond
17509 ((not (derived-mode-p 'org-mode)) ad-do-it)
17510 ((eq this-command 'cdlatex-math-symbol)
17511 (setq ad-return-value t
17512 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17514 (let ((p (org-inside-LaTeX-fragment-p)))
17515 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17516 (setq ad-return-value t
17517 texmathp-why '("Org-mode embedded math" . 0))
17518 (if p ad-do-it)))))))))
17520 (defun turn-on-org-cdlatex ()
17521 "Unconditionally turn on `org-cdlatex-mode'."
17522 (org-cdlatex-mode 1))
17524 (defun org-inside-LaTeX-fragment-p ()
17525 "Test if point is inside a LaTeX fragment.
17526 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17527 sequence appearing also before point.
17528 Even though the matchers for math are configurable, this function assumes
17529 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17530 delimiters are skipped when they have been removed by customization.
17531 The return value is nil, or a cons cell with the delimiter and the
17532 position of this delimiter.
17534 This function does a reasonably good job, but can locally be fooled by
17535 for example currency specifications. For example it will assume being in
17536 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17537 fragments that are properly closed, but during editing, we have to live
17538 with the uncertainty caused by missing closing delimiters. This function
17539 looks only before point, not after."
17540 (catch 'exit
17541 (let ((pos (point))
17542 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17543 (lim (progn
17544 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17545 (point)))
17546 dd-on str (start 0) m re)
17547 (goto-char pos)
17548 (when dodollar
17549 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17550 re (nth 1 (assoc "$" org-latex-regexps)))
17551 (while (string-match re str start)
17552 (cond
17553 ((= (match-end 0) (length str))
17554 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17555 ((= (match-end 0) (- (length str) 5))
17556 (throw 'exit nil))
17557 (t (setq start (match-end 0))))))
17558 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17559 (goto-char pos)
17560 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17561 (and (match-beginning 2) (throw 'exit nil))
17562 ;; count $$
17563 (while (re-search-backward "\\$\\$" lim t)
17564 (setq dd-on (not dd-on)))
17565 (goto-char pos)
17566 (if dd-on (cons "$$" m))))))
17568 (defun org-inside-latex-macro-p ()
17569 "Is point inside a LaTeX macro or its arguments?"
17570 (save-match-data
17571 (org-in-regexp
17572 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17574 (defun org-try-cdlatex-tab ()
17575 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17576 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17577 - inside a LaTeX fragment, or
17578 - after the first word in a line, where an abbreviation expansion could
17579 insert a LaTeX environment."
17580 (when org-cdlatex-mode
17581 (cond
17582 ;; Before any word on the line: No expansion possible.
17583 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17584 ;; Just after first word on the line: Expand it. Make sure it
17585 ;; cannot happen on headlines, though.
17586 ((save-excursion
17587 (skip-chars-backward "a-zA-Z0-9*")
17588 (skip-chars-backward " \t")
17589 (and (bolp) (not (org-at-heading-p))))
17590 (cdlatex-tab) t)
17591 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17593 (defun org-cdlatex-underscore-caret (&optional arg)
17594 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17595 Revert to the normal definition outside of these fragments."
17596 (interactive "P")
17597 (if (org-inside-LaTeX-fragment-p)
17598 (call-interactively 'cdlatex-sub-superscript)
17599 (let (org-cdlatex-mode)
17600 (call-interactively (key-binding (vector last-input-event))))))
17602 (defun org-cdlatex-math-modify (&optional arg)
17603 "Execute `cdlatex-math-modify' in LaTeX fragments.
17604 Revert to the normal definition outside of these fragments."
17605 (interactive "P")
17606 (if (org-inside-LaTeX-fragment-p)
17607 (call-interactively 'cdlatex-math-modify)
17608 (let (org-cdlatex-mode)
17609 (call-interactively (key-binding (vector last-input-event))))))
17611 (defvar org-latex-fragment-image-overlays nil
17612 "List of overlays carrying the images of latex fragments.")
17613 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17615 (defun org-remove-latex-fragment-image-overlays ()
17616 "Remove all overlays with LaTeX fragment images in current buffer."
17617 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17618 (setq org-latex-fragment-image-overlays nil))
17620 (defun org-preview-latex-fragment (&optional subtree)
17621 "Preview the LaTeX fragment at point, or all locally or globally.
17622 If the cursor is in a LaTeX fragment, create the image and overlay
17623 it over the source code. If there is no fragment at point, display
17624 all fragments in the current text, from one headline to the next. With
17625 prefix SUBTREE, display all fragments in the current subtree. With a
17626 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17627 the cursor is before the first headline,
17628 display all fragments in the buffer.
17629 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17630 (interactive "P")
17631 (unless buffer-file-name
17632 (error "Can't preview LaTeX fragment in a non-file buffer"))
17633 (org-remove-latex-fragment-image-overlays)
17634 (save-excursion
17635 (save-restriction
17636 (let (beg end at msg)
17637 (cond
17638 ((or (equal subtree '(16))
17639 (not (save-excursion
17640 (re-search-backward org-outline-regexp-bol nil t))))
17641 (setq beg (point-min) end (point-max)
17642 msg "Creating images for buffer...%s"))
17643 ((equal subtree '(4))
17644 (org-back-to-heading)
17645 (setq beg (point) end (org-end-of-subtree t)
17646 msg "Creating images for subtree...%s"))
17648 (if (setq at (org-inside-LaTeX-fragment-p))
17649 (goto-char (max (point-min) (- (cdr at) 2)))
17650 (org-back-to-heading))
17651 (setq beg (point) end (progn (outline-next-heading) (point))
17652 msg (if at "Creating image...%s"
17653 "Creating images for entry...%s"))))
17654 (message msg "")
17655 (narrow-to-region beg end)
17656 (goto-char beg)
17657 (org-format-latex
17658 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17659 (file-name-nondirectory
17660 buffer-file-name)))
17661 default-directory 'overlays msg at 'forbuffer
17662 org-latex-create-formula-image-program)
17663 (message msg "done. Use `C-c C-c' to remove images.")))))
17665 (defvar org-latex-regexps
17666 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17667 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17668 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17669 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17670 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17671 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17672 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17673 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17674 "Regular expressions for matching embedded LaTeX.")
17676 (defvar org-export-have-math nil) ;; dynamic scoping
17677 (defun org-format-latex (prefix &optional dir overlays msg at
17678 forbuffer processing-type)
17679 "Replace LaTeX fragments with links to an image, and produce images.
17680 Some of the options can be changed using the variable
17681 `org-format-latex-options'."
17682 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17683 (let* ((prefixnodir (file-name-nondirectory prefix))
17684 (absprefix (expand-file-name prefix dir))
17685 (todir (file-name-directory absprefix))
17686 (opt org-format-latex-options)
17687 (optnew org-format-latex-options)
17688 (matchers (plist-get opt :matchers))
17689 (re-list org-latex-regexps)
17690 (org-format-latex-header-extra
17691 (plist-get (org-infile-export-plist) :latex-header-extra))
17692 (cnt 0) txt hash link beg end re e checkdir
17693 string
17694 m n block-type block linkfile movefile ov)
17695 ;; Check the different regular expressions
17696 (while (setq e (pop re-list))
17697 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17698 block (if block-type "\n\n" ""))
17699 (when (member m matchers)
17700 (goto-char (point-min))
17701 (while (re-search-forward re nil t)
17702 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17703 (not (get-text-property (match-beginning n)
17704 'org-protected))
17705 (or (not overlays)
17706 (not (eq (get-char-property (match-beginning n)
17707 'org-overlay-type)
17708 'org-latex-overlay))))
17709 (setq org-export-have-math t)
17710 (cond
17711 ((eq processing-type 'verbatim)
17712 ;; Leave the text verbatim, just protect it
17713 (add-text-properties (match-beginning n) (match-end n)
17714 '(org-protected t)))
17715 ((eq processing-type 'mathjax)
17716 ;; Prepare for MathJax processing
17717 (setq string (match-string n))
17718 (if (member m '("$" "$1"))
17719 (save-excursion
17720 (delete-region (match-beginning n) (match-end n))
17721 (goto-char (match-beginning n))
17722 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17723 "\\)")
17724 '(org-protected t))))
17725 (add-text-properties (match-beginning n) (match-end n)
17726 '(org-protected t))))
17727 ((or (eq processing-type 'dvipng)
17728 (eq processing-type 'imagemagick))
17729 ;; Process to an image
17730 (setq txt (match-string n)
17731 beg (match-beginning n) end (match-end n)
17732 cnt (1+ cnt))
17733 (let ((face (face-at-point))
17734 (fg (plist-get opt :foreground))
17735 (bg (plist-get opt :background))
17736 print-length print-level) ; make sure full list is printed
17737 (when forbuffer
17738 ; Get the colors from the face at point
17739 (goto-char beg)
17740 (when (eq fg 'auto)
17741 (setq fg (face-attribute face :foreground nil 'default)))
17742 (when (eq bg 'auto)
17743 (setq bg (face-attribute face :background nil 'default)))
17744 (setq optnew (copy-sequence opt))
17745 (plist-put optnew :foreground fg)
17746 (plist-put optnew :background bg))
17747 (setq hash (sha1 (prin1-to-string
17748 (list org-format-latex-header
17749 org-format-latex-header-extra
17750 org-export-latex-default-packages-alist
17751 org-export-latex-packages-alist
17752 org-format-latex-options
17753 forbuffer txt fg bg)))
17754 linkfile (format "%s_%s.png" prefix hash)
17755 movefile (format "%s_%s.png" absprefix hash)))
17756 (setq link (concat block "[[file:" linkfile "]]" block))
17757 (if msg (message msg cnt))
17758 (goto-char beg)
17759 (unless checkdir ; make sure the directory exists
17760 (setq checkdir t)
17761 (or (file-directory-p todir) (make-directory todir t)))
17762 (unless (file-exists-p movefile)
17763 (org-create-formula-image
17764 txt movefile optnew forbuffer processing-type))
17765 (if overlays
17766 (progn
17767 (mapc (lambda (o)
17768 (if (eq (overlay-get o 'org-overlay-type)
17769 'org-latex-overlay)
17770 (delete-overlay o)))
17771 (overlays-in beg end))
17772 (setq ov (make-overlay beg end))
17773 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17774 (if (featurep 'xemacs)
17775 (progn
17776 (overlay-put ov 'invisible t)
17777 (overlay-put
17778 ov 'end-glyph
17779 (make-glyph (vector 'png :file movefile))))
17780 (overlay-put
17781 ov 'display
17782 (list 'image :type 'png :file movefile :ascent 'center)))
17783 (push ov org-latex-fragment-image-overlays)
17784 (goto-char end))
17785 (delete-region beg end)
17786 (insert (org-add-props link
17787 (list 'org-latex-src
17788 (replace-regexp-in-string
17789 "\"" "" txt)
17790 'org-latex-src-embed-type
17791 (if block-type 'paragraph 'character))))))
17792 ((eq processing-type 'mathml)
17793 ;; Process to MathML
17794 (unless (save-match-data (org-format-latex-mathml-available-p))
17795 (error "LaTeX to MathML converter not configured"))
17796 (setq txt (match-string n)
17797 beg (match-beginning n) end (match-end n)
17798 cnt (1+ cnt))
17799 (if msg (message msg cnt))
17800 (goto-char beg)
17801 (delete-region beg end)
17802 (insert (org-format-latex-as-mathml
17803 txt block-type prefix dir)))
17805 (error "Unknown conversion type %s for latex fragments"
17806 processing-type)))))))))
17808 (defun org-create-math-formula (latex-frag &optional mathml-file)
17809 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17810 Use `org-latex-to-mathml-convert-command'. If the conversion is
17811 sucessful, return the portion between \"<math...> </math>\"
17812 elements otherwise return nil. When MATHML-FILE is specified,
17813 write the results in to that file. When invoked as an
17814 interactive command, prompt for LATEX-FRAG, with initial value
17815 set to the current active region and echo the results for user
17816 inspection."
17817 (interactive (list (let ((frag (when (org-region-active-p)
17818 (buffer-substring-no-properties
17819 (region-beginning) (region-end)))))
17820 (read-string "LaTeX Fragment: " frag nil frag))))
17821 (unless latex-frag (error "Invalid latex-frag"))
17822 (let* ((tmp-in-file (file-relative-name
17823 (make-temp-name (expand-file-name "ltxmathml-in"))))
17824 (ignore (write-region latex-frag nil tmp-in-file))
17825 (tmp-out-file (file-relative-name
17826 (make-temp-name (expand-file-name "ltxmathml-out"))))
17827 (cmd (format-spec
17828 org-latex-to-mathml-convert-command
17829 `((?j . ,(shell-quote-argument
17830 (expand-file-name org-latex-to-mathml-jar-file)))
17831 (?I . ,(shell-quote-argument tmp-in-file))
17832 (?o . ,(shell-quote-argument tmp-out-file)))))
17833 mathml shell-command-output)
17834 (when (org-called-interactively-p 'any)
17835 (unless (org-format-latex-mathml-available-p)
17836 (error "LaTeX to MathML converter not configured")))
17837 (message "Running %s" cmd)
17838 (setq shell-command-output (shell-command-to-string cmd))
17839 (setq mathml
17840 (when (file-readable-p tmp-out-file)
17841 (with-current-buffer (find-file-noselect tmp-out-file t)
17842 (goto-char (point-min))
17843 (when (re-search-forward
17844 (concat
17845 (regexp-quote
17846 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17847 "\\(.\\|\n\\)*"
17848 (regexp-quote "</math>")) nil t)
17849 (prog1 (match-string 0) (kill-buffer))))))
17850 (cond
17851 (mathml
17852 (setq mathml
17853 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17854 (when mathml-file
17855 (write-region mathml nil mathml-file))
17856 (when (org-called-interactively-p 'any)
17857 (message mathml)))
17858 ((message "LaTeX to MathML conversion failed")
17859 (message shell-command-output)))
17860 (delete-file tmp-in-file)
17861 (when (file-exists-p tmp-out-file)
17862 (delete-file tmp-out-file))
17863 mathml))
17865 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17866 prefix &optional dir)
17867 "Use `org-create-math-formula' but check local cache first."
17868 (let* ((absprefix (expand-file-name prefix dir))
17869 (print-length nil) (print-level nil)
17870 (formula-id (concat
17871 "formula-"
17872 (sha1
17873 (prin1-to-string
17874 (list latex-frag
17875 org-latex-to-mathml-convert-command)))))
17876 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17877 (formula-cache-dir (file-name-directory formula-cache)))
17879 (unless (file-directory-p formula-cache-dir)
17880 (make-directory formula-cache-dir t))
17882 (unless (file-exists-p formula-cache)
17883 (org-create-math-formula latex-frag formula-cache))
17885 (if (file-exists-p formula-cache)
17886 ;; Successful conversion. Return the link to MathML file.
17887 (org-add-props
17888 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17889 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17890 'org-latex-src-embed-type (if latex-frag-type
17891 'paragraph 'character)))
17892 ;; Failed conversion. Return the LaTeX fragment verbatim
17893 (add-text-properties
17894 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17895 latex-frag)))
17897 (defun org-create-formula-image (string tofile options buffer &optional type)
17898 "Create an image from LaTeX source using dvipng or convert.
17899 This function calls either `org-create-formula-image-with-dvipng'
17900 or `org-create-formula-image-with-imagemagick' depending on the
17901 value of `org-latex-create-formula-image-program' or on the value
17902 of the optional TYPE variable.
17904 Note: ultimately these two function should be combined as they
17905 share a good deal of logic."
17906 (org-check-external-command
17907 "latex" "needed to convert LaTeX fragments to images")
17908 (funcall
17909 (case (or type org-latex-create-formula-image-program)
17910 ('dvipng
17911 (org-check-external-command
17912 "dvipng" "needed to convert LaTeX fragments to images")
17913 #'org-create-formula-image-with-dvipng)
17914 ('imagemagick
17915 (org-check-external-command
17916 "convert" "you need to install imagemagick")
17917 #'org-create-formula-image-with-imagemagick)
17918 (t (error
17919 "invalid value of `org-latex-create-formula-image-program'")))
17920 string tofile options buffer))
17922 ;; This function borrows from Ganesh Swami's latex2png.el
17923 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17924 "This calls dvipng."
17925 (require 'org-latex)
17926 (let* ((tmpdir (if (featurep 'xemacs)
17927 (temp-directory)
17928 temporary-file-directory))
17929 (texfilebase (make-temp-name
17930 (expand-file-name "orgtex" tmpdir)))
17931 (texfile (concat texfilebase ".tex"))
17932 (dvifile (concat texfilebase ".dvi"))
17933 (pngfile (concat texfilebase ".png"))
17934 (fnh (if (featurep 'xemacs)
17935 (font-height (face-font 'default))
17936 (face-attribute 'default :height nil)))
17937 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17938 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17939 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17940 "Black"))
17941 (bg (or (plist-get options (if buffer :background :html-background))
17942 "Transparent")))
17943 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17944 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17945 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17946 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17947 (with-temp-file texfile
17948 (insert (org-splice-latex-header
17949 org-format-latex-header
17950 org-export-latex-default-packages-alist
17951 org-export-latex-packages-alist t
17952 org-format-latex-header-extra))
17953 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17954 (require 'org-latex)
17955 (org-export-latex-fix-inputenc))
17956 (let ((dir default-directory))
17957 (condition-case nil
17958 (progn
17959 (cd tmpdir)
17960 (call-process "latex" nil nil nil texfile))
17961 (error nil))
17962 (cd dir))
17963 (if (not (file-exists-p dvifile))
17964 (progn (message "Failed to create dvi file from %s" texfile) nil)
17965 (condition-case nil
17966 (if (featurep 'xemacs)
17967 (call-process "dvipng" nil nil nil
17968 "-fg" fg "-bg" bg
17969 "-T" "tight"
17970 "-o" pngfile
17971 dvifile)
17972 (call-process "dvipng" nil nil nil
17973 "-fg" fg "-bg" bg
17974 "-D" dpi
17975 ;;"-x" scale "-y" scale
17976 "-T" "tight"
17977 "-o" pngfile
17978 dvifile))
17979 (error nil))
17980 (if (not (file-exists-p pngfile))
17981 (if org-format-latex-signal-error
17982 (error "Failed to create png file from %s" texfile)
17983 (message "Failed to create png file from %s" texfile)
17984 nil)
17985 ;; Use the requested file name and clean up
17986 (copy-file pngfile tofile 'replace)
17987 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17988 (if (file-exists-p (concat texfilebase e))
17989 (delete-file (concat texfilebase e))))
17990 pngfile))))
17992 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17993 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17994 "This calls convert, which is included into imagemagick."
17995 (require 'org-latex)
17996 (let* ((tmpdir (if (featurep 'xemacs)
17997 (temp-directory)
17998 temporary-file-directory))
17999 (texfilebase (make-temp-name
18000 (expand-file-name "orgtex" tmpdir)))
18001 (texfile (concat texfilebase ".tex"))
18002 (pdffile (concat texfilebase ".pdf"))
18003 (pngfile (concat texfilebase ".png"))
18004 (fnh (if (featurep 'xemacs)
18005 (font-height (face-font 'default))
18006 (face-attribute 'default :height nil)))
18007 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18008 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18009 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18010 "black"))
18011 (bg (or (plist-get options (if buffer :background :html-background))
18012 "white")))
18013 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18014 (setq fg (org-latex-color-format fg)))
18015 (if (eq bg 'default) (setq bg (org-latex-color :background))
18016 (setq bg (org-latex-color-format
18017 (if (string= bg "Transparent") "white" bg))))
18018 (with-temp-file texfile
18019 (insert (org-splice-latex-header
18020 org-format-latex-header
18021 org-export-latex-default-packages-alist
18022 org-export-latex-packages-alist t
18023 org-format-latex-header-extra))
18024 (insert "\n\\begin{document}\n"
18025 "\\definecolor{fg}{rgb}{" fg "}\n"
18026 "\\definecolor{bg}{rgb}{" bg "}\n"
18027 "\n\\pagecolor{bg}\n"
18028 "\n{\\color{fg}\n"
18029 string
18030 "\n}\n"
18031 "\n\\end{document}\n" )
18032 (require 'org-latex)
18033 (org-export-latex-fix-inputenc))
18034 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18035 (condition-case nil
18036 (progn
18037 (cd tmpdir)
18038 (setq cmds org-latex-to-pdf-process)
18039 (while cmds
18040 (setq latex-frags-cmds (pop cmds))
18041 (if (listp latex-frags-cmds)
18042 (setq cmds nil)
18043 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
18044 (while latex-frags-cmds
18045 (setq cmd (pop latex-frags-cmds))
18046 (while (string-match "%b" cmd)
18047 (setq cmd (replace-match
18048 (save-match-data
18049 (shell-quote-argument texfile))
18050 t t cmd)))
18051 (while (string-match "%f" cmd)
18052 (setq cmd (replace-match
18053 (save-match-data
18054 (shell-quote-argument (file-name-nondirectory texfile)))
18055 t t cmd)))
18056 (while (string-match "%o" cmd)
18057 (setq cmd (replace-match
18058 (save-match-data
18059 (shell-quote-argument (file-name-directory texfile)))
18060 t t cmd)))
18061 (setq cmd (split-string cmd))
18062 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18063 (error nil))
18064 (cd dir))
18065 (if (not (file-exists-p pdffile))
18066 (progn (message "Failed to create pdf file from %s" texfile) nil)
18067 (condition-case nil
18068 (if (featurep 'xemacs)
18069 (call-process "convert" nil nil nil
18070 "-density" "96"
18071 "-trim"
18072 "-antialias"
18073 pdffile
18074 "-quality" "100"
18075 ;; "-sharpen" "0x1.0"
18076 pngfile)
18077 (call-process "convert" nil nil nil
18078 "-density" dpi
18079 "-trim"
18080 "-antialias"
18081 pdffile
18082 "-quality" "100"
18083 ; "-sharpen" "0x1.0"
18084 pngfile))
18085 (error nil))
18086 (if (not (file-exists-p pngfile))
18087 (if org-format-latex-signal-error
18088 (error "Failed to create png file from %s" texfile)
18089 (message "Failed to create png file from %s" texfile)
18090 nil)
18091 ;; Use the requested file name and clean up
18092 (copy-file pngfile tofile 'replace)
18093 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18094 (if (file-exists-p (concat texfilebase e))
18095 (delete-file (concat texfilebase e))))
18096 pngfile))))
18098 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18099 "Fill a LaTeX header template TPL.
18100 In the template, the following place holders will be recognized:
18102 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18103 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18104 [PACKAGES] \\usepackage statements for PKG
18105 [NO-PACKAGES] do not include PKG
18106 [EXTRA] the string EXTRA
18107 [NO-EXTRA] do not include EXTRA
18109 For backward compatibility, if both the positive and the negative place
18110 holder is missing, the positive one (without the \"NO-\") will be
18111 assumed to be present at the end of the template.
18112 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18113 EXTRA is a string.
18114 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18115 (let (rpl (end ""))
18116 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18117 (setq rpl (if (or (match-end 1) (not def-pkg))
18118 "" (org-latex-packages-to-string def-pkg snippets-p t))
18119 tpl (replace-match rpl t t tpl))
18120 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18122 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18123 (setq rpl (if (or (match-end 1) (not pkg))
18124 "" (org-latex-packages-to-string pkg snippets-p t))
18125 tpl (replace-match rpl t t tpl))
18126 (if pkg (setq end
18127 (concat end "\n"
18128 (org-latex-packages-to-string pkg snippets-p)))))
18130 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18131 (setq rpl (if (or (match-end 1) (not extra))
18132 "" (concat extra "\n"))
18133 tpl (replace-match rpl t t tpl))
18134 (if (and extra (string-match "\\S-" extra))
18135 (setq end (concat end "\n" extra))))
18137 (if (string-match "\\S-" end)
18138 (concat tpl "\n" end)
18139 tpl)))
18141 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18142 "Turn an alist of packages into a string with the \\usepackage macros."
18143 (setq pkg (mapconcat (lambda(p)
18144 (cond
18145 ((stringp p) p)
18146 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18147 (format "%% Package %s omitted" (cadr p)))
18148 ((equal "" (car p))
18149 (format "\\usepackage{%s}" (cadr p)))
18151 (format "\\usepackage[%s]{%s}"
18152 (car p) (cadr p)))))
18154 "\n"))
18155 (if newline (concat pkg "\n") pkg))
18157 (defun org-dvipng-color (attr)
18158 "Return a RGB color specification for dvipng."
18159 (apply 'format "rgb %s %s %s"
18160 (mapcar 'org-normalize-color
18161 (if (featurep 'xemacs)
18162 (color-rgb-components
18163 (face-property 'default
18164 (cond ((eq attr :foreground) 'foreground)
18165 ((eq attr :background) 'background))))
18166 (color-values (face-attribute 'default attr nil))))))
18168 (defun org-dvipng-color-format (color-name)
18169 "Convert COLOR-NAME to a RGB color value for dvipng."
18170 (apply 'format "rgb %s %s %s"
18171 (mapcar 'org-normalize-color
18172 (color-values color-name))))
18174 (defun org-latex-color (attr)
18175 "Return a RGB color for the LaTeX color package."
18176 (apply 'format "%s,%s,%s"
18177 (mapcar 'org-normalize-color
18178 (if (featurep 'xemacs)
18179 (color-rgb-components
18180 (face-property 'default
18181 (cond ((eq attr :foreground) 'foreground)
18182 ((eq attr :background) 'background))))
18183 (color-values (face-attribute 'default attr nil))))))
18185 (defun org-latex-color-format (color-name)
18186 "Convert COLOR-NAME to a RGB color value."
18187 (apply 'format "%s,%s,%s"
18188 (mapcar 'org-normalize-color
18189 (color-values color-name))))
18191 (defun org-normalize-color (value)
18192 "Return string to be used as color value for an RGB component."
18193 (format "%g" (/ value 65535.0)))
18195 ;; Image display
18198 (defvar org-inline-image-overlays nil)
18199 (make-variable-buffer-local 'org-inline-image-overlays)
18201 (defun org-toggle-inline-images (&optional include-linked)
18202 "Toggle the display of inline images.
18203 INCLUDE-LINKED is passed to `org-display-inline-images'."
18204 (interactive "P")
18205 (if org-inline-image-overlays
18206 (progn
18207 (org-remove-inline-images)
18208 (message "Inline image display turned off"))
18209 (org-display-inline-images include-linked)
18210 (if (and (org-called-interactively-p)
18211 org-inline-image-overlays)
18212 (message "%d images displayed inline"
18213 (length org-inline-image-overlays))
18214 (message "No images to display inline"))))
18216 (defun org-redisplay-inline-images ()
18217 "Refresh the display of inline images."
18218 (interactive)
18219 (if (not org-inline-image-overlays)
18220 (org-toggle-inline-images)
18221 (org-toggle-inline-images)
18222 (org-toggle-inline-images)))
18224 (defun org-display-inline-images (&optional include-linked refresh beg end)
18225 "Display inline images.
18226 Normally only links without a description part are inlined, because this
18227 is how it will work for export. When INCLUDE-LINKED is set, also links
18228 with a description part will be inlined. This can be nice for a quick
18229 look at those images, but it does not reflect what exported files will look
18230 like.
18231 When REFRESH is set, refresh existing images between BEG and END.
18232 This will create new image displays only if necessary.
18233 BEG and END default to the buffer boundaries."
18234 (interactive "P")
18235 (unless refresh
18236 (org-remove-inline-images)
18237 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18238 (save-excursion
18239 (save-restriction
18240 (widen)
18241 (setq beg (or beg (point-min)) end (or end (point-max)))
18242 (goto-char beg)
18243 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18244 (substring (org-image-file-name-regexp) 0 -2)
18245 "\\)\\]" (if include-linked "" "\\]")))
18246 old file ov img type attrwidth width)
18247 (while (re-search-forward re end t)
18248 (setq old (get-char-property-and-overlay (match-beginning 1)
18249 'org-image-overlay)
18250 file (expand-file-name
18251 (concat (or (match-string 3) "") (match-string 4))))
18252 (when (image-type-available-p 'imagemagick)
18253 (setq attrwidth (if (or (listp org-image-actual-width)
18254 (null org-image-actual-width))
18255 (save-excursion
18256 (save-match-data
18257 (when (re-search-backward
18258 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18259 (save-excursion
18260 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18261 (string-to-number (match-string 1))))))
18262 width (cond ((eq org-image-actual-width t) nil)
18263 ((null org-image-actual-width) attrwidth)
18264 ((numberp org-image-actual-width)
18265 org-image-actual-width)
18266 ((listp org-image-actual-width)
18267 (or attrwidth (car org-image-actual-width))))
18268 type (if width 'imagemagick)))
18269 (when (file-exists-p file)
18270 (if (and (car-safe old) refresh)
18271 (image-refresh (overlay-get (cdr old) 'display))
18272 (setq img (save-match-data (create-image file type nil :width width)))
18273 (when img
18274 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18275 (overlay-put ov 'display img)
18276 (overlay-put ov 'face 'default)
18277 (overlay-put ov 'org-image-overlay t)
18278 (overlay-put ov 'modification-hooks
18279 (list 'org-display-inline-remove-overlay))
18280 (push ov org-inline-image-overlays)))))))))
18282 (define-obsolete-function-alias
18283 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18285 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18286 "Remove inline-display overlay if a corresponding region is modified."
18287 (let ((inhibit-modification-hooks t))
18288 (when (and ov after)
18289 (delete ov org-inline-image-overlays)
18290 (delete-overlay ov))))
18292 (defun org-remove-inline-images ()
18293 "Remove inline display of images."
18294 (interactive)
18295 (mapc 'delete-overlay org-inline-image-overlays)
18296 (setq org-inline-image-overlays nil))
18298 ;;;; Key bindings
18300 ;; Outline functions from `outline-mode-prefix-map'
18301 ;; that can be remapped in Org:
18302 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18303 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18304 (define-key org-mode-map [remap outline-forward-same-level]
18305 'org-forward-heading-same-level)
18306 (define-key org-mode-map [remap outline-backward-same-level]
18307 'org-backward-heading-same-level)
18308 (define-key org-mode-map [remap show-branches]
18309 'org-kill-note-or-show-branches)
18310 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18311 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18312 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18314 ;; Outline functions from `outline-mode-prefix-map' that can not
18315 ;; be remapped in Org:
18317 ;; - the column "key binding" shows whether the Outline function is still
18318 ;; available in Org mode on the same key that it has been bound to in
18319 ;; Outline mode:
18320 ;; - "overridden": key used for a different functionality in Org mode
18321 ;; - else: key still bound to the same Outline function in Org mode
18323 ;; | Outline function | key binding | Org replacement |
18324 ;; |------------------------------------+-------------+-----------------------|
18325 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18326 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18327 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18328 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18329 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18330 ;; | `show-entry' | overridden | no replacement |
18331 ;; | `show-children' | `C-c C-i' | visibility cycling |
18332 ;; | `show-branches' | `C-c C-k' | still same function |
18333 ;; | `show-subtree' | overridden | visibility cycling |
18334 ;; | `show-all' | overridden | no replacement |
18335 ;; | `hide-subtree' | overridden | visibility cycling |
18336 ;; | `hide-body' | overridden | no replacement |
18337 ;; | `hide-entry' | overridden | visibility cycling |
18338 ;; | `hide-leaves' | overridden | no replacement |
18339 ;; | `hide-sublevels' | overridden | no replacement |
18340 ;; | `hide-other' | overridden | no replacement |
18342 ;; Make `C-c C-x' a prefix key
18343 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18345 ;; TAB key with modifiers
18346 (org-defkey org-mode-map "\C-i" 'org-cycle)
18347 (org-defkey org-mode-map [(tab)] 'org-cycle)
18348 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18349 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18350 ;; The following line is necessary under Suse GNU/Linux
18351 (unless (featurep 'xemacs)
18352 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18353 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18354 (define-key org-mode-map [backtab] 'org-shifttab)
18356 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18357 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18358 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18360 ;; Cursor keys with modifiers
18361 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18362 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18363 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18364 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18366 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18367 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18368 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18369 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18371 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18372 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18373 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18374 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18376 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18377 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18378 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18379 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18381 ;; Babel keys
18382 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18383 (mapc (lambda (pair)
18384 (define-key org-babel-map (car pair) (cdr pair)))
18385 org-babel-key-bindings)
18387 ;;; Extra keys for tty access.
18388 ;; We only set them when really needed because otherwise the
18389 ;; menus don't show the simple keys
18391 (when (or org-use-extra-keys
18392 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18393 (not window-system))
18394 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18395 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18396 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18397 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18398 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18399 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18400 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18401 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18402 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18403 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18404 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18405 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18406 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18407 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18408 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18409 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18410 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18411 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18412 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18413 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18414 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18415 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18416 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18417 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18418 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18419 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18420 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18421 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18423 ;; All the other keys
18425 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18426 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18427 (if (boundp 'narrow-map)
18428 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18429 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18430 (if (boundp 'narrow-map)
18431 (org-defkey narrow-map "b" 'org-narrow-to-block)
18432 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18433 (if (boundp 'narrow-map)
18434 (org-defkey narrow-map "e" 'org-narrow-to-element)
18435 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18436 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18437 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18438 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18439 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18440 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18441 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18442 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18443 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18444 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18445 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18446 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18447 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18448 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18449 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18450 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18451 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18452 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18453 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18454 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18455 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18456 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18457 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18458 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18459 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18460 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18461 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18462 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18463 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18464 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18465 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18466 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18467 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18468 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18469 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18470 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18471 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18472 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18473 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18474 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18475 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18476 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18477 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18478 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18479 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18480 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18481 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18482 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18483 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18484 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18485 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18486 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18487 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18488 (org-defkey org-mode-map "\C-c^" 'org-sort)
18489 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18490 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18491 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18492 (org-defkey org-mode-map "\C-m" 'org-return)
18493 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18494 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18495 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18496 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18497 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18498 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18499 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18500 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18501 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18502 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18503 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18504 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18505 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18506 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18507 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18508 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18509 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18510 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18511 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18512 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18513 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18514 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18515 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18517 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18518 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18519 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18521 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18522 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18523 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18524 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18525 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18526 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18527 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18528 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18529 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18530 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18531 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18532 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18533 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18534 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18535 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18536 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18537 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18538 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18539 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18540 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18541 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18542 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18543 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18545 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18546 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18547 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18548 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18549 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18551 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18553 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18555 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18556 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18558 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18561 (when (featurep 'xemacs)
18562 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18565 (defconst org-speed-commands-default
18567 ("Outline Navigation")
18568 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18569 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18570 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18571 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18572 ("u" . (org-speed-move-safe 'outline-up-heading))
18573 ("j" . org-goto)
18574 ("g" . (org-refile t))
18575 ("Outline Visibility")
18576 ("c" . org-cycle)
18577 ("C" . org-shifttab)
18578 (" " . org-display-outline-path)
18579 ("=" . org-columns)
18580 ("Outline Structure Editing")
18581 ("U" . org-shiftmetaup)
18582 ("D" . org-shiftmetadown)
18583 ("r" . org-metaright)
18584 ("l" . org-metaleft)
18585 ("R" . org-shiftmetaright)
18586 ("L" . org-shiftmetaleft)
18587 ("i" . (progn (forward-char 1) (call-interactively
18588 'org-insert-heading-respect-content)))
18589 ("^" . org-sort)
18590 ("w" . org-refile)
18591 ("a" . org-archive-subtree-default-with-confirmation)
18592 ("." . org-mark-subtree)
18593 ("#" . org-toggle-comment)
18594 ("Clock Commands")
18595 ("I" . org-clock-in)
18596 ("O" . org-clock-out)
18597 ("Meta Data Editing")
18598 ("t" . org-todo)
18599 ("," . (org-priority))
18600 ("0" . (org-priority ?\ ))
18601 ("1" . (org-priority ?A))
18602 ("2" . (org-priority ?B))
18603 ("3" . (org-priority ?C))
18604 (":" . org-set-tags-command)
18605 ("e" . org-set-effort)
18606 ("E" . org-inc-effort)
18607 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18608 (org-entry-put (point) "APPT_WARNTIME" m)))
18609 ("Agenda Views etc")
18610 ("v" . org-agenda)
18611 ("/" . org-sparse-tree)
18612 ("Misc")
18613 ("o" . org-open-at-point)
18614 ("?" . org-speed-command-help)
18615 ("<" . (org-agenda-set-restriction-lock 'subtree))
18616 (">" . (org-agenda-remove-restriction-lock))
18618 "The default speed commands.")
18620 (defun org-print-speed-command (e)
18621 (if (> (length (car e)) 1)
18622 (progn
18623 (princ "\n")
18624 (princ (car e))
18625 (princ "\n")
18626 (princ (make-string (length (car e)) ?-))
18627 (princ "\n"))
18628 (princ (car e))
18629 (princ " ")
18630 (if (symbolp (cdr e))
18631 (princ (symbol-name (cdr e)))
18632 (prin1 (cdr e)))
18633 (princ "\n")))
18635 (defun org-speed-command-help ()
18636 "Show the available speed commands."
18637 (interactive)
18638 (if (not org-use-speed-commands)
18639 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18640 (with-output-to-temp-buffer "*Help*"
18641 (princ "User-defined Speed commands\n===========================\n")
18642 (mapc 'org-print-speed-command org-speed-commands-user)
18643 (princ "\n")
18644 (princ "Built-in Speed commands\n=======================\n")
18645 (mapc 'org-print-speed-command org-speed-commands-default))
18646 (with-current-buffer "*Help*"
18647 (setq truncate-lines t))))
18649 (defun org-speed-move-safe (cmd)
18650 "Execute CMD, but make sure that the cursor always ends up in a headline.
18651 If not, return to the original position and throw an error."
18652 (interactive)
18653 (let ((pos (point)))
18654 (call-interactively cmd)
18655 (unless (and (bolp) (org-at-heading-p))
18656 (goto-char pos)
18657 (error "Boundary reached while executing %s" cmd))))
18659 (defvar org-self-insert-command-undo-counter 0)
18661 (defvar org-table-auto-blank-field) ; defined in org-table.el
18662 (defvar org-speed-command nil)
18664 (define-obsolete-function-alias
18665 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18667 (defun org-speed-command-activate (keys)
18668 "Hook for activating single-letter speed commands.
18669 `org-speed-commands-default' specifies a minimal command set.
18670 Use `org-speed-commands-user' for further customization."
18671 (when (or (and (bolp) (looking-at org-outline-regexp))
18672 (and (functionp org-use-speed-commands)
18673 (funcall org-use-speed-commands)))
18674 (cdr (assoc keys (append org-speed-commands-user
18675 org-speed-commands-default)))))
18677 (define-obsolete-function-alias
18678 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18680 (defun org-babel-speed-command-activate (keys)
18681 "Hook for activating single-letter code block commands."
18682 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18683 (cdr (assoc keys org-babel-key-bindings))))
18685 (defcustom org-speed-command-hook
18686 '(org-speed-command-default-hook org-babel-speed-command-hook)
18687 "Hook for activating speed commands at strategic locations.
18688 Hook functions are called in sequence until a valid handler is
18689 found.
18691 Each hook takes a single argument, a user-pressed command key
18692 which is also a `self-insert-command' from the global map.
18694 Within the hook, examine the cursor position and the command key
18695 and return nil or a valid handler as appropriate. Handler could
18696 be one of an interactive command, a function, or a form.
18698 Set `org-use-speed-commands' to non-nil value to enable this
18699 hook. The default setting is `org-speed-command-activate'."
18700 :group 'org-structure
18701 :version "24.1"
18702 :type 'hook)
18704 (defun org-self-insert-command (N)
18705 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18706 If the cursor is in a table looking at whitespace, the whitespace is
18707 overwritten, and the table is not marked as requiring realignment."
18708 (interactive "p")
18709 (org-check-before-invisible-edit 'insert)
18710 (cond
18711 ((and org-use-speed-commands
18712 (setq org-speed-command
18713 (run-hook-with-args-until-success
18714 'org-speed-command-hook (this-command-keys))))
18715 (cond
18716 ((commandp org-speed-command)
18717 (setq this-command org-speed-command)
18718 (call-interactively org-speed-command))
18719 ((functionp org-speed-command)
18720 (funcall org-speed-command))
18721 ((and org-speed-command (listp org-speed-command))
18722 (eval org-speed-command))
18723 (t (let (org-use-speed-commands)
18724 (call-interactively 'org-self-insert-command)))))
18725 ((and
18726 (org-table-p)
18727 (progn
18728 ;; check if we blank the field, and if that triggers align
18729 (and (featurep 'org-table) org-table-auto-blank-field
18730 (member last-command
18731 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18732 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18733 ;; got extra space, this field does not determine column width
18734 (let (org-table-may-need-update) (org-table-blank-field))
18735 ;; no extra space, this field may determine column width
18736 (org-table-blank-field)))
18738 (eq N 1)
18739 (looking-at "[^|\n]* |"))
18740 (let (org-table-may-need-update)
18741 (goto-char (1- (match-end 0)))
18742 (backward-delete-char 1)
18743 (goto-char (match-beginning 0))
18744 (self-insert-command N)))
18746 (setq org-table-may-need-update t)
18747 (self-insert-command N)
18748 (org-fix-tags-on-the-fly)
18749 (if org-self-insert-cluster-for-undo
18750 (if (not (eq last-command 'org-self-insert-command))
18751 (setq org-self-insert-command-undo-counter 1)
18752 (if (>= org-self-insert-command-undo-counter 20)
18753 (setq org-self-insert-command-undo-counter 1)
18754 (and (> org-self-insert-command-undo-counter 0)
18755 buffer-undo-list (listp buffer-undo-list)
18756 (not (cadr buffer-undo-list)) ; remove nil entry
18757 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18758 (setq org-self-insert-command-undo-counter
18759 (1+ org-self-insert-command-undo-counter))))))))
18761 (defun org-check-before-invisible-edit (kind)
18762 "Check is editing if kind KIND would be dangerous with invisible text around.
18763 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18764 ;; First, try to get out of here as quickly as possible, to reduce overhead
18765 (if (and org-catch-invisible-edits
18766 (or (not (boundp 'visible-mode)) (not visible-mode))
18767 (or (get-char-property (point) 'invisible)
18768 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18769 ;; OK, we need to take a closer look
18770 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18771 (invisible-before-point (if (bobp) nil (get-char-property
18772 (1- (point)) 'invisible)))
18773 (border-and-ok-direction
18775 ;; Check if we are acting predictably before invisible text
18776 (and invisible-at-point (not invisible-before-point)
18777 (memq kind '(insert delete-backward)))
18778 ;; Check if we are acting predictably after invisible text
18779 ;; This works not well, and I have turned it off. It seems
18780 ;; better to always show and stop after invisible text.
18781 ;; (and (not invisible-at-point) invisible-before-point
18782 ;; (memq kind '(insert delete)))
18784 (when (or (memq invisible-at-point '(outline org-hide-block t))
18785 (memq invisible-before-point '(outline org-hide-block t)))
18786 (if (eq org-catch-invisible-edits 'error)
18787 (error "Editing in invisible areas is prohibited - make visible first"))
18788 (if (and org-custom-properties-overlays
18789 (y-or-n-p "Display invisible properties in this buffer? "))
18790 (org-toggle-custom-properties-visibility)
18791 ;; Make the area visible
18792 (save-excursion
18793 (if invisible-before-point
18794 (goto-char (previous-single-char-property-change
18795 (point) 'invisible)))
18796 (org-cycle))
18797 (cond
18798 ((eq org-catch-invisible-edits 'show)
18799 ;; That's it, we do the edit after showing
18800 (message
18801 "Unfolding invisible region around point before editing")
18802 (sit-for 1))
18803 ((and (eq org-catch-invisible-edits 'smart)
18804 border-and-ok-direction)
18805 (message "Unfolding invisible region around point before editing"))
18807 ;; Don't do the edit, make the user repeat it in full visibility
18808 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18810 (defun org-fix-tags-on-the-fly ()
18811 (when (and (equal (char-after (point-at-bol)) ?*)
18812 (org-at-heading-p))
18813 (org-align-tags-here org-tags-column)))
18815 (defun org-delete-backward-char (N)
18816 "Like `delete-backward-char', insert whitespace at field end in tables.
18817 When deleting backwards, in tables this function will insert whitespace in
18818 front of the next \"|\" separator, to keep the table aligned. The table will
18819 still be marked for re-alignment if the field did fill the entire column,
18820 because, in this case the deletion might narrow the column."
18821 (interactive "p")
18822 (save-match-data
18823 (org-check-before-invisible-edit 'delete-backward)
18824 (if (and (org-table-p)
18825 (eq N 1)
18826 (string-match "|" (buffer-substring (point-at-bol) (point)))
18827 (looking-at ".*?|"))
18828 (let ((pos (point))
18829 (noalign (looking-at "[^|\n\r]* |"))
18830 (c org-table-may-need-update))
18831 (backward-delete-char N)
18832 (if (not overwrite-mode)
18833 (progn
18834 (skip-chars-forward "^|")
18835 (insert " ")
18836 (goto-char (1- pos))))
18837 ;; noalign: if there were two spaces at the end, this field
18838 ;; does not determine the width of the column.
18839 (if noalign (setq org-table-may-need-update c)))
18840 (backward-delete-char N)
18841 (org-fix-tags-on-the-fly))))
18843 (defun org-delete-char (N)
18844 "Like `delete-char', but insert whitespace at field end in tables.
18845 When deleting characters, in tables this function will insert whitespace in
18846 front of the next \"|\" separator, to keep the table aligned. The table will
18847 still be marked for re-alignment if the field did fill the entire column,
18848 because, in this case the deletion might narrow the column."
18849 (interactive "p")
18850 (save-match-data
18851 (org-check-before-invisible-edit 'delete)
18852 (if (and (org-table-p)
18853 (not (bolp))
18854 (not (= (char-after) ?|))
18855 (eq N 1))
18856 (if (looking-at ".*?|")
18857 (let ((pos (point))
18858 (noalign (looking-at "[^|\n\r]* |"))
18859 (c org-table-may-need-update))
18860 (replace-match (concat
18861 (substring (match-string 0) 1 -1)
18862 " |"))
18863 (goto-char pos)
18864 ;; noalign: if there were two spaces at the end, this field
18865 ;; does not determine the width of the column.
18866 (if noalign (setq org-table-may-need-update c)))
18867 (delete-char N))
18868 (delete-char N)
18869 (org-fix-tags-on-the-fly))))
18871 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18872 (put 'org-self-insert-command 'delete-selection t)
18873 (put 'orgtbl-self-insert-command 'delete-selection t)
18874 (put 'org-delete-char 'delete-selection 'supersede)
18875 (put 'org-delete-backward-char 'delete-selection 'supersede)
18876 (put 'org-yank 'delete-selection 'yank)
18878 ;; Make `flyspell-mode' delay after some commands
18879 (put 'org-self-insert-command 'flyspell-delayed t)
18880 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18881 (put 'org-delete-char 'flyspell-delayed t)
18882 (put 'org-delete-backward-char 'flyspell-delayed t)
18884 ;; Make pabbrev-mode expand after org-mode commands
18885 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18886 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18888 ;; How to do this: Measure non-white length of current string
18889 ;; If equal to column width, we should realign.
18891 (defun org-remap (map &rest commands)
18892 "In MAP, remap the functions given in COMMANDS.
18893 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18894 (let (new old)
18895 (while commands
18896 (setq old (pop commands) new (pop commands))
18897 (if (fboundp 'command-remapping)
18898 (org-defkey map (vector 'remap old) new)
18899 (substitute-key-definition old new map global-map)))))
18901 (when (eq org-enable-table-editor 'optimized)
18902 ;; If the user wants maximum table support, we need to hijack
18903 ;; some standard editing functions
18904 (org-remap org-mode-map
18905 'self-insert-command 'org-self-insert-command
18906 'delete-char 'org-delete-char
18907 'delete-backward-char 'org-delete-backward-char)
18908 (org-defkey org-mode-map "|" 'org-force-self-insert))
18910 (defvar org-ctrl-c-ctrl-c-hook nil
18911 "Hook for functions attaching themselves to `C-c C-c'.
18913 This can be used to add additional functionality to the C-c C-c
18914 key which executes context-dependent commands. This hook is run
18915 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18916 run after the last test.
18918 Each function will be called with no arguments. The function
18919 must check if the context is appropriate for it to act. If yes,
18920 it should do its thing and then return a non-nil value. If the
18921 context is wrong, just do nothing and return nil.")
18923 (defvar org-ctrl-c-ctrl-c-final-hook nil
18924 "Hook for functions attaching themselves to `C-c C-c'.
18926 This can be used to add additional functionality to the C-c C-c
18927 key which executes context-dependent commands. This hook is run
18928 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18929 before the first test.
18931 Each function will be called with no arguments. The function
18932 must check if the context is appropriate for it to act. If yes,
18933 it should do its thing and then return a non-nil value. If the
18934 context is wrong, just do nothing and return nil.")
18936 (defvar org-tab-first-hook nil
18937 "Hook for functions to attach themselves to TAB.
18938 See `org-ctrl-c-ctrl-c-hook' for more information.
18939 This hook runs as the first action when TAB is pressed, even before
18940 `org-cycle' messes around with the `outline-regexp' to cater for
18941 inline tasks and plain list item folding.
18942 If any function in this hook returns t, any other actions that
18943 would have been caused by TAB (such as table field motion or visibility
18944 cycling) will not occur.")
18946 (defvar org-tab-after-check-for-table-hook nil
18947 "Hook for functions to attach themselves to TAB.
18948 See `org-ctrl-c-ctrl-c-hook' for more information.
18949 This hook runs after it has been established that the cursor is not in a
18950 table, but before checking if the cursor is in a headline or if global cycling
18951 should be done.
18952 If any function in this hook returns t, not other actions like visibility
18953 cycling will be done.")
18955 (defvar org-tab-after-check-for-cycling-hook nil
18956 "Hook for functions to attach themselves to TAB.
18957 See `org-ctrl-c-ctrl-c-hook' for more information.
18958 This hook runs after it has been established that not table field motion and
18959 not visibility should be done because of current context. This is probably
18960 the place where a package like yasnippets can hook in.")
18962 (defvar org-tab-before-tab-emulation-hook nil
18963 "Hook for functions to attach themselves to TAB.
18964 See `org-ctrl-c-ctrl-c-hook' for more information.
18965 This hook runs after every other options for TAB have been exhausted, but
18966 before indentation and \t insertion takes place.")
18968 (defvar org-metaleft-hook nil
18969 "Hook for functions attaching themselves to `M-left'.
18970 See `org-ctrl-c-ctrl-c-hook' for more information.")
18971 (defvar org-metaright-hook nil
18972 "Hook for functions attaching themselves to `M-right'.
18973 See `org-ctrl-c-ctrl-c-hook' for more information.")
18974 (defvar org-metaup-hook nil
18975 "Hook for functions attaching themselves to `M-up'.
18976 See `org-ctrl-c-ctrl-c-hook' for more information.")
18977 (defvar org-metadown-hook nil
18978 "Hook for functions attaching themselves to `M-down'.
18979 See `org-ctrl-c-ctrl-c-hook' for more information.")
18980 (defvar org-shiftmetaleft-hook nil
18981 "Hook for functions attaching themselves to `M-S-left'.
18982 See `org-ctrl-c-ctrl-c-hook' for more information.")
18983 (defvar org-shiftmetaright-hook nil
18984 "Hook for functions attaching themselves to `M-S-right'.
18985 See `org-ctrl-c-ctrl-c-hook' for more information.")
18986 (defvar org-shiftmetaup-hook nil
18987 "Hook for functions attaching themselves to `M-S-up'.
18988 See `org-ctrl-c-ctrl-c-hook' for more information.")
18989 (defvar org-shiftmetadown-hook nil
18990 "Hook for functions attaching themselves to `M-S-down'.
18991 See `org-ctrl-c-ctrl-c-hook' for more information.")
18992 (defvar org-metareturn-hook nil
18993 "Hook for functions attaching themselves to `M-RET'.
18994 See `org-ctrl-c-ctrl-c-hook' for more information.")
18995 (defvar org-shiftup-hook nil
18996 "Hook for functions attaching themselves to `S-up'.
18997 See `org-ctrl-c-ctrl-c-hook' for more information.")
18998 (defvar org-shiftup-final-hook nil
18999 "Hook for functions attaching themselves to `S-up'.
19000 This one runs after all other options except shift-select have been excluded.
19001 See `org-ctrl-c-ctrl-c-hook' for more information.")
19002 (defvar org-shiftdown-hook nil
19003 "Hook for functions attaching themselves to `S-down'.
19004 See `org-ctrl-c-ctrl-c-hook' for more information.")
19005 (defvar org-shiftdown-final-hook nil
19006 "Hook for functions attaching themselves to `S-down'.
19007 This one runs after all other options except shift-select have been excluded.
19008 See `org-ctrl-c-ctrl-c-hook' for more information.")
19009 (defvar org-shiftleft-hook nil
19010 "Hook for functions attaching themselves to `S-left'.
19011 See `org-ctrl-c-ctrl-c-hook' for more information.")
19012 (defvar org-shiftleft-final-hook nil
19013 "Hook for functions attaching themselves to `S-left'.
19014 This one runs after all other options except shift-select have been excluded.
19015 See `org-ctrl-c-ctrl-c-hook' for more information.")
19016 (defvar org-shiftright-hook nil
19017 "Hook for functions attaching themselves to `S-right'.
19018 See `org-ctrl-c-ctrl-c-hook' for more information.")
19019 (defvar org-shiftright-final-hook nil
19020 "Hook for functions attaching themselves to `S-right'.
19021 This one runs after all other options except shift-select have been excluded.
19022 See `org-ctrl-c-ctrl-c-hook' for more information.")
19024 (defun org-modifier-cursor-error ()
19025 "Throw an error, a modified cursor command was applied in wrong context."
19026 (error "This command is active in special context like tables, headlines or items"))
19028 (defun org-shiftselect-error ()
19029 "Throw an error because Shift-Cursor command was applied in wrong context."
19030 (if (and (boundp 'shift-select-mode) shift-select-mode)
19031 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19032 (error "This command works only in special context like headlines or timestamps")))
19034 (defun org-call-for-shift-select (cmd)
19035 (let ((this-command-keys-shift-translated t))
19036 (call-interactively cmd)))
19038 (defun org-shifttab (&optional arg)
19039 "Global visibility cycling or move to previous table field.
19040 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19041 on context.
19042 See the individual commands for more information."
19043 (interactive "P")
19044 (cond
19045 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19046 ((integerp arg)
19047 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19048 (message "Content view to level: %d" arg)
19049 (org-content (prefix-numeric-value arg2))
19050 (setq org-cycle-global-status 'overview)))
19051 (t (call-interactively 'org-global-cycle))))
19053 (defun org-shiftmetaleft ()
19054 "Promote subtree or delete table column.
19055 Calls `org-promote-subtree', `org-outdent-item-tree', or
19056 `org-table-delete-column', depending on context. See the
19057 individual commands for more information."
19058 (interactive)
19059 (cond
19060 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19061 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19062 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19063 ((if (not (org-region-active-p)) (org-at-item-p)
19064 (save-excursion (goto-char (region-beginning))
19065 (org-at-item-p)))
19066 (call-interactively 'org-outdent-item-tree))
19067 (t (org-modifier-cursor-error))))
19069 (defun org-shiftmetaright ()
19070 "Demote subtree or insert table column.
19071 Calls `org-demote-subtree', `org-indent-item-tree', or
19072 `org-table-insert-column', depending on context. See the
19073 individual commands for more information."
19074 (interactive)
19075 (cond
19076 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19077 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19078 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19079 ((if (not (org-region-active-p)) (org-at-item-p)
19080 (save-excursion (goto-char (region-beginning))
19081 (org-at-item-p)))
19082 (call-interactively 'org-indent-item-tree))
19083 (t (org-modifier-cursor-error))))
19085 (defun org-shiftmetaup (&optional arg)
19086 "Move subtree up or kill table row.
19087 Calls `org-move-subtree-up' or `org-table-kill-row' or
19088 `org-move-item-up' or `org-timestamp-up', depending on context.
19089 See the individual commands for more information."
19090 (interactive "P")
19091 (cond
19092 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19093 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19094 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19095 ((org-at-item-p) (call-interactively 'org-move-item-up))
19096 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19097 (call-interactively 'org-timestamp-up)))
19098 (t (org-modifier-cursor-error))))
19100 (defun org-shiftmetadown (&optional arg)
19101 "Move subtree down or insert table row.
19102 Calls `org-move-subtree-down' or `org-table-insert-row' or
19103 `org-move-item-down' or `org-timestamp-up', depending on context.
19104 See the individual commands for more information."
19105 (interactive "P")
19106 (cond
19107 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19108 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19109 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19110 ((org-at-item-p) (call-interactively 'org-move-item-down))
19111 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19112 (call-interactively 'org-timestamp-down)))
19113 (t (org-modifier-cursor-error))))
19115 (defsubst org-hidden-tree-error ()
19116 (error
19117 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19119 (defun org-metaleft (&optional arg)
19120 "Promote heading or move table column to left.
19121 Calls `org-do-promote' or `org-table-move-column', depending on context.
19122 With no specific context, calls the Emacs default `backward-word'.
19123 See the individual commands for more information."
19124 (interactive "P")
19125 (cond
19126 ((run-hook-with-args-until-success 'org-metaleft-hook))
19127 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19128 ((org-with-limited-levels
19129 (or (org-at-heading-p)
19130 (and (org-region-active-p)
19131 (save-excursion
19132 (goto-char (region-beginning))
19133 (org-at-heading-p)))))
19134 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19135 (call-interactively 'org-do-promote))
19136 ;; At an inline task.
19137 ((org-at-heading-p)
19138 (call-interactively 'org-inlinetask-promote))
19139 ((or (org-at-item-p)
19140 (and (org-region-active-p)
19141 (save-excursion
19142 (goto-char (region-beginning))
19143 (org-at-item-p))))
19144 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19145 (call-interactively 'org-outdent-item))
19146 (t (call-interactively 'backward-word))))
19148 (defun org-metaright (&optional arg)
19149 "Demote a subtree, a list item or move table column to right.
19150 In front of a drawer or a block keyword, indent it correctly.
19151 With no specific context, calls the Emacs default `forward-word'.
19152 See the individual commands for more information."
19153 (interactive "P")
19154 (cond
19155 ((run-hook-with-args-until-success 'org-metaright-hook))
19156 ((org-at-table-p) (call-interactively 'org-table-move-column))
19157 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19158 ((org-at-block-p) (call-interactively 'org-indent-block))
19159 ((org-with-limited-levels
19160 (or (org-at-heading-p)
19161 (and (org-region-active-p)
19162 (save-excursion
19163 (goto-char (region-beginning))
19164 (org-at-heading-p)))))
19165 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19166 (call-interactively 'org-do-demote))
19167 ;; At an inline task.
19168 ((org-at-heading-p)
19169 (call-interactively 'org-inlinetask-demote))
19170 ((or (org-at-item-p)
19171 (and (org-region-active-p)
19172 (save-excursion
19173 (goto-char (region-beginning))
19174 (org-at-item-p))))
19175 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19176 (call-interactively 'org-indent-item))
19177 (t (call-interactively 'forward-word))))
19179 (defun org-check-for-hidden (what)
19180 "Check if there are hidden headlines/items in the current visual line.
19181 WHAT can be either `headlines' or `items'. If the current line is
19182 an outline or item heading and it has a folded subtree below it,
19183 this function returns t, nil otherwise."
19184 (let ((re (cond
19185 ((eq what 'headlines) org-outline-regexp-bol)
19186 ((eq what 'items) (org-item-beginning-re))
19187 (t (error "This should not happen"))))
19188 beg end)
19189 (save-excursion
19190 (catch 'exit
19191 (unless (org-region-active-p)
19192 (setq beg (point-at-bol))
19193 (beginning-of-line 2)
19194 (while (and (not (eobp)) ;; this is like `next-line'
19195 (get-char-property (1- (point)) 'invisible))
19196 (beginning-of-line 2))
19197 (setq end (point))
19198 (goto-char beg)
19199 (goto-char (point-at-eol))
19200 (setq end (max end (point)))
19201 (while (re-search-forward re end t)
19202 (if (get-char-property (match-beginning 0) 'invisible)
19203 (throw 'exit t))))
19204 nil))))
19206 (defun org-metaup (&optional arg)
19207 "Move subtree up or move table row up.
19208 Calls `org-move-subtree-up' or `org-table-move-row' or
19209 `org-move-item-up', depending on context. See the individual commands
19210 for more information."
19211 (interactive "P")
19212 (cond
19213 ((run-hook-with-args-until-success 'org-metaup-hook))
19214 ((org-region-active-p)
19215 (let* ((a (min (region-beginning) (region-end)))
19216 (b (1- (max (region-beginning) (region-end))))
19217 (c (save-excursion (goto-char a)
19218 (move-beginning-of-line 0)))
19219 (d (save-excursion (goto-char a)
19220 (move-end-of-line 0) (point))))
19221 (transpose-regions a b c d)
19222 (goto-char c)))
19223 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19224 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19225 ((org-at-item-p) (call-interactively 'org-move-item-up))
19226 (t (org-drag-element-backward))))
19228 (defun org-metadown (&optional arg)
19229 "Move subtree down or move table row down.
19230 Calls `org-move-subtree-down' or `org-table-move-row' or
19231 `org-move-item-down', depending on context. See the individual
19232 commands for more information."
19233 (interactive "P")
19234 (cond
19235 ((run-hook-with-args-until-success 'org-metadown-hook))
19236 ((org-region-active-p)
19237 (let* ((a (min (region-beginning) (region-end)))
19238 (b (max (region-beginning) (region-end)))
19239 (c (save-excursion (goto-char b)
19240 (move-beginning-of-line 1)))
19241 (d (save-excursion (goto-char b)
19242 (move-end-of-line 1) (1+ (point)))))
19243 (transpose-regions a b c d)
19244 (goto-char d)))
19245 ((org-at-table-p) (call-interactively 'org-table-move-row))
19246 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19247 ((org-at-item-p) (call-interactively 'org-move-item-down))
19248 (t (org-drag-element-forward))))
19250 (defun org-shiftup (&optional arg)
19251 "Increase item in timestamp or increase priority of current headline.
19252 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19253 depending on context. See the individual commands for more information."
19254 (interactive "P")
19255 (cond
19256 ((run-hook-with-args-until-success 'org-shiftup-hook))
19257 ((and org-support-shift-select (org-region-active-p))
19258 (org-call-for-shift-select 'previous-line))
19259 ((org-at-timestamp-p t)
19260 (call-interactively (if org-edit-timestamp-down-means-later
19261 'org-timestamp-down 'org-timestamp-up)))
19262 ((and (not (eq org-support-shift-select 'always))
19263 org-enable-priority-commands
19264 (org-at-heading-p))
19265 (call-interactively 'org-priority-up))
19266 ((and (not org-support-shift-select) (org-at-item-p))
19267 (call-interactively 'org-previous-item))
19268 ((org-clocktable-try-shift 'up arg))
19269 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19270 (org-support-shift-select
19271 (org-call-for-shift-select 'previous-line))
19272 (t (org-shiftselect-error))))
19274 (defun org-shiftdown (&optional arg)
19275 "Decrease item in timestamp or decrease priority of current headline.
19276 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19277 depending on context. See the individual commands for more information."
19278 (interactive "P")
19279 (cond
19280 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19281 ((and org-support-shift-select (org-region-active-p))
19282 (org-call-for-shift-select 'next-line))
19283 ((org-at-timestamp-p t)
19284 (call-interactively (if org-edit-timestamp-down-means-later
19285 'org-timestamp-up 'org-timestamp-down)))
19286 ((and (not (eq org-support-shift-select 'always))
19287 org-enable-priority-commands
19288 (org-at-heading-p))
19289 (call-interactively 'org-priority-down))
19290 ((and (not org-support-shift-select) (org-at-item-p))
19291 (call-interactively 'org-next-item))
19292 ((org-clocktable-try-shift 'down arg))
19293 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19294 (org-support-shift-select
19295 (org-call-for-shift-select 'next-line))
19296 (t (org-shiftselect-error))))
19298 (defun org-shiftright (&optional arg)
19299 "Cycle the thing at point or in the current line, depending on context.
19300 Depending on context, this does one of the following:
19302 - switch a timestamp at point one day into the future
19303 - on a headline, switch to the next TODO keyword.
19304 - on an item, switch entire list to the next bullet type
19305 - on a property line, switch to the next allowed value
19306 - on a clocktable definition line, move time block into the future"
19307 (interactive "P")
19308 (cond
19309 ((run-hook-with-args-until-success 'org-shiftright-hook))
19310 ((and org-support-shift-select (org-region-active-p))
19311 (org-call-for-shift-select 'forward-char))
19312 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19313 ((and (not (eq org-support-shift-select 'always))
19314 (org-at-heading-p))
19315 (let ((org-inhibit-logging
19316 (not org-treat-S-cursor-todo-selection-as-state-change))
19317 (org-inhibit-blocking
19318 (not org-treat-S-cursor-todo-selection-as-state-change)))
19319 (org-call-with-arg 'org-todo 'right)))
19320 ((or (and org-support-shift-select
19321 (not (eq org-support-shift-select 'always))
19322 (org-at-item-bullet-p))
19323 (and (not org-support-shift-select) (org-at-item-p)))
19324 (org-call-with-arg 'org-cycle-list-bullet nil))
19325 ((and (not (eq org-support-shift-select 'always))
19326 (org-at-property-p))
19327 (call-interactively 'org-property-next-allowed-value))
19328 ((org-clocktable-try-shift 'right arg))
19329 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19330 (org-support-shift-select
19331 (org-call-for-shift-select 'forward-char))
19332 (t (org-shiftselect-error))))
19334 (defun org-shiftleft (&optional arg)
19335 "Cycle the thing at point or in the current line, depending on context.
19336 Depending on context, this does one of the following:
19338 - switch a timestamp at point one day into the past
19339 - on a headline, switch to the previous TODO keyword.
19340 - on an item, switch entire list to the previous bullet type
19341 - on a property line, switch to the previous allowed value
19342 - on a clocktable definition line, move time block into the past"
19343 (interactive "P")
19344 (cond
19345 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19346 ((and org-support-shift-select (org-region-active-p))
19347 (org-call-for-shift-select 'backward-char))
19348 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19349 ((and (not (eq org-support-shift-select 'always))
19350 (org-at-heading-p))
19351 (let ((org-inhibit-logging
19352 (not org-treat-S-cursor-todo-selection-as-state-change))
19353 (org-inhibit-blocking
19354 (not org-treat-S-cursor-todo-selection-as-state-change)))
19355 (org-call-with-arg 'org-todo 'left)))
19356 ((or (and org-support-shift-select
19357 (not (eq org-support-shift-select 'always))
19358 (org-at-item-bullet-p))
19359 (and (not org-support-shift-select) (org-at-item-p)))
19360 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19361 ((and (not (eq org-support-shift-select 'always))
19362 (org-at-property-p))
19363 (call-interactively 'org-property-previous-allowed-value))
19364 ((org-clocktable-try-shift 'left arg))
19365 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19366 (org-support-shift-select
19367 (org-call-for-shift-select 'backward-char))
19368 (t (org-shiftselect-error))))
19370 (defun org-shiftcontrolright ()
19371 "Switch to next TODO set."
19372 (interactive)
19373 (cond
19374 ((and org-support-shift-select (org-region-active-p))
19375 (org-call-for-shift-select 'forward-word))
19376 ((and (not (eq org-support-shift-select 'always))
19377 (org-at-heading-p))
19378 (org-call-with-arg 'org-todo 'nextset))
19379 (org-support-shift-select
19380 (org-call-for-shift-select 'forward-word))
19381 (t (org-shiftselect-error))))
19383 (defun org-shiftcontrolleft ()
19384 "Switch to previous TODO set."
19385 (interactive)
19386 (cond
19387 ((and org-support-shift-select (org-region-active-p))
19388 (org-call-for-shift-select 'backward-word))
19389 ((and (not (eq org-support-shift-select 'always))
19390 (org-at-heading-p))
19391 (org-call-with-arg 'org-todo 'previousset))
19392 (org-support-shift-select
19393 (org-call-for-shift-select 'backward-word))
19394 (t (org-shiftselect-error))))
19396 (defun org-shiftcontrolup (&optional n)
19397 "Change timestamps synchronously up in CLOCK log lines.
19398 Optional argument N tells to change by that many units."
19399 (interactive "P")
19400 (cond ((and (not org-support-shift-select)
19401 (org-at-clock-log-p)
19402 (org-at-timestamp-p t))
19403 (org-clock-timestamps-up n))
19404 (t (org-shiftselect-error))))
19406 (defun org-shiftcontroldown (&optional n)
19407 "Change timestamps synchronously down in CLOCK log lines.
19408 Optional argument N tells to change by that many units."
19409 (interactive "P")
19410 (cond ((and (not org-support-shift-select)
19411 (org-at-clock-log-p)
19412 (org-at-timestamp-p t))
19413 (org-clock-timestamps-down n))
19414 (t (org-shiftselect-error))))
19416 (defun org-ctrl-c-ret ()
19417 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19418 (interactive)
19419 (cond
19420 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19421 (t (call-interactively 'org-insert-heading))))
19423 (defun org-find-visible ()
19424 (let ((s (point)))
19425 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19426 (get-char-property s 'invisible)))
19428 (defun org-find-invisible ()
19429 (let ((s (point)))
19430 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19431 (not (get-char-property s 'invisible))))
19434 (defun org-copy-visible (beg end)
19435 "Copy the visible parts of the region."
19436 (interactive "r")
19437 (let (snippets s)
19438 (save-excursion
19439 (save-restriction
19440 (narrow-to-region beg end)
19441 (setq s (goto-char (point-min)))
19442 (while (not (= (point) (point-max)))
19443 (goto-char (org-find-invisible))
19444 (push (buffer-substring s (point)) snippets)
19445 (setq s (goto-char (org-find-visible))))))
19446 (kill-new (apply 'concat (nreverse snippets)))))
19448 (defun org-copy-special ()
19449 "Copy region in table or copy current subtree.
19450 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19451 See the individual commands for more information."
19452 (interactive)
19453 (call-interactively
19454 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19456 (defun org-cut-special ()
19457 "Cut region in table or cut current subtree.
19458 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19459 See the individual commands for more information."
19460 (interactive)
19461 (call-interactively
19462 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19464 (defun org-paste-special (arg)
19465 "Paste rectangular region into table, or past subtree relative to level.
19466 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19467 See the individual commands for more information."
19468 (interactive "P")
19469 (if (org-at-table-p)
19470 (org-table-paste-rectangle)
19471 (org-paste-subtree arg)))
19473 (defsubst org-in-fixed-width-region-p ()
19474 "Is point in a fixed-width region?"
19475 (save-match-data
19476 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19478 (defun org-edit-special (&optional arg)
19479 "Call a special editor for the element at point.
19480 When at a table, call the formula editor with `org-table-edit-formulas'.
19481 When in a source code block, call `org-edit-src-code'.
19482 When in a fixed-width region, call `org-edit-fixed-width-region'.
19483 When at an #+INCLUDE keyword, visit the included file.
19484 On a link, call `ffap' to visit the link at point.
19485 Otherwise, return a user error."
19486 (interactive)
19487 (let ((element (org-element-at-point)))
19488 (case (org-element-type element)
19489 (src-block
19490 (if (not arg) (org-edit-src-code)
19491 (let* ((info (org-babel-get-src-block-info))
19492 (lang (nth 0 info))
19493 (params (nth 2 info))
19494 (session (cdr (assq :session params))))
19495 (if (not session) (org-edit-src-code)
19496 ;; At a src-block with a session and function called with
19497 ;; an ARG: switch to the buffer related to the inferior
19498 ;; process.
19499 (funcall (intern (concat "org-babel-prep-session:" lang))
19500 session params)))))
19501 (keyword
19502 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19503 (find-file
19504 (org-remove-double-quotes
19505 (car (org-split-string (org-element-property :value element)))))
19506 (user-error "No special environment to edit here")))
19507 (table
19508 (if (eq (org-element-property :type element) 'table.el)
19509 (org-edit-src-code)
19510 (call-interactively 'org-table-edit-formulas)))
19511 ;; Only Org tables contain `table-row' type elements.
19512 (table-row (call-interactively 'org-table-edit-formulas))
19513 ((example-block export-block) (org-edit-src-code))
19514 (fixed-width (org-edit-fixed-width-region))
19515 (otherwise
19516 ;; No notable element at point. Though, we may be at a link,
19517 ;; which is an object. Thus, scan deeper.
19518 (if (eq (org-element-type (org-element-context element)) 'link)
19519 (call-interactively 'ffap)
19520 (user-error "No special environment to edit here"))))))
19522 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19523 (defun org-ctrl-c-ctrl-c (&optional arg)
19524 "Set tags in headline, or update according to changed information at point.
19526 This command does many different things, depending on context:
19528 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19529 this is what we do.
19531 - If the cursor is on a statistics cookie, update it.
19533 - If the cursor is in a headline, prompt for tags and insert them
19534 into the current line, aligned to `org-tags-column'. When called
19535 with prefix arg, realign all tags in the current buffer.
19537 - If the cursor is in one of the special #+KEYWORD lines, this
19538 triggers scanning the buffer for these lines and updating the
19539 information.
19541 - If the cursor is inside a table, realign the table. This command
19542 works even if the automatic table editor has been turned off.
19544 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19545 the entire table.
19547 - If the cursor is at a footnote reference or definition, jump to
19548 the corresponding definition or references, respectively.
19550 - If the cursor is a the beginning of a dynamic block, update it.
19552 - If the current buffer is a capture buffer, close note and file it.
19554 - If the cursor is on a <<<target>>>, update radio targets and
19555 corresponding links in this buffer.
19557 - If the cursor is on a numbered item in a plain list, renumber the
19558 ordered list.
19560 - If the cursor is on a checkbox, toggle it.
19562 - If the cursor is on a code block, evaluate it. The variable
19563 `org-confirm-babel-evaluate' can be used to control prompting
19564 before code block evaluation, by default every code block
19565 evaluation requires confirmation. Code block evaluation can be
19566 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19567 (interactive "P")
19568 (cond
19569 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19570 org-occur-highlights
19571 org-latex-fragment-image-overlays)
19572 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19573 (org-remove-occur-highlights)
19574 (org-remove-latex-fragment-image-overlays)
19575 (message "Temporary highlights/overlays removed from current buffer"))
19576 ((and (local-variable-p 'org-finish-function (current-buffer))
19577 (fboundp org-finish-function))
19578 (funcall org-finish-function))
19579 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19581 (let* ((context (org-element-context)) (type (org-element-type context)))
19582 ;; Test if point is within blanks at the end of an element.
19583 (if (save-excursion
19584 (or (not context)
19585 (beginning-of-line)
19586 (and (looking-at "[ \t]*$")
19587 (skip-chars-forward " \r\t\n")
19588 (>= (point) (org-element-property :end context)))))
19589 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19590 (user-error "C-c C-c can do nothing useful at this location"))
19591 ;; For convenience: at the first line of a paragraph on the
19592 ;; same line as an item, apply function on that item instead.
19593 (when (eq type 'paragraph)
19594 (let ((parent (org-element-property :parent context)))
19595 (when (and (eq (org-element-type parent) 'item)
19596 (= (point-at-bol) (org-element-property :begin parent)))
19597 (setq context parent type 'item))))
19598 ;; Act according to type of element or object at point.
19599 (case type
19600 (clock (org-clock-update-time-maybe))
19601 (dynamic-block
19602 (save-excursion
19603 (goto-char (org-element-property :post-affiliated context))
19604 (org-update-dblock)))
19605 (footnote-definition
19606 (goto-char (org-element-property :post-affiliated context))
19607 (call-interactively 'org-footnote-action))
19608 (footnote-reference (call-interactively 'org-footnote-action))
19609 ((headline inlinetask)
19610 (save-excursion (goto-char (org-element-property :begin context))
19611 (call-interactively 'org-set-tags)))
19612 (item
19613 ;; At an item: a double C-u set checkbox to "[-]"
19614 ;; unconditionally, whereas a single one will toggle its
19615 ;; presence. Without an universal argument, if the item
19616 ;; has a checkbox, toggle it. Otherwise repair the list.
19617 (let* ((box (org-element-property :checkbox context))
19618 (struct (org-element-property :structure context))
19619 (old-struct (copy-tree struct))
19620 (parents (org-list-parents-alist struct))
19621 (prevs (org-list-prevs-alist struct))
19622 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19623 (org-list-set-checkbox
19624 (org-element-property :begin context) struct
19625 (cond ((equal arg '(16)) "[-]")
19626 ((and (not box) (equal arg '(4))) "[ ]")
19627 ((or (not box) (equal arg '(4))) nil)
19628 ((eq box 'on) "[ ]")
19629 (t "[X]")))
19630 ;; Mimic `org-list-write-struct' but with grabbing
19631 ;; a return value from `org-list-struct-fix-box'.
19632 (org-list-struct-fix-ind struct parents 2)
19633 (org-list-struct-fix-item-end struct)
19634 (org-list-struct-fix-bul struct prevs)
19635 (org-list-struct-fix-ind struct parents)
19636 (let ((block-item
19637 (org-list-struct-fix-box struct parents prevs orderedp)))
19638 (if (and box (equal struct old-struct))
19639 (if (equal arg '(16))
19640 (message "Checkboxes already reset")
19641 (user-error "Cannot toggle this checkbox: %s"
19642 (if (eq box 'on)
19643 "all subitems checked"
19644 "unchecked subitems")))
19645 (org-list-struct-apply-struct struct old-struct)
19646 (org-update-checkbox-count-maybe))
19647 (when block-item
19648 (message "Checkboxes were removed due to empty box at line %d"
19649 (org-current-line block-item))))))
19650 (keyword
19651 (let ((org-inhibit-startup-visibility-stuff t)
19652 (org-startup-align-all-tables nil))
19653 (when (boundp 'org-table-coordinate-overlays)
19654 (mapc 'delete-overlay org-table-coordinate-overlays)
19655 (setq org-table-coordinate-overlays nil))
19656 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19657 (message "Local setup has been refreshed"))
19658 (plain-list
19659 ;; At a plain list, with a double C-u argument, set
19660 ;; checkboxes of each item to "[-]", whereas a single one
19661 ;; will toggle their presence according to the state of the
19662 ;; first item in the list. Without an argument, repair the
19663 ;; list.
19664 (let* ((begin (org-element-property :contents-begin context))
19665 (struct (org-element-property :structure context))
19666 (old-struct (copy-tree struct))
19667 (first-box (save-excursion
19668 (goto-char begin)
19669 (looking-at org-list-full-item-re)
19670 (match-string-no-properties 3)))
19671 (new-box (cond ((equal arg '(16)) "[-]")
19672 ((equal arg '(4)) (unless first-box "[ ]"))
19673 ((equal first-box "[X]") "[ ]")
19674 (t "[X]"))))
19675 (cond
19676 (arg
19677 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19678 (org-list-get-all-items
19679 begin struct (org-list-prevs-alist struct))))
19680 ((and first-box (eq (point) begin))
19681 ;; For convenience, when point is at bol on the first
19682 ;; item of the list and no argument is provided, simply
19683 ;; toggle checkbox of that item, if any.
19684 (org-list-set-checkbox begin struct new-box)))
19685 (org-list-write-struct
19686 struct (org-list-parents-alist struct) old-struct)
19687 (org-update-checkbox-count-maybe)
19688 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19689 ((property-drawer node-property)
19690 (call-interactively 'org-property-action))
19691 ((radio-target target)
19692 (call-interactively 'org-update-radio-target-regexp))
19693 (statistics-cookie
19694 (call-interactively 'org-update-statistics-cookies))
19695 ((table table-cell table-row)
19696 ;; At a table, recalculate every field and align it. Also
19697 ;; send the table if necessary. If the table has
19698 ;; a `table.el' type, just give up. At a table row or
19699 ;; cell, maybe recalculate line but always align table.
19700 (if (eq (org-element-property :type context) 'table.el)
19701 (message "Use C-c ' to edit table.el tables")
19702 (let ((org-enable-table-editor t))
19703 (if (or (eq type 'table)
19704 ;; Check if point is at a TBLFM line.
19705 (and (eq type 'table-row)
19706 (= (point) (org-element-property :end context))))
19707 (save-excursion
19708 (goto-char (org-element-property :contents-begin context))
19709 (org-call-with-arg 'org-table-recalculate (or arg t))
19710 (orgtbl-send-table 'maybe))
19711 (org-table-maybe-eval-formula)
19712 (cond (arg (call-interactively 'org-table-recalculate))
19713 ((org-table-maybe-recalculate-line))
19714 (t (org-table-align)))))))
19715 (timestamp (org-timestamp-change 0 'day))
19716 (otherwise
19717 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19718 (user-error
19719 "C-c C-c can do nothing useful at this location")))))))))
19721 (defun org-mode-restart ()
19722 "Restart Org-mode, to scan again for special lines.
19723 Also updates the keyword regular expressions."
19724 (interactive)
19725 (org-mode)
19726 (message "Org-mode restarted"))
19728 (defun org-kill-note-or-show-branches ()
19729 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19730 (interactive)
19731 (if (not org-finish-function)
19732 (progn
19733 (hide-subtree)
19734 (call-interactively 'show-branches))
19735 (let ((org-note-abort t))
19736 (funcall org-finish-function))))
19738 (defun org-return (&optional indent)
19739 "Goto next table row or insert a newline.
19740 Calls `org-table-next-row' or `newline', depending on context.
19741 See the individual commands for more information."
19742 (interactive)
19743 (let (org-ts-what)
19744 (cond
19745 ((or (bobp) (org-in-src-block-p))
19746 (if indent (newline-and-indent) (newline)))
19747 ((org-at-table-p)
19748 (org-table-justify-field-maybe)
19749 (call-interactively 'org-table-next-row))
19750 ;; when `newline-and-indent' is called within a list, make sure
19751 ;; text moved stays inside the item.
19752 ((and (org-in-item-p) indent)
19753 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19754 (progn
19755 (save-match-data (newline))
19756 (org-indent-line-to (length (match-string 0))))
19757 (let ((ind (org-get-indentation)))
19758 (newline)
19759 (if (org-looking-back org-list-end-re)
19760 (org-indent-line)
19761 (org-indent-line-to ind)))))
19762 ((and org-return-follows-link
19763 (org-at-timestamp-p t)
19764 (not (eq org-ts-what 'after)))
19765 (org-follow-timestamp-link))
19766 ((and org-return-follows-link
19767 (let ((tprop (get-text-property (point) 'face)))
19768 (or (eq tprop 'org-link)
19769 (and (listp tprop) (memq 'org-link tprop)))))
19770 (call-interactively 'org-open-at-point))
19771 ((and (org-at-heading-p)
19772 (looking-at
19773 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19774 (org-show-entry)
19775 (end-of-line 1)
19776 (newline))
19777 (t (if indent (newline-and-indent) (newline))))))
19779 (defun org-return-indent ()
19780 "Goto next table row or insert a newline and indent.
19781 Calls `org-table-next-row' or `newline-and-indent', depending on
19782 context. See the individual commands for more information."
19783 (interactive)
19784 (org-return t))
19786 (defun org-ctrl-c-star ()
19787 "Compute table, or change heading status of lines.
19788 Calls `org-table-recalculate' or `org-toggle-heading',
19789 depending on context."
19790 (interactive)
19791 (cond
19792 ((org-at-table-p)
19793 (call-interactively 'org-table-recalculate))
19795 ;; Convert all lines in region to list items
19796 (call-interactively 'org-toggle-heading))))
19798 (defun org-ctrl-c-minus ()
19799 "Insert separator line in table or modify bullet status of line.
19800 Also turns a plain line or a region of lines into list items.
19801 Calls `org-table-insert-hline', `org-toggle-item', or
19802 `org-cycle-list-bullet', depending on context."
19803 (interactive)
19804 (cond
19805 ((org-at-table-p)
19806 (call-interactively 'org-table-insert-hline))
19807 ((org-region-active-p)
19808 (call-interactively 'org-toggle-item))
19809 ((org-in-item-p)
19810 (call-interactively 'org-cycle-list-bullet))
19812 (call-interactively 'org-toggle-item))))
19814 (defun org-toggle-item (arg)
19815 "Convert headings or normal lines to items, items to normal lines.
19816 If there is no active region, only the current line is considered.
19818 If the first non blank line in the region is an headline, convert
19819 all headlines to items, shifting text accordingly.
19821 If it is an item, convert all items to normal lines.
19823 If it is normal text, change region into an item. With a prefix
19824 argument ARG, change each line in region into an item."
19825 (interactive "P")
19826 (let ((shift-text
19827 (function
19828 ;; Shift text in current section to IND, from point to END.
19829 ;; The function leaves point to END line.
19830 (lambda (ind end)
19831 (let ((min-i 1000) (end (copy-marker end)))
19832 ;; First determine the minimum indentation (MIN-I) of
19833 ;; the text.
19834 (save-excursion
19835 (catch 'exit
19836 (while (< (point) end)
19837 (let ((i (org-get-indentation)))
19838 (cond
19839 ;; Skip blank lines and inline tasks.
19840 ((looking-at "^[ \t]*$"))
19841 ((looking-at org-outline-regexp-bol))
19842 ;; We can't find less than 0 indentation.
19843 ((zerop i) (throw 'exit (setq min-i 0)))
19844 ((< i min-i) (setq min-i i))))
19845 (forward-line))))
19846 ;; Then indent each line so that a line indented to
19847 ;; MIN-I becomes indented to IND. Ignore blank lines
19848 ;; and inline tasks in the process.
19849 (let ((delta (- ind min-i)))
19850 (while (< (point) end)
19851 (unless (or (looking-at "^[ \t]*$")
19852 (looking-at org-outline-regexp-bol))
19853 (org-indent-line-to (+ (org-get-indentation) delta)))
19854 (forward-line)))))))
19855 (skip-blanks
19856 (function
19857 ;; Return beginning of first non-blank line, starting from
19858 ;; line at POS.
19859 (lambda (pos)
19860 (save-excursion
19861 (goto-char pos)
19862 (skip-chars-forward " \r\t\n")
19863 (point-at-bol)))))
19864 beg end)
19865 ;; Determine boundaries of changes.
19866 (if (org-region-active-p)
19867 (setq beg (funcall skip-blanks (region-beginning))
19868 end (copy-marker (region-end)))
19869 (setq beg (funcall skip-blanks (point-at-bol))
19870 end (copy-marker (point-at-eol))))
19871 ;; Depending on the starting line, choose an action on the text
19872 ;; between BEG and END.
19873 (org-with-limited-levels
19874 (save-excursion
19875 (goto-char beg)
19876 (cond
19877 ;; Case 1. Start at an item: de-itemize. Note that it only
19878 ;; happens when a region is active: `org-ctrl-c-minus'
19879 ;; would call `org-cycle-list-bullet' otherwise.
19880 ((org-at-item-p)
19881 (while (< (point) end)
19882 (when (org-at-item-p)
19883 (skip-chars-forward " \t")
19884 (delete-region (point) (match-end 0)))
19885 (forward-line)))
19886 ;; Case 2. Start at an heading: convert to items.
19887 ((org-at-heading-p)
19888 (let* ((bul (org-list-bullet-string "-"))
19889 (bul-len (length bul))
19890 ;; Indentation of the first heading. It should be
19891 ;; relative to the indentation of its parent, if any.
19892 (start-ind (save-excursion
19893 (cond
19894 ((not org-adapt-indentation) 0)
19895 ((not (outline-previous-heading)) 0)
19896 (t (length (match-string 0))))))
19897 ;; Level of first heading. Further headings will be
19898 ;; compared to it to determine hierarchy in the list.
19899 (ref-level (org-reduced-level (org-outline-level))))
19900 (while (< (point) end)
19901 (let* ((level (org-reduced-level (org-outline-level)))
19902 (delta (max 0 (- level ref-level))))
19903 ;; If current headline is less indented than the first
19904 ;; one, set it as reference, in order to preserve
19905 ;; subtrees.
19906 (when (< level ref-level) (setq ref-level level))
19907 (replace-match bul t t)
19908 (org-indent-line-to (+ start-ind (* delta bul-len)))
19909 ;; Ensure all text down to END (or SECTION-END) belongs
19910 ;; to the newly created item.
19911 (let ((section-end (save-excursion
19912 (or (outline-next-heading) (point)))))
19913 (forward-line)
19914 (funcall shift-text
19915 (+ start-ind (* (1+ delta) bul-len))
19916 (min end section-end)))))))
19917 ;; Case 3. Normal line with ARG: turn each non-item line into
19918 ;; an item.
19919 (arg
19920 (while (< (point) end)
19921 (unless (or (org-at-heading-p) (org-at-item-p))
19922 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19923 (replace-match
19924 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19925 (forward-line)))
19926 ;; Case 4. Normal line without ARG: make the first line of
19927 ;; region an item, and shift indentation of others
19928 ;; lines to set them as item's body.
19929 (t (let* ((bul (org-list-bullet-string "-"))
19930 (bul-len (length bul))
19931 (ref-ind (org-get-indentation)))
19932 (skip-chars-forward " \t")
19933 (insert bul)
19934 (forward-line)
19935 (while (< (point) end)
19936 ;; Ensure that lines less indented than first one
19937 ;; still get included in item body.
19938 (funcall shift-text
19939 (+ ref-ind bul-len)
19940 (min end (save-excursion (or (outline-next-heading)
19941 (point)))))
19942 (forward-line)))))))))
19944 (defun org-toggle-heading (&optional nstars)
19945 "Convert headings to normal text, or items or text to headings.
19946 If there is no active region, only the current line is considered.
19948 With a \\[universal-argument] prefix, convert the whole list at
19949 point into heading.
19951 In a region:
19953 - If the first non blank line is an headline, remove the stars
19954 from all headlines in the region.
19956 - If it is a normal line turn each and every normal line (i.e. not an
19957 heading or an item) in the region into a heading.
19959 - If it is a plain list item, turn all plain list items into headings.
19961 When converting a line into a heading, the number of stars is chosen
19962 such that the lines become children of the current entry. However,
19963 when a prefix argument is given, its value determines the number of
19964 stars to add."
19965 (interactive "P")
19966 (let ((skip-blanks
19967 (function
19968 ;; Return beginning of first non-blank line, starting from
19969 ;; line at POS.
19970 (lambda (pos)
19971 (save-excursion
19972 (goto-char pos)
19973 (while (org-at-comment-p) (forward-line))
19974 (skip-chars-forward " \r\t\n")
19975 (point-at-bol)))))
19976 beg end toggled)
19977 ;; Determine boundaries of changes. If a universal prefix has
19978 ;; been given, put the list in a region. If region ends at a bol,
19979 ;; do not consider the last line to be in the region.
19981 (when (and current-prefix-arg (org-at-item-p))
19982 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19983 (org-mark-element))
19985 (if (org-region-active-p)
19986 (setq beg (funcall skip-blanks (region-beginning))
19987 end (copy-marker (save-excursion
19988 (goto-char (region-end))
19989 (if (bolp) (point) (point-at-eol)))))
19990 (setq beg (funcall skip-blanks (point-at-bol))
19991 end (copy-marker (point-at-eol))))
19992 ;; Ensure inline tasks don't count as headings.
19993 (org-with-limited-levels
19994 (save-excursion
19995 (goto-char beg)
19996 (cond
19997 ;; Case 1. Started at an heading: de-star headings.
19998 ((org-at-heading-p)
19999 (while (< (point) end)
20000 (when (org-at-heading-p t)
20001 (looking-at org-outline-regexp) (replace-match "")
20002 (setq toggled t))
20003 (forward-line)))
20004 ;; Case 2. Started at an item: change items into headlines.
20005 ;; One star will be added by `org-list-to-subtree'.
20006 ((org-at-item-p)
20007 (let* ((stars (make-string
20008 (if nstars
20009 ;; subtract the star that will be added again by
20010 ;; `org-list-to-subtree'
20011 (1- (prefix-numeric-value current-prefix-arg))
20012 (or (org-current-level) 0))
20013 ?*))
20014 (add-stars
20015 (cond (nstars "") ; stars from prefix only
20016 ((equal stars "") "") ; before first heading
20017 (org-odd-levels-only "*") ; inside heading, odd
20018 (t "")))) ; inside heading, oddeven
20019 (while (< (point) end)
20020 (when (org-at-item-p)
20021 ;; Pay attention to cases when region ends before list.
20022 (let* ((struct (org-list-struct))
20023 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20024 (save-restriction
20025 (narrow-to-region (point) list-end)
20026 (insert
20027 (org-list-to-subtree
20028 (org-list-parse-list t)
20029 '(:istart (concat stars add-stars (funcall get-stars depth))
20030 :icount (concat stars add-stars (funcall get-stars depth)))))))
20031 (setq toggled t))
20032 (forward-line))))
20033 ;; Case 3. Started at normal text: make every line an heading,
20034 ;; skipping headlines and items.
20035 (t (let* ((stars (make-string
20036 (if nstars
20037 (prefix-numeric-value current-prefix-arg)
20038 (or (org-current-level) 0))
20039 ?*))
20040 (add-stars
20041 (cond (nstars "") ; stars from prefix only
20042 ((equal stars "") "*") ; before first heading
20043 (org-odd-levels-only "**") ; inside heading, odd
20044 (t "*"))) ; inside heading, oddeven
20045 (rpl (concat stars add-stars " ")))
20046 (while (< (point) end)
20047 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20048 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20049 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20050 (forward-line)))))))
20051 (unless toggled (message "Cannot toggle heading from here"))))
20053 (defun org-meta-return (&optional arg)
20054 "Insert a new heading or wrap a region in a table.
20055 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20056 See the individual commands for more information."
20057 (interactive "P")
20058 (cond
20059 ((run-hook-with-args-until-success 'org-metareturn-hook))
20060 ((or (org-at-drawer-p) (org-at-property-p))
20061 (newline-and-indent))
20062 ((org-at-table-p)
20063 (call-interactively 'org-table-wrap-region))
20064 (t (call-interactively 'org-insert-heading))))
20066 ;;; Menu entries
20068 (defsubst org-in-subtree-not-table-p ()
20069 "Are we in a subtree and not in a table?"
20070 (and (not (org-before-first-heading-p))
20071 (not (org-at-table-p))))
20073 ;; Define the Org-mode menus
20074 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20075 '("Tbl"
20076 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20077 ["Next Field" org-cycle (org-at-table-p)]
20078 ["Previous Field" org-shifttab (org-at-table-p)]
20079 ["Next Row" org-return (org-at-table-p)]
20080 "--"
20081 ["Blank Field" org-table-blank-field (org-at-table-p)]
20082 ["Edit Field" org-table-edit-field (org-at-table-p)]
20083 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20084 "--"
20085 ("Column"
20086 ["Move Column Left" org-metaleft (org-at-table-p)]
20087 ["Move Column Right" org-metaright (org-at-table-p)]
20088 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20089 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20090 ("Row"
20091 ["Move Row Up" org-metaup (org-at-table-p)]
20092 ["Move Row Down" org-metadown (org-at-table-p)]
20093 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20094 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20095 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20096 "--"
20097 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20098 ("Rectangle"
20099 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20100 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20101 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20102 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20103 "--"
20104 ("Calculate"
20105 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20106 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20107 ["Edit Formulas" org-edit-special (org-at-table-p)]
20108 "--"
20109 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20110 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20111 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20112 "--"
20113 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20114 "--"
20115 ["Sum Column/Rectangle" org-table-sum
20116 (or (org-at-table-p) (org-region-active-p))]
20117 ["Which Column?" org-table-current-column (org-at-table-p)])
20118 ["Debug Formulas"
20119 org-table-toggle-formula-debugger
20120 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20121 ["Show Col/Row Numbers"
20122 org-table-toggle-coordinate-overlays
20123 :style toggle
20124 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20125 "--"
20126 ["Create" org-table-create (and (not (org-at-table-p))
20127 org-enable-table-editor)]
20128 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20129 ["Import from File" org-table-import (not (org-at-table-p))]
20130 ["Export to File" org-table-export (org-at-table-p)]
20131 "--"
20132 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20134 (easy-menu-define org-org-menu org-mode-map "Org menu"
20135 '("Org"
20136 ("Show/Hide"
20137 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20138 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20139 ["Sparse Tree..." org-sparse-tree t]
20140 ["Reveal Context" org-reveal t]
20141 ["Show All" show-all t]
20142 "--"
20143 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20144 "--"
20145 ["New Heading" org-insert-heading t]
20146 ("Navigate Headings"
20147 ["Up" outline-up-heading t]
20148 ["Next" outline-next-visible-heading t]
20149 ["Previous" outline-previous-visible-heading t]
20150 ["Next Same Level" outline-forward-same-level t]
20151 ["Previous Same Level" outline-backward-same-level t]
20152 "--"
20153 ["Jump" org-goto t])
20154 ("Edit Structure"
20155 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20156 "--"
20157 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20158 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20159 "--"
20160 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20161 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20162 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20163 "--"
20164 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20165 "--"
20166 ["Copy visible text" org-copy-visible t]
20167 "--"
20168 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20169 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20170 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20171 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20172 "--"
20173 ["Sort Region/Children" org-sort t]
20174 "--"
20175 ["Convert to odd levels" org-convert-to-odd-levels t]
20176 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20177 ("Editing"
20178 ["Emphasis..." org-emphasize t]
20179 ["Edit Source Example" org-edit-special t]
20180 "--"
20181 ["Footnote new/jump" org-footnote-action t]
20182 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20183 ("Archive"
20184 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20185 "--"
20186 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20187 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20188 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20190 "--"
20191 ("Hyperlinks"
20192 ["Store Link (Global)" org-store-link t]
20193 ["Find existing link to here" org-occur-link-in-agenda-files t]
20194 ["Insert Link" org-insert-link t]
20195 ["Follow Link" org-open-at-point t]
20196 "--"
20197 ["Next link" org-next-link t]
20198 ["Previous link" org-previous-link t]
20199 "--"
20200 ["Descriptive Links"
20201 org-toggle-link-display
20202 :style radio
20203 :selected org-descriptive-links
20205 ["Literal Links"
20206 org-toggle-link-display
20207 :style radio
20208 :selected (not org-descriptive-links)])
20209 "--"
20210 ("TODO Lists"
20211 ["TODO/DONE/-" org-todo t]
20212 ("Select keyword"
20213 ["Next keyword" org-shiftright (org-at-heading-p)]
20214 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20215 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20216 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20217 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20218 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20219 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20220 "--"
20221 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20222 :selected org-enforce-todo-dependencies :style toggle :active t]
20223 "Settings for tree at point"
20224 ["Do Children sequentially" org-toggle-ordered-property :style radio
20225 :selected (org-entry-get nil "ORDERED")
20226 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20227 ["Do Children parallel" org-toggle-ordered-property :style radio
20228 :selected (not (org-entry-get nil "ORDERED"))
20229 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20230 "--"
20231 ["Set Priority" org-priority t]
20232 ["Priority Up" org-shiftup t]
20233 ["Priority Down" org-shiftdown t]
20234 "--"
20235 ["Get news from all feeds" org-feed-update-all t]
20236 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20237 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20238 ("TAGS and Properties"
20239 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20240 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20241 "--"
20242 ["Set property" org-set-property (not (org-before-first-heading-p))]
20243 ["Column view of properties" org-columns t]
20244 ["Insert Column View DBlock" org-insert-columns-dblock t])
20245 ("Dates and Scheduling"
20246 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20247 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20248 ("Change Date"
20249 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20250 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20251 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20252 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20253 ["Compute Time Range" org-evaluate-time-range t]
20254 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20255 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20256 "--"
20257 ["Custom time format" org-toggle-time-stamp-overlays
20258 :style radio :selected org-display-custom-times]
20259 "--"
20260 ["Goto Calendar" org-goto-calendar t]
20261 ["Date from Calendar" org-date-from-calendar t]
20262 "--"
20263 ["Start/Restart Timer" org-timer-start t]
20264 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20265 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20266 ["Insert Timer String" org-timer t]
20267 ["Insert Timer Item" org-timer-item t])
20268 ("Logging work"
20269 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20270 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20271 ["Clock out" org-clock-out t]
20272 ["Clock cancel" org-clock-cancel t]
20273 "--"
20274 ["Mark as default task" org-clock-mark-default-task t]
20275 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20276 ["Goto running clock" org-clock-goto t]
20277 "--"
20278 ["Display times" org-clock-display t]
20279 ["Create clock table" org-clock-report t]
20280 "--"
20281 ["Record DONE time"
20282 (progn (setq org-log-done (not org-log-done))
20283 (message "Switching to %s will %s record a timestamp"
20284 (car org-done-keywords)
20285 (if org-log-done "automatically" "not")))
20286 :style toggle :selected org-log-done])
20287 "--"
20288 ["Agenda Command..." org-agenda t]
20289 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20290 ("File List for Agenda")
20291 ("Special views current file"
20292 ["TODO Tree" org-show-todo-tree t]
20293 ["Check Deadlines" org-check-deadlines t]
20294 ["Timeline" org-timeline t]
20295 ["Tags/Property tree" org-match-sparse-tree t])
20296 "--"
20297 ["Export/Publish..." org-export t]
20298 ("LaTeX"
20299 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20300 :selected org-cdlatex-mode]
20301 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20302 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20303 ["Modify math symbol" org-cdlatex-math-modify
20304 (org-inside-LaTeX-fragment-p)]
20305 ["Insert citation" org-reftex-citation t]
20306 "--"
20307 ["Template for BEAMER" (progn (require 'org-beamer)
20308 (org-insert-beamer-options-template)) t])
20309 "--"
20310 ("MobileOrg"
20311 ["Push Files and Views" org-mobile-push t]
20312 ["Get Captured and Flagged" org-mobile-pull t]
20313 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20314 "--"
20315 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20316 "--"
20317 ("Documentation"
20318 ["Show Version" org-version t]
20319 ["Info Documentation" org-info t])
20320 ("Customize"
20321 ["Browse Org Group" org-customize t]
20322 "--"
20323 ["Expand This Menu" org-create-customize-menu
20324 (fboundp 'customize-menu-create)])
20325 ["Send bug report" org-submit-bug-report t]
20326 "--"
20327 ("Refresh/Reload"
20328 ["Refresh setup current buffer" org-mode-restart t]
20329 ["Reload Org (after update)" org-reload t]
20330 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20333 (defun org-info (&optional node)
20334 "Read documentation for Org-mode in the info system.
20335 With optional NODE, go directly to that node."
20336 (interactive)
20337 (info (format "(org)%s" (or node ""))))
20339 ;;;###autoload
20340 (defun org-submit-bug-report ()
20341 "Submit a bug report on Org-mode via mail.
20343 Don't hesitate to report any problems or inaccurate documentation.
20345 If you don't have setup sending mail from (X)Emacs, please copy the
20346 output buffer into your mail program, as it gives us important
20347 information about your Org-mode version and configuration."
20348 (interactive)
20349 (require 'reporter)
20350 (org-load-modules-maybe)
20351 (org-require-autoloaded-modules)
20352 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20353 (reporter-submit-bug-report
20354 "emacs-orgmode@gnu.org"
20355 (org-version nil 'full)
20356 (let (list)
20357 (save-window-excursion
20358 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20359 (delete-other-windows)
20360 (erase-buffer)
20361 (insert "You are about to submit a bug report to the Org-mode mailing list.
20363 We would like to add your full Org-mode and Outline configuration to the
20364 bug report. This greatly simplifies the work of the maintainer and
20365 other experts on the mailing list.
20367 HOWEVER, some variables you have customized may contain private
20368 information. The names of customers, colleagues, or friends, might
20369 appear in the form of file names, tags, todo states, or search strings.
20370 If you answer yes to the prompt, you might want to check and remove
20371 such private information before sending the email.")
20372 (add-text-properties (point-min) (point-max) '(face org-warning))
20373 (when (yes-or-no-p "Include your Org-mode configuration ")
20374 (mapatoms
20375 (lambda (v)
20376 (and (boundp v)
20377 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20378 (or (and (symbol-value v)
20379 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20380 (and
20381 (get v 'custom-type) (get v 'standard-value)
20382 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20383 (push v list)))))
20384 (kill-buffer (get-buffer "*Warn about privacy*"))
20385 list))
20386 nil nil
20387 "Remember to cover the basics, that is, what you expected to happen and
20388 what in fact did happen. You don't know how to make a good report? See
20390 http://orgmode.org/manual/Feedback.html#Feedback
20392 Your bug report will be posted to the Org-mode mailing list.
20393 ------------------------------------------------------------------------")
20394 (save-excursion
20395 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20396 (replace-match "\\1Bug: \\3 [\\2]")))))
20399 (defun org-install-agenda-files-menu ()
20400 (let ((bl (buffer-list)))
20401 (save-excursion
20402 (while bl
20403 (set-buffer (pop bl))
20404 (if (derived-mode-p 'org-mode) (setq bl nil)))
20405 (when (derived-mode-p 'org-mode)
20406 (easy-menu-change
20407 '("Org") "File List for Agenda"
20408 (append
20409 (list
20410 ["Edit File List" (org-edit-agenda-file-list) t]
20411 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20412 ["Remove Current File from List" org-remove-file t]
20413 ["Cycle through agenda files" org-cycle-agenda-files t]
20414 ["Occur in all agenda files" org-occur-in-agenda-files t]
20415 "--")
20416 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20418 ;;;; Documentation
20420 (defun org-require-autoloaded-modules ()
20421 (interactive)
20422 (mapc 'require
20423 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20424 org-docbook org-exp org-html org-icalendar
20425 org-id org-latex
20426 org-publish org-remember org-table
20427 org-timer org-xoxo)))
20429 ;;;###autoload
20430 (defun org-reload (&optional uncompiled)
20431 "Reload all org lisp files.
20432 With prefix arg UNCOMPILED, load the uncompiled versions."
20433 (interactive "P")
20434 (require 'loadhist)
20435 (let* ((org-dir (org-find-library-dir "org"))
20436 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20437 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20438 (remove-re (mapconcat 'identity
20439 (mapcar (lambda (f) (concat "^" f "$"))
20440 (list (if (featurep 'xemacs)
20441 "org-colview"
20442 "org-colview-xemacs")
20443 "org" "org-loaddefs" "org-version"))
20444 "\\|"))
20445 (feats (delete-dups
20446 (mapcar 'file-name-sans-extension
20447 (mapcar 'file-name-nondirectory
20448 (delq nil
20449 (mapcar 'feature-file
20450 features))))))
20451 (lfeat (append
20452 (sort
20453 (setq feats
20454 (delq nil (mapcar
20455 (lambda (f)
20456 (if (and (string-match feature-re f)
20457 (not (string-match remove-re f)))
20458 f nil))
20459 feats)))
20460 'string-lessp)
20461 (list "org-version" "org")))
20462 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20463 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20464 load-uncore load-misses)
20465 (setq load-misses
20466 (delq 't
20467 (mapcar (lambda (f)
20468 (or (org-load-noerror-mustsuffix (concat org-dir f))
20469 (and (string= org-dir contrib-dir)
20470 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20471 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20472 (add-to-list 'load-uncore f 'append)
20475 lfeat)))
20476 (if load-uncore
20477 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20478 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20479 (if load-misses
20480 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20481 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20482 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20484 ;;;###autoload
20485 (defun org-customize ()
20486 "Call the customize function with org as argument."
20487 (interactive)
20488 (org-load-modules-maybe)
20489 (org-require-autoloaded-modules)
20490 (customize-browse 'org))
20492 (defun org-create-customize-menu ()
20493 "Create a full customization menu for Org-mode, insert it into the menu."
20494 (interactive)
20495 (org-load-modules-maybe)
20496 (org-require-autoloaded-modules)
20497 (if (fboundp 'customize-menu-create)
20498 (progn
20499 (easy-menu-change
20500 '("Org") "Customize"
20501 `(["Browse Org group" org-customize t]
20502 "--"
20503 ,(customize-menu-create 'org)
20504 ["Set" Custom-set t]
20505 ["Save" Custom-save t]
20506 ["Reset to Current" Custom-reset-current t]
20507 ["Reset to Saved" Custom-reset-saved t]
20508 ["Reset to Standard Settings" Custom-reset-standard t]))
20509 (message "\"Org\"-menu now contains full customization menu"))
20510 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20512 ;;;; Miscellaneous stuff
20514 ;;; Generally useful functions
20516 (defun org-get-at-bol (property)
20517 "Get text property PROPERTY at beginning of line."
20518 (get-text-property (point-at-bol) property))
20520 (defun org-find-text-property-in-string (prop s)
20521 "Return the first non-nil value of property PROP in string S."
20522 (or (get-text-property 0 prop s)
20523 (get-text-property (or (next-single-property-change 0 prop s) 0)
20524 prop s)))
20526 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20527 "Display the given MESSAGE as a warning."
20528 (if (fboundp 'display-warning)
20529 (display-warning 'org message
20530 (if (featurep 'xemacs) 'warning :warning))
20531 (let ((buf (get-buffer-create "*Org warnings*")))
20532 (with-current-buffer buf
20533 (goto-char (point-max))
20534 (insert "Warning (Org): " message)
20535 (unless (bolp)
20536 (newline)))
20537 (display-buffer buf)
20538 (sit-for 0))))
20540 (defun org-eval (form)
20541 "Eval FORM and return result."
20542 (condition-case error
20543 (eval form)
20544 (error (format "%%![Error: %s]" error))))
20546 (defun org-in-clocktable-p ()
20547 "Check if the cursor is in a clocktable."
20548 (let ((pos (point)) start)
20549 (save-excursion
20550 (end-of-line 1)
20551 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20552 (setq start (match-beginning 0))
20553 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20554 (>= (match-end 0) pos)
20555 start))))
20557 (defun org-in-commented-line ()
20558 "Is point in a line starting with `#'?"
20559 (equal (char-after (point-at-bol)) ?#))
20561 (defun org-in-indented-comment-line ()
20562 "Is point in a line starting with `#' after some white space?"
20563 (save-excursion
20564 (save-match-data
20565 (goto-char (point-at-bol))
20566 (looking-at "[ \t]*#"))))
20568 (defun org-in-verbatim-emphasis ()
20569 (save-match-data
20570 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20572 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20573 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20574 (if (and marker (marker-buffer marker)
20575 (buffer-live-p (marker-buffer marker)))
20576 (progn
20577 (org-pop-to-buffer-same-window (marker-buffer marker))
20578 (if (or (> marker (point-max)) (< marker (point-min)))
20579 (widen))
20580 (goto-char marker)
20581 (org-show-context 'org-goto))
20582 (if bookmark
20583 (bookmark-jump bookmark)
20584 (error "Cannot find location"))))
20586 (defun org-quote-csv-field (s)
20587 "Quote field for inclusion in CSV material."
20588 (if (string-match "[\",]" s)
20589 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20592 (defun org-force-self-insert (N)
20593 "Needed to enforce self-insert under remapping."
20594 (interactive "p")
20595 (self-insert-command N))
20597 (defun org-string-width (s)
20598 "Compute width of string, ignoring invisible characters.
20599 This ignores character with invisibility property `org-link', and also
20600 characters with property `org-cwidth', because these will become invisible
20601 upon the next fontification round."
20602 (let (b l)
20603 (when (or (eq t buffer-invisibility-spec)
20604 (assq 'org-link buffer-invisibility-spec))
20605 (while (setq b (text-property-any 0 (length s)
20606 'invisible 'org-link s))
20607 (setq s (concat (substring s 0 b)
20608 (substring s (or (next-single-property-change
20609 b 'invisible s) (length s)))))))
20610 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20611 (setq s (concat (substring s 0 b)
20612 (substring s (or (next-single-property-change
20613 b 'org-cwidth s) (length s))))))
20614 (setq l (string-width s) b -1)
20615 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20616 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20619 (defun org-shorten-string (s maxlength)
20620 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20621 If the string is shorter or has length MAXLENGTH, just return the
20622 original string. If it is longer, the functions finds a space in the
20623 string, breaks this string off at that locations and adds three dots
20624 as ellipsis. Including the ellipsis, the string will not be longer
20625 than MAXLENGTH. If finding a good breaking point in the string does
20626 not work, the string is just chopped off in the middle of a word
20627 if necessary."
20628 (if (<= (length s) maxlength)
20630 (let* ((n (max (- maxlength 4) 1))
20631 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20632 (if (string-match re s)
20633 (concat (match-string 1 s) "...")
20634 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20636 (defun org-get-indentation (&optional line)
20637 "Get the indentation of the current line, interpreting tabs.
20638 When LINE is given, assume it represents a line and compute its indentation."
20639 (if line
20640 (if (string-match "^ *" (org-remove-tabs line))
20641 (match-end 0))
20642 (save-excursion
20643 (beginning-of-line 1)
20644 (skip-chars-forward " \t")
20645 (current-column))))
20647 (defun org-get-string-indentation (s)
20648 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20649 (let ((n -1) (i 0) (w tab-width) c)
20650 (catch 'exit
20651 (while (< (setq n (1+ n)) (length s))
20652 (setq c (aref s n))
20653 (cond ((= c ?\ ) (setq i (1+ i)))
20654 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20655 (t (throw 'exit t)))))
20658 (defun org-remove-tabs (s &optional width)
20659 "Replace tabulators in S with spaces.
20660 Assumes that s is a single line, starting in column 0."
20661 (setq width (or width tab-width))
20662 (while (string-match "\t" s)
20663 (setq s (replace-match
20664 (make-string
20665 (- (* width (/ (+ (match-beginning 0) width) width))
20666 (match-beginning 0)) ?\ )
20667 t t s)))
20670 (defun org-fix-indentation (line ind)
20671 "Fix indentation in LINE.
20672 IND is a cons cell with target and minimum indentation.
20673 If the current indentation in LINE is smaller than the minimum,
20674 leave it alone. If it is larger than ind, set it to the target."
20675 (let* ((l (org-remove-tabs line))
20676 (i (org-get-indentation l))
20677 (i1 (car ind)) (i2 (cdr ind)))
20678 (if (>= i i2) (setq l (substring line i2)))
20679 (if (> i1 0)
20680 (concat (make-string i1 ?\ ) l)
20681 l)))
20683 (defun org-remove-indentation (code &optional n)
20684 "Remove the maximum common indentation from the lines in CODE.
20685 N may optionally be the number of spaces to remove."
20686 (with-temp-buffer
20687 (insert code)
20688 (org-do-remove-indentation n)
20689 (buffer-string)))
20691 (defun org-do-remove-indentation (&optional n)
20692 "Remove the maximum common indentation from the buffer."
20693 (untabify (point-min) (point-max))
20694 (let ((min 10000) re)
20695 (if n
20696 (setq min n)
20697 (goto-char (point-min))
20698 (while (re-search-forward "^ *[^ \n]" nil t)
20699 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20700 (unless (or (= min 0) (= min 10000))
20701 (setq re (format "^ \\{%d\\}" min))
20702 (goto-char (point-min))
20703 (while (re-search-forward re nil t)
20704 (replace-match "")
20705 (end-of-line 1))
20706 min)))
20708 (defun org-fill-template (template alist)
20709 "Find each %key of ALIST in TEMPLATE and replace it."
20710 (let ((case-fold-search nil)
20711 entry key value)
20712 (setq alist (sort (copy-sequence alist)
20713 (lambda (a b) (< (length (car a)) (length (car b))))))
20714 (while (setq entry (pop alist))
20715 (setq template
20716 (replace-regexp-in-string
20717 (concat "%" (regexp-quote (car entry)))
20718 (or (cdr entry) "") template t t)))
20719 template))
20721 (defun org-base-buffer (buffer)
20722 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20723 (if (not buffer)
20724 buffer
20725 (or (buffer-base-buffer buffer)
20726 buffer)))
20728 (defun org-trim (s)
20729 "Remove whitespace at beginning and end of string."
20730 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20731 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20734 (defun org-wrap (string &optional width lines)
20735 "Wrap string to either a number of lines, or a width in characters.
20736 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20737 that costs. If there is a word longer than WIDTH, the text is actually
20738 wrapped to the length of that word.
20739 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20740 many lines, whatever width that takes.
20741 The return value is a list of lines, without newlines at the end."
20742 (let* ((words (org-split-string string "[ \t\n]+"))
20743 (maxword (apply 'max (mapcar 'org-string-width words)))
20744 w ll)
20745 (cond (width
20746 (org-do-wrap words (max maxword width)))
20747 (lines
20748 (setq w maxword)
20749 (setq ll (org-do-wrap words maxword))
20750 (if (<= (length ll) lines)
20752 (setq ll words)
20753 (while (> (length ll) lines)
20754 (setq w (1+ w))
20755 (setq ll (org-do-wrap words w)))
20756 ll))
20757 (t (error "Cannot wrap this")))))
20759 (defun org-do-wrap (words width)
20760 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20761 (let (lines line)
20762 (while words
20763 (setq line (pop words))
20764 (while (and words (< (+ (length line) (length (car words))) width))
20765 (setq line (concat line " " (pop words))))
20766 (setq lines (push line lines)))
20767 (nreverse lines)))
20769 (defun org-split-string (string &optional separators)
20770 "Splits STRING into substrings at SEPARATORS.
20771 No empty strings are returned if there are matches at the beginning
20772 and end of string."
20773 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20774 (start 0)
20775 notfirst
20776 (list nil))
20777 (while (and (string-match rexp string
20778 (if (and notfirst
20779 (= start (match-beginning 0))
20780 (< start (length string)))
20781 (1+ start) start))
20782 (< (match-beginning 0) (length string)))
20783 (setq notfirst t)
20784 (or (eq (match-beginning 0) 0)
20785 (and (eq (match-beginning 0) (match-end 0))
20786 (eq (match-beginning 0) start))
20787 (setq list
20788 (cons (substring string start (match-beginning 0))
20789 list)))
20790 (setq start (match-end 0)))
20791 (or (eq start (length string))
20792 (setq list
20793 (cons (substring string start)
20794 list)))
20795 (nreverse list)))
20797 (defun org-quote-vert (s)
20798 "Replace \"|\" with \"\\vert\"."
20799 (while (string-match "|" s)
20800 (setq s (replace-match "\\vert" t t s)))
20803 (defun org-uuidgen-p (s)
20804 "Is S an ID created by UUIDGEN?"
20805 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20807 (defun org-in-src-block-p (&optional inside)
20808 "Whether point is in a code source block.
20809 When INSIDE is non-nil, don't consider we are within a src block
20810 when point is at #+BEGIN_SRC or #+END_SRC."
20811 (let ((case-fold-search t) ov)
20812 (or (and (setq ov (overlays-at (point)))
20813 (memq 'org-block-background
20814 (overlay-properties (car ov))))
20815 (and (not inside)
20816 (save-match-data
20817 (save-excursion
20818 (beginning-of-line)
20819 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20821 (defun org-context ()
20822 "Return a list of contexts of the current cursor position.
20823 If several contexts apply, all are returned.
20824 Each context entry is a list with a symbol naming the context, and
20825 two positions indicating start and end of the context. Possible
20826 contexts are:
20828 :headline anywhere in a headline
20829 :headline-stars on the leading stars in a headline
20830 :todo-keyword on a TODO keyword (including DONE) in a headline
20831 :tags on the TAGS in a headline
20832 :priority on the priority cookie in a headline
20833 :item on the first line of a plain list item
20834 :item-bullet on the bullet/number of a plain list item
20835 :checkbox on the checkbox in a plain list item
20836 :table in an org-mode table
20837 :table-special on a special filed in a table
20838 :table-table in a table.el table
20839 :clocktable in a clocktable
20840 :src-block in a source block
20841 :link on a hyperlink
20842 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20843 :target on a <<target>>
20844 :radio-target on a <<<radio-target>>>
20845 :latex-fragment on a LaTeX fragment
20846 :latex-preview on a LaTeX fragment with overlaid preview image
20848 This function expects the position to be visible because it uses font-lock
20849 faces as a help to recognize the following contexts: :table-special, :link,
20850 and :keyword."
20851 (let* ((f (get-text-property (point) 'face))
20852 (faces (if (listp f) f (list f)))
20853 (case-fold-search t)
20854 (p (point)) clist o)
20855 ;; First the large context
20856 (cond
20857 ((org-at-heading-p t)
20858 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20859 (when (progn
20860 (beginning-of-line 1)
20861 (looking-at org-todo-line-tags-regexp))
20862 (push (org-point-in-group p 1 :headline-stars) clist)
20863 (push (org-point-in-group p 2 :todo-keyword) clist)
20864 (push (org-point-in-group p 4 :tags) clist))
20865 (goto-char p)
20866 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20867 (if (looking-at "\\[#[A-Z0-9]\\]")
20868 (push (org-point-in-group p 0 :priority) clist)))
20870 ((org-at-item-p)
20871 (push (org-point-in-group p 2 :item-bullet) clist)
20872 (push (list :item (point-at-bol)
20873 (save-excursion (org-end-of-item) (point)))
20874 clist)
20875 (and (org-at-item-checkbox-p)
20876 (push (org-point-in-group p 0 :checkbox) clist)))
20878 ((org-at-table-p)
20879 (push (list :table (org-table-begin) (org-table-end)) clist)
20880 (if (memq 'org-formula faces)
20881 (push (list :table-special
20882 (previous-single-property-change p 'face)
20883 (next-single-property-change p 'face)) clist)))
20884 ((org-at-table-p 'any)
20885 (push (list :table-table) clist)))
20886 (goto-char p)
20888 (let ((case-fold-search t))
20889 ;; New the "medium" contexts: clocktables, source blocks
20890 (cond ((org-in-clocktable-p)
20891 (push (list :clocktable
20892 (and (or (looking-at "#\\+BEGIN: clocktable")
20893 (search-backward "#+BEGIN: clocktable" nil t))
20894 (match-beginning 0))
20895 (and (re-search-forward "#\\+END:?" nil t)
20896 (match-end 0))) clist))
20897 ((org-in-src-block-p)
20898 (push (list :src-block
20899 (and (or (looking-at "#\\+BEGIN_SRC")
20900 (search-backward "#+BEGIN_SRC" nil t))
20901 (match-beginning 0))
20902 (and (search-forward "#+END_SRC" nil t)
20903 (match-beginning 0))) clist))))
20904 (goto-char p)
20906 ;; Now the small context
20907 (cond
20908 ((org-at-timestamp-p)
20909 (push (org-point-in-group p 0 :timestamp) clist))
20910 ((memq 'org-link faces)
20911 (push (list :link
20912 (previous-single-property-change p 'face)
20913 (next-single-property-change p 'face)) clist))
20914 ((memq 'org-special-keyword faces)
20915 (push (list :keyword
20916 (previous-single-property-change p 'face)
20917 (next-single-property-change p 'face)) clist))
20918 ((org-at-target-p)
20919 (push (org-point-in-group p 0 :target) clist)
20920 (goto-char (1- (match-beginning 0)))
20921 (if (looking-at org-radio-target-regexp)
20922 (push (org-point-in-group p 0 :radio-target) clist))
20923 (goto-char p))
20924 ((setq o (car (delq nil
20925 (mapcar
20926 (lambda (x)
20927 (if (memq x org-latex-fragment-image-overlays) x))
20928 (overlays-at (point))))))
20929 (push (list :latex-fragment
20930 (overlay-start o) (overlay-end o)) clist)
20931 (push (list :latex-preview
20932 (overlay-start o) (overlay-end o)) clist))
20933 ((org-inside-LaTeX-fragment-p)
20934 ;; FIXME: positions wrong.
20935 (push (list :latex-fragment (point) (point)) clist)))
20937 (setq clist (nreverse (delq nil clist)))
20938 clist))
20940 ;; FIXME: Compare with at-regexp-p Do we need both?
20941 (defun org-in-regexp (re &optional nlines visually)
20942 "Check if point is inside a match of regexp.
20943 Normally only the current line is checked, but you can include NLINES extra
20944 lines both before and after point into the search.
20945 If VISUALLY is set, require that the cursor is not after the match but
20946 really on, so that the block visually is on the match."
20947 (catch 'exit
20948 (let ((pos (point))
20949 (eol (point-at-eol (+ 1 (or nlines 0))))
20950 (inc (if visually 1 0)))
20951 (save-excursion
20952 (beginning-of-line (- 1 (or nlines 0)))
20953 (while (re-search-forward re eol t)
20954 (if (and (<= (match-beginning 0) pos)
20955 (>= (+ inc (match-end 0)) pos))
20956 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20958 (defun org-at-regexp-p (regexp)
20959 "Is point inside a match of REGEXP in the current line?"
20960 (catch 'exit
20961 (save-excursion
20962 (let ((pos (point)) (end (point-at-eol)))
20963 (beginning-of-line 1)
20964 (while (re-search-forward regexp end t)
20965 (if (and (<= (match-beginning 0) pos)
20966 (>= (match-end 0) pos))
20967 (throw 'exit t)))
20968 nil))))
20970 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20971 "Non-nil when point is between matches of START-RE and END-RE.
20973 Also return a non-nil value when point is on one of the matches.
20975 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20976 buffer positions. Default values are the positions of headlines
20977 surrounding the point.
20979 The functions returns a cons cell whose car (resp. cdr) is the
20980 position before START-RE (resp. after END-RE)."
20981 (save-match-data
20982 (let ((pos (point))
20983 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20984 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20985 beg end)
20986 (save-excursion
20987 ;; Point is on a block when on START-RE or if START-RE can be
20988 ;; found before it...
20989 (and (or (org-at-regexp-p start-re)
20990 (re-search-backward start-re limit-up t))
20991 (setq beg (match-beginning 0))
20992 ;; ... and END-RE after it...
20993 (goto-char (match-end 0))
20994 (re-search-forward end-re limit-down t)
20995 (> (setq end (match-end 0)) pos)
20996 ;; ... without another START-RE in-between.
20997 (goto-char (match-beginning 0))
20998 (not (re-search-backward start-re (1+ beg) t))
20999 ;; Return value.
21000 (cons beg end))))))
21002 (defun org-in-block-p (names)
21003 "Non-nil when point belongs to a block whose name belongs to NAMES.
21005 NAMES is a list of strings containing names of blocks.
21007 Return first block name matched, or nil. Beware that in case of
21008 nested blocks, the returned name may not belong to the closest
21009 block from point."
21010 (save-match-data
21011 (catch 'exit
21012 (let ((case-fold-search t)
21013 (lim-up (save-excursion (outline-previous-heading)))
21014 (lim-down (save-excursion (outline-next-heading))))
21015 (mapc (lambda (name)
21016 (let ((n (regexp-quote name)))
21017 (when (org-between-regexps-p
21018 (concat "^[ \t]*#\\+begin_" n)
21019 (concat "^[ \t]*#\\+end_" n)
21020 lim-up lim-down)
21021 (throw 'exit n))))
21022 names))
21023 nil)))
21025 (defun org-occur-in-agenda-files (regexp &optional nlines)
21026 "Call `multi-occur' with buffers for all agenda files."
21027 (interactive "sOrg-files matching: \np")
21028 (let* ((files (org-agenda-files))
21029 (tnames (mapcar 'file-truename files))
21030 (extra org-agenda-text-search-extra-files)
21032 (when (eq (car extra) 'agenda-archives)
21033 (setq extra (cdr extra))
21034 (setq files (org-add-archive-files files)))
21035 (while (setq f (pop extra))
21036 (unless (member (file-truename f) tnames)
21037 (add-to-list 'files f 'append)
21038 (add-to-list 'tnames (file-truename f) 'append)))
21039 (multi-occur
21040 (mapcar (lambda (x)
21041 (with-current-buffer
21042 (or (get-file-buffer x) (find-file-noselect x))
21043 (widen)
21044 (current-buffer)))
21045 files)
21046 regexp)))
21048 (if (boundp 'occur-mode-find-occurrence-hook)
21049 ;; Emacs 23
21050 (add-hook 'occur-mode-find-occurrence-hook
21051 (lambda ()
21052 (when (derived-mode-p 'org-mode)
21053 (org-reveal))))
21054 ;; Emacs 22
21055 (defadvice occur-mode-goto-occurrence
21056 (after org-occur-reveal activate)
21057 (and (derived-mode-p 'org-mode) (org-reveal)))
21058 (defadvice occur-mode-goto-occurrence-other-window
21059 (after org-occur-reveal activate)
21060 (and (derived-mode-p 'org-mode) (org-reveal)))
21061 (defadvice occur-mode-display-occurrence
21062 (after org-occur-reveal activate)
21063 (when (derived-mode-p 'org-mode)
21064 (let ((pos (occur-mode-find-occurrence)))
21065 (with-current-buffer (marker-buffer pos)
21066 (save-excursion
21067 (goto-char pos)
21068 (org-reveal)))))))
21070 (defun org-occur-link-in-agenda-files ()
21071 "Create a link and search for it in the agendas.
21072 The link is not stored in `org-stored-links', it is just created
21073 for the search purpose."
21074 (interactive)
21075 (let ((link (condition-case nil
21076 (org-store-link nil)
21077 (error "Unable to create a link to here"))))
21078 (org-occur-in-agenda-files (regexp-quote link))))
21080 (defun org-uniquify (list)
21081 "Remove duplicate elements from LIST."
21082 (let (res)
21083 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21084 res))
21086 (defun org-delete-all (elts list)
21087 "Remove all elements in ELTS from LIST."
21088 (while elts
21089 (setq list (delete (pop elts) list)))
21090 list)
21092 (defun org-count (cl-item cl-seq)
21093 "Count the number of occurrences of ITEM in SEQ.
21094 Taken from `count' in cl-seq.el with all keyword arguments removed."
21095 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21096 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21097 (while (< cl-start cl-end)
21098 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21099 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21100 (setq cl-start (1+ cl-start)))
21101 cl-count))
21103 (defun org-remove-if (predicate seq)
21104 "Remove everything from SEQ that fulfills PREDICATE."
21105 (let (res e)
21106 (while seq
21107 (setq e (pop seq))
21108 (if (not (funcall predicate e)) (push e res)))
21109 (nreverse res)))
21111 (defun org-remove-if-not (predicate seq)
21112 "Remove everything from SEQ that does not fulfill PREDICATE."
21113 (let (res e)
21114 (while seq
21115 (setq e (pop seq))
21116 (if (funcall predicate e) (push e res)))
21117 (nreverse res)))
21119 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21120 "Reduce two-argument FUNCTION across SEQ.
21121 Taken from `reduce' in cl-seq.el with all keyword arguments but
21122 \":initial-value\" removed."
21123 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21124 (cadr (memq :initial-value cl-keys)))
21125 (cl-seq (pop cl-seq))
21126 (t (funcall cl-func)))))
21127 (while cl-seq
21128 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21129 cl-accum))
21131 (defun org-back-over-empty-lines ()
21132 "Move backwards over whitespace, to the beginning of the first empty line.
21133 Returns the number of empty lines passed."
21134 (let ((pos (point)))
21135 (if (cdr (assoc 'heading org-blank-before-new-entry))
21136 (skip-chars-backward " \t\n\r")
21137 (unless (eobp)
21138 (forward-line -1)))
21139 (beginning-of-line 2)
21140 (goto-char (min (point) pos))
21141 (count-lines (point) pos)))
21143 (defun org-skip-whitespace ()
21144 (skip-chars-forward " \t\n\r"))
21146 (defun org-point-in-group (point group &optional context)
21147 "Check if POINT is in match-group GROUP.
21148 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21149 match. If the match group does not exist or point is not inside it,
21150 return nil."
21151 (and (match-beginning group)
21152 (>= point (match-beginning group))
21153 (<= point (match-end group))
21154 (if context
21155 (list context (match-beginning group) (match-end group))
21156 t)))
21158 (defun org-switch-to-buffer-other-window (&rest args)
21159 "Switch to buffer in a second window on the current frame.
21160 In particular, do not allow pop-up frames.
21161 Returns the newly created buffer."
21162 (org-no-popups
21163 (apply 'switch-to-buffer-other-window args)))
21165 (defun org-combine-plists (&rest plists)
21166 "Create a single property list from all plists in PLISTS.
21167 The process starts by copying the first list, and then setting properties
21168 from the other lists. Settings in the last list are the most significant
21169 ones and overrule settings in the other lists."
21170 (let ((rtn (copy-sequence (pop plists)))
21171 p v ls)
21172 (while plists
21173 (setq ls (pop plists))
21174 (while ls
21175 (setq p (pop ls) v (pop ls))
21176 (setq rtn (plist-put rtn p v))))
21177 rtn))
21179 (defun org-replace-escapes (string table)
21180 "Replace %-escapes in STRING with values in TABLE.
21181 TABLE is an association list with keys like \"%a\" and string values.
21182 The sequences in STRING may contain normal field width and padding information,
21183 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21184 so values can contain further %-escapes if they are define later in TABLE."
21185 (let ((tbl (copy-alist table))
21186 (case-fold-search nil)
21187 (pchg 0)
21188 e re rpl)
21189 (while (setq e (pop tbl))
21190 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21191 (when (and (cdr e) (string-match re (cdr e)))
21192 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21193 (safe "SREF"))
21194 (add-text-properties 0 3 (list 'sref sref) safe)
21195 (setcdr e (replace-match safe t t (cdr e)))))
21196 (while (string-match re string)
21197 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21198 (cdr e)))
21199 (setq string (replace-match rpl t t string))))
21200 (while (setq pchg (next-property-change pchg string))
21201 (let ((sref (get-text-property pchg 'sref string)))
21202 (when (and sref (string-match "SREF" string pchg))
21203 (setq string (replace-match sref t t string)))))
21204 string))
21206 (defun org-sublist (list start end)
21207 "Return a section of LIST, from START to END.
21208 Counting starts at 1."
21209 (let (rtn (c start))
21210 (setq list (nthcdr (1- start) list))
21211 (while (and list (<= c end))
21212 (push (pop list) rtn)
21213 (setq c (1+ c)))
21214 (nreverse rtn)))
21216 (defun org-find-base-buffer-visiting (file)
21217 "Like `find-buffer-visiting' but always return the base buffer and
21218 not an indirect buffer."
21219 (let ((buf (or (get-file-buffer file)
21220 (find-buffer-visiting file))))
21221 (if buf
21222 (or (buffer-base-buffer buf) buf)
21223 nil)))
21225 (defun org-image-file-name-regexp (&optional extensions)
21226 "Return regexp matching the file names of images.
21227 If EXTENSIONS is given, only match these."
21228 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21229 (image-file-name-regexp)
21230 (let ((image-file-name-extensions
21231 (or extensions
21232 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21233 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21234 (concat "\\."
21235 (regexp-opt (nconc (mapcar 'upcase
21236 image-file-name-extensions)
21237 image-file-name-extensions)
21239 "\\'"))))
21241 (defun org-file-image-p (file &optional extensions)
21242 "Return non-nil if FILE is an image."
21243 (save-match-data
21244 (string-match (org-image-file-name-regexp extensions) file)))
21246 (defun org-get-cursor-date (&optional with-time)
21247 "Return the date at cursor in as a time.
21248 This works in the calendar and in the agenda, anywhere else it just
21249 returns the current time.
21250 If WITH-TIME is non-nil, returns the time of the event at point (in
21251 the agenda) or the current time of the day."
21252 (let (date day defd tp tm hod mod)
21253 (when with-time
21254 (setq tp (get-text-property (point) 'time))
21255 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21256 (setq hod (string-to-number (match-string 1 tp))
21257 mod (string-to-number (match-string 2 tp))))
21258 (or tp (setq hod (nth 2 (decode-time (current-time)))
21259 mod (nth 1 (decode-time (current-time))))))
21260 (cond
21261 ((eq major-mode 'calendar-mode)
21262 (setq date (calendar-cursor-to-date)
21263 defd (encode-time 0 (or mod 0) (or hod 0)
21264 (nth 1 date) (nth 0 date) (nth 2 date))))
21265 ((eq major-mode 'org-agenda-mode)
21266 (setq day (get-text-property (point) 'day))
21267 (if day
21268 (setq date (calendar-gregorian-from-absolute day)
21269 defd (encode-time 0 (or mod 0) (or hod 0)
21270 (nth 1 date) (nth 0 date) (nth 2 date))))))
21271 (or defd (current-time))))
21273 (defun org-mark-subtree (&optional up)
21274 "Mark the current subtree.
21275 This puts point at the start of the current subtree, and mark at
21276 the end. If a numeric prefix UP is given, move up into the
21277 hierarchy of headlines by UP levels before marking the subtree."
21278 (interactive "P")
21279 (org-with-limited-levels
21280 (cond ((org-at-heading-p) (beginning-of-line))
21281 ((org-before-first-heading-p) (error "Not in a subtree"))
21282 (t (outline-previous-visible-heading 1))))
21283 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21284 (if (org-called-interactively-p 'any)
21285 (call-interactively 'org-mark-element)
21286 (org-mark-element)))
21289 ;;; Macros
21291 ;; Macros are expanded with `org-macro-replace-all', which relies
21292 ;; internally on `org-macro-expand'.
21294 ;; Default templates for expansion are stored in the buffer-local
21295 ;; variable `org-macro-templates'. This variable is updated by
21296 ;; `org-macro-initialize-templates'.
21298 ;; Along with macros defined through #+MACRO: keyword, default
21299 ;; templates include the following hard-coded macros:
21300 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21301 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21303 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21304 ;; {{{title}}} will also be provided.
21307 (defvar org-macro-templates nil
21308 "Alist containing all macro templates in current buffer.
21309 Associations are in the shape of (NAME . TEMPLATE) where NAME
21310 stands for macro's name and template for its replacement value,
21311 both as strings. This is an internal variable. Do not set it
21312 directly, use instead:
21314 #+MACRO: name template")
21315 (make-variable-buffer-local 'org-macro-templates)
21317 (defun org-macro-expand (macro templates)
21318 "Return expanded MACRO, as a string.
21319 MACRO is an object, obtained, for example, with
21320 `org-element-context'. TEMPLATES is an alist of templates used
21321 for expansion. See `org-macro-templates' for a buffer-local
21322 default value. Return nil if no template was found."
21323 (let ((template
21324 ;; Macro names are case-insensitive.
21325 (cdr (assoc-string (org-element-property :key macro) templates t))))
21326 (when template
21327 (let ((value (replace-regexp-in-string
21328 "\\$[0-9]+"
21329 (lambda (arg)
21330 (or (nth (1- (string-to-number (substring arg 1)))
21331 (org-element-property :args macro))
21332 ;; No argument provided: remove
21333 ;; place-holder.
21334 ""))
21335 template)))
21336 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21337 (when (string-match "\\`(eval\\>" value)
21338 (setq value (eval (read value))))
21339 ;; Return string.
21340 (format "%s" (or value ""))))))
21342 (defun org-macro-replace-all (templates)
21343 "Replace all macros in current buffer by their expansion.
21344 TEMPLATES is an alist of templates used for expansion. See
21345 `org-macro-templates' for a buffer-local default value."
21346 (save-excursion
21347 (goto-char (point-min))
21348 (let (record)
21349 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21350 (let ((object (org-element-context)))
21351 (when (eq (org-element-type object) 'macro)
21352 (let* ((value (org-macro-expand object templates))
21353 (begin (org-element-property :begin object))
21354 (signature (list begin
21355 object
21356 (org-element-property :args object))))
21357 ;; Avoid circular dependencies by checking if the same
21358 ;; macro with the same arguments is expanded at the same
21359 ;; position twice.
21360 (if (member signature record)
21361 (error "Circular macro expansion: %s"
21362 (org-element-property :key object))
21363 (when value
21364 (push signature record)
21365 (delete-region
21366 begin
21367 ;; Preserve white spaces after the macro.
21368 (progn (goto-char (org-element-property :end object))
21369 (skip-chars-backward " \t")
21370 (point)))
21371 ;; Leave point before replacement in case of recursive
21372 ;; expansions.
21373 (save-excursion (insert value)))))))))))
21375 (defun org-macro-initialize-templates ()
21376 "Collect macro templates defined in current buffer.
21377 Templates are stored in buffer-local variable
21378 `org-macro-templates'. In addition to buffer-defined macros, the
21379 function installs the following ones: \"property\",
21380 \"time\". and, if the buffer is associated to a file,
21381 \"input-file\" and \"modification-time\"."
21382 (let ((case-fold-search t)
21383 (set-template
21384 (lambda (cell)
21385 ;; Add CELL to `org-macro-templates' if there's no
21386 ;; association matching its name already. Otherwise,
21387 ;; replace old association with the new one in that
21388 ;; variable.
21389 (let ((old-template (assoc (car cell) org-macro-templates)))
21390 (if old-template (setcdr old-template (cdr cell))
21391 (push cell org-macro-templates))))))
21392 ;; Install buffer-local macros.
21393 (org-with-wide-buffer
21394 (goto-char (point-min))
21395 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21396 (let ((element (org-element-at-point)))
21397 (when (eq (org-element-type element) 'keyword)
21398 (let ((value (org-element-property :value element)))
21399 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21400 (funcall set-template
21401 (cons (match-string 1 value)
21402 (or (match-string 2 value) "")))))))))
21403 ;; Install hard-coded macros.
21404 (mapc (lambda (cell) (funcall set-template cell))
21405 (list
21406 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21407 (cons "time" "(eval (format-time-string \"$1\"))")))
21408 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21409 (when (and visited-file (file-exists-p visited-file))
21410 (mapc (lambda (cell) (funcall set-template cell))
21411 (list
21412 (cons "input-file" (file-name-nondirectory visited-file))
21413 (cons "modification-time"
21414 (format "(eval (format-time-string \"$1\" '%s))"
21415 (prin1-to-string
21416 (nth 5 (file-attributes visited-file)))))))))))
21419 ;;; Indentation
21421 (defun org-indent-line ()
21422 "Indent line depending on context."
21423 (interactive)
21424 (let* ((pos (point))
21425 (itemp (org-at-item-p))
21426 (case-fold-search t)
21427 (org-drawer-regexp (or org-drawer-regexp "\000"))
21428 (inline-task-p (and (featurep 'org-inlinetask)
21429 (org-inlinetask-in-task-p)))
21430 (inline-re (and inline-task-p
21431 (org-inlinetask-outline-regexp)))
21432 column)
21433 (if (and orgstruct-is-++ (eq pos (point)))
21434 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21435 (indent-according-to-mode))
21436 (beginning-of-line 1)
21437 (cond
21438 ;; Headings
21439 ((looking-at org-outline-regexp) (setq column 0))
21440 ;; Included files
21441 ((looking-at "#\\+include:") (setq column 0))
21442 ;; Footnote definition
21443 ((looking-at org-footnote-definition-re) (setq column 0))
21444 ;; Literal examples
21445 ((looking-at "[ \t]*:\\( \\|$\\)")
21446 (setq column (org-get-indentation))) ; do nothing
21447 ;; Lists
21448 ((ignore-errors (goto-char (org-in-item-p)))
21449 (setq column (if itemp
21450 (org-get-indentation)
21451 (org-list-item-body-column (point))))
21452 (goto-char pos))
21453 ;; Drawers
21454 ((and (looking-at "[ \t]*:END:")
21455 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21456 (save-excursion
21457 (goto-char (1- (match-beginning 1)))
21458 (setq column (current-column))))
21459 ;; Special blocks
21460 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21461 (save-excursion
21462 (re-search-backward
21463 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21464 (setq column (org-get-indentation (match-string 0))))
21465 ((and (not (looking-at "[ \t]*#\\+begin_"))
21466 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21467 (save-excursion
21468 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21469 (setq column
21470 (cond ((equal (downcase (match-string 1)) "src")
21471 ;; src blocks: let `org-edit-src-exit' handle them
21472 (org-get-indentation))
21473 ((equal (downcase (match-string 1)) "example")
21474 (max (org-get-indentation)
21475 (org-get-indentation (match-string 0))))
21477 (org-get-indentation (match-string 0))))))
21478 ;; This line has nothing special, look at the previous relevant
21479 ;; line to compute indentation
21481 (beginning-of-line 0)
21482 (while (and (not (bobp))
21483 (not (looking-at org-table-line-regexp))
21484 (not (looking-at org-drawer-regexp))
21485 ;; When point started in an inline task, do not move
21486 ;; above task starting line.
21487 (not (and inline-task-p (looking-at inline-re)))
21488 ;; Skip drawers, blocks, empty lines, verbatim,
21489 ;; comments, tables, footnotes definitions, lists,
21490 ;; inline tasks.
21491 (or (and (looking-at "[ \t]*:END:")
21492 (re-search-backward org-drawer-regexp nil t))
21493 (and (looking-at "[ \t]*#\\+end_")
21494 (re-search-backward "[ \t]*#\\+begin_"nil t))
21495 (looking-at "[ \t]*[\n:#|]")
21496 (looking-at org-footnote-definition-re)
21497 (and (ignore-errors (goto-char (org-in-item-p)))
21498 (goto-char
21499 (org-list-get-top-point (org-list-struct))))
21500 (and (not inline-task-p)
21501 (featurep 'org-inlinetask)
21502 (org-inlinetask-in-task-p)
21503 (or (org-inlinetask-goto-beginning) t))))
21504 (beginning-of-line 0))
21505 (cond
21506 ;; There was an heading above.
21507 ((looking-at "\\*+[ \t]+")
21508 (if (not org-adapt-indentation)
21509 (setq column 0)
21510 (goto-char (match-end 0))
21511 (setq column (current-column))))
21512 ;; A drawer had started and is unfinished
21513 ((looking-at org-drawer-regexp)
21514 (goto-char (1- (match-beginning 1)))
21515 (setq column (current-column)))
21516 ;; Else, nothing noticeable found: get indentation and go on.
21517 (t (setq column (org-get-indentation))))))
21518 ;; Now apply indentation and move cursor accordingly
21519 (goto-char pos)
21520 (if (<= (current-column) (current-indentation))
21521 (org-indent-line-to column)
21522 (save-excursion (org-indent-line-to column)))
21523 ;; Special polishing for properties, see `org-property-format'
21524 (setq column (current-column))
21525 (beginning-of-line 1)
21526 (if (looking-at
21527 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21528 (replace-match (concat (match-string 1)
21529 (format org-property-format
21530 (match-string 2) (match-string 3)))
21531 t t))
21532 (org-move-to-column column))))
21534 (defun org-indent-drawer ()
21535 "Indent the drawer at point."
21536 (interactive)
21537 (let ((p (point))
21538 (e (and (save-excursion (re-search-forward ":END:" nil t))
21539 (match-end 0)))
21540 (folded
21541 (save-excursion
21542 (end-of-line)
21543 (when (overlays-at (point))
21544 (member 'invisible (overlay-properties
21545 (car (overlays-at (point)))))))))
21546 (when folded (org-cycle))
21547 (indent-for-tab-command)
21548 (while (and (move-beginning-of-line 2) (< (point) e))
21549 (indent-for-tab-command))
21550 (goto-char p)
21551 (when folded (org-cycle)))
21552 (message "Drawer at point indented"))
21554 (defun org-indent-block ()
21555 "Indent the block at point."
21556 (interactive)
21557 (let ((p (point))
21558 (case-fold-search t)
21559 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21560 (match-end 0)))
21561 (folded
21562 (save-excursion
21563 (end-of-line)
21564 (when (overlays-at (point))
21565 (member 'invisible (overlay-properties
21566 (car (overlays-at (point)))))))))
21567 (when folded (org-cycle))
21568 (indent-for-tab-command)
21569 (while (and (move-beginning-of-line 2) (< (point) e))
21570 (indent-for-tab-command))
21571 (goto-char p)
21572 (when folded (org-cycle)))
21573 (message "Block at point indented"))
21575 (defun org-indent-region (start end)
21576 "Indent region."
21577 (interactive "r")
21578 (save-excursion
21579 (let ((line-end (org-current-line end)))
21580 (goto-char start)
21581 (while (< (org-current-line) line-end)
21582 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21583 (t (call-interactively 'org-indent-line)))
21584 (move-beginning-of-line 2)))))
21587 ;;; Filling
21589 ;; We use our own fill-paragraph and auto-fill functions.
21591 ;; `org-fill-paragraph' relies on adaptive filling and context
21592 ;; checking. Appropriate `fill-prefix' is computed with
21593 ;; `org-adaptive-fill-function'.
21595 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21596 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21597 ;; `org-adaptive-fill-function' value. Internally,
21598 ;; `org-comment-line-break-function' breaks the line.
21600 ;; `org-setup-filling' installs filling and auto-filling related
21601 ;; variables during `org-mode' initialization.
21603 (defun org-setup-filling ()
21604 (interactive)
21605 ;; Prevent auto-fill from inserting unwanted new items.
21606 (when (boundp 'fill-nobreak-predicate)
21607 (org-set-local
21608 'fill-nobreak-predicate
21609 (org-uniquify
21610 (append fill-nobreak-predicate
21611 '(org-fill-paragraph-separate-nobreak-p
21612 org-fill-line-break-nobreak-p)))))
21613 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21614 (org-set-local 'auto-fill-inhibit-regexp nil)
21615 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21616 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21617 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21619 (defvar org-element-paragraph-separate) ; org-element.el
21620 (defun org-fill-paragraph-separate-nobreak-p ()
21621 "Non-nil when a line break at point would insert a new item."
21622 (looking-at (substring org-element-paragraph-separate 1)))
21624 (defun org-fill-line-break-nobreak-p ()
21625 "Non-nil when a line break at point would create an Org line break."
21626 (save-excursion
21627 (skip-chars-backward "[ \t]")
21628 (skip-chars-backward "\\\\")
21629 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21631 (declare-function message-in-body-p "message" ())
21632 (defvar orgtbl-line-start-regexp) ; From org-table.el
21633 (defun org-adaptive-fill-function ()
21634 "Compute a fill prefix for the current line.
21635 Return fill prefix, as a string, or nil if current line isn't
21636 meant to be filled."
21637 (let (prefix)
21638 (catch 'exit
21639 (when (derived-mode-p 'message-mode)
21640 (save-excursion
21641 (beginning-of-line)
21642 (cond ((or (not (message-in-body-p))
21643 (looking-at orgtbl-line-start-regexp))
21644 (throw 'exit nil))
21645 ((looking-at message-cite-prefix-regexp)
21646 (throw 'exit (match-string-no-properties 0)))
21647 ((looking-at org-outline-regexp)
21648 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21649 (org-with-wide-buffer
21650 (let* ((p (line-beginning-position))
21651 (element (save-excursion (beginning-of-line)
21652 (org-element-at-point)))
21653 (type (org-element-type element))
21654 (post-affiliated (org-element-property :post-affiliated element)))
21655 (unless (and post-affiliated (< p post-affiliated))
21656 (case type
21657 (comment (looking-at "[ \t]*# ?") (match-string 0))
21658 (footnote-definition "")
21659 ((item plain-list)
21660 (make-string (org-list-item-body-column
21661 (or post-affiliated
21662 (org-element-property :begin element)))
21663 ? ))
21664 (paragraph
21665 ;; Fill prefix is usually the same as the current line,
21666 ;; except if the paragraph is at the beginning of an item.
21667 (let ((parent (org-element-property :parent element)))
21668 (cond ((eq (org-element-type parent) 'item)
21669 (make-string (org-list-item-body-column
21670 (org-element-property :begin parent))
21671 ? ))
21672 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21673 (match-string 0))
21674 (t ""))))
21675 (comment-block
21676 ;; Only fill contents if P is within block boundaries.
21677 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21678 (forward-line)
21679 (point)))
21680 (cend (save-excursion
21681 (goto-char (org-element-property :end element))
21682 (skip-chars-backward " \r\t\n")
21683 (line-beginning-position))))
21684 (when (and (>= p cbeg) (< p cend))
21685 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21686 (match-string 0)
21687 "")))))))))))
21689 (declare-function message-goto-body "message" ())
21690 (defvar message-cite-prefix-regexp) ; From message.el
21691 (defvar org-element-all-objects) ; From org-element.el
21692 (defun org-fill-paragraph (&optional justify)
21693 "Fill element at point, when applicable.
21695 This function only applies to comment blocks, comments, example
21696 blocks and paragraphs. Also, as a special case, re-align table
21697 when point is at one.
21699 If JUSTIFY is non-nil (interactively, with prefix argument),
21700 justify as well. If `sentence-end-double-space' is non-nil, then
21701 period followed by one space does not end a sentence, so don't
21702 break a line there. The variable `fill-column' controls the
21703 width for filling.
21705 For convenience, when point is at a plain list, an item or
21706 a footnote definition, try to fill the first paragraph within."
21707 (interactive)
21708 (if (and (derived-mode-p 'message-mode)
21709 (or (not (message-in-body-p))
21710 (save-excursion (move-beginning-of-line 1)
21711 (looking-at message-cite-prefix-regexp))))
21712 ;; First ensure filling is correct in message-mode.
21713 (let ((fill-paragraph-function
21714 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21715 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21716 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21717 (paragraph-separate
21718 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21719 (fill-paragraph nil))
21720 (save-excursion
21721 ;; Move to end of line in order to get the first paragraph
21722 ;; within a plain list or a footnote definition.
21723 (end-of-line)
21724 (let ((element (org-element-at-point)))
21725 ;; First check if point is in a blank line at the beginning of
21726 ;; the buffer. In that case, ignore filling.
21727 (if (< (point) (org-element-property :begin element)) t
21728 (case (org-element-type element)
21729 ;; Use major mode filling function is src blocks.
21730 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21731 ;; Align Org tables, leave table.el tables as-is.
21732 (table-row (org-table-align) t)
21733 (table
21734 (when (eq (org-element-property :type element) 'org)
21735 (org-table-align))
21737 (paragraph
21738 ;; Paragraphs may contain `line-break' type objects.
21739 (let ((beg (max (point-min)
21740 (org-element-property :contents-begin element)))
21741 (end (min (point-max)
21742 (org-element-property :contents-end element))))
21743 ;; Do nothing if point is at an affiliated keyword.
21744 (if (< (point) beg) t
21745 (when (derived-mode-p 'message-mode)
21746 ;; In `message-mode', do not fill following
21747 ;; citation in current paragraph nor text before
21748 ;; message body.
21749 (let ((body-start (save-excursion (message-goto-body))))
21750 (when body-start (setq beg (max body-start beg))))
21751 (when (save-excursion
21752 (re-search-forward
21753 (concat "^" message-cite-prefix-regexp) end t))
21754 (setq end (match-beginning 0))))
21755 ;; Fill paragraph, taking line breaks into
21756 ;; consideration. For that, slice the paragraph
21757 ;; using line breaks as separators, and fill the
21758 ;; parts in reverse order to avoid messing with
21759 ;; markers.
21760 (save-excursion
21761 (goto-char end)
21762 (mapc
21763 (lambda (pos)
21764 (fill-region-as-paragraph pos (point) justify)
21765 (goto-char pos))
21766 ;; Find the list of ending positions for line
21767 ;; breaks in the current paragraph. Add paragraph
21768 ;; beginning to include first slice.
21769 (nreverse
21770 (cons
21772 (org-element-map
21773 (org-element--parse-objects
21774 beg end nil org-element-all-objects)
21775 'line-break
21776 (lambda (lb) (org-element-property :end lb)))))))
21777 t)))
21778 ;; Contents of `comment-block' type elements should be
21779 ;; filled as plain text, but only if point is within block
21780 ;; markers.
21781 (comment-block
21782 (let* ((case-fold-search t)
21783 (beg (save-excursion
21784 (goto-char (org-element-property :begin element))
21785 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21786 (forward-line)
21787 (point)))
21788 (end (save-excursion
21789 (goto-char (org-element-property :end element))
21790 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21791 (line-beginning-position))))
21792 (when (and (>= (point) beg) (< (point) end))
21793 (fill-region-as-paragraph
21794 (save-excursion
21795 (end-of-line)
21796 (re-search-backward "^[ \t]*$" beg 'move)
21797 (line-beginning-position))
21798 (save-excursion
21799 (beginning-of-line)
21800 (re-search-forward "^[ \t]*$" end 'move)
21801 (line-beginning-position))
21802 justify)))
21804 ;; Fill comments.
21805 (comment (fill-comment-paragraph justify))
21806 ;; Ignore every other element.
21807 (otherwise t)))))))
21809 (defun org-auto-fill-function ()
21810 "Auto-fill function."
21811 ;; Check if auto-filling is meaningful.
21812 (let ((fc (current-fill-column)))
21813 (when (and fc (> (current-column) fc))
21814 (let* ((fill-prefix (org-adaptive-fill-function))
21815 ;; Enforce empty fill prefix, if required. Otherwise, it
21816 ;; will be computed again.
21817 (adaptive-fill-mode (not (equal fill-prefix ""))))
21818 (when fill-prefix (do-auto-fill))))))
21820 (defun org-comment-line-break-function (&optional soft)
21821 "Break line at point and indent, continuing comment if within one.
21822 The inserted newline is marked hard if variable
21823 `use-hard-newlines' is true, unless optional argument SOFT is
21824 non-nil."
21825 (if soft (insert-and-inherit ?\n) (newline 1))
21826 (save-excursion (forward-char -1) (delete-horizontal-space))
21827 (delete-horizontal-space)
21828 (indent-to-left-margin)
21829 (insert-before-markers-and-inherit fill-prefix))
21832 ;;; Comments
21834 ;; Org comments syntax is quite complex. It requires the entire line
21835 ;; to be just a comment. Also, even with the right syntax at the
21836 ;; beginning of line, some some elements (i.e. verse-block or
21837 ;; example-block) don't accept comments. Usual Emacs comment commands
21838 ;; cannot cope with those requirements. Therefore, Org replaces them.
21840 ;; Org still relies on `comment-dwim', but cannot trust
21841 ;; `comment-only-p'. So, `comment-region-function' and
21842 ;; `uncomment-region-function' both point
21843 ;; to`org-comment-or-uncomment-region'. Eventually,
21844 ;; `org-insert-comment' takes care of insertion of comments at the
21845 ;; beginning of line.
21847 ;; `org-setup-comments-handling' install comments related variables
21848 ;; during `org-mode' initialization.
21850 (defun org-setup-comments-handling ()
21851 (interactive)
21852 (org-set-local 'comment-use-syntax nil)
21853 (org-set-local 'comment-start "# ")
21854 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21855 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21856 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21857 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21859 (defun org-insert-comment ()
21860 "Insert an empty comment above current line.
21861 If the line is empty, insert comment at its beginning."
21862 (beginning-of-line)
21863 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21864 (org-indent-line)
21865 (insert "# "))
21867 (defvar comment-empty-lines) ; From newcomment.el.
21868 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21869 "Comment or uncomment each non-blank line in the region.
21870 Uncomment each non-blank line between BEG and END if it only
21871 contains commented lines. Otherwise, comment them."
21872 (save-restriction
21873 ;; Restrict region
21874 (narrow-to-region (save-excursion (goto-char beg)
21875 (skip-chars-forward " \r\t\n" end)
21876 (line-beginning-position))
21877 (save-excursion (goto-char end)
21878 (skip-chars-backward " \r\t\n" beg)
21879 (line-end-position)))
21880 (let ((uncommentp
21881 ;; UNCOMMENTP is non-nil when every non blank line between
21882 ;; BEG and END is a comment.
21883 (save-excursion
21884 (goto-char (point-min))
21885 (while (and (not (eobp))
21886 (let ((element (org-element-at-point)))
21887 (and (eq (org-element-type element) 'comment)
21888 (goto-char (min (point-max)
21889 (org-element-property
21890 :end element)))))))
21891 (eobp))))
21892 (if uncommentp
21893 ;; Only blank lines and comments in region: uncomment it.
21894 (save-excursion
21895 (goto-char (point-min))
21896 (while (not (eobp))
21897 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21898 (replace-match "" nil nil nil 1))
21899 (forward-line)))
21900 ;; Comment each line in region.
21901 (let ((min-indent (point-max)))
21902 ;; First find the minimum indentation across all lines.
21903 (save-excursion
21904 (goto-char (point-min))
21905 (while (and (not (eobp)) (not (zerop min-indent)))
21906 (unless (looking-at "[ \t]*$")
21907 (setq min-indent (min min-indent (current-indentation))))
21908 (forward-line)))
21909 ;; Then loop over all lines.
21910 (save-excursion
21911 (goto-char (point-min))
21912 (while (not (eobp))
21913 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21914 (org-move-to-column min-indent t)
21915 (insert comment-start))
21916 (forward-line))))))))
21919 ;;; Planning
21921 ;; This section contains tools to operate on timestamp objects, as
21922 ;; returned by, e.g. `org-element-context'.
21924 (defun org-timestamp-has-time-p (timestamp)
21925 "Non-nil when TIMESTAMP has a time specified."
21926 (org-element-property :hour-start timestamp))
21928 (defun org-timestamp-format (timestamp format &optional end utc)
21929 "Format a TIMESTAMP element into a string.
21931 FORMAT is a format specifier to be passed to
21932 `format-time-string'.
21934 When optional argument END is non-nil, use end of date-range or
21935 time-range, if possible.
21937 When optional argument UTC is non-nil, time will be expressed as
21938 Universal Time."
21939 (format-time-string
21940 format
21941 (apply 'encode-time
21942 (cons 0
21943 (mapcar
21944 (lambda (prop) (or (org-element-property prop timestamp) 0))
21945 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21946 '(:minute-start :hour-start :day-start :month-start
21947 :year-start)))))
21948 utc))
21950 (defun org-timestamp-split-range (timestamp &optional end)
21951 "Extract a timestamp object from a date or time range.
21953 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21954 the end of the range. Otherwise, extract its start.
21956 Return a new timestamp object sharing the same parent as
21957 TIMESTAMP."
21958 (let ((type (org-element-property :type timestamp)))
21959 (if (memq type '(active inactive diary)) timestamp
21960 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21961 ;; Set new type.
21962 (org-element-put-property
21963 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21964 ;; Copy start properties over end properties if END is
21965 ;; non-nil. Otherwise, copy end properties over `start' ones.
21966 (let ((p-alist '((:minute-start . :minute-end)
21967 (:hour-start . :hour-end)
21968 (:day-start . :day-end)
21969 (:month-start . :month-end)
21970 (:year-start . :year-end))))
21971 (dolist (p-cell p-alist)
21972 (org-element-put-property
21973 split-ts
21974 (funcall (if end 'car 'cdr) p-cell)
21975 (org-element-property
21976 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21977 ;; Eventually refresh `:raw-value'.
21978 (org-element-put-property split-ts :raw-value nil)
21979 (org-element-put-property
21980 split-ts :raw-value (org-element-interpret-data split-ts)))))))
21982 (defun org-timestamp-translate (timestamp &optional boundary)
21983 "Apply `org-translate-time' on a TIMESTAMP object.
21984 When optional argument BOUNDARY is non-nil, it is either the
21985 symbol `start' or `end'. In this case, only translate the
21986 starting or ending part of TIMESTAMP if it is a date or time
21987 range. Otherwise, translate both parts."
21988 (if (and (not boundary)
21989 (memq (org-element-property :type timestamp)
21990 '(active-range inactive-range)))
21991 (concat
21992 (org-translate-time
21993 (org-element-property :raw-value
21994 (org-timestamp-split-range timestamp)))
21995 "--"
21996 (org-translate-time
21997 (org-element-property :raw-value
21998 (org-timestamp-split-range timestamp t))))
21999 (org-translate-time
22000 (org-element-property
22001 :raw-value
22002 (if (not boundary) timestamp
22003 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22007 ;;; Other stuff.
22009 (defun org-toggle-fixed-width-section (arg)
22010 "Toggle the fixed-width export.
22011 If there is no active region, the QUOTE keyword at the current headline is
22012 inserted or removed. When present, it causes the text between this headline
22013 and the next to be exported as fixed-width text, and unmodified.
22014 If there is an active region, this command adds or removes a colon as the
22015 first character of this line. If the first character of a line is a colon,
22016 this line is also exported in fixed-width font."
22017 (interactive "P")
22018 (let* ((cc 0)
22019 (regionp (org-region-active-p))
22020 (beg (if regionp (region-beginning) (point)))
22021 (end (if regionp (region-end)))
22022 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22023 (case-fold-search nil)
22024 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22025 off)
22026 (if regionp
22027 (save-excursion
22028 (goto-char beg)
22029 (setq cc (current-column))
22030 (beginning-of-line 1)
22031 (setq off (looking-at re))
22032 (while (> nlines 0)
22033 (setq nlines (1- nlines))
22034 (beginning-of-line 1)
22035 (cond
22036 (arg
22037 (org-move-to-column cc t)
22038 (insert ": \n")
22039 (forward-line -1))
22040 ((and off (looking-at re))
22041 (replace-match "" t t nil 1))
22042 ((not off) (org-move-to-column cc t) (insert ": ")))
22043 (forward-line 1)))
22044 (save-excursion
22045 (org-back-to-heading)
22046 (cond
22047 ((looking-at (format org-heading-keyword-regexp-format
22048 org-quote-string))
22049 (goto-char (match-end 1))
22050 (looking-at (concat " +" org-quote-string))
22051 (replace-match "" t t)
22052 (when (eolp) (insert " ")))
22053 ((looking-at org-outline-regexp)
22054 (goto-char (match-end 0))
22055 (insert org-quote-string " ")))))))
22057 (defun org-reftex-citation ()
22058 "Use reftex-citation to insert a citation into the buffer.
22059 This looks for a line like
22061 #+BIBLIOGRAPHY: foo plain option:-d
22063 and derives from it that foo.bib is the bibliography file relevant
22064 for this document. It then installs the necessary environment for RefTeX
22065 to work in this buffer and calls `reftex-citation' to insert a citation
22066 into the buffer.
22068 Export of such citations to both LaTeX and HTML is handled by the contributed
22069 package org-exp-bibtex by Taru Karttunen."
22070 (interactive)
22071 (let ((reftex-docstruct-symbol 'rds)
22072 (reftex-cite-format "\\cite{%l}")
22073 rds bib)
22074 (save-excursion
22075 (save-restriction
22076 (widen)
22077 (let ((case-fold-search t)
22078 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22079 (if (not (save-excursion
22080 (or (re-search-forward re nil t)
22081 (re-search-backward re nil t))))
22082 (error "No bibliography defined in file")
22083 (setq bib (concat (match-string 1) ".bib")
22084 rds (list (list 'bib bib)))))))
22085 (call-interactively 'reftex-citation)))
22087 ;;;; Functions extending outline functionality
22089 (defun org-beginning-of-line (&optional arg)
22090 "Go to the beginning of the current line. If that is invisible, continue
22091 to a visible line beginning. This makes the function of C-a more intuitive.
22092 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22093 first attempt, and only move to after the tags when the cursor is already
22094 beyond the end of the headline."
22095 (interactive "P")
22096 (let ((pos (point))
22097 (special (if (consp org-special-ctrl-a/e)
22098 (car org-special-ctrl-a/e)
22099 org-special-ctrl-a/e))
22100 refpos)
22101 (if (org-bound-and-true-p visual-line-mode)
22102 (beginning-of-visual-line 1)
22103 (beginning-of-line 1))
22104 (if (and arg (fboundp 'move-beginning-of-line))
22105 (call-interactively 'move-beginning-of-line)
22106 (if (bobp)
22108 (backward-char 1)
22109 (if (org-truely-invisible-p)
22110 (while (and (not (bobp)) (org-truely-invisible-p))
22111 (backward-char 1)
22112 (beginning-of-line 1))
22113 (forward-char 1))))
22114 (when special
22115 (cond
22116 ((and (looking-at org-complex-heading-regexp)
22117 (= (char-after (match-end 1)) ?\ ))
22118 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22119 (point-at-eol)))
22120 (goto-char
22121 (if (eq special t)
22122 (cond ((> pos refpos) refpos)
22123 ((= pos (point)) refpos)
22124 (t (point)))
22125 (cond ((> pos (point)) (point))
22126 ((not (eq last-command this-command)) (point))
22127 (t refpos)))))
22128 ((org-at-item-p)
22129 ;; Being at an item and not looking at an the item means point
22130 ;; was previously moved to beginning of a visual line, which
22131 ;; doesn't contain the item. Therefore, do nothing special,
22132 ;; just stay here.
22133 (when (looking-at org-list-full-item-re)
22134 ;; Set special position at first white space character after
22135 ;; bullet, and check-box, if any.
22136 (let ((after-bullet
22137 (let ((box (match-end 3)))
22138 (if (not box) (match-end 1)
22139 (let ((after (char-after box)))
22140 (if (and after (= after ? )) (1+ box) box))))))
22141 ;; Special case: Move point to special position when
22142 ;; currently after it or at beginning of line.
22143 (if (eq special t)
22144 (when (or (> pos after-bullet) (= (point) pos))
22145 (goto-char after-bullet))
22146 ;; Reversed case: Move point to special position when
22147 ;; point was already at beginning of line and command is
22148 ;; repeated.
22149 (when (and (= (point) pos) (eq last-command this-command))
22150 (goto-char after-bullet))))))))
22151 (org-no-warnings
22152 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22154 (defun org-end-of-line (&optional arg)
22155 "Go to the end of the line.
22156 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22157 tags on the first attempt, and only move to after the tags when
22158 the cursor is already beyond the end of the headline."
22159 (interactive "P")
22160 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22161 org-special-ctrl-a/e))
22162 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22163 'end-of-visual-line)
22164 ((fboundp 'move-end-of-line) 'move-end-of-line)
22165 (t 'end-of-line))))
22166 (if (or (not special) arg) (call-interactively move-fun)
22167 (let* ((element (save-excursion (beginning-of-line)
22168 (org-element-at-point)))
22169 (type (org-element-type element)))
22170 (cond
22171 ((memq type '(headline inlinetask))
22172 (let ((pos (point)))
22173 (beginning-of-line 1)
22174 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22175 (if (eq special t)
22176 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22177 (goto-char (match-beginning 1))
22178 (goto-char (match-end 0)))
22179 (if (or (< pos (match-end 0))
22180 (not (eq this-command last-command)))
22181 (goto-char (match-end 0))
22182 (goto-char (match-beginning 1))))
22183 (call-interactively move-fun))))
22184 ((org-element-property :hiddenp element)
22185 ;; If element is hidden, `move-end-of-line' would put point
22186 ;; after it. Use `end-of-line' to stay on current line.
22187 (call-interactively 'end-of-line))
22188 (t (call-interactively move-fun)))))
22189 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22191 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22192 (define-key org-mode-map "\C-e" 'org-end-of-line)
22194 (defun org-backward-sentence (&optional arg)
22195 "Go to beginning of sentence, or beginning of table field.
22196 This will call `backward-sentence' or `org-table-beginning-of-field',
22197 depending on context."
22198 (interactive "P")
22199 (cond
22200 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22201 (t (call-interactively 'backward-sentence))))
22203 (defun org-forward-sentence (&optional arg)
22204 "Go to end of sentence, or end of table field.
22205 This will call `forward-sentence' or `org-table-end-of-field',
22206 depending on context."
22207 (interactive "P")
22208 (cond
22209 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22210 (t (call-interactively 'forward-sentence))))
22212 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22213 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22215 (defun org-kill-line (&optional arg)
22216 "Kill line, to tags or end of line."
22217 (interactive "P")
22218 (cond
22219 ((or (not org-special-ctrl-k)
22220 (bolp)
22221 (not (org-at-heading-p)))
22222 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22223 org-ctrl-k-protect-subtree)
22224 (if (or (eq org-ctrl-k-protect-subtree 'error)
22225 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22226 (error "C-k aborted - would kill hidden subtree")))
22227 (call-interactively
22228 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22229 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22230 (kill-region (point) (match-beginning 1))
22231 (org-set-tags nil t))
22232 (t (kill-region (point) (point-at-eol)))))
22234 (define-key org-mode-map "\C-k" 'org-kill-line)
22236 (defun org-yank (&optional arg)
22237 "Yank. If the kill is a subtree, treat it specially.
22238 This command will look at the current kill and check if is a single
22239 subtree, or a series of subtrees[1]. If it passes the test, and if the
22240 cursor is at the beginning of a line or after the stars of a currently
22241 empty headline, then the yank is handled specially. How exactly depends
22242 on the value of the following variables, both set by default.
22244 org-yank-folded-subtrees
22245 When set, the subtree(s) will be folded after insertion, but only
22246 if doing so would now swallow text after the yanked text.
22248 org-yank-adjusted-subtrees
22249 When set, the subtree will be promoted or demoted in order to
22250 fit into the local outline tree structure, which means that the level
22251 will be adjusted so that it becomes the smaller one of the two
22252 *visible* surrounding headings.
22254 Any prefix to this command will cause `yank' to be called directly with
22255 no special treatment. In particular, a simple \\[universal-argument] prefix \
22256 will just
22257 plainly yank the text as it is.
22259 \[1] The test checks if the first non-white line is a heading
22260 and if there are no other headings with fewer stars."
22261 (interactive "P")
22262 (org-yank-generic 'yank arg))
22264 (defun org-yank-generic (command arg)
22265 "Perform some yank-like command.
22267 This function implements the behavior described in the `org-yank'
22268 documentation. However, it has been generalized to work for any
22269 interactive command with similar behavior."
22271 ;; pretend to be command COMMAND
22272 (setq this-command command)
22274 (if arg
22275 (call-interactively command)
22277 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22278 (and (org-kill-is-subtree-p)
22279 (or (bolp)
22280 (and (looking-at "[ \t]*$")
22281 (string-match
22282 "\\`\\*+\\'"
22283 (buffer-substring (point-at-bol) (point)))))))
22284 swallowp)
22285 (cond
22286 ((and subtreep org-yank-folded-subtrees)
22287 (let ((beg (point))
22288 end)
22289 (if (and subtreep org-yank-adjusted-subtrees)
22290 (org-paste-subtree nil nil 'for-yank)
22291 (call-interactively command))
22293 (setq end (point))
22294 (goto-char beg)
22295 (when (and (bolp) subtreep
22296 (not (setq swallowp
22297 (org-yank-folding-would-swallow-text beg end))))
22298 (org-with-limited-levels
22299 (or (looking-at org-outline-regexp)
22300 (re-search-forward org-outline-regexp-bol end t))
22301 (while (and (< (point) end) (looking-at org-outline-regexp))
22302 (hide-subtree)
22303 (org-cycle-show-empty-lines 'folded)
22304 (condition-case nil
22305 (outline-forward-same-level 1)
22306 (error (goto-char end))))))
22307 (when swallowp
22308 (message
22309 "Inserted text not folded because that would swallow text"))
22311 (goto-char end)
22312 (skip-chars-forward " \t\n\r")
22313 (beginning-of-line 1)
22314 (push-mark beg 'nomsg)))
22315 ((and subtreep org-yank-adjusted-subtrees)
22316 (let ((beg (point-at-bol)))
22317 (org-paste-subtree nil nil 'for-yank)
22318 (push-mark beg 'nomsg)))
22320 (call-interactively command))))))
22322 (defun org-yank-folding-would-swallow-text (beg end)
22323 "Would hide-subtree at BEG swallow any text after END?"
22324 (let (level)
22325 (org-with-limited-levels
22326 (save-excursion
22327 (goto-char beg)
22328 (when (or (looking-at org-outline-regexp)
22329 (re-search-forward org-outline-regexp-bol end t))
22330 (setq level (org-outline-level)))
22331 (goto-char end)
22332 (skip-chars-forward " \t\r\n\v\f")
22333 (if (or (eobp)
22334 (and (bolp) (looking-at org-outline-regexp)
22335 (<= (org-outline-level) level)))
22336 nil ; Nothing would be swallowed
22337 t))))) ; something would swallow
22339 (define-key org-mode-map "\C-y" 'org-yank)
22341 (defun org-truely-invisible-p ()
22342 "Check if point is at a character currently not visible.
22343 This version does not only check the character property, but also
22344 `visible-mode'."
22345 ;; Early versions of noutline don't have `outline-invisible-p'.
22346 (if (org-bound-and-true-p visible-mode)
22348 (outline-invisible-p)))
22350 (defun org-invisible-p2 ()
22351 "Check if point is at a character currently not visible."
22352 (save-excursion
22353 (if (and (eolp) (not (bobp))) (backward-char 1))
22354 ;; Early versions of noutline don't have `outline-invisible-p'.
22355 (outline-invisible-p)))
22357 (defun org-back-to-heading (&optional invisible-ok)
22358 "Call `outline-back-to-heading', but provide a better error message."
22359 (condition-case nil
22360 (outline-back-to-heading invisible-ok)
22361 (error (error "Before first headline at position %d in buffer %s"
22362 (point) (current-buffer)))))
22364 (defun org-before-first-heading-p ()
22365 "Before first heading?"
22366 (save-excursion
22367 (end-of-line)
22368 (null (re-search-backward org-outline-regexp-bol nil t))))
22370 (defun org-at-heading-p (&optional ignored)
22371 (outline-on-heading-p t))
22372 ;; Compatibility alias with Org versions < 7.8.03
22373 (defalias 'org-on-heading-p 'org-at-heading-p)
22375 (defun org-at-comment-p nil
22376 "Is cursor in a line starting with a # character?"
22377 (save-excursion
22378 (beginning-of-line)
22379 (looking-at "^#")))
22381 (defun org-at-drawer-p nil
22382 "Is cursor at a drawer keyword?"
22383 (save-excursion
22384 (move-beginning-of-line 1)
22385 (looking-at org-drawer-regexp)))
22387 (defun org-at-block-p nil
22388 "Is cursor at a block keyword?"
22389 (save-excursion
22390 (move-beginning-of-line 1)
22391 (looking-at org-block-regexp)))
22393 (defun org-point-at-end-of-empty-headline ()
22394 "If point is at the end of an empty headline, return t, else nil.
22395 If the heading only contains a TODO keyword, it is still still considered
22396 empty."
22397 (and (looking-at "[ \t]*$")
22398 (when org-todo-line-regexp
22399 (save-excursion
22400 (beginning-of-line 1)
22401 (let ((case-fold-search nil))
22402 (looking-at org-todo-line-regexp)
22403 (string= (match-string 3) ""))))))
22405 (defun org-at-heading-or-item-p ()
22406 (or (org-at-heading-p) (org-at-item-p)))
22408 (defun org-at-target-p ()
22409 (or (org-in-regexp org-radio-target-regexp)
22410 (org-in-regexp org-target-regexp)))
22411 ;; Compatibility alias with Org versions < 7.8.03
22412 (defalias 'org-on-target-p 'org-at-target-p)
22414 (defun org-up-heading-all (arg)
22415 "Move to the heading line of which the present line is a subheading.
22416 This function considers both visible and invisible heading lines.
22417 With argument, move up ARG levels."
22418 (if (fboundp 'outline-up-heading-all)
22419 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22420 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22422 (defun org-up-heading-safe ()
22423 "Move to the heading line of which the present line is a subheading.
22424 This version will not throw an error. It will return the level of the
22425 headline found, or nil if no higher level is found.
22427 Also, this function will be a lot faster than `outline-up-heading',
22428 because it relies on stars being the outline starters. This can really
22429 make a significant difference in outlines with very many siblings."
22430 (let (start-level re)
22431 (org-back-to-heading t)
22432 (setq start-level (funcall outline-level))
22433 (if (equal start-level 1)
22435 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22436 (if (re-search-backward re nil t)
22437 (funcall outline-level)))))
22439 (defun org-first-sibling-p ()
22440 "Is this heading the first child of its parents?"
22441 (interactive)
22442 (let ((re org-outline-regexp-bol)
22443 level l)
22444 (unless (org-at-heading-p t)
22445 (error "Not at a heading"))
22446 (setq level (funcall outline-level))
22447 (save-excursion
22448 (if (not (re-search-backward re nil t))
22450 (setq l (funcall outline-level))
22451 (< l level)))))
22453 (defun org-goto-sibling (&optional previous)
22454 "Goto the next sibling, even if it is invisible.
22455 When PREVIOUS is set, go to the previous sibling instead. Returns t
22456 when a sibling was found. When none is found, return nil and don't
22457 move point."
22458 (let ((fun (if previous 're-search-backward 're-search-forward))
22459 (pos (point))
22460 (re org-outline-regexp-bol)
22461 level l)
22462 (when (condition-case nil (org-back-to-heading t) (error nil))
22463 (setq level (funcall outline-level))
22464 (catch 'exit
22465 (or previous (forward-char 1))
22466 (while (funcall fun re nil t)
22467 (setq l (funcall outline-level))
22468 (when (< l level) (goto-char pos) (throw 'exit nil))
22469 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22470 (goto-char pos)
22471 nil))))
22473 (defun org-show-siblings ()
22474 "Show all siblings of the current headline."
22475 (save-excursion
22476 (while (org-goto-sibling) (org-flag-heading nil)))
22477 (save-excursion
22478 (while (org-goto-sibling 'previous)
22479 (org-flag-heading nil))))
22481 (defun org-goto-first-child ()
22482 "Goto the first child, even if it is invisible.
22483 Return t when a child was found. Otherwise don't move point and
22484 return nil."
22485 (let (level (pos (point)) (re org-outline-regexp-bol))
22486 (when (condition-case nil (org-back-to-heading t) (error nil))
22487 (setq level (outline-level))
22488 (forward-char 1)
22489 (if (and (re-search-forward re nil t) (> (outline-level) level))
22490 (progn (goto-char (match-beginning 0)) t)
22491 (goto-char pos) nil))))
22493 (defun org-show-hidden-entry ()
22494 "Show an entry where even the heading is hidden."
22495 (save-excursion
22496 (org-show-entry)))
22498 (defun org-flag-heading (flag &optional entry)
22499 "Flag the current heading. FLAG non-nil means make invisible.
22500 When ENTRY is non-nil, show the entire entry."
22501 (save-excursion
22502 (org-back-to-heading t)
22503 ;; Check if we should show the entire entry
22504 (if entry
22505 (progn
22506 (org-show-entry)
22507 (save-excursion
22508 (and (outline-next-heading)
22509 (org-flag-heading nil))))
22510 (outline-flag-region (max (point-min) (1- (point)))
22511 (save-excursion (outline-end-of-heading) (point))
22512 flag))))
22514 (defun org-get-next-sibling ()
22515 "Move to next heading of the same level, and return point.
22516 If there is no such heading, return nil.
22517 This is like outline-next-sibling, but invisible headings are ok."
22518 (let ((level (funcall outline-level)))
22519 (outline-next-heading)
22520 (while (and (not (eobp)) (> (funcall outline-level) level))
22521 (outline-next-heading))
22522 (if (or (eobp) (< (funcall outline-level) level))
22524 (point))))
22526 (defun org-get-last-sibling ()
22527 "Move to previous heading of the same level, and return point.
22528 If there is no such heading, return nil."
22529 (let ((opoint (point))
22530 (level (funcall outline-level)))
22531 (outline-previous-heading)
22532 (when (and (/= (point) opoint) (outline-on-heading-p t))
22533 (while (and (> (funcall outline-level) level)
22534 (not (bobp)))
22535 (outline-previous-heading))
22536 (if (< (funcall outline-level) level)
22538 (point)))))
22540 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22541 "Goto to the end of a subtree."
22542 ;; This contains an exact copy of the original function, but it uses
22543 ;; `org-back-to-heading', to make it work also in invisible
22544 ;; trees. And is uses an invisible-ok argument.
22545 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22546 ;; Furthermore, when used inside Org, finding the end of a large subtree
22547 ;; with many children and grandchildren etc, this can be much faster
22548 ;; than the outline version.
22549 (org-back-to-heading invisible-ok)
22550 (let ((first t)
22551 (level (funcall outline-level)))
22552 (if (and (derived-mode-p 'org-mode) (< level 1000))
22553 ;; A true heading (not a plain list item), in Org-mode
22554 ;; This means we can easily find the end by looking
22555 ;; only for the right number of stars. Using a regexp to do
22556 ;; this is so much faster than using a Lisp loop.
22557 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22558 (forward-char 1)
22559 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22560 ;; something else, do it the slow way
22561 (while (and (not (eobp))
22562 (or first (> (funcall outline-level) level)))
22563 (setq first nil)
22564 (outline-next-heading)))
22565 (unless to-heading
22566 (if (memq (preceding-char) '(?\n ?\^M))
22567 (progn
22568 ;; Go to end of line before heading
22569 (forward-char -1)
22570 (if (memq (preceding-char) '(?\n ?\^M))
22571 ;; leave blank line before heading
22572 (forward-char -1))))))
22573 (point))
22575 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22576 "Use Org version in org-mode, for dramatic speed-up."
22577 (if (derived-mode-p 'org-mode)
22578 (progn
22579 (org-end-of-subtree nil t)
22580 (unless (eobp) (backward-char 1)))
22581 ad-do-it))
22583 (defun org-end-of-meta-data-and-drawers ()
22584 "Jump to the first text after meta data and drawers in the current entry.
22585 This will move over empty lines, lines with planning time stamps,
22586 clocking lines, and drawers."
22587 (org-back-to-heading t)
22588 (let ((end (save-excursion (outline-next-heading) (point)))
22589 (re (concat "\\(" org-drawer-regexp "\\)"
22590 "\\|" "[ \t]*" org-keyword-time-regexp)))
22591 (forward-line 1)
22592 (while (re-search-forward re end t)
22593 (if (not (match-end 1))
22594 ;; empty or planning line
22595 (forward-line 1)
22596 ;; a drawer, find the end
22597 (re-search-forward "^[ \t]*:END:" end 'move)
22598 (forward-line 1)))
22599 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22600 (point)))
22602 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22603 "Move forward to the arg'th subheading at same level as this one.
22604 Stop at the first and last subheadings of a superior heading.
22605 Normally this only looks at visible headings, but when INVISIBLE-OK is
22606 non-nil it will also look at invisible ones."
22607 (interactive "p")
22608 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22609 (outline-next-heading)
22610 (org-at-heading-p)
22611 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22612 (re (format "^\\*\\{1,%d\\} " level))
22614 (forward-char 1)
22615 (while (> arg 0)
22616 (while (and (re-search-forward re nil 'move)
22617 (setq l (- (match-end 0) (match-beginning 0) 1))
22618 (= l level)
22619 (not invisible-ok)
22620 (progn (backward-char 1) (outline-invisible-p)))
22621 (if (< l level) (setq arg 1)))
22622 (setq arg (1- arg)))
22623 (beginning-of-line 1))))
22625 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22626 "Move backward to the arg'th subheading at same level as this one.
22627 Stop at the first and last subheadings of a superior heading."
22628 (interactive "p")
22629 (if (not (ignore-errors (org-back-to-heading)))
22630 (goto-char (point-min))
22631 (org-at-heading-p)
22632 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22633 (re (format "^\\*\\{1,%d\\} " level))
22635 (while (> arg 0)
22636 (while (and (re-search-backward re nil 'move)
22637 (setq l (- (match-end 0) (match-beginning 0) 1))
22638 (= l level)
22639 (not invisible-ok)
22640 (outline-invisible-p))
22641 (if (< l level) (setq arg 1)))
22642 (setq arg (1- arg))))))
22644 (defun org-forward-element ()
22645 "Move forward by one element.
22646 Move to the next element at the same level, when possible."
22647 (interactive)
22648 (cond ((eobp) (error "Cannot move further down"))
22649 ((org-with-limited-levels (org-at-heading-p))
22650 (let ((origin (point)))
22651 (org-forward-heading-same-level 1)
22652 (unless (org-with-limited-levels (org-at-heading-p))
22653 (goto-char origin)
22654 (error "Cannot move further down"))))
22656 (let* ((elem (org-element-at-point))
22657 (end (org-element-property :end elem))
22658 (parent (org-element-property :parent elem)))
22659 (if (and parent (= (org-element-property :contents-end parent) end))
22660 (goto-char (org-element-property :end parent))
22661 (goto-char end))))))
22663 (defun org-backward-element ()
22664 "Move backward by one element.
22665 Move to the previous element at the same level, when possible."
22666 (interactive)
22667 (cond ((bobp) (error "Cannot move further up"))
22668 ((org-with-limited-levels (org-at-heading-p))
22669 ;; At an headline, move to the previous one, if any, or stay
22670 ;; here.
22671 (let ((origin (point)))
22672 (org-backward-heading-same-level 1)
22673 (unless (org-with-limited-levels (org-at-heading-p))
22674 (goto-char origin)
22675 (error "Cannot move further up"))))
22677 (let* ((trail (org-element-at-point 'keep-trail))
22678 (elem (car trail))
22679 (prev-elem (nth 1 trail))
22680 (beg (org-element-property :begin elem)))
22681 (cond
22682 ;; Move to beginning of current element if point isn't
22683 ;; there already.
22684 ((/= (point) beg) (goto-char beg))
22685 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22686 ((org-before-first-heading-p) (goto-char (point-min)))
22687 (t (org-back-to-heading)))))))
22689 (defun org-up-element ()
22690 "Move to upper element."
22691 (interactive)
22692 (if (org-with-limited-levels (org-at-heading-p))
22693 (unless (org-up-heading-safe) (error "No surrounding element"))
22694 (let* ((elem (org-element-at-point))
22695 (parent (org-element-property :parent elem)))
22696 (if parent (goto-char (org-element-property :begin parent))
22697 (if (org-with-limited-levels (org-before-first-heading-p))
22698 (error "No surrounding element")
22699 (org-with-limited-levels (org-back-to-heading)))))))
22701 (defvar org-element-greater-elements)
22702 (defun org-down-element ()
22703 "Move to inner element."
22704 (interactive)
22705 (let ((element (org-element-at-point)))
22706 (cond
22707 ((memq (org-element-type element) '(plain-list table))
22708 (goto-char (org-element-property :contents-begin element))
22709 (forward-char))
22710 ((memq (org-element-type element) org-element-greater-elements)
22711 ;; If contents are hidden, first disclose them.
22712 (when (org-element-property :hiddenp element) (org-cycle))
22713 (goto-char (or (org-element-property :contents-begin element)
22714 (error "No content for this element"))))
22715 (t (error "No inner element")))))
22717 (defun org-drag-element-backward ()
22718 "Move backward element at point."
22719 (interactive)
22720 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22721 (let* ((trail (org-element-at-point 'keep-trail))
22722 (elem (car trail))
22723 (prev-elem (nth 1 trail)))
22724 ;; Error out if no previous element or previous element is
22725 ;; a parent of the current one.
22726 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22727 (error "Cannot drag element backward")
22728 (let ((pos (point)))
22729 (org-element-swap-A-B prev-elem elem)
22730 (goto-char (+ (org-element-property :begin prev-elem)
22731 (- pos (org-element-property :begin elem)))))))))
22733 (defun org-drag-element-forward ()
22734 "Move forward element at point."
22735 (interactive)
22736 (let* ((pos (point))
22737 (elem (org-element-at-point)))
22738 (when (= (point-max) (org-element-property :end elem))
22739 (error "Cannot drag element forward"))
22740 (goto-char (org-element-property :end elem))
22741 (let ((next-elem (org-element-at-point)))
22742 (when (or (org-element-nested-p elem next-elem)
22743 (and (eq (org-element-type next-elem) 'headline)
22744 (not (eq (org-element-type elem) 'headline))))
22745 (goto-char pos)
22746 (error "Cannot drag element forward"))
22747 ;; Compute new position of point: it's shifted by NEXT-ELEM
22748 ;; body's length (without final blanks) and by the length of
22749 ;; blanks between ELEM and NEXT-ELEM.
22750 (let ((size-next (- (save-excursion
22751 (goto-char (org-element-property :end next-elem))
22752 (skip-chars-backward " \r\t\n")
22753 (forward-line)
22754 ;; Small correction if buffer doesn't end
22755 ;; with a newline character.
22756 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22757 (org-element-property :begin next-elem)))
22758 (size-blank (- (org-element-property :end elem)
22759 (save-excursion
22760 (goto-char (org-element-property :end elem))
22761 (skip-chars-backward " \r\t\n")
22762 (forward-line)
22763 (point)))))
22764 (org-element-swap-A-B elem next-elem)
22765 (goto-char (+ pos size-next size-blank))))))
22767 (defun org-mark-element ()
22768 "Put point at beginning of this element, mark at end.
22770 Interactively, if this command is repeated or (in Transient Mark
22771 mode) if the mark is active, it marks the next element after the
22772 ones already marked."
22773 (interactive)
22774 (let (deactivate-mark)
22775 (if (and (org-called-interactively-p 'any)
22776 (or (and (eq last-command this-command) (mark t))
22777 (and transient-mark-mode mark-active)))
22778 (set-mark
22779 (save-excursion
22780 (goto-char (mark))
22781 (goto-char (org-element-property :end (org-element-at-point)))))
22782 (let ((element (org-element-at-point)))
22783 (end-of-line)
22784 (push-mark (org-element-property :end element) t t)
22785 (goto-char (org-element-property :begin element))))))
22787 (defun org-narrow-to-element ()
22788 "Narrow buffer to current element."
22789 (interactive)
22790 (let ((elem (org-element-at-point)))
22791 (cond
22792 ((eq (car elem) 'headline)
22793 (narrow-to-region
22794 (org-element-property :begin elem)
22795 (org-element-property :end elem)))
22796 ((memq (car elem) org-element-greater-elements)
22797 (narrow-to-region
22798 (org-element-property :contents-begin elem)
22799 (org-element-property :contents-end elem)))
22801 (narrow-to-region
22802 (org-element-property :begin elem)
22803 (org-element-property :end elem))))))
22805 (defun org-transpose-words ()
22806 "Transpose words, using `org-mode' syntax table."
22807 (interactive)
22808 (with-syntax-table org-syntax-table
22809 (call-interactively 'transpose-words)))
22810 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22812 (defun org-transpose-element ()
22813 "Transpose current and previous elements, keeping blank lines between.
22814 Point is moved after both elements."
22815 (interactive)
22816 (org-skip-whitespace)
22817 (let ((end (org-element-property :end (org-element-at-point))))
22818 (org-drag-element-backward)
22819 (goto-char end)))
22821 (defun org-unindent-buffer ()
22822 "Un-indent the visible part of the buffer.
22823 Relative indentation (between items, inside blocks, etc.) isn't
22824 modified."
22825 (interactive)
22826 (unless (eq major-mode 'org-mode)
22827 (error "Cannot un-indent a buffer not in Org mode"))
22828 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22829 unindent-tree ; For byte-compiler.
22830 (unindent-tree
22831 (function
22832 (lambda (contents)
22833 (mapc
22834 (lambda (element)
22835 (if (memq (org-element-type element) '(headline section))
22836 (funcall unindent-tree (org-element-contents element))
22837 (save-excursion
22838 (save-restriction
22839 (narrow-to-region
22840 (org-element-property :begin element)
22841 (org-element-property :end element))
22842 (org-do-remove-indentation)))))
22843 (reverse contents))))))
22844 (funcall unindent-tree (org-element-contents parse-tree))))
22846 (defun org-show-subtree ()
22847 "Show everything after this heading at deeper levels."
22848 (interactive)
22849 (outline-flag-region
22850 (point)
22851 (save-excursion
22852 (org-end-of-subtree t t))
22853 nil))
22855 (defun org-show-entry ()
22856 "Show the body directly following this heading.
22857 Show the heading too, if it is currently invisible."
22858 (interactive)
22859 (save-excursion
22860 (condition-case nil
22861 (progn
22862 (org-back-to-heading t)
22863 (outline-flag-region
22864 (max (point-min) (1- (point)))
22865 (save-excursion
22866 (if (re-search-forward
22867 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22868 (match-beginning 1)
22869 (point-max)))
22870 nil)
22871 (org-cycle-hide-drawers 'children))
22872 (error nil))))
22874 (defun org-make-options-regexp (kwds &optional extra)
22875 "Make a regular expression for keyword lines."
22876 (concat
22877 "^#\\+\\("
22878 (mapconcat 'regexp-quote kwds "\\|")
22879 (if extra (concat "\\|" extra))
22880 "\\):[ \t]*\\(.*\\)"))
22882 ;; Make isearch reveal the necessary context
22883 (defun org-isearch-end ()
22884 "Reveal context after isearch exits."
22885 (when isearch-success ; only if search was successful
22886 (if (featurep 'xemacs)
22887 ;; Under XEmacs, the hook is run in the correct place,
22888 ;; we directly show the context.
22889 (org-show-context 'isearch)
22890 ;; In Emacs the hook runs *before* restoring the overlays.
22891 ;; So we have to use a one-time post-command-hook to do this.
22892 ;; (Emacs 22 has a special variable, see function `org-mode')
22893 (unless (and (boundp 'isearch-mode-end-hook-quit)
22894 isearch-mode-end-hook-quit)
22895 ;; Only when the isearch was not quitted.
22896 (org-add-hook 'post-command-hook 'org-isearch-post-command
22897 'append 'local)))))
22899 (defun org-isearch-post-command ()
22900 "Remove self from hook, and show context."
22901 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22902 (org-show-context 'isearch))
22905 ;;;; Integration with and fixes for other packages
22907 ;;; Imenu support
22909 (defvar org-imenu-markers nil
22910 "All markers currently used by Imenu.")
22911 (make-variable-buffer-local 'org-imenu-markers)
22913 (defun org-imenu-new-marker (&optional pos)
22914 "Return a new marker for use by Imenu, and remember the marker."
22915 (let ((m (make-marker)))
22916 (move-marker m (or pos (point)))
22917 (push m org-imenu-markers)
22920 (defun org-imenu-get-tree ()
22921 "Produce the index for Imenu."
22922 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22923 (setq org-imenu-markers nil)
22924 (let* ((n org-imenu-depth)
22925 (re (concat "^" (org-get-limited-outline-regexp)))
22926 (subs (make-vector (1+ n) nil))
22927 (last-level 0)
22928 m level head)
22929 (save-excursion
22930 (save-restriction
22931 (widen)
22932 (goto-char (point-max))
22933 (while (re-search-backward re nil t)
22934 (setq level (org-reduced-level (funcall outline-level)))
22935 (when (and (<= level n)
22936 (looking-at org-complex-heading-regexp))
22937 (setq head (org-link-display-format
22938 (org-match-string-no-properties 4))
22939 m (org-imenu-new-marker))
22940 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22941 (if (>= level last-level)
22942 (push (cons head m) (aref subs level))
22943 (push (cons head (aref subs (1+ level))) (aref subs level))
22944 (loop for i from (1+ level) to n do (aset subs i nil)))
22945 (setq last-level level)))))
22946 (aref subs 1)))
22948 (eval-after-load "imenu"
22949 '(progn
22950 (add-hook 'imenu-after-jump-hook
22951 (lambda ()
22952 (if (derived-mode-p 'org-mode)
22953 (org-show-context 'org-goto))))))
22955 (defun org-link-display-format (link)
22956 "Replace a link with either the description, or the link target
22957 if no description is present"
22958 (save-match-data
22959 (if (string-match org-bracket-link-analytic-regexp link)
22960 (replace-match (if (match-end 5)
22961 (match-string 5 link)
22962 (concat (match-string 1 link)
22963 (match-string 3 link)))
22964 nil t link)
22965 link)))
22967 (defun org-toggle-link-display ()
22968 "Toggle the literal or descriptive display of links."
22969 (interactive)
22970 (if org-descriptive-links
22971 (progn (org-remove-from-invisibility-spec '(org-link))
22972 (org-restart-font-lock)
22973 (setq org-descriptive-links nil))
22974 (progn (add-to-invisibility-spec '(org-link))
22975 (org-restart-font-lock)
22976 (setq org-descriptive-links t))))
22978 ;; Speedbar support
22980 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22981 "Overlay marking the agenda restriction line in speedbar.")
22982 (overlay-put org-speedbar-restriction-lock-overlay
22983 'face 'org-agenda-restriction-lock)
22984 (overlay-put org-speedbar-restriction-lock-overlay
22985 'help-echo "Agendas are currently limited to this item.")
22986 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22988 (defun org-speedbar-set-agenda-restriction ()
22989 "Restrict future agenda commands to the location at point in speedbar.
22990 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22991 (interactive)
22992 (require 'org-agenda)
22993 (let (p m tp np dir txt)
22994 (cond
22995 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22996 'org-imenu t))
22997 (setq m (get-text-property p 'org-imenu-marker))
22998 (with-current-buffer (marker-buffer m)
22999 (goto-char m)
23000 (org-agenda-set-restriction-lock 'subtree)))
23001 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23002 'speedbar-function 'speedbar-find-file))
23003 (setq tp (previous-single-property-change
23004 (1+ p) 'speedbar-function)
23005 np (next-single-property-change
23006 tp 'speedbar-function)
23007 dir (speedbar-line-directory)
23008 txt (buffer-substring-no-properties (or tp (point-min))
23009 (or np (point-max))))
23010 (with-current-buffer (find-file-noselect
23011 (let ((default-directory dir))
23012 (expand-file-name txt)))
23013 (unless (derived-mode-p 'org-mode)
23014 (error "Cannot restrict to non-Org-mode file"))
23015 (org-agenda-set-restriction-lock 'file)))
23016 (t (error "Don't know how to restrict Org-mode's agenda")))
23017 (move-overlay org-speedbar-restriction-lock-overlay
23018 (point-at-bol) (point-at-eol))
23019 (setq current-prefix-arg nil)
23020 (org-agenda-maybe-redo)))
23022 (eval-after-load "speedbar"
23023 '(progn
23024 (speedbar-add-supported-extension ".org")
23025 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23026 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23027 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23028 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23029 (add-hook 'speedbar-visiting-tag-hook
23030 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23032 ;;; Fixes and Hacks for problems with other packages
23034 ;; Make flyspell not check words in links, to not mess up our keymap
23035 (defun org-mode-flyspell-verify ()
23036 "Don't let flyspell put overlays at active buttons, or on
23037 {todo,all-time,additional-option-like}-keywords."
23038 (let ((pos (max (1- (point)) (point-min)))
23039 (word (thing-at-point 'word)))
23040 (and (not (get-text-property pos 'keymap))
23041 (not (get-text-property pos 'org-no-flyspell))
23042 (not (member word org-todo-keywords-1))
23043 (not (member word org-all-time-keywords))
23044 (not (member word org-options-keywords))
23045 (not (member word (mapcar 'car org-startup-options)))
23046 (not (member word org-additional-option-like-keywords-for-flyspell)))))
23048 (defun org-remove-flyspell-overlays-in (beg end)
23049 "Remove flyspell overlays in region."
23050 (and (org-bound-and-true-p flyspell-mode)
23051 (fboundp 'flyspell-delete-region-overlays)
23052 (flyspell-delete-region-overlays beg end))
23053 (add-text-properties beg end '(org-no-flyspell t)))
23055 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23056 (eval-after-load "bookmark"
23057 '(if (boundp 'bookmark-after-jump-hook)
23058 ;; We can use the hook
23059 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23060 ;; Hook not available, use advice
23061 (defadvice bookmark-jump (after org-make-visible activate)
23062 "Make the position visible."
23063 (org-bookmark-jump-unhide))))
23065 ;; Make sure saveplace shows the location if it was hidden
23066 (eval-after-load "saveplace"
23067 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23068 "Make the position visible."
23069 (org-bookmark-jump-unhide)))
23071 ;; Make sure ecb shows the location if it was hidden
23072 (eval-after-load "ecb"
23073 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23074 "Make hierarchy visible when jumping into location from ECB tree buffer."
23075 (if (derived-mode-p 'org-mode)
23076 (org-show-context))))
23078 (defun org-bookmark-jump-unhide ()
23079 "Unhide the current position, to show the bookmark location."
23080 (and (derived-mode-p 'org-mode)
23081 (or (outline-invisible-p)
23082 (save-excursion (goto-char (max (point-min) (1- (point))))
23083 (outline-invisible-p)))
23084 (org-show-context 'bookmark-jump)))
23086 ;; Make session.el ignore our circular variable
23087 (eval-after-load "session"
23088 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23090 ;;;; Experimental code
23092 (defun org-closed-in-range ()
23093 "Sparse tree of items closed in a certain time range.
23094 Still experimental, may disappear in the future."
23095 (interactive)
23096 ;; Get the time interval from the user.
23097 (let* ((time1 (org-float-time
23098 (org-read-date nil 'to-time nil "Starting date: ")))
23099 (time2 (org-float-time
23100 (org-read-date nil 'to-time nil "End date:")))
23101 ;; callback function
23102 (callback (lambda ()
23103 (let ((time
23104 (org-float-time
23105 (apply 'encode-time
23106 (org-parse-time-string
23107 (match-string 1))))))
23108 ;; check if time in interval
23109 (and (>= time time1) (<= time time2))))))
23110 ;; make tree, check each match with the callback
23111 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23113 ;;;; Finish up
23115 (provide 'org)
23117 (run-hooks 'org-load-hook)
23119 ;;; org.el ends here