org-e-latex: Added an attribute to inline images
[org-mode.git] / lisp / org.el
blob67261b32431987fb1af3b4866c79fb6b72e39135
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (require 'org-macs)
82 (require 'org-compat)
84 (let ((load-suffixes (list ".el")))
85 (org-load-noerror-mustsuffix "org-loaddefs"))
87 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
88 ;; some places -- e.g. see the macro org-with-limited-levels.
90 ;; In Org buffers, the value of `outline-regexp' is that of
91 ;; `org-outline-regexp'. The only function still directly relying on
92 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
93 ;; job when `orgstruct-mode' is active.
94 (defvar org-outline-regexp "\\*+ "
95 "Regexp to match Org headlines.")
97 (defvar org-outline-regexp-bol "^\\*+ "
98 "Regexp to match Org headlines.
99 This is similar to `org-outline-regexp' but additionally makes
100 sure that we are at the beginning of the line.")
102 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
103 "Matches an headline, putting stars and text into groups.
104 Stars are put in group 1 and the trimmed body in group 2.")
106 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
107 (when (fboundp 'defvaralias)
108 (unless (boundp 'calendar-view-holidays-initially-flag)
109 (defvaralias 'calendar-view-holidays-initially-flag
110 'view-calendar-holidays-initially))
111 (unless (boundp 'calendar-view-diary-initially-flag)
112 (defvaralias 'calendar-view-diary-initially-flag
113 'view-diary-entries-initially))
114 (unless (boundp 'diary-fancy-buffer)
115 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
117 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
118 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
119 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
120 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
121 (declare-function org-at-clock-log-p "org-clock" ())
122 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
123 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
124 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
125 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
127 (declare-function orgtbl-mode "org-table" (&optional arg))
128 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
129 (declare-function org-beamer-mode "org-beamer" ())
130 (declare-function org-table-edit-field "org-table" (arg))
131 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
132 (declare-function org-id-get-create "org-id" (&optional force))
133 (declare-function org-id-find-id-file "org-id" (id))
134 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
135 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
136 (declare-function org-table-align "org-table" ())
137 (declare-function org-table-paste-rectangle "org-table" ())
138 (declare-function org-table-maybe-eval-formula "org-table" ())
139 (declare-function org-table-maybe-recalculate-line "org-table" ())
141 (autoload 'org-element-at-point "org-element")
142 (autoload 'org-element-type "org-element")
144 (declare-function org-element-at-point "org-element" (&optional keep-trail))
145 (declare-function org-element-type "org-element" (element))
146 (declare-function org-element-context "org-element" (&optional element))
147 (declare-function org-element-contents "org-element" (element))
148 (declare-function org-element-property "org-element" (property element))
149 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
150 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
151 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
152 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
153 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
155 ;; load languages based on value of `org-babel-load-languages'
156 (defvar org-babel-load-languages)
158 ;;;###autoload
159 (defun org-babel-do-load-languages (sym value)
160 "Load the languages defined in `org-babel-load-languages'."
161 (set-default sym value)
162 (mapc (lambda (pair)
163 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
164 (if active
165 (progn
166 (require (intern (concat "ob-" lang))))
167 (progn
168 (funcall 'fmakunbound
169 (intern (concat "org-babel-execute:" lang)))
170 (funcall 'fmakunbound
171 (intern (concat "org-babel-expand-body:" lang)))))))
172 org-babel-load-languages))
174 (defcustom org-babel-load-languages '((emacs-lisp . t))
175 "Languages which can be evaluated in Org-mode buffers.
176 This list can be used to load support for any of the languages
177 below, note that each language will depend on a different set of
178 system executables and/or Emacs modes. When a language is
179 \"loaded\", then code blocks in that language can be evaluated
180 with `org-babel-execute-src-block' bound by default to C-c
181 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
182 be set to remove code block evaluation from the C-c C-c
183 keybinding. By default only Emacs Lisp (which has no
184 requirements) is loaded."
185 :group 'org-babel
186 :set 'org-babel-do-load-languages
187 :version "24.1"
188 :type '(alist :tag "Babel Languages"
189 :key-type
190 (choice
191 (const :tag "Awk" awk)
192 (const :tag "C" C)
193 (const :tag "R" R)
194 (const :tag "Asymptote" asymptote)
195 (const :tag "Calc" calc)
196 (const :tag "Clojure" clojure)
197 (const :tag "CSS" css)
198 (const :tag "Ditaa" ditaa)
199 (const :tag "Dot" dot)
200 (const :tag "Emacs Lisp" emacs-lisp)
201 (const :tag "Fortran" fortran)
202 (const :tag "Gnuplot" gnuplot)
203 (const :tag "Haskell" haskell)
204 (const :tag "IO" io)
205 (const :tag "Java" java)
206 (const :tag "Javascript" js)
207 (const :tag "LaTeX" latex)
208 (const :tag "Ledger" ledger)
209 (const :tag "Lilypond" lilypond)
210 (const :tag "Lisp" lisp)
211 (const :tag "Makefile" makefile)
212 (const :tag "Maxima" maxima)
213 (const :tag "Matlab" matlab)
214 (const :tag "Mscgen" mscgen)
215 (const :tag "Ocaml" ocaml)
216 (const :tag "Octave" octave)
217 (const :tag "Org" org)
218 (const :tag "Perl" perl)
219 (const :tag "Pico Lisp" picolisp)
220 (const :tag "PlantUML" plantuml)
221 (const :tag "Python" python)
222 (const :tag "Ruby" ruby)
223 (const :tag "Sass" sass)
224 (const :tag "Scala" scala)
225 (const :tag "Scheme" scheme)
226 (const :tag "Screen" screen)
227 (const :tag "Shell Script" sh)
228 (const :tag "Shen" shen)
229 (const :tag "Sql" sql)
230 (const :tag "Sqlite" sqlite))
231 :value-type (boolean :tag "Activate" :value t)))
233 ;;;; Customization variables
234 (defcustom org-clone-delete-id nil
235 "Remove ID property of clones of a subtree.
236 When non-nil, clones of a subtree don't inherit the ID property.
237 Otherwise they inherit the ID property with a new unique
238 identifier."
239 :type 'boolean
240 :version "24.1"
241 :group 'org-id)
243 ;;; Version
244 (org-check-version)
246 ;;;###autoload
247 (defun org-version (&optional here full message)
248 "Show the org-mode version in the echo area.
249 With prefix argument HERE, insert it at point.
250 When FULL is non-nil, use a verbose version string.
251 When MESSAGE is non-nil, display a message with the version."
252 (interactive "P")
253 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
254 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
255 (load-suffixes (list ".el"))
256 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
257 (org-trash (or
258 (and (fboundp 'org-release) (fboundp 'org-git-version))
259 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
260 (load-suffixes save-load-suffixes)
261 (org-version (org-release))
262 (git-version (org-git-version))
263 (version (format "Org-mode version %s (%s @ %s)"
264 org-version
265 git-version
266 (if org-install-dir
267 (if (string= org-dir org-install-dir)
268 org-install-dir
269 (concat "mixed installation! " org-install-dir " and " org-dir))
270 "org-loaddefs.el can not be found!")))
271 (_version (if full version org-version)))
272 (if (org-called-interactively-p 'interactive)
273 (if here
274 (insert version)
275 (message version))
276 (if message (message _version))
277 _version)))
279 (defconst org-version (org-version))
281 ;;; Compatibility constants
283 ;;; The custom variables
285 (defgroup org nil
286 "Outline-based notes management and organizer."
287 :tag "Org"
288 :group 'outlines
289 :group 'calendar)
291 (defcustom org-mode-hook nil
292 "Mode hook for Org-mode, run after the mode was turned on."
293 :group 'org
294 :type 'hook)
296 (defcustom org-load-hook nil
297 "Hook that is run after org.el has been loaded."
298 :group 'org
299 :type 'hook)
301 (defcustom org-log-buffer-setup-hook nil
302 "Hook that is run after an Org log buffer is created."
303 :group 'org
304 :version "24.1"
305 :type 'hook)
307 (defvar org-modules) ; defined below
308 (defvar org-modules-loaded nil
309 "Have the modules been loaded already?")
311 (defun org-load-modules-maybe (&optional force)
312 "Load all extensions listed in `org-modules'."
313 (when (or force (not org-modules-loaded))
314 (mapc (lambda (ext)
315 (condition-case nil (require ext)
316 (error (message "Problems while trying to load feature `%s'" ext))))
317 org-modules)
318 (setq org-modules-loaded t)))
320 (defun org-set-modules (var value)
321 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
322 (set var value)
323 (when (featurep 'org)
324 (org-load-modules-maybe 'force)))
326 (when (org-bound-and-true-p org-modules)
327 (let ((a (member 'org-infojs org-modules)))
328 (and a (setcar a 'org-jsinfo))))
330 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
331 "Modules that should always be loaded together with org.el.
332 If a description starts with <C>, the file is not part of Emacs
333 and loading it will require that you have downloaded and properly installed
334 the org-mode distribution.
336 You can also use this system to load external packages (i.e. neither Org
337 core modules, nor modules from the CONTRIB directory). Just add symbols
338 to the end of the list. If the package is called org-xyz.el, then you need
339 to add the symbol `xyz', and the package must have a call to
341 (provide 'org-xyz)"
342 :group 'org
343 :set 'org-set-modules
344 :type
345 '(set :greedy t
346 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
347 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
348 (const :tag " crypt: Encryption of subtrees" org-crypt)
349 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
350 (const :tag " docview: Links to doc-view buffers" org-docview)
351 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
352 (const :tag " id: Global IDs for identifying entries" org-id)
353 (const :tag " info: Links to Info nodes" org-info)
354 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
355 (const :tag " habit: Track your consistency with habits" org-habit)
356 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
357 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
358 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
359 (const :tag " mew Links to Mew folders/messages" org-mew)
360 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
361 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
362 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
363 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
364 (const :tag " vm: Links to VM folders/messages" org-vm)
365 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
366 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
367 (const :tag " mouse: Additional mouse support" org-mouse)
368 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
370 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
371 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
372 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
373 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
374 (const :tag "C collector: Collect properties into tables" org-collector)
375 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
376 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
377 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
378 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
379 (const :tag "C eval: Include command output as text" org-eval)
380 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
381 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
382 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
383 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
384 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
386 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
388 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
389 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
390 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
391 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
392 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
393 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
394 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
395 (const :tag "C mtags: Support for muse-like tags" org-mtags)
396 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
397 (const :tag "C registry: A registry for Org-mode links" org-registry)
398 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
399 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
400 (const :tag "C secretary: Team management with org-mode" org-secretary)
401 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
402 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
403 (const :tag "C track: Keep up with Org-mode development" org-track)
404 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
405 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
406 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
408 (defcustom org-support-shift-select nil
409 "Non-nil means make shift-cursor commands select text when possible.
411 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
412 start selecting a region, or enlarge regions started in this way.
413 In Org-mode, in special contexts, these same keys are used for
414 other purposes, important enough to compete with shift selection.
415 Org tries to balance these needs by supporting `shift-select-mode'
416 outside these special contexts, under control of this variable.
418 The default of this variable is nil, to avoid confusing behavior. Shifted
419 cursor keys will then execute Org commands in the following contexts:
420 - on a headline, changing TODO state (left/right) and priority (up/down)
421 - on a time stamp, changing the time
422 - in a plain list item, changing the bullet type
423 - in a property definition line, switching between allowed values
424 - in the BEGIN line of a clock table (changing the time block).
425 Outside these contexts, the commands will throw an error.
427 When this variable is t and the cursor is not in a special
428 context, Org-mode will support shift-selection for making and
429 enlarging regions. To make this more effective, the bullet
430 cycling will no longer happen anywhere in an item line, but only
431 if the cursor is exactly on the bullet.
433 If you set this variable to the symbol `always', then the keys
434 will not be special in headlines, property lines, and item lines,
435 to make shift selection work there as well. If this is what you
436 want, you can use the following alternative commands: `C-c C-t'
437 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
438 can be used to switch TODO sets, `C-c -' to cycle item bullet
439 types, and properties can be edited by hand or in column view.
441 However, when the cursor is on a timestamp, shift-cursor commands
442 will still edit the time stamp - this is just too good to give up.
444 XEmacs user should have this variable set to nil, because
445 `shift-select-mode' is in Emacs 23 or later only."
446 :group 'org
447 :type '(choice
448 (const :tag "Never" nil)
449 (const :tag "When outside special context" t)
450 (const :tag "Everywhere except timestamps" always)))
452 (defcustom org-loop-over-headlines-in-active-region nil
453 "Shall some commands act upon headlines in the active region?
455 When set to `t', some commands will be performed in all headlines
456 within the active region.
458 When set to `start-level', some commands will be performed in all
459 headlines within the active region, provided that these headlines
460 are of the same level than the first one.
462 When set to a string, those commands will be performed on the
463 matching headlines within the active region. Such string must be
464 a tags/property/todo match as it is used in the agenda tags view.
466 The list of commands is: `org-schedule', `org-deadline',
467 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
468 `org-archive-to-archive-sibling'. The archiving commands skip
469 already archived entries."
470 :type '(choice (const :tag "Don't loop" nil)
471 (const :tag "All headlines in active region" t)
472 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
473 (string :tag "Tags/Property/Todo matcher"))
474 :version "24.1"
475 :group 'org-todo
476 :group 'org-archive)
478 (defgroup org-startup nil
479 "Options concerning startup of Org-mode."
480 :tag "Org Startup"
481 :group 'org)
483 (defcustom org-startup-folded t
484 "Non-nil means entering Org-mode will switch to OVERVIEW.
485 This can also be configured on a per-file basis by adding one of
486 the following lines anywhere in the buffer:
488 #+STARTUP: fold (or `overview', this is equivalent)
489 #+STARTUP: nofold (or `showall', this is equivalent)
490 #+STARTUP: content
491 #+STARTUP: showeverything"
492 :group 'org-startup
493 :type '(choice
494 (const :tag "nofold: show all" nil)
495 (const :tag "fold: overview" t)
496 (const :tag "content: all headlines" content)
497 (const :tag "show everything, even drawers" showeverything)))
499 (defcustom org-startup-truncated t
500 "Non-nil means entering Org-mode will set `truncate-lines'.
501 This is useful since some lines containing links can be very long and
502 uninteresting. Also tables look terrible when wrapped."
503 :group 'org-startup
504 :type 'boolean)
506 (defcustom org-startup-indented nil
507 "Non-nil means turn on `org-indent-mode' on startup.
508 This can also be configured on a per-file basis by adding one of
509 the following lines anywhere in the buffer:
511 #+STARTUP: indent
512 #+STARTUP: noindent"
513 :group 'org-structure
514 :type '(choice
515 (const :tag "Not" nil)
516 (const :tag "Globally (slow on startup in large files)" t)))
518 (defcustom org-use-sub-superscripts t
519 "Non-nil means interpret \"_\" and \"^\" for export.
520 When this option is turned on, you can use TeX-like syntax for sub- and
521 superscripts. Several characters after \"_\" or \"^\" will be
522 considered as a single item - so grouping with {} is normally not
523 needed. For example, the following things will be parsed as single
524 sub- or superscripts.
526 10^24 or 10^tau several digits will be considered 1 item.
527 10^-12 or 10^-tau a leading sign with digits or a word
528 x^2-y^3 will be read as x^2 - y^3, because items are
529 terminated by almost any nonword/nondigit char.
530 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
532 Still, ambiguity is possible - so when in doubt use {} to enclose the
533 sub/superscript. If you set this variable to the symbol `{}',
534 the braces are *required* in order to trigger interpretations as
535 sub/superscript. This can be helpful in documents that need \"_\"
536 frequently in plain text.
538 Not all export backends support this, but HTML does.
540 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
541 :group 'org-startup
542 :group 'org-export-translation
543 :version "24.1"
544 :type '(choice
545 (const :tag "Always interpret" t)
546 (const :tag "Only with braces" {})
547 (const :tag "Never interpret" nil)))
549 (if (fboundp 'defvaralias)
550 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
553 (defcustom org-startup-with-beamer-mode nil
554 "Non-nil means turn on `org-beamer-mode' on startup.
555 This can also be configured on a per-file basis by adding one of
556 the following lines anywhere in the buffer:
558 #+STARTUP: beamer"
559 :group 'org-startup
560 :version "24.1"
561 :type 'boolean)
563 (defcustom org-startup-align-all-tables nil
564 "Non-nil means align all tables when visiting a file.
565 This is useful when the column width in tables is forced with <N> cookies
566 in table fields. Such tables will look correct only after the first re-align.
567 This can also be configured on a per-file basis by adding one of
568 the following lines anywhere in the buffer:
569 #+STARTUP: align
570 #+STARTUP: noalign"
571 :group 'org-startup
572 :type 'boolean)
574 (defcustom org-startup-with-inline-images nil
575 "Non-nil means show inline images when loading a new Org file.
576 This can also be configured on a per-file basis by adding one of
577 the following lines anywhere in the buffer:
578 #+STARTUP: inlineimages
579 #+STARTUP: noinlineimages"
580 :group 'org-startup
581 :version "24.1"
582 :type 'boolean)
584 (defcustom org-insert-mode-line-in-empty-file nil
585 "Non-nil means insert the first line setting Org-mode in empty files.
586 When the function `org-mode' is called interactively in an empty file, this
587 normally means that the file name does not automatically trigger Org-mode.
588 To ensure that the file will always be in Org-mode in the future, a
589 line enforcing Org-mode will be inserted into the buffer, if this option
590 has been set."
591 :group 'org-startup
592 :type 'boolean)
594 (defcustom org-replace-disputed-keys nil
595 "Non-nil means use alternative key bindings for some keys.
596 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
597 These keys are also used by other packages like shift-selection-mode'
598 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
599 If you want to use Org-mode together with one of these other modes,
600 or more generally if you would like to move some Org-mode commands to
601 other keys, set this variable and configure the keys with the variable
602 `org-disputed-keys'.
604 This option is only relevant at load-time of Org-mode, and must be set
605 *before* org.el is loaded. Changing it requires a restart of Emacs to
606 become effective."
607 :group 'org-startup
608 :type 'boolean)
610 (defcustom org-use-extra-keys nil
611 "Non-nil means use extra key sequence definitions for certain commands.
612 This happens automatically if you run XEmacs or if `window-system'
613 is nil. This variable lets you do the same manually. You must
614 set it before loading org.
616 Example: on Carbon Emacs 22 running graphically, with an external
617 keyboard on a Powerbook, the default way of setting M-left might
618 not work for either Alt or ESC. Setting this variable will make
619 it work for ESC."
620 :group 'org-startup
621 :type 'boolean)
623 (if (fboundp 'defvaralias)
624 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
626 (defcustom org-disputed-keys
627 '(([(shift up)] . [(meta p)])
628 ([(shift down)] . [(meta n)])
629 ([(shift left)] . [(meta -)])
630 ([(shift right)] . [(meta +)])
631 ([(control shift right)] . [(meta shift +)])
632 ([(control shift left)] . [(meta shift -)]))
633 "Keys for which Org-mode and other modes compete.
634 This is an alist, cars are the default keys, second element specifies
635 the alternative to use when `org-replace-disputed-keys' is t.
637 Keys can be specified in any syntax supported by `define-key'.
638 The value of this option takes effect only at Org-mode's startup,
639 therefore you'll have to restart Emacs to apply it after changing."
640 :group 'org-startup
641 :type 'alist)
643 (defun org-key (key)
644 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
645 Or return the original if not disputed.
646 Also apply the translations defined in `org-xemacs-key-equivalents'."
647 (when org-replace-disputed-keys
648 (let* ((nkey (key-description key))
649 (x (org-find-if (lambda (x)
650 (equal (key-description (car x)) nkey))
651 org-disputed-keys)))
652 (setq key (if x (cdr x) key))))
653 (when (featurep 'xemacs)
654 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
655 key)
657 (defun org-find-if (predicate seq)
658 (catch 'exit
659 (while seq
660 (if (funcall predicate (car seq))
661 (throw 'exit (car seq))
662 (pop seq)))))
664 (defun org-defkey (keymap key def)
665 "Define a key, possibly translated, as returned by `org-key'."
666 (define-key keymap (org-key key) def))
668 (defcustom org-ellipsis nil
669 "The ellipsis to use in the Org-mode outline.
670 When nil, just use the standard three dots. When a string, use that instead,
671 When a face, use the standard 3 dots, but with the specified face.
672 The change affects only Org-mode (which will then use its own display table).
673 Changing this requires executing `M-x org-mode' in a buffer to become
674 effective."
675 :group 'org-startup
676 :type '(choice (const :tag "Default" nil)
677 (face :tag "Face" :value org-warning)
678 (string :tag "String" :value "...#")))
680 (defvar org-display-table nil
681 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
683 (defgroup org-keywords nil
684 "Keywords in Org-mode."
685 :tag "Org Keywords"
686 :group 'org)
688 (defcustom org-deadline-string "DEADLINE:"
689 "String to mark deadline entries.
690 A deadline is this string, followed by a time stamp. Should be a word,
691 terminated by a colon. You can insert a schedule keyword and
692 a timestamp with \\[org-deadline].
693 Changes become only effective after restarting Emacs."
694 :group 'org-keywords
695 :type 'string)
697 (defcustom org-scheduled-string "SCHEDULED:"
698 "String to mark scheduled TODO entries.
699 A schedule is this string, followed by a time stamp. Should be a word,
700 terminated by a colon. You can insert a schedule keyword and
701 a timestamp with \\[org-schedule].
702 Changes become only effective after restarting Emacs."
703 :group 'org-keywords
704 :type 'string)
706 (defcustom org-closed-string "CLOSED:"
707 "String used as the prefix for timestamps logging closing a TODO entry."
708 :group 'org-keywords
709 :type 'string)
711 (defcustom org-clock-string "CLOCK:"
712 "String used as prefix for timestamps clocking work hours on an item."
713 :group 'org-keywords
714 :type 'string)
716 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
717 org-scheduled-string "\\|"
718 org-deadline-string "\\|"
719 org-closed-string "\\|"
720 org-clock-string "\\)")
721 "Matches a line with planning or clock info.")
723 (defcustom org-comment-string "COMMENT"
724 "Entries starting with this keyword will never be exported.
725 An entry can be toggled between COMMENT and normal with
726 \\[org-toggle-comment].
727 Changes become only effective after restarting Emacs."
728 :group 'org-keywords
729 :type 'string)
731 (defcustom org-quote-string "QUOTE"
732 "Entries starting with this keyword will be exported in fixed-width font.
733 Quoting applies only to the text in the entry following the headline, and does
734 not extend beyond the next headline, even if that is lower level.
735 An entry can be toggled between QUOTE and normal with
736 \\[org-toggle-fixed-width-section]."
737 :group 'org-keywords
738 :type 'string)
740 (defconst org-repeat-re
741 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
742 "Regular expression for specifying repeated events.
743 After a match, group 1 contains the repeat expression.")
745 (defgroup org-structure nil
746 "Options concerning the general structure of Org-mode files."
747 :tag "Org Structure"
748 :group 'org)
750 (defgroup org-reveal-location nil
751 "Options about how to make context of a location visible."
752 :tag "Org Reveal Location"
753 :group 'org-structure)
755 (defconst org-context-choice
756 '(choice
757 (const :tag "Always" t)
758 (const :tag "Never" nil)
759 (repeat :greedy t :tag "Individual contexts"
760 (cons
761 (choice :tag "Context"
762 (const agenda)
763 (const org-goto)
764 (const occur-tree)
765 (const tags-tree)
766 (const link-search)
767 (const mark-goto)
768 (const bookmark-jump)
769 (const isearch)
770 (const default))
771 (boolean))))
772 "Contexts for the reveal options.")
774 (defcustom org-show-hierarchy-above '((default . t))
775 "Non-nil means show full hierarchy when revealing a location.
776 Org-mode often shows locations in an org-mode file which might have
777 been invisible before. When this is set, the hierarchy of headings
778 above the exposed location is shown.
779 Turning this off for example for sparse trees makes them very compact.
780 Instead of t, this can also be an alist specifying this option for different
781 contexts. Valid contexts are
782 agenda when exposing an entry from the agenda
783 org-goto when using the command `org-goto' on key C-c C-j
784 occur-tree when using the command `org-occur' on key C-c /
785 tags-tree when constructing a sparse tree based on tags matches
786 link-search when exposing search matches associated with a link
787 mark-goto when exposing the jump goal of a mark
788 bookmark-jump when exposing a bookmark location
789 isearch when exiting from an incremental search
790 default default for all contexts not set explicitly"
791 :group 'org-reveal-location
792 :type org-context-choice)
794 (defcustom org-show-following-heading '((default . nil))
795 "Non-nil means show following heading when revealing a location.
796 Org-mode often shows locations in an org-mode file which might have
797 been invisible before. When this is set, the heading following the
798 match is shown.
799 Turning this off for example for sparse trees makes them very compact,
800 but makes it harder to edit the location of the match. In such a case,
801 use the command \\[org-reveal] to show more context.
802 Instead of t, this can also be an alist specifying this option for different
803 contexts. See `org-show-hierarchy-above' for valid contexts."
804 :group 'org-reveal-location
805 :type org-context-choice)
807 (defcustom org-show-siblings '((default . nil) (isearch t))
808 "Non-nil means show all sibling heading when revealing a location.
809 Org-mode often shows locations in an org-mode file which might have
810 been invisible before. When this is set, the sibling of the current entry
811 heading are all made visible. If `org-show-hierarchy-above' is t,
812 the same happens on each level of the hierarchy above the current entry.
814 By default this is on for the isearch context, off for all other contexts.
815 Turning this off for example for sparse trees makes them very compact,
816 but makes it harder to edit the location of the match. In such a case,
817 use the command \\[org-reveal] to show more context.
818 Instead of t, this can also be an alist specifying this option for different
819 contexts. See `org-show-hierarchy-above' for valid contexts."
820 :group 'org-reveal-location
821 :type org-context-choice)
823 (defcustom org-show-entry-below '((default . nil))
824 "Non-nil means show the entry below a headline when revealing a location.
825 Org-mode often shows locations in an org-mode file which might have
826 been invisible before. When this is set, the text below the headline that is
827 exposed is also shown.
829 By default this is off for all contexts.
830 Instead of t, this can also be an alist specifying this option for different
831 contexts. See `org-show-hierarchy-above' for valid contexts."
832 :group 'org-reveal-location
833 :type org-context-choice)
835 (defcustom org-indirect-buffer-display 'other-window
836 "How should indirect tree buffers be displayed?
837 This applies to indirect buffers created with the commands
838 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
839 Valid values are:
840 current-window Display in the current window
841 other-window Just display in another window.
842 dedicated-frame Create one new frame, and re-use it each time.
843 new-frame Make a new frame each time. Note that in this case
844 previously-made indirect buffers are kept, and you need to
845 kill these buffers yourself."
846 :group 'org-structure
847 :group 'org-agenda-windows
848 :type '(choice
849 (const :tag "In current window" current-window)
850 (const :tag "In current frame, other window" other-window)
851 (const :tag "Each time a new frame" new-frame)
852 (const :tag "One dedicated frame" dedicated-frame)))
854 (defcustom org-use-speed-commands nil
855 "Non-nil means activate single letter commands at beginning of a headline.
856 This may also be a function to test for appropriate locations where speed
857 commands should be active."
858 :group 'org-structure
859 :type '(choice
860 (const :tag "Never" nil)
861 (const :tag "At beginning of headline stars" t)
862 (function)))
864 (defcustom org-speed-commands-user nil
865 "Alist of additional speed commands.
866 This list will be checked before `org-speed-commands-default'
867 when the variable `org-use-speed-commands' is non-nil
868 and when the cursor is at the beginning of a headline.
869 The car if each entry is a string with a single letter, which must
870 be assigned to `self-insert-command' in the global map.
871 The cdr is either a command to be called interactively, a function
872 to be called, or a form to be evaluated.
873 An entry that is just a list with a single string will be interpreted
874 as a descriptive headline that will be added when listing the speed
875 commands in the Help buffer using the `?' speed command."
876 :group 'org-structure
877 :type '(repeat :value ("k" . ignore)
878 (choice :value ("k" . ignore)
879 (list :tag "Descriptive Headline" (string :tag "Headline"))
880 (cons :tag "Letter and Command"
881 (string :tag "Command letter")
882 (choice
883 (function)
884 (sexp))))))
886 (defgroup org-cycle nil
887 "Options concerning visibility cycling in Org-mode."
888 :tag "Org Cycle"
889 :group 'org-structure)
891 (defcustom org-cycle-skip-children-state-if-no-children t
892 "Non-nil means skip CHILDREN state in entries that don't have any."
893 :group 'org-cycle
894 :type 'boolean)
896 (defcustom org-cycle-max-level nil
897 "Maximum level which should still be subject to visibility cycling.
898 Levels higher than this will, for cycling, be treated as text, not a headline.
899 When `org-odd-levels-only' is set, a value of N in this variable actually
900 means 2N-1 stars as the limiting headline.
901 When nil, cycle all levels.
902 Note that the limiting level of cycling is also influenced by
903 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
904 `org-inlinetask-min-level' is, cycling will be limited to levels one less
905 than its value."
906 :group 'org-cycle
907 :type '(choice
908 (const :tag "No limit" nil)
909 (integer :tag "Maximum level")))
911 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
912 "Names of drawers. Drawers are not opened by cycling on the headline above.
913 Drawers only open with a TAB on the drawer line itself. A drawer looks like
914 this:
915 :DRAWERNAME:
916 .....
917 :END:
918 The drawer \"PROPERTIES\" is special for capturing properties through
919 the property API.
921 Drawers can be defined on the per-file basis with a line like:
923 #+DRAWERS: HIDDEN STATE PROPERTIES"
924 :group 'org-structure
925 :group 'org-cycle
926 :type '(repeat (string :tag "Drawer Name")))
928 (defcustom org-hide-block-startup nil
929 "Non-nil means entering Org-mode will fold all blocks.
930 This can also be set in on a per-file basis with
932 #+STARTUP: hideblocks
933 #+STARTUP: showblocks"
934 :group 'org-startup
935 :group 'org-cycle
936 :type 'boolean)
938 (defcustom org-cycle-global-at-bob nil
939 "Cycle globally if cursor is at beginning of buffer and not at a headline.
940 This makes it possible to do global cycling without having to use S-TAB or
941 \\[universal-argument] TAB. For this special case to work, the first line
942 of the buffer must not be a headline -- it may be empty or some other text.
943 When used in this way, `org-cycle-hook' is disabled temporarily to make
944 sure the cursor stays at the beginning of the buffer. When this option is
945 nil, don't do anything special at the beginning of the buffer."
946 :group 'org-cycle
947 :type 'boolean)
949 (defcustom org-cycle-level-after-item/entry-creation t
950 "Non-nil means cycle entry level or item indentation in new empty entries.
952 When the cursor is at the end of an empty headline, i.e with only stars
953 and maybe a TODO keyword, TAB will then switch the entry to become a child,
954 and then all possible ancestor states, before returning to the original state.
955 This makes data entry extremely fast: M-RET to create a new headline,
956 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
958 When the cursor is at the end of an empty plain list item, one TAB will
959 make it a subitem, two or more tabs will back up to make this an item
960 higher up in the item hierarchy."
961 :group 'org-cycle
962 :type 'boolean)
964 (defcustom org-cycle-emulate-tab t
965 "Where should `org-cycle' emulate TAB.
966 nil Never
967 white Only in completely white lines
968 whitestart Only at the beginning of lines, before the first non-white char
969 t Everywhere except in headlines
970 exc-hl-bol Everywhere except at the start of a headline
971 If TAB is used in a place where it does not emulate TAB, the current subtree
972 visibility is cycled."
973 :group 'org-cycle
974 :type '(choice (const :tag "Never" nil)
975 (const :tag "Only in completely white lines" white)
976 (const :tag "Before first char in a line" whitestart)
977 (const :tag "Everywhere except in headlines" t)
978 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
981 (defcustom org-cycle-separator-lines 2
982 "Number of empty lines needed to keep an empty line between collapsed trees.
983 If you leave an empty line between the end of a subtree and the following
984 headline, this empty line is hidden when the subtree is folded.
985 Org-mode will leave (exactly) one empty line visible if the number of
986 empty lines is equal or larger to the number given in this variable.
987 So the default 2 means at least 2 empty lines after the end of a subtree
988 are needed to produce free space between a collapsed subtree and the
989 following headline.
991 If the number is negative, and the number of empty lines is at least -N,
992 all empty lines are shown.
994 Special case: when 0, never leave empty lines in collapsed view."
995 :group 'org-cycle
996 :type 'integer)
997 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
999 (defcustom org-pre-cycle-hook nil
1000 "Hook that is run before visibility cycling is happening.
1001 The function(s) in this hook must accept a single argument which indicates
1002 the new state that will be set right after running this hook. The
1003 argument is a symbol. Before a global state change, it can have the values
1004 `overview', `content', or `all'. Before a local state change, it can have
1005 the values `folded', `children', or `subtree'."
1006 :group 'org-cycle
1007 :type 'hook)
1009 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1010 org-cycle-hide-drawers
1011 org-cycle-hide-inline-tasks
1012 org-cycle-show-empty-lines
1013 org-optimize-window-after-visibility-change)
1014 "Hook that is run after `org-cycle' has changed the buffer visibility.
1015 The function(s) in this hook must accept a single argument which indicates
1016 the new state that was set by the most recent `org-cycle' command. The
1017 argument is a symbol. After a global state change, it can have the values
1018 `overview', `contents', or `all'. After a local state change, it can have
1019 the values `folded', `children', or `subtree'."
1020 :group 'org-cycle
1021 :type 'hook)
1023 (defgroup org-edit-structure nil
1024 "Options concerning structure editing in Org-mode."
1025 :tag "Org Edit Structure"
1026 :group 'org-structure)
1028 (defcustom org-odd-levels-only nil
1029 "Non-nil means skip even levels and only use odd levels for the outline.
1030 This has the effect that two stars are being added/taken away in
1031 promotion/demotion commands. It also influences how levels are
1032 handled by the exporters.
1033 Changing it requires restart of `font-lock-mode' to become effective
1034 for fontification also in regions already fontified.
1035 You may also set this on a per-file basis by adding one of the following
1036 lines to the buffer:
1038 #+STARTUP: odd
1039 #+STARTUP: oddeven"
1040 :group 'org-edit-structure
1041 :group 'org-appearance
1042 :type 'boolean)
1044 (defcustom org-adapt-indentation t
1045 "Non-nil means adapt indentation to outline node level.
1047 When this variable is set, Org assumes that you write outlines by
1048 indenting text in each node to align with the headline (after the stars).
1049 The following issues are influenced by this variable:
1051 - When this is set and the *entire* text in an entry is indented, the
1052 indentation is increased by one space in a demotion command, and
1053 decreased by one in a promotion command. If any line in the entry
1054 body starts with text at column 0, indentation is not changed at all.
1056 - Property drawers and planning information is inserted indented when
1057 this variable s set. When nil, they will not be indented.
1059 - TAB indents a line relative to context. The lines below a headline
1060 will be indented when this variable is set.
1062 Note that this is all about true indentation, by adding and removing
1063 space characters. See also `org-indent.el' which does level-dependent
1064 indentation in a virtual way, i.e. at display time in Emacs."
1065 :group 'org-edit-structure
1066 :type 'boolean)
1068 (defcustom org-special-ctrl-a/e nil
1069 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1071 When t, `C-a' will bring back the cursor to the beginning of the
1072 headline text, i.e. after the stars and after a possible TODO
1073 keyword. In an item, this will be the position after bullet and
1074 check-box, if any. When the cursor is already at that position,
1075 another `C-a' will bring it to the beginning of the line.
1077 `C-e' will jump to the end of the headline, ignoring the presence
1078 of tags in the headline. A second `C-e' will then jump to the
1079 true end of the line, after any tags. This also means that, when
1080 this variable is non-nil, `C-e' also will never jump beyond the
1081 end of the heading of a folded section, i.e. not after the
1082 ellipses.
1084 When set to the symbol `reversed', the first `C-a' or `C-e' works
1085 normally, going to the true line boundary first. Only a directly
1086 following, identical keypress will bring the cursor to the
1087 special positions.
1089 This may also be a cons cell where the behavior for `C-a' and
1090 `C-e' is set separately."
1091 :group 'org-edit-structure
1092 :type '(choice
1093 (const :tag "off" nil)
1094 (const :tag "on: after stars/bullet and before tags first" t)
1095 (const :tag "reversed: true line boundary first" reversed)
1096 (cons :tag "Set C-a and C-e separately"
1097 (choice :tag "Special C-a"
1098 (const :tag "off" nil)
1099 (const :tag "on: after stars/bullet first" t)
1100 (const :tag "reversed: before stars/bullet first" reversed))
1101 (choice :tag "Special C-e"
1102 (const :tag "off" nil)
1103 (const :tag "on: before tags first" t)
1104 (const :tag "reversed: after tags first" reversed)))))
1105 (if (fboundp 'defvaralias)
1106 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1108 (defcustom org-special-ctrl-k nil
1109 "Non-nil means `C-k' will behave specially in headlines.
1110 When nil, `C-k' will call the default `kill-line' command.
1111 When t, the following will happen while the cursor is in the headline:
1113 - When the cursor is at the beginning of a headline, kill the entire
1114 line and possible the folded subtree below the line.
1115 - When in the middle of the headline text, kill the headline up to the tags.
1116 - When after the headline text, kill the tags."
1117 :group 'org-edit-structure
1118 :type 'boolean)
1120 (defcustom org-ctrl-k-protect-subtree nil
1121 "Non-nil means, do not delete a hidden subtree with C-k.
1122 When set to the symbol `error', simply throw an error when C-k is
1123 used to kill (part-of) a headline that has hidden text behind it.
1124 Any other non-nil value will result in a query to the user, if it is
1125 OK to kill that hidden subtree. When nil, kill without remorse."
1126 :group 'org-edit-structure
1127 :version "24.1"
1128 :type '(choice
1129 (const :tag "Do not protect hidden subtrees" nil)
1130 (const :tag "Protect hidden subtrees with a security query" t)
1131 (const :tag "Never kill a hidden subtree with C-k" error)))
1133 (defcustom org-catch-invisible-edits nil
1134 "Check if in invisible region before inserting or deleting a character.
1135 Valid values are:
1137 nil Do not check, so just do invisible edits.
1138 error Throw an error and do nothing.
1139 show Make point visible, and do the requested edit.
1140 show-and-error Make point visible, then throw an error and abort the edit.
1141 smart Make point visible, and do insertion/deletion if it is
1142 adjacent to visible text and the change feels predictable.
1143 Never delete a previously invisible character or add in the
1144 middle or right after an invisible region. Basically, this
1145 allows insertion and backward-delete right before ellipses.
1146 FIXME: maybe in this case we should not even show?"
1147 :group 'org-edit-structure
1148 :version "24.1"
1149 :type '(choice
1150 (const :tag "Do not check" nil)
1151 (const :tag "Throw error when trying to edit" error)
1152 (const :tag "Unhide, but do not do the edit" show-and-error)
1153 (const :tag "Show invisible part and do the edit" show)
1154 (const :tag "Be smart and do the right thing" smart)))
1156 (defcustom org-yank-folded-subtrees t
1157 "Non-nil means when yanking subtrees, fold them.
1158 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1159 it starts with a heading and all other headings in it are either children
1160 or siblings, then fold all the subtrees. However, do this only if no
1161 text after the yank would be swallowed into a folded tree by this action."
1162 :group 'org-edit-structure
1163 :type 'boolean)
1165 (defcustom org-yank-adjusted-subtrees nil
1166 "Non-nil means when yanking subtrees, adjust the level.
1167 With this setting, `org-paste-subtree' is used to insert the subtree, see
1168 this function for details."
1169 :group 'org-edit-structure
1170 :type 'boolean)
1172 (defcustom org-M-RET-may-split-line '((default . t))
1173 "Non-nil means M-RET will split the line at the cursor position.
1174 When nil, it will go to the end of the line before making a
1175 new line.
1176 You may also set this option in a different way for different
1177 contexts. Valid contexts are:
1179 headline when creating a new headline
1180 item when creating a new item
1181 table in a table field
1182 default the value to be used for all contexts not explicitly
1183 customized"
1184 :group 'org-structure
1185 :group 'org-table
1186 :type '(choice
1187 (const :tag "Always" t)
1188 (const :tag "Never" nil)
1189 (repeat :greedy t :tag "Individual contexts"
1190 (cons
1191 (choice :tag "Context"
1192 (const headline)
1193 (const item)
1194 (const table)
1195 (const default))
1196 (boolean)))))
1199 (defcustom org-insert-heading-respect-content nil
1200 "Non-nil means insert new headings after the current subtree.
1201 When nil, the new heading is created directly after the current line.
1202 The commands \\[org-insert-heading-respect-content] and
1203 \\[org-insert-todo-heading-respect-content] turn this variable on
1204 for the duration of the command."
1205 :group 'org-structure
1206 :type 'boolean)
1208 (defcustom org-blank-before-new-entry '((heading . auto)
1209 (plain-list-item . auto))
1210 "Should `org-insert-heading' leave a blank line before new heading/item?
1211 The value is an alist, with `heading' and `plain-list-item' as CAR,
1212 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1213 which case Org will look at the surrounding headings/items and try to
1214 make an intelligent decision whether to insert a blank line or not.
1216 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1217 set, the setting here is ignored and no empty line is inserted, to avoid
1218 breaking the list structure."
1219 :group 'org-edit-structure
1220 :type '(list
1221 (cons (const heading)
1222 (choice (const :tag "Never" nil)
1223 (const :tag "Always" t)
1224 (const :tag "Auto" auto)))
1225 (cons (const plain-list-item)
1226 (choice (const :tag "Never" nil)
1227 (const :tag "Always" t)
1228 (const :tag "Auto" auto)))))
1230 (defcustom org-insert-heading-hook nil
1231 "Hook being run after inserting a new heading."
1232 :group 'org-edit-structure
1233 :type 'hook)
1235 (defcustom org-enable-fixed-width-editor t
1236 "Non-nil means lines starting with \":\" are treated as fixed-width.
1237 This currently only means they are never auto-wrapped.
1238 When nil, such lines will be treated like ordinary lines.
1239 See also the QUOTE keyword."
1240 :group 'org-edit-structure
1241 :type 'boolean)
1243 (defcustom org-goto-auto-isearch t
1244 "Non-nil means typing characters in `org-goto' starts incremental search.
1245 When nil, you can use these keybindings to navigate the buffer:
1247 q Quit the org-goto interface
1248 n Go to the next visible heading
1249 p Go to the previous visible heading
1250 f Go one heading forward on same level
1251 b Go one heading backward on same level
1252 u Go one heading up"
1253 :group 'org-edit-structure
1254 :type 'boolean)
1256 (defgroup org-sparse-trees nil
1257 "Options concerning sparse trees in Org-mode."
1258 :tag "Org Sparse Trees"
1259 :group 'org-structure)
1261 (defcustom org-highlight-sparse-tree-matches t
1262 "Non-nil means highlight all matches that define a sparse tree.
1263 The highlights will automatically disappear the next time the buffer is
1264 changed by an edit command."
1265 :group 'org-sparse-trees
1266 :type 'boolean)
1268 (defcustom org-remove-highlights-with-change t
1269 "Non-nil means any change to the buffer will remove temporary highlights.
1270 Such highlights are created by `org-occur' and `org-clock-display'.
1271 When nil, `C-c C-c needs to be used to get rid of the highlights.
1272 The highlights created by `org-preview-latex-fragment' always need
1273 `C-c C-c' to be removed."
1274 :group 'org-sparse-trees
1275 :group 'org-time
1276 :type 'boolean)
1279 (defcustom org-occur-hook '(org-first-headline-recenter)
1280 "Hook that is run after `org-occur' has constructed a sparse tree.
1281 This can be used to recenter the window to show as much of the structure
1282 as possible."
1283 :group 'org-sparse-trees
1284 :type 'hook)
1286 (defgroup org-imenu-and-speedbar nil
1287 "Options concerning imenu and speedbar in Org-mode."
1288 :tag "Org Imenu and Speedbar"
1289 :group 'org-structure)
1291 (defcustom org-imenu-depth 2
1292 "The maximum level for Imenu access to Org-mode headlines.
1293 This also applied for speedbar access."
1294 :group 'org-imenu-and-speedbar
1295 :type 'integer)
1297 (defgroup org-table nil
1298 "Options concerning tables in Org-mode."
1299 :tag "Org Table"
1300 :group 'org)
1302 (defcustom org-enable-table-editor 'optimized
1303 "Non-nil means lines starting with \"|\" are handled by the table editor.
1304 When nil, such lines will be treated like ordinary lines.
1306 When equal to the symbol `optimized', the table editor will be optimized to
1307 do the following:
1308 - Automatic overwrite mode in front of whitespace in table fields.
1309 This makes the structure of the table stay in tact as long as the edited
1310 field does not exceed the column width.
1311 - Minimize the number of realigns. Normally, the table is aligned each time
1312 TAB or RET are pressed to move to another field. With optimization this
1313 happens only if changes to a field might have changed the column width.
1314 Optimization requires replacing the functions `self-insert-command',
1315 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1316 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1317 very good at guessing when a re-align will be necessary, but you can always
1318 force one with \\[org-ctrl-c-ctrl-c].
1320 If you would like to use the optimized version in Org-mode, but the
1321 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1323 This variable can be used to turn on and off the table editor during a session,
1324 but in order to toggle optimization, a restart is required.
1326 See also the variable `org-table-auto-blank-field'."
1327 :group 'org-table
1328 :type '(choice
1329 (const :tag "off" nil)
1330 (const :tag "on" t)
1331 (const :tag "on, optimized" optimized)))
1333 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1334 (version<= emacs-version "24.1"))
1335 "Non-nil means cluster self-insert commands for undo when possible.
1336 If this is set, then, like in the Emacs command loop, 20 consecutive
1337 characters will be undone together.
1338 This is configurable, because there is some impact on typing performance."
1339 :group 'org-table
1340 :type 'boolean)
1342 (defcustom org-table-tab-recognizes-table.el t
1343 "Non-nil means TAB will automatically notice a table.el table.
1344 When it sees such a table, it moves point into it and - if necessary -
1345 calls `table-recognize-table'."
1346 :group 'org-table-editing
1347 :type 'boolean)
1349 (defgroup org-link nil
1350 "Options concerning links in Org-mode."
1351 :tag "Org Link"
1352 :group 'org)
1354 (defvar org-link-abbrev-alist-local nil
1355 "Buffer-local version of `org-link-abbrev-alist', which see.
1356 The value of this is taken from the #+LINK lines.")
1357 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1359 (defcustom org-link-abbrev-alist nil
1360 "Alist of link abbreviations.
1361 The car of each element is a string, to be replaced at the start of a link.
1362 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1363 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1365 [[linkkey:tag][description]]
1367 The 'linkkey' must be a word word, starting with a letter, followed
1368 by letters, numbers, '-' or '_'.
1370 If REPLACE is a string, the tag will simply be appended to create the link.
1371 If the string contains \"%s\", the tag will be inserted there. If the string
1372 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1373 at that point (see the function `url-hexify-string'). If the string contains
1374 the specifier \"%(my-function)\", then the custom function `my-function' will
1375 be invoked: this function takes the tag as its only argument and must return
1376 a string.
1378 REPLACE may also be a function that will be called with the tag as the
1379 only argument to create the link, which should be returned as a string.
1381 See the manual for examples."
1382 :group 'org-link
1383 :type '(repeat
1384 (cons
1385 (string :tag "Protocol")
1386 (choice
1387 (string :tag "Format")
1388 (function)))))
1390 (defcustom org-descriptive-links t
1391 "Non-nil means Org will display descriptive links.
1392 E.g. [[http://orgmode.org][Org website]] will be displayed as
1393 \"Org Website\", hiding the link itself and just displaying its
1394 description. When set to `nil', Org will display the full links
1395 literally.
1397 You can interactively set the value of this variable by calling
1398 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1399 :group 'org-link
1400 :type 'boolean)
1402 (defcustom org-link-file-path-type 'adaptive
1403 "How the path name in file links should be stored.
1404 Valid values are:
1406 relative Relative to the current directory, i.e. the directory of the file
1407 into which the link is being inserted.
1408 absolute Absolute path, if possible with ~ for home directory.
1409 noabbrev Absolute path, no abbreviation of home directory.
1410 adaptive Use relative path for files in the current directory and sub-
1411 directories of it. For other files, use an absolute path."
1412 :group 'org-link
1413 :type '(choice
1414 (const relative)
1415 (const absolute)
1416 (const noabbrev)
1417 (const adaptive)))
1419 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1420 "Types of links that should be activated in Org-mode files.
1421 This is a list of symbols, each leading to the activation of a certain link
1422 type. In principle, it does not hurt to turn on most link types - there may
1423 be a small gain when turning off unused link types. The types are:
1425 bracket The recommended [[link][description]] or [[link]] links with hiding.
1426 angle Links in angular brackets that may contain whitespace like
1427 <bbdb:Carsten Dominik>.
1428 plain Plain links in normal text, no whitespace, like http://google.com.
1429 radio Text that is matched by a radio target, see manual for details.
1430 tag Tag settings in a headline (link to tag search).
1431 date Time stamps (link to calendar).
1432 footnote Footnote labels.
1434 Changing this variable requires a restart of Emacs to become effective."
1435 :group 'org-link
1436 :type '(set :greedy t
1437 (const :tag "Double bracket links" bracket)
1438 (const :tag "Angular bracket links" angle)
1439 (const :tag "Plain text links" plain)
1440 (const :tag "Radio target matches" radio)
1441 (const :tag "Tags" tag)
1442 (const :tag "Timestamps" date)
1443 (const :tag "Footnotes" footnote)))
1445 (defcustom org-make-link-description-function nil
1446 "Function to use for generating link descriptions from links.
1447 When nil, the link location will be used. This function must take
1448 two parameters: the first one is the link, the second one is the
1449 description generated by `org-insert-link'. The function should
1450 return the description to use."
1451 :group 'org-link
1452 :type 'function)
1454 (defgroup org-link-store nil
1455 "Options concerning storing links in Org-mode."
1456 :tag "Org Store Link"
1457 :group 'org-link)
1459 (defcustom org-url-hexify-p t
1460 "When non-nil, hexify URL when creating a link."
1461 :type 'boolean
1462 :version "24.3"
1463 :group 'org-link-store)
1465 (defcustom org-email-link-description-format "Email %c: %.30s"
1466 "Format of the description part of a link to an email or usenet message.
1467 The following %-escapes will be replaced by corresponding information:
1469 %F full \"From\" field
1470 %f name, taken from \"From\" field, address if no name
1471 %T full \"To\" field
1472 %t first name in \"To\" field, address if no name
1473 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1474 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1475 %s subject
1476 %d date
1477 %m message-id.
1479 You may use normal field width specification between the % and the letter.
1480 This is for example useful to limit the length of the subject.
1482 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1483 :group 'org-link-store
1484 :type 'string)
1486 (defcustom org-from-is-user-regexp
1487 (let (r1 r2)
1488 (when (and user-mail-address (not (string= user-mail-address "")))
1489 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1490 (when (and user-full-name (not (string= user-full-name "")))
1491 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1492 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1493 "Regexp matched against the \"From:\" header of an email or usenet message.
1494 It should match if the message is from the user him/herself."
1495 :group 'org-link-store
1496 :type 'regexp)
1498 (defcustom org-context-in-file-links t
1499 "Non-nil means file links from `org-store-link' contain context.
1500 A search string will be added to the file name with :: as separator and
1501 used to find the context when the link is activated by the command
1502 `org-open-at-point'. When this option is t, the entire active region
1503 will be placed in the search string of the file link. If set to a
1504 positive integer, only the first n lines of context will be stored.
1506 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1507 negates this setting for the duration of the command."
1508 :group 'org-link-store
1509 :type '(choice boolean integer))
1511 (defcustom org-keep-stored-link-after-insertion nil
1512 "Non-nil means keep link in list for entire session.
1514 The command `org-store-link' adds a link pointing to the current
1515 location to an internal list. These links accumulate during a session.
1516 The command `org-insert-link' can be used to insert links into any
1517 Org-mode file (offering completion for all stored links). When this
1518 option is nil, every link which has been inserted once using \\[org-insert-link]
1519 will be removed from the list, to make completing the unused links
1520 more efficient."
1521 :group 'org-link-store
1522 :type 'boolean)
1524 (defgroup org-link-follow nil
1525 "Options concerning following links in Org-mode."
1526 :tag "Org Follow Link"
1527 :group 'org-link)
1529 (defcustom org-link-translation-function nil
1530 "Function to translate links with different syntax to Org syntax.
1531 This can be used to translate links created for example by the Planner
1532 or emacs-wiki packages to Org syntax.
1533 The function must accept two parameters, a TYPE containing the link
1534 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1535 which is everything after the link protocol. It should return a cons
1536 with possibly modified values of type and path.
1537 Org contains a function for this, so if you set this variable to
1538 `org-translate-link-from-planner', you should be able follow many
1539 links created by planner."
1540 :group 'org-link-follow
1541 :type 'function)
1543 (defcustom org-follow-link-hook nil
1544 "Hook that is run after a link has been followed."
1545 :group 'org-link-follow
1546 :type 'hook)
1548 (defcustom org-tab-follows-link nil
1549 "Non-nil means on links TAB will follow the link.
1550 Needs to be set before org.el is loaded.
1551 This really should not be used, it does not make sense, and the
1552 implementation is bad."
1553 :group 'org-link-follow
1554 :type 'boolean)
1556 (defcustom org-return-follows-link nil
1557 "Non-nil means on links RET will follow the link."
1558 :group 'org-link-follow
1559 :type 'boolean)
1561 (defcustom org-mouse-1-follows-link
1562 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1563 "Non-nil means mouse-1 on a link will follow the link.
1564 A longer mouse click will still set point. Does not work on XEmacs.
1565 Needs to be set before org.el is loaded."
1566 :group 'org-link-follow
1567 :type 'boolean)
1569 (defcustom org-mark-ring-length 4
1570 "Number of different positions to be recorded in the ring.
1571 Changing this requires a restart of Emacs to work correctly."
1572 :group 'org-link-follow
1573 :type 'integer)
1575 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1576 "Non-nil means internal links in Org files must exactly match a headline.
1577 When nil, the link search tries to match a phrase with all words
1578 in the search text."
1579 :group 'org-link-follow
1580 :version "24.1"
1581 :type '(choice
1582 (const :tag "Use fuzzy text search" nil)
1583 (const :tag "Match only exact headline" t)
1584 (const :tag "Match exact headline or query to create it"
1585 query-to-create)))
1587 (defcustom org-link-frame-setup
1588 '((vm . vm-visit-folder-other-frame)
1589 (vm-imap . vm-visit-imap-folder-other-frame)
1590 (gnus . org-gnus-no-new-news)
1591 (file . find-file-other-window)
1592 (wl . wl-other-frame))
1593 "Setup the frame configuration for following links.
1594 When following a link with Emacs, it may often be useful to display
1595 this link in another window or frame. This variable can be used to
1596 set this up for the different types of links.
1597 For VM, use any of
1598 `vm-visit-folder'
1599 `vm-visit-folder-other-window'
1600 `vm-visit-folder-other-frame'
1601 For Gnus, use any of
1602 `gnus'
1603 `gnus-other-frame'
1604 `org-gnus-no-new-news'
1605 For FILE, use any of
1606 `find-file'
1607 `find-file-other-window'
1608 `find-file-other-frame'
1609 For Wanderlust use any of
1610 `wl'
1611 `wl-other-frame'
1612 For the calendar, use the variable `calendar-setup'.
1613 For BBDB, it is currently only possible to display the matches in
1614 another window."
1615 :group 'org-link-follow
1616 :type '(list
1617 (cons (const vm)
1618 (choice
1619 (const vm-visit-folder)
1620 (const vm-visit-folder-other-window)
1621 (const vm-visit-folder-other-frame)))
1622 (cons (const gnus)
1623 (choice
1624 (const gnus)
1625 (const gnus-other-frame)
1626 (const org-gnus-no-new-news)))
1627 (cons (const file)
1628 (choice
1629 (const find-file)
1630 (const find-file-other-window)
1631 (const find-file-other-frame)))
1632 (cons (const wl)
1633 (choice
1634 (const wl)
1635 (const wl-other-frame)))))
1637 (defcustom org-display-internal-link-with-indirect-buffer nil
1638 "Non-nil means use indirect buffer to display infile links.
1639 Activating internal links (from one location in a file to another location
1640 in the same file) normally just jumps to the location. When the link is
1641 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1642 is displayed in
1643 another window. When this option is set, the other window actually displays
1644 an indirect buffer clone of the current buffer, to avoid any visibility
1645 changes to the current buffer."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-non-existing-files nil
1650 "Non-nil means `org-open-file' will open non-existing files.
1651 When nil, an error will be generated.
1652 This variable applies only to external applications because they
1653 might choke on non-existing files. If the link is to a file that
1654 will be opened in Emacs, the variable is ignored."
1655 :group 'org-link-follow
1656 :type 'boolean)
1658 (defcustom org-open-directory-means-index-dot-org nil
1659 "Non-nil means a link to a directory really means to index.org.
1660 When nil, following a directory link will run dired or open a finder/explorer
1661 window on that directory."
1662 :group 'org-link-follow
1663 :type 'boolean)
1665 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1666 "Function and arguments to call for following mailto links.
1667 This is a list with the first element being a Lisp function, and the
1668 remaining elements being arguments to the function. In string arguments,
1669 %a will be replaced by the address, and %s will be replaced by the subject
1670 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1671 :group 'org-link-follow
1672 :type '(choice
1673 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1674 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1675 (const :tag "message-mail" (message-mail "%a" "%s"))
1676 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1678 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1679 "Non-nil means ask for confirmation before executing shell links.
1680 Shell links can be dangerous: just think about a link
1682 [[shell:rm -rf ~/*][Google Search]]
1684 This link would show up in your Org-mode document as \"Google Search\",
1685 but really it would remove your entire home directory.
1686 Therefore we advise against setting this variable to nil.
1687 Just change it to `y-or-n-p' if you want to confirm with a
1688 single keystroke rather than having to type \"yes\"."
1689 :group 'org-link-follow
1690 :type '(choice
1691 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1692 (const :tag "with y-or-n (faster)" y-or-n-p)
1693 (const :tag "no confirmation (dangerous)" nil)))
1694 (put 'org-confirm-shell-link-function
1695 'safe-local-variable
1696 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1698 (defcustom org-confirm-shell-link-not-regexp ""
1699 "A regexp to skip confirmation for shell links."
1700 :group 'org-link-follow
1701 :version "24.1"
1702 :type 'regexp)
1704 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1705 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1706 Elisp links can be dangerous: just think about a link
1708 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1710 This link would show up in your Org-mode document as \"Google Search\",
1711 but really it would remove your entire home directory.
1712 Therefore we advise against setting this variable to nil.
1713 Just change it to `y-or-n-p' if you want to confirm with a
1714 single keystroke rather than having to type \"yes\"."
1715 :group 'org-link-follow
1716 :type '(choice
1717 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1718 (const :tag "with y-or-n (faster)" y-or-n-p)
1719 (const :tag "no confirmation (dangerous)" nil)))
1720 (put 'org-confirm-shell-link-function
1721 'safe-local-variable
1722 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1724 (defcustom org-confirm-elisp-link-not-regexp ""
1725 "A regexp to skip confirmation for Elisp links."
1726 :group 'org-link-follow
1727 :version "24.1"
1728 :type 'regexp)
1730 (defconst org-file-apps-defaults-gnu
1731 '((remote . emacs)
1732 (system . mailcap)
1733 (t . mailcap))
1734 "Default file applications on a UNIX or GNU/Linux system.
1735 See `org-file-apps'.")
1737 (defconst org-file-apps-defaults-macosx
1738 '((remote . emacs)
1739 (t . "open %s")
1740 (system . "open %s")
1741 ("ps.gz" . "gv %s")
1742 ("eps.gz" . "gv %s")
1743 ("dvi" . "xdvi %s")
1744 ("fig" . "xfig %s"))
1745 "Default file applications on a MacOS X system.
1746 The system \"open\" is known as a default, but we use X11 applications
1747 for some files for which the OS does not have a good default.
1748 See `org-file-apps'.")
1750 (defconst org-file-apps-defaults-windowsnt
1751 (list
1752 '(remote . emacs)
1753 (cons t
1754 (list (if (featurep 'xemacs)
1755 'mswindows-shell-execute
1756 'w32-shell-execute)
1757 "open" 'file))
1758 (cons 'system
1759 (list (if (featurep 'xemacs)
1760 'mswindows-shell-execute
1761 'w32-shell-execute)
1762 "open" 'file)))
1763 "Default file applications on a Windows NT system.
1764 The system \"open\" is used for most files.
1765 See `org-file-apps'.")
1767 (defcustom org-file-apps
1769 (auto-mode . emacs)
1770 ("\\.mm\\'" . default)
1771 ("\\.x?html?\\'" . default)
1772 ("\\.pdf\\'" . default)
1774 "External applications for opening `file:path' items in a document.
1775 Org-mode uses system defaults for different file types, but
1776 you can use this variable to set the application for a given file
1777 extension. The entries in this list are cons cells where the car identifies
1778 files and the cdr the corresponding command. Possible values for the
1779 file identifier are
1780 \"string\" A string as a file identifier can be interpreted in different
1781 ways, depending on its contents:
1783 - Alphanumeric characters only:
1784 Match links with this file extension.
1785 Example: (\"pdf\" . \"evince %s\")
1786 to open PDFs with evince.
1788 - Regular expression: Match links where the
1789 filename matches the regexp. If you want to
1790 use groups here, use shy groups.
1792 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1793 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1794 to open *.html and *.xhtml with firefox.
1796 - Regular expression which contains (non-shy) groups:
1797 Match links where the whole link, including \"::\", and
1798 anything after that, matches the regexp.
1799 In a custom command string, %1, %2, etc. are replaced with
1800 the parts of the link that were matched by the groups.
1801 For backwards compatibility, if a command string is given
1802 that does not use any of the group matches, this case is
1803 handled identically to the second one (i.e. match against
1804 file name only).
1805 In a custom lisp form, you can access the group matches with
1806 (match-string n link).
1808 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1809 to open [[file:document.pdf::5]] with evince at page 5.
1811 `directory' Matches a directory
1812 `remote' Matches a remote file, accessible through tramp or efs.
1813 Remote files most likely should be visited through Emacs
1814 because external applications cannot handle such paths.
1815 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1816 so all files Emacs knows how to handle. Using this with
1817 command `emacs' will open most files in Emacs. Beware that this
1818 will also open html files inside Emacs, unless you add
1819 (\"html\" . default) to the list as well.
1820 t Default for files not matched by any of the other options.
1821 `system' The system command to open files, like `open' on Windows
1822 and Mac OS X, and mailcap under GNU/Linux. This is the command
1823 that will be selected if you call `C-c C-o' with a double
1824 \\[universal-argument] \\[universal-argument] prefix.
1826 Possible values for the command are:
1827 `emacs' The file will be visited by the current Emacs process.
1828 `default' Use the default application for this file type, which is the
1829 association for t in the list, most likely in the system-specific
1830 part.
1831 This can be used to overrule an unwanted setting in the
1832 system-specific variable.
1833 `system' Use the system command for opening files, like \"open\".
1834 This command is specified by the entry whose car is `system'.
1835 Most likely, the system-specific version of this variable
1836 does define this command, but you can overrule/replace it
1837 here.
1838 string A command to be executed by a shell; %s will be replaced
1839 by the path to the file.
1840 sexp A Lisp form which will be evaluated. The file path will
1841 be available in the Lisp variable `file'.
1842 For more examples, see the system specific constants
1843 `org-file-apps-defaults-macosx'
1844 `org-file-apps-defaults-windowsnt'
1845 `org-file-apps-defaults-gnu'."
1846 :group 'org-link-follow
1847 :type '(repeat
1848 (cons (choice :value ""
1849 (string :tag "Extension")
1850 (const :tag "System command to open files" system)
1851 (const :tag "Default for unrecognized files" t)
1852 (const :tag "Remote file" remote)
1853 (const :tag "Links to a directory" directory)
1854 (const :tag "Any files that have Emacs modes"
1855 auto-mode))
1856 (choice :value ""
1857 (const :tag "Visit with Emacs" emacs)
1858 (const :tag "Use default" default)
1859 (const :tag "Use the system command" system)
1860 (string :tag "Command")
1861 (sexp :tag "Lisp form")))))
1863 (defcustom org-doi-server-url "http://dx.doi.org/"
1864 "The URL of the DOI server."
1865 :type 'string
1866 :version "24.3"
1867 :group 'org-link-follow)
1869 (defgroup org-refile nil
1870 "Options concerning refiling entries in Org-mode."
1871 :tag "Org Refile"
1872 :group 'org)
1874 (defcustom org-directory "~/org"
1875 "Directory with org files.
1876 This is just a default location to look for Org files. There is no need
1877 at all to put your files into this directory. It is only used in the
1878 following situations:
1880 1. When a capture template specifies a target file that is not an
1881 absolute path. The path will then be interpreted relative to
1882 `org-directory'
1883 2. When a capture note is filed away in an interactive way (when exiting the
1884 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1885 with `org-directory' as the default path."
1886 :group 'org-refile
1887 :group 'org-remember
1888 :group 'org-capture
1889 :type 'directory)
1891 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1892 "Default target for storing notes.
1893 Used as a fall back file for org-remember.el and org-capture.el, for
1894 templates that do not specify a target file."
1895 :group 'org-refile
1896 :group 'org-remember
1897 :group 'org-capture
1898 :type '(choice
1899 (const :tag "Default from remember-data-file" nil)
1900 file))
1902 (defcustom org-goto-interface 'outline
1903 "The default interface to be used for `org-goto'.
1904 Allowed values are:
1905 outline The interface shows an outline of the relevant file
1906 and the correct heading is found by moving through
1907 the outline or by searching with incremental search.
1908 outline-path-completion Headlines in the current buffer are offered via
1909 completion. This is the interface also used by
1910 the refile command."
1911 :group 'org-refile
1912 :type '(choice
1913 (const :tag "Outline" outline)
1914 (const :tag "Outline-path-completion" outline-path-completion)))
1916 (defcustom org-goto-max-level 5
1917 "Maximum target level when running `org-goto' with refile interface."
1918 :group 'org-refile
1919 :type 'integer)
1921 (defcustom org-reverse-note-order nil
1922 "Non-nil means store new notes at the beginning of a file or entry.
1923 When nil, new notes will be filed to the end of a file or entry.
1924 This can also be a list with cons cells of regular expressions that
1925 are matched against file names, and values."
1926 :group 'org-remember
1927 :group 'org-capture
1928 :group 'org-refile
1929 :type '(choice
1930 (const :tag "Reverse always" t)
1931 (const :tag "Reverse never" nil)
1932 (repeat :tag "By file name regexp"
1933 (cons regexp boolean))))
1935 (defcustom org-log-refile nil
1936 "Information to record when a task is refiled.
1938 Possible values are:
1940 nil Don't add anything
1941 time Add a time stamp to the task
1942 note Prompt for a note and add it with template `org-log-note-headings'
1944 This option can also be set with on a per-file-basis with
1946 #+STARTUP: nologrefile
1947 #+STARTUP: logrefile
1948 #+STARTUP: lognoterefile
1950 You can have local logging settings for a subtree by setting the LOGGING
1951 property to one or more of these keywords.
1953 When bulk-refiling from the agenda, the value `note' is forbidden and
1954 will temporarily be changed to `time'."
1955 :group 'org-refile
1956 :group 'org-progress
1957 :version "24.1"
1958 :type '(choice
1959 (const :tag "No logging" nil)
1960 (const :tag "Record timestamp" time)
1961 (const :tag "Record timestamp with note." note)))
1963 (defcustom org-refile-targets nil
1964 "Targets for refiling entries with \\[org-refile].
1965 This is a list of cons cells. Each cell contains:
1966 - a specification of the files to be considered, either a list of files,
1967 or a symbol whose function or variable value will be used to retrieve
1968 a file name or a list of file names. If you use `org-agenda-files' for
1969 that, all agenda files will be scanned for targets. Nil means consider
1970 headings in the current buffer.
1971 - A specification of how to find candidate refile targets. This may be
1972 any of:
1973 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1974 This tag has to be present in all target headlines, inheritance will
1975 not be considered.
1976 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1977 todo keyword.
1978 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1979 headlines that are refiling targets.
1980 - a cons cell (:level . N). Any headline of level N is considered a target.
1981 Note that, when `org-odd-levels-only' is set, level corresponds to
1982 order in hierarchy, not to the number of stars.
1983 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1984 Note that, when `org-odd-levels-only' is set, level corresponds to
1985 order in hierarchy, not to the number of stars.
1987 Each element of this list generates a set of possible targets.
1988 The union of these sets is presented (with completion) to
1989 the user by `org-refile'.
1991 You can set the variable `org-refile-target-verify-function' to a function
1992 to verify each headline found by the simple criteria above.
1994 When this variable is nil, all top-level headlines in the current buffer
1995 are used, equivalent to the value `((nil . (:level . 1))'."
1996 :group 'org-refile
1997 :type '(repeat
1998 (cons
1999 (choice :value org-agenda-files
2000 (const :tag "All agenda files" org-agenda-files)
2001 (const :tag "Current buffer" nil)
2002 (function) (variable) (file))
2003 (choice :tag "Identify target headline by"
2004 (cons :tag "Specific tag" (const :value :tag) (string))
2005 (cons :tag "TODO keyword" (const :value :todo) (string))
2006 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2007 (cons :tag "Level number" (const :value :level) (integer))
2008 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2010 (defcustom org-refile-target-verify-function nil
2011 "Function to verify if the headline at point should be a refile target.
2012 The function will be called without arguments, with point at the
2013 beginning of the headline. It should return t and leave point
2014 where it is if the headline is a valid target for refiling.
2016 If the target should not be selected, the function must return nil.
2017 In addition to this, it may move point to a place from where the search
2018 should be continued. For example, the function may decide that the entire
2019 subtree of the current entry should be excluded and move point to the end
2020 of the subtree."
2021 :group 'org-refile
2022 :type 'function)
2024 (defcustom org-refile-use-cache nil
2025 "Non-nil means cache refile targets to speed up the process.
2026 The cache for a particular file will be updated automatically when
2027 the buffer has been killed, or when any of the marker used for flagging
2028 refile targets no longer points at a live buffer.
2029 If you have added new entries to a buffer that might themselves be targets,
2030 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2031 find that easier, `C-u C-u C-u C-c C-w'."
2032 :group 'org-refile
2033 :version "24.1"
2034 :type 'boolean)
2036 (defcustom org-refile-use-outline-path nil
2037 "Non-nil means provide refile targets as paths.
2038 So a level 3 headline will be available as level1/level2/level3.
2040 When the value is `file', also include the file name (without directory)
2041 into the path. In this case, you can also stop the completion after
2042 the file name, to get entries inserted as top level in the file.
2044 When `full-file-path', include the full file path."
2045 :group 'org-refile
2046 :type '(choice
2047 (const :tag "Not" nil)
2048 (const :tag "Yes" t)
2049 (const :tag "Start with file name" file)
2050 (const :tag "Start with full file path" full-file-path)))
2052 (defcustom org-outline-path-complete-in-steps t
2053 "Non-nil means complete the outline path in hierarchical steps.
2054 When Org-mode uses the refile interface to select an outline path
2055 \(see variable `org-refile-use-outline-path'), the completion of
2056 the path can be done is a single go, or if can be done in steps down
2057 the headline hierarchy. Going in steps is probably the best if you
2058 do not use a special completion package like `ido' or `icicles'.
2059 However, when using these packages, going in one step can be very
2060 fast, while still showing the whole path to the entry."
2061 :group 'org-refile
2062 :type 'boolean)
2064 (defcustom org-refile-allow-creating-parent-nodes nil
2065 "Non-nil means allow to create new nodes as refile targets.
2066 New nodes are then created by adding \"/new node name\" to the completion
2067 of an existing node. When the value of this variable is `confirm',
2068 new node creation must be confirmed by the user (recommended)
2069 When nil, the completion must match an existing entry.
2071 Note that, if the new heading is not seen by the criteria
2072 listed in `org-refile-targets', multiple instances of the same
2073 heading would be created by trying again to file under the new
2074 heading."
2075 :group 'org-refile
2076 :type '(choice
2077 (const :tag "Never" nil)
2078 (const :tag "Always" t)
2079 (const :tag "Prompt for confirmation" confirm)))
2081 (defcustom org-refile-active-region-within-subtree nil
2082 "Non-nil means also refile active region within a subtree.
2084 By default `org-refile' doesn't allow refiling regions if they
2085 don't contain a set of subtrees, but it might be convenient to
2086 do so sometimes: in that case, the first line of the region is
2087 converted to a headline before refiling."
2088 :group 'org-refile
2089 :version "24.1"
2090 :type 'boolean)
2092 (defgroup org-todo nil
2093 "Options concerning TODO items in Org-mode."
2094 :tag "Org TODO"
2095 :group 'org)
2097 (defgroup org-progress nil
2098 "Options concerning Progress logging in Org-mode."
2099 :tag "Org Progress"
2100 :group 'org-time)
2102 (defvar org-todo-interpretation-widgets
2103 '((:tag "Sequence (cycling hits every state)" sequence)
2104 (:tag "Type (cycling directly to DONE)" type))
2105 "The available interpretation symbols for customizing `org-todo-keywords'.
2106 Interested libraries should add to this list.")
2108 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2109 "List of TODO entry keyword sequences and their interpretation.
2110 \\<org-mode-map>This is a list of sequences.
2112 Each sequence starts with a symbol, either `sequence' or `type',
2113 indicating if the keywords should be interpreted as a sequence of
2114 action steps, or as different types of TODO items. The first
2115 keywords are states requiring action - these states will select a headline
2116 for inclusion into the global TODO list Org-mode produces. If one of
2117 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2118 signify that no further action is necessary. If \"|\" is not found,
2119 the last keyword is treated as the only DONE state of the sequence.
2121 The command \\[org-todo] cycles an entry through these states, and one
2122 additional state where no keyword is present. For details about this
2123 cycling, see the manual.
2125 TODO keywords and interpretation can also be set on a per-file basis with
2126 the special #+SEQ_TODO and #+TYP_TODO lines.
2128 Each keyword can optionally specify a character for fast state selection
2129 \(in combination with the variable `org-use-fast-todo-selection')
2130 and specifiers for state change logging, using the same syntax that
2131 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2132 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2133 indicates to record a time stamp each time this state is selected.
2135 Each keyword may also specify if a timestamp or a note should be
2136 recorded when entering or leaving the state, by adding additional
2137 characters in the parenthesis after the keyword. This looks like this:
2138 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2139 record only the time of the state change. With X and Y being either
2140 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2141 Y when leaving the state if and only if the *target* state does not
2142 define X. You may omit any of the fast-selection key or X or /Y,
2143 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2145 For backward compatibility, this variable may also be just a list
2146 of keywords. In this case the interpretation (sequence or type) will be
2147 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2148 :group 'org-todo
2149 :group 'org-keywords
2150 :type '(choice
2151 (repeat :tag "Old syntax, just keywords"
2152 (string :tag "Keyword"))
2153 (repeat :tag "New syntax"
2154 (cons
2155 (choice
2156 :tag "Interpretation"
2157 ;;Quick and dirty way to see
2158 ;;`org-todo-interpretations'. This takes the
2159 ;;place of item arguments
2160 :convert-widget
2161 (lambda (widget)
2162 (widget-put widget
2163 :args (mapcar
2164 #'(lambda (x)
2165 (widget-convert
2166 (cons 'const x)))
2167 org-todo-interpretation-widgets))
2168 widget))
2169 (repeat
2170 (string :tag "Keyword"))))))
2172 (defvar org-todo-keywords-1 nil
2173 "All TODO and DONE keywords active in a buffer.")
2174 (make-variable-buffer-local 'org-todo-keywords-1)
2175 (defvar org-todo-keywords-for-agenda nil)
2176 (defvar org-done-keywords-for-agenda nil)
2177 (defvar org-drawers-for-agenda nil)
2178 (defvar org-todo-keyword-alist-for-agenda nil)
2179 (defvar org-tag-alist-for-agenda nil)
2180 (defvar org-agenda-contributing-files nil)
2181 (defvar org-not-done-keywords nil)
2182 (make-variable-buffer-local 'org-not-done-keywords)
2183 (defvar org-done-keywords nil)
2184 (make-variable-buffer-local 'org-done-keywords)
2185 (defvar org-todo-heads nil)
2186 (make-variable-buffer-local 'org-todo-heads)
2187 (defvar org-todo-sets nil)
2188 (make-variable-buffer-local 'org-todo-sets)
2189 (defvar org-todo-log-states nil)
2190 (make-variable-buffer-local 'org-todo-log-states)
2191 (defvar org-todo-kwd-alist nil)
2192 (make-variable-buffer-local 'org-todo-kwd-alist)
2193 (defvar org-todo-key-alist nil)
2194 (make-variable-buffer-local 'org-todo-key-alist)
2195 (defvar org-todo-key-trigger nil)
2196 (make-variable-buffer-local 'org-todo-key-trigger)
2198 (defcustom org-todo-interpretation 'sequence
2199 "Controls how TODO keywords are interpreted.
2200 This variable is in principle obsolete and is only used for
2201 backward compatibility, if the interpretation of todo keywords is
2202 not given already in `org-todo-keywords'. See that variable for
2203 more information."
2204 :group 'org-todo
2205 :group 'org-keywords
2206 :type '(choice (const sequence)
2207 (const type)))
2209 (defcustom org-use-fast-todo-selection t
2210 "Non-nil means use the fast todo selection scheme with C-c C-t.
2211 This variable describes if and under what circumstances the cycling
2212 mechanism for TODO keywords will be replaced by a single-key, direct
2213 selection scheme.
2215 When nil, fast selection is never used.
2217 When the symbol `prefix', it will be used when `org-todo' is called
2218 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2219 `C-u t' in an agenda buffer.
2221 When t, fast selection is used by default. In this case, the prefix
2222 argument forces cycling instead.
2224 In all cases, the special interface is only used if access keys have
2225 actually been assigned by the user, i.e. if keywords in the configuration
2226 are followed by a letter in parenthesis, like TODO(t)."
2227 :group 'org-todo
2228 :type '(choice
2229 (const :tag "Never" nil)
2230 (const :tag "By default" t)
2231 (const :tag "Only with C-u C-c C-t" prefix)))
2233 (defcustom org-provide-todo-statistics t
2234 "Non-nil means update todo statistics after insert and toggle.
2235 ALL-HEADLINES means update todo statistics by including headlines
2236 with no TODO keyword as well, counting them as not done.
2237 A list of TODO keywords means the same, but skip keywords that are
2238 not in this list.
2240 When this is set, todo statistics is updated in the parent of the
2241 current entry each time a todo state is changed."
2242 :group 'org-todo
2243 :type '(choice
2244 (const :tag "Yes, only for TODO entries" t)
2245 (const :tag "Yes, including all entries" 'all-headlines)
2246 (repeat :tag "Yes, for TODOs in this list"
2247 (string :tag "TODO keyword"))
2248 (other :tag "No TODO statistics" nil)))
2250 (defcustom org-hierarchical-todo-statistics t
2251 "Non-nil means TODO statistics covers just direct children.
2252 When nil, all entries in the subtree are considered.
2253 This has only an effect if `org-provide-todo-statistics' is set.
2254 To set this to nil for only a single subtree, use a COOKIE_DATA
2255 property and include the word \"recursive\" into the value."
2256 :group 'org-todo
2257 :type 'boolean)
2259 (defcustom org-after-todo-state-change-hook nil
2260 "Hook which is run after the state of a TODO item was changed.
2261 The new state (a string with a TODO keyword, or nil) is available in the
2262 Lisp variable `org-state'."
2263 :group 'org-todo
2264 :type 'hook)
2266 (defvar org-blocker-hook nil
2267 "Hook for functions that are allowed to block a state change.
2269 Functions in this hook should not modify the buffer.
2270 Each function gets as its single argument a property list,
2271 see `org-trigger-hook' for more information about this list.
2273 If any of the functions in this hook returns nil, the state change
2274 is blocked.")
2276 (defvar org-trigger-hook nil
2277 "Hook for functions that are triggered by a state change.
2279 Each function gets as its single argument a property list with at
2280 least the following elements:
2282 (:type type-of-change :position pos-at-entry-start
2283 :from old-state :to new-state)
2285 Depending on the type, more properties may be present.
2287 This mechanism is currently implemented for:
2289 TODO state changes
2290 ------------------
2291 :type todo-state-change
2292 :from previous state (keyword as a string), or nil, or a symbol
2293 'todo' or 'done', to indicate the general type of state.
2294 :to new state, like in :from")
2296 (defcustom org-enforce-todo-dependencies nil
2297 "Non-nil means undone TODO entries will block switching the parent to DONE.
2298 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2299 be blocked if any prior sibling is not yet done.
2300 Finally, if the parent is blocked because of ordered siblings of its own,
2301 the child will also be blocked."
2302 :set (lambda (var val)
2303 (set var val)
2304 (if val
2305 (add-hook 'org-blocker-hook
2306 'org-block-todo-from-children-or-siblings-or-parent)
2307 (remove-hook 'org-blocker-hook
2308 'org-block-todo-from-children-or-siblings-or-parent)))
2309 :group 'org-todo
2310 :type 'boolean)
2312 (defcustom org-enforce-todo-checkbox-dependencies nil
2313 "Non-nil means unchecked boxes will block switching the parent to DONE.
2314 When this is nil, checkboxes have no influence on switching TODO states.
2315 When non-nil, you first need to check off all check boxes before the TODO
2316 entry can be switched to DONE.
2317 This variable needs to be set before org.el is loaded, and you need to
2318 restart Emacs after a change to make the change effective. The only way
2319 to change is while Emacs is running is through the customize interface."
2320 :set (lambda (var val)
2321 (set var val)
2322 (if val
2323 (add-hook 'org-blocker-hook
2324 'org-block-todo-from-checkboxes)
2325 (remove-hook 'org-blocker-hook
2326 'org-block-todo-from-checkboxes)))
2327 :group 'org-todo
2328 :type 'boolean)
2330 (defcustom org-treat-insert-todo-heading-as-state-change nil
2331 "Non-nil means inserting a TODO heading is treated as state change.
2332 So when the command \\[org-insert-todo-heading] is used, state change
2333 logging will apply if appropriate. When nil, the new TODO item will
2334 be inserted directly, and no logging will take place."
2335 :group 'org-todo
2336 :type 'boolean)
2338 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2339 "Non-nil means switching TODO states with S-cursor counts as state change.
2340 This is the default behavior. However, setting this to nil allows a
2341 convenient way to select a TODO state and bypass any logging associated
2342 with that."
2343 :group 'org-todo
2344 :type 'boolean)
2346 (defcustom org-todo-state-tags-triggers nil
2347 "Tag changes that should be triggered by TODO state changes.
2348 This is a list. Each entry is
2350 (state-change (tag . flag) .......)
2352 State-change can be a string with a state, and empty string to indicate the
2353 state that has no TODO keyword, or it can be one of the symbols `todo'
2354 or `done', meaning any not-done or done state, respectively."
2355 :group 'org-todo
2356 :group 'org-tags
2357 :type '(repeat
2358 (cons (choice :tag "When changing to"
2359 (const :tag "Not-done state" todo)
2360 (const :tag "Done state" done)
2361 (string :tag "State"))
2362 (repeat
2363 (cons :tag "Tag action"
2364 (string :tag "Tag")
2365 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2367 (defcustom org-log-done nil
2368 "Information to record when a task moves to the DONE state.
2370 Possible values are:
2372 nil Don't add anything, just change the keyword
2373 time Add a time stamp to the task
2374 note Prompt for a note and add it with template `org-log-note-headings'
2376 This option can also be set with on a per-file-basis with
2378 #+STARTUP: nologdone
2379 #+STARTUP: logdone
2380 #+STARTUP: lognotedone
2382 You can have local logging settings for a subtree by setting the LOGGING
2383 property to one or more of these keywords."
2384 :group 'org-todo
2385 :group 'org-progress
2386 :type '(choice
2387 (const :tag "No logging" nil)
2388 (const :tag "Record CLOSED timestamp" time)
2389 (const :tag "Record CLOSED timestamp with note." note)))
2391 ;; Normalize old uses of org-log-done.
2392 (cond
2393 ((eq org-log-done t) (setq org-log-done 'time))
2394 ((and (listp org-log-done) (memq 'done org-log-done))
2395 (setq org-log-done 'note)))
2397 (defcustom org-log-reschedule nil
2398 "Information to record when the scheduling date of a tasks is modified.
2400 Possible values are:
2402 nil Don't add anything, just change the date
2403 time Add a time stamp to the task
2404 note Prompt for a note and add it with template `org-log-note-headings'
2406 This option can also be set with on a per-file-basis with
2408 #+STARTUP: nologreschedule
2409 #+STARTUP: logreschedule
2410 #+STARTUP: lognotereschedule"
2411 :group 'org-todo
2412 :group 'org-progress
2413 :type '(choice
2414 (const :tag "No logging" nil)
2415 (const :tag "Record timestamp" time)
2416 (const :tag "Record timestamp with note." note)))
2418 (defcustom org-log-redeadline nil
2419 "Information to record when the deadline date of a tasks is modified.
2421 Possible values are:
2423 nil Don't add anything, just change the date
2424 time Add a time stamp to the task
2425 note Prompt for a note and add it with template `org-log-note-headings'
2427 This option can also be set with on a per-file-basis with
2429 #+STARTUP: nologredeadline
2430 #+STARTUP: logredeadline
2431 #+STARTUP: lognoteredeadline
2433 You can have local logging settings for a subtree by setting the LOGGING
2434 property to one or more of these keywords."
2435 :group 'org-todo
2436 :group 'org-progress
2437 :type '(choice
2438 (const :tag "No logging" nil)
2439 (const :tag "Record timestamp" time)
2440 (const :tag "Record timestamp with note." note)))
2442 (defcustom org-log-note-clock-out nil
2443 "Non-nil means record a note when clocking out of an item.
2444 This can also be configured on a per-file basis by adding one of
2445 the following lines anywhere in the buffer:
2447 #+STARTUP: lognoteclock-out
2448 #+STARTUP: nolognoteclock-out"
2449 :group 'org-todo
2450 :group 'org-progress
2451 :type 'boolean)
2453 (defcustom org-log-done-with-time t
2454 "Non-nil means the CLOSED time stamp will contain date and time.
2455 When nil, only the date will be recorded."
2456 :group 'org-progress
2457 :type 'boolean)
2459 (defcustom org-log-note-headings
2460 '((done . "CLOSING NOTE %t")
2461 (state . "State %-12s from %-12S %t")
2462 (note . "Note taken on %t")
2463 (reschedule . "Rescheduled from %S on %t")
2464 (delschedule . "Not scheduled, was %S on %t")
2465 (redeadline . "New deadline from %S on %t")
2466 (deldeadline . "Removed deadline, was %S on %t")
2467 (refile . "Refiled on %t")
2468 (clock-out . ""))
2469 "Headings for notes added to entries.
2470 The value is an alist, with the car being a symbol indicating the note
2471 context, and the cdr is the heading to be used. The heading may also be the
2472 empty string.
2473 %t in the heading will be replaced by a time stamp.
2474 %T will be an active time stamp instead the default inactive one
2475 %d will be replaced by a short-format time stamp.
2476 %D will be replaced by an active short-format time stamp.
2477 %s will be replaced by the new TODO state, in double quotes.
2478 %S will be replaced by the old TODO state, in double quotes.
2479 %u will be replaced by the user name.
2480 %U will be replaced by the full user name.
2482 In fact, it is not a good idea to change the `state' entry, because
2483 agenda log mode depends on the format of these entries."
2484 :group 'org-todo
2485 :group 'org-progress
2486 :type '(list :greedy t
2487 (cons (const :tag "Heading when closing an item" done) string)
2488 (cons (const :tag
2489 "Heading when changing todo state (todo sequence only)"
2490 state) string)
2491 (cons (const :tag "Heading when just taking a note" note) string)
2492 (cons (const :tag "Heading when clocking out" clock-out) string)
2493 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2494 (cons (const :tag "Heading when rescheduling" reschedule) string)
2495 (cons (const :tag "Heading when changing deadline" redeadline) string)
2496 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2497 (cons (const :tag "Heading when refiling" refile) string)))
2499 (unless (assq 'note org-log-note-headings)
2500 (push '(note . "%t") org-log-note-headings))
2502 (defcustom org-log-into-drawer nil
2503 "Non-nil means insert state change notes and time stamps into a drawer.
2504 When nil, state changes notes will be inserted after the headline and
2505 any scheduling and clock lines, but not inside a drawer.
2507 The value of this variable should be the name of the drawer to use.
2508 LOGBOOK is proposed as the default drawer for this purpose, you can
2509 also set this to a string to define the drawer of your choice.
2511 A value of t is also allowed, representing \"LOGBOOK\".
2513 A value of t or nil can also be set with on a per-file-basis with
2515 #+STARTUP: logdrawer
2516 #+STARTUP: nologdrawer
2518 If this variable is set, `org-log-state-notes-insert-after-drawers'
2519 will be ignored.
2521 You can set the property LOG_INTO_DRAWER to overrule this setting for
2522 a subtree."
2523 :group 'org-todo
2524 :group 'org-progress
2525 :type '(choice
2526 (const :tag "Not into a drawer" nil)
2527 (const :tag "LOGBOOK" t)
2528 (string :tag "Other")))
2530 (if (fboundp 'defvaralias)
2531 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2533 (defun org-log-into-drawer ()
2534 "Return the value of `org-log-into-drawer', but let properties overrule.
2535 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2536 used instead of the default value."
2537 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2538 (cond
2539 ((not p) org-log-into-drawer)
2540 ((equal p "nil") nil)
2541 ((equal p "t") "LOGBOOK")
2542 (t p))))
2544 (defcustom org-log-state-notes-insert-after-drawers nil
2545 "Non-nil means insert state change notes after any drawers in entry.
2546 Only the drawers that *immediately* follow the headline and the
2547 deadline/scheduled line are skipped.
2548 When nil, insert notes right after the heading and perhaps the line
2549 with deadline/scheduling if present.
2551 This variable will have no effect if `org-log-into-drawer' is
2552 set."
2553 :group 'org-todo
2554 :group 'org-progress
2555 :type 'boolean)
2557 (defcustom org-log-states-order-reversed t
2558 "Non-nil means the latest state note will be directly after heading.
2559 When nil, the state change notes will be ordered according to time.
2561 This option can also be set with on a per-file-basis with
2563 #+STARTUP: logstatesreversed
2564 #+STARTUP: nologstatesreversed"
2565 :group 'org-todo
2566 :group 'org-progress
2567 :type 'boolean)
2569 (defcustom org-todo-repeat-to-state nil
2570 "The TODO state to which a repeater should return the repeating task.
2571 By default this is the first task in a TODO sequence, or the previous state
2572 in a TODO_TYP set. But you can specify another task here.
2573 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2574 :group 'org-todo
2575 :version "24.1"
2576 :type '(choice (const :tag "Head of sequence" nil)
2577 (string :tag "Specific state")))
2579 (defcustom org-log-repeat 'time
2580 "Non-nil means record moving through the DONE state when triggering repeat.
2581 An auto-repeating task is immediately switched back to TODO when
2582 marked DONE. If you are not logging state changes (by adding \"@\"
2583 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2584 record a closing note, there will be no record of the task moving
2585 through DONE. This variable forces taking a note anyway.
2587 nil Don't force a record
2588 time Record a time stamp
2589 note Prompt for a note and add it with template `org-log-note-headings'
2591 This option can also be set with on a per-file-basis with
2593 #+STARTUP: nologrepeat
2594 #+STARTUP: logrepeat
2595 #+STARTUP: lognoterepeat
2597 You can have local logging settings for a subtree by setting the LOGGING
2598 property to one or more of these keywords."
2599 :group 'org-todo
2600 :group 'org-progress
2601 :type '(choice
2602 (const :tag "Don't force a record" nil)
2603 (const :tag "Force recording the DONE state" time)
2604 (const :tag "Force recording a note with the DONE state" note)))
2607 (defgroup org-priorities nil
2608 "Priorities in Org-mode."
2609 :tag "Org Priorities"
2610 :group 'org-todo)
2612 (defcustom org-enable-priority-commands t
2613 "Non-nil means priority commands are active.
2614 When nil, these commands will be disabled, so that you never accidentally
2615 set a priority."
2616 :group 'org-priorities
2617 :type 'boolean)
2619 (defcustom org-highest-priority ?A
2620 "The highest priority of TODO items. A character like ?A, ?B etc.
2621 Must have a smaller ASCII number than `org-lowest-priority'."
2622 :group 'org-priorities
2623 :type 'character)
2625 (defcustom org-lowest-priority ?C
2626 "The lowest priority of TODO items. A character like ?A, ?B etc.
2627 Must have a larger ASCII number than `org-highest-priority'."
2628 :group 'org-priorities
2629 :type 'character)
2631 (defcustom org-default-priority ?B
2632 "The default priority of TODO items.
2633 This is the priority an item gets if no explicit priority is given.
2634 When starting to cycle on an empty priority the first step in the cycle
2635 depends on `org-priority-start-cycle-with-default'. The resulting first
2636 step priority must not exceed the range from `org-highest-priority' to
2637 `org-lowest-priority' which means that `org-default-priority' has to be
2638 in this range exclusive or inclusive the range boundaries. Else the
2639 first step refuses to set the default and the second will fall back
2640 to (depending on the command used) the highest or lowest priority."
2641 :group 'org-priorities
2642 :type 'character)
2644 (defcustom org-priority-start-cycle-with-default t
2645 "Non-nil means start with default priority when starting to cycle.
2646 When this is nil, the first step in the cycle will be (depending on the
2647 command used) one higher or lower than the default priority.
2648 See also `org-default-priority'."
2649 :group 'org-priorities
2650 :type 'boolean)
2652 (defcustom org-get-priority-function nil
2653 "Function to extract the priority from a string.
2654 The string is normally the headline. If this is nil Org computes the
2655 priority from the priority cookie like [#A] in the headline. It returns
2656 an integer, increasing by 1000 for each priority level.
2657 The user can set a different function here, which should take a string
2658 as an argument and return the numeric priority."
2659 :group 'org-priorities
2660 :version "24.1"
2661 :type 'function)
2663 (defgroup org-time nil
2664 "Options concerning time stamps and deadlines in Org-mode."
2665 :tag "Org Time"
2666 :group 'org)
2668 (defcustom org-insert-labeled-timestamps-at-point nil
2669 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2670 When nil, these labeled time stamps are forces into the second line of an
2671 entry, just after the headline. When scheduling from the global TODO list,
2672 the time stamp will always be forced into the second line."
2673 :group 'org-time
2674 :type 'boolean)
2676 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2677 "Formats for `format-time-string' which are used for time stamps.
2678 It is not recommended to change this constant.")
2680 (defcustom org-time-stamp-rounding-minutes '(0 5)
2681 "Number of minutes to round time stamps to.
2682 These are two values, the first applies when first creating a time stamp.
2683 The second applies when changing it with the commands `S-up' and `S-down'.
2684 When changing the time stamp, this means that it will change in steps
2685 of N minutes, as given by the second value.
2687 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2688 numbers should be factors of 60, so for example 5, 10, 15.
2690 When this is larger than 1, you can still force an exact time stamp by using
2691 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2692 and by using a prefix arg to `S-up/down' to specify the exact number
2693 of minutes to shift."
2694 :group 'org-time
2695 :get #'(lambda (var) ; Make sure both elements are there
2696 (if (integerp (default-value var))
2697 (list (default-value var) 5)
2698 (default-value var)))
2699 :type '(list
2700 (integer :tag "when inserting times")
2701 (integer :tag "when modifying times")))
2703 ;; Normalize old customizations of this variable.
2704 (when (integerp org-time-stamp-rounding-minutes)
2705 (setq org-time-stamp-rounding-minutes
2706 (list org-time-stamp-rounding-minutes
2707 org-time-stamp-rounding-minutes)))
2709 (defcustom org-display-custom-times nil
2710 "Non-nil means overlay custom formats over all time stamps.
2711 The formats are defined through the variable `org-time-stamp-custom-formats'.
2712 To turn this on on a per-file basis, insert anywhere in the file:
2713 #+STARTUP: customtime"
2714 :group 'org-time
2715 :set 'set-default
2716 :type 'sexp)
2717 (make-variable-buffer-local 'org-display-custom-times)
2719 (defcustom org-time-stamp-custom-formats
2720 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2721 "Custom formats for time stamps. See `format-time-string' for the syntax.
2722 These are overlaid over the default ISO format if the variable
2723 `org-display-custom-times' is set. Time like %H:%M should be at the
2724 end of the second format. The custom formats are also honored by export
2725 commands, if custom time display is turned on at the time of export."
2726 :group 'org-time
2727 :type 'sexp)
2729 (defun org-time-stamp-format (&optional long inactive)
2730 "Get the right format for a time string."
2731 (let ((f (if long (cdr org-time-stamp-formats)
2732 (car org-time-stamp-formats))))
2733 (if inactive
2734 (concat "[" (substring f 1 -1) "]")
2735 f)))
2737 (defcustom org-time-clocksum-format
2738 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2739 "The format string used when creating CLOCKSUM lines.
2740 This is also used when Org mode generates a time duration.
2742 The value can be a single format string containing two
2743 %-sequences, which will be filled with the number of hours and
2744 minutes in that order.
2746 Alternatively, the value can be a plist associating any of the
2747 keys :years, :months, :weeks, :days, :hours or :minutes with
2748 format strings. The time duration is formatted using only the
2749 time components that are needed and concatenating the results.
2750 If a time unit in absent, it falls back to the next smallest
2751 unit.
2753 The keys :require-years, :require-months, :require-days,
2754 :require-weeks, :require-hours, :require-minutes are also
2755 meaningful. A non-nil value for these keys indicates that the
2756 corresponding time component should always be included, even if
2757 its value is 0.
2760 For example,
2762 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2763 :require-minutes t)
2765 means durations longer than a day will be expressed in days,
2766 hours and minutes, and durations less than a day will always be
2767 expressed in hours and minutes (even for durations less than an
2768 hour).
2770 The value
2772 \(:days \"%dd\" :minutes \"%dm\")
2774 means durations longer than a day will be expressed in days and
2775 minutes, and durations less than a day will be expressed entirely
2776 in minutes (even for durations longer than an hour)."
2777 :group 'org-time
2778 :group 'org-clock
2779 :version "24.3"
2780 :type '(choice (string :tag "Format string")
2781 (set :tag "Plist"
2782 (group :inline t (const :tag "Years" :years)
2783 (string :tag "Format string"))
2784 (group :inline t
2785 (const :tag "Always show years" :require-years)
2786 (const t))
2787 (group :inline t (const :tag "Months" :months)
2788 (string :tag "Format string"))
2789 (group :inline t
2790 (const :tag "Always show months" :require-months)
2791 (const t))
2792 (group :inline t (const :tag "Weeks" :weeks)
2793 (string :tag "Format string"))
2794 (group :inline t
2795 (const :tag "Always show weeks" :require-weeks)
2796 (const t))
2797 (group :inline t (const :tag "Days" :days)
2798 (string :tag "Format string"))
2799 (group :inline t
2800 (const :tag "Always show days" :require-days)
2801 (const t))
2802 (group :inline t (const :tag "Hours" :hours)
2803 (string :tag "Format string"))
2804 (group :inline t
2805 (const :tag "Always show hours" :require-hours)
2806 (const t))
2807 (group :inline t (const :tag "Minutes" :minutes)
2808 (string :tag "Format string"))
2809 (group :inline t
2810 (const :tag "Always show minutes" :require-minutes)
2811 (const t)))))
2813 (defcustom org-time-clocksum-use-fractional nil
2814 "When non-nil, \\[org-clock-display] uses fractional times.
2815 See `org-time-clocksum-format' for more on time clock formats."
2816 :group 'org-time
2817 :group 'org-clock
2818 :version "24.3"
2819 :type 'boolean)
2821 (defcustom org-time-clocksum-use-effort-durations t
2822 "When non-nil, \\[org-clock-display] uses effort durations.
2823 E.g. by default, one day is considered to be a 8 hours effort,
2824 so a task that has been clocked for 16 hours will be displayed
2825 as during 2 days in the clock display or in the clocktable.
2827 See `org-effort-durations' on how to set effort durations
2828 and `org-time-clocksum-format' for more on time clock formats."
2829 :group 'org-time
2830 :group 'org-clock
2831 :version "24.3"
2832 :type 'boolean)
2834 (defcustom org-time-clocksum-fractional-format "%.2f"
2835 "The format string used when creating CLOCKSUM lines,
2836 or when Org mode generates a time duration, if
2837 `org-time-clocksum-use-fractional' is enabled.
2839 The value can be a single format string containing one
2840 %-sequence, which will be filled with the number of hours as
2841 a float.
2843 Alternatively, the value can be a plist associating any of the
2844 keys :years, :months, :weeks, :days, :hours or :minutes with
2845 a format string. The time duration is formatted using the
2846 largest time unit which gives a non-zero integer part. If all
2847 specified formats have zero integer part, the smallest time unit
2848 is used."
2849 :group 'org-time
2850 :type '(choice (string :tag "Format string")
2851 (set (group :inline t (const :tag "Years" :years)
2852 (string :tag "Format string"))
2853 (group :inline t (const :tag "Months" :months)
2854 (string :tag "Format string"))
2855 (group :inline t (const :tag "Weeks" :weeks)
2856 (string :tag "Format string"))
2857 (group :inline t (const :tag "Days" :days)
2858 (string :tag "Format string"))
2859 (group :inline t (const :tag "Hours" :hours)
2860 (string :tag "Format string"))
2861 (group :inline t (const :tag "Minutes" :minutes)
2862 (string :tag "Format string")))))
2864 (defcustom org-deadline-warning-days 14
2865 "No. of days before expiration during which a deadline becomes active.
2866 This variable governs the display in sparse trees and in the agenda.
2867 When 0 or negative, it means use this number (the absolute value of it)
2868 even if a deadline has a different individual lead time specified.
2870 Custom commands can set this variable in the options section."
2871 :group 'org-time
2872 :group 'org-agenda-daily/weekly
2873 :type 'integer)
2875 (defcustom org-read-date-prefer-future t
2876 "Non-nil means assume future for incomplete date input from user.
2877 This affects the following situations:
2878 1. The user gives a month but not a year.
2879 For example, if it is April and you enter \"feb 2\", this will be read
2880 as Feb 2, *next* year. \"May 5\", however, will be this year.
2881 2. The user gives a day, but no month.
2882 For example, if today is the 15th, and you enter \"3\", Org-mode will
2883 read this as the third of *next* month. However, if you enter \"17\",
2884 it will be considered as *this* month.
2886 If you set this variable to the symbol `time', then also the following
2887 will work:
2889 3. If the user gives a time.
2890 If the time is before now, it will be interpreted as tomorrow.
2892 Currently none of this works for ISO week specifications.
2894 When this option is nil, the current day, month and year will always be
2895 used as defaults.
2897 See also `org-agenda-jump-prefer-future'."
2898 :group 'org-time
2899 :type '(choice
2900 (const :tag "Never" nil)
2901 (const :tag "Check month and day" t)
2902 (const :tag "Check month, day, and time" time)))
2904 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2905 "Should the agenda jump command prefer the future for incomplete dates?
2906 The default is to do the same as configured in `org-read-date-prefer-future'.
2907 But you can also set a deviating value here.
2908 This may t or nil, or the symbol `org-read-date-prefer-future'."
2909 :group 'org-agenda
2910 :group 'org-time
2911 :version "24.1"
2912 :type '(choice
2913 (const :tag "Use org-read-date-prefer-future"
2914 org-read-date-prefer-future)
2915 (const :tag "Never" nil)
2916 (const :tag "Always" t)))
2918 (defcustom org-read-date-force-compatible-dates t
2919 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2921 Depending on the system Emacs is running on, certain dates cannot
2922 be represented with the type used internally to represent time.
2923 Dates between 1970-1-1 and 2038-1-1 can always be represented
2924 correctly. Some systems allow for earlier dates, some for later,
2925 some for both. One way to find out it to insert any date into an
2926 Org buffer, putting the cursor on the year and hitting S-up and
2927 S-down to test the range.
2929 When this variable is set to t, the date/time prompt will not let
2930 you specify dates outside the 1970-2037 range, so it is certain that
2931 these dates will work in whatever version of Emacs you are
2932 running, and also that you can move a file from one Emacs implementation
2933 to another. WHenever Org is forcing the year for you, it will display
2934 a message and beep.
2936 When this variable is nil, Org will check if the date is
2937 representable in the specific Emacs implementation you are using.
2938 If not, it will force a year, usually the current year, and beep
2939 to remind you. Currently this setting is not recommended because
2940 the likelihood that you will open your Org files in an Emacs that
2941 has limited date range is not negligible.
2943 A workaround for this problem is to use diary sexp dates for time
2944 stamps outside of this range."
2945 :group 'org-time
2946 :version "24.1"
2947 :type 'boolean)
2949 (defcustom org-read-date-display-live t
2950 "Non-nil means display current interpretation of date prompt live.
2951 This display will be in an overlay, in the minibuffer."
2952 :group 'org-time
2953 :type 'boolean)
2955 (defcustom org-read-date-popup-calendar t
2956 "Non-nil means pop up a calendar when prompting for a date.
2957 In the calendar, the date can be selected with mouse-1. However, the
2958 minibuffer will also be active, and you can simply enter the date as well.
2959 When nil, only the minibuffer will be available."
2960 :group 'org-time
2961 :type 'boolean)
2962 (if (fboundp 'defvaralias)
2963 (defvaralias 'org-popup-calendar-for-date-prompt
2964 'org-read-date-popup-calendar))
2966 (defcustom org-read-date-minibuffer-setup-hook nil
2967 "Hook to be used to set up keys for the date/time interface.
2968 Add key definitions to `minibuffer-local-map', which will be a temporary
2969 copy."
2970 :group 'org-time
2971 :type 'hook)
2973 (defcustom org-extend-today-until 0
2974 "The hour when your day really ends. Must be an integer.
2975 This has influence for the following applications:
2976 - When switching the agenda to \"today\". It it is still earlier than
2977 the time given here, the day recognized as TODAY is actually yesterday.
2978 - When a date is read from the user and it is still before the time given
2979 here, the current date and time will be assumed to be yesterday, 23:59.
2980 Also, timestamps inserted in capture templates follow this rule.
2982 IMPORTANT: This is a feature whose implementation is and likely will
2983 remain incomplete. Really, it is only here because past midnight seems to
2984 be the favorite working time of John Wiegley :-)"
2985 :group 'org-time
2986 :type 'integer)
2988 (defcustom org-use-effective-time nil
2989 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2990 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2991 \"effective time\" of any timestamps between midnight and 8am will be
2992 23:59 of the previous day."
2993 :group 'org-time
2994 :version "24.1"
2995 :type 'boolean)
2997 (defcustom org-use-last-clock-out-time-as-effective-time nil
2998 "When non-nil, use the last clock out time for `org-todo'.
2999 Note that this option has precedence over the combined use of
3000 `org-use-effective-time' and `org-extend-today-until'."
3001 :group 'org-time
3002 ;; :version "24.3"
3003 :type 'boolean)
3005 (defcustom org-edit-timestamp-down-means-later nil
3006 "Non-nil means S-down will increase the time in a time stamp.
3007 When nil, S-up will increase."
3008 :group 'org-time
3009 :type 'boolean)
3011 (defcustom org-calendar-follow-timestamp-change t
3012 "Non-nil means make the calendar window follow timestamp changes.
3013 When a timestamp is modified and the calendar window is visible, it will be
3014 moved to the new date."
3015 :group 'org-time
3016 :type 'boolean)
3018 (defgroup org-tags nil
3019 "Options concerning tags in Org-mode."
3020 :tag "Org Tags"
3021 :group 'org)
3023 (defcustom org-tag-alist nil
3024 "List of tags allowed in Org-mode files.
3025 When this list is nil, Org-mode will base TAG input on what is already in the
3026 buffer.
3027 The value of this variable is an alist, the car of each entry must be a
3028 keyword as a string, the cdr may be a character that is used to select
3029 that tag through the fast-tag-selection interface.
3030 See the manual for details."
3031 :group 'org-tags
3032 :type '(repeat
3033 (choice
3034 (cons (string :tag "Tag name")
3035 (character :tag "Access char"))
3036 (list :tag "Start radio group"
3037 (const :startgroup)
3038 (option (string :tag "Group description")))
3039 (list :tag "End radio group"
3040 (const :endgroup)
3041 (option (string :tag "Group description")))
3042 (const :tag "New line" (:newline)))))
3044 (defcustom org-tag-persistent-alist nil
3045 "List of tags that will always appear in all Org-mode files.
3046 This is in addition to any in buffer settings or customizations
3047 of `org-tag-alist'.
3048 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3049 The value of this variable is an alist, the car of each entry must be a
3050 keyword as a string, the cdr may be a character that is used to select
3051 that tag through the fast-tag-selection interface.
3052 See the manual for details.
3053 To disable these tags on a per-file basis, insert anywhere in the file:
3054 #+STARTUP: noptag"
3055 :group 'org-tags
3056 :type '(repeat
3057 (choice
3058 (cons (string :tag "Tag name")
3059 (character :tag "Access char"))
3060 (const :tag "Start radio group" (:startgroup))
3061 (const :tag "End radio group" (:endgroup))
3062 (const :tag "New line" (:newline)))))
3064 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3065 "If non-nil, always offer completion for all tags of all agenda files.
3066 Instead of customizing this variable directly, you might want to
3067 set it locally for capture buffers, because there no list of
3068 tags in that file can be created dynamically (there are none).
3070 (add-hook 'org-capture-mode-hook
3071 (lambda ()
3072 (set (make-local-variable
3073 'org-complete-tags-always-offer-all-agenda-tags)
3074 t)))"
3075 :group 'org-tags
3076 :version "24.1"
3077 :type 'boolean)
3079 (defvar org-file-tags nil
3080 "List of tags that can be inherited by all entries in the file.
3081 The tags will be inherited if the variable `org-use-tag-inheritance'
3082 says they should be.
3083 This variable is populated from #+FILETAGS lines.")
3085 (defcustom org-use-fast-tag-selection 'auto
3086 "Non-nil means use fast tag selection scheme.
3087 This is a special interface to select and deselect tags with single keys.
3088 When nil, fast selection is never used.
3089 When the symbol `auto', fast selection is used if and only if selection
3090 characters for tags have been configured, either through the variable
3091 `org-tag-alist' or through a #+TAGS line in the buffer.
3092 When t, fast selection is always used and selection keys are assigned
3093 automatically if necessary."
3094 :group 'org-tags
3095 :type '(choice
3096 (const :tag "Always" t)
3097 (const :tag "Never" nil)
3098 (const :tag "When selection characters are configured" 'auto)))
3100 (defcustom org-fast-tag-selection-single-key nil
3101 "Non-nil means fast tag selection exits after first change.
3102 When nil, you have to press RET to exit it.
3103 During fast tag selection, you can toggle this flag with `C-c'.
3104 This variable can also have the value `expert'. In this case, the window
3105 displaying the tags menu is not even shown, until you press C-c again."
3106 :group 'org-tags
3107 :type '(choice
3108 (const :tag "No" nil)
3109 (const :tag "Yes" t)
3110 (const :tag "Expert" expert)))
3112 (defvar org-fast-tag-selection-include-todo nil
3113 "Non-nil means fast tags selection interface will also offer TODO states.
3114 This is an undocumented feature, you should not rely on it.")
3116 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3117 "The column to which tags should be indented in a headline.
3118 If this number is positive, it specifies the column. If it is negative,
3119 it means that the tags should be flushright to that column. For example,
3120 -80 works well for a normal 80 character screen.
3121 When 0, place tags directly after headline text, with only one space in
3122 between."
3123 :group 'org-tags
3124 :type 'integer)
3126 (defcustom org-auto-align-tags t
3127 "Non-nil keeps tags aligned when modifying headlines.
3128 Some operations (i.e. demoting) change the length of a headline and
3129 therefore shift the tags around. With this option turned on, after
3130 each such operation the tags are again aligned to `org-tags-column'."
3131 :group 'org-tags
3132 :type 'boolean)
3134 (defcustom org-use-tag-inheritance t
3135 "Non-nil means tags in levels apply also for sublevels.
3136 When nil, only the tags directly given in a specific line apply there.
3137 This may also be a list of tags that should be inherited, or a regexp that
3138 matches tags that should be inherited. Additional control is possible
3139 with the variable `org-tags-exclude-from-inheritance' which gives an
3140 explicit list of tags to be excluded from inheritance, even if the value of
3141 `org-use-tag-inheritance' would select it for inheritance.
3143 If this option is t, a match early-on in a tree can lead to a large
3144 number of matches in the subtree when constructing the agenda or creating
3145 a sparse tree. If you only want to see the first match in a tree during
3146 a search, check out the variable `org-tags-match-list-sublevels'."
3147 :group 'org-tags
3148 :type '(choice
3149 (const :tag "Not" nil)
3150 (const :tag "Always" t)
3151 (repeat :tag "Specific tags" (string :tag "Tag"))
3152 (regexp :tag "Tags matched by regexp")))
3154 (defcustom org-tags-exclude-from-inheritance nil
3155 "List of tags that should never be inherited.
3156 This is a way to exclude a few tags from inheritance. For way to do
3157 the opposite, to actively allow inheritance for selected tags,
3158 see the variable `org-use-tag-inheritance'."
3159 :group 'org-tags
3160 :type '(repeat (string :tag "Tag")))
3162 (defun org-tag-inherit-p (tag)
3163 "Check if TAG is one that should be inherited."
3164 (cond
3165 ((member tag org-tags-exclude-from-inheritance) nil)
3166 ((eq org-use-tag-inheritance t) t)
3167 ((not org-use-tag-inheritance) nil)
3168 ((stringp org-use-tag-inheritance)
3169 (string-match org-use-tag-inheritance tag))
3170 ((listp org-use-tag-inheritance)
3171 (member tag org-use-tag-inheritance))
3172 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3174 (defcustom org-tags-match-list-sublevels t
3175 "Non-nil means list also sublevels of headlines matching a search.
3176 This variable applies to tags/property searches, and also to stuck
3177 projects because this search is based on a tags match as well.
3179 When set to the symbol `indented', sublevels are indented with
3180 leading dots.
3182 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3183 the sublevels of a headline matching a tag search often also match
3184 the same search. Listing all of them can create very long lists.
3185 Setting this variable to nil causes subtrees of a match to be skipped.
3187 This variable is semi-obsolete and probably should always be true. It
3188 is better to limit inheritance to certain tags using the variables
3189 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3190 :group 'org-tags
3191 :type '(choice
3192 (const :tag "No, don't list them" nil)
3193 (const :tag "Yes, do list them" t)
3194 (const :tag "List them, indented with leading dots" indented)))
3196 (defcustom org-tags-sort-function nil
3197 "When set, tags are sorted using this function as a comparator."
3198 :group 'org-tags
3199 :type '(choice
3200 (const :tag "No sorting" nil)
3201 (const :tag "Alphabetical" string<)
3202 (const :tag "Reverse alphabetical" string>)
3203 (function :tag "Custom function" nil)))
3205 (defvar org-tags-history nil
3206 "History of minibuffer reads for tags.")
3207 (defvar org-last-tags-completion-table nil
3208 "The last used completion table for tags.")
3209 (defvar org-after-tags-change-hook nil
3210 "Hook that is run after the tags in a line have changed.")
3212 (defgroup org-properties nil
3213 "Options concerning properties in Org-mode."
3214 :tag "Org Properties"
3215 :group 'org)
3217 (defcustom org-property-format "%-10s %s"
3218 "How property key/value pairs should be formatted by `indent-line'.
3219 When `indent-line' hits a property definition, it will format the line
3220 according to this format, mainly to make sure that the values are
3221 lined-up with respect to each other."
3222 :group 'org-properties
3223 :type 'string)
3225 (defcustom org-properties-postprocess-alist nil
3226 "Alist of properties and functions to adjust inserted values.
3227 Elements of this alist must be of the form
3229 ([string] [function])
3231 where [string] must be a property name and [function] must be a
3232 lambda expression: this lambda expression must take one argument,
3233 the value to adjust, and return the new value as a string.
3235 For example, this element will allow the property \"Remaining\"
3236 to be updated wrt the relation between the \"Effort\" property
3237 and the clock summary:
3239 ((\"Remaining\" (lambda(value)
3240 (let ((clocksum (org-clock-sum-current-item))
3241 (effort (org-duration-string-to-minutes
3242 (org-entry-get (point) \"Effort\"))))
3243 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3244 :group 'org-properties
3245 :version "24.1"
3246 :type '(alist :key-type (string :tag "Property")
3247 :value-type (function :tag "Function")))
3249 (defcustom org-use-property-inheritance nil
3250 "Non-nil means properties apply also for sublevels.
3252 This setting is chiefly used during property searches. Turning it on can
3253 cause significant overhead when doing a search, which is why it is not
3254 on by default.
3256 When nil, only the properties directly given in the current entry count.
3257 When t, every property is inherited. The value may also be a list of
3258 properties that should have inheritance, or a regular expression matching
3259 properties that should be inherited.
3261 However, note that some special properties use inheritance under special
3262 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3263 and the properties ending in \"_ALL\" when they are used as descriptor
3264 for valid values of a property.
3266 Note for programmers:
3267 When querying an entry with `org-entry-get', you can control if inheritance
3268 should be used. By default, `org-entry-get' looks only at the local
3269 properties. You can request inheritance by setting the inherit argument
3270 to t (to force inheritance) or to `selective' (to respect the setting
3271 in this variable)."
3272 :group 'org-properties
3273 :type '(choice
3274 (const :tag "Not" nil)
3275 (const :tag "Always" t)
3276 (repeat :tag "Specific properties" (string :tag "Property"))
3277 (regexp :tag "Properties matched by regexp")))
3279 (defun org-property-inherit-p (property)
3280 "Check if PROPERTY is one that should be inherited."
3281 (cond
3282 ((eq org-use-property-inheritance t) t)
3283 ((not org-use-property-inheritance) nil)
3284 ((stringp org-use-property-inheritance)
3285 (string-match org-use-property-inheritance property))
3286 ((listp org-use-property-inheritance)
3287 (member property org-use-property-inheritance))
3288 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3290 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3291 "The default column format, if no other format has been defined.
3292 This variable can be set on the per-file basis by inserting a line
3294 #+COLUMNS: %25ITEM ....."
3295 :group 'org-properties
3296 :type 'string)
3298 (defcustom org-columns-ellipses ".."
3299 "The ellipses to be used when a field in column view is truncated.
3300 When this is the empty string, as many characters as possible are shown,
3301 but then there will be no visual indication that the field has been truncated.
3302 When this is a string of length N, the last N characters of a truncated
3303 field are replaced by this string. If the column is narrower than the
3304 ellipses string, only part of the ellipses string will be shown."
3305 :group 'org-properties
3306 :type 'string)
3308 (defcustom org-columns-modify-value-for-display-function nil
3309 "Function that modifies values for display in column view.
3310 For example, it can be used to cut out a certain part from a time stamp.
3311 The function must take 2 arguments:
3313 column-title The title of the column (*not* the property name)
3314 value The value that should be modified.
3316 The function should return the value that should be displayed,
3317 or nil if the normal value should be used."
3318 :group 'org-properties
3319 :type 'function)
3321 (defcustom org-effort-property "Effort"
3322 "The property that is being used to keep track of effort estimates.
3323 Effort estimates given in this property need to have the format H:MM."
3324 :group 'org-properties
3325 :group 'org-progress
3326 :type '(string :tag "Property"))
3328 (defconst org-global-properties-fixed
3329 '(("VISIBILITY_ALL" . "folded children content all")
3330 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3331 "List of property/value pairs that can be inherited by any entry.
3333 These are fixed values, for the preset properties. The user variable
3334 that can be used to add to this list is `org-global-properties'.
3336 The entries in this list are cons cells where the car is a property
3337 name and cdr is a string with the value. If the value represents
3338 multiple items like an \"_ALL\" property, separate the items by
3339 spaces.")
3341 (defcustom org-global-properties nil
3342 "List of property/value pairs that can be inherited by any entry.
3344 This list will be combined with the constant `org-global-properties-fixed'.
3346 The entries in this list are cons cells where the car is a property
3347 name and cdr is a string with the value.
3349 You can set buffer-local values for the same purpose in the variable
3350 `org-file-properties' this by adding lines like
3352 #+PROPERTY: NAME VALUE"
3353 :group 'org-properties
3354 :type '(repeat
3355 (cons (string :tag "Property")
3356 (string :tag "Value"))))
3358 (defvar org-file-properties nil
3359 "List of property/value pairs that can be inherited by any entry.
3360 Valid for the current buffer.
3361 This variable is populated from #+PROPERTY lines.")
3362 (make-variable-buffer-local 'org-file-properties)
3364 (defgroup org-agenda nil
3365 "Options concerning agenda views in Org-mode."
3366 :tag "Org Agenda"
3367 :group 'org)
3369 (defvar org-category nil
3370 "Variable used by org files to set a category for agenda display.
3371 Such files should use a file variable to set it, for example
3373 # -*- mode: org; org-category: \"ELisp\"
3375 or contain a special line
3377 #+CATEGORY: ELisp
3379 If the file does not specify a category, then file's base name
3380 is used instead.")
3381 (make-variable-buffer-local 'org-category)
3382 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3384 (defcustom org-agenda-files nil
3385 "The files to be used for agenda display.
3386 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3387 \\[org-remove-file]. You can also use customize to edit the list.
3389 If an entry is a directory, all files in that directory that are matched by
3390 `org-agenda-file-regexp' will be part of the file list.
3392 If the value of the variable is not a list but a single file name, then
3393 the list of agenda files is actually stored and maintained in that file, one
3394 agenda file per line. In this file paths can be given relative to
3395 `org-directory'. Tilde expansion and environment variable substitution
3396 are also made."
3397 :group 'org-agenda
3398 :type '(choice
3399 (repeat :tag "List of files and directories" file)
3400 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3402 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3403 "Regular expression to match files for `org-agenda-files'.
3404 If any element in the list in that variable contains a directory instead
3405 of a normal file, all files in that directory that are matched by this
3406 regular expression will be included."
3407 :group 'org-agenda
3408 :type 'regexp)
3410 (defcustom org-agenda-text-search-extra-files nil
3411 "List of extra files to be searched by text search commands.
3412 These files will be search in addition to the agenda files by the
3413 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3414 Note that these files will only be searched for text search commands,
3415 not for the other agenda views like todo lists, tag searches or the weekly
3416 agenda. This variable is intended to list notes and possibly archive files
3417 that should also be searched by these two commands.
3418 In fact, if the first element in the list is the symbol `agenda-archives',
3419 than all archive files of all agenda files will be added to the search
3420 scope."
3421 :group 'org-agenda
3422 :type '(set :greedy t
3423 (const :tag "Agenda Archives" agenda-archives)
3424 (repeat :inline t (file))))
3426 (if (fboundp 'defvaralias)
3427 (defvaralias 'org-agenda-multi-occur-extra-files
3428 'org-agenda-text-search-extra-files))
3430 (defcustom org-agenda-skip-unavailable-files nil
3431 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3432 A nil value means to remove them, after a query, from the list."
3433 :group 'org-agenda
3434 :type 'boolean)
3436 (defcustom org-calendar-to-agenda-key [?c]
3437 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3438 The command `org-calendar-goto-agenda' will be bound to this key. The
3439 default is the character `c' because then `c' can be used to switch back and
3440 forth between agenda and calendar."
3441 :group 'org-agenda
3442 :type 'sexp)
3444 (defcustom org-calendar-insert-diary-entry-key [?i]
3445 "The key to be installed in `calendar-mode-map' for adding diary entries.
3446 This option is irrelevant until `org-agenda-diary-file' has been configured
3447 to point to an Org-mode file. When that is the case, the command
3448 `org-agenda-diary-entry' will be bound to the key given here, by default
3449 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3450 if you want to continue doing this, you need to change this to a different
3451 key."
3452 :group 'org-agenda
3453 :type 'sexp)
3455 (defcustom org-agenda-diary-file 'diary-file
3456 "File to which to add new entries with the `i' key in agenda and calendar.
3457 When this is the symbol `diary-file', the functionality in the Emacs
3458 calendar will be used to add entries to the `diary-file'. But when this
3459 points to a file, `org-agenda-diary-entry' will be used instead."
3460 :group 'org-agenda
3461 :type '(choice
3462 (const :tag "The standard Emacs diary file" diary-file)
3463 (file :tag "Special Org file diary entries")))
3465 (eval-after-load "calendar"
3466 '(progn
3467 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3468 'org-calendar-goto-agenda)
3469 (add-hook 'calendar-mode-hook
3470 (lambda ()
3471 (unless (eq org-agenda-diary-file 'diary-file)
3472 (define-key calendar-mode-map
3473 org-calendar-insert-diary-entry-key
3474 'org-agenda-diary-entry))))))
3476 (defgroup org-latex nil
3477 "Options for embedding LaTeX code into Org-mode."
3478 :tag "Org LaTeX"
3479 :group 'org)
3481 (defcustom org-format-latex-options
3482 '(:foreground default :background default :scale 1.0
3483 :html-foreground "Black" :html-background "Transparent"
3484 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3485 "Options for creating images from LaTeX fragments.
3486 This is a property list with the following properties:
3487 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3488 `default' means use the foreground of the default face.
3489 `auto' means use the foreground from the text face.
3490 :background the background color, or \"Transparent\".
3491 `default' means use the background of the default face.
3492 `auto' means use the background from the text face.
3493 :scale a scaling factor for the size of the images, to get more pixels
3494 :html-foreground, :html-background, :html-scale
3495 the same numbers for HTML export.
3496 :matchers a list indicating which matchers should be used to
3497 find LaTeX fragments. Valid members of this list are:
3498 \"begin\" find environments
3499 \"$1\" find single characters surrounded by $.$
3500 \"$\" find math expressions surrounded by $...$
3501 \"$$\" find math expressions surrounded by $$....$$
3502 \"\\(\" find math expressions surrounded by \\(...\\)
3503 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3504 :group 'org-latex
3505 :type 'plist)
3507 (defcustom org-format-latex-signal-error t
3508 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3509 When nil, just push out a message."
3510 :group 'org-latex
3511 :version "24.1"
3512 :type 'boolean)
3514 (defcustom org-latex-to-mathml-jar-file nil
3515 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3516 Use this to specify additional executable file say a jar file.
3518 When using MathToWeb as the converter, specify the full-path to
3519 your mathtoweb.jar file."
3520 :group 'org-latex
3521 :version "24.1"
3522 :type '(choice
3523 (const :tag "None" nil)
3524 (file :tag "JAR file" :must-match t)))
3526 (defcustom org-latex-to-mathml-convert-command nil
3527 "Command to convert LaTeX fragments to MathML.
3528 Replace format-specifiers in the command as noted below and use
3529 `shell-command' to convert LaTeX to MathML.
3530 %j: Executable file in fully expanded form as specified by
3531 `org-latex-to-mathml-jar-file'.
3532 %I: Input LaTeX file in fully expanded form
3533 %o: Output MathML file
3534 This command is used by `org-create-math-formula'.
3536 When using MathToWeb as the converter, set this to
3537 \"java -jar %j -unicode -force -df %o %I\"."
3538 :group 'org-latex
3539 :version "24.1"
3540 :type '(choice
3541 (const :tag "None" nil)
3542 (string :tag "\nShell command")))
3544 (defcustom org-latex-create-formula-image-program 'dvipng
3545 "Program to convert LaTeX fragments with.
3547 dvipng Process the LaTeX fragments to dvi file, then convert
3548 dvi files to png files using dvipng.
3549 This will also include processing of non-math environments.
3550 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3551 to convert pdf files to png files"
3552 :group 'org-latex
3553 :version "24.1"
3554 :type '(choice
3555 (const :tag "dvipng" dvipng)
3556 (const :tag "imagemagick" imagemagick)))
3558 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3559 "Path to store latex preview images.
3560 A relative path here creates many directories relative to the
3561 processed org files paths. An absolute path puts all preview
3562 images at the same place."
3563 :group 'org-latex
3564 :version "24.3"
3565 :type 'string)
3567 (defun org-format-latex-mathml-available-p ()
3568 "Return t if `org-latex-to-mathml-convert-command' is usable."
3569 (save-match-data
3570 (when (and (boundp 'org-latex-to-mathml-convert-command)
3571 org-latex-to-mathml-convert-command)
3572 (let ((executable (car (split-string
3573 org-latex-to-mathml-convert-command))))
3574 (when (executable-find executable)
3575 (if (string-match
3576 "%j" org-latex-to-mathml-convert-command)
3577 (file-readable-p org-latex-to-mathml-jar-file)
3578 t))))))
3580 (defcustom org-format-latex-header "\\documentclass{article}
3581 \\usepackage[usenames]{color}
3582 \\usepackage{amsmath}
3583 \\usepackage[mathscr]{eucal}
3584 \\pagestyle{empty} % do not remove
3585 \[PACKAGES]
3586 \[DEFAULT-PACKAGES]
3587 % The settings below are copied from fullpage.sty
3588 \\setlength{\\textwidth}{\\paperwidth}
3589 \\addtolength{\\textwidth}{-3cm}
3590 \\setlength{\\oddsidemargin}{1.5cm}
3591 \\addtolength{\\oddsidemargin}{-2.54cm}
3592 \\setlength{\\evensidemargin}{\\oddsidemargin}
3593 \\setlength{\\textheight}{\\paperheight}
3594 \\addtolength{\\textheight}{-\\headheight}
3595 \\addtolength{\\textheight}{-\\headsep}
3596 \\addtolength{\\textheight}{-\\footskip}
3597 \\addtolength{\\textheight}{-3cm}
3598 \\setlength{\\topmargin}{1.5cm}
3599 \\addtolength{\\topmargin}{-2.54cm}"
3600 "The document header used for processing LaTeX fragments.
3601 It is imperative that this header make sure that no page number
3602 appears on the page. The package defined in the variables
3603 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3604 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3605 will be appended."
3606 :group 'org-latex
3607 :type 'string)
3609 (defvar org-format-latex-header-extra nil)
3611 (defun org-set-packages-alist (var val)
3612 "Set the packages alist and make sure it has 3 elements per entry."
3613 (set var (mapcar (lambda (x)
3614 (if (and (consp x) (= (length x) 2))
3615 (list (car x) (nth 1 x) t)
3617 val)))
3619 (defun org-get-packages-alist (var)
3621 "Get the packages alist and make sure it has 3 elements per entry."
3622 (mapcar (lambda (x)
3623 (if (and (consp x) (= (length x) 2))
3624 (list (car x) (nth 1 x) t)
3626 (default-value var)))
3628 ;; The following variables are defined here because is it also used
3629 ;; when formatting latex fragments. Originally it was part of the
3630 ;; LaTeX exporter, which is why the name includes "export".
3631 (defcustom org-export-latex-default-packages-alist
3632 '(("AUTO" "inputenc" t)
3633 ("T1" "fontenc" t)
3634 ("" "fixltx2e" nil)
3635 ("" "graphicx" t)
3636 ("" "longtable" nil)
3637 ("" "float" nil)
3638 ("" "wrapfig" nil)
3639 ("" "soul" t)
3640 ("" "textcomp" t)
3641 ("" "marvosym" t)
3642 ("" "wasysym" t)
3643 ("" "latexsym" t)
3644 ("" "amssymb" t)
3645 ("" "hyperref" nil)
3646 "\\tolerance=1000"
3648 "Alist of default packages to be inserted in the header.
3649 Change this only if one of the packages here causes an incompatibility
3650 with another package you are using.
3651 The packages in this list are needed by one part or another of Org-mode
3652 to function properly.
3654 - inputenc, fontenc: for basic font and character selection
3655 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3656 for interpreting the entities in `org-entities'. You can skip some of these
3657 packages if you don't use any of the symbols in it.
3658 - graphicx: for including images
3659 - float, wrapfig: for figure placement
3660 - longtable: for long tables
3661 - hyperref: for cross references
3663 Therefore you should not modify this variable unless you know what you
3664 are doing. The one reason to change it anyway is that you might be loading
3665 some other package that conflicts with one of the default packages.
3666 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3667 If SNIPPET-FLAG is t, the package also needs to be included when
3668 compiling LaTeX snippets into images for inclusion into HTML."
3669 :group 'org-export-latex
3670 :set 'org-set-packages-alist
3671 :get 'org-get-packages-alist
3672 :version "24.1"
3673 :type '(repeat
3674 (choice
3675 (list :tag "options/package pair"
3676 (string :tag "options")
3677 (string :tag "package")
3678 (boolean :tag "Snippet"))
3679 (string :tag "A line of LaTeX"))))
3681 (defcustom org-export-latex-packages-alist nil
3682 "Alist of packages to be inserted in every LaTeX header.
3683 These will be inserted after `org-export-latex-default-packages-alist'.
3684 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3685 SNIPPET-FLAG, when t, indicates that this package is also needed when
3686 turning LaTeX snippets into images for inclusion into HTML.
3687 Make sure that you only list packages here which:
3688 - you want in every file
3689 - do not conflict with the default packages in
3690 `org-export-latex-default-packages-alist'
3691 - do not conflict with the setup in `org-format-latex-header'."
3692 :group 'org-export-latex
3693 :set 'org-set-packages-alist
3694 :get 'org-get-packages-alist
3695 :type '(repeat
3696 (choice
3697 (list :tag "options/package pair"
3698 (string :tag "options")
3699 (string :tag "package")
3700 (boolean :tag "Snippet"))
3701 (string :tag "A line of LaTeX"))))
3704 (defgroup org-appearance nil
3705 "Settings for Org-mode appearance."
3706 :tag "Org Appearance"
3707 :group 'org)
3709 (defcustom org-level-color-stars-only nil
3710 "Non-nil means fontify only the stars in each headline.
3711 When nil, the entire headline is fontified.
3712 Changing it requires restart of `font-lock-mode' to become effective
3713 also in regions already fontified."
3714 :group 'org-appearance
3715 :type 'boolean)
3717 (defcustom org-hide-leading-stars nil
3718 "Non-nil means hide the first N-1 stars in a headline.
3719 This works by using the face `org-hide' for these stars. This
3720 face is white for a light background, and black for a dark
3721 background. You may have to customize the face `org-hide' to
3722 make this work.
3723 Changing it requires restart of `font-lock-mode' to become effective
3724 also in regions already fontified.
3725 You may also set this on a per-file basis by adding one of the following
3726 lines to the buffer:
3728 #+STARTUP: hidestars
3729 #+STARTUP: showstars"
3730 :group 'org-appearance
3731 :type 'boolean)
3733 (defcustom org-hidden-keywords nil
3734 "List of symbols corresponding to keywords to be hidden the org buffer.
3735 For example, a value '(title) for this list will make the document's title
3736 appear in the buffer without the initial #+TITLE: keyword."
3737 :group 'org-appearance
3738 :version "24.1"
3739 :type '(set (const :tag "#+AUTHOR" author)
3740 (const :tag "#+DATE" date)
3741 (const :tag "#+EMAIL" email)
3742 (const :tag "#+TITLE" title)))
3744 (defcustom org-custom-properties nil
3745 "List of properties (as strings) with a special meaning.
3746 The default use of these custom properties is to let the user
3747 hide them with `org-toggle-custom-properties-visibility'."
3748 :group 'org-properties
3749 :group 'org-appearance
3750 :version "24.3"
3751 :type '(repeat (string :tag "Property Name")))
3753 (defcustom org-fontify-done-headline nil
3754 "Non-nil means change the face of a headline if it is marked DONE.
3755 Normally, only the TODO/DONE keyword indicates the state of a headline.
3756 When this is non-nil, the headline after the keyword is set to the
3757 `org-headline-done' as an additional indication."
3758 :group 'org-appearance
3759 :type 'boolean)
3761 (defcustom org-fontify-emphasized-text t
3762 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3763 Changing this variable requires a restart of Emacs to take effect."
3764 :group 'org-appearance
3765 :type 'boolean)
3767 (defcustom org-fontify-whole-heading-line nil
3768 "Non-nil means fontify the whole line for headings.
3769 This is useful when setting a background color for the
3770 org-level-* faces."
3771 :group 'org-appearance
3772 :type 'boolean)
3774 (defcustom org-highlight-latex-fragments-and-specials nil
3775 "Non-nil means fontify what is treated specially by the exporters."
3776 :group 'org-appearance
3777 :type 'boolean)
3779 (defcustom org-hide-emphasis-markers nil
3780 "Non-nil mean font-lock should hide the emphasis marker characters."
3781 :group 'org-appearance
3782 :type 'boolean)
3784 (defcustom org-pretty-entities nil
3785 "Non-nil means show entities as UTF8 characters.
3786 When nil, the \\name form remains in the buffer."
3787 :group 'org-appearance
3788 :version "24.1"
3789 :type 'boolean)
3791 (defcustom org-pretty-entities-include-sub-superscripts t
3792 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3793 :group 'org-appearance
3794 :version "24.1"
3795 :type 'boolean)
3797 (defvar org-emph-re nil
3798 "Regular expression for matching emphasis.
3799 After a match, the match groups contain these elements:
3800 0 The match of the full regular expression, including the characters
3801 before and after the proper match
3802 1 The character before the proper match, or empty at beginning of line
3803 2 The proper match, including the leading and trailing markers
3804 3 The leading marker like * or /, indicating the type of highlighting
3805 4 The text between the emphasis markers, not including the markers
3806 5 The character after the match, empty at the end of a line")
3807 (defvar org-verbatim-re nil
3808 "Regular expression for matching verbatim text.")
3809 (defvar org-emphasis-regexp-components) ; defined just below
3810 (defvar org-emphasis-alist) ; defined just below
3811 (defun org-set-emph-re (var val)
3812 "Set variable and compute the emphasis regular expression."
3813 (set var val)
3814 (when (and (boundp 'org-emphasis-alist)
3815 (boundp 'org-emphasis-regexp-components)
3816 org-emphasis-alist org-emphasis-regexp-components)
3817 (let* ((e org-emphasis-regexp-components)
3818 (pre (car e))
3819 (post (nth 1 e))
3820 (border (nth 2 e))
3821 (body (nth 3 e))
3822 (nl (nth 4 e))
3823 (body1 (concat body "*?"))
3824 (markers (mapconcat 'car org-emphasis-alist ""))
3825 (vmarkers (mapconcat
3826 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3827 org-emphasis-alist "")))
3828 ;; make sure special characters appear at the right position in the class
3829 (if (string-match "\\^" markers)
3830 (setq markers (concat (replace-match "" t t markers) "^")))
3831 (if (string-match "-" markers)
3832 (setq markers (concat (replace-match "" t t markers) "-")))
3833 (if (string-match "\\^" vmarkers)
3834 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3835 (if (string-match "-" vmarkers)
3836 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3837 (if (> nl 0)
3838 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3839 (int-to-string nl) "\\}")))
3840 ;; Make the regexp
3841 (setq org-emph-re
3842 (concat "\\([" pre "]\\|^\\)"
3843 "\\("
3844 "\\([" markers "]\\)"
3845 "\\("
3846 "[^" border "]\\|"
3847 "[^" border "]"
3848 body1
3849 "[^" border "]"
3850 "\\)"
3851 "\\3\\)"
3852 "\\([" post "]\\|$\\)"))
3853 (setq org-verbatim-re
3854 (concat "\\([" pre "]\\|^\\)"
3855 "\\("
3856 "\\([" vmarkers "]\\)"
3857 "\\("
3858 "[^" border "]\\|"
3859 "[^" border "]"
3860 body1
3861 "[^" border "]"
3862 "\\)"
3863 "\\3\\)"
3864 "\\([" post "]\\|$\\)")))))
3866 (defcustom org-emphasis-regexp-components
3867 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3868 "Components used to build the regular expression for emphasis.
3869 This is a list with five entries. Terminology: In an emphasis string
3870 like \" *strong word* \", we call the initial space PREMATCH, the final
3871 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3872 and \"trong wor\" is the body. The different components in this variable
3873 specify what is allowed/forbidden in each part:
3875 pre Chars allowed as prematch. Beginning of line will be allowed too.
3876 post Chars allowed as postmatch. End of line will be allowed too.
3877 border The chars *forbidden* as border characters.
3878 body-regexp A regexp like \".\" to match a body character. Don't use
3879 non-shy groups here, and don't allow newline here.
3880 newline The maximum number of newlines allowed in an emphasis exp.
3882 Use customize to modify this, or restart Emacs after changing it."
3883 :group 'org-appearance
3884 :set 'org-set-emph-re
3885 :type '(list
3886 (sexp :tag "Allowed chars in pre ")
3887 (sexp :tag "Allowed chars in post ")
3888 (sexp :tag "Forbidden chars in border ")
3889 (sexp :tag "Regexp for body ")
3890 (integer :tag "number of newlines allowed")
3891 (option (boolean :tag "Please ignore this button"))))
3893 (defcustom org-emphasis-alist
3894 `(("*" bold "<b>" "</b>")
3895 ("/" italic "<i>" "</i>")
3896 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3897 ("=" org-code "<code>" "</code>" verbatim)
3898 ("~" org-verbatim "<code>" "</code>" verbatim)
3899 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3900 "<del>" "</del>")
3902 "Special syntax for emphasized text.
3903 Text starting and ending with a special character will be emphasized, for
3904 example *bold*, _underlined_ and /italic/. This variable sets the marker
3905 characters, the face to be used by font-lock for highlighting in Org-mode
3906 Emacs buffers, and the HTML tags to be used for this.
3907 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3908 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3909 Use customize to modify this, or restart Emacs after changing it."
3910 :group 'org-appearance
3911 :set 'org-set-emph-re
3912 :type '(repeat
3913 (list
3914 (string :tag "Marker character")
3915 (choice
3916 (face :tag "Font-lock-face")
3917 (plist :tag "Face property list"))
3918 (string :tag "HTML start tag")
3919 (string :tag "HTML end tag")
3920 (option (const verbatim)))))
3922 (defvar org-syntax-table
3923 (let ((st (make-syntax-table)))
3924 (mapc (lambda(c) (modify-syntax-entry
3925 (string-to-char (car c)) "w p" st))
3926 org-emphasis-alist)
3927 st))
3929 (defvar org-protecting-blocks
3930 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3931 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3932 This is needed for font-lock setup.")
3934 ;;; Miscellaneous options
3936 (defgroup org-completion nil
3937 "Completion in Org-mode."
3938 :tag "Org Completion"
3939 :group 'org)
3941 (defcustom org-completion-use-ido nil
3942 "Non-nil means use ido completion wherever possible.
3943 Note that `ido-mode' must be active for this variable to be relevant.
3944 If you decide to turn this variable on, you might well want to turn off
3945 `org-outline-path-complete-in-steps'.
3946 See also `org-completion-use-iswitchb'."
3947 :group 'org-completion
3948 :type 'boolean)
3950 (defcustom org-completion-use-iswitchb nil
3951 "Non-nil means use iswitchb completion wherever possible.
3952 Note that `iswitchb-mode' must be active for this variable to be relevant.
3953 If you decide to turn this variable on, you might well want to turn off
3954 `org-outline-path-complete-in-steps'.
3955 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3956 :group 'org-completion
3957 :type 'boolean)
3959 (defcustom org-completion-fallback-command 'hippie-expand
3960 "The expansion command called by \\[pcomplete] in normal context.
3961 Normal means, no org-mode-specific context."
3962 :group 'org-completion
3963 :type 'function)
3965 ;;; Functions and variables from their packages
3966 ;; Declared here to avoid compiler warnings
3968 ;; XEmacs only
3969 (defvar outline-mode-menu-heading)
3970 (defvar outline-mode-menu-show)
3971 (defvar outline-mode-menu-hide)
3972 (defvar zmacs-regions) ; XEmacs regions
3974 ;; Emacs only
3975 (defvar mark-active)
3977 ;; Various packages
3978 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3979 (declare-function calendar-forward-day "cal-move" (arg))
3980 (declare-function calendar-goto-date "cal-move" (date))
3981 (declare-function calendar-goto-today "cal-move" ())
3982 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3983 (defvar calc-embedded-close-formula)
3984 (defvar calc-embedded-open-formula)
3985 (declare-function cdlatex-tab "ext:cdlatex" ())
3986 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3987 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3988 (defvar font-lock-unfontify-region-function)
3989 (declare-function iswitchb-read-buffer "iswitchb"
3990 (prompt &optional default require-match start matches-set))
3991 (defvar iswitchb-temp-buflist)
3992 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3993 (defvar org-agenda-tags-todo-honor-ignore-options)
3994 (declare-function org-agenda-skip "org-agenda" ())
3995 (declare-function
3996 org-agenda-format-item "org-agenda"
3997 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3998 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3999 (declare-function org-agenda-change-all-lines "org-agenda"
4000 (newhead hdmarker &optional fixface just-this))
4001 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4002 (declare-function org-agenda-maybe-redo "org-agenda" ())
4003 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4004 (beg end))
4005 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4006 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4007 "org-agenda" (&optional end))
4008 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4009 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4010 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4011 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4012 (declare-function org-indent-mode "org-indent" (&optional arg))
4013 (declare-function parse-time-string "parse-time" (string))
4014 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4015 (declare-function org-export-latex-fix-inputenc "org-latex" ())
4016 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4017 (defvar remember-data-file)
4018 (defvar texmathp-why)
4019 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4020 (declare-function table--at-cell-p "table" (position &optional object at-column))
4022 (defvar org-latex-regexps)
4024 ;;; Autoload and prepare some org modules
4026 ;; Some table stuff that needs to be defined here, because it is used
4027 ;; by the functions setting up org-mode or checking for table context.
4029 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4030 "Detect an org-type or table-type table.")
4031 (defconst org-table-line-regexp "^[ \t]*|"
4032 "Detect an org-type table line.")
4033 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4034 "Detect an org-type table line.")
4035 (defconst org-table-hline-regexp "^[ \t]*|-"
4036 "Detect an org-type table hline.")
4037 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4038 "Detect a table-type table hline.")
4039 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4040 "Detect the first line outside a table when searching from within it.
4041 This works for both table types.")
4043 ;; Autoload the functions in org-table.el that are needed by functions here.
4045 (eval-and-compile
4046 (org-autoload "org-table"
4047 '(org-table-begin org-table-blank-field org-table-end)))
4049 ;;;###autoload
4050 (defun turn-on-orgtbl ()
4051 "Unconditionally turn on `orgtbl-mode'."
4052 (require 'org-table)
4053 (orgtbl-mode 1))
4055 (defun org-at-table-p (&optional table-type)
4056 "Return t if the cursor is inside an org-type table.
4057 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4058 (if org-enable-table-editor
4059 (save-excursion
4060 (beginning-of-line 1)
4061 (looking-at (if table-type org-table-any-line-regexp
4062 org-table-line-regexp)))
4063 nil))
4064 (defsubst org-table-p () (org-at-table-p))
4066 (defun org-at-table.el-p ()
4067 "Return t if and only if we are at a table.el table."
4068 (and (org-at-table-p 'any)
4069 (save-excursion
4070 (goto-char (org-table-begin 'any))
4071 (looking-at org-table1-hline-regexp))))
4072 (defun org-table-recognize-table.el ()
4073 "If there is a table.el table nearby, recognize it and move into it."
4074 (if org-table-tab-recognizes-table.el
4075 (if (org-at-table.el-p)
4076 (progn
4077 (beginning-of-line 1)
4078 (if (looking-at org-table-dataline-regexp)
4080 (if (looking-at org-table1-hline-regexp)
4081 (progn
4082 (beginning-of-line 2)
4083 (if (looking-at org-table-any-border-regexp)
4084 (beginning-of-line -1)))))
4085 (if (re-search-forward "|" (org-table-end t) t)
4086 (progn
4087 (require 'table)
4088 (if (table--at-cell-p (point))
4090 (message "recognizing table.el table...")
4091 (table-recognize-table)
4092 (message "recognizing table.el table...done")))
4093 (error "This should not happen"))
4095 nil)
4096 nil))
4098 (defun org-at-table-hline-p ()
4099 "Return t if the cursor is inside a hline in a table."
4100 (if org-enable-table-editor
4101 (save-excursion
4102 (beginning-of-line 1)
4103 (looking-at org-table-hline-regexp))
4104 nil))
4106 (defvar org-table-clean-did-remove-column nil)
4108 (defun org-table-map-tables (function &optional quietly)
4109 "Apply FUNCTION to the start of all tables in the buffer."
4110 (save-excursion
4111 (save-restriction
4112 (widen)
4113 (goto-char (point-min))
4114 (while (re-search-forward org-table-any-line-regexp nil t)
4115 (unless quietly
4116 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4117 (beginning-of-line 1)
4118 (when (and (looking-at org-table-line-regexp)
4119 ;; Exclude tables in src/example/verbatim/clocktable blocks
4120 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4121 (save-excursion (funcall function))
4122 (or (looking-at org-table-line-regexp)
4123 (forward-char 1)))
4124 (re-search-forward org-table-any-border-regexp nil 1))))
4125 (unless quietly (message "Mapping tables: done")))
4127 ;; Declare and autoload functions from org-exp.el & Co
4129 (declare-function org-default-export-plist "org-exp")
4130 (declare-function org-infile-export-plist "org-exp")
4131 (declare-function org-get-current-options "org-exp")
4133 ;; Declare and autoload functions from org-agenda.el
4135 (eval-and-compile
4136 (org-autoload "org-agenda"
4137 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4139 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4140 (declare-function org-clock-update-mode-line "org-clock" ())
4141 (declare-function org-resolve-clocks "org-clock"
4142 (&optional also-non-dangling-p prompt last-valid))
4143 (defvar org-clock-start-time)
4144 (defvar org-clock-marker (make-marker)
4145 "Marker recording the last clock-in.")
4146 (defvar org-clock-hd-marker (make-marker)
4147 "Marker recording the last clock-in, but the headline position.")
4148 (defvar org-clock-heading ""
4149 "The heading of the current clock entry.")
4150 (defun org-clock-is-active ()
4151 "Return non-nil if clock is currently running.
4152 The return value is actually the clock marker."
4153 (marker-buffer org-clock-marker))
4155 (eval-and-compile
4156 (org-autoload "org-clock" '(org-clock-remove-overlays
4157 org-clock-update-time-maybe
4158 org-clocktable-shift)))
4160 (defun org-check-running-clock ()
4161 "Check if the current buffer contains the running clock.
4162 If yes, offer to stop it and to save the buffer with the changes."
4163 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4164 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4165 (buffer-name))))
4166 (org-clock-out)
4167 (when (y-or-n-p "Save changed buffer?")
4168 (save-buffer))))
4170 (defun org-clocktable-try-shift (dir n)
4171 "Check if this line starts a clock table, if yes, shift the time block."
4172 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4173 (org-clocktable-shift dir n)))
4175 ;;;###autoload
4176 (defun org-clock-persistence-insinuate ()
4177 "Set up hooks for clock persistence."
4178 (require 'org-clock)
4179 (add-hook 'org-mode-hook 'org-clock-load)
4180 (add-hook 'kill-emacs-hook 'org-clock-save))
4182 ;; Define the variable already here, to make sure we have it.
4183 (defvar org-indent-mode nil
4184 "Non-nil if Org-Indent mode is enabled.
4185 Use the command `org-indent-mode' to change this variable.")
4187 ;; Autoload archiving code
4188 ;; The stuff that is needed for cycling and tags has to be defined here.
4190 (defgroup org-archive nil
4191 "Options concerning archiving in Org-mode."
4192 :tag "Org Archive"
4193 :group 'org-structure)
4195 (defcustom org-archive-location "%s_archive::"
4196 "The location where subtrees should be archived.
4198 The value of this variable is a string, consisting of two parts,
4199 separated by a double-colon. The first part is a filename and
4200 the second part is a headline.
4202 When the filename is omitted, archiving happens in the same file.
4203 %s in the filename will be replaced by the current file
4204 name (without the directory part). Archiving to a different file
4205 is useful to keep archived entries from contributing to the
4206 Org-mode Agenda.
4208 The archived entries will be filed as subtrees of the specified
4209 headline. When the headline is omitted, the subtrees are simply
4210 filed away at the end of the file, as top-level entries. Also in
4211 the heading you can use %s to represent the file name, this can be
4212 useful when using the same archive for a number of different files.
4214 Here are a few examples:
4215 \"%s_archive::\"
4216 If the current file is Projects.org, archive in file
4217 Projects.org_archive, as top-level trees. This is the default.
4219 \"::* Archived Tasks\"
4220 Archive in the current file, under the top-level headline
4221 \"* Archived Tasks\".
4223 \"~/org/archive.org::\"
4224 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4226 \"~/org/archive.org::* From %s\"
4227 Archive in file ~/org/archive.org (absolute path), under headlines
4228 \"From FILENAME\" where file name is the current file name.
4230 \"~/org/datetree.org::datetree/* Finished Tasks\"
4231 The \"datetree/\" string is special, signifying to archive
4232 items to the datetree. Items are placed in either the CLOSED
4233 date of the item, or the current date if there is no CLOSED date.
4234 The heading will be a subentry to the current date. There doesn't
4235 need to be a heading, but there always needs to be a slash after
4236 datetree. For example, to store archived items directly in the
4237 datetree, use \"~/org/datetree.org::datetree/\".
4239 \"basement::** Finished Tasks\"
4240 Archive in file ./basement (relative path), as level 3 trees
4241 below the level 2 heading \"** Finished Tasks\".
4243 You may set this option on a per-file basis by adding to the buffer a
4244 line like
4246 #+ARCHIVE: basement::** Finished Tasks
4248 You may also define it locally for a subtree by setting an ARCHIVE property
4249 in the entry. If such a property is found in an entry, or anywhere up
4250 the hierarchy, it will be used."
4251 :group 'org-archive
4252 :type 'string)
4254 (defcustom org-archive-tag "ARCHIVE"
4255 "The tag that marks a subtree as archived.
4256 An archived subtree does not open during visibility cycling, and does
4257 not contribute to the agenda listings.
4258 After changing this, font-lock must be restarted in the relevant buffers to
4259 get the proper fontification."
4260 :group 'org-archive
4261 :group 'org-keywords
4262 :type 'string)
4264 (defcustom org-agenda-skip-archived-trees t
4265 "Non-nil means the agenda will skip any items located in archived trees.
4266 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4267 variable is no longer recommended, you should leave it at the value t.
4268 Instead, use the key `v' to cycle the archives-mode in the agenda."
4269 :group 'org-archive
4270 :group 'org-agenda-skip
4271 :type 'boolean)
4273 (defcustom org-columns-skip-archived-trees t
4274 "Non-nil means ignore archived trees when creating column view."
4275 :group 'org-archive
4276 :group 'org-properties
4277 :type 'boolean)
4279 (defcustom org-cycle-open-archived-trees nil
4280 "Non-nil means `org-cycle' will open archived trees.
4281 An archived tree is a tree marked with the tag ARCHIVE.
4282 When nil, archived trees will stay folded. You can still open them with
4283 normal outline commands like `show-all', but not with the cycling commands."
4284 :group 'org-archive
4285 :group 'org-cycle
4286 :type 'boolean)
4288 (defcustom org-sparse-tree-open-archived-trees nil
4289 "Non-nil means sparse tree construction shows matches in archived trees.
4290 When nil, matches in these trees are highlighted, but the trees are kept in
4291 collapsed state."
4292 :group 'org-archive
4293 :group 'org-sparse-trees
4294 :type 'boolean)
4296 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4297 "The default date type when building a sparse tree.
4298 When this is nil, a date is a scheduled or a deadline timestamp.
4299 Otherwise, these types are allowed:
4301 all: all timestamps
4302 active: only active timestamps (<...>)
4303 inactive: only inactive timestamps (<...)
4304 scheduled: only scheduled timestamps
4305 deadline: only deadline timestamps"
4306 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4307 (const :tag "All timestamps" all)
4308 (const :tag "Only active timestamps" active)
4309 (const :tag "Only inactive timestamps" inactive)
4310 (const :tag "Only scheduled timestamps" scheduled)
4311 (const :tag "Only deadline timestamps" deadline))
4312 :version "24.3"
4313 :group 'org-sparse-trees)
4315 (defun org-cycle-hide-archived-subtrees (state)
4316 "Re-hide all archived subtrees after a visibility state change."
4317 (when (and (not org-cycle-open-archived-trees)
4318 (not (memq state '(overview folded))))
4319 (save-excursion
4320 (let* ((globalp (memq state '(contents all)))
4321 (beg (if globalp (point-min) (point)))
4322 (end (if globalp (point-max) (org-end-of-subtree t))))
4323 (org-hide-archived-subtrees beg end)
4324 (goto-char beg)
4325 (if (looking-at (concat ".*:" org-archive-tag ":"))
4326 (message "%s" (substitute-command-keys
4327 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4329 (defun org-force-cycle-archived ()
4330 "Cycle subtree even if it is archived."
4331 (interactive)
4332 (setq this-command 'org-cycle)
4333 (let ((org-cycle-open-archived-trees t))
4334 (call-interactively 'org-cycle)))
4336 (defun org-hide-archived-subtrees (beg end)
4337 "Re-hide all archived subtrees after a visibility state change."
4338 (save-excursion
4339 (let* ((re (concat ":" org-archive-tag ":")))
4340 (goto-char beg)
4341 (while (re-search-forward re end t)
4342 (when (org-at-heading-p)
4343 (org-flag-subtree t)
4344 (org-end-of-subtree t))))))
4346 (declare-function outline-end-of-heading "outline" ())
4347 (declare-function outline-flag-region "outline" (from to flag))
4348 (defun org-flag-subtree (flag)
4349 (save-excursion
4350 (org-back-to-heading t)
4351 (outline-end-of-heading)
4352 (outline-flag-region (point)
4353 (progn (org-end-of-subtree t) (point))
4354 flag)))
4356 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4358 (eval-and-compile
4359 (org-autoload "org-archive"
4360 '(org-add-archive-files)))
4362 ;; Autoload Column View Code
4364 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4365 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4366 (declare-function org-columns-compute "org-colview" (property))
4368 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4369 '(org-columns-number-to-string
4370 org-columns-get-format-and-top-level
4371 org-columns-compute
4372 org-columns-remove-overlays))
4374 ;; Autoload ID code
4376 (declare-function org-id-store-link "org-id")
4377 (declare-function org-id-locations-load "org-id")
4378 (declare-function org-id-locations-save "org-id")
4379 (defvar org-id-track-globally)
4380 (org-autoload "org-id"
4381 '(org-id-new
4382 org-id-copy
4383 org-id-get-with-outline-path-completion
4384 org-id-get-with-outline-drilling))
4386 ;;; Variables for pre-computed regular expressions, all buffer local
4388 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4389 "Matches first line of a hidden block.")
4390 (make-variable-buffer-local 'org-drawer-regexp)
4391 (defvar org-todo-regexp nil
4392 "Matches any of the TODO state keywords.")
4393 (make-variable-buffer-local 'org-todo-regexp)
4394 (defvar org-not-done-regexp nil
4395 "Matches any of the TODO state keywords except the last one.")
4396 (make-variable-buffer-local 'org-not-done-regexp)
4397 (defvar org-not-done-heading-regexp nil
4398 "Matches a TODO headline that is not done.")
4399 (make-variable-buffer-local 'org-not-done-regexp)
4400 (defvar org-todo-line-regexp nil
4401 "Matches a headline and puts TODO state into group 2 if present.")
4402 (make-variable-buffer-local 'org-todo-line-regexp)
4403 (defvar org-complex-heading-regexp nil
4404 "Matches a headline and puts everything into groups:
4405 group 1: the stars
4406 group 2: The todo keyword, maybe
4407 group 3: Priority cookie
4408 group 4: True headline
4409 group 5: Tags")
4410 (make-variable-buffer-local 'org-complex-heading-regexp)
4411 (defvar org-complex-heading-regexp-format nil
4412 "Printf format to make regexp to match an exact headline.
4413 This regexp will match the headline of any node which has the
4414 exact headline text that is put into the format, but may have any
4415 TODO state, priority and tags.")
4416 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4417 (defvar org-todo-line-tags-regexp nil
4418 "Matches a headline and puts TODO state into group 2 if present.
4419 Also put tags into group 4 if tags are present.")
4420 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4421 (defvar org-ds-keyword-length 12
4422 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4423 (make-variable-buffer-local 'org-ds-keyword-length)
4424 (defvar org-deadline-regexp nil
4425 "Matches the DEADLINE keyword.")
4426 (make-variable-buffer-local 'org-deadline-regexp)
4427 (defvar org-deadline-time-regexp nil
4428 "Matches the DEADLINE keyword together with a time stamp.")
4429 (make-variable-buffer-local 'org-deadline-time-regexp)
4430 (defvar org-deadline-line-regexp nil
4431 "Matches the DEADLINE keyword and the rest of the line.")
4432 (make-variable-buffer-local 'org-deadline-line-regexp)
4433 (defvar org-scheduled-regexp nil
4434 "Matches the SCHEDULED keyword.")
4435 (make-variable-buffer-local 'org-scheduled-regexp)
4436 (defvar org-scheduled-time-regexp nil
4437 "Matches the SCHEDULED keyword together with a time stamp.")
4438 (make-variable-buffer-local 'org-scheduled-time-regexp)
4439 (defvar org-closed-time-regexp nil
4440 "Matches the CLOSED keyword together with a time stamp.")
4441 (make-variable-buffer-local 'org-closed-time-regexp)
4443 (defvar org-keyword-time-regexp nil
4444 "Matches any of the 4 keywords, together with the time stamp.")
4445 (make-variable-buffer-local 'org-keyword-time-regexp)
4446 (defvar org-keyword-time-not-clock-regexp nil
4447 "Matches any of the 3 keywords, together with the time stamp.")
4448 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4449 (defvar org-maybe-keyword-time-regexp nil
4450 "Matches a timestamp, possibly preceded by a keyword.")
4451 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4452 (defvar org-all-time-keywords nil
4453 "List of time keywords.")
4454 (make-variable-buffer-local 'org-all-time-keywords)
4456 (defconst org-plain-time-of-day-regexp
4457 (concat
4458 "\\(\\<[012]?[0-9]"
4459 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4460 "\\(--?"
4461 "\\(\\<[012]?[0-9]"
4462 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4463 "\\)?")
4464 "Regular expression to match a plain time or time range.
4465 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4466 groups carry important information:
4467 0 the full match
4468 1 the first time, range or not
4469 8 the second time, if it is a range.")
4471 (defconst org-plain-time-extension-regexp
4472 (concat
4473 "\\(\\<[012]?[0-9]"
4474 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4475 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4476 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4477 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4478 groups carry important information:
4479 0 the full match
4480 7 hours of duration
4481 9 minutes of duration")
4483 (defconst org-stamp-time-of-day-regexp
4484 (concat
4485 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4486 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4487 "\\(--?"
4488 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4489 "Regular expression to match a timestamp time or time range.
4490 After a match, the following groups carry important information:
4491 0 the full match
4492 1 date plus weekday, for back referencing to make sure both times are on the same day
4493 2 the first time, range or not
4494 4 the second time, if it is a range.")
4496 (defconst org-startup-options
4497 '(("fold" org-startup-folded t)
4498 ("overview" org-startup-folded t)
4499 ("nofold" org-startup-folded nil)
4500 ("showall" org-startup-folded nil)
4501 ("showeverything" org-startup-folded showeverything)
4502 ("content" org-startup-folded content)
4503 ("indent" org-startup-indented t)
4504 ("noindent" org-startup-indented nil)
4505 ("hidestars" org-hide-leading-stars t)
4506 ("showstars" org-hide-leading-stars nil)
4507 ("odd" org-odd-levels-only t)
4508 ("oddeven" org-odd-levels-only nil)
4509 ("align" org-startup-align-all-tables t)
4510 ("noalign" org-startup-align-all-tables nil)
4511 ("inlineimages" org-startup-with-inline-images t)
4512 ("noinlineimages" org-startup-with-inline-images nil)
4513 ("customtime" org-display-custom-times t)
4514 ("logdone" org-log-done time)
4515 ("lognotedone" org-log-done note)
4516 ("nologdone" org-log-done nil)
4517 ("lognoteclock-out" org-log-note-clock-out t)
4518 ("nolognoteclock-out" org-log-note-clock-out nil)
4519 ("logrepeat" org-log-repeat state)
4520 ("lognoterepeat" org-log-repeat note)
4521 ("logdrawer" org-log-into-drawer t)
4522 ("nologdrawer" org-log-into-drawer nil)
4523 ("logstatesreversed" org-log-states-order-reversed t)
4524 ("nologstatesreversed" org-log-states-order-reversed nil)
4525 ("nologrepeat" org-log-repeat nil)
4526 ("logreschedule" org-log-reschedule time)
4527 ("lognotereschedule" org-log-reschedule note)
4528 ("nologreschedule" org-log-reschedule nil)
4529 ("logredeadline" org-log-redeadline time)
4530 ("lognoteredeadline" org-log-redeadline note)
4531 ("nologredeadline" org-log-redeadline nil)
4532 ("logrefile" org-log-refile time)
4533 ("lognoterefile" org-log-refile note)
4534 ("nologrefile" org-log-refile nil)
4535 ("fninline" org-footnote-define-inline t)
4536 ("nofninline" org-footnote-define-inline nil)
4537 ("fnlocal" org-footnote-section nil)
4538 ("fnauto" org-footnote-auto-label t)
4539 ("fnprompt" org-footnote-auto-label nil)
4540 ("fnconfirm" org-footnote-auto-label confirm)
4541 ("fnplain" org-footnote-auto-label plain)
4542 ("fnadjust" org-footnote-auto-adjust t)
4543 ("nofnadjust" org-footnote-auto-adjust nil)
4544 ("constcgs" constants-unit-system cgs)
4545 ("constSI" constants-unit-system SI)
4546 ("noptag" org-tag-persistent-alist nil)
4547 ("hideblocks" org-hide-block-startup t)
4548 ("nohideblocks" org-hide-block-startup nil)
4549 ("beamer" org-startup-with-beamer-mode t)
4550 ("entitiespretty" org-pretty-entities t)
4551 ("entitiesplain" org-pretty-entities nil))
4552 "Variable associated with STARTUP options for org-mode.
4553 Each element is a list of three items: the startup options (as written
4554 in the #+STARTUP line), the corresponding variable, and the value to set
4555 this variable to if the option is found. An optional forth element PUSH
4556 means to push this value onto the list in the variable.")
4558 (defun org-update-property-plist (key val props)
4559 "Update PROPS with KEY and VAL."
4560 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4561 (key (if appending (substring key 0 (- (length key) 1)) key))
4562 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4563 (previous (cdr (assoc key props))))
4564 (if appending
4565 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4566 (cons (cons key val) remainder))))
4568 (defconst org-block-regexp
4569 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4570 "Regular expression for hiding blocks.")
4571 (defconst org-heading-keyword-regexp-format
4572 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4573 "Printf format for a regexp matching an headline with some keyword.
4574 This regexp will match the headline of any node which has the
4575 exact keyword that is put into the format. The keyword isn't in
4576 any group by default, but the stars and the body are.")
4577 (defconst org-heading-keyword-maybe-regexp-format
4578 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4579 "Printf format for a regexp matching an headline, possibly with some keyword.
4580 This regexp can match any headline with the specified keyword, or
4581 without a keyword. The keyword isn't in any group by default,
4582 but the stars and the body are.")
4584 (defun org-set-regexps-and-options ()
4585 "Precompute regular expressions for current buffer."
4586 (when (derived-mode-p 'org-mode)
4587 (org-set-local 'org-todo-kwd-alist nil)
4588 (org-set-local 'org-todo-key-alist nil)
4589 (org-set-local 'org-todo-key-trigger nil)
4590 (org-set-local 'org-todo-keywords-1 nil)
4591 (org-set-local 'org-done-keywords nil)
4592 (org-set-local 'org-todo-heads nil)
4593 (org-set-local 'org-todo-sets nil)
4594 (org-set-local 'org-todo-log-states nil)
4595 (org-set-local 'org-file-properties nil)
4596 (org-set-local 'org-file-tags nil)
4597 (let ((re (org-make-options-regexp
4598 '("CATEGORY" "TODO" "COLUMNS"
4599 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4600 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4601 "OPTIONS")
4602 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4603 (splitre "[ \t]+")
4604 (scripts org-use-sub-superscripts)
4605 kwds kws0 kwsa key log value cat arch tags const links hw dws
4606 tail sep kws1 prio props ftags drawers beamer-p
4607 ext-setup-or-nil setup-contents (start 0))
4608 (save-excursion
4609 (save-restriction
4610 (widen)
4611 (goto-char (point-min))
4612 (while (or (and ext-setup-or-nil
4613 (string-match re ext-setup-or-nil start)
4614 (setq start (match-end 0)))
4615 (and (setq ext-setup-or-nil nil start 0)
4616 (re-search-forward re nil t)))
4617 (setq key (upcase (match-string 1 ext-setup-or-nil))
4618 value (org-match-string-no-properties 2 ext-setup-or-nil))
4619 (if (stringp value) (setq value (org-trim value)))
4620 (cond
4621 ((equal key "CATEGORY")
4622 (setq cat value))
4623 ((member key '("SEQ_TODO" "TODO"))
4624 (push (cons 'sequence (org-split-string value splitre)) kwds))
4625 ((equal key "TYP_TODO")
4626 (push (cons 'type (org-split-string value splitre)) kwds))
4627 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4628 ;; general TODO-like setup
4629 (push (cons (intern (downcase (match-string 1 key)))
4630 (org-split-string value splitre)) kwds))
4631 ((equal key "TAGS")
4632 (setq tags (append tags (if tags '("\\n") nil)
4633 (org-split-string value splitre))))
4634 ((equal key "COLUMNS")
4635 (org-set-local 'org-columns-default-format value))
4636 ((equal key "LINK")
4637 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4638 (push (cons (match-string 1 value)
4639 (org-trim (match-string 2 value)))
4640 links)))
4641 ((equal key "PRIORITIES")
4642 (setq prio (org-split-string value " +")))
4643 ((equal key "PROPERTY")
4644 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4645 (setq props (org-update-property-plist (match-string 1 value)
4646 (match-string 2 value)
4647 props))))
4648 ((equal key "FILETAGS")
4649 (when (string-match "\\S-" value)
4650 (setq ftags
4651 (append
4652 ftags
4653 (apply 'append
4654 (mapcar (lambda (x) (org-split-string x ":"))
4655 (org-split-string value)))))))
4656 ((equal key "DRAWERS")
4657 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4658 ((equal key "CONSTANTS")
4659 (setq const (append const (org-split-string value splitre))))
4660 ((equal key "STARTUP")
4661 (let ((opts (org-split-string value splitre))
4662 l var val)
4663 (while (setq l (pop opts))
4664 (when (setq l (assoc l org-startup-options))
4665 (setq var (nth 1 l) val (nth 2 l))
4666 (if (not (nth 3 l))
4667 (set (make-local-variable var) val)
4668 (if (not (listp (symbol-value var)))
4669 (set (make-local-variable var) nil))
4670 (set (make-local-variable var) (symbol-value var))
4671 (add-to-list var val))))))
4672 ((equal key "ARCHIVE")
4673 (setq arch value)
4674 (remove-text-properties 0 (length arch)
4675 '(face t fontified t) arch))
4676 ((equal key "LATEX_CLASS")
4677 (setq beamer-p (equal value "beamer")))
4678 ((equal key "OPTIONS")
4679 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4680 (setq scripts (read (match-string 2 value)))))
4681 ((equal key "SETUPFILE")
4682 (setq setup-contents (org-file-contents
4683 (expand-file-name
4684 (org-remove-double-quotes value))
4685 'noerror))
4686 (if (not ext-setup-or-nil)
4687 (setq ext-setup-or-nil setup-contents start 0)
4688 (setq ext-setup-or-nil
4689 (concat (substring ext-setup-or-nil 0 start)
4690 "\n" setup-contents "\n"
4691 (substring ext-setup-or-nil start)))))))
4692 ;; search for property blocks
4693 (goto-char (point-min))
4694 (while (re-search-forward org-block-regexp nil t)
4695 (when (equal "PROPERTY" (upcase (match-string 1)))
4696 (setq value (replace-regexp-in-string
4697 "[\n\r]" " " (match-string 4)))
4698 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4699 (setq props (org-update-property-plist (match-string 1 value)
4700 (match-string 2 value)
4701 props)))))))
4702 (org-set-local 'org-use-sub-superscripts scripts)
4703 (when cat
4704 (org-set-local 'org-category (intern cat))
4705 (push (cons "CATEGORY" cat) props))
4706 (when prio
4707 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4708 (setq prio (mapcar 'string-to-char prio))
4709 (org-set-local 'org-highest-priority (nth 0 prio))
4710 (org-set-local 'org-lowest-priority (nth 1 prio))
4711 (org-set-local 'org-default-priority (nth 2 prio)))
4712 (and props (org-set-local 'org-file-properties (nreverse props)))
4713 (and ftags (org-set-local 'org-file-tags
4714 (mapcar 'org-add-prop-inherited ftags)))
4715 (and drawers (org-set-local 'org-drawers drawers))
4716 (and arch (org-set-local 'org-archive-location arch))
4717 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4718 ;; Process the TODO keywords
4719 (unless kwds
4720 ;; Use the global values as if they had been given locally.
4721 (setq kwds (default-value 'org-todo-keywords))
4722 (if (stringp (car kwds))
4723 (setq kwds (list (cons org-todo-interpretation
4724 (default-value 'org-todo-keywords)))))
4725 (setq kwds (reverse kwds)))
4726 (setq kwds (nreverse kwds))
4727 (let (inter kws kw)
4728 (while (setq kws (pop kwds))
4729 (let ((kws (or
4730 (run-hook-with-args-until-success
4731 'org-todo-setup-filter-hook kws)
4732 kws)))
4733 (setq inter (pop kws) sep (member "|" kws)
4734 kws0 (delete "|" (copy-sequence kws))
4735 kwsa nil
4736 kws1 (mapcar
4737 (lambda (x)
4738 ;; 1 2
4739 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4740 (progn
4741 (setq kw (match-string 1 x)
4742 key (and (match-end 2) (match-string 2 x))
4743 log (org-extract-log-state-settings x))
4744 (push (cons kw (and key (string-to-char key))) kwsa)
4745 (and log (push log org-todo-log-states))
4747 (error "Invalid TODO keyword %s" x)))
4748 kws0)
4749 kwsa (if kwsa (append '((:startgroup))
4750 (nreverse kwsa)
4751 '((:endgroup))))
4752 hw (car kws1)
4753 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4754 tail (list inter hw (car dws) (org-last dws))))
4755 (add-to-list 'org-todo-heads hw 'append)
4756 (push kws1 org-todo-sets)
4757 (setq org-done-keywords (append org-done-keywords dws nil))
4758 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4759 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4760 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4761 (setq org-todo-sets (nreverse org-todo-sets)
4762 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4763 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4764 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4765 ;; Process the constants
4766 (when const
4767 (let (e cst)
4768 (while (setq e (pop const))
4769 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4770 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4771 (setq org-table-formula-constants-local cst)))
4773 ;; Process the tags.
4774 (when tags
4775 (let (e tgs)
4776 (while (setq e (pop tags))
4777 (cond
4778 ((equal e "{") (push '(:startgroup) tgs))
4779 ((equal e "}") (push '(:endgroup) tgs))
4780 ((equal e "\\n") (push '(:newline) tgs))
4781 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4782 (push (cons (match-string 1 e)
4783 (string-to-char (match-string 2 e)))
4784 tgs))
4785 (t (push (list e) tgs))))
4786 (org-set-local 'org-tag-alist nil)
4787 (while (setq e (pop tgs))
4788 (or (and (stringp (car e))
4789 (assoc (car e) org-tag-alist))
4790 (push e org-tag-alist)))))
4792 ;; Compute the regular expressions and other local variables.
4793 ;; Using `org-outline-regexp-bol' would complicate them much,
4794 ;; because of the fixed white space at the end of that string.
4795 (if (not org-done-keywords)
4796 (setq org-done-keywords (and org-todo-keywords-1
4797 (list (org-last org-todo-keywords-1)))))
4798 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4799 (length org-scheduled-string)
4800 (length org-clock-string)
4801 (length org-closed-string)))
4802 org-drawer-regexp
4803 (concat "^[ \t]*:\\("
4804 (mapconcat 'regexp-quote org-drawers "\\|")
4805 "\\):[ \t]*$")
4806 org-not-done-keywords
4807 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4808 org-todo-regexp
4809 (concat "\\("
4810 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4811 "\\)")
4812 org-not-done-regexp
4813 (concat "\\("
4814 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4815 "\\)")
4816 org-not-done-heading-regexp
4817 (format org-heading-keyword-regexp-format org-not-done-regexp)
4818 org-todo-line-regexp
4819 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4820 org-complex-heading-regexp
4821 (concat "^\\(\\*+\\)"
4822 "\\(?: +" org-todo-regexp "\\)?"
4823 "\\(?: +\\(\\[#.\\]\\)\\)?"
4824 "\\(?: +\\(.*?\\)\\)??"
4825 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4826 "[ \t]*$")
4827 org-complex-heading-regexp-format
4828 (concat "^\\(\\*+\\)"
4829 "\\(?: +" org-todo-regexp "\\)?"
4830 "\\(?: +\\(\\[#.\\]\\)\\)?"
4831 "\\(?: +"
4832 ;; Stats cookies can be stuck to body.
4833 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4834 "\\(%s\\)"
4835 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4836 "\\)"
4837 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4838 "[ \t]*$")
4839 org-todo-line-tags-regexp
4840 (concat "^\\(\\*+\\)"
4841 "\\(?: +" org-todo-regexp "\\)?"
4842 "\\(?: +\\(.*?\\)\\)??"
4843 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4844 "[ \t]*$")
4845 org-deadline-regexp (concat "\\<" org-deadline-string)
4846 org-deadline-time-regexp
4847 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4848 org-deadline-line-regexp
4849 (concat "\\<\\(" org-deadline-string "\\).*")
4850 org-scheduled-regexp
4851 (concat "\\<" org-scheduled-string)
4852 org-scheduled-time-regexp
4853 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4854 org-closed-time-regexp
4855 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4856 org-keyword-time-regexp
4857 (concat "\\<\\(" org-scheduled-string
4858 "\\|" org-deadline-string
4859 "\\|" org-closed-string
4860 "\\|" org-clock-string "\\)"
4861 " *[[<]\\([^]>]+\\)[]>]")
4862 org-keyword-time-not-clock-regexp
4863 (concat "\\<\\(" org-scheduled-string
4864 "\\|" org-deadline-string
4865 "\\|" org-closed-string
4866 "\\)"
4867 " *[[<]\\([^]>]+\\)[]>]")
4868 org-maybe-keyword-time-regexp
4869 (concat "\\(\\<\\(" org-scheduled-string
4870 "\\|" org-deadline-string
4871 "\\|" org-closed-string
4872 "\\|" org-clock-string "\\)\\)?"
4873 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4874 org-all-time-keywords
4875 (mapcar (lambda (w) (substring w 0 -1))
4876 (list org-scheduled-string org-deadline-string
4877 org-clock-string org-closed-string))
4879 (org-compute-latex-and-specials-regexp)
4880 (org-set-font-lock-defaults))))
4882 (defun org-file-contents (file &optional noerror)
4883 "Return the contents of FILE, as a string."
4884 (if (or (not file)
4885 (not (file-readable-p file)))
4886 (if noerror
4887 (progn
4888 (message "Cannot read file \"%s\"" file)
4889 (ding) (sit-for 2)
4891 (error "Cannot read file \"%s\"" file))
4892 (with-temp-buffer
4893 (insert-file-contents file)
4894 (buffer-string))))
4896 (defun org-extract-log-state-settings (x)
4897 "Extract the log state setting from a TODO keyword string.
4898 This will extract info from a string like \"WAIT(w@/!)\"."
4899 (let (kw key log1 log2)
4900 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4901 (setq kw (match-string 1 x)
4902 key (and (match-end 2) (match-string 2 x))
4903 log1 (and (match-end 3) (match-string 3 x))
4904 log2 (and (match-end 4) (match-string 4 x)))
4905 (and (or log1 log2)
4906 (list kw
4907 (and log1 (if (equal log1 "!") 'time 'note))
4908 (and log2 (if (equal log2 "!") 'time 'note)))))))
4910 (defun org-remove-keyword-keys (list)
4911 "Remove a pair of parenthesis at the end of each string in LIST."
4912 (mapcar (lambda (x)
4913 (if (string-match "(.*)$" x)
4914 (substring x 0 (match-beginning 0))
4916 list))
4918 (defun org-assign-fast-keys (alist)
4919 "Assign fast keys to a keyword-key alist.
4920 Respect keys that are already there."
4921 (let (new e (alt ?0))
4922 (while (setq e (pop alist))
4923 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4924 (cdr e)) ;; Key already assigned.
4925 (push e new)
4926 (let ((clist (string-to-list (downcase (car e))))
4927 (used (append new alist)))
4928 (when (= (car clist) ?@)
4929 (pop clist))
4930 (while (and clist (rassoc (car clist) used))
4931 (pop clist))
4932 (unless clist
4933 (while (rassoc alt used)
4934 (incf alt)))
4935 (push (cons (car e) (or (car clist) alt)) new))))
4936 (nreverse new)))
4938 ;;; Some variables used in various places
4940 (defvar org-window-configuration nil
4941 "Used in various places to store a window configuration.")
4942 (defvar org-selected-window nil
4943 "Used in various places to store a window configuration.")
4944 (defvar org-finish-function nil
4945 "Function to be called when `C-c C-c' is used.
4946 This is for getting out of special buffers like capture.")
4949 ;; FIXME: Occasionally check by commenting these, to make sure
4950 ;; no other functions uses these, forgetting to let-bind them.
4951 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4952 (defvar org-last-state)
4953 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4955 ;; Defined somewhere in this file, but used before definition.
4956 (defvar org-entities) ;; defined in org-entities.el
4957 (defvar org-struct-menu)
4958 (defvar org-org-menu)
4959 (defvar org-tbl-menu)
4961 ;;;; Define the Org-mode
4963 ;; We use a before-change function to check if a table might need
4964 ;; an update.
4965 (defvar org-table-may-need-update t
4966 "Indicates that a table might need an update.
4967 This variable is set by `org-before-change-function'.
4968 `org-table-align' sets it back to nil.")
4969 (defun org-before-change-function (beg end)
4970 "Every change indicates that a table might need an update."
4971 (setq org-table-may-need-update t))
4972 (defvar org-mode-map)
4973 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4974 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4975 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4976 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4977 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4978 (defvar org-table-buffer-is-an nil)
4980 (defvar bidi-paragraph-direction)
4981 (defvar buffer-face-mode-face)
4983 (require 'outline)
4984 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4985 (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"))
4986 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4988 ;; Other stuff we need.
4989 (require 'time-date)
4990 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4991 (require 'easymenu)
4992 (require 'overlay)
4994 ;; (require 'org-macs) moved higher up in the file before it is first used
4995 (require 'org-entities)
4996 ;; (require 'org-compat) moved higher up in the file before it is first used
4997 (require 'org-faces)
4998 (require 'org-list)
4999 (require 'org-pcomplete)
5000 (require 'org-src)
5001 (require 'org-footnote)
5003 ;; babel
5004 (require 'ob)
5006 ;;;###autoload
5007 (define-derived-mode org-mode outline-mode "Org"
5008 "Outline-based notes management and organizer, alias
5009 \"Carsten's outline-mode for keeping track of everything.\"
5011 Org-mode develops organizational tasks around a NOTES file which
5012 contains information about projects as plain text. Org-mode is
5013 implemented on top of outline-mode, which is ideal to keep the content
5014 of large files well structured. It supports ToDo items, deadlines and
5015 time stamps, which magically appear in the diary listing of the Emacs
5016 calendar. Tables are easily created with a built-in table editor.
5017 Plain text URL-like links connect to websites, emails (VM), Usenet
5018 messages (Gnus), BBDB entries, and any files related to the project.
5019 For printing and sharing of notes, an Org-mode file (or a part of it)
5020 can be exported as a structured ASCII or HTML file.
5022 The following commands are available:
5024 \\{org-mode-map}"
5026 ;; Get rid of Outline menus, they are not needed
5027 ;; Need to do this here because define-derived-mode sets up
5028 ;; the keymap so late. Still, it is a waste to call this each time
5029 ;; we switch another buffer into org-mode.
5030 (if (featurep 'xemacs)
5031 (when (boundp 'outline-mode-menu-heading)
5032 ;; Assume this is Greg's port, it uses easymenu
5033 (easy-menu-remove outline-mode-menu-heading)
5034 (easy-menu-remove outline-mode-menu-show)
5035 (easy-menu-remove outline-mode-menu-hide))
5036 (define-key org-mode-map [menu-bar headings] 'undefined)
5037 (define-key org-mode-map [menu-bar hide] 'undefined)
5038 (define-key org-mode-map [menu-bar show] 'undefined))
5040 (org-load-modules-maybe)
5041 (easy-menu-add org-org-menu)
5042 (easy-menu-add org-tbl-menu)
5043 (org-install-agenda-files-menu)
5044 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5045 (add-to-invisibility-spec '(org-cwidth))
5046 (add-to-invisibility-spec '(org-hide-block . t))
5047 (when (featurep 'xemacs)
5048 (org-set-local 'line-move-ignore-invisible t))
5049 (org-set-local 'outline-regexp org-outline-regexp)
5050 (org-set-local 'outline-level 'org-outline-level)
5051 (setq bidi-paragraph-direction 'left-to-right)
5052 (when (and org-ellipsis
5053 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5054 (fboundp 'make-glyph-code))
5055 (unless org-display-table
5056 (setq org-display-table (make-display-table)))
5057 (set-display-table-slot
5058 org-display-table 4
5059 (vconcat (mapcar
5060 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5061 org-ellipsis)))
5062 (if (stringp org-ellipsis) org-ellipsis "..."))))
5063 (setq buffer-display-table org-display-table))
5064 (org-set-regexps-and-options)
5065 (when (and org-tag-faces (not org-tags-special-faces-re))
5066 ;; tag faces set outside customize.... force initialization.
5067 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5068 ;; Calc embedded
5069 (org-set-local 'calc-embedded-open-mode "# ")
5070 (modify-syntax-entry ?@ "w")
5071 (modify-syntax-entry ?\" "\"")
5072 (if org-startup-truncated (setq truncate-lines t))
5073 (org-set-local 'font-lock-unfontify-region-function
5074 'org-unfontify-region)
5075 ;; Activate before-change-function
5076 (org-set-local 'org-table-may-need-update t)
5077 (org-add-hook 'before-change-functions 'org-before-change-function nil
5078 'local)
5079 ;; Check for running clock before killing a buffer
5080 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5081 ;; Initialize macros templates.
5082 (org-macro-initialize-templates)
5083 ;; Initialize radio targets.
5084 (org-update-radio-target-regexp)
5085 ;; Indentation.
5086 (org-set-local 'indent-line-function 'org-indent-line)
5087 (org-set-local 'indent-region-function 'org-indent-region)
5088 ;; Filling and auto-filling.
5089 (org-setup-filling)
5090 ;; Comments.
5091 (org-setup-comments-handling)
5092 ;; Beginning/end of defun
5093 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5094 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5095 ;; Next error for sparse trees
5096 (org-set-local 'next-error-function 'org-occur-next-match)
5097 ;; Make sure dependence stuff works reliably, even for users who set it
5098 ;; too late :-(
5099 (if org-enforce-todo-dependencies
5100 (add-hook 'org-blocker-hook
5101 'org-block-todo-from-children-or-siblings-or-parent)
5102 (remove-hook 'org-blocker-hook
5103 'org-block-todo-from-children-or-siblings-or-parent))
5104 (if org-enforce-todo-checkbox-dependencies
5105 (add-hook 'org-blocker-hook
5106 'org-block-todo-from-checkboxes)
5107 (remove-hook 'org-blocker-hook
5108 'org-block-todo-from-checkboxes))
5110 ;; Align options lines
5111 (org-set-local
5112 'align-mode-rules-list
5113 '((org-in-buffer-settings
5114 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5115 (modes . '(org-mode)))))
5117 ;; Imenu
5118 (org-set-local 'imenu-create-index-function
5119 'org-imenu-get-tree)
5121 ;; Make isearch reveal context
5122 (if (or (featurep 'xemacs)
5123 (not (boundp 'outline-isearch-open-invisible-function)))
5124 ;; Emacs 21 and XEmacs make use of the hook
5125 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5126 ;; Emacs 22 deals with this through a special variable
5127 (org-set-local 'outline-isearch-open-invisible-function
5128 (lambda (&rest ignore) (org-show-context 'isearch))))
5130 ;; Turn on org-beamer-mode?
5131 (and org-startup-with-beamer-mode (org-beamer-mode))
5133 ;; Setup the pcomplete hooks
5134 (set (make-local-variable 'pcomplete-command-completion-function)
5135 'org-pcomplete-initial)
5136 (set (make-local-variable 'pcomplete-command-name-function)
5137 'org-command-at-point)
5138 (set (make-local-variable 'pcomplete-default-completion-function)
5139 'ignore)
5140 (set (make-local-variable 'pcomplete-parse-arguments-function)
5141 'org-parse-arguments)
5142 (set (make-local-variable 'pcomplete-termination-string) "")
5143 (when (>= emacs-major-version 23)
5144 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5146 ;; If empty file that did not turn on org-mode automatically, make it to.
5147 (if (and org-insert-mode-line-in-empty-file
5148 (org-called-interactively-p 'any)
5149 (= (point-min) (point-max)))
5150 (insert "# -*- mode: org -*-\n\n"))
5151 (unless org-inhibit-startup
5152 (when org-startup-align-all-tables
5153 (let ((bmp (buffer-modified-p)))
5154 (org-table-map-tables 'org-table-align 'quietly)
5155 (set-buffer-modified-p bmp)))
5156 (when org-startup-with-inline-images
5157 (org-display-inline-images))
5158 (when org-startup-indented
5159 (require 'org-indent)
5160 (org-indent-mode 1))
5161 (unless org-inhibit-startup-visibility-stuff
5162 (org-set-startup-visibility)))
5163 ;; Try to set org-hide correctly
5164 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5166 (when (fboundp 'abbrev-table-put)
5167 (abbrev-table-put org-mode-abbrev-table
5168 :parents (list text-mode-abbrev-table)))
5170 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5173 (defun org-find-invisible-foreground ()
5174 (let ((candidates (remove
5175 "unspecified-bg"
5176 (nconc
5177 (list (face-background 'default)
5178 (face-background 'org-default))
5179 (mapcar
5180 (lambda (alist)
5181 (when (boundp alist)
5182 (cdr (assoc 'background-color (symbol-value alist)))))
5183 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5184 (list (face-foreground 'org-hide))))))
5185 (car (remove nil candidates))))
5187 (defun org-current-time (&optional rounding-minutes)
5188 "Current time, possibly rounded to ROUNDING-MINUTES.
5189 When ROUNDING-MINUTES is not an integer, fall back on the car of
5190 `org-time-stamp-rounding-minutes'."
5191 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5192 (car org-time-stamp-rounding-minutes)))
5193 (time (decode-time)))
5194 (if (> r 1)
5195 (apply 'encode-time
5196 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5197 (nthcdr 2 time)))
5198 (current-time))))
5200 (defun org-today ()
5201 "Return today date, considering `org-extend-today-until'."
5202 (time-to-days
5203 (time-subtract (current-time)
5204 (list 0 (* 3600 org-extend-today-until) 0))))
5206 ;;;; Font-Lock stuff, including the activators
5208 (defvar org-mouse-map (make-sparse-keymap))
5209 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5210 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5211 (when org-mouse-1-follows-link
5212 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5213 (when org-tab-follows-link
5214 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5215 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5217 (require 'font-lock)
5219 (defconst org-non-link-chars "]\t\n\r<>")
5220 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5221 "shell" "elisp" "doi" "message"))
5222 (defvar org-link-types-re nil
5223 "Matches a link that has a url-like prefix like \"http:\"")
5224 (defvar org-link-re-with-space nil
5225 "Matches a link with spaces, optional angular brackets around it.")
5226 (defvar org-link-re-with-space2 nil
5227 "Matches a link with spaces, optional angular brackets around it.")
5228 (defvar org-link-re-with-space3 nil
5229 "Matches a link with spaces, only for internal part in bracket links.")
5230 (defvar org-angle-link-re nil
5231 "Matches link with angular brackets, spaces are allowed.")
5232 (defvar org-plain-link-re nil
5233 "Matches plain link, without spaces.")
5234 (defvar org-bracket-link-regexp nil
5235 "Matches a link in double brackets.")
5236 (defvar org-bracket-link-analytic-regexp nil
5237 "Regular expression used to analyze links.
5238 Here is what the match groups contain after a match:
5239 1: http:
5240 2: http
5241 3: path
5242 4: [desc]
5243 5: desc")
5244 (defvar org-bracket-link-analytic-regexp++ nil
5245 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5246 (defvar org-any-link-re nil
5247 "Regular expression matching any link.")
5249 (defcustom org-match-sexp-depth 3
5250 "Number of stacked braces for sub/superscript matching.
5251 This has to be set before loading org.el to be effective."
5252 :group 'org-export-translation ; ??????????????????????????/
5253 :type 'integer)
5255 (defun org-create-multibrace-regexp (left right n)
5256 "Create a regular expression which will match a balanced sexp.
5257 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5258 as single character strings.
5259 The regexp returned will match the entire expression including the
5260 delimiters. It will also define a single group which contains the
5261 match except for the outermost delimiters. The maximum depth of
5262 stacked delimiters is N. Escaping delimiters is not possible."
5263 (let* ((nothing (concat "[^" left right "]*?"))
5264 (or "\\|")
5265 (re nothing)
5266 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5267 (while (> n 1)
5268 (setq n (1- n)
5269 re (concat re or next)
5270 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5271 (concat left "\\(" re "\\)" right)))
5273 (defvar org-match-substring-regexp
5274 (concat
5275 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5276 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5277 "\\|"
5278 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5279 "\\|"
5280 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5281 "The regular expression matching a sub- or superscript.")
5283 (defvar org-match-substring-with-braces-regexp
5284 (concat
5285 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5286 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5287 "\\)")
5288 "The regular expression matching a sub- or superscript, forcing braces.")
5290 (defun org-make-link-regexps ()
5291 "Update the link regular expressions.
5292 This should be called after the variable `org-link-types' has changed."
5293 (setq org-link-types-re
5294 (concat
5295 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5296 org-link-re-with-space
5297 (concat
5298 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5299 "\\([^" org-non-link-chars " ]"
5300 "[^" org-non-link-chars "]*"
5301 "[^" org-non-link-chars " ]\\)>?")
5302 org-link-re-with-space2
5303 (concat
5304 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5305 "\\([^" org-non-link-chars " ]"
5306 "[^\t\n\r]*"
5307 "[^" org-non-link-chars " ]\\)>?")
5308 org-link-re-with-space3
5309 (concat
5310 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5311 "\\([^" org-non-link-chars " ]"
5312 "[^\t\n\r]*\\)")
5313 org-angle-link-re
5314 (concat
5315 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5316 "\\([^" org-non-link-chars " ]"
5317 "[^" org-non-link-chars "]*"
5318 "\\)>")
5319 org-plain-link-re
5320 (concat
5321 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5322 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5323 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5324 org-bracket-link-regexp
5325 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5326 org-bracket-link-analytic-regexp
5327 (concat
5328 "\\[\\["
5329 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5330 "\\([^]]+\\)"
5331 "\\]"
5332 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5333 "\\]")
5334 org-bracket-link-analytic-regexp++
5335 (concat
5336 "\\[\\["
5337 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5338 "\\([^]]+\\)"
5339 "\\]"
5340 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5341 "\\]")
5342 org-any-link-re
5343 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5344 org-angle-link-re "\\)\\|\\("
5345 org-plain-link-re "\\)")))
5347 (org-make-link-regexps)
5349 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5350 "Regular expression for fast time stamp matching.")
5351 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5352 "Regular expression for fast time stamp matching.")
5353 (defconst org-ts-regexp0
5354 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5355 "Regular expression matching time strings for analysis.
5356 This one does not require the space after the date, so it can be used
5357 on a string that terminates immediately after the date.")
5358 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5359 "Regular expression matching time strings for analysis.")
5360 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5361 "Regular expression matching time stamps, with groups.")
5362 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5363 "Regular expression matching time stamps (also [..]), with groups.")
5364 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5365 "Regular expression matching a time stamp range.")
5366 (defconst org-tr-regexp-both
5367 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5368 "Regular expression matching a time stamp range.")
5369 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5370 org-ts-regexp "\\)?")
5371 "Regular expression matching a time stamp or time stamp range.")
5372 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5373 org-ts-regexp-both "\\)?")
5374 "Regular expression matching a time stamp or time stamp range.
5375 The time stamps may be either active or inactive.")
5377 (defvar org-emph-face nil)
5379 (defun org-do-emphasis-faces (limit)
5380 "Run through the buffer and add overlays to emphasized strings."
5381 (let (rtn a)
5382 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5383 (if (not (= (char-after (match-beginning 3))
5384 (char-after (match-beginning 4))))
5385 (progn
5386 (setq rtn t)
5387 (setq a (assoc (match-string 3) org-emphasis-alist))
5388 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5389 'face
5390 (nth 1 a))
5391 (and (nth 4 a)
5392 (org-remove-flyspell-overlays-in
5393 (match-beginning 0) (match-end 0)))
5394 (add-text-properties (match-beginning 2) (match-end 2)
5395 '(font-lock-multiline t org-emphasis t))
5396 (when org-hide-emphasis-markers
5397 (add-text-properties (match-end 4) (match-beginning 5)
5398 '(invisible org-link))
5399 (add-text-properties (match-beginning 3) (match-end 3)
5400 '(invisible org-link)))))
5401 (backward-char 1))
5402 rtn))
5404 (defun org-emphasize (&optional char)
5405 "Insert or change an emphasis, i.e. a font like bold or italic.
5406 If there is an active region, change that region to a new emphasis.
5407 If there is no region, just insert the marker characters and position
5408 the cursor between them.
5409 CHAR should be either the marker character, or the first character of the
5410 HTML tag associated with that emphasis. If CHAR is a space, the means
5411 to remove the emphasis of the selected region.
5412 If char is not given (for example in an interactive call) it
5413 will be prompted for."
5414 (interactive)
5415 (let ((eal org-emphasis-alist) e det
5416 (erc org-emphasis-regexp-components)
5417 (prompt "")
5418 (string "") beg end move tag c s)
5419 (if (org-region-active-p)
5420 (setq beg (region-beginning) end (region-end)
5421 string (buffer-substring beg end))
5422 (setq move t))
5424 (while (setq e (pop eal))
5425 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5426 c (aref tag 0))
5427 (push (cons c (string-to-char (car e))) det)
5428 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5429 (substring tag 1)))))
5430 (setq det (nreverse det))
5431 (unless char
5432 (message "%s" (concat "Emphasis marker or tag:" prompt))
5433 (setq char (read-char-exclusive)))
5434 (setq char (or (cdr (assoc char det)) char))
5435 (if (equal char ?\ )
5436 (setq s "" move nil)
5437 (unless (assoc (char-to-string char) org-emphasis-alist)
5438 (error "No such emphasis marker: \"%c\"" char))
5439 (setq s (char-to-string char)))
5440 (while (and (> (length string) 1)
5441 (equal (substring string 0 1) (substring string -1))
5442 (assoc (substring string 0 1) org-emphasis-alist))
5443 (setq string (substring string 1 -1)))
5444 (setq string (concat s string s))
5445 (if beg (delete-region beg end))
5446 (unless (or (bolp)
5447 (string-match (concat "[" (nth 0 erc) "\n]")
5448 (char-to-string (char-before (point)))))
5449 (insert " "))
5450 (unless (or (eobp)
5451 (string-match (concat "[" (nth 1 erc) "\n]")
5452 (char-to-string (char-after (point)))))
5453 (insert " ") (backward-char 1))
5454 (insert string)
5455 (and move (backward-char 1))))
5457 (defconst org-nonsticky-props
5458 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5460 (defsubst org-rear-nonsticky-at (pos)
5461 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5463 (defun org-activate-plain-links (limit)
5464 "Run through the buffer and add overlays to links."
5465 (catch 'exit
5466 (let (f hl)
5467 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5468 (not (org-in-src-block-p)))
5469 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5470 (setq f (get-text-property (match-beginning 0) 'face))
5471 (setq hl (org-match-string-no-properties 0))
5472 (if (or (eq f 'org-tag)
5473 (and (listp f) (memq 'org-tag f)))
5475 (add-text-properties (match-beginning 0) (match-end 0)
5476 (list 'mouse-face 'highlight
5477 'face 'org-link
5478 'htmlize-link `(:uri ,hl)
5479 'keymap org-mouse-map))
5480 (org-rear-nonsticky-at (match-end 0)))
5481 t))))
5483 (defun org-activate-code (limit)
5484 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5485 (progn
5486 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5487 (remove-text-properties (match-beginning 0) (match-end 0)
5488 '(display t invisible t intangible t))
5489 t)))
5491 (defcustom org-src-fontify-natively nil
5492 "When non-nil, fontify code in code blocks."
5493 :type 'boolean
5494 :version "24.1"
5495 :group 'org-appearance
5496 :group 'org-babel)
5498 (defcustom org-allow-promoting-top-level-subtree nil
5499 "When non-nil, allow promoting a top level subtree.
5500 The leading star of the top level headline will be replaced
5501 by a #."
5502 :type 'boolean
5503 :version "24.1"
5504 :group 'org-appearance)
5506 (defun org-fontify-meta-lines-and-blocks (limit)
5507 (condition-case nil
5508 (org-fontify-meta-lines-and-blocks-1 limit)
5509 (error (message "org-mode fontification error"))))
5511 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5512 "Fontify #+ lines and blocks, in the correct ways."
5513 (let ((case-fold-search t))
5514 (if (re-search-forward
5515 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5516 limit t)
5517 (let ((beg (match-beginning 0))
5518 (block-start (match-end 0))
5519 (block-end nil)
5520 (lang (match-string 7))
5521 (beg1 (line-beginning-position 2))
5522 (dc1 (downcase (match-string 2)))
5523 (dc3 (downcase (match-string 3)))
5524 end end1 quoting block-type ovl)
5525 (cond
5526 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5527 ;; a single line of backend-specific content
5528 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5529 (remove-text-properties (match-beginning 0) (match-end 0)
5530 '(display t invisible t intangible t))
5531 (add-text-properties (match-beginning 1) (match-end 3)
5532 '(font-lock-fontified t face org-meta-line))
5533 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5534 '(font-lock-fontified t face org-block))
5535 ; for backend-specific code
5537 ((and (match-end 4) (equal dc3 "+begin"))
5538 ;; Truly a block
5539 (setq block-type (downcase (match-string 5))
5540 quoting (member block-type org-protecting-blocks))
5541 (when (re-search-forward
5542 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5543 nil t) ;; on purpose, we look further than LIMIT
5544 (setq end (min (point-max) (match-end 0))
5545 end1 (min (point-max) (1- (match-beginning 0))))
5546 (setq block-end (match-beginning 0))
5547 (when quoting
5548 (remove-text-properties beg end
5549 '(display t invisible t intangible t)))
5550 (add-text-properties
5551 beg end
5552 '(font-lock-fontified t font-lock-multiline t))
5553 (add-text-properties beg beg1 '(face org-meta-line))
5554 (add-text-properties end1 (min (point-max) (1+ end))
5555 '(face org-meta-line)) ; for end_src
5556 (cond
5557 ((and lang (not (string= lang "")) org-src-fontify-natively)
5558 (org-src-font-lock-fontify-block lang block-start block-end)
5559 ;; remove old background overlays
5560 (mapc (lambda (ov)
5561 (if (eq (overlay-get ov 'face) 'org-block-background)
5562 (delete-overlay ov)))
5563 (overlays-at (/ (+ beg1 block-end) 2)))
5564 ;; add a background overlay
5565 (setq ovl (make-overlay beg1 block-end))
5566 (overlay-put ovl 'face 'org-block-background)
5567 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5568 (quoting
5569 (add-text-properties beg1 (min (point-max) (1+ end1))
5570 '(face org-block))) ; end of source block
5571 ((not org-fontify-quote-and-verse-blocks))
5572 ((string= block-type "quote")
5573 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5574 ((string= block-type "verse")
5575 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5576 (add-text-properties beg beg1 '(face org-block-begin-line))
5577 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5578 '(face org-block-end-line))
5580 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5581 (add-text-properties
5582 beg (match-end 3)
5583 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5584 '(font-lock-fontified t invisible t)
5585 '(font-lock-fontified t face org-document-info-keyword)))
5586 (add-text-properties
5587 (match-beginning 6) (1+ (match-end 6))
5588 (if (string-equal dc1 "+title:")
5589 '(font-lock-fontified t face org-document-title)
5590 '(font-lock-fontified t face org-document-info))))
5591 ((or (equal dc1 "+results")
5592 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5593 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5594 "+call:" "+header:" "+headers:" "+name:"))
5595 (and (match-end 4) (equal dc3 "+attr")))
5596 (add-text-properties
5597 beg (match-end 0)
5598 '(font-lock-fontified t face org-meta-line))
5600 ((member dc3 '(" " ""))
5601 (add-text-properties
5602 beg (match-end 0)
5603 '(font-lock-fontified t face font-lock-comment-face)))
5604 ((not (member (char-after beg) '(?\ ?\t)))
5605 ;; just any other in-buffer setting, but not indented
5606 (add-text-properties
5607 beg (match-end 0)
5608 '(font-lock-fontified t face org-meta-line))
5610 (t nil))))))
5612 (defun org-activate-angle-links (limit)
5613 "Run through the buffer and add overlays to links."
5614 (if (and (re-search-forward org-angle-link-re limit t)
5615 (not (org-in-src-block-p)))
5616 (progn
5617 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5618 (add-text-properties (match-beginning 0) (match-end 0)
5619 (list 'mouse-face 'highlight
5620 'keymap org-mouse-map))
5621 (org-rear-nonsticky-at (match-end 0))
5622 t)))
5624 (defun org-activate-footnote-links (limit)
5625 "Run through the buffer and add overlays to footnotes."
5626 (let ((fn (org-footnote-next-reference-or-definition limit)))
5627 (when fn
5628 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5629 (org-remove-flyspell-overlays-in beg end)
5630 (add-text-properties beg end
5631 (list 'mouse-face 'highlight
5632 'keymap org-mouse-map
5633 'help-echo
5634 (if (= (point-at-bol) beg)
5635 "Footnote definition"
5636 "Footnote reference")
5637 'font-lock-fontified t
5638 'font-lock-multiline t
5639 'face 'org-footnote))))))
5641 (defun org-activate-bracket-links (limit)
5642 "Run through the buffer and add overlays to bracketed links."
5643 (if (and (re-search-forward org-bracket-link-regexp limit t)
5644 (not (org-in-src-block-p)))
5645 (let* ((hl (org-match-string-no-properties 1))
5646 (help (concat "LINK: " hl))
5647 ;; FIXME: Above we should remove the escapes. But that
5648 ;; requires another match, protecting match data, a lot
5649 ;; of overhead for font-lock.
5650 (ip (org-maybe-intangible
5651 (list 'invisible 'org-link
5652 'keymap org-mouse-map 'mouse-face 'highlight
5653 'font-lock-multiline t 'help-echo help
5654 'htmlize-link `(:uri ,hl))))
5655 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5656 'font-lock-multiline t 'help-echo help
5657 'htmlize-link `(:uri ,hl))))
5658 ;; We need to remove the invisible property here. Table narrowing
5659 ;; may have made some of this invisible.
5660 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5661 (remove-text-properties (match-beginning 0) (match-end 0)
5662 '(invisible nil))
5663 (if (match-end 3)
5664 (progn
5665 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5666 (org-rear-nonsticky-at (match-beginning 3))
5667 (add-text-properties (match-beginning 3) (match-end 3) vp)
5668 (org-rear-nonsticky-at (match-end 3))
5669 (add-text-properties (match-end 3) (match-end 0) ip)
5670 (org-rear-nonsticky-at (match-end 0)))
5671 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5672 (org-rear-nonsticky-at (match-beginning 1))
5673 (add-text-properties (match-beginning 1) (match-end 1) vp)
5674 (org-rear-nonsticky-at (match-end 1))
5675 (add-text-properties (match-end 1) (match-end 0) ip)
5676 (org-rear-nonsticky-at (match-end 0)))
5677 t)))
5679 (defun org-activate-dates (limit)
5680 "Run through the buffer and add overlays to dates."
5681 (if (re-search-forward org-tsr-regexp-both limit t)
5682 (progn
5683 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5684 (add-text-properties (match-beginning 0) (match-end 0)
5685 (list 'mouse-face 'highlight
5686 'keymap org-mouse-map))
5687 (org-rear-nonsticky-at (match-end 0))
5688 (when org-display-custom-times
5689 (if (match-end 3)
5690 (org-display-custom-time (match-beginning 3) (match-end 3)))
5691 (org-display-custom-time (match-beginning 1) (match-end 1)))
5692 t)))
5694 (defvar org-target-link-regexp nil
5695 "Regular expression matching radio targets in plain text.")
5696 (make-variable-buffer-local 'org-target-link-regexp)
5697 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5698 "Regular expression matching a link target.")
5699 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5700 "Regular expression matching a radio target.")
5701 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5702 "Regular expression matching any target.")
5704 (defun org-activate-target-links (limit)
5705 "Run through the buffer and add overlays to target matches."
5706 (when org-target-link-regexp
5707 (let ((case-fold-search t))
5708 (if (re-search-forward org-target-link-regexp limit t)
5709 (progn
5710 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5711 (add-text-properties (match-beginning 0) (match-end 0)
5712 (list 'mouse-face 'highlight
5713 'keymap org-mouse-map
5714 'help-echo "Radio target link"
5715 'org-linked-text t))
5716 (org-rear-nonsticky-at (match-end 0))
5717 t)))))
5719 (defun org-update-radio-target-regexp ()
5720 "Find all radio targets in this file and update the regular expression."
5721 (interactive)
5722 (when (memq 'radio org-activate-links)
5723 (setq org-target-link-regexp
5724 (org-make-target-link-regexp (org-all-targets 'radio)))
5725 (org-restart-font-lock)))
5727 (defun org-hide-wide-columns (limit)
5728 (let (s e)
5729 (setq s (text-property-any (point) (or limit (point-max))
5730 'org-cwidth t))
5731 (when s
5732 (setq e (next-single-property-change s 'org-cwidth))
5733 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5734 (goto-char e)
5735 t)))
5737 (defvar org-latex-and-specials-regexp nil
5738 "Regular expression for highlighting export special stuff.")
5739 (defvar org-match-substring-regexp)
5740 (defvar org-match-substring-with-braces-regexp)
5742 ;; This should be with the exporter code, but we also use if for font-locking
5743 (defconst org-export-html-special-string-regexps
5744 '(("\\\\-" . "&shy;")
5745 ("---\\([^-]\\)" . "&mdash;\\1")
5746 ("--\\([^-]\\)" . "&ndash;\\1")
5747 ("\\.\\.\\." . "&hellip;"))
5748 "Regular expressions for special string conversion.")
5751 (defun org-compute-latex-and-specials-regexp ()
5752 "Compute regular expression for stuff treated specially by exporters."
5753 (if (not org-highlight-latex-fragments-and-specials)
5754 (org-set-local 'org-latex-and-specials-regexp nil)
5755 (require 'org-exp)
5756 (let*
5757 ((matchers (plist-get org-format-latex-options :matchers))
5758 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5759 org-latex-regexps)))
5760 (org-export-allow-BIND nil)
5761 (options (org-combine-plists (org-default-export-plist)
5762 (org-infile-export-plist)))
5763 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5764 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5765 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5766 (org-export-html-expand (plist-get options :expand-quoted-html))
5767 (org-export-with-special-strings (plist-get options :special-strings))
5768 (re-sub
5769 (cond
5770 ((equal org-export-with-sub-superscripts '{})
5771 (list org-match-substring-with-braces-regexp))
5772 (org-export-with-sub-superscripts
5773 (list org-match-substring-regexp))))
5774 (re-latex
5775 (if org-export-with-LaTeX-fragments
5776 (mapcar (lambda (x) (nth 1 x)) latexs)))
5777 (re-macros
5778 (if org-export-with-TeX-macros
5779 (list (concat "\\\\"
5780 (regexp-opt
5781 (append
5783 (delq nil
5784 (mapcar 'car-safe
5785 (append org-entities-user
5786 org-entities)))
5787 (if (boundp 'org-latex-entities)
5788 (mapcar (lambda (x)
5789 (or (car-safe x) x))
5790 org-latex-entities)
5791 nil))
5792 'words))) ; FIXME
5794 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5795 (re-special (if org-export-with-special-strings
5796 (mapcar (lambda (x) (car x))
5797 org-export-html-special-string-regexps)))
5798 (re-rest
5799 (delq nil
5800 (list
5801 (if org-export-html-expand "@<[^>\n]+>")
5802 ))))
5803 (org-set-local
5804 'org-latex-and-specials-regexp
5805 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5806 re-rest) "\\|")))))
5808 (defun org-do-latex-and-special-faces (limit)
5809 "Run through the buffer and add overlays to links."
5810 (when org-latex-and-specials-regexp
5811 (let (rtn d)
5812 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5813 limit t))
5814 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5815 'face))
5816 '(org-code org-verbatim underline)))
5817 (progn
5818 (setq rtn t
5819 d (cond ((member (char-after (1+ (match-beginning 0)))
5820 '(?_ ?^)) 1)
5821 (t 0)))
5822 (font-lock-prepend-text-property
5823 (+ d (match-beginning 0)) (match-end 0)
5824 'face 'org-latex-and-export-specials)
5825 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5826 '(font-lock-multiline t)))))
5827 rtn)))
5829 (defun org-restart-font-lock ()
5830 "Restart `font-lock-mode', to force refontification."
5831 (when (and (boundp 'font-lock-mode) font-lock-mode)
5832 (font-lock-mode -1)
5833 (font-lock-mode 1)))
5835 (defun org-all-targets (&optional radio)
5836 "Return a list of all targets in this file.
5837 When optional argument RADIO is non-nil, only find radio
5838 targets."
5839 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5840 (save-excursion
5841 (goto-char (point-min))
5842 (while (re-search-forward re nil t)
5843 ;; Make sure point is really within the object.
5844 (backward-char)
5845 (let ((obj (org-element-context)))
5846 (when (memq (org-element-type obj) '(radio-target target))
5847 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5848 rtn)))
5850 (defun org-make-target-link-regexp (targets)
5851 "Make regular expression matching all strings in TARGETS.
5852 The regular expression finds the targets also if there is a line break
5853 between words."
5854 (and targets
5855 (concat
5856 "\\<\\("
5857 (mapconcat
5858 (lambda (x)
5859 (setq x (regexp-quote x))
5860 (while (string-match " +" x)
5861 (setq x (replace-match "\\s-+" t t x)))
5863 targets
5864 "\\|")
5865 "\\)\\>")))
5867 (defun org-activate-tags (limit)
5868 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5869 (progn
5870 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5871 (add-text-properties (match-beginning 1) (match-end 1)
5872 (list 'mouse-face 'highlight
5873 'keymap org-mouse-map))
5874 (org-rear-nonsticky-at (match-end 1))
5875 t)))
5877 (defun org-outline-level ()
5878 "Compute the outline level of the heading at point.
5879 If this is called at a normal headline, the level is the number of stars.
5880 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5881 (save-excursion
5882 (if (not (condition-case nil
5883 (org-back-to-heading t)
5884 (error nil)))
5886 (looking-at org-outline-regexp)
5887 (1- (- (match-end 0) (match-beginning 0))))))
5889 (defvar org-font-lock-keywords nil)
5891 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5892 "Regular expression matching a property line.")
5894 (defvar org-font-lock-hook nil
5895 "Functions to be called for special font lock stuff.")
5897 (defvar org-font-lock-set-keywords-hook nil
5898 "Functions that can manipulate `org-font-lock-extra-keywords'.
5899 This is called after `org-font-lock-extra-keywords' is defined, but before
5900 it is installed to be used by font lock. This can be useful if something
5901 needs to be inserted at a specific position in the font-lock sequence.")
5903 (defun org-font-lock-hook (limit)
5904 "Run `org-font-lock-hook' within LIMIT."
5905 (run-hook-with-args 'org-font-lock-hook limit))
5907 (defun org-set-font-lock-defaults ()
5908 "Set font lock defaults for the current buffer."
5909 (let* ((em org-fontify-emphasized-text)
5910 (lk org-activate-links)
5911 (org-font-lock-extra-keywords
5912 (list
5913 ;; Call the hook
5914 '(org-font-lock-hook)
5915 ;; Headlines
5916 `(,(if org-fontify-whole-heading-line
5917 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5918 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5919 (1 (org-get-level-face 1))
5920 (2 (org-get-level-face 2))
5921 (3 (org-get-level-face 3)))
5922 ;; Table lines
5923 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5924 (1 'org-table t))
5925 ;; Table internals
5926 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5927 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5928 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5929 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5930 ;; Drawers
5931 (list org-drawer-regexp '(0 'org-special-keyword t))
5932 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5933 ;; Properties
5934 (list org-property-re
5935 '(1 'org-special-keyword t)
5936 '(3 'org-property-value t))
5937 ;; Links
5938 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5939 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5940 (if (memq 'plain lk) '(org-activate-plain-links))
5941 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5942 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5943 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5944 (if (memq 'footnote lk) '(org-activate-footnote-links))
5945 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5946 '(org-hide-wide-columns (0 nil append))
5947 ;; TODO keyword
5948 (list (format org-heading-keyword-regexp-format
5949 org-todo-regexp)
5950 '(2 (org-get-todo-face 2) t))
5951 ;; DONE
5952 (if org-fontify-done-headline
5953 (list (format org-heading-keyword-regexp-format
5954 (concat
5955 "\\(?:"
5956 (mapconcat 'regexp-quote org-done-keywords "\\|")
5957 "\\)"))
5958 '(2 'org-headline-done t))
5959 nil)
5960 ;; Priorities
5961 '(org-font-lock-add-priority-faces)
5962 ;; Tags
5963 '(org-font-lock-add-tag-faces)
5964 ;; Special keywords
5965 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5966 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5967 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5968 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5969 ;; Emphasis
5970 (if em
5971 (if (featurep 'xemacs)
5972 '(org-do-emphasis-faces (0 nil append))
5973 '(org-do-emphasis-faces)))
5974 ;; Checkboxes
5975 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5976 1 'org-checkbox prepend)
5977 (if (cdr (assq 'checkbox org-list-automatic-rules))
5978 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5979 (0 (org-get-checkbox-statistics-face) t)))
5980 ;; Description list items
5981 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5982 1 'org-list-dt prepend)
5983 ;; ARCHIVEd headings
5984 (list (concat
5985 org-outline-regexp-bol
5986 "\\(.*:" org-archive-tag ":.*\\)")
5987 '(1 'org-archived prepend))
5988 ;; Specials
5989 '(org-do-latex-and-special-faces)
5990 '(org-fontify-entities)
5991 '(org-raise-scripts)
5992 ;; Code
5993 '(org-activate-code (1 'org-code t))
5994 ;; COMMENT
5995 (list (format org-heading-keyword-regexp-format
5996 (concat "\\("
5997 org-comment-string "\\|" org-quote-string
5998 "\\)"))
5999 '(2 'org-special-keyword t))
6000 ;; Blocks and meta lines
6001 '(org-fontify-meta-lines-and-blocks)
6003 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6004 (run-hooks 'org-font-lock-set-keywords-hook)
6005 ;; Now set the full font-lock-keywords
6006 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6007 (org-set-local 'font-lock-defaults
6008 '(org-font-lock-keywords t nil nil backward-paragraph))
6009 (kill-local-variable 'font-lock-keywords) nil))
6011 (defun org-toggle-pretty-entities ()
6012 "Toggle the composition display of entities as UTF8 characters."
6013 (interactive)
6014 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6015 (org-restart-font-lock)
6016 (if org-pretty-entities
6017 (message "Entities are displayed as UTF8 characters")
6018 (save-restriction
6019 (widen)
6020 (org-decompose-region (point-min) (point-max))
6021 (message "Entities are displayed plain"))))
6023 (defvar org-custom-properties-overlays nil
6024 "List of overlays used for custom properties.")
6025 (make-variable-buffer-local 'org-custom-properties-overlays)
6027 (defun org-toggle-custom-properties-visibility ()
6028 "Display or hide properties in `org-custom-properties'."
6029 (interactive)
6030 (if org-custom-properties-overlays
6031 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6032 (setq org-custom-properties-overlays nil))
6033 (unless (not org-custom-properties)
6034 (save-excursion
6035 (save-restriction
6036 (widen)
6037 (goto-char (point-min))
6038 (while (re-search-forward org-property-re nil t)
6039 (mapc (lambda(p)
6040 (when (equal p (substring (match-string 1) 1 -1))
6041 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6042 (overlay-put o 'invisible t)
6043 (overlay-put o 'org-custom-property t)
6044 (push o org-custom-properties-overlays))))
6045 org-custom-properties)))))))
6047 (defun org-fontify-entities (limit)
6048 "Find an entity to fontify."
6049 (let (ee)
6050 (when org-pretty-entities
6051 (catch 'match
6052 (while (re-search-forward
6053 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6054 limit t)
6055 (if (and (not (org-in-indented-comment-line))
6056 (setq ee (org-entity-get (match-string 1)))
6057 (= (length (nth 6 ee)) 1))
6058 (let*
6059 ((end (if (equal (match-string 2) "{}")
6060 (match-end 2)
6061 (match-end 1))))
6062 (add-text-properties
6063 (match-beginning 0) end
6064 (list 'font-lock-fontified t))
6065 (compose-region (match-beginning 0) end
6066 (nth 6 ee) nil)
6067 (backward-char 1)
6068 (throw 'match t))))
6069 nil))))
6071 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6072 "Fontify string S like in Org-mode."
6073 (with-temp-buffer
6074 (insert s)
6075 (let ((org-odd-levels-only odd-levels))
6076 (org-mode)
6077 (font-lock-fontify-buffer)
6078 (buffer-string))))
6080 (defvar org-m nil)
6081 (defvar org-l nil)
6082 (defvar org-f nil)
6083 (defun org-get-level-face (n)
6084 "Get the right face for match N in font-lock matching of headlines."
6085 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6086 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6087 (if org-cycle-level-faces
6088 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6089 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6090 (cond
6091 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6092 ((eq n 2) org-f)
6093 (t (if org-level-color-stars-only nil org-f))))
6096 (defun org-get-todo-face (kwd)
6097 "Get the right face for a TODO keyword KWD.
6098 If KWD is a number, get the corresponding match group."
6099 (if (numberp kwd) (setq kwd (match-string kwd)))
6100 (or (org-face-from-face-or-color
6101 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6102 (and (member kwd org-done-keywords) 'org-done)
6103 'org-todo))
6105 (defun org-face-from-face-or-color (context inherit face-or-color)
6106 "Create a face list that inherits INHERIT, but sets the foreground color.
6107 When FACE-OR-COLOR is not a string, just return it."
6108 (if (stringp face-or-color)
6109 (list :inherit inherit
6110 (cdr (assoc context org-faces-easy-properties))
6111 face-or-color)
6112 face-or-color))
6114 (defun org-font-lock-add-tag-faces (limit)
6115 "Add the special tag faces."
6116 (when (and org-tag-faces org-tags-special-faces-re)
6117 (while (re-search-forward org-tags-special-faces-re limit t)
6118 (add-text-properties (match-beginning 1) (match-end 1)
6119 (list 'face (org-get-tag-face 1)
6120 'font-lock-fontified t))
6121 (backward-char 1))))
6123 (defun org-font-lock-add-priority-faces (limit)
6124 "Add the special priority faces."
6125 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6126 (when (save-match-data (org-at-heading-p))
6127 (add-text-properties
6128 (match-beginning 0) (match-end 0)
6129 (list 'face (or (org-face-from-face-or-color
6130 'priority 'org-special-keyword
6131 (cdr (assoc (char-after (match-beginning 1))
6132 org-priority-faces)))
6133 'org-special-keyword)
6134 'font-lock-fontified t)))))
6136 (defun org-get-tag-face (kwd)
6137 "Get the right face for a TODO keyword KWD.
6138 If KWD is a number, get the corresponding match group."
6139 (if (numberp kwd) (setq kwd (match-string kwd)))
6140 (or (org-face-from-face-or-color
6141 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6142 'org-tag))
6144 (defun org-unfontify-region (beg end &optional maybe_loudly)
6145 "Remove fontification and activation overlays from links."
6146 (font-lock-default-unfontify-region beg end)
6147 (let* ((buffer-undo-list t)
6148 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6149 (inhibit-modification-hooks t)
6150 deactivate-mark buffer-file-name buffer-file-truename)
6151 (org-decompose-region beg end)
6152 (remove-text-properties beg end
6153 '(mouse-face t keymap t org-linked-text t
6154 invisible t intangible t
6155 org-no-flyspell t org-emphasis t))
6156 (org-remove-font-lock-display-properties beg end)))
6158 (defconst org-script-display '(((raise -0.3) (height 0.7))
6159 ((raise 0.3) (height 0.7))
6160 ((raise -0.5))
6161 ((raise 0.5)))
6162 "Display properties for showing superscripts and subscripts.")
6164 (defun org-remove-font-lock-display-properties (beg end)
6165 "Remove specific display properties that have been added by font lock.
6166 The will remove the raise properties that are used to show superscripts
6167 and subscripts."
6168 (let (next prop)
6169 (while (< beg end)
6170 (setq next (next-single-property-change beg 'display nil end)
6171 prop (get-text-property beg 'display))
6172 (if (member prop org-script-display)
6173 (put-text-property beg next 'display nil))
6174 (setq beg next))))
6176 (defun org-raise-scripts (limit)
6177 "Add raise properties to sub/superscripts."
6178 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6179 (if (re-search-forward
6180 (if (eq org-use-sub-superscripts t)
6181 org-match-substring-regexp
6182 org-match-substring-with-braces-regexp)
6183 limit t)
6184 (let* ((pos (point)) table-p comment-p
6185 (mpos (match-beginning 3))
6186 (emph-p (get-text-property mpos 'org-emphasis))
6187 (link-p (get-text-property mpos 'mouse-face))
6188 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6189 (goto-char (point-at-bol))
6190 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6191 comment-p (org-looking-at-p "[ \t]*#"))
6192 (goto-char pos)
6193 ;; FIXME: Should we go back one character here, for a_b^c
6194 ;; (goto-char (1- pos)) ;????????????????????
6195 (if (or comment-p emph-p link-p keyw-p)
6197 (put-text-property (match-beginning 3) (match-end 0)
6198 'display
6199 (if (equal (char-after (match-beginning 2)) ?^)
6200 (nth (if table-p 3 1) org-script-display)
6201 (nth (if table-p 2 0) org-script-display)))
6202 (add-text-properties (match-beginning 2) (match-end 2)
6203 (list 'invisible t
6204 'org-dwidth t 'org-dwidth-n 1))
6205 (if (and (eq (char-after (match-beginning 3)) ?{)
6206 (eq (char-before (match-end 3)) ?}))
6207 (progn
6208 (add-text-properties
6209 (match-beginning 3) (1+ (match-beginning 3))
6210 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6211 (add-text-properties
6212 (1- (match-end 3)) (match-end 3)
6213 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6214 t)))))
6216 ;;;; Visibility cycling, including org-goto and indirect buffer
6218 ;;; Cycling
6220 (defvar org-cycle-global-status nil)
6221 (make-variable-buffer-local 'org-cycle-global-status)
6222 (defvar org-cycle-subtree-status nil)
6223 (make-variable-buffer-local 'org-cycle-subtree-status)
6225 (defvar org-inlinetask-min-level)
6227 ;;;###autoload
6228 (defun org-cycle (&optional arg)
6229 "TAB-action and visibility cycling for Org-mode.
6231 This is the command invoked in Org-mode by the TAB key. Its main purpose
6232 is outline visibility cycling, but it also invokes other actions
6233 in special contexts.
6235 - When this function is called with a prefix argument, rotate the entire
6236 buffer through 3 states (global cycling)
6237 1. OVERVIEW: Show only top-level headlines.
6238 2. CONTENTS: Show all headlines of all levels, but no body text.
6239 3. SHOW ALL: Show everything.
6240 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6241 determined by the variable `org-startup-folded', and by any VISIBILITY
6242 properties in the buffer.
6243 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6244 including any drawers.
6246 - When inside a table, re-align the table and move to the next field.
6248 - When point is at the beginning of a headline, rotate the subtree started
6249 by this line through 3 different states (local cycling)
6250 1. FOLDED: Only the main headline is shown.
6251 2. CHILDREN: The main headline and the direct children are shown.
6252 From this state, you can move to one of the children
6253 and zoom in further.
6254 3. SUBTREE: Show the entire subtree, including body text.
6255 If there is no subtree, switch directly from CHILDREN to FOLDED.
6257 - When point is at the beginning of an empty headline and the variable
6258 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6259 of the headline by demoting and promoting it to likely levels. This
6260 speeds up creation document structure by pressing TAB once or several
6261 times right after creating a new headline.
6263 - When there is a numeric prefix, go up to a heading with level ARG, do
6264 a `show-subtree' and return to the previous cursor position. If ARG
6265 is negative, go up that many levels.
6267 - When point is not at the beginning of a headline, execute the global
6268 binding for TAB, which is re-indenting the line. See the option
6269 `org-cycle-emulate-tab' for details.
6271 - Special case: if point is at the beginning of the buffer and there is
6272 no headline in line 1, this function will act as if called with prefix arg
6273 (C-u TAB, same as S-TAB) also when called without prefix arg.
6274 But only if also the variable `org-cycle-global-at-bob' is t."
6275 (interactive "P")
6276 (org-load-modules-maybe)
6277 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6278 (and org-cycle-level-after-item/entry-creation
6279 (or (org-cycle-level)
6280 (org-cycle-item-indentation))))
6281 (let* (message-log-max ; Don't populate the *Messages* buffer
6282 (limit-level
6283 (or org-cycle-max-level
6284 (and (boundp 'org-inlinetask-min-level)
6285 org-inlinetask-min-level
6286 (1- org-inlinetask-min-level))))
6287 (nstars (and limit-level
6288 (if org-odd-levels-only
6289 (and limit-level (1- (* limit-level 2)))
6290 limit-level)))
6291 (org-outline-regexp
6292 (if (not (derived-mode-p 'org-mode))
6293 outline-regexp
6294 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6295 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6296 (not (looking-at org-outline-regexp))))
6297 (org-cycle-hook
6298 (if bob-special
6299 (delq 'org-optimize-window-after-visibility-change
6300 (copy-sequence org-cycle-hook))
6301 org-cycle-hook))
6302 (pos (point)))
6304 (if (or bob-special (equal arg '(4)))
6305 ;; special case: use global cycling
6306 (setq arg t))
6308 (cond
6310 ((equal arg '(16))
6311 (setq last-command 'dummy)
6312 (org-set-startup-visibility)
6313 (message "Startup visibility, plus VISIBILITY properties"))
6315 ((equal arg '(64))
6316 (show-all)
6317 (message "Entire buffer visible, including drawers"))
6319 ;; Table: enter it or move to the next field.
6320 ((org-at-table-p 'any)
6321 (if (org-at-table.el-p)
6322 (message "Use C-c ' to edit table.el tables")
6323 (if arg (org-table-edit-field t)
6324 (org-table-justify-field-maybe)
6325 (call-interactively 'org-table-next-field))))
6327 ((run-hook-with-args-until-success
6328 'org-tab-after-check-for-table-hook))
6330 ;; Global cycling: delegate to `org-cycle-internal-global'.
6331 ((eq arg t) (org-cycle-internal-global))
6333 ;; Drawers: delegate to `org-flag-drawer'.
6334 ((and org-drawers org-drawer-regexp
6335 (save-excursion
6336 (beginning-of-line 1)
6337 (looking-at org-drawer-regexp)))
6338 (org-flag-drawer ; toggle block visibility
6339 (not (get-char-property (match-end 0) 'invisible))))
6341 ;; Show-subtree, ARG levels up from here.
6342 ((integerp arg)
6343 (save-excursion
6344 (org-back-to-heading)
6345 (outline-up-heading (if (< arg 0) (- arg)
6346 (- (funcall outline-level) arg)))
6347 (org-show-subtree)))
6349 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6350 ((and (featurep 'org-inlinetask)
6351 (org-inlinetask-at-task-p)
6352 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6353 (org-inlinetask-toggle-visibility))
6355 ((org-try-cdlatex-tab))
6357 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6358 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6359 (save-excursion (beginning-of-line 1)
6360 (looking-at org-outline-regexp)))
6361 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6362 (org-cycle-internal-local))
6364 ;; From there: TAB emulation and template completion.
6365 (buffer-read-only (org-back-to-heading))
6367 ((run-hook-with-args-until-success
6368 'org-tab-after-check-for-cycling-hook))
6370 ((org-try-structure-completion))
6372 ((run-hook-with-args-until-success
6373 'org-tab-before-tab-emulation-hook))
6375 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6376 (or (not (bolp))
6377 (not (looking-at org-outline-regexp))))
6378 (call-interactively (global-key-binding "\t")))
6380 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6381 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6382 (or (and (eq org-cycle-emulate-tab 'white)
6383 (= (match-end 0) (point-at-eol)))
6384 (and (eq org-cycle-emulate-tab 'whitestart)
6385 (>= (match-end 0) pos))))
6387 (eq org-cycle-emulate-tab t))
6388 (call-interactively (global-key-binding "\t")))
6390 (t (save-excursion
6391 (org-back-to-heading)
6392 (org-cycle)))))))
6394 (defun org-cycle-internal-global ()
6395 "Do the global cycling action."
6396 ;; Hack to avoid display of messages for .org attachments in Gnus
6397 (let (message-log-max ; Don't populate the *Messages* buffer
6398 (ga (string-match "\\*fontification" (buffer-name))))
6399 (cond
6400 ((and (eq last-command this-command)
6401 (eq org-cycle-global-status 'overview))
6402 ;; We just created the overview - now do table of contents
6403 ;; This can be slow in very large buffers, so indicate action
6404 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6405 (unless ga (message "CONTENTS..."))
6406 (org-content)
6407 (unless ga (message "CONTENTS...done"))
6408 (setq org-cycle-global-status 'contents)
6409 (run-hook-with-args 'org-cycle-hook 'contents))
6411 ((and (eq last-command this-command)
6412 (eq org-cycle-global-status 'contents))
6413 ;; We just showed the table of contents - now show everything
6414 (run-hook-with-args 'org-pre-cycle-hook 'all)
6415 (show-all)
6416 (unless ga (message "SHOW ALL"))
6417 (setq org-cycle-global-status 'all)
6418 (run-hook-with-args 'org-cycle-hook 'all))
6421 ;; Default action: go to overview
6422 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6423 (org-overview)
6424 (unless ga (message "OVERVIEW"))
6425 (setq org-cycle-global-status 'overview)
6426 (run-hook-with-args 'org-cycle-hook 'overview)))))
6428 (defun org-cycle-internal-local ()
6429 "Do the local cycling action."
6430 (let (message-log-max ; Don't populate the *Messages* buffer
6431 (goal-column 0) eoh eol eos has-children children-skipped struct)
6432 ;; First, determine end of headline (EOH), end of subtree or item
6433 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6434 (save-excursion
6435 (if (org-at-item-p)
6436 (progn
6437 (beginning-of-line)
6438 (setq struct (org-list-struct))
6439 (setq eoh (point-at-eol))
6440 (setq eos (org-list-get-item-end-before-blank (point) struct))
6441 (setq has-children (org-list-has-child-p (point) struct)))
6442 (org-back-to-heading)
6443 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6444 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6445 (setq has-children
6446 (or (save-excursion
6447 (let ((level (funcall outline-level)))
6448 (outline-next-heading)
6449 (and (org-at-heading-p t)
6450 (> (funcall outline-level) level))))
6451 (save-excursion
6452 (org-list-search-forward (org-item-beginning-re) eos t)))))
6453 ;; Determine end invisible part of buffer (EOL)
6454 (beginning-of-line 2)
6455 ;; XEmacs doesn't have `next-single-char-property-change'
6456 (if (featurep 'xemacs)
6457 (while (and (not (eobp)) ;; this is like `next-line'
6458 (get-char-property (1- (point)) 'invisible))
6459 (beginning-of-line 2))
6460 (while (and (not (eobp)) ;; this is like `next-line'
6461 (get-char-property (1- (point)) 'invisible))
6462 (goto-char (next-single-char-property-change (point) 'invisible))
6463 (and (eolp) (beginning-of-line 2))))
6464 (setq eol (point)))
6465 ;; Find out what to do next and set `this-command'
6466 (cond
6467 ((= eos eoh)
6468 ;; Nothing is hidden behind this heading
6469 (unless (org-before-first-heading-p)
6470 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6471 (message "EMPTY ENTRY")
6472 (setq org-cycle-subtree-status nil)
6473 (save-excursion
6474 (goto-char eos)
6475 (outline-next-heading)
6476 (if (outline-invisible-p) (org-flag-heading nil))))
6477 ((and (or (>= eol eos)
6478 (not (string-match "\\S-" (buffer-substring eol eos))))
6479 (or has-children
6480 (not (setq children-skipped
6481 org-cycle-skip-children-state-if-no-children))))
6482 ;; Entire subtree is hidden in one line: children view
6483 (unless (org-before-first-heading-p)
6484 (run-hook-with-args 'org-pre-cycle-hook 'children))
6485 (if (org-at-item-p)
6486 (org-list-set-item-visibility (point-at-bol) struct 'children)
6487 (org-show-entry)
6488 (org-with-limited-levels (show-children))
6489 ;; FIXME: This slows down the func way too much.
6490 ;; How keep drawers hidden in subtree anyway?
6491 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6492 ;; (org-cycle-hide-drawers 'subtree))
6494 ;; Fold every list in subtree to top-level items.
6495 (when (eq org-cycle-include-plain-lists 'integrate)
6496 (save-excursion
6497 (org-back-to-heading)
6498 (while (org-list-search-forward (org-item-beginning-re) eos t)
6499 (beginning-of-line 1)
6500 (let* ((struct (org-list-struct))
6501 (prevs (org-list-prevs-alist struct))
6502 (end (org-list-get-bottom-point struct)))
6503 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6504 (org-list-get-all-items (point) struct prevs))
6505 (goto-char end))))))
6506 (message "CHILDREN")
6507 (save-excursion
6508 (goto-char eos)
6509 (outline-next-heading)
6510 (if (outline-invisible-p) (org-flag-heading nil)))
6511 (setq org-cycle-subtree-status 'children)
6512 (unless (org-before-first-heading-p)
6513 (run-hook-with-args 'org-cycle-hook 'children)))
6514 ((or children-skipped
6515 (and (eq last-command this-command)
6516 (eq org-cycle-subtree-status 'children)))
6517 ;; We just showed the children, or no children are there,
6518 ;; now show everything.
6519 (unless (org-before-first-heading-p)
6520 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6521 (outline-flag-region eoh eos nil)
6522 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6523 (setq org-cycle-subtree-status 'subtree)
6524 (unless (org-before-first-heading-p)
6525 (run-hook-with-args 'org-cycle-hook 'subtree)))
6527 ;; Default action: hide the subtree.
6528 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6529 (outline-flag-region eoh eos t)
6530 (message "FOLDED")
6531 (setq org-cycle-subtree-status 'folded)
6532 (unless (org-before-first-heading-p)
6533 (run-hook-with-args 'org-cycle-hook 'folded))))))
6535 ;;;###autoload
6536 (defun org-global-cycle (&optional arg)
6537 "Cycle the global visibility. For details see `org-cycle'.
6538 With \\[universal-argument] prefix arg, switch to startup visibility.
6539 With a numeric prefix, show all headlines up to that level."
6540 (interactive "P")
6541 (let ((org-cycle-include-plain-lists
6542 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6543 (cond
6544 ((integerp arg)
6545 (show-all)
6546 (hide-sublevels arg)
6547 (setq org-cycle-global-status 'contents))
6548 ((equal arg '(4))
6549 (org-set-startup-visibility)
6550 (message "Startup visibility, plus VISIBILITY properties."))
6552 (org-cycle '(4))))))
6554 (defun org-set-startup-visibility ()
6555 "Set the visibility required by startup options and properties."
6556 (cond
6557 ((eq org-startup-folded t)
6558 (org-cycle '(4)))
6559 ((eq org-startup-folded 'content)
6560 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6561 (org-cycle '(4)) (org-cycle '(4)))))
6562 (unless (eq org-startup-folded 'showeverything)
6563 (if org-hide-block-startup (org-hide-block-all))
6564 (org-set-visibility-according-to-property 'no-cleanup)
6565 (org-cycle-hide-archived-subtrees 'all)
6566 (org-cycle-hide-drawers 'all)
6567 (org-cycle-show-empty-lines t)))
6569 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6570 "Switch subtree visibilities according to :VISIBILITY: property."
6571 (interactive)
6572 (let (org-show-entry-below state)
6573 (save-excursion
6574 (goto-char (point-min))
6575 (while (re-search-forward
6576 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6577 nil t)
6578 (setq state (match-string 1))
6579 (save-excursion
6580 (org-back-to-heading t)
6581 (hide-subtree)
6582 (org-reveal)
6583 (cond
6584 ((equal state '("fold" "folded"))
6585 (hide-subtree))
6586 ((equal state "children")
6587 (org-show-hidden-entry)
6588 (show-children))
6589 ((equal state "content")
6590 (save-excursion
6591 (save-restriction
6592 (org-narrow-to-subtree)
6593 (org-content))))
6594 ((member state '("all" "showall"))
6595 (show-subtree)))))
6596 (unless no-cleanup
6597 (org-cycle-hide-archived-subtrees 'all)
6598 (org-cycle-hide-drawers 'all)
6599 (org-cycle-show-empty-lines 'all)))))
6601 ;; This function uses outline-regexp instead of the more fundamental
6602 ;; org-outline-regexp so that org-cycle-global works outside of Org
6603 ;; buffers, where outline-regexp is needed.
6604 (defun org-overview ()
6605 "Switch to overview mode, showing only top-level headlines.
6606 Really, this shows all headlines with level equal or greater than the level
6607 of the first headline in the buffer. This is important, because if the
6608 first headline is not level one, then (hide-sublevels 1) gives confusing
6609 results."
6610 (interactive)
6611 (let ((level (save-excursion
6612 (goto-char (point-min))
6613 (if (re-search-forward (concat "^" outline-regexp) nil t)
6614 (progn
6615 (goto-char (match-beginning 0))
6616 (funcall outline-level))))))
6617 (and level (hide-sublevels level))))
6619 (defun org-content (&optional arg)
6620 "Show all headlines in the buffer, like a table of contents.
6621 With numerical argument N, show content up to level N."
6622 (interactive "P")
6623 (save-excursion
6624 ;; Visit all headings and show their offspring
6625 (and (integerp arg) (org-overview))
6626 (goto-char (point-max))
6627 (catch 'exit
6628 (while (and (progn (condition-case nil
6629 (outline-previous-visible-heading 1)
6630 (error (goto-char (point-min))))
6632 (looking-at org-outline-regexp))
6633 (if (integerp arg)
6634 (show-children (1- arg))
6635 (show-branches))
6636 (if (bobp) (throw 'exit nil))))))
6639 (defun org-optimize-window-after-visibility-change (state)
6640 "Adjust the window after a change in outline visibility.
6641 This function is the default value of the hook `org-cycle-hook'."
6642 (when (get-buffer-window (current-buffer))
6643 (cond
6644 ((eq state 'content) nil)
6645 ((eq state 'all) nil)
6646 ((eq state 'folded) nil)
6647 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6648 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6650 (defun org-remove-empty-overlays-at (pos)
6651 "Remove outline overlays that do not contain non-white stuff."
6652 (mapc
6653 (lambda (o)
6654 (and (eq 'outline (overlay-get o 'invisible))
6655 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6656 (overlay-end o))))
6657 (delete-overlay o)))
6658 (overlays-at pos)))
6660 (defun org-clean-visibility-after-subtree-move ()
6661 "Fix visibility issues after moving a subtree."
6662 ;; First, find a reasonable region to look at:
6663 ;; Start two siblings above, end three below
6664 (let* ((beg (save-excursion
6665 (and (org-get-last-sibling)
6666 (org-get-last-sibling))
6667 (point)))
6668 (end (save-excursion
6669 (and (org-get-next-sibling)
6670 (org-get-next-sibling)
6671 (org-get-next-sibling))
6672 (if (org-at-heading-p)
6673 (point-at-eol)
6674 (point))))
6675 (level (looking-at "\\*+"))
6676 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6677 (save-excursion
6678 (save-restriction
6679 (narrow-to-region beg end)
6680 (when re
6681 ;; Properly fold already folded siblings
6682 (goto-char (point-min))
6683 (while (re-search-forward re nil t)
6684 (if (and (not (outline-invisible-p))
6685 (save-excursion
6686 (goto-char (point-at-eol)) (outline-invisible-p)))
6687 (hide-entry))))
6688 (org-cycle-show-empty-lines 'overview)
6689 (org-cycle-hide-drawers 'overview)))))
6691 (defun org-cycle-show-empty-lines (state)
6692 "Show empty lines above all visible headlines.
6693 The region to be covered depends on STATE when called through
6694 `org-cycle-hook'. Lisp program can use t for STATE to get the
6695 entire buffer covered. Note that an empty line is only shown if there
6696 are at least `org-cycle-separator-lines' empty lines before the headline."
6697 (when (not (= org-cycle-separator-lines 0))
6698 (save-excursion
6699 (let* ((n (abs org-cycle-separator-lines))
6700 (re (cond
6701 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6702 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6703 (t (let ((ns (number-to-string (- n 2))))
6704 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6705 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6706 beg end b e)
6707 (cond
6708 ((memq state '(overview contents t))
6709 (setq beg (point-min) end (point-max)))
6710 ((memq state '(children folded))
6711 (setq beg (point) end (progn (org-end-of-subtree t t)
6712 (beginning-of-line 2)
6713 (point)))))
6714 (when beg
6715 (goto-char beg)
6716 (while (re-search-forward re end t)
6717 (unless (get-char-property (match-end 1) 'invisible)
6718 (setq e (match-end 1))
6719 (if (< org-cycle-separator-lines 0)
6720 (setq b (save-excursion
6721 (goto-char (match-beginning 0))
6722 (org-back-over-empty-lines)
6723 (if (save-excursion
6724 (goto-char (max (point-min) (1- (point))))
6725 (org-at-heading-p))
6726 (1- (point))
6727 (point))))
6728 (setq b (match-beginning 1)))
6729 (outline-flag-region b e nil)))))))
6730 ;; Never hide empty lines at the end of the file.
6731 (save-excursion
6732 (goto-char (point-max))
6733 (outline-previous-heading)
6734 (outline-end-of-heading)
6735 (if (and (looking-at "[ \t\n]+")
6736 (= (match-end 0) (point-max)))
6737 (outline-flag-region (point) (match-end 0) nil))))
6739 (defun org-show-empty-lines-in-parent ()
6740 "Move to the parent and re-show empty lines before visible headlines."
6741 (save-excursion
6742 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6743 (org-cycle-show-empty-lines context))))
6745 (defun org-files-list ()
6746 "Return `org-agenda-files' list, plus all open org-mode files.
6747 This is useful for operations that need to scan all of a user's
6748 open and agenda-wise Org files."
6749 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6750 (dolist (buf (buffer-list))
6751 (with-current-buffer buf
6752 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6753 (let ((file (expand-file-name (buffer-file-name))))
6754 (unless (member file files)
6755 (push file files))))))
6756 files))
6758 (defsubst org-entry-beginning-position ()
6759 "Return the beginning position of the current entry."
6760 (save-excursion (outline-back-to-heading t) (point)))
6762 (defsubst org-entry-end-position ()
6763 "Return the end position of the current entry."
6764 (save-excursion (outline-next-heading) (point)))
6766 (defun org-cycle-hide-drawers (state)
6767 "Re-hide all drawers after a visibility state change."
6768 (when (and (derived-mode-p 'org-mode)
6769 (not (memq state '(overview folded contents))))
6770 (save-excursion
6771 (let* ((globalp (memq state '(contents all)))
6772 (beg (if globalp (point-min) (point)))
6773 (end (if globalp (point-max)
6774 (if (eq state 'children)
6775 (save-excursion (outline-next-heading) (point))
6776 (org-end-of-subtree t)))))
6777 (goto-char beg)
6778 (while (re-search-forward org-drawer-regexp end t)
6779 (org-flag-drawer t))))))
6781 (defun org-cycle-hide-inline-tasks (state)
6782 "Re-hide inline task when switching to 'contents visibility state."
6783 (when (and (eq state 'contents)
6784 (boundp 'org-inlinetask-min-level)
6785 org-inlinetask-min-level)
6786 (hide-sublevels (1- org-inlinetask-min-level))))
6788 (defun org-flag-drawer (flag)
6789 "When FLAG is non-nil, hide the drawer we are within.
6790 Otherwise make it visible."
6791 (save-excursion
6792 (beginning-of-line 1)
6793 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6794 (let ((b (match-end 0)))
6795 (if (re-search-forward
6796 "^[ \t]*:END:"
6797 (save-excursion (outline-next-heading) (point)) t)
6798 (outline-flag-region b (point-at-eol) flag)
6799 (error ":END: line missing at position %s" b))))))
6801 (defun org-subtree-end-visible-p ()
6802 "Is the end of the current subtree visible?"
6803 (pos-visible-in-window-p
6804 (save-excursion (org-end-of-subtree t) (point))))
6806 (defun org-first-headline-recenter (&optional N)
6807 "Move cursor to the first headline and recenter the headline.
6808 Optional argument N means put the headline into the Nth line of the window."
6809 (goto-char (point-min))
6810 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6811 (beginning-of-line)
6812 (recenter (prefix-numeric-value N))))
6814 ;;; Saving and restoring visibility
6816 (defun org-outline-overlay-data (&optional use-markers)
6817 "Return a list of the locations of all outline overlays.
6818 These are overlays with the `invisible' property value `outline'.
6819 The return value is a list of cons cells, with start and stop
6820 positions for each overlay.
6821 If USE-MARKERS is set, return the positions as markers."
6822 (let (beg end)
6823 (save-excursion
6824 (save-restriction
6825 (widen)
6826 (delq nil
6827 (mapcar (lambda (o)
6828 (when (eq (overlay-get o 'invisible) 'outline)
6829 (setq beg (overlay-start o)
6830 end (overlay-end o))
6831 (and beg end (> end beg)
6832 (if use-markers
6833 (cons (move-marker (make-marker) beg)
6834 (move-marker (make-marker) end))
6835 (cons beg end)))))
6836 (overlays-in (point-min) (point-max))))))))
6838 (defun org-set-outline-overlay-data (data)
6839 "Create visibility overlays for all positions in DATA.
6840 DATA should have been made by `org-outline-overlay-data'."
6841 (let (o)
6842 (save-excursion
6843 (save-restriction
6844 (widen)
6845 (show-all)
6846 (mapc (lambda (c)
6847 (outline-flag-region (car c) (cdr c) t))
6848 data)))))
6850 ;;; Folding of blocks
6852 (defvar org-hide-block-overlays nil
6853 "Overlays hiding blocks.")
6854 (make-variable-buffer-local 'org-hide-block-overlays)
6856 (defun org-block-map (function &optional start end)
6857 "Call FUNCTION at the head of all source blocks in the current buffer.
6858 Optional arguments START and END can be used to limit the range."
6859 (let ((start (or start (point-min)))
6860 (end (or end (point-max))))
6861 (save-excursion
6862 (goto-char start)
6863 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6864 (save-excursion
6865 (save-match-data
6866 (goto-char (match-beginning 0))
6867 (funcall function)))))))
6869 (defun org-hide-block-toggle-all ()
6870 "Toggle the visibility of all blocks in the current buffer."
6871 (org-block-map #'org-hide-block-toggle))
6873 (defun org-hide-block-all ()
6874 "Fold all blocks in the current buffer."
6875 (interactive)
6876 (org-show-block-all)
6877 (org-block-map #'org-hide-block-toggle-maybe))
6879 (defun org-show-block-all ()
6880 "Unfold all blocks in the current buffer."
6881 (interactive)
6882 (mapc 'delete-overlay org-hide-block-overlays)
6883 (setq org-hide-block-overlays nil))
6885 (defun org-hide-block-toggle-maybe ()
6886 "Toggle visibility of block at point."
6887 (interactive)
6888 (let ((case-fold-search t))
6889 (if (save-excursion
6890 (beginning-of-line 1)
6891 (looking-at org-block-regexp))
6892 (progn (org-hide-block-toggle)
6893 t) ;; to signal that we took action
6894 nil))) ;; to signal that we did not
6896 (defun org-hide-block-toggle (&optional force)
6897 "Toggle the visibility of the current block."
6898 (interactive)
6899 (save-excursion
6900 (beginning-of-line)
6901 (if (re-search-forward org-block-regexp nil t)
6902 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6903 (end (match-end 0)) ;; end of entire body
6905 (if (memq t (mapcar (lambda (overlay)
6906 (eq (overlay-get overlay 'invisible)
6907 'org-hide-block))
6908 (overlays-at start)))
6909 (if (or (not force) (eq force 'off))
6910 (mapc (lambda (ov)
6911 (when (member ov org-hide-block-overlays)
6912 (setq org-hide-block-overlays
6913 (delq ov org-hide-block-overlays)))
6914 (when (eq (overlay-get ov 'invisible)
6915 'org-hide-block)
6916 (delete-overlay ov)))
6917 (overlays-at start)))
6918 (setq ov (make-overlay start end))
6919 (overlay-put ov 'invisible 'org-hide-block)
6920 ;; make the block accessible to isearch
6921 (overlay-put
6922 ov 'isearch-open-invisible
6923 (lambda (ov)
6924 (when (member ov org-hide-block-overlays)
6925 (setq org-hide-block-overlays
6926 (delq ov org-hide-block-overlays)))
6927 (when (eq (overlay-get ov 'invisible)
6928 'org-hide-block)
6929 (delete-overlay ov))))
6930 (push ov org-hide-block-overlays)))
6931 (error "Not looking at a source block"))))
6933 ;; org-tab-after-check-for-cycling-hook
6934 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6935 ;; Remove overlays when changing major mode
6936 (add-hook 'org-mode-hook
6937 (lambda () (org-add-hook 'change-major-mode-hook
6938 'org-show-block-all 'append 'local)))
6940 ;;; Org-goto
6942 (defvar org-goto-window-configuration nil)
6943 (defvar org-goto-marker nil)
6944 (defvar org-goto-map)
6945 (defun org-goto-map ()
6946 "Set the keymap `org-goto'."
6947 (setq org-goto-map
6948 (let ((map (make-sparse-keymap)))
6949 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6950 mouse-drag-region universal-argument org-occur))
6951 cmd)
6952 (while (setq cmd (pop cmds))
6953 (substitute-key-definition cmd cmd map global-map)))
6954 (suppress-keymap map)
6955 (org-defkey map "\C-m" 'org-goto-ret)
6956 (org-defkey map [(return)] 'org-goto-ret)
6957 (org-defkey map [(left)] 'org-goto-left)
6958 (org-defkey map [(right)] 'org-goto-right)
6959 (org-defkey map [(control ?g)] 'org-goto-quit)
6960 (org-defkey map "\C-i" 'org-cycle)
6961 (org-defkey map [(tab)] 'org-cycle)
6962 (org-defkey map [(down)] 'outline-next-visible-heading)
6963 (org-defkey map [(up)] 'outline-previous-visible-heading)
6964 (if org-goto-auto-isearch
6965 (if (fboundp 'define-key-after)
6966 (define-key-after map [t] 'org-goto-local-auto-isearch)
6967 nil)
6968 (org-defkey map "q" 'org-goto-quit)
6969 (org-defkey map "n" 'outline-next-visible-heading)
6970 (org-defkey map "p" 'outline-previous-visible-heading)
6971 (org-defkey map "f" 'outline-forward-same-level)
6972 (org-defkey map "b" 'outline-backward-same-level)
6973 (org-defkey map "u" 'outline-up-heading))
6974 (org-defkey map "/" 'org-occur)
6975 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6976 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6977 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6978 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6979 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6980 map)))
6982 (defconst org-goto-help
6983 "Browse buffer copy, to find location or copy text.%s
6984 RET=jump to location C-g=quit and return to previous location
6985 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6987 (defvar org-goto-start-pos) ; dynamically scoped parameter
6989 ;; FIXME: Docstring does not mention both interfaces
6990 (defun org-goto (&optional alternative-interface)
6991 "Look up a different location in the current file, keeping current visibility.
6993 When you want look-up or go to a different location in a
6994 document, the fastest way is often to fold the entire buffer and
6995 then dive into the tree. This method has the disadvantage, that
6996 the previous location will be folded, which may not be what you
6997 want.
6999 This command works around this by showing a copy of the current
7000 buffer in an indirect buffer, in overview mode. You can dive
7001 into the tree in that copy, use org-occur and incremental search
7002 to find a location. When pressing RET or `Q', the command
7003 returns to the original buffer in which the visibility is still
7004 unchanged. After RET it will also jump to the location selected
7005 in the indirect buffer and expose the headline hierarchy above.
7007 With a prefix argument, use the alternative interface: e.g. if
7008 `org-goto-interface' is 'outline use 'outline-path-completion."
7009 (interactive "P")
7010 (org-goto-map)
7011 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7012 (org-refile-use-outline-path t)
7013 (org-refile-target-verify-function nil)
7014 (interface
7015 (if (not alternative-interface)
7016 org-goto-interface
7017 (if (eq org-goto-interface 'outline)
7018 'outline-path-completion
7019 'outline)))
7020 (org-goto-start-pos (point))
7021 (selected-point
7022 (if (eq interface 'outline)
7023 (car (org-get-location (current-buffer) org-goto-help))
7024 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7025 (org-refile-check-position pa)
7026 (nth 3 pa)))))
7027 (if selected-point
7028 (progn
7029 (org-mark-ring-push org-goto-start-pos)
7030 (goto-char selected-point)
7031 (if (or (outline-invisible-p) (org-invisible-p2))
7032 (org-show-context 'org-goto)))
7033 (message "Quit"))))
7035 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7036 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7037 (defvar org-goto-local-auto-isearch-map) ; defined below
7039 (defun org-get-location (buf help)
7040 "Let the user select a location in the Org-mode buffer BUF.
7041 This function uses a recursive edit. It returns the selected position
7042 or nil."
7043 (org-no-popups
7044 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7045 (isearch-hide-immediately nil)
7046 (isearch-search-fun-function
7047 (lambda () 'org-goto-local-search-headings))
7048 (org-goto-selected-point org-goto-exit-command))
7049 (save-excursion
7050 (save-window-excursion
7051 (delete-other-windows)
7052 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7053 (org-pop-to-buffer-same-window
7054 (condition-case nil
7055 (make-indirect-buffer (current-buffer) "*org-goto*")
7056 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7057 (with-output-to-temp-buffer "*Org Help*"
7058 (princ (format help (if org-goto-auto-isearch
7059 " Just type for auto-isearch."
7060 " n/p/f/b/u to navigate, q to quit."))))
7061 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7062 (setq buffer-read-only nil)
7063 (let ((org-startup-truncated t)
7064 (org-startup-folded nil)
7065 (org-startup-align-all-tables nil))
7066 (org-mode)
7067 (org-overview))
7068 (setq buffer-read-only t)
7069 (if (and (boundp 'org-goto-start-pos)
7070 (integer-or-marker-p org-goto-start-pos))
7071 (let ((org-show-hierarchy-above t)
7072 (org-show-siblings t)
7073 (org-show-following-heading t))
7074 (goto-char org-goto-start-pos)
7075 (and (outline-invisible-p) (org-show-context)))
7076 (goto-char (point-min)))
7077 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7078 (message "Select location and press RET")
7079 (use-local-map org-goto-map)
7080 (recursive-edit)))
7081 (kill-buffer "*org-goto*")
7082 (cons org-goto-selected-point org-goto-exit-command))))
7084 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7085 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7086 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7087 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7089 (defun org-goto-local-search-headings (string bound noerror)
7090 "Search and make sure that any matches are in headlines."
7091 (catch 'return
7092 (while (if isearch-forward
7093 (search-forward string bound noerror)
7094 (search-backward string bound noerror))
7095 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7096 (and (member :headline context)
7097 (not (member :tags context))))
7098 (throw 'return (point))))))
7100 (defun org-goto-local-auto-isearch ()
7101 "Start isearch."
7102 (interactive)
7103 (goto-char (point-min))
7104 (let ((keys (this-command-keys)))
7105 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7106 (isearch-mode t)
7107 (isearch-process-search-char (string-to-char keys)))))
7109 (defun org-goto-ret (&optional arg)
7110 "Finish `org-goto' by going to the new location."
7111 (interactive "P")
7112 (setq org-goto-selected-point (point)
7113 org-goto-exit-command 'return)
7114 (throw 'exit nil))
7116 (defun org-goto-left ()
7117 "Finish `org-goto' by going to the new location."
7118 (interactive)
7119 (if (org-at-heading-p)
7120 (progn
7121 (beginning-of-line 1)
7122 (setq org-goto-selected-point (point)
7123 org-goto-exit-command 'left)
7124 (throw 'exit nil))
7125 (error "Not on a heading")))
7127 (defun org-goto-right ()
7128 "Finish `org-goto' by going to the new location."
7129 (interactive)
7130 (if (org-at-heading-p)
7131 (progn
7132 (setq org-goto-selected-point (point)
7133 org-goto-exit-command 'right)
7134 (throw 'exit nil))
7135 (error "Not on a heading")))
7137 (defun org-goto-quit ()
7138 "Finish `org-goto' without cursor motion."
7139 (interactive)
7140 (setq org-goto-selected-point nil)
7141 (setq org-goto-exit-command 'quit)
7142 (throw 'exit nil))
7144 ;;; Indirect buffer display of subtrees
7146 (defvar org-indirect-dedicated-frame nil
7147 "This is the frame being used for indirect tree display.")
7148 (defvar org-last-indirect-buffer nil)
7150 (defun org-tree-to-indirect-buffer (&optional arg)
7151 "Create indirect buffer and narrow it to current subtree.
7152 With a numerical prefix ARG, go up to this level and then take that tree.
7153 If ARG is negative, go up that many levels.
7155 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7156 indirect buffer previously made with this command, to avoid proliferation of
7157 indirect buffers. However, when you call the command with a \
7158 \\[universal-argument] prefix, or
7159 when `org-indirect-buffer-display' is `new-frame', the last buffer
7160 is kept so that you can work with several indirect buffers at the same time.
7161 If `org-indirect-buffer-display' is `dedicated-frame', the \
7162 \\[universal-argument] prefix also
7163 requests that a new frame be made for the new buffer, so that the dedicated
7164 frame is not changed."
7165 (interactive "P")
7166 (let ((cbuf (current-buffer))
7167 (cwin (selected-window))
7168 (pos (point))
7169 beg end level heading ibuf)
7170 (save-excursion
7171 (org-back-to-heading t)
7172 (when (numberp arg)
7173 (setq level (org-outline-level))
7174 (if (< arg 0) (setq arg (+ level arg)))
7175 (while (> (setq level (org-outline-level)) arg)
7176 (org-up-heading-safe)))
7177 (setq beg (point)
7178 heading (org-get-heading))
7179 (org-end-of-subtree t t)
7180 (if (org-at-heading-p) (backward-char 1))
7181 (setq end (point)))
7182 (if (and (buffer-live-p org-last-indirect-buffer)
7183 (not (eq org-indirect-buffer-display 'new-frame))
7184 (not arg))
7185 (kill-buffer org-last-indirect-buffer))
7186 (setq ibuf (org-get-indirect-buffer cbuf)
7187 org-last-indirect-buffer ibuf)
7188 (cond
7189 ((or (eq org-indirect-buffer-display 'new-frame)
7190 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7191 (select-frame (make-frame))
7192 (delete-other-windows)
7193 (org-pop-to-buffer-same-window ibuf)
7194 (org-set-frame-title heading))
7195 ((eq org-indirect-buffer-display 'dedicated-frame)
7196 (raise-frame
7197 (select-frame (or (and org-indirect-dedicated-frame
7198 (frame-live-p org-indirect-dedicated-frame)
7199 org-indirect-dedicated-frame)
7200 (setq org-indirect-dedicated-frame (make-frame)))))
7201 (delete-other-windows)
7202 (org-pop-to-buffer-same-window ibuf)
7203 (org-set-frame-title (concat "Indirect: " heading)))
7204 ((eq org-indirect-buffer-display 'current-window)
7205 (org-pop-to-buffer-same-window ibuf))
7206 ((eq org-indirect-buffer-display 'other-window)
7207 (pop-to-buffer ibuf))
7208 (t (error "Invalid value")))
7209 (if (featurep 'xemacs)
7210 (save-excursion (org-mode) (turn-on-font-lock)))
7211 (narrow-to-region beg end)
7212 (show-all)
7213 (goto-char pos)
7214 (run-hook-with-args 'org-cycle-hook 'all)
7215 (and (window-live-p cwin) (select-window cwin))))
7217 (defun org-get-indirect-buffer (&optional buffer)
7218 (setq buffer (or buffer (current-buffer)))
7219 (let ((n 1) (base (buffer-name buffer)) bname)
7220 (while (buffer-live-p
7221 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7222 (setq n (1+ n)))
7223 (condition-case nil
7224 (make-indirect-buffer buffer bname 'clone)
7225 (error (make-indirect-buffer buffer bname)))))
7227 (defun org-set-frame-title (title)
7228 "Set the title of the current frame to the string TITLE."
7229 ;; FIXME: how to name a single frame in XEmacs???
7230 (unless (featurep 'xemacs)
7231 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7233 ;;;; Structure editing
7235 ;;; Inserting headlines
7237 (defun org-previous-line-empty-p ()
7238 (save-excursion
7239 (and (not (bobp))
7240 (or (beginning-of-line 0) t)
7241 (save-match-data
7242 (looking-at "[ \t]*$")))))
7244 (defun org-insert-heading (&optional force-heading invisible-ok)
7245 "Insert a new heading or item with same depth at point.
7246 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7247 If point is at the beginning of a headline, insert a sibling before the
7248 current headline. If point is not at the beginning, split the line,
7249 create the new headline with the text in the current line after point
7250 \(but see also the variable `org-M-RET-may-split-line').
7252 With a double prefix arg, force the heading to be inserted at the
7253 end of the parent subtree.
7255 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7256 This is important for non-interactive uses of the command."
7257 (interactive "P")
7258 (if (or (= (buffer-size) 0)
7259 (and (not (save-excursion
7260 (and (ignore-errors (org-back-to-heading invisible-ok))
7261 (org-at-heading-p))))
7262 (or force-heading (not (org-in-item-p)))))
7263 (progn
7264 (insert "\n* ")
7265 (run-hooks 'org-insert-heading-hook))
7266 (when (or force-heading (not (org-insert-item)))
7267 (let* ((empty-line-p nil)
7268 (level nil)
7269 (on-heading (org-at-heading-p))
7270 (head (save-excursion
7271 (condition-case nil
7272 (progn
7273 (org-back-to-heading invisible-ok)
7274 (when (and (not on-heading)
7275 (featurep 'org-inlinetask)
7276 (integerp org-inlinetask-min-level)
7277 (>= (length (match-string 0))
7278 org-inlinetask-min-level))
7279 ;; Find a heading level before the inline task
7280 (while (and (setq level (org-up-heading-safe))
7281 (>= level org-inlinetask-min-level)))
7282 (if (org-at-heading-p)
7283 (org-back-to-heading invisible-ok)
7284 (error "This should not happen")))
7285 (setq empty-line-p (org-previous-line-empty-p))
7286 (match-string 0))
7287 (error "*"))))
7288 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7289 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7290 pos hide-previous previous-pos)
7291 (cond
7292 ((and (org-at-heading-p) (bolp)
7293 (or (bobp)
7294 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7295 ;; insert before the current line
7296 (open-line (if blank 2 1)))
7297 ((and (bolp)
7298 (not org-insert-heading-respect-content)
7299 (or (bobp)
7300 (save-excursion
7301 (backward-char 1) (not (outline-invisible-p)))))
7302 ;; insert right here
7303 nil)
7305 ;; somewhere in the line
7306 (save-excursion
7307 (setq previous-pos (point-at-bol))
7308 (end-of-line)
7309 (setq hide-previous (outline-invisible-p)))
7310 (and org-insert-heading-respect-content (org-show-subtree))
7311 (let ((split
7312 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7313 (save-excursion
7314 (let ((p (point)))
7315 (goto-char (point-at-bol))
7316 (and (looking-at org-complex-heading-regexp)
7317 (match-beginning 4)
7318 (> p (match-beginning 4)))))))
7319 tags pos)
7320 (cond
7321 (org-insert-heading-respect-content
7322 (if (not (equal force-heading '(16)))
7323 (org-end-of-subtree nil t)
7324 (org-up-heading-safe)
7325 (org-end-of-subtree nil t))
7326 (when (featurep 'org-inlinetask)
7327 (while (and (not (eobp))
7328 (looking-at "\\(\\*+\\)[ \t]+")
7329 (>= (length (match-string 1))
7330 org-inlinetask-min-level))
7331 (org-end-of-subtree nil t)))
7332 (or (bolp) (newline))
7333 (or (org-previous-line-empty-p)
7334 (and blank (newline)))
7335 (open-line 1))
7336 ((org-at-heading-p)
7337 (when hide-previous
7338 (show-children)
7339 (org-show-entry))
7340 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7341 (setq tags (and (match-end 2) (match-string 2)))
7342 (and (match-end 1)
7343 (delete-region (match-beginning 1) (match-end 1)))
7344 (setq pos (point-at-bol))
7345 (or split (end-of-line 1))
7346 (delete-horizontal-space)
7347 (if (string-match "\\`\\*+\\'"
7348 (buffer-substring (point-at-bol) (point)))
7349 (insert " "))
7350 (newline (if blank 2 1))
7351 (when tags
7352 (save-excursion
7353 (goto-char pos)
7354 (end-of-line 1)
7355 (insert " " tags)
7356 (org-set-tags nil 'align))))
7358 (or split (end-of-line 1))
7359 (newline (if blank 2 1)))))))
7360 (insert head) (just-one-space)
7361 (setq pos (point))
7362 (end-of-line 1)
7363 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7364 (when (and org-insert-heading-respect-content hide-previous)
7365 (save-excursion
7366 (goto-char previous-pos)
7367 (hide-subtree)))
7368 (run-hooks 'org-insert-heading-hook)))))
7370 (defun org-get-heading (&optional no-tags no-todo)
7371 "Return the heading of the current entry, without the stars.
7372 When NO-TAGS is non-nil, don't include tags.
7373 When NO-TODO is non-nil, don't include TODO keywords."
7374 (save-excursion
7375 (org-back-to-heading t)
7376 (cond
7377 ((and no-tags no-todo)
7378 (looking-at org-complex-heading-regexp)
7379 (match-string 4))
7380 (no-tags
7381 (looking-at (concat org-outline-regexp
7382 "\\(.*?\\)"
7383 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7384 (match-string 1))
7385 (no-todo
7386 (looking-at org-todo-line-regexp)
7387 (match-string 3))
7388 (t (looking-at org-heading-regexp)
7389 (match-string 2)))))
7391 (defun org-heading-components ()
7392 "Return the components of the current heading.
7393 This is a list with the following elements:
7394 - the level as an integer
7395 - the reduced level, different if `org-odd-levels-only' is set.
7396 - the TODO keyword, or nil
7397 - the priority character, like ?A, or nil if no priority is given
7398 - the headline text itself, or the tags string if no headline text
7399 - the tags string, or nil."
7400 (save-excursion
7401 (org-back-to-heading t)
7402 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7403 (list (length (match-string 1))
7404 (org-reduced-level (length (match-string 1)))
7405 (org-match-string-no-properties 2)
7406 (and (match-end 3) (aref (match-string 3) 2))
7407 (org-match-string-no-properties 4)
7408 (org-match-string-no-properties 5)))))
7410 (defun org-get-entry ()
7411 "Get the entry text, after heading, entire subtree."
7412 (save-excursion
7413 (org-back-to-heading t)
7414 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7416 (defun org-insert-heading-after-current ()
7417 "Insert a new heading with same level as current, after current subtree."
7418 (interactive)
7419 (org-back-to-heading)
7420 (org-insert-heading)
7421 (org-move-subtree-down)
7422 (end-of-line 1))
7424 (defun org-insert-heading-respect-content ()
7425 (interactive)
7426 (let ((org-insert-heading-respect-content t))
7427 (org-insert-heading t)))
7429 (defun org-insert-todo-heading-respect-content (&optional force-state)
7430 (interactive "P")
7431 (let ((org-insert-heading-respect-content t))
7432 (org-insert-todo-heading force-state t)))
7434 (defun org-insert-todo-heading (arg &optional force-heading)
7435 "Insert a new heading with the same level and TODO state as current heading.
7436 If the heading has no TODO state, or if the state is DONE, use the first
7437 state (TODO by default). Also one prefix arg, force first state. With two
7438 prefix args, force inserting at the end of the parent subtree."
7439 (interactive "P")
7440 (when (or force-heading (not (org-insert-item 'checkbox)))
7441 (org-insert-heading (or (and (equal arg '(16)) '(16))
7442 force-heading))
7443 (save-excursion
7444 (org-back-to-heading)
7445 (outline-previous-heading)
7446 (looking-at org-todo-line-regexp))
7447 (let*
7448 ((new-mark-x
7449 (if (or arg
7450 (not (match-beginning 2))
7451 (member (match-string 2) org-done-keywords))
7452 (car org-todo-keywords-1)
7453 (match-string 2)))
7454 (new-mark
7456 (run-hook-with-args-until-success
7457 'org-todo-get-default-hook new-mark-x nil)
7458 new-mark-x)))
7459 (beginning-of-line 1)
7460 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7461 (if org-treat-insert-todo-heading-as-state-change
7462 (org-todo new-mark)
7463 (insert new-mark " "))))
7464 (when org-provide-todo-statistics
7465 (org-update-parent-todo-statistics))))
7467 (defun org-insert-subheading (arg)
7468 "Insert a new subheading and demote it.
7469 Works for outline headings and for plain lists alike."
7470 (interactive "P")
7471 (org-insert-heading arg)
7472 (cond
7473 ((org-at-heading-p) (org-do-demote))
7474 ((org-at-item-p) (org-indent-item))))
7476 (defun org-insert-todo-subheading (arg)
7477 "Insert a new subheading with TODO keyword or checkbox and demote it.
7478 Works for outline headings and for plain lists alike."
7479 (interactive "P")
7480 (org-insert-todo-heading arg)
7481 (cond
7482 ((org-at-heading-p) (org-do-demote))
7483 ((org-at-item-p) (org-indent-item))))
7485 ;;; Promotion and Demotion
7487 (defvar org-after-demote-entry-hook nil
7488 "Hook run after an entry has been demoted.
7489 The cursor will be at the beginning of the entry.
7490 When a subtree is being demoted, the hook will be called for each node.")
7492 (defvar org-after-promote-entry-hook nil
7493 "Hook run after an entry has been promoted.
7494 The cursor will be at the beginning of the entry.
7495 When a subtree is being promoted, the hook will be called for each node.")
7497 (defun org-promote-subtree ()
7498 "Promote the entire subtree.
7499 See also `org-promote'."
7500 (interactive)
7501 (save-excursion
7502 (org-with-limited-levels (org-map-tree 'org-promote)))
7503 (org-fix-position-after-promote))
7505 (defun org-demote-subtree ()
7506 "Demote the entire subtree. See `org-demote'.
7507 See also `org-promote'."
7508 (interactive)
7509 (save-excursion
7510 (org-with-limited-levels (org-map-tree 'org-demote)))
7511 (org-fix-position-after-promote))
7514 (defun org-do-promote ()
7515 "Promote the current heading higher up the tree.
7516 If the region is active in `transient-mark-mode', promote all headings
7517 in the region."
7518 (interactive)
7519 (save-excursion
7520 (if (org-region-active-p)
7521 (org-map-region 'org-promote (region-beginning) (region-end))
7522 (org-promote)))
7523 (org-fix-position-after-promote))
7525 (defun org-do-demote ()
7526 "Demote the current heading lower down the tree.
7527 If the region is active in `transient-mark-mode', demote all headings
7528 in the region."
7529 (interactive)
7530 (save-excursion
7531 (if (org-region-active-p)
7532 (org-map-region 'org-demote (region-beginning) (region-end))
7533 (org-demote)))
7534 (org-fix-position-after-promote))
7536 (defun org-fix-position-after-promote ()
7537 "Make sure that after pro/demotion cursor position is right."
7538 (let ((pos (point)))
7539 (when (save-excursion
7540 (beginning-of-line 1)
7541 (looking-at org-todo-line-regexp)
7542 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7543 (cond ((eobp) (insert " "))
7544 ((eolp) (insert " "))
7545 ((equal (char-after) ?\ ) (forward-char 1))))))
7547 (defun org-current-level ()
7548 "Return the level of the current entry, or nil if before the first headline.
7549 The level is the number of stars at the beginning of the headline."
7550 (save-excursion
7551 (org-with-limited-levels
7552 (if (ignore-errors (org-back-to-heading t))
7553 (funcall outline-level)))))
7555 (defun org-get-previous-line-level ()
7556 "Return the outline depth of the last headline before the current line.
7557 Returns 0 for the first headline in the buffer, and nil if before the
7558 first headline."
7559 (let ((current-level (org-current-level))
7560 (prev-level (when (> (line-number-at-pos) 1)
7561 (save-excursion
7562 (beginning-of-line 0)
7563 (org-current-level)))))
7564 (cond ((null current-level) nil) ; Before first headline
7565 ((null prev-level) 0) ; At first headline
7566 (prev-level))))
7568 (defun org-reduced-level (l)
7569 "Compute the effective level of a heading.
7570 This takes into account the setting of `org-odd-levels-only'."
7571 (cond
7572 ((zerop l) 0)
7573 (org-odd-levels-only (1+ (floor (/ l 2))))
7574 (t l)))
7576 (defun org-level-increment ()
7577 "Return the number of stars that will be added or removed at a
7578 time to headlines when structure editing, based on the value of
7579 `org-odd-levels-only'."
7580 (if org-odd-levels-only 2 1))
7582 (defun org-get-valid-level (level &optional change)
7583 "Rectify a level change under the influence of `org-odd-levels-only'
7584 LEVEL is a current level, CHANGE is by how much the level should be
7585 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7586 even level numbers will become the next higher odd number."
7587 (if org-odd-levels-only
7588 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7589 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7590 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7591 (max 1 (+ level (or change 0)))))
7593 (org-define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
7595 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7596 ;; ̀org-with-limited-levels'
7597 (defun org-promote ()
7598 "Promote the current heading higher up the tree.
7599 If the region is active in `transient-mark-mode', promote all headings
7600 in the region."
7601 (org-back-to-heading t)
7602 (let* ((level (save-match-data (funcall outline-level)))
7603 (after-change-functions (remove 'flyspell-after-change-function
7604 after-change-functions))
7605 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7606 (diff (abs (- level (length up-head) -1))))
7607 (cond ((and (= level 1) org-called-with-limited-levels
7608 org-allow-promoting-top-level-subtree)
7609 (replace-match "# " nil t))
7610 ((= level 1)
7611 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7612 (t (replace-match up-head nil t)))
7613 ;; Fixup tag positioning
7614 (unless (= level 1)
7615 (and org-auto-align-tags (org-set-tags nil t))
7616 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7617 (run-hooks 'org-after-promote-entry-hook)))
7619 (defun org-demote ()
7620 "Demote the current heading lower down the tree.
7621 If the region is active in `transient-mark-mode', demote all headings
7622 in the region."
7623 (org-back-to-heading t)
7624 (let* ((level (save-match-data (funcall outline-level)))
7625 (after-change-functions (remove 'flyspell-after-change-function
7626 after-change-functions))
7627 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7628 (diff (abs (- level (length down-head) -1))))
7629 (replace-match down-head nil t)
7630 ;; Fixup tag positioning
7631 (and org-auto-align-tags (org-set-tags nil t))
7632 (if org-adapt-indentation (org-fixup-indentation diff))
7633 (run-hooks 'org-after-demote-entry-hook)))
7635 (defun org-cycle-level ()
7636 "Cycle the level of an empty headline through possible states.
7637 This goes first to child, then to parent, level, then up the hierarchy.
7638 After top level, it switches back to sibling level."
7639 (interactive)
7640 (let ((org-adapt-indentation nil))
7641 (when (org-point-at-end-of-empty-headline)
7642 (setq this-command 'org-cycle-level) ; Only needed for caching
7643 (let ((cur-level (org-current-level))
7644 (prev-level (org-get-previous-line-level)))
7645 (cond
7646 ;; If first headline in file, promote to top-level.
7647 ((= prev-level 0)
7648 (loop repeat (/ (- cur-level 1) (org-level-increment))
7649 do (org-do-promote)))
7650 ;; If same level as prev, demote one.
7651 ((= prev-level cur-level)
7652 (org-do-demote))
7653 ;; If parent is top-level, promote to top level if not already.
7654 ((= prev-level 1)
7655 (loop repeat (/ (- cur-level 1) (org-level-increment))
7656 do (org-do-promote)))
7657 ;; If top-level, return to prev-level.
7658 ((= cur-level 1)
7659 (loop repeat (/ (- prev-level 1) (org-level-increment))
7660 do (org-do-demote)))
7661 ;; If less than prev-level, promote one.
7662 ((< cur-level prev-level)
7663 (org-do-promote))
7664 ;; If deeper than prev-level, promote until higher than
7665 ;; prev-level.
7666 ((> cur-level prev-level)
7667 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7668 do (org-do-promote))))
7669 t))))
7671 (defun org-map-tree (fun)
7672 "Call FUN for every heading underneath the current one."
7673 (org-back-to-heading)
7674 (let ((level (funcall outline-level)))
7675 (save-excursion
7676 (funcall fun)
7677 (while (and (progn
7678 (outline-next-heading)
7679 (> (funcall outline-level) level))
7680 (not (eobp)))
7681 (funcall fun)))))
7683 (defun org-map-region (fun beg end)
7684 "Call FUN for every heading between BEG and END."
7685 (let ((org-ignore-region t))
7686 (save-excursion
7687 (setq end (copy-marker end))
7688 (goto-char beg)
7689 (if (and (re-search-forward org-outline-regexp-bol nil t)
7690 (< (point) end))
7691 (funcall fun))
7692 (while (and (progn
7693 (outline-next-heading)
7694 (< (point) end))
7695 (not (eobp)))
7696 (funcall fun)))))
7698 (defvar org-property-end-re) ; silence byte-compiler
7699 (defun org-fixup-indentation (diff)
7700 "Change the indentation in the current entry by DIFF.
7701 However, if any line in the current entry has no indentation, or if it
7702 would end up with no indentation after the change, nothing at all is done."
7703 (save-excursion
7704 (let ((end (save-excursion (outline-next-heading)
7705 (point-marker)))
7706 (prohibit (if (> diff 0)
7707 "^\\S-"
7708 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7709 col)
7710 (unless (save-excursion (end-of-line 1)
7711 (re-search-forward prohibit end t))
7712 (while (and (< (point) end)
7713 (re-search-forward "^[ \t]+" end t))
7714 (goto-char (match-end 0))
7715 (setq col (current-column))
7716 (if (< diff 0) (replace-match ""))
7717 (org-indent-to-column (+ diff col))))
7718 (move-marker end nil))))
7720 (defun org-convert-to-odd-levels ()
7721 "Convert an org-mode file with all levels allowed to one with odd levels.
7722 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7723 level 5 etc."
7724 (interactive)
7725 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7726 (let ((outline-level 'org-outline-level)
7727 (org-odd-levels-only nil) n)
7728 (save-excursion
7729 (goto-char (point-min))
7730 (while (re-search-forward "^\\*\\*+ " nil t)
7731 (setq n (- (length (match-string 0)) 2))
7732 (while (>= (setq n (1- n)) 0)
7733 (org-demote))
7734 (end-of-line 1))))))
7736 (defun org-convert-to-oddeven-levels ()
7737 "Convert an org-mode file with only odd levels to one with odd/even levels.
7738 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7739 file contains a section with an even level, conversion would
7740 destroy the structure of the file. An error is signaled in this
7741 case."
7742 (interactive)
7743 (goto-char (point-min))
7744 ;; First check if there are no even levels
7745 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7746 (org-show-context t)
7747 (error "Not all levels are odd in this file. Conversion not possible"))
7748 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7749 (let ((outline-regexp org-outline-regexp)
7750 (outline-level 'org-outline-level)
7751 (org-odd-levels-only nil) n)
7752 (save-excursion
7753 (goto-char (point-min))
7754 (while (re-search-forward "^\\*\\*+ " nil t)
7755 (setq n (/ (1- (length (match-string 0))) 2))
7756 (while (>= (setq n (1- n)) 0)
7757 (org-promote))
7758 (end-of-line 1))))))
7760 (defun org-tr-level (n)
7761 "Make N odd if required."
7762 (if org-odd-levels-only (1+ (/ n 2)) n))
7764 ;;; Vertical tree motion, cutting and pasting of subtrees
7766 (defun org-move-subtree-up (&optional arg)
7767 "Move the current subtree up past ARG headlines of the same level."
7768 (interactive "p")
7769 (org-move-subtree-down (- (prefix-numeric-value arg))))
7771 (defun org-move-subtree-down (&optional arg)
7772 "Move the current subtree down past ARG headlines of the same level."
7773 (interactive "p")
7774 (setq arg (prefix-numeric-value arg))
7775 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7776 'org-get-last-sibling))
7777 (ins-point (make-marker))
7778 (cnt (abs arg))
7779 (col (current-column))
7780 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7781 ;; Select the tree
7782 (org-back-to-heading)
7783 (setq beg0 (point))
7784 (save-excursion
7785 (setq ne-beg (org-back-over-empty-lines))
7786 (setq beg (point)))
7787 (save-match-data
7788 (save-excursion (outline-end-of-heading)
7789 (setq folded (outline-invisible-p)))
7790 (outline-end-of-subtree))
7791 (outline-next-heading)
7792 (setq ne-end (org-back-over-empty-lines))
7793 (setq end (point))
7794 (goto-char beg0)
7795 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7796 ;; include less whitespace
7797 (save-excursion
7798 (goto-char beg)
7799 (forward-line (- ne-beg ne-end))
7800 (setq beg (point))))
7801 ;; Find insertion point, with error handling
7802 (while (> cnt 0)
7803 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7804 (progn (goto-char beg0)
7805 (error "Cannot move past superior level or buffer limit")))
7806 (setq cnt (1- cnt)))
7807 (if (> arg 0)
7808 ;; Moving forward - still need to move over subtree
7809 (progn (org-end-of-subtree t t)
7810 (save-excursion
7811 (org-back-over-empty-lines)
7812 (or (bolp) (newline)))))
7813 (setq ne-ins (org-back-over-empty-lines))
7814 (move-marker ins-point (point))
7815 (setq txt (buffer-substring beg end))
7816 (org-save-markers-in-region beg end)
7817 (delete-region beg end)
7818 (org-remove-empty-overlays-at beg)
7819 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7820 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7821 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7822 (let ((bbb (point)))
7823 (insert-before-markers txt)
7824 (org-reinstall-markers-in-region bbb)
7825 (move-marker ins-point bbb))
7826 (or (bolp) (insert "\n"))
7827 (setq ins-end (point))
7828 (goto-char ins-point)
7829 (org-skip-whitespace)
7830 (when (and (< arg 0)
7831 (org-first-sibling-p)
7832 (> ne-ins ne-beg))
7833 ;; Move whitespace back to beginning
7834 (save-excursion
7835 (goto-char ins-end)
7836 (let ((kill-whole-line t))
7837 (kill-line (- ne-ins ne-beg)) (point)))
7838 (insert (make-string (- ne-ins ne-beg) ?\n)))
7839 (move-marker ins-point nil)
7840 (if folded
7841 (hide-subtree)
7842 (org-show-entry)
7843 (show-children)
7844 (org-cycle-hide-drawers 'children))
7845 (org-clean-visibility-after-subtree-move)
7846 ;; move back to the initial column we were at
7847 (move-to-column col)))
7849 (defvar org-subtree-clip ""
7850 "Clipboard for cut and paste of subtrees.
7851 This is actually only a copy of the kill, because we use the normal kill
7852 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7854 (defvar org-subtree-clip-folded nil
7855 "Was the last copied subtree folded?
7856 This is used to fold the tree back after pasting.")
7858 (defun org-cut-subtree (&optional n)
7859 "Cut the current subtree into the clipboard.
7860 With prefix arg N, cut this many sequential subtrees.
7861 This is a short-hand for marking the subtree and then cutting it."
7862 (interactive "p")
7863 (org-copy-subtree n 'cut))
7865 (defun org-copy-subtree (&optional n cut force-store-markers)
7866 "Cut the current subtree into the clipboard.
7867 With prefix arg N, cut this many sequential subtrees.
7868 This is a short-hand for marking the subtree and then copying it.
7869 If CUT is non-nil, actually cut the subtree.
7870 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7871 of some markers in the region, even if CUT is non-nil. This is
7872 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7873 (interactive "p")
7874 (let (beg end folded (beg0 (point)))
7875 (if (org-called-interactively-p 'any)
7876 (org-back-to-heading nil) ; take what looks like a subtree
7877 (org-back-to-heading t)) ; take what is really there
7878 (setq beg (point))
7879 (skip-chars-forward " \t\r\n")
7880 (save-match-data
7881 (save-excursion (outline-end-of-heading)
7882 (setq folded (outline-invisible-p)))
7883 (condition-case nil
7884 (org-forward-heading-same-level (1- n) t)
7885 (error nil))
7886 (org-end-of-subtree t t))
7887 (setq end (point))
7888 (goto-char beg0)
7889 (when (> end beg)
7890 (setq org-subtree-clip-folded folded)
7891 (when (or cut force-store-markers)
7892 (org-save-markers-in-region beg end))
7893 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7894 (setq org-subtree-clip (current-kill 0))
7895 (message "%s: Subtree(s) with %d characters"
7896 (if cut "Cut" "Copied")
7897 (length org-subtree-clip)))))
7899 (defun org-paste-subtree (&optional level tree for-yank)
7900 "Paste the clipboard as a subtree, with modification of headline level.
7901 The entire subtree is promoted or demoted in order to match a new headline
7902 level.
7904 If the cursor is at the beginning of a headline, the same level as
7905 that headline is used to paste the tree
7907 If not, the new level is derived from the *visible* headings
7908 before and after the insertion point, and taken to be the inferior headline
7909 level of the two. So if the previous visible heading is level 3 and the
7910 next is level 4 (or vice versa), level 4 will be used for insertion.
7911 This makes sure that the subtree remains an independent subtree and does
7912 not swallow low level entries.
7914 You can also force a different level, either by using a numeric prefix
7915 argument, or by inserting the heading marker by hand. For example, if the
7916 cursor is after \"*****\", then the tree will be shifted to level 5.
7918 If optional TREE is given, use this text instead of the kill ring.
7920 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7921 move back over whitespace before inserting, and move point to the end of
7922 the inserted text when done."
7923 (interactive "P")
7924 (setq tree (or tree (and kill-ring (current-kill 0))))
7925 (unless (org-kill-is-subtree-p tree)
7926 (error "%s"
7927 (substitute-command-keys
7928 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7929 (org-with-limited-levels
7930 (let* ((visp (not (outline-invisible-p)))
7931 (txt tree)
7932 (^re_ "\\(\\*+\\)[ \t]*")
7933 (old-level (if (string-match org-outline-regexp-bol txt)
7934 (- (match-end 0) (match-beginning 0) 1)
7935 -1))
7936 (force-level (cond (level (prefix-numeric-value level))
7937 ((and (looking-at "[ \t]*$")
7938 (string-match
7939 "^\\*+$" (buffer-substring
7940 (point-at-bol) (point))))
7941 (- (match-end 1) (match-beginning 1)))
7942 ((and (bolp)
7943 (looking-at org-outline-regexp))
7944 (- (match-end 0) (point) 1))))
7945 (previous-level (save-excursion
7946 (condition-case nil
7947 (progn
7948 (outline-previous-visible-heading 1)
7949 (if (looking-at ^re_)
7950 (- (match-end 0) (match-beginning 0) 1)
7952 (error 1))))
7953 (next-level (save-excursion
7954 (condition-case nil
7955 (progn
7956 (or (looking-at org-outline-regexp)
7957 (outline-next-visible-heading 1))
7958 (if (looking-at ^re_)
7959 (- (match-end 0) (match-beginning 0) 1)
7961 (error 1))))
7962 (new-level (or force-level (max previous-level next-level)))
7963 (shift (if (or (= old-level -1)
7964 (= new-level -1)
7965 (= old-level new-level))
7967 (- new-level old-level)))
7968 (delta (if (> shift 0) -1 1))
7969 (func (if (> shift 0) 'org-demote 'org-promote))
7970 (org-odd-levels-only nil)
7971 beg end newend)
7972 ;; Remove the forced level indicator
7973 (if force-level
7974 (delete-region (point-at-bol) (point)))
7975 ;; Paste
7976 (beginning-of-line (if (bolp) 1 2))
7977 (setq beg (point))
7978 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7979 (insert-before-markers txt)
7980 (unless (string-match "\n\\'" txt) (insert "\n"))
7981 (setq newend (point))
7982 (org-reinstall-markers-in-region beg)
7983 (setq end (point))
7984 (goto-char beg)
7985 (skip-chars-forward " \t\n\r")
7986 (setq beg (point))
7987 (if (and (outline-invisible-p) visp)
7988 (save-excursion (outline-show-heading)))
7989 ;; Shift if necessary
7990 (unless (= shift 0)
7991 (save-restriction
7992 (narrow-to-region beg end)
7993 (while (not (= shift 0))
7994 (org-map-region func (point-min) (point-max))
7995 (setq shift (+ delta shift)))
7996 (goto-char (point-min))
7997 (setq newend (point-max))))
7998 (when (or (org-called-interactively-p 'interactive) for-yank)
7999 (message "Clipboard pasted as level %d subtree" new-level))
8000 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8001 kill-ring
8002 (eq org-subtree-clip (current-kill 0))
8003 org-subtree-clip-folded)
8004 ;; The tree was folded before it was killed/copied
8005 (hide-subtree))
8006 (and for-yank (goto-char newend)))))
8008 (defun org-kill-is-subtree-p (&optional txt)
8009 "Check if the current kill is an outline subtree, or a set of trees.
8010 Returns nil if kill does not start with a headline, or if the first
8011 headline level is not the largest headline level in the tree.
8012 So this will actually accept several entries of equal levels as well,
8013 which is OK for `org-paste-subtree'.
8014 If optional TXT is given, check this string instead of the current kill."
8015 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8016 (re (org-get-limited-outline-regexp))
8017 (^re (concat "^" re))
8018 (start-level (and kill
8019 (string-match
8020 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8021 kill)
8022 (- (match-end 2) (match-beginning 2) 1)))
8023 (start (1+ (or (match-beginning 2) -1))))
8024 (if (not start-level)
8025 (progn
8026 nil) ;; does not even start with a heading
8027 (catch 'exit
8028 (while (setq start (string-match ^re kill (1+ start)))
8029 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8030 (throw 'exit nil)))
8031 t))))
8033 (defvar org-markers-to-move nil
8034 "Markers that should be moved with a cut-and-paste operation.
8035 Those markers are stored together with their positions relative to
8036 the start of the region.")
8038 (defun org-save-markers-in-region (beg end)
8039 "Check markers in region.
8040 If these markers are between BEG and END, record their position relative
8041 to BEG, so that after moving the block of text, we can put the markers back
8042 into place.
8043 This function gets called just before an entry or tree gets cut from the
8044 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8045 called immediately, to move the markers with the entries."
8046 (setq org-markers-to-move nil)
8047 (when (featurep 'org-clock)
8048 (org-clock-save-markers-for-cut-and-paste beg end))
8049 (when (featurep 'org-agenda)
8050 (org-agenda-save-markers-for-cut-and-paste beg end)))
8052 (defun org-check-and-save-marker (marker beg end)
8053 "Check if MARKER is between BEG and END.
8054 If yes, remember the marker and the distance to BEG."
8055 (when (and (marker-buffer marker)
8056 (equal (marker-buffer marker) (current-buffer)))
8057 (if (and (>= marker beg) (< marker end))
8058 (push (cons marker (- marker beg)) org-markers-to-move))))
8060 (defun org-reinstall-markers-in-region (beg)
8061 "Move all remembered markers to their position relative to BEG."
8062 (mapc (lambda (x)
8063 (move-marker (car x) (+ beg (cdr x))))
8064 org-markers-to-move)
8065 (setq org-markers-to-move nil))
8067 (defun org-narrow-to-subtree ()
8068 "Narrow buffer to the current subtree."
8069 (interactive)
8070 (save-excursion
8071 (save-match-data
8072 (org-with-limited-levels
8073 (narrow-to-region
8074 (progn (org-back-to-heading t) (point))
8075 (progn (org-end-of-subtree t t)
8076 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8077 (point)))))))
8079 (defun org-narrow-to-block ()
8080 "Narrow buffer to the current block."
8081 (interactive)
8082 (let* ((case-fold-search t)
8083 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8084 "^[ \t]*#\\+end_.*")))
8085 (if blockp
8086 (narrow-to-region (car blockp) (cdr blockp))
8087 (error "Not in a block"))))
8089 (eval-when-compile
8090 (defvar org-property-drawer-re))
8092 (defvar org-property-start-re) ;; defined below
8093 (defun org-clone-subtree-with-time-shift (n &optional shift)
8094 "Clone the task (subtree) at point N times.
8095 The clones will be inserted as siblings.
8097 In interactive use, the user will be prompted for the number of
8098 clones to be produced, and for a time SHIFT, which may be a
8099 repeater as used in time stamps, for example `+3d'.
8101 When a valid repeater is given and the entry contains any time
8102 stamps, the clones will become a sequence in time, with time
8103 stamps in the subtree shifted for each clone produced. If SHIFT
8104 is nil or the empty string, time stamps will be left alone. The
8105 ID property of the original subtree is removed.
8107 If the original subtree did contain time stamps with a repeater,
8108 the following will happen:
8109 - the repeater will be removed in each clone
8110 - an additional clone will be produced, with the current, unshifted
8111 date(s) in the entry.
8112 - the original entry will be placed *after* all the clones, with
8113 repeater intact.
8114 - the start days in the repeater in the original entry will be shifted
8115 to past the last clone.
8116 In this way you can spell out a number of instances of a repeating task,
8117 and still retain the repeater to cover future instances of the task."
8118 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8119 (let (beg end template task idprop
8120 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8121 (drawer-re org-drawer-regexp))
8122 (if (not (and (integerp n) (> n 0)))
8123 (error "Invalid number of replications %s" n))
8124 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8125 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8126 shift)))
8127 (error "Invalid shift specification %s" shift))
8128 (when doshift
8129 (setq shift-n (string-to-number (match-string 1 shift))
8130 shift-what (cdr (assoc (match-string 2 shift)
8131 '(("d" . day) ("w" . week)
8132 ("m" . month) ("y" . year))))))
8133 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8134 (setq nmin 1 nmax n)
8135 (org-back-to-heading t)
8136 (setq beg (point))
8137 (setq idprop (org-entry-get nil "ID"))
8138 (org-end-of-subtree t t)
8139 (or (bolp) (insert "\n"))
8140 (setq end (point))
8141 (setq template (buffer-substring beg end))
8142 (when (and doshift
8143 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8144 (delete-region beg end)
8145 (setq end beg)
8146 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8147 (goto-char end)
8148 (loop for n from nmin to nmax do
8149 ;; prepare clone
8150 (with-temp-buffer
8151 (insert template)
8152 (org-mode)
8153 (goto-char (point-min))
8154 (org-show-subtree)
8155 (and idprop (if org-clone-delete-id
8156 (org-entry-delete nil "ID")
8157 (org-id-get-create t)))
8158 (unless (= n 0)
8159 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8160 (kill-whole-line))
8161 (goto-char (point-min))
8162 (while (re-search-forward drawer-re nil t)
8163 (mapc (lambda (d)
8164 (org-remove-empty-drawer-at d (point))) org-drawers)))
8165 (goto-char (point-min))
8166 (when doshift
8167 (while (re-search-forward org-ts-regexp-both nil t)
8168 (org-timestamp-change (* n shift-n) shift-what))
8169 (unless (= n n-no-remove)
8170 (goto-char (point-min))
8171 (while (re-search-forward org-ts-regexp nil t)
8172 (save-excursion
8173 (goto-char (match-beginning 0))
8174 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8175 (delete-region (match-beginning 1) (match-end 1)))))))
8176 (setq task (buffer-string)))
8177 (insert task))
8178 (goto-char beg)))
8180 ;;; Outline Sorting
8182 (defun org-sort (with-case)
8183 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8184 Optional argument WITH-CASE means sort case-sensitively."
8185 (interactive "P")
8186 (cond
8187 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8188 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8190 (org-call-with-arg 'org-sort-entries with-case))))
8192 (defun org-sort-remove-invisible (s)
8193 (remove-text-properties 0 (length s) org-rm-props s)
8194 (while (string-match org-bracket-link-regexp s)
8195 (setq s (replace-match (if (match-end 2)
8196 (match-string 3 s)
8197 (match-string 1 s)) t t s)))
8200 (defvar org-priority-regexp) ; defined later in the file
8202 (defvar org-after-sorting-entries-or-items-hook nil
8203 "Hook that is run after a bunch of entries or items have been sorted.
8204 When children are sorted, the cursor is in the parent line when this
8205 hook gets called. When a region or a plain list is sorted, the cursor
8206 will be in the first entry of the sorted region/list.")
8208 (defun org-sort-entries
8209 (&optional with-case sorting-type getkey-func compare-func property)
8210 "Sort entries on a certain level of an outline tree.
8211 If there is an active region, the entries in the region are sorted.
8212 Else, if the cursor is before the first entry, sort the top-level items.
8213 Else, the children of the entry at point are sorted.
8215 Sorting can be alphabetically, numerically, by date/time as given by
8216 a time stamp, by a property or by priority.
8218 The command prompts for the sorting type unless it has been given to the
8219 function through the SORTING-TYPE argument, which needs to be a character,
8220 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8221 precise meaning of each character:
8223 n Numerically, by converting the beginning of the entry/item to a number.
8224 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8225 o By order of TODO keywords.
8226 t By date/time, either the first active time stamp in the entry, or, if
8227 none exist, by the first inactive one.
8228 s By the scheduled date/time.
8229 d By deadline date/time.
8230 c By creation time, which is assumed to be the first inactive time stamp
8231 at the beginning of a line.
8232 p By priority according to the cookie.
8233 r By the value of a property.
8235 Capital letters will reverse the sort order.
8237 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8238 called with point at the beginning of the record. It must return either
8239 a string or a number that should serve as the sorting key for that record.
8241 Comparing entries ignores case by default. However, with an optional argument
8242 WITH-CASE, the sorting considers case as well."
8243 (interactive "P")
8244 (let ((case-func (if with-case 'identity 'downcase))
8245 (cmstr
8246 ;; The clock marker is lost when using `sort-subr', let's
8247 ;; store the clocking string.
8248 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8249 (save-excursion
8250 (goto-char org-clock-marker)
8251 (looking-back "^.*") (match-string-no-properties 0))))
8252 start beg end stars re re2
8253 txt what tmp)
8254 ;; Find beginning and end of region to sort
8255 (cond
8256 ((org-region-active-p)
8257 ;; we will sort the region
8258 (setq end (region-end)
8259 what "region")
8260 (goto-char (region-beginning))
8261 (if (not (org-at-heading-p)) (outline-next-heading))
8262 (setq start (point)))
8263 ((or (org-at-heading-p)
8264 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8265 ;; we will sort the children of the current headline
8266 (org-back-to-heading)
8267 (setq start (point)
8268 end (progn (org-end-of-subtree t t)
8269 (or (bolp) (insert "\n"))
8270 (org-back-over-empty-lines)
8271 (point))
8272 what "children")
8273 (goto-char start)
8274 (show-subtree)
8275 (outline-next-heading))
8277 ;; we will sort the top-level entries in this file
8278 (goto-char (point-min))
8279 (or (org-at-heading-p) (outline-next-heading))
8280 (setq start (point))
8281 (goto-char (point-max))
8282 (beginning-of-line 1)
8283 (when (looking-at ".*?\\S-")
8284 ;; File ends in a non-white line
8285 (end-of-line 1)
8286 (insert "\n"))
8287 (setq end (point-max))
8288 (setq what "top-level")
8289 (goto-char start)
8290 (show-all)))
8292 (setq beg (point))
8293 (if (>= beg end) (error "Nothing to sort"))
8295 (looking-at "\\(\\*+\\)")
8296 (setq stars (match-string 1)
8297 re (concat "^" (regexp-quote stars) " +")
8298 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8299 txt (buffer-substring beg end))
8300 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8301 (if (and (not (equal stars "*")) (string-match re2 txt))
8302 (error "Region to sort contains a level above the first entry"))
8304 (unless sorting-type
8305 (message
8306 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8307 [t]ime [s]cheduled [d]eadline [c]reated
8308 A/N/P/R/O/F/T/S/D/C means reversed:"
8309 what)
8310 (setq sorting-type (read-char-exclusive))
8312 (unless getkey-func
8313 (and (= (downcase sorting-type) ?f)
8314 (setq getkey-func
8315 (org-icompleting-read "Sort using function: "
8316 obarray 'fboundp t nil nil))
8317 (setq getkey-func (intern getkey-func))))
8319 (and (= (downcase sorting-type) ?r)
8320 (not property)
8321 (setq property
8322 (org-icompleting-read "Property: "
8323 (mapcar 'list (org-buffer-property-keys t))
8324 nil t))))
8326 (message "Sorting entries...")
8328 (save-restriction
8329 (narrow-to-region start end)
8330 (let ((dcst (downcase sorting-type))
8331 (case-fold-search nil)
8332 (now (current-time)))
8333 (sort-subr
8334 (/= dcst sorting-type)
8335 ;; This function moves to the beginning character of the "record" to
8336 ;; be sorted.
8337 (lambda nil
8338 (if (re-search-forward re nil t)
8339 (goto-char (match-beginning 0))
8340 (goto-char (point-max))))
8341 ;; This function moves to the last character of the "record" being
8342 ;; sorted.
8343 (lambda nil
8344 (save-match-data
8345 (condition-case nil
8346 (outline-forward-same-level 1)
8347 (error
8348 (goto-char (point-max))))))
8349 ;; This function returns the value that gets sorted against.
8350 (lambda nil
8351 (cond
8352 ((= dcst ?n)
8353 (if (looking-at org-complex-heading-regexp)
8354 (string-to-number (match-string 4))
8355 nil))
8356 ((= dcst ?a)
8357 (if (looking-at org-complex-heading-regexp)
8358 (funcall case-func (match-string 4))
8359 nil))
8360 ((= dcst ?t)
8361 (let ((end (save-excursion (outline-next-heading) (point))))
8362 (if (or (re-search-forward org-ts-regexp end t)
8363 (re-search-forward org-ts-regexp-both end t))
8364 (org-time-string-to-seconds (match-string 0))
8365 (org-float-time now))))
8366 ((= dcst ?c)
8367 (let ((end (save-excursion (outline-next-heading) (point))))
8368 (if (re-search-forward
8369 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8370 end t)
8371 (org-time-string-to-seconds (match-string 0))
8372 (org-float-time now))))
8373 ((= dcst ?s)
8374 (let ((end (save-excursion (outline-next-heading) (point))))
8375 (if (re-search-forward org-scheduled-time-regexp end t)
8376 (org-time-string-to-seconds (match-string 1))
8377 (org-float-time now))))
8378 ((= dcst ?d)
8379 (let ((end (save-excursion (outline-next-heading) (point))))
8380 (if (re-search-forward org-deadline-time-regexp end t)
8381 (org-time-string-to-seconds (match-string 1))
8382 (org-float-time now))))
8383 ((= dcst ?p)
8384 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8385 (string-to-char (match-string 2))
8386 org-default-priority))
8387 ((= dcst ?r)
8388 (or (org-entry-get nil property) ""))
8389 ((= dcst ?o)
8390 (if (looking-at org-complex-heading-regexp)
8391 (- 9999 (length (member (match-string 2)
8392 org-todo-keywords-1)))))
8393 ((= dcst ?f)
8394 (if getkey-func
8395 (progn
8396 (setq tmp (funcall getkey-func))
8397 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8398 tmp)
8399 (error "Invalid key function `%s'" getkey-func)))
8400 (t (error "Invalid sorting type `%c'" sorting-type))))
8402 (cond
8403 ((= dcst ?a) 'string<)
8404 ((= dcst ?f) compare-func)
8405 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8406 (run-hooks 'org-after-sorting-entries-or-items-hook)
8407 ;; Reset the clock marker if needed
8408 (when cmstr
8409 (save-excursion
8410 (goto-char start)
8411 (search-forward cmstr nil t)
8412 (move-marker org-clock-marker (point))))
8413 (message "Sorting entries...done")))
8415 (defun org-do-sort (table what &optional with-case sorting-type)
8416 "Sort TABLE of WHAT according to SORTING-TYPE.
8417 The user will be prompted for the SORTING-TYPE if the call to this
8418 function does not specify it. WHAT is only for the prompt, to indicate
8419 what is being sorted. The sorting key will be extracted from
8420 the car of the elements of the table.
8421 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8422 (unless sorting-type
8423 (message
8424 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8425 what)
8426 (setq sorting-type (read-char-exclusive)))
8427 (let ((dcst (downcase sorting-type))
8428 extractfun comparefun)
8429 ;; Define the appropriate functions
8430 (cond
8431 ((= dcst ?n)
8432 (setq extractfun 'string-to-number
8433 comparefun (if (= dcst sorting-type) '< '>)))
8434 ((= dcst ?a)
8435 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8436 (lambda(x) (downcase (org-sort-remove-invisible x))))
8437 comparefun (if (= dcst sorting-type)
8438 'string<
8439 (lambda (a b) (and (not (string< a b))
8440 (not (string= a b)))))))
8441 ((= dcst ?t)
8442 (setq extractfun
8443 (lambda (x)
8444 (if (or (string-match org-ts-regexp x)
8445 (string-match org-ts-regexp-both x))
8446 (org-float-time
8447 (org-time-string-to-time (match-string 0 x)))
8449 comparefun (if (= dcst sorting-type) '< '>)))
8450 (t (error "Invalid sorting type `%c'" sorting-type)))
8452 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8453 table)
8454 (lambda (a b) (funcall comparefun (car a) (car b))))))
8457 ;;; The orgstruct minor mode
8459 ;; Define a minor mode which can be used in other modes in order to
8460 ;; integrate the org-mode structure editing commands.
8462 ;; This is really a hack, because the org-mode structure commands use
8463 ;; keys which normally belong to the major mode. Here is how it
8464 ;; works: The minor mode defines all the keys necessary to operate the
8465 ;; structure commands, but wraps the commands into a function which
8466 ;; tests if the cursor is currently at a headline or a plain list
8467 ;; item. If that is the case, the structure command is used,
8468 ;; temporarily setting many Org-mode variables like regular
8469 ;; expressions for filling etc. However, when any of those keys is
8470 ;; used at a different location, function uses `key-binding' to look
8471 ;; up if the key has an associated command in another currently active
8472 ;; keymap (minor modes, major mode, global), and executes that
8473 ;; command. There might be problems if any of the keys is otherwise
8474 ;; used as a prefix key.
8476 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8477 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8478 ;; addresses this by checking explicitly for both bindings.
8480 (defvar orgstruct-mode-map (make-sparse-keymap)
8481 "Keymap for the minor `orgstruct-mode'.")
8483 (defvar org-local-vars nil
8484 "List of local variables, for use by `orgstruct-mode'.")
8486 ;;;###autoload
8487 (define-minor-mode orgstruct-mode
8488 "Toggle the minor mode `orgstruct-mode'.
8489 This mode is for using Org-mode structure commands in other
8490 modes. The following keys behave as if Org-mode were active, if
8491 the cursor is on a headline, or on a plain list item (both as
8492 defined by Org-mode).
8494 M-up Move entry/item up
8495 M-down Move entry/item down
8496 M-left Promote
8497 M-right Demote
8498 M-S-up Move entry/item up
8499 M-S-down Move entry/item down
8500 M-S-left Promote subtree
8501 M-S-right Demote subtree
8502 M-q Fill paragraph and items like in Org-mode
8503 C-c ^ Sort entries
8504 C-c - Cycle list bullet
8505 TAB Cycle item visibility
8506 M-RET Insert new heading/item
8507 S-M-RET Insert new TODO heading / Checkbox item
8508 C-c C-c Set tags / toggle checkbox"
8509 nil " OrgStruct" nil
8510 (org-load-modules-maybe)
8511 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8513 ;;;###autoload
8514 (defun turn-on-orgstruct ()
8515 "Unconditionally turn on `orgstruct-mode'."
8516 (orgstruct-mode 1))
8518 (defvar org-fb-vars nil)
8519 (make-variable-buffer-local 'org-fb-vars)
8520 (defun orgstruct++-mode (&optional arg)
8521 "Toggle `orgstruct-mode', the enhanced version of it.
8522 In addition to setting orgstruct-mode, this also exports all
8523 indentation and autofilling variables from org-mode into the
8524 buffer. It will also recognize item context in multiline items."
8525 (interactive "P")
8526 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8527 (if (< arg 1)
8528 (progn (orgstruct-mode -1)
8529 (mapc (lambda(v)
8530 (org-set-local (car v)
8531 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8532 org-fb-vars))
8533 (orgstruct-mode 1)
8534 (setq org-fb-vars nil)
8535 (let (var val)
8536 (mapc
8537 (lambda (x)
8538 (when (string-match
8539 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8540 (symbol-name (car x)))
8541 (setq var (car x) val (nth 1 x))
8542 (push (list var `(quote ,(eval var))) org-fb-vars)
8543 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8544 org-local-vars)
8545 (org-set-local 'orgstruct-is-++ t))))
8547 (defvar orgstruct-is-++ nil
8548 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8549 (make-variable-buffer-local 'orgstruct-is-++)
8551 ;;;###autoload
8552 (defun turn-on-orgstruct++ ()
8553 "Unconditionally turn on `orgstruct++-mode'."
8554 (orgstruct++-mode 1))
8556 (defun orgstruct-error ()
8557 "Error when there is no default binding for a structure key."
8558 (interactive)
8559 (error "This key has no function outside structure elements"))
8561 (defun orgstruct-setup ()
8562 "Setup orgstruct keymaps."
8563 (let ((nfunc 0)
8564 (bindings
8565 (list
8566 '([(meta up)] org-metaup)
8567 '([(meta down)] org-metadown)
8568 '([(meta left)] org-metaleft)
8569 '([(meta right)] org-metaright)
8570 '([(meta shift up)] org-shiftmetaup)
8571 '([(meta shift down)] org-shiftmetadown)
8572 '([(meta shift left)] org-shiftmetaleft)
8573 '([(meta shift right)] org-shiftmetaright)
8574 '([?\e (up)] org-metaup)
8575 '([?\e (down)] org-metadown)
8576 '([?\e (left)] org-metaleft)
8577 '([?\e (right)] org-metaright)
8578 '([?\e (shift up)] org-shiftmetaup)
8579 '([?\e (shift down)] org-shiftmetadown)
8580 '([?\e (shift left)] org-shiftmetaleft)
8581 '([?\e (shift right)] org-shiftmetaright)
8582 '([(shift up)] org-shiftup)
8583 '([(shift down)] org-shiftdown)
8584 '([(shift left)] org-shiftleft)
8585 '([(shift right)] org-shiftright)
8586 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8587 '("\M-q" fill-paragraph)
8588 '("\C-c^" org-sort)
8589 '("\C-c-" org-cycle-list-bullet)))
8590 elt key fun cmd)
8591 (while (setq elt (pop bindings))
8592 (setq nfunc (1+ nfunc))
8593 (setq key (org-key (car elt))
8594 fun (nth 1 elt)
8595 cmd (orgstruct-make-binding fun nfunc key))
8596 (org-defkey orgstruct-mode-map key cmd))
8598 ;; Prevent an error for users who forgot to make autoloads
8599 (require 'org-element)
8601 ;; Special treatment needed for TAB and RET
8602 (org-defkey orgstruct-mode-map [(tab)]
8603 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8604 (org-defkey orgstruct-mode-map "\C-i"
8605 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8607 (org-defkey orgstruct-mode-map "\M-\C-m"
8608 (orgstruct-make-binding 'org-insert-heading 105
8609 "\M-\C-m" [(meta return)]))
8610 (org-defkey orgstruct-mode-map [(meta return)]
8611 (orgstruct-make-binding 'org-insert-heading 106
8612 [(meta return)] "\M-\C-m"))
8614 (org-defkey orgstruct-mode-map [(shift meta return)]
8615 (orgstruct-make-binding 'org-insert-todo-heading 107
8616 [(meta return)] "\M-\C-m"))
8618 (org-defkey orgstruct-mode-map "\e\C-m"
8619 (orgstruct-make-binding 'org-insert-heading 108
8620 "\e\C-m" [?\e (return)]))
8621 (org-defkey orgstruct-mode-map [?\e (return)]
8622 (orgstruct-make-binding 'org-insert-heading 109
8623 [?\e (return)] "\e\C-m"))
8624 (org-defkey orgstruct-mode-map [?\e (shift return)]
8625 (orgstruct-make-binding 'org-insert-todo-heading 110
8626 [?\e (return)] "\e\C-m"))
8628 (unless org-local-vars
8629 (setq org-local-vars (org-get-local-variables)))
8633 (defun orgstruct-make-binding (fun n &rest keys)
8634 "Create a function for binding in the structure minor mode.
8635 FUN is the command to call inside a table. N is used to create a unique
8636 command name. KEYS are keys that should be checked in for a command
8637 to execute outside of tables."
8638 (eval
8639 (list 'defun
8640 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8641 '(arg)
8642 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8643 "Outside of structure, run the binding of `"
8644 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8645 "'.")
8646 '(interactive "p")
8647 (list 'if
8648 `(org-context-p 'headline 'item
8649 (and orgstruct-is-++
8650 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8651 'item-body))
8652 (list 'org-run-like-in-org-mode (list 'quote fun))
8653 (list 'let '(orgstruct-mode)
8654 (list 'call-interactively
8655 (append '(or)
8656 (mapcar (lambda (k)
8657 (list 'key-binding k))
8658 keys)
8659 '('orgstruct-error))))))))
8661 (defun org-contextualize-keys (alist contexts)
8662 "Return valid elements in ALIST depending on CONTEXTS.
8664 `org-agenda-custom-commands' or `org-capture-templates' are the
8665 values used for ALIST, and `org-agenda-custom-commands-contexts'
8666 or `org-capture-templates-contexts' are the associated contexts
8667 definitions."
8668 (let ((contexts
8669 ;; normalize contexts
8670 (mapcar
8671 (lambda(c) (cond ((listp (cadr c))
8672 (list (car c) (car c) (cadr c)))
8673 ((string= "" (cadr c))
8674 (list (car c) (car c) (caddr c)))
8675 (t c))) contexts))
8676 (a alist) c r s)
8677 ;; loop over all commands or templates
8678 (while (setq c (pop a))
8679 (let (vrules repl)
8680 (cond
8681 ((not (assoc (car c) contexts))
8682 (push c r))
8683 ((and (assoc (car c) contexts)
8684 (setq vrules (org-contextualize-validate-key
8685 (car c) contexts)))
8686 (mapc (lambda (vr)
8687 (when (not (equal (car vr) (cadr vr)))
8688 (setq repl vr))) vrules)
8689 (if (not repl) (push c r)
8690 (push (cadr repl) s)
8691 (push
8692 (cons (car c)
8693 (cdr (or (assoc (cadr repl) alist)
8694 (error "Undefined key `%s' as contextual replacement for `%s'"
8695 (cadr repl) (car c)))))
8696 r))))))
8697 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8698 (delq
8700 (delete-dups
8701 (mapcar (lambda (x)
8702 (let ((tpl (car x)))
8703 (when (not (delq
8705 (mapcar (lambda(y)
8706 (equal y tpl)) s))) x)))
8707 (reverse r))))))
8709 (defun org-contextualize-validate-key (key contexts)
8710 "Check CONTEXTS for agenda or capture KEY."
8711 (let (r rr res)
8712 (while (setq r (pop contexts))
8713 (mapc
8714 (lambda (rr)
8715 (when
8716 (and (equal key (car r))
8717 (if (functionp rr) (funcall rr)
8718 (or (and (eq (car rr) 'in-file)
8719 (buffer-file-name)
8720 (string-match (cdr rr) (buffer-file-name)))
8721 (and (eq (car rr) 'in-mode)
8722 (string-match (cdr rr) (symbol-name major-mode)))
8723 (when (and (eq (car rr) 'not-in-file)
8724 (buffer-file-name))
8725 (not (string-match (cdr rr) (buffer-file-name))))
8726 (when (eq (car rr) 'not-in-mode)
8727 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8728 (push r res)))
8729 (car (last r))))
8730 (delete-dups (delq nil res))))
8732 (defun org-context-p (&rest contexts)
8733 "Check if local context is any of CONTEXTS.
8734 Possible values in the list of contexts are `table', `headline', and `item'."
8735 (let ((pos (point)))
8736 (goto-char (point-at-bol))
8737 (prog1 (or (and (memq 'table contexts)
8738 (looking-at "[ \t]*|"))
8739 (and (memq 'headline contexts)
8740 (looking-at org-outline-regexp))
8741 (and (memq 'item contexts)
8742 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8743 (and (memq 'item-body contexts)
8744 (org-in-item-p)))
8745 (goto-char pos))))
8747 (defun org-get-local-variables ()
8748 "Return a list of all local variables in an Org mode buffer."
8749 (let (varlist)
8750 (with-current-buffer (get-buffer-create "*Org tmp*")
8751 (erase-buffer)
8752 (org-mode)
8753 (setq varlist (buffer-local-variables)))
8754 (kill-buffer "*Org tmp*")
8755 (delq nil
8756 (mapcar
8757 (lambda (x)
8758 (setq x
8759 (if (symbolp x)
8760 (list x)
8761 (list (car x) (list 'quote (cdr x)))))
8762 (if (string-match
8763 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8764 (symbol-name (car x)))
8765 x nil))
8766 varlist))))
8768 (defun org-clone-local-variables (from-buffer &optional regexp)
8769 "Clone local variables from FROM-BUFFER.
8770 Optional argument REGEXP selects variables to clone."
8771 (mapc
8772 (lambda (pair)
8773 (and (symbolp (car pair))
8774 (or (null regexp)
8775 (string-match regexp (symbol-name (car pair))))
8776 (set (make-local-variable (car pair))
8777 (cdr pair))))
8778 (buffer-local-variables from-buffer)))
8780 ;;;###autoload
8781 (defun org-run-like-in-org-mode (cmd)
8782 "Run a command, pretending that the current buffer is in Org-mode.
8783 This will temporarily bind local variables that are typically bound in
8784 Org-mode to the values they have in Org-mode, and then interactively
8785 call CMD."
8786 (org-load-modules-maybe)
8787 (unless org-local-vars
8788 (setq org-local-vars (org-get-local-variables)))
8789 (eval (list 'let org-local-vars
8790 (list 'call-interactively (list 'quote cmd)))))
8792 ;;;; Archiving
8794 (defun org-get-category (&optional pos force-refresh)
8795 "Get the category applying to position POS."
8796 (save-match-data
8797 (if force-refresh (org-refresh-category-properties))
8798 (let ((pos (or pos (point))))
8799 (or (get-text-property pos 'org-category)
8800 (progn (org-refresh-category-properties)
8801 (get-text-property pos 'org-category))))))
8803 (defun org-refresh-category-properties ()
8804 "Refresh category text properties in the buffer."
8805 (let ((case-fold-search t)
8806 (inhibit-read-only t)
8807 (def-cat (cond
8808 ((null org-category)
8809 (if buffer-file-name
8810 (file-name-sans-extension
8811 (file-name-nondirectory buffer-file-name))
8812 "???"))
8813 ((symbolp org-category) (symbol-name org-category))
8814 (t org-category)))
8815 beg end cat pos optionp)
8816 (org-unmodified
8817 (save-excursion
8818 (save-restriction
8819 (widen)
8820 (goto-char (point-min))
8821 (put-text-property (point) (point-max) 'org-category def-cat)
8822 (while (re-search-forward
8823 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8824 (setq pos (match-end 0)
8825 optionp (equal (char-after (match-beginning 0)) ?#)
8826 cat (org-trim (match-string 2)))
8827 (if optionp
8828 (setq beg (point-at-bol) end (point-max))
8829 (org-back-to-heading t)
8830 (setq beg (point) end (org-end-of-subtree t t)))
8831 (put-text-property beg end 'org-category cat)
8832 (put-text-property beg end 'org-category-position beg)
8833 (goto-char pos)))))))
8835 (defun org-refresh-properties (dprop tprop)
8836 "Refresh buffer text properties.
8837 DPROP is the drawer property and TPROP is the corresponding text
8838 property to set."
8839 (let ((case-fold-search t)
8840 (inhibit-read-only t) p)
8841 (org-unmodified
8842 (save-excursion
8843 (save-restriction
8844 (widen)
8845 (goto-char (point-min))
8846 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8847 (setq p (org-match-string-no-properties 1))
8848 (save-excursion
8849 (org-back-to-heading t)
8850 (put-text-property
8851 (point-at-bol) (point-at-eol) tprop p))))))))
8854 ;;;; Link Stuff
8856 ;;; Link abbreviations
8858 (defun org-link-expand-abbrev (link)
8859 "Apply replacements as defined in `org-link-abbrev-alist'."
8860 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8861 (let* ((key (match-string 1 link))
8862 (as (or (assoc key org-link-abbrev-alist-local)
8863 (assoc key org-link-abbrev-alist)))
8864 (tag (and (match-end 2) (match-string 3 link)))
8865 rpl)
8866 (if (not as)
8867 link
8868 (setq rpl (cdr as))
8869 (cond
8870 ((symbolp rpl) (funcall rpl tag))
8871 ((string-match "%(\\([^)]+\\))" rpl)
8872 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8873 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8874 ((string-match "%h" rpl)
8875 (replace-match (url-hexify-string (or tag "")) t t rpl))
8876 (t (concat rpl tag)))))
8877 link))
8879 ;;; Storing and inserting links
8881 (defvar org-insert-link-history nil
8882 "Minibuffer history for links inserted with `org-insert-link'.")
8884 (defvar org-stored-links nil
8885 "Contains the links stored with `org-store-link'.")
8887 (defvar org-store-link-plist nil
8888 "Plist with info about the most recently link created with `org-store-link'.")
8890 (defvar org-link-protocols nil
8891 "Link protocols added to Org-mode using `org-add-link-type'.")
8893 (defvar org-store-link-functions nil
8894 "List of functions that are called to create and store a link.
8895 Each function will be called in turn until one returns a non-nil
8896 value. Each function should check if it is responsible for creating
8897 this link (for example by looking at the major mode).
8898 If not, it must exit and return nil.
8899 If yes, it should return a non-nil value after a calling
8900 `org-store-link-props' with a list of properties and values.
8901 Special properties are:
8903 :type The link prefix, like \"http\". This must be given.
8904 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8905 This is obligatory as well.
8906 :description Optional default description for the second pair
8907 of brackets in an Org-mode link. The user can still change
8908 this when inserting this link into an Org-mode buffer.
8910 In addition to these, any additional properties can be specified
8911 and then used in capture templates.")
8913 (defun org-add-link-type (type &optional follow export)
8914 "Add TYPE to the list of `org-link-types'.
8915 Re-compute all regular expressions depending on `org-link-types'
8917 FOLLOW and EXPORT are two functions.
8919 FOLLOW should take the link path as the single argument and do whatever
8920 is necessary to follow the link, for example find a file or display
8921 a mail message.
8923 EXPORT should format the link path for export to one of the export formats.
8924 It should be a function accepting three arguments:
8926 path the path of the link, the text after the prefix (like \"http:\")
8927 desc the description of the link, if any, or a description added by
8928 org-export-normalize-links if there is none
8929 format the export format, a symbol like `html' or `latex' or `ascii'..
8931 The function may use the FORMAT information to return different values
8932 depending on the format. The return value will be put literally into
8933 the exported file. If the return value is nil, this means Org should
8934 do what it normally does with links which do not have EXPORT defined.
8936 Org-mode has a built-in default for exporting links. If you are happy with
8937 this default, there is no need to define an export function for the link
8938 type. For a simple example of an export function, see `org-bbdb.el'."
8939 (add-to-list 'org-link-types type t)
8940 (org-make-link-regexps)
8941 (if (assoc type org-link-protocols)
8942 (setcdr (assoc type org-link-protocols) (list follow export))
8943 (push (list type follow export) org-link-protocols)))
8945 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8946 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8948 ;;;###autoload
8949 (defun org-store-link (arg)
8950 "\\<org-mode-map>Store an org-link to the current location.
8951 This link is added to `org-stored-links' and can later be inserted
8952 into an org-buffer with \\[org-insert-link].
8954 For some link types, a prefix arg is interpreted.
8955 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8956 For file links, arg negates `org-context-in-file-links'.
8958 A double prefix arg force skipping storing functions that are not
8959 part of Org's core."
8960 (interactive "P")
8961 (org-load-modules-maybe)
8962 (setq org-store-link-plist nil) ; reset
8963 (org-with-limited-levels
8964 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8965 (cond
8966 ((and (not (equal arg '(16)))
8967 (setq sfuns
8968 (delq
8969 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8970 org-store-link-functions))
8971 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8972 (or (and (cdr sfuns)
8973 (funcall (intern
8974 (completing-read "Which function for creating the link? "
8975 sfunsn t (car sfunsn)))))
8976 (funcall (caar sfuns)))
8977 (setq link (plist-get org-store-link-plist :link)
8978 desc (or (plist-get org-store-link-plist :description) link))))
8979 ((org-src-edit-buffer-p)
8980 (let (label gc)
8981 (while (or (not label)
8982 (save-excursion
8983 (save-restriction
8984 (widen)
8985 (goto-char (point-min))
8986 (re-search-forward
8987 (regexp-quote (format org-coderef-label-format label))
8988 nil t))))
8989 (when label (message "Label exists already") (sit-for 2))
8990 (setq label (read-string "Code line label: " label)))
8991 (end-of-line 1)
8992 (setq link (format org-coderef-label-format label))
8993 (setq gc (- 79 (length link)))
8994 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8995 (insert link)
8996 (setq link (concat "(" label ")") desc nil)))
8998 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8999 ;; We are in the agenda, link to referenced location
9000 (let ((m (or (get-text-property (point) 'org-hd-marker)
9001 (get-text-property (point) 'org-marker))))
9002 (when m
9003 (org-with-point-at m
9004 (setq agenda-link
9005 (if (org-called-interactively-p 'any)
9006 (call-interactively 'org-store-link)
9007 (org-store-link nil)))))))
9009 ((eq major-mode 'calendar-mode)
9010 (let ((cd (calendar-cursor-to-date)))
9011 (setq link
9012 (format-time-string
9013 (car org-time-stamp-formats)
9014 (apply 'encode-time
9015 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9016 nil nil nil))))
9017 (org-store-link-props :type "calendar" :date cd)))
9019 ((eq major-mode 'help-mode)
9020 (setq link (concat "help:" (save-excursion
9021 (goto-char (point-min))
9022 (looking-at "^[^ ]+")
9023 (match-string 0))))
9024 (org-store-link-props :type "help"))
9026 ((eq major-mode 'w3-mode)
9027 (setq cpltxt (if (and (buffer-name)
9028 (not (string-match "Untitled" (buffer-name))))
9029 (buffer-name)
9030 (url-view-url t))
9031 link (url-view-url t))
9032 (org-store-link-props :type "w3" :url (url-view-url t)))
9034 ((setq search (run-hook-with-args-until-success
9035 'org-create-file-search-functions))
9036 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9037 "::" search))
9038 (setq cpltxt (or description link)))
9040 ((eq major-mode 'image-mode)
9041 (setq cpltxt (concat "file:"
9042 (abbreviate-file-name buffer-file-name))
9043 link cpltxt)
9044 (org-store-link-props :type "image" :file buffer-file-name))
9046 ((eq major-mode 'dired-mode)
9047 ;; link to the file in the current line
9048 (let ((file (dired-get-filename nil t)))
9049 (setq file (if file
9050 (abbreviate-file-name
9051 (expand-file-name (dired-get-filename nil t)))
9052 ;; otherwise, no file so use current directory.
9053 default-directory))
9054 (setq cpltxt (concat "file:" file)
9055 link cpltxt)))
9057 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9058 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9059 (cond
9060 ((org-in-regexp "<<\\(.*?\\)>>")
9061 (setq cpltxt
9062 (concat "file:"
9063 (abbreviate-file-name
9064 (buffer-file-name (buffer-base-buffer)))
9065 "::" (match-string 1))
9066 link cpltxt))
9067 ((and (featurep 'org-id)
9068 (or (eq org-id-link-to-org-use-id t)
9069 (and (org-called-interactively-p 'any)
9070 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9071 (and (eq org-id-link-to-org-use-id
9072 'create-if-interactive-and-no-custom-id)
9073 (not custom-id))))
9074 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9075 ;; We can make a link using the ID.
9076 (setq link (condition-case nil
9077 (prog1 (org-id-store-link)
9078 (setq desc (plist-get org-store-link-plist :description)))
9079 (error
9080 ;; probably before first headline, link to file only
9081 (concat "file:"
9082 (abbreviate-file-name
9083 (buffer-file-name (buffer-base-buffer))))))))
9085 ;; Just link to current headline
9086 (setq cpltxt (concat "file:"
9087 (abbreviate-file-name
9088 (buffer-file-name (buffer-base-buffer)))))
9089 ;; Add a context search string
9090 (when (org-xor org-context-in-file-links arg)
9091 (let* ((ee (org-element-at-point))
9092 (et (org-element-type ee))
9093 (ev (plist-get (cadr ee) :value)))
9094 (setq txt (cond
9095 ((org-at-heading-p) nil)
9096 ((eq et 'keyword) ev)
9097 ((org-region-active-p)
9098 (buffer-substring (region-beginning) (region-end)))))
9099 (when (or (null txt) (string-match "\\S-" txt))
9100 (setq cpltxt
9101 (concat cpltxt "::"
9102 (condition-case nil
9103 (org-make-org-heading-search-string txt)
9104 (error "")))
9105 desc (or (and (eq et 'keyword) ev)
9106 (nth 4 (ignore-errors (org-heading-components)))
9107 "NONE")))))
9108 (if (string-match "::\\'" cpltxt)
9109 (setq cpltxt (substring cpltxt 0 -2)))
9110 (setq link cpltxt))))
9112 ((buffer-file-name (buffer-base-buffer))
9113 ;; Just link to this file here.
9114 (setq cpltxt (concat "file:"
9115 (abbreviate-file-name
9116 (buffer-file-name (buffer-base-buffer)))))
9117 ;; Add a context string
9118 (when (org-xor org-context-in-file-links arg)
9119 (setq txt (if (org-region-active-p)
9120 (buffer-substring (region-beginning) (region-end))
9121 (buffer-substring (point-at-bol) (point-at-eol))))
9122 ;; Only use search option if there is some text.
9123 (when (string-match "\\S-" txt)
9124 (setq cpltxt
9125 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9126 desc "NONE")))
9127 (setq link cpltxt))
9129 ((org-called-interactively-p 'interactive)
9130 (user-error "No method for storing a link from this buffer"))
9132 (t (setq link nil)))
9134 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9135 (setq link (or link cpltxt)
9136 desc (or desc cpltxt))
9137 (cond ((equal desc "NONE") (setq desc nil))
9138 ((string-match org-bracket-link-regexp desc)
9139 (setq desc (replace-regexp-in-string
9140 org-bracket-link-regexp
9141 (concat "\\3" (if (equal (length (match-string 0 desc))
9142 (length desc)) "*" "")) desc))))
9144 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9145 (progn
9146 (setq org-stored-links
9147 (cons (list link desc) org-stored-links))
9148 (message "Stored: %s" (or desc link))
9149 (when custom-id
9150 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9151 "::#" custom-id))
9152 (setq org-stored-links
9153 (cons (list link desc) org-stored-links))))
9154 (or agenda-link (and link (org-make-link-string link desc)))))))
9156 (defun org-store-link-props (&rest plist)
9157 "Store link properties, extract names and addresses."
9158 (let (x adr)
9159 (when (setq x (plist-get plist :from))
9160 (setq adr (mail-extract-address-components x))
9161 (setq plist (plist-put plist :fromname (car adr)))
9162 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9163 (when (setq x (plist-get plist :to))
9164 (setq adr (mail-extract-address-components x))
9165 (setq plist (plist-put plist :toname (car adr)))
9166 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9167 (let ((from (plist-get plist :from))
9168 (to (plist-get plist :to)))
9169 (when (and from to org-from-is-user-regexp)
9170 (setq plist
9171 (plist-put plist :fromto
9172 (if (string-match org-from-is-user-regexp from)
9173 (concat "to %t")
9174 (concat "from %f"))))))
9175 (setq org-store-link-plist plist))
9177 (defun org-add-link-props (&rest plist)
9178 "Add these properties to the link property list."
9179 (let (key value)
9180 (while plist
9181 (setq key (pop plist) value (pop plist))
9182 (setq org-store-link-plist
9183 (plist-put org-store-link-plist key value)))))
9185 (defun org-email-link-description (&optional fmt)
9186 "Return the description part of an email link.
9187 This takes information from `org-store-link-plist' and formats it
9188 according to FMT (default from `org-email-link-description-format')."
9189 (setq fmt (or fmt org-email-link-description-format))
9190 (let* ((p org-store-link-plist)
9191 (to (plist-get p :toaddress))
9192 (from (plist-get p :fromaddress))
9193 (table
9194 (list
9195 (cons "%c" (plist-get p :fromto))
9196 (cons "%F" (plist-get p :from))
9197 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9198 (cons "%T" (plist-get p :to))
9199 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9200 (cons "%s" (plist-get p :subject))
9201 (cons "%d" (plist-get p :date))
9202 (cons "%m" (plist-get p :message-id)))))
9203 (when (string-match "%c" fmt)
9204 ;; Check if the user wrote this message
9205 (if (and org-from-is-user-regexp from to
9206 (save-match-data (string-match org-from-is-user-regexp from)))
9207 (setq fmt (replace-match "to %t" t t fmt))
9208 (setq fmt (replace-match "from %f" t t fmt))))
9209 (org-replace-escapes fmt table)))
9211 (defun org-make-org-heading-search-string (&optional string)
9212 "Make search string for the current headline or STRING."
9213 (let ((s (or string
9214 (and (derived-mode-p 'org-mode)
9215 (save-excursion
9216 (org-back-to-heading t)
9217 (plist-get (cadr (org-element-at-point))
9218 :raw-value)))))
9219 (lines org-context-in-file-links))
9220 (or string (setq s (concat "*" s))) ; Add * for headlines
9221 (when (and string (integerp lines) (> lines 0))
9222 (let ((slines (org-split-string s "\n")))
9223 (when (< lines (length slines))
9224 (setq s (mapconcat
9225 'identity
9226 (reverse (nthcdr (- (length slines) lines)
9227 (reverse slines))) "\n")))))
9228 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9230 (defun org-make-link-string (link &optional description)
9231 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9232 (unless (string-match "\\S-" link)
9233 (error "Empty link"))
9234 (when (and description
9235 (stringp description)
9236 (not (string-match "\\S-" description)))
9237 (setq description nil))
9238 (when (stringp description)
9239 ;; Remove brackets from the description, they are fatal.
9240 (while (string-match "\\[" description)
9241 (setq description (replace-match "{" t t description)))
9242 (while (string-match "\\]" description)
9243 (setq description (replace-match "}" t t description))))
9244 (when (equal link description)
9245 ;; No description needed, it is identical
9246 (setq description nil))
9247 (when (and (not description)
9248 (not (string-match (org-image-file-name-regexp) link))
9249 (not (equal link (org-link-escape link))))
9250 (setq description (org-extract-attributes link)))
9251 (setq link
9252 (cond ((string-match (org-image-file-name-regexp) link) link)
9253 ((string-match org-link-types-re link)
9254 (concat (match-string 1 link)
9255 (org-link-escape (substring link (match-end 1)))))
9256 (t (org-link-escape link))))
9257 (concat "[[" link "]"
9258 (if description (concat "[" description "]") "")
9259 "]"))
9261 (defconst org-link-escape-chars
9262 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9263 "List of characters that should be escaped in link.
9264 This is the list that is used for internal purposes.")
9266 (defconst org-link-escape-chars-browser
9267 '(?\ )
9268 "List of escapes for characters that are problematic in links.
9269 This is the list that is used before handing over to the browser.")
9271 (defun org-link-escape (text &optional table merge)
9272 "Return percent escaped representation of TEXT.
9273 TEXT is a string with the text to escape.
9274 Optional argument TABLE is a list with characters that should be
9275 escaped. When nil, `org-link-escape-chars' is used.
9276 If optional argument MERGE is set, merge TABLE into
9277 `org-link-escape-chars'."
9278 (cond
9279 ((and table merge)
9280 (mapc (lambda (defchr)
9281 (unless (member defchr table)
9282 (setq table (cons defchr table)))) org-link-escape-chars))
9283 ((null table)
9284 (setq table org-link-escape-chars)))
9285 (mapconcat
9286 (lambda (char)
9287 (if (or (member char table)
9288 (and (or (< char 32) (= char 37) (> char 126))
9289 org-url-hexify-p))
9290 (mapconcat (lambda (sequence-element)
9291 (format "%%%.2X" sequence-element))
9292 (or (encode-coding-char char 'utf-8)
9293 (error "Unable to percent escape character: %s"
9294 (char-to-string char))) "")
9295 (char-to-string char))) text ""))
9297 (defun org-link-unescape (str)
9298 "Unhex hexified Unicode strings as returned from the JavaScript function
9299 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9300 (unless (and (null str) (string= "" str))
9301 (let ((pos 0) (case-fold-search t) unhexed)
9302 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9303 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9304 (setq str (replace-match unhexed t t str))
9305 (setq pos (+ pos (length unhexed))))))
9306 str)
9308 (defun org-link-unescape-compound (hex)
9309 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9310 Note: this function also decodes single byte encodings like
9311 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9312 (save-match-data
9313 (let* ((bytes (cdr (split-string hex "%")))
9314 (ret "")
9315 (eat 0)
9316 (sum 0))
9317 (while bytes
9318 (let* ((val (string-to-number (pop bytes) 16))
9319 (shift-xor
9320 (if (= 0 eat)
9321 (cond
9322 ((>= val 252) (cons 6 252))
9323 ((>= val 248) (cons 5 248))
9324 ((>= val 240) (cons 4 240))
9325 ((>= val 224) (cons 3 224))
9326 ((>= val 192) (cons 2 192))
9327 (t (cons 0 0)))
9328 (cons 6 128))))
9329 (if (>= val 192) (setq eat (car shift-xor)))
9330 (setq val (logxor val (cdr shift-xor)))
9331 (setq sum (+ (lsh sum (car shift-xor)) val))
9332 (if (> eat 0) (setq eat (- eat 1)))
9333 (cond
9334 ((= 0 eat) ;multi byte
9335 (setq ret (concat ret (org-char-to-string sum)))
9336 (setq sum 0))
9337 ((not bytes) ; single byte(s)
9338 (setq ret (org-link-unescape-single-byte-sequence hex))))
9339 )) ;; end (while bytes
9340 ret )))
9342 (defun org-link-unescape-single-byte-sequence (hex)
9343 "Unhexify hex-encoded single byte character sequences."
9344 (mapconcat (lambda (byte)
9345 (char-to-string (string-to-number byte 16)))
9346 (cdr (split-string hex "%")) ""))
9348 (defun org-xor (a b)
9349 "Exclusive or."
9350 (if a (not b) b))
9352 (defun org-fixup-message-id-for-http (s)
9353 "Replace special characters in a message id, so it can be used in an http query."
9354 (when (string-match "%" s)
9355 (setq s (mapconcat (lambda (c)
9356 (if (eq c ?%)
9357 "%25"
9358 (char-to-string c)))
9359 s "")))
9360 (while (string-match "<" s)
9361 (setq s (replace-match "%3C" t t s)))
9362 (while (string-match ">" s)
9363 (setq s (replace-match "%3E" t t s)))
9364 (while (string-match "@" s)
9365 (setq s (replace-match "%40" t t s)))
9368 (defun org-link-prettify (link)
9369 "Return a human-readable representation of LINK.
9370 The car of LINK must be a raw link the cdr of LINK must be either
9371 a link description or nil."
9372 (let ((desc (or (cadr link) "<no description>")))
9373 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9374 "<" (car link) ">")))
9376 ;;;###autoload
9377 (defun org-insert-link-global ()
9378 "Insert a link like Org-mode does.
9379 This command can be called in any mode to insert a link in Org-mode syntax."
9380 (interactive)
9381 (org-load-modules-maybe)
9382 (org-run-like-in-org-mode 'org-insert-link))
9384 (defun org-insert-all-links (&optional keep)
9385 "Insert all links in `org-stored-links'."
9386 (interactive "P")
9387 (let ((links (copy-sequence org-stored-links)) l)
9388 (while (setq l (if keep (pop links) (pop org-stored-links)))
9389 (insert "- ")
9390 (org-insert-link nil (car l) (cadr l))
9391 (insert "\n"))))
9393 (defun org-link-fontify-links-to-this-file ()
9394 "Fontify links to the current file in `org-stored-links'."
9395 (let ((f (buffer-file-name)) a b)
9396 (setq a (mapcar (lambda(l)
9397 (let ((ll (car l)))
9398 (when (and (string-match "^file:\\(.+\\)::" ll)
9399 (equal f (expand-file-name (match-string 1 ll))))
9400 ll)))
9401 org-stored-links))
9402 (when (featurep 'org-id)
9403 (setq b (mapcar (lambda(l)
9404 (let ((ll (car l)))
9405 (when (and (string-match "^id:\\(.+\\)$" ll)
9406 (equal f (expand-file-name
9407 (or (org-id-find-id-file
9408 (match-string 1 ll)) ""))))
9409 ll)))
9410 org-stored-links)))
9411 (mapcar (lambda(l)
9412 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9413 (delq nil (append a b)))))
9415 (defvar org-link-links-in-this-file nil)
9416 (defun org-insert-link (&optional complete-file link-location default-description)
9417 "Insert a link. At the prompt, enter the link.
9419 Completion can be used to insert any of the link protocol prefixes like
9420 http or ftp in use.
9422 The history can be used to select a link previously stored with
9423 `org-store-link'. When the empty string is entered (i.e. if you just
9424 press RET at the prompt), the link defaults to the most recently
9425 stored link. As SPC triggers completion in the minibuffer, you need to
9426 use M-SPC or C-q SPC to force the insertion of a space character.
9428 You will also be prompted for a description, and if one is given, it will
9429 be displayed in the buffer instead of the link.
9431 If there is already a link at point, this command will allow you to edit link
9432 and description parts.
9434 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9435 be selected using completion. The path to the file will be relative to the
9436 current directory if the file is in the current directory or a subdirectory.
9437 Otherwise, the link will be the absolute path as completed in the minibuffer
9438 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9439 option `org-link-file-path-type'.
9441 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9442 the current directory or below.
9444 With three \\[universal-argument] prefixes, negate the meaning of
9445 `org-keep-stored-link-after-insertion'.
9447 If `org-make-link-description-function' is non-nil, this function will be
9448 called with the link target, and the result will be the default
9449 link description.
9451 If the LINK-LOCATION parameter is non-nil, this value will be
9452 used as the link location instead of reading one interactively.
9454 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9455 be used as the default description."
9456 (interactive "P")
9457 (let* ((wcf (current-window-configuration))
9458 (origbuf (current-buffer))
9459 (region (if (org-region-active-p)
9460 (buffer-substring (region-beginning) (region-end))))
9461 (remove (and region (list (region-beginning) (region-end))))
9462 (desc region)
9463 tmphist ; byte-compile incorrectly complains about this
9464 (link link-location)
9465 (abbrevs org-link-abbrev-alist-local)
9466 entry file all-prefixes auto-desc)
9467 (cond
9468 (link-location) ; specified by arg, just use it.
9469 ((org-in-regexp org-bracket-link-regexp 1)
9470 ;; We do have a link at point, and we are going to edit it.
9471 (setq remove (list (match-beginning 0) (match-end 0)))
9472 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9473 (setq link (read-string "Link: "
9474 (org-link-unescape
9475 (org-match-string-no-properties 1)))))
9476 ((or (org-in-regexp org-angle-link-re)
9477 (org-in-regexp org-plain-link-re))
9478 ;; Convert to bracket link
9479 (setq remove (list (match-beginning 0) (match-end 0))
9480 link (read-string "Link: "
9481 (org-remove-angle-brackets (match-string 0)))))
9482 ((member complete-file '((4) (16)))
9483 ;; Completing read for file names.
9484 (setq link (org-file-complete-link complete-file)))
9486 ;; Read link, with completion for stored links.
9487 (org-link-fontify-links-to-this-file)
9488 (org-switch-to-buffer-other-window "*Org Links*")
9489 (with-current-buffer "*Org Links*"
9490 (erase-buffer)
9491 (insert "Insert a link.
9492 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9493 (when org-stored-links
9494 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9495 (insert (mapconcat 'org-link-prettify
9496 (reverse org-stored-links) "\n")))
9497 (goto-char (point-min)))
9498 (let ((cw (selected-window)))
9499 (select-window (get-buffer-window "*Org Links*" 'visible))
9500 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9501 (unless (pos-visible-in-window-p (point-max))
9502 (org-fit-window-to-buffer))
9503 (and (window-live-p cw) (select-window cw)))
9504 ;; Fake a link history, containing the stored links.
9505 (setq tmphist (append (mapcar 'car org-stored-links)
9506 org-insert-link-history))
9507 (setq all-prefixes (append (mapcar 'car abbrevs)
9508 (mapcar 'car org-link-abbrev-alist)
9509 org-link-types))
9510 (unwind-protect
9511 (progn
9512 (setq link
9513 (org-completing-read
9514 "Link: "
9515 (append
9516 (mapcar (lambda (x) (concat x ":"))
9517 all-prefixes)
9518 (mapcar 'car org-stored-links))
9519 nil nil nil
9520 'tmphist
9521 (caar org-stored-links)))
9522 (if (not (string-match "\\S-" link))
9523 (error "No link selected"))
9524 (mapc (lambda(l)
9525 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9526 org-stored-links)
9527 (if (or (member link all-prefixes)
9528 (and (equal ":" (substring link -1))
9529 (member (substring link 0 -1) all-prefixes)
9530 (setq link (substring link 0 -1))))
9531 (setq link (with-current-buffer origbuf
9532 (org-link-try-special-completion link)))))
9533 (set-window-configuration wcf)
9534 (kill-buffer "*Org Links*"))
9535 (setq entry (assoc link org-stored-links))
9536 (or entry (push link org-insert-link-history))
9537 (setq desc (or desc (nth 1 entry)))))
9539 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9540 (not org-keep-stored-link-after-insertion))
9541 (setq org-stored-links (delq (assoc link org-stored-links)
9542 org-stored-links)))
9544 (if (string-match org-plain-link-re link)
9545 ;; URL-like link, normalize the use of angular brackets.
9546 (setq link (org-remove-angle-brackets link)))
9548 ;; Check if we are linking to the current file with a search
9549 ;; option If yes, simplify the link by using only the search
9550 ;; option.
9551 (when (and buffer-file-name
9552 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9553 (let* ((path (match-string 1 link))
9554 (case-fold-search nil)
9555 (search (match-string 2 link)))
9556 (save-match-data
9557 (if (equal (file-truename buffer-file-name) (file-truename path))
9558 ;; We are linking to this same file, with a search option
9559 (setq link search)))))
9561 ;; Check if we can/should use a relative path. If yes, simplify the link
9562 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9563 (let* ((type (match-string 1 link))
9564 (path (match-string 2 link))
9565 (origpath path)
9566 (case-fold-search nil))
9567 (cond
9568 ((or (eq org-link-file-path-type 'absolute)
9569 (equal complete-file '(16)))
9570 (setq path (abbreviate-file-name (expand-file-name path))))
9571 ((eq org-link-file-path-type 'noabbrev)
9572 (setq path (expand-file-name path)))
9573 ((eq org-link-file-path-type 'relative)
9574 (setq path (file-relative-name path)))
9576 (save-match-data
9577 (if (string-match (concat "^" (regexp-quote
9578 (expand-file-name
9579 (file-name-as-directory
9580 default-directory))))
9581 (expand-file-name path))
9582 ;; We are linking a file with relative path name.
9583 (setq path (substring (expand-file-name path)
9584 (match-end 0)))
9585 (setq path (abbreviate-file-name (expand-file-name path)))))))
9586 (setq link (concat type path))
9587 (if (equal desc origpath)
9588 (setq desc path))))
9590 (if org-make-link-description-function
9591 (setq desc
9592 (or (condition-case nil
9593 (funcall org-make-link-description-function link desc)
9594 (error (progn (message "Can't get link description from `%s'"
9595 (symbol-name org-make-link-description-function))
9596 (sit-for 2) nil)))
9597 (read-string "Description: " default-description)))
9598 (if default-description (setq desc default-description)
9599 (setq desc (or (and auto-desc desc)
9600 (read-string "Description: " desc)))))
9602 (unless (string-match "\\S-" desc) (setq desc nil))
9603 (if remove (apply 'delete-region remove))
9604 (insert (org-make-link-string link desc))))
9606 (defun org-link-try-special-completion (type)
9607 "If there is completion support for link type TYPE, offer it."
9608 (let ((fun (intern (concat "org-" type "-complete-link"))))
9609 (if (functionp fun)
9610 (funcall fun)
9611 (read-string "Link (no completion support): " (concat type ":")))))
9613 (defun org-file-complete-link (&optional arg)
9614 "Create a file link using completion."
9615 (let (file link)
9616 (setq file (org-iread-file-name "File: "))
9617 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9618 (pwd1 (file-name-as-directory (abbreviate-file-name
9619 (expand-file-name ".")))))
9620 (cond
9621 ((equal arg '(16))
9622 (setq link (concat
9623 "file:"
9624 (abbreviate-file-name (expand-file-name file)))))
9625 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9626 (setq link (concat "file:" (match-string 1 file))))
9627 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9628 (expand-file-name file))
9629 (setq link (concat
9630 "file:" (match-string 1 (expand-file-name file)))))
9631 (t (setq link (concat "file:" file)))))
9632 link))
9634 (defun org-iread-file-name (&rest args)
9635 "Read-file-name using `ido-mode' speedup if available.
9636 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9637 See `read-file-name' for a description of parameters."
9638 (org-without-partial-completion
9639 (if (and org-completion-use-ido
9640 (fboundp 'ido-read-file-name)
9641 (boundp 'ido-mode) ido-mode
9642 (listp (second args)))
9643 (let ((ido-enter-matching-directory nil))
9644 (apply 'ido-read-file-name args))
9645 (apply 'read-file-name args))))
9647 (defun org-completing-read (&rest args)
9648 "Completing-read with SPACE being a normal character."
9649 (let ((enable-recursive-minibuffers t)
9650 (minibuffer-local-completion-map
9651 (copy-keymap minibuffer-local-completion-map)))
9652 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9653 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9654 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9655 (apply 'org-icompleting-read args)))
9657 (defun org-completing-read-no-i (&rest args)
9658 (let (org-completion-use-ido org-completion-use-iswitchb)
9659 (apply 'org-completing-read args)))
9661 (defun org-iswitchb-completing-read (prompt choices &rest args)
9662 "Use iswitch as a completing-read replacement to choose from choices.
9663 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9664 from."
9665 (let* ((iswitchb-use-virtual-buffers nil)
9666 (iswitchb-make-buflist-hook
9667 (lambda ()
9668 (setq iswitchb-temp-buflist choices))))
9669 (iswitchb-read-buffer prompt)))
9671 (defun org-icompleting-read (&rest args)
9672 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9673 (org-without-partial-completion
9674 (if (and org-completion-use-ido
9675 (fboundp 'ido-completing-read)
9676 (boundp 'ido-mode) ido-mode
9677 (listp (second args)))
9678 (let ((ido-enter-matching-directory nil))
9679 (apply 'ido-completing-read (concat (car args))
9680 (if (consp (car (nth 1 args)))
9681 (mapcar 'car (nth 1 args))
9682 (nth 1 args))
9683 (cddr args)))
9684 (if (and org-completion-use-iswitchb
9685 (boundp 'iswitchb-mode) iswitchb-mode
9686 (listp (second args)))
9687 (apply 'org-iswitchb-completing-read (concat (car args))
9688 (if (consp (car (nth 1 args)))
9689 (mapcar 'car (nth 1 args))
9690 (nth 1 args))
9691 (cddr args))
9692 (apply 'completing-read args)))))
9694 (defun org-extract-attributes (s)
9695 "Extract the attributes cookie from a string and set as text property."
9696 (let (a attr (start 0) key value)
9697 (save-match-data
9698 (when (string-match "{{\\([^}]+\\)}}$" s)
9699 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9700 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9701 (setq key (match-string 1 a) value (match-string 2 a)
9702 start (match-end 0)
9703 attr (plist-put attr (intern key) value))))
9704 (org-add-props s nil 'org-attr attr))
9707 (defun org-extract-attributes-from-string (tag)
9708 (let (key value attr)
9709 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9710 (setq key (match-string 1 tag) value (match-string 2 tag)
9711 tag (replace-match "" t t tag)
9712 attr (plist-put attr (intern key) value)))
9713 (cons tag attr)))
9715 (defun org-attributes-to-string (plist)
9716 "Format a property list into an HTML attribute list."
9717 (let ((s "") key value)
9718 (while plist
9719 (setq key (pop plist) value (pop plist))
9720 (and value
9721 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9724 ;;; Opening/following a link
9726 (defvar org-link-search-failed nil)
9728 (defvar org-open-link-functions nil
9729 "Hook for functions finding a plain text link.
9730 These functions must take a single argument, the link content.
9731 They will be called for links that look like [[link text][description]]
9732 when LINK TEXT does not have a protocol like \"http:\" and does not look
9733 like a filename (e.g. \"./blue.png\").
9735 These functions will be called *before* Org attempts to resolve the
9736 link by doing text searches in the current buffer - so if you want a
9737 link \"[[target]]\" to still find \"<<target>>\", your function should
9738 handle this as a special case.
9740 When the function does handle the link, it must return a non-nil value.
9741 If it decides that it is not responsible for this link, it must return
9742 nil to indicate that that Org-mode can continue with other options
9743 like exact and fuzzy text search.")
9745 (defun org-next-link ()
9746 "Move forward to the next link.
9747 If the link is in hidden text, expose it."
9748 (interactive)
9749 (when (and org-link-search-failed (eq this-command last-command))
9750 (goto-char (point-min))
9751 (message "Link search wrapped back to beginning of buffer"))
9752 (setq org-link-search-failed nil)
9753 (let* ((pos (point))
9754 (ct (org-context))
9755 (a (assoc :link ct)))
9756 (if a (goto-char (nth 2 a)))
9757 (if (re-search-forward org-any-link-re nil t)
9758 (progn
9759 (goto-char (match-beginning 0))
9760 (if (outline-invisible-p) (org-show-context)))
9761 (goto-char pos)
9762 (setq org-link-search-failed t)
9763 (error "No further link found"))))
9765 (defun org-previous-link ()
9766 "Move backward to the previous link.
9767 If the link is in hidden text, expose it."
9768 (interactive)
9769 (when (and org-link-search-failed (eq this-command last-command))
9770 (goto-char (point-max))
9771 (message "Link search wrapped back to end of buffer"))
9772 (setq org-link-search-failed nil)
9773 (let* ((pos (point))
9774 (ct (org-context))
9775 (a (assoc :link ct)))
9776 (if a (goto-char (nth 1 a)))
9777 (if (re-search-backward org-any-link-re nil t)
9778 (progn
9779 (goto-char (match-beginning 0))
9780 (if (outline-invisible-p) (org-show-context)))
9781 (goto-char pos)
9782 (setq org-link-search-failed t)
9783 (error "No further link found"))))
9785 (defun org-translate-link (s)
9786 "Translate a link string if a translation function has been defined."
9787 (if (and org-link-translation-function
9788 (fboundp org-link-translation-function)
9789 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9790 (progn
9791 (setq s (funcall org-link-translation-function
9792 (match-string 1 s) (match-string 2 s)))
9793 (concat (car s) ":" (cdr s)))
9796 (defun org-translate-link-from-planner (type path)
9797 "Translate a link from Emacs Planner syntax so that Org can follow it.
9798 This is still an experimental function, your mileage may vary."
9799 (cond
9800 ((member type '("http" "https" "news" "ftp"))
9801 ;; standard Internet links are the same.
9802 nil)
9803 ((and (equal type "irc") (string-match "^//" path))
9804 ;; Planner has two / at the beginning of an irc link, we have 1.
9805 ;; We should have zero, actually....
9806 (setq path (substring path 1)))
9807 ((and (equal type "lisp") (string-match "^/" path))
9808 ;; Planner has a slash, we do not.
9809 (setq type "elisp" path (substring path 1)))
9810 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9811 ;; A typical message link. Planner has the id after the final slash,
9812 ;; we separate it with a hash mark
9813 (setq path (concat (match-string 1 path) "#"
9814 (org-remove-angle-brackets (match-string 2 path)))))
9816 (cons type path))
9818 (defun org-find-file-at-mouse (ev)
9819 "Open file link or URL at mouse."
9820 (interactive "e")
9821 (mouse-set-point ev)
9822 (org-open-at-point 'in-emacs))
9824 (defun org-open-at-mouse (ev)
9825 "Open file link or URL at mouse.
9826 See the docstring of `org-open-file' for details."
9827 (interactive "e")
9828 (mouse-set-point ev)
9829 (if (eq major-mode 'org-agenda-mode)
9830 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9831 (org-open-at-point))
9833 (defvar org-window-config-before-follow-link nil
9834 "The window configuration before following a link.
9835 This is saved in case the need arises to restore it.")
9837 (defvar org-open-link-marker (make-marker)
9838 "Marker pointing to the location where `org-open-at-point; was called.")
9840 ;;;###autoload
9841 (defun org-open-at-point-global ()
9842 "Follow a link like Org-mode does.
9843 This command can be called in any mode to follow a link that has
9844 Org-mode syntax."
9845 (interactive)
9846 (org-run-like-in-org-mode 'org-open-at-point))
9848 ;;;###autoload
9849 (defun org-open-link-from-string (s &optional arg reference-buffer)
9850 "Open a link in the string S, as if it was in Org-mode."
9851 (interactive "sLink: \nP")
9852 (let ((reference-buffer (or reference-buffer (current-buffer))))
9853 (with-temp-buffer
9854 (let ((org-inhibit-startup (not reference-buffer)))
9855 (org-mode)
9856 (insert s)
9857 (goto-char (point-min))
9858 (when reference-buffer
9859 (setq org-link-abbrev-alist-local
9860 (with-current-buffer reference-buffer
9861 org-link-abbrev-alist-local)))
9862 (org-open-at-point arg reference-buffer)))))
9864 (defvar org-open-at-point-functions nil
9865 "Hook that is run when following a link at point.
9867 Functions in this hook must return t if they identify and follow
9868 a link at point. If they don't find anything interesting at point,
9869 they must return nil.")
9871 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9872 (defun org-open-at-point (&optional arg reference-buffer)
9873 "Open link at or after point.
9874 If there is no link at point, this function will search forward up to
9875 the end of the current line.
9876 Normally, files will be opened by an appropriate application. If the
9877 optional prefix argument ARG is non-nil, Emacs will visit the file.
9878 With a double prefix argument, try to open outside of Emacs, in the
9879 application the system uses for this file type."
9880 (interactive "P")
9881 ;; if in a code block, then open the block's results
9882 (unless (call-interactively #'org-babel-open-src-block-result)
9883 (org-load-modules-maybe)
9884 (move-marker org-open-link-marker (point))
9885 (setq org-window-config-before-follow-link (current-window-configuration))
9886 (org-remove-occur-highlights nil nil t)
9887 (cond
9888 ((and (org-at-heading-p)
9889 (not (org-at-timestamp-p t))
9890 (not (org-in-regexp
9891 (concat org-plain-link-re "\\|"
9892 org-bracket-link-regexp "\\|"
9893 org-angle-link-re "\\|"
9894 "[ \t]:[^ \t\n]+:[ \t]*$")))
9895 (not (get-text-property (point) 'org-linked-text)))
9896 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9897 (lk (car lkall))
9898 (lkend (cdr lkall)))
9899 (when lk
9900 (prog1 (search-forward lk nil lkend)
9901 (goto-char (match-beginning 0))
9902 (org-open-at-point))))
9903 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9904 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9905 ((and (org-at-timestamp-p t)
9906 (not (org-in-regexp org-bracket-link-regexp)))
9907 (org-follow-timestamp-link))
9908 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9909 (not (org-in-regexp org-any-link-re)))
9910 (org-footnote-action))
9912 (let (type path link line search (pos (point)))
9913 (catch 'match
9914 (save-excursion
9915 (skip-chars-forward "^]\n\r")
9916 (when (org-in-regexp org-bracket-link-regexp 1)
9917 (setq link (org-extract-attributes
9918 (org-link-unescape (org-match-string-no-properties 1))))
9919 (while (string-match " *\n *" link)
9920 (setq link (replace-match " " t t link)))
9921 (setq link (org-link-expand-abbrev link))
9922 (cond
9923 ((or (file-name-absolute-p link)
9924 (string-match "^\\.\\.?/" link))
9925 (setq type "file" path link))
9926 ((string-match org-link-re-with-space3 link)
9927 (setq type (match-string 1 link) path (match-string 2 link)))
9928 ((string-match "^help:+\\(.+\\)" link)
9929 (setq type "help" path (match-string 1 link)))
9930 (t (setq type "thisfile" path link)))
9931 (throw 'match t)))
9933 (when (get-text-property (point) 'org-linked-text)
9934 (setq type "thisfile"
9935 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9936 (1+ (point)) (point))
9937 path (buffer-substring
9938 (or (previous-single-property-change pos 'org-linked-text)
9939 (point-min))
9940 (or (next-single-property-change pos 'org-linked-text)
9941 (point-max))))
9942 (throw 'match t))
9944 (save-excursion
9945 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9946 (when (or (org-in-regexp org-angle-link-re)
9947 (and plinkpos (goto-char (car plinkpos))
9948 (save-match-data (not (looking-back "\\[\\[")))))
9949 (setq type (match-string 1)
9950 path (org-link-unescape (match-string 2)))
9951 (throw 'match t))))
9952 (save-excursion
9953 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9954 (setq type "tags"
9955 path (match-string 1))
9956 (while (string-match ":" path)
9957 (setq path (replace-match "+" t t path)))
9958 (throw 'match t)))
9959 (when (org-in-regexp "<\\([^><\n]+\\)>")
9960 (setq type "tree-match"
9961 path (match-string 1))
9962 (throw 'match t)))
9963 (unless path
9964 (user-error "No link found"))
9966 ;; switch back to reference buffer
9967 ;; needed when if called in a temporary buffer through
9968 ;; org-open-link-from-string
9969 (with-current-buffer (or reference-buffer (current-buffer))
9971 ;; Remove any trailing spaces in path
9972 (if (string-match " +\\'" path)
9973 (setq path (replace-match "" t t path)))
9974 (if (and org-link-translation-function
9975 (fboundp org-link-translation-function))
9976 ;; Check if we need to translate the link
9977 (let ((tmp (funcall org-link-translation-function type path)))
9978 (setq type (car tmp) path (cdr tmp))))
9980 (cond
9982 ((assoc type org-link-protocols)
9983 (funcall (nth 1 (assoc type org-link-protocols)) path))
9985 ((equal type "help")
9986 (let ((f-or-v (intern path)))
9987 (cond ((fboundp f-or-v)
9988 (describe-function f-or-v))
9989 ((boundp f-or-v)
9990 (describe-variable f-or-v))
9991 (t (error "Not a known function or variable")))))
9993 ((equal type "mailto")
9994 (let ((cmd (car org-link-mailto-program))
9995 (args (cdr org-link-mailto-program)) args1
9996 (address path) (subject "") a)
9997 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9998 (setq address (match-string 1 path)
9999 subject (org-link-escape (match-string 2 path))))
10000 (while args
10001 (cond
10002 ((not (stringp (car args))) (push (pop args) args1))
10003 (t (setq a (pop args))
10004 (if (string-match "%a" a)
10005 (setq a (replace-match address t t a)))
10006 (if (string-match "%s" a)
10007 (setq a (replace-match subject t t a)))
10008 (push a args1))))
10009 (apply cmd (nreverse args1))))
10011 ((member type '("http" "https" "ftp" "news"))
10012 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10013 (org-link-escape
10014 path org-link-escape-chars-browser)
10015 path))))
10017 ((string= type "doi")
10018 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10019 (org-link-escape
10020 path org-link-escape-chars-browser)
10021 path))))
10023 ((member type '("message"))
10024 (browse-url (concat type ":" path)))
10026 ((string= type "tags")
10027 (org-tags-view arg path))
10029 ((string= type "tree-match")
10030 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10032 ((string= type "file")
10033 (if (string-match "::\\([0-9]+\\)\\'" path)
10034 (setq line (string-to-number (match-string 1 path))
10035 path (substring path 0 (match-beginning 0)))
10036 (if (string-match "::\\(.+\\)\\'" path)
10037 (setq search (match-string 1 path)
10038 path (substring path 0 (match-beginning 0)))))
10039 (if (string-match "[*?{]" (file-name-nondirectory path))
10040 (dired path)
10041 (org-open-file path arg line search)))
10043 ((string= type "shell")
10044 (let ((buf (generate-new-buffer "*Org Shell Output"))
10045 (cmd path))
10046 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10047 (string-match org-confirm-shell-link-not-regexp cmd))
10048 (not org-confirm-shell-link-function)
10049 (funcall org-confirm-shell-link-function
10050 (format "Execute \"%s\" in shell? "
10051 (org-add-props cmd nil
10052 'face 'org-warning))))
10053 (progn
10054 (message "Executing %s" cmd)
10055 (shell-command cmd buf)
10056 (if (featurep 'midnight)
10057 (setq clean-buffer-list-kill-buffer-names
10058 (cons buf clean-buffer-list-kill-buffer-names))))
10059 (error "Abort"))))
10061 ((string= type "elisp")
10062 (let ((cmd path))
10063 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10064 (string-match org-confirm-elisp-link-not-regexp cmd))
10065 (not org-confirm-elisp-link-function)
10066 (funcall org-confirm-elisp-link-function
10067 (format "Execute \"%s\" as elisp? "
10068 (org-add-props cmd nil
10069 'face 'org-warning))))
10070 (message "%s => %s" cmd
10071 (if (equal (string-to-char cmd) ?\()
10072 (eval (read cmd))
10073 (call-interactively (read cmd))))
10074 (error "Abort"))))
10076 ((and (string= type "thisfile")
10077 (run-hook-with-args-until-success
10078 'org-open-link-functions path)))
10080 ((string= type "thisfile")
10081 (if arg
10082 (switch-to-buffer-other-window
10083 (org-get-buffer-for-internal-link (current-buffer)))
10084 (org-mark-ring-push))
10085 (let ((cmd `(org-link-search
10086 ,path
10087 ,(cond ((equal arg '(4)) ''occur)
10088 ((equal arg '(16)) ''org-occur))
10089 ,pos)))
10090 (condition-case nil (let ((org-link-search-inhibit-query t))
10091 (eval cmd))
10092 (error (progn (widen) (eval cmd))))))
10094 (t (browse-url-at-point)))))))
10095 (move-marker org-open-link-marker nil)
10096 (run-hook-with-args 'org-follow-link-hook)))
10098 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10099 "Offer links in the current entry and return the selected link.
10100 If there is only one link, return it.
10101 If NTH is an integer, return the NTH link found.
10102 If ZERO is a string, check also this string for a link, and if
10103 there is one, return it."
10104 (with-current-buffer buffer
10105 (save-excursion
10106 (save-restriction
10107 (widen)
10108 (goto-char marker)
10109 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10110 "\\(" org-angle-link-re "\\)\\|"
10111 "\\(" org-plain-link-re "\\)"))
10112 (cnt ?0)
10113 (in-emacs (if (integerp nth) nil nth))
10114 have-zero end links link c)
10115 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10116 (push (match-string 0 zero) links)
10117 (setq cnt (1- cnt) have-zero t))
10118 (save-excursion
10119 (org-back-to-heading t)
10120 (setq end (save-excursion (outline-next-heading) (point)))
10121 (while (re-search-forward re end t)
10122 (push (match-string 0) links))
10123 (setq links (org-uniquify (reverse links))))
10124 (cond
10125 ((null links)
10126 (message "No links"))
10127 ((equal (length links) 1)
10128 (setq link (car links)))
10129 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10130 (setq link (nth (if have-zero nth (1- nth)) links)))
10131 (t ; we have to select a link
10132 (save-excursion
10133 (save-window-excursion
10134 (delete-other-windows)
10135 (with-output-to-temp-buffer "*Select Link*"
10136 (mapc (lambda (l)
10137 (if (not (string-match org-bracket-link-regexp l))
10138 (princ (format "[%c] %s\n" (incf cnt)
10139 (org-remove-angle-brackets l)))
10140 (if (match-end 3)
10141 (princ (format "[%c] %s (%s)\n" (incf cnt)
10142 (match-string 3 l) (match-string 1 l)))
10143 (princ (format "[%c] %s\n" (incf cnt)
10144 (match-string 1 l))))))
10145 links))
10146 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10147 (message "Select link to open, RET to open all:")
10148 (setq c (read-char-exclusive))
10149 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10150 (when (equal c ?q) (error "Abort"))
10151 (if (equal c ?\C-m)
10152 (setq link links)
10153 (setq nth (- c ?0))
10154 (if have-zero (setq nth (1+ nth)))
10155 (unless (and (integerp nth) (>= (length links) nth))
10156 (error "Invalid link selection"))
10157 (setq link (nth (1- nth) links)))))
10158 (cons link end))))))
10160 ;; Add special file links that specify the way of opening
10162 (org-add-link-type "file+sys" 'org-open-file-with-system)
10163 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10164 (defun org-open-file-with-system (path)
10165 "Open file at PATH using the system way of opening it."
10166 (org-open-file path 'system))
10167 (defun org-open-file-with-emacs (path)
10168 "Open file at PATH in Emacs."
10169 (org-open-file path 'emacs))
10170 (defun org-remove-file-link-modifiers ()
10171 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10172 (goto-char (point-min))
10173 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10174 (org-if-unprotected
10175 (replace-match "file:" t t))))
10176 (eval-after-load "org-exp"
10177 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10178 'org-remove-file-link-modifiers))
10180 ;;; File search
10182 (defvar org-create-file-search-functions nil
10183 "List of functions to construct the right search string for a file link.
10184 These functions are called in turn with point at the location to
10185 which the link should point.
10187 A function in the hook should first test if it would like to
10188 handle this file type, for example by checking the `major-mode'
10189 or the file extension. If it decides not to handle this file, it
10190 should just return nil to give other functions a chance. If it
10191 does handle the file, it must return the search string to be used
10192 when following the link. The search string will be part of the
10193 file link, given after a double colon, and `org-open-at-point'
10194 will automatically search for it. If special measures must be
10195 taken to make the search successful, another function should be
10196 added to the companion hook `org-execute-file-search-functions',
10197 which see.
10199 A function in this hook may also use `setq' to set the variable
10200 `description' to provide a suggestion for the descriptive text to
10201 be used for this link when it gets inserted into an Org-mode
10202 buffer with \\[org-insert-link].")
10204 (defvar org-execute-file-search-functions nil
10205 "List of functions to execute a file search triggered by a link.
10207 Functions added to this hook must accept a single argument, the
10208 search string that was part of the file link, the part after the
10209 double colon. The function must first check if it would like to
10210 handle this search, for example by checking the `major-mode' or
10211 the file extension. If it decides not to handle this search, it
10212 should just return nil to give other functions a chance. If it
10213 does handle the search, it must return a non-nil value to keep
10214 other functions from trying.
10216 Each function can access the current prefix argument through the
10217 variable `current-prefix-argument'. Note that a single prefix is
10218 used to force opening a link in Emacs, so it may be good to only
10219 use a numeric or double prefix to guide the search function.
10221 In case this is needed, a function in this hook can also restore
10222 the window configuration before `org-open-at-point' was called using:
10224 (set-window-configuration org-window-config-before-follow-link)")
10226 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10227 (defun org-link-search (s &optional type avoid-pos stealth)
10228 "Search for a link search option.
10229 If S is surrounded by forward slashes, it is interpreted as a
10230 regular expression. In org-mode files, this will create an `org-occur'
10231 sparse tree. In ordinary files, `occur' will be used to list matches.
10232 If the current buffer is in `dired-mode', grep will be used to search
10233 in all files. If AVOID-POS is given, ignore matches near that position.
10235 When optional argument STEALTH is non-nil, do not modify
10236 visibility around point, thus ignoring
10237 `org-show-hierarchy-above', `org-show-following-heading' and
10238 `org-show-siblings' variables."
10239 (let ((case-fold-search t)
10240 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10241 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10242 (append '(("") (" ") ("\t") ("\n"))
10243 org-emphasis-alist)
10244 "\\|") "\\)"))
10245 (pos (point))
10246 (pre nil) (post nil)
10247 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10248 (cond
10249 ;; First check if there are any special search functions
10250 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10251 ;; Now try the builtin stuff
10252 ((and (equal (string-to-char s0) ?#)
10253 (> (length s0) 1)
10254 (save-excursion
10255 (goto-char (point-min))
10256 (and
10257 (re-search-forward
10258 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10259 (setq type 'dedicated
10260 pos (match-beginning 0))))
10261 ;; There is an exact target for this
10262 (goto-char pos)
10263 (org-back-to-heading t)))
10264 ((save-excursion
10265 (goto-char (point-min))
10266 (and
10267 (re-search-forward
10268 (concat "<<" (regexp-quote s0) ">>") nil t)
10269 (setq type 'dedicated
10270 pos (match-beginning 0))))
10271 ;; There is an exact target for this
10272 (goto-char pos))
10273 ((save-excursion
10274 (goto-char (point-min))
10275 (and
10276 (re-search-forward
10277 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10278 (setq type 'dedicated pos (match-beginning 0))))
10279 ;; Found an invisible target.
10280 (goto-char pos))
10281 ((save-excursion
10282 (goto-char (point-min))
10283 (and
10284 (re-search-forward
10285 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10286 (setq type 'dedicated pos (match-beginning 0))))
10287 ;; Found an element with a matching #+name affiliated keyword.
10288 (goto-char pos))
10289 ((and (string-match "^(\\(.*\\))$" s0)
10290 (save-excursion
10291 (goto-char (point-min))
10292 (and
10293 (re-search-forward
10294 (concat "[^[]" (regexp-quote
10295 (format org-coderef-label-format
10296 (match-string 1 s0))))
10297 nil t)
10298 (setq type 'dedicated
10299 pos (1+ (match-beginning 0))))))
10300 ;; There is a coderef target for this
10301 (goto-char pos))
10302 ((string-match "^/\\(.*\\)/$" s)
10303 ;; A regular expression
10304 (cond
10305 ((derived-mode-p 'org-mode)
10306 (org-occur (match-string 1 s)))
10307 ;;((eq major-mode 'dired-mode)
10308 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10309 (t (org-do-occur (match-string 1 s)))))
10310 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10311 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10312 (goto-char (point-min))
10313 (cond
10314 ((let (case-fold-search)
10315 (re-search-forward (format org-complex-heading-regexp-format
10316 (regexp-quote s))
10317 nil t))
10318 ;; OK, found a match
10319 (setq type 'dedicated)
10320 (goto-char (match-beginning 0)))
10321 ((and (not org-link-search-inhibit-query)
10322 (eq org-link-search-must-match-exact-headline 'query-to-create)
10323 (y-or-n-p "No match - create this as a new heading? "))
10324 (goto-char (point-max))
10325 (or (bolp) (newline))
10326 (insert "* " s "\n")
10327 (beginning-of-line 0))
10329 (goto-char pos)
10330 (error "No match"))))
10332 ;; A normal search string
10333 (when (equal (string-to-char s) ?*)
10334 ;; Anchor on headlines, post may include tags.
10335 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10336 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10337 s (substring s 1)))
10338 (remove-text-properties
10339 0 (length s)
10340 '(face nil mouse-face nil keymap nil fontified nil) s)
10341 ;; Make a series of regular expressions to find a match
10342 (setq words (org-split-string s "[ \n\r\t]+")
10344 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10345 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10346 "\\)" markers)
10347 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10348 re2a (concat "[ \t\r\n]" re2a_)
10349 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10350 re4 (concat "[^a-zA-Z_]" re4_)
10352 re1 (concat pre re2 post)
10353 re3 (concat pre (if pre re4_ re4) post)
10354 re5 (concat pre ".*" re4)
10355 re2 (concat pre re2)
10356 re2a (concat pre (if pre re2a_ re2a))
10357 re4 (concat pre (if pre re4_ re4))
10358 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10359 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10360 re5 "\\)"
10362 (cond
10363 ((eq type 'org-occur) (org-occur reall))
10364 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10365 (t (goto-char (point-min))
10366 (setq type 'fuzzy)
10367 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10368 (org-search-not-self 1 re1 nil t)
10369 (org-search-not-self 1 re2 nil t)
10370 (org-search-not-self 1 re2a nil t)
10371 (org-search-not-self 1 re3 nil t)
10372 (org-search-not-self 1 re4 nil t)
10373 (org-search-not-self 1 re5 nil t)
10375 (goto-char (match-beginning 1))
10376 (goto-char pos)
10377 (error "No match"))))))
10378 (and (derived-mode-p 'org-mode)
10379 (not stealth)
10380 (org-show-context 'link-search))
10381 type))
10383 (defun org-search-not-self (group &rest args)
10384 "Execute `re-search-forward', but only accept matches that do not
10385 enclose the position of `org-open-link-marker'."
10386 (let ((m org-open-link-marker))
10387 (catch 'exit
10388 (while (apply 're-search-forward args)
10389 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10390 (goto-char (match-end group))
10391 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10392 (> (match-beginning 0) (marker-position m))
10393 (< (match-end 0) (marker-position m)))
10394 (save-match-data
10395 (or (not (org-in-regexp
10396 org-bracket-link-analytic-regexp 1))
10397 (not (match-end 4)) ; no description
10398 (and (<= (match-beginning 4) (point))
10399 (>= (match-end 4) (point))))))
10400 (throw 'exit (point))))))))
10402 (defun org-get-buffer-for-internal-link (buffer)
10403 "Return a buffer to be used for displaying the link target of internal links."
10404 (cond
10405 ((not org-display-internal-link-with-indirect-buffer)
10406 buffer)
10407 ((string-match "(Clone)$" (buffer-name buffer))
10408 (message "Buffer is already a clone, not making another one")
10409 ;; we also do not modify visibility in this case
10410 buffer)
10411 (t ; make a new indirect buffer for displaying the link
10412 (let* ((bn (buffer-name buffer))
10413 (ibn (concat bn "(Clone)"))
10414 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10415 (with-current-buffer ib (org-overview))
10416 ib))))
10418 (defun org-do-occur (regexp &optional cleanup)
10419 "Call the Emacs command `occur'.
10420 If CLEANUP is non-nil, remove the printout of the regular expression
10421 in the *Occur* buffer. This is useful if the regex is long and not useful
10422 to read."
10423 (occur regexp)
10424 (when cleanup
10425 (let ((cwin (selected-window)) win beg end)
10426 (when (setq win (get-buffer-window "*Occur*"))
10427 (select-window win))
10428 (goto-char (point-min))
10429 (when (re-search-forward "match[a-z]+" nil t)
10430 (setq beg (match-end 0))
10431 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10432 (setq end (1- (match-beginning 0)))))
10433 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10434 (goto-char (point-min))
10435 (select-window cwin))))
10437 ;;; The mark ring for links jumps
10439 (defvar org-mark-ring nil
10440 "Mark ring for positions before jumps in Org-mode.")
10441 (defvar org-mark-ring-last-goto nil
10442 "Last position in the mark ring used to go back.")
10443 ;; Fill and close the ring
10444 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10445 (loop for i from 1 to org-mark-ring-length do
10446 (push (make-marker) org-mark-ring))
10447 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10448 org-mark-ring)
10450 (defun org-mark-ring-push (&optional pos buffer)
10451 "Put the current position or POS into the mark ring and rotate it."
10452 (interactive)
10453 (setq pos (or pos (point)))
10454 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10455 (move-marker (car org-mark-ring)
10456 (or pos (point))
10457 (or buffer (current-buffer)))
10458 (message "%s"
10459 (substitute-command-keys
10460 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10462 (defun org-mark-ring-goto (&optional n)
10463 "Jump to the previous position in the mark ring.
10464 With prefix arg N, jump back that many stored positions. When
10465 called several times in succession, walk through the entire ring.
10466 Org-mode commands jumping to a different position in the current file,
10467 or to another Org-mode file, automatically push the old position
10468 onto the ring."
10469 (interactive "p")
10470 (let (p m)
10471 (if (eq last-command this-command)
10472 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10473 (setq p org-mark-ring))
10474 (setq org-mark-ring-last-goto p)
10475 (setq m (car p))
10476 (org-pop-to-buffer-same-window (marker-buffer m))
10477 (goto-char m)
10478 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10480 (defun org-remove-angle-brackets (s)
10481 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10482 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10484 (defun org-add-angle-brackets (s)
10485 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10486 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10488 (defun org-remove-double-quotes (s)
10489 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10490 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10493 ;;; Following specific links
10495 (defun org-follow-timestamp-link ()
10496 "Open an agenda view for the time-stamp date/range at point."
10497 (cond
10498 ((org-at-date-range-p t)
10499 (let ((org-agenda-start-on-weekday)
10500 (t1 (match-string 1))
10501 (t2 (match-string 2)) tt1 tt2)
10502 (setq tt1 (time-to-days (org-time-string-to-time t1))
10503 tt2 (time-to-days (org-time-string-to-time t2)))
10504 (let ((org-agenda-buffer-tmp-name
10505 (format "*Org Agenda(a:%s)"
10506 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10507 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10508 ((org-at-timestamp-p t)
10509 (let ((org-agenda-buffer-tmp-name
10510 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10511 (org-agenda-list nil (time-to-days (org-time-string-to-time
10512 (substring (match-string 1) 0 10)))
10513 1)))
10514 (t (error "This should not happen"))))
10517 ;;; Following file links
10518 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10519 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10520 (declare-function mailcap-mime-info
10521 "mailcap" (string &optional request no-decode))
10522 (defvar org-wait nil)
10523 (defun org-open-file (path &optional in-emacs line search)
10524 "Open the file at PATH.
10525 First, this expands any special file name abbreviations. Then the
10526 configuration variable `org-file-apps' is checked if it contains an
10527 entry for this file type, and if yes, the corresponding command is launched.
10529 If no application is found, Emacs simply visits the file.
10531 With optional prefix argument IN-EMACS, Emacs will visit the file.
10532 With a double \\[universal-argument] \\[universal-argument] \
10533 prefix arg, Org tries to avoid opening in Emacs
10534 and to use an external application to visit the file.
10536 Optional LINE specifies a line to go to, optional SEARCH a string
10537 to search for. If LINE or SEARCH is given, the file will be
10538 opened in Emacs, unless an entry from org-file-apps that makes
10539 use of groups in a regexp matches.
10541 If you want to change the way frames are used when following a
10542 link, please customize `org-link-frame-setup'.
10544 If the file does not exist, an error is thrown."
10545 (let* ((file (if (equal path "")
10546 buffer-file-name
10547 (substitute-in-file-name (expand-file-name path))))
10548 (file-apps (append org-file-apps (org-default-apps)))
10549 (apps (org-remove-if
10550 'org-file-apps-entry-match-against-dlink-p file-apps))
10551 (apps-dlink (org-remove-if-not
10552 'org-file-apps-entry-match-against-dlink-p file-apps))
10553 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10554 (dirp (if remp nil (file-directory-p file)))
10555 (file (if (and dirp org-open-directory-means-index-dot-org)
10556 (concat (file-name-as-directory file) "index.org")
10557 file))
10558 (a-m-a-p (assq 'auto-mode apps))
10559 (dfile (downcase file))
10560 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10561 (link (cond ((and (eq line nil)
10562 (eq search nil))
10563 file)
10564 (line
10565 (concat file "::" (number-to-string line)))
10566 (search
10567 (concat file "::" search))))
10568 (dlink (downcase link))
10569 (old-buffer (current-buffer))
10570 (old-pos (point))
10571 (old-mode major-mode)
10572 ext cmd link-match-data)
10573 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10574 (setq ext (match-string 1 dfile))
10575 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10576 (setq ext (match-string 1 dfile))))
10577 (cond
10578 ((member in-emacs '((16) system))
10579 (setq cmd (cdr (assoc 'system apps))))
10580 (in-emacs (setq cmd 'emacs))
10582 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10583 (and dirp (cdr (assoc 'directory apps)))
10584 ; first, try matching against apps-dlink
10585 ; if we get a match here, store the match data for later
10586 (let ((match (assoc-default dlink apps-dlink
10587 'string-match)))
10588 (if match
10589 (progn (setq link-match-data (match-data))
10590 match)
10591 (progn (setq in-emacs (or in-emacs line search))
10592 nil))) ; if we have no match in apps-dlink,
10593 ; always open the file in emacs if line or search
10594 ; is given (for backwards compatibility)
10595 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10596 'string-match)
10597 (cdr (assoc ext apps))
10598 (cdr (assoc t apps))))))
10599 (when (eq cmd 'system)
10600 (setq cmd (cdr (assoc 'system apps))))
10601 (when (eq cmd 'default)
10602 (setq cmd (cdr (assoc t apps))))
10603 (when (eq cmd 'mailcap)
10604 (require 'mailcap)
10605 (mailcap-parse-mailcaps)
10606 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10607 (command (mailcap-mime-info mime-type)))
10608 (if (stringp command)
10609 (setq cmd command)
10610 (setq cmd 'emacs))))
10611 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10612 (not (file-exists-p file))
10613 (not org-open-non-existing-files))
10614 (error "No such file: %s" file))
10615 (cond
10616 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10617 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10618 (while (string-match "['\"]%s['\"]" cmd)
10619 (setq cmd (replace-match "%s" t t cmd)))
10620 (while (string-match "%s" cmd)
10621 (setq cmd (replace-match
10622 (save-match-data
10623 (shell-quote-argument
10624 (convert-standard-filename file)))
10625 t t cmd)))
10627 ;; Replace "%1", "%2" etc. in command with group matches from regex
10628 (save-match-data
10629 (let ((match-index 1)
10630 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10631 (set-match-data link-match-data)
10632 (while (<= match-index number-of-groups)
10633 (let ((regex (concat "%" (number-to-string match-index)))
10634 (replace-with (match-string match-index dlink)))
10635 (while (string-match regex cmd)
10636 (setq cmd (replace-match replace-with t t cmd))))
10637 (setq match-index (+ match-index 1)))))
10639 (save-window-excursion
10640 (message "Running %s...done" cmd)
10641 (start-process-shell-command cmd nil cmd)
10642 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10643 ((or (stringp cmd)
10644 (eq cmd 'emacs))
10645 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10646 (widen)
10647 (if line (org-goto-line line)
10648 (if search (org-link-search search))))
10649 ((consp cmd)
10650 (let ((file (convert-standard-filename file)))
10651 (save-match-data
10652 (set-match-data link-match-data)
10653 (eval cmd))))
10654 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10655 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10656 (or (not (equal old-buffer (current-buffer)))
10657 (not (equal old-pos (point))))
10658 (org-mark-ring-push old-pos old-buffer))))
10660 (defun org-file-apps-entry-match-against-dlink-p (entry)
10661 "This function returns non-nil if `entry' uses a regular
10662 expression which should be matched against the whole link by
10663 org-open-file.
10665 It assumes that is the case when the entry uses a regular
10666 expression which has at least one grouping construct and the
10667 action is either a lisp form or a command string containing
10668 '%1', i.e. using at least one subexpression match as a
10669 parameter."
10670 (let ((selector (car entry))
10671 (action (cdr entry)))
10672 (if (stringp selector)
10673 (and (> (regexp-opt-depth selector) 0)
10674 (or (and (stringp action)
10675 (string-match "%[0-9]" action))
10676 (consp action)))
10677 nil)))
10679 (defun org-default-apps ()
10680 "Return the default applications for this operating system."
10681 (cond
10682 ((eq system-type 'darwin)
10683 org-file-apps-defaults-macosx)
10684 ((eq system-type 'windows-nt)
10685 org-file-apps-defaults-windowsnt)
10686 (t org-file-apps-defaults-gnu)))
10688 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10689 "Convert extensions to regular expressions in the cars of LIST.
10690 Also, weed out any non-string entries, because the return value is used
10691 only for regexp matching.
10692 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10693 point to the symbol `emacs', indicating that the file should
10694 be opened in Emacs."
10695 (append
10696 (delq nil
10697 (mapcar (lambda (x)
10698 (if (not (stringp (car x)))
10700 (if (string-match "\\W" (car x))
10702 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10703 list))
10704 (if add-auto-mode
10705 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10707 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10708 (defun org-file-remote-p (file)
10709 "Test whether FILE specifies a location on a remote system.
10710 Return non-nil if the location is indeed remote.
10712 For example, the filename \"/user@host:/foo\" specifies a location
10713 on the system \"/user@host:\"."
10714 (cond ((fboundp 'file-remote-p)
10715 (file-remote-p file))
10716 ((fboundp 'tramp-handle-file-remote-p)
10717 (tramp-handle-file-remote-p file))
10718 ((and (boundp 'ange-ftp-name-format)
10719 (string-match (car ange-ftp-name-format) file))
10720 t)))
10723 ;;;; Refiling
10725 (defun org-get-org-file ()
10726 "Read a filename, with default directory `org-directory'."
10727 (let ((default (or org-default-notes-file remember-data-file)))
10728 (read-file-name (format "File name [%s]: " default)
10729 (file-name-as-directory org-directory)
10730 default)))
10732 (defun org-notes-order-reversed-p ()
10733 "Check if the current file should receive notes in reversed order."
10734 (cond
10735 ((not org-reverse-note-order) nil)
10736 ((eq t org-reverse-note-order) t)
10737 ((not (listp org-reverse-note-order)) nil)
10738 (t (catch 'exit
10739 (let ((all org-reverse-note-order)
10740 entry)
10741 (while (setq entry (pop all))
10742 (if (string-match (car entry) buffer-file-name)
10743 (throw 'exit (cdr entry))))
10744 nil)))))
10746 (defvar org-refile-target-table nil
10747 "The list of refile targets, created by `org-refile'.")
10749 (defvar org-agenda-new-buffers nil
10750 "Buffers created to visit agenda files.")
10752 (defvar org-refile-cache nil
10753 "Cache for refile targets.")
10755 (defvar org-refile-markers nil
10756 "All the markers used for caching refile locations.")
10758 (defun org-refile-marker (pos)
10759 "Get a new refile marker, but only if caching is in use."
10760 (if (not org-refile-use-cache)
10762 (let ((m (make-marker)))
10763 (move-marker m pos)
10764 (push m org-refile-markers)
10765 m)))
10767 (defun org-refile-cache-clear ()
10768 "Clear the refile cache and disable all the markers."
10769 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10770 (setq org-refile-markers nil)
10771 (setq org-refile-cache nil)
10772 (message "Refile cache has been cleared"))
10774 (defun org-refile-cache-check-set (set)
10775 "Check if all the markers in the cache still have live buffers."
10776 (let (marker)
10777 (catch 'exit
10778 (while (and set (setq marker (nth 3 (pop set))))
10779 ;; if org-refile-use-outline-path is 'file, marker may be nil
10780 (when (and marker (null (marker-buffer marker)))
10781 (message "not found") (sit-for 3)
10782 (throw 'exit nil)))
10783 t)))
10785 (defun org-refile-cache-put (set &rest identifiers)
10786 "Push the refile targets SET into the cache, under IDENTIFIERS."
10787 (let* ((key (sha1 (prin1-to-string identifiers)))
10788 (entry (assoc key org-refile-cache)))
10789 (if entry
10790 (setcdr entry set)
10791 (push (cons key set) org-refile-cache))))
10793 (defun org-refile-cache-get (&rest identifiers)
10794 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10795 (cond
10796 ((not org-refile-cache) nil)
10797 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10799 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10800 org-refile-cache))))
10801 (and set (org-refile-cache-check-set set) set)))))
10803 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10804 "Produce a table with refile targets."
10805 (let ((case-fold-search nil)
10806 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10807 (entries (or org-refile-targets '((nil . (:level . 1)))))
10808 targets tgs txt re files f desc descre fast-path-p level pos0)
10809 (message "Getting targets...")
10810 (with-current-buffer (or default-buffer (current-buffer))
10811 (while (setq entry (pop entries))
10812 (setq files (car entry) desc (cdr entry))
10813 (setq fast-path-p nil)
10814 (cond
10815 ((null files) (setq files (list (current-buffer))))
10816 ((eq files 'org-agenda-files)
10817 (setq files (org-agenda-files 'unrestricted)))
10818 ((and (symbolp files) (fboundp files))
10819 (setq files (funcall files)))
10820 ((and (symbolp files) (boundp files))
10821 (setq files (symbol-value files))))
10822 (if (stringp files) (setq files (list files)))
10823 (cond
10824 ((eq (car desc) :tag)
10825 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10826 ((eq (car desc) :todo)
10827 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10828 ((eq (car desc) :regexp)
10829 (setq descre (cdr desc)))
10830 ((eq (car desc) :level)
10831 (setq descre (concat "^\\*\\{" (number-to-string
10832 (if org-odd-levels-only
10833 (1- (* 2 (cdr desc)))
10834 (cdr desc)))
10835 "\\}[ \t]")))
10836 ((eq (car desc) :maxlevel)
10837 (setq fast-path-p t)
10838 (setq descre (concat "^\\*\\{1," (number-to-string
10839 (if org-odd-levels-only
10840 (1- (* 2 (cdr desc)))
10841 (cdr desc)))
10842 "\\}[ \t]")))
10843 (t (error "Bad refiling target description %s" desc)))
10844 (while (setq f (pop files))
10845 (with-current-buffer
10846 (if (bufferp f) f (org-get-agenda-file-buffer f))
10848 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10849 (progn
10850 (if (bufferp f) (setq f (buffer-file-name
10851 (buffer-base-buffer f))))
10852 (setq f (and f (expand-file-name f)))
10853 (if (eq org-refile-use-outline-path 'file)
10854 (push (list (file-name-nondirectory f) f nil nil) tgs))
10855 (save-excursion
10856 (save-restriction
10857 (widen)
10858 (goto-char (point-min))
10859 (while (re-search-forward descre nil t)
10860 (goto-char (setq pos0 (point-at-bol)))
10861 (catch 'next
10862 (when org-refile-target-verify-function
10863 (save-match-data
10864 (or (funcall org-refile-target-verify-function)
10865 (throw 'next t))))
10866 (when (and (looking-at org-complex-heading-regexp)
10867 (not (member (match-string 4) excluded-entries))
10868 (match-string 4))
10869 (setq level (org-reduced-level
10870 (- (match-end 1) (match-beginning 1)))
10871 txt (org-link-display-format (match-string 4))
10872 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10873 re (format org-complex-heading-regexp-format
10874 (regexp-quote (match-string 4))))
10875 (when org-refile-use-outline-path
10876 (setq txt (mapconcat
10877 'org-protect-slash
10878 (append
10879 (if (eq org-refile-use-outline-path
10880 'file)
10881 (list (file-name-nondirectory
10882 (buffer-file-name
10883 (buffer-base-buffer))))
10884 (if (eq org-refile-use-outline-path
10885 'full-file-path)
10886 (list (buffer-file-name
10887 (buffer-base-buffer)))))
10888 (org-get-outline-path fast-path-p
10889 level txt)
10890 (list txt))
10891 "/")))
10892 (push (list txt f re (org-refile-marker (point)))
10893 tgs)))
10894 (when (= (point) pos0)
10895 ;; verification function has not moved point
10896 (goto-char (point-at-eol))))))))
10897 (when org-refile-use-cache
10898 (org-refile-cache-put tgs (buffer-file-name) descre))
10899 (setq targets (append tgs targets))
10900 ))))
10901 (message "Getting targets...done")
10902 (nreverse targets)))
10904 (defun org-protect-slash (s)
10905 (while (string-match "/" s)
10906 (setq s (replace-match "\\" t t s)))
10909 (defvar org-olpa (make-vector 20 nil))
10911 (defun org-get-outline-path (&optional fastp level heading)
10912 "Return the outline path to the current entry, as a list.
10914 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10915 routine which makes outline path derivations for an entire file,
10916 avoiding backtracing. Refile target collection makes use of that."
10917 (if fastp
10918 (progn
10919 (if (> level 19)
10920 (error "Outline path failure, more than 19 levels"))
10921 (loop for i from level upto 19 do
10922 (aset org-olpa i nil))
10923 (prog1
10924 (delq nil (append org-olpa nil))
10925 (aset org-olpa level heading)))
10926 (let (rtn case-fold-search)
10927 (save-excursion
10928 (save-restriction
10929 (widen)
10930 (while (org-up-heading-safe)
10931 (when (looking-at org-complex-heading-regexp)
10932 (push (org-match-string-no-properties 4) rtn)))
10933 rtn)))))
10935 (defun org-format-outline-path (path &optional width prefix separator)
10936 "Format the outline path PATH for display.
10937 WIDTH is the maximum number of characters that is available.
10938 PREFIX is a prefix to be included in the returned string,
10939 such as the file name.
10940 SEPARATOR is inserted between the different parts of the path,
10941 the default is \"/\"."
10942 (setq width (or width 79))
10943 (if prefix (setq width (- width (length prefix))))
10944 (if (not path)
10945 (or prefix "")
10946 (let* ((nsteps (length path))
10947 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10948 (maxwidth (if (<= total-width width)
10949 10000 ;; everything fits
10950 ;; we need to shorten the level headings
10951 (/ (- width nsteps) nsteps)))
10952 (org-odd-levels-only nil)
10953 (n 0)
10954 (total (1+ (length prefix))))
10955 (setq maxwidth (max maxwidth 10))
10956 (concat prefix
10957 (if prefix (or separator "/"))
10958 (mapconcat
10959 (lambda (h)
10960 (setq n (1+ n))
10961 (if (and (= n nsteps) (< maxwidth 10000))
10962 (setq maxwidth (- total-width total)))
10963 (if (< (length h) maxwidth)
10964 (progn (setq total (+ total (length h) 1)) h)
10965 (setq h (substring h 0 (- maxwidth 2))
10966 total (+ total maxwidth 1))
10967 (if (string-match "[ \t]+\\'" h)
10968 (setq h (substring h 0 (match-beginning 0))))
10969 (setq h (concat h "..")))
10970 (org-add-props h nil 'face
10971 (nth (% (1- n) org-n-level-faces)
10972 org-level-faces))
10974 path (or separator "/"))))))
10976 (defun org-display-outline-path (&optional file current separator just-return-string)
10977 "Display the current outline path in the echo area.
10979 If FILE is non-nil, prepend the output with the file name.
10980 If CURRENT is non-nil, append the current heading to the output.
10981 SEPARATOR is passed through to `org-format-outline-path'. It separates
10982 the different parts of the path and defaults to \"/\".
10983 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10984 (interactive "P")
10985 (let* (case-fold-search
10986 message-log-max ; Don't populate the *Messages* buffer
10987 (bfn (buffer-file-name (buffer-base-buffer)))
10988 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10989 res)
10990 (if current (setq path (append path
10991 (save-excursion
10992 (org-back-to-heading t)
10993 (if (looking-at org-complex-heading-regexp)
10994 (list (match-string 4)))))))
10995 (setq res
10996 (org-format-outline-path
10997 path
10998 (1- (frame-width))
10999 (and file bfn (concat (file-name-nondirectory bfn) separator))
11000 separator))
11001 (if just-return-string
11002 (org-no-properties res)
11003 (message "%s" res))))
11005 (defvar org-refile-history nil
11006 "History for refiling operations.")
11008 (defvar org-after-refile-insert-hook nil
11009 "Hook run after `org-refile' has inserted its stuff at the new location.
11010 Note that this is still *before* the stuff will be removed from
11011 the *old* location.")
11013 (defvar org-capture-last-stored-marker)
11014 (defvar org-refile-keep nil
11015 "Non-nil means `org-refile' will copy instead of refile.")
11017 (defun org-copy ()
11018 "Like `org-refile', but copy."
11019 (interactive)
11020 (let ((org-refile-keep t))
11021 (funcall 'org-refile nil nil nil "Copy")))
11023 (defun org-refile (&optional goto default-buffer rfloc msg)
11024 "Move the entry or entries at point to another heading.
11025 The list of target headings is compiled using the information in
11026 `org-refile-targets', which see.
11028 At the target location, the entry is filed as a subitem of the target
11029 heading. Depending on `org-reverse-note-order', the new subitem will
11030 either be the first or the last subitem.
11032 If there is an active region, all entries in that region will be moved.
11033 However, the region must fulfill the requirement that the first heading
11034 is the first one sets the top-level of the moved text - at most siblings
11035 below it are allowed.
11037 With prefix arg GOTO, the command will only visit the target location
11038 and not actually move anything.
11040 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11041 go to the location where the last refiling operation has put the subtree.
11042 With a prefix argument of `2', refile to the running clock.
11044 RFLOC can be a refile location obtained in a different way.
11046 MSG is a string to replace \"Refile\" in the default prompt with
11047 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11049 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11051 If you are using target caching (see `org-refile-use-cache'),
11052 you have to clear the target cache in order to find new targets.
11053 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11054 prefix argument (`C-u C-u C-u C-c C-w')."
11056 (interactive "P")
11057 (if (member goto '(0 (64)))
11058 (org-refile-cache-clear)
11059 (let* ((actionmsg (or msg "Refile"))
11060 (cbuf (current-buffer))
11061 (regionp (org-region-active-p))
11062 (region-start (and regionp (region-beginning)))
11063 (region-end (and regionp (region-end)))
11064 (region-length (and regionp (- region-end region-start)))
11065 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11066 pos it nbuf file re level reversed)
11067 (setq last-command nil)
11068 (when regionp
11069 (goto-char region-start)
11070 (or (bolp) (goto-char (point-at-bol)))
11071 (setq region-start (point))
11072 (unless (or (org-kill-is-subtree-p
11073 (buffer-substring region-start region-end))
11074 (prog1 org-refile-active-region-within-subtree
11075 (org-toggle-heading)))
11076 (error "The region is not a (sequence of) subtree(s)")))
11077 (if (equal goto '(16))
11078 (org-refile-goto-last-stored)
11079 (when (or
11080 (and (equal goto 2)
11081 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11082 (prog1
11083 (setq it (list (or org-clock-heading "running clock")
11084 (buffer-file-name
11085 (marker-buffer org-clock-hd-marker))
11087 (marker-position org-clock-hd-marker)))
11088 (setq goto nil)))
11089 (setq it (or rfloc
11090 (let (heading-text)
11091 (save-excursion
11092 (unless goto
11093 (org-back-to-heading t)
11094 (setq heading-text
11095 (nth 4 (org-heading-components))))
11097 (org-refile-get-location
11098 (cond (goto "Goto")
11099 (regionp (concat actionmsg " region to"))
11100 (t (concat actionmsg " subtree \""
11101 heading-text "\" to")))
11102 default-buffer
11103 (and (not (equal '(4) goto))
11104 org-refile-allow-creating-parent-nodes)
11105 goto))))))
11106 (setq file (nth 1 it)
11107 re (nth 2 it)
11108 pos (nth 3 it))
11109 (if (and (not goto)
11111 (equal (buffer-file-name) file)
11112 (if regionp
11113 (and (>= pos region-start)
11114 (<= pos region-end))
11115 (and (>= pos (point))
11116 (< pos (save-excursion
11117 (org-end-of-subtree t t))))))
11118 (error "Cannot refile to position inside the tree or region"))
11120 (setq nbuf (or (find-buffer-visiting file)
11121 (find-file-noselect file)))
11122 (if goto
11123 (progn
11124 (org-pop-to-buffer-same-window nbuf)
11125 (goto-char pos)
11126 (org-show-context 'org-goto))
11127 (if regionp
11128 (progn
11129 (org-kill-new (buffer-substring region-start region-end))
11130 (org-save-markers-in-region region-start region-end))
11131 (org-copy-subtree 1 nil t))
11132 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11133 (find-file-noselect file)))
11134 (setq reversed (org-notes-order-reversed-p))
11135 (save-excursion
11136 (save-restriction
11137 (widen)
11138 (if pos
11139 (progn
11140 (goto-char pos)
11141 (looking-at org-outline-regexp)
11142 (setq level (org-get-valid-level (funcall outline-level) 1))
11143 (goto-char
11144 (if reversed
11145 (or (outline-next-heading) (point-max))
11146 (or (save-excursion (org-get-next-sibling))
11147 (org-end-of-subtree t t)
11148 (point-max)))))
11149 (setq level 1)
11150 (if (not reversed)
11151 (goto-char (point-max))
11152 (goto-char (point-min))
11153 (or (outline-next-heading) (goto-char (point-max)))))
11154 (if (not (bolp)) (newline))
11155 (org-paste-subtree level)
11156 (when org-log-refile
11157 (org-add-log-setup 'refile nil nil 'findpos
11158 org-log-refile)
11159 (unless (eq org-log-refile 'note)
11160 (save-excursion (org-add-log-note))))
11161 (and org-auto-align-tags
11162 (let ((org-loop-over-headlines-in-active-region nil))
11163 (org-set-tags nil t)))
11164 (with-demoted-errors
11165 (bookmark-set "org-refile-last-stored"))
11166 ;; If we are refiling for capture, make sure that the
11167 ;; last-capture pointers point here
11168 (when (org-bound-and-true-p org-refile-for-capture)
11169 (with-demoted-errors
11170 (bookmark-set "org-capture-last-stored-marker"))
11171 (move-marker org-capture-last-stored-marker (point)))
11172 (if (fboundp 'deactivate-mark) (deactivate-mark))
11173 (run-hooks 'org-after-refile-insert-hook))))
11174 (unless org-refile-keep
11175 (if regionp
11176 (delete-region (point) (+ (point) region-length))
11177 (org-cut-subtree)))
11178 (when (featurep 'org-inlinetask)
11179 (org-inlinetask-remove-END-maybe))
11180 (setq org-markers-to-move nil)
11181 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11183 (defun org-refile-goto-last-stored ()
11184 "Go to the location where the last refile was stored."
11185 (interactive)
11186 (bookmark-jump "org-refile-last-stored")
11187 (message "This is the location of the last refile"))
11189 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11190 no-exclude)
11191 "Prompt the user for a refile location, using PROMPT.
11192 PROMPT should not be suffixed with a colon and a space, because
11193 this function appends the default value from
11194 `org-refile-history' automatically, if that is not empty.
11195 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11196 this is used for the GOTO interface."
11197 (let ((org-refile-targets org-refile-targets)
11198 (org-refile-use-outline-path org-refile-use-outline-path)
11199 excluded-entries)
11200 (when (and (derived-mode-p 'org-mode)
11201 (not org-refile-use-cache)
11202 (not no-exclude))
11203 (org-map-tree
11204 (lambda()
11205 (setq excluded-entries
11206 (append excluded-entries (list (org-get-heading t t)))))))
11207 (setq org-refile-target-table
11208 (org-refile-get-targets default-buffer excluded-entries)))
11209 (unless org-refile-target-table
11210 (error "No refile targets"))
11211 (let* ((cbuf (current-buffer))
11212 (partial-completion-mode nil)
11213 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11214 (cfunc (if (and org-refile-use-outline-path
11215 org-outline-path-complete-in-steps)
11216 'org-olpath-completing-read
11217 'org-icompleting-read))
11218 (extra (if org-refile-use-outline-path "/" ""))
11219 (cbnex (concat (buffer-name) extra))
11220 (filename (and cfn (expand-file-name cfn)))
11221 (tbl (mapcar
11222 (lambda (x)
11223 (if (and (not (member org-refile-use-outline-path
11224 '(file full-file-path)))
11225 (not (equal filename (nth 1 x))))
11226 (cons (concat (car x) extra " ("
11227 (file-name-nondirectory (nth 1 x)) ")")
11228 (cdr x))
11229 (cons (concat (car x) extra) (cdr x))))
11230 org-refile-target-table))
11231 (completion-ignore-case t)
11232 cdef
11233 (prompt (concat prompt
11234 (or (and (car org-refile-history)
11235 (concat " (default " (car org-refile-history) ")"))
11236 (and (assoc cbnex tbl) (setq cdef cbnex)
11237 (concat " (default " cbnex ")"))) ": "))
11238 pa answ parent-target child parent old-hist)
11239 (setq old-hist org-refile-history)
11240 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11241 nil 'org-refile-history (or cdef (car org-refile-history))))
11242 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11243 (org-refile-check-position pa)
11244 (if pa
11245 (progn
11246 (when (or (not org-refile-history)
11247 (not (eq old-hist org-refile-history))
11248 (not (equal (car pa) (car org-refile-history))))
11249 (setq org-refile-history
11250 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11251 org-refile-history
11252 (cdr org-refile-history))))
11253 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11254 (pop org-refile-history)))
11256 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11257 (progn
11258 (setq parent (match-string 1 answ)
11259 child (match-string 2 answ))
11260 (setq parent-target (or (assoc parent tbl)
11261 (assoc (concat parent "/") tbl)))
11262 (when (and parent-target
11263 (or (eq new-nodes t)
11264 (and (eq new-nodes 'confirm)
11265 (y-or-n-p (format "Create new node \"%s\"? "
11266 child)))))
11267 (org-refile-new-child parent-target child)))
11268 (error "Invalid target location")))))
11270 (declare-function org-string-nw-p "org-macs" (s))
11271 (defun org-refile-check-position (refile-pointer)
11272 "Check if the refile pointer matches the headline to which it points."
11273 (let* ((file (nth 1 refile-pointer))
11274 (re (nth 2 refile-pointer))
11275 (pos (nth 3 refile-pointer))
11276 buffer)
11277 (if (and (not (markerp pos)) (not file))
11278 (error "Please save the buffer to a file before refiling")
11279 (when (org-string-nw-p re)
11280 (setq buffer (if (markerp pos)
11281 (marker-buffer pos)
11282 (or (find-buffer-visiting file)
11283 (find-file-noselect file))))
11284 (with-current-buffer buffer
11285 (save-excursion
11286 (save-restriction
11287 (widen)
11288 (goto-char pos)
11289 (beginning-of-line 1)
11290 (unless (org-looking-at-p re)
11291 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11293 (defun org-refile-new-child (parent-target child)
11294 "Use refile target PARENT-TARGET to add new CHILD below it."
11295 (unless parent-target
11296 (error "Cannot find parent for new node"))
11297 (let ((file (nth 1 parent-target))
11298 (pos (nth 3 parent-target))
11299 level)
11300 (with-current-buffer (or (find-buffer-visiting file)
11301 (find-file-noselect file))
11302 (save-excursion
11303 (save-restriction
11304 (widen)
11305 (if pos
11306 (goto-char pos)
11307 (goto-char (point-max))
11308 (if (not (bolp)) (newline)))
11309 (when (looking-at org-outline-regexp)
11310 (setq level (funcall outline-level))
11311 (org-end-of-subtree t t))
11312 (org-back-over-empty-lines)
11313 (insert "\n" (make-string
11314 (if pos (org-get-valid-level level 1) 1) ?*)
11315 " " child "\n")
11316 (beginning-of-line 0)
11317 (list (concat (car parent-target) "/" child) file "" (point)))))))
11319 (defun org-olpath-completing-read (prompt collection &rest args)
11320 "Read an outline path like a file name."
11321 (let ((thetable collection)
11322 (org-completion-use-ido nil) ; does not work with ido.
11323 (org-completion-use-iswitchb nil)) ; or iswitchb
11324 (apply
11325 'org-icompleting-read prompt
11326 (lambda (string predicate &optional flag)
11327 (let (rtn r f (l (length string)))
11328 (cond
11329 ((eq flag nil)
11330 ;; try completion
11331 (try-completion string thetable))
11332 ((eq flag t)
11333 ;; all-completions
11334 (setq rtn (all-completions string thetable predicate))
11335 (mapcar
11336 (lambda (x)
11337 (setq r (substring x l))
11338 (if (string-match " ([^)]*)$" x)
11339 (setq f (match-string 0 x))
11340 (setq f ""))
11341 (if (string-match "/" r)
11342 (concat string (substring r 0 (match-end 0)) f)
11344 rtn))
11345 ((eq flag 'lambda)
11346 ;; exact match?
11347 (assoc string thetable)))))
11348 args)))
11350 ;;;; Dynamic blocks
11352 (defun org-find-dblock (name)
11353 "Find the first dynamic block with name NAME in the buffer.
11354 If not found, stay at current position and return nil."
11355 (let ((case-fold-search t) pos)
11356 (save-excursion
11357 (goto-char (point-min))
11358 (setq pos (and (re-search-forward
11359 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11360 (match-beginning 0))))
11361 (if pos (goto-char pos))
11362 pos))
11364 (defconst org-dblock-start-re
11365 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11366 "Matches the start line of a dynamic block, with parameters.")
11368 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11369 "Matches the end of a dynamic block.")
11371 (defun org-create-dblock (plist)
11372 "Create a dynamic block section, with parameters taken from PLIST.
11373 PLIST must contain a :name entry which is used as name of the block."
11374 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11375 (end-of-line 1)
11376 (newline))
11377 (let ((col (current-column))
11378 (name (plist-get plist :name)))
11379 (insert "#+BEGIN: " name)
11380 (while plist
11381 (if (eq (car plist) :name)
11382 (setq plist (cddr plist))
11383 (insert " " (prin1-to-string (pop plist)))))
11384 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11385 (beginning-of-line -2)))
11387 (defun org-prepare-dblock ()
11388 "Prepare dynamic block for refresh.
11389 This empties the block, puts the cursor at the insert position and returns
11390 the property list including an extra property :name with the block name."
11391 (unless (looking-at org-dblock-start-re)
11392 (error "Not at a dynamic block"))
11393 (let* ((begdel (1+ (match-end 0)))
11394 (name (org-no-properties (match-string 1)))
11395 (params (append (list :name name)
11396 (read (concat "(" (match-string 3) ")")))))
11397 (save-excursion
11398 (beginning-of-line 1)
11399 (skip-chars-forward " \t")
11400 (setq params (plist-put params :indentation-column (current-column))))
11401 (unless (re-search-forward org-dblock-end-re nil t)
11402 (error "Dynamic block not terminated"))
11403 (setq params
11404 (append params
11405 (list :content (buffer-substring
11406 begdel (match-beginning 0)))))
11407 (delete-region begdel (match-beginning 0))
11408 (goto-char begdel)
11409 (open-line 1)
11410 params))
11412 (defun org-map-dblocks (&optional command)
11413 "Apply COMMAND to all dynamic blocks in the current buffer.
11414 If COMMAND is not given, use `org-update-dblock'."
11415 (let ((cmd (or command 'org-update-dblock)))
11416 (save-excursion
11417 (goto-char (point-min))
11418 (while (re-search-forward org-dblock-start-re nil t)
11419 (goto-char (match-beginning 0))
11420 (save-excursion
11421 (condition-case nil
11422 (funcall cmd)
11423 (error (message "Error during update of dynamic block"))))
11424 (unless (re-search-forward org-dblock-end-re nil t)
11425 (error "Dynamic block not terminated"))))))
11427 (defun org-dblock-update (&optional arg)
11428 "User command for updating dynamic blocks.
11429 Update the dynamic block at point. With prefix ARG, update all dynamic
11430 blocks in the buffer."
11431 (interactive "P")
11432 (if arg
11433 (org-update-all-dblocks)
11434 (or (looking-at org-dblock-start-re)
11435 (org-beginning-of-dblock))
11436 (org-update-dblock)))
11438 (defun org-update-dblock ()
11439 "Update the dynamic block at point.
11440 This means to empty the block, parse for parameters and then call
11441 the correct writing function."
11442 (interactive)
11443 (save-window-excursion
11444 (let* ((pos (point))
11445 (line (org-current-line))
11446 (params (org-prepare-dblock))
11447 (name (plist-get params :name))
11448 (indent (plist-get params :indentation-column))
11449 (cmd (intern (concat "org-dblock-write:" name))))
11450 (message "Updating dynamic block `%s' at line %d..." name line)
11451 (funcall cmd params)
11452 (message "Updating dynamic block `%s' at line %d...done" name line)
11453 (goto-char pos)
11454 (when (and indent (> indent 0))
11455 (setq indent (make-string indent ?\ ))
11456 (save-excursion
11457 (org-beginning-of-dblock)
11458 (forward-line 1)
11459 (while (not (looking-at org-dblock-end-re))
11460 (insert indent)
11461 (beginning-of-line 2))
11462 (when (looking-at org-dblock-end-re)
11463 (and (looking-at "[ \t]+")
11464 (replace-match ""))
11465 (insert indent)))))))
11467 (defun org-beginning-of-dblock ()
11468 "Find the beginning of the dynamic block at point.
11469 Error if there is no such block at point."
11470 (let ((pos (point))
11471 beg)
11472 (end-of-line 1)
11473 (if (and (re-search-backward org-dblock-start-re nil t)
11474 (setq beg (match-beginning 0))
11475 (re-search-forward org-dblock-end-re nil t)
11476 (> (match-end 0) pos))
11477 (goto-char beg)
11478 (goto-char pos)
11479 (error "Not in a dynamic block"))))
11481 (defun org-update-all-dblocks ()
11482 "Update all dynamic blocks in the buffer.
11483 This function can be used in a hook."
11484 (interactive)
11485 (when (derived-mode-p 'org-mode)
11486 (org-map-dblocks 'org-update-dblock)))
11489 ;;;; Completion
11491 (defconst org-additional-option-like-keywords
11492 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11493 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11494 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11495 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11496 "BEGIN:" "END:"
11497 "ORGTBL" "TBLFM:" "TBLNAME:"
11498 "BEGIN_EXAMPLE" "END_EXAMPLE"
11499 "BEGIN_VERBATIM" "END_VERBATIM"
11500 "BEGIN_QUOTE" "END_QUOTE"
11501 "BEGIN_VERSE" "END_VERSE"
11502 "BEGIN_CENTER" "END_CENTER"
11503 "BEGIN_SRC" "END_SRC"
11504 "BEGIN_RESULT" "END_RESULT"
11505 "BEGIN_lstlisting" "END_lstlisting"
11506 "NAME:" "RESULTS:"
11507 "HEADER:" "HEADERS:"
11508 "COLUMNS:" "PROPERTY:"
11509 "CAPTION:" "LABEL:"
11510 "SETUPFILE:"
11511 "INCLUDE:" "INDEX:"
11512 "BIND:"
11513 "MACRO:"))
11515 (defconst org-options-keywords
11516 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11517 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11518 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11519 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11520 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11521 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11522 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11524 (defconst org-additional-option-like-keywords-for-flyspell
11525 (delete-dups
11526 (split-string
11527 (mapconcat (lambda(k)
11528 (replace-regexp-in-string
11529 "_\\|:" " "
11530 (concat k " " (downcase k) " " (upcase k))))
11531 (append org-options-keywords org-additional-option-like-keywords)
11532 " ")
11533 " +" t)))
11535 (defcustom org-structure-template-alist
11536 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11537 "<src lang=\"?\">\n\n</src>")
11538 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11539 "<example>\n?\n</example>")
11540 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11541 "<quote>\n?\n</quote>")
11542 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11543 "<verse>\n?\n</verse>")
11544 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11545 "<verbatim>\n?\n</verbatim>")
11546 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11547 "<center>\n?\n</center>")
11548 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11549 "<literal style=\"latex\">\n?\n</literal>")
11550 ("L" "#+LaTeX: "
11551 "<literal style=\"latex\">?</literal>")
11552 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11553 "<literal style=\"html\">\n?\n</literal>")
11554 ("H" "#+HTML: "
11555 "<literal style=\"html\">?</literal>")
11556 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11557 ("A" "#+ASCII: ")
11558 ("i" "#+INDEX: ?"
11559 "#+INDEX: ?")
11560 ("I" "#+INCLUDE: %file ?"
11561 "<include file=%file markup=\"?\">"))
11562 "Structure completion elements.
11563 This is a list of abbreviation keys and values. The value gets inserted
11564 if you type `<' followed by the key and then press the completion key,
11565 usually `M-TAB'. %file will be replaced by a file name after prompting
11566 for the file using completion. The cursor will be placed at the position
11567 of the `?` in the template.
11568 There are two templates for each key, the first uses the original Org syntax,
11569 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11570 the default when the /org-mtags.el/ module has been loaded. See also the
11571 variable `org-mtags-prefer-muse-templates'."
11572 :group 'org-completion
11573 :type '(repeat
11574 (string :tag "Key")
11575 (string :tag "Template")
11576 (string :tag "Muse Template")))
11578 (defun org-try-structure-completion ()
11579 "Try to complete a structure template before point.
11580 This looks for strings like \"<e\" on an otherwise empty line and
11581 expands them."
11582 (let ((l (buffer-substring (point-at-bol) (point)))
11584 (when (and (looking-at "[ \t]*$")
11585 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11586 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11587 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11588 (match-beginning 1)) a)
11589 t)))
11591 (defun org-complete-expand-structure-template (start cell)
11592 "Expand a structure template."
11593 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11594 (rpl (nth (if musep 2 1) cell))
11595 (ind ""))
11596 (delete-region start (point))
11597 (when (string-match "\\`#\\+" rpl)
11598 (cond
11599 ((bolp))
11600 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11601 (setq ind (buffer-substring (point-at-bol) (point))))
11602 (t (newline))))
11603 (setq start (point))
11604 (if (string-match "%file" rpl)
11605 (setq rpl (replace-match
11606 (concat
11607 "\""
11608 (save-match-data
11609 (abbreviate-file-name (read-file-name "Include file: ")))
11610 "\"")
11611 t t rpl)))
11612 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11613 (concat "\n" ind)))
11614 (insert rpl)
11615 (if (re-search-backward "\\?" start t) (delete-char 1))))
11617 ;;;; TODO, DEADLINE, Comments
11619 (defun org-toggle-comment ()
11620 "Change the COMMENT state of an entry."
11621 (interactive)
11622 (save-excursion
11623 (org-back-to-heading)
11624 (let (case-fold-search)
11625 (cond
11626 ((looking-at (format org-heading-keyword-regexp-format
11627 org-comment-string))
11628 (goto-char (match-end 1))
11629 (looking-at (concat " +" org-comment-string))
11630 (replace-match "" t t)
11631 (when (eolp) (insert " ")))
11632 ((looking-at org-outline-regexp)
11633 (goto-char (match-end 0))
11634 (insert org-comment-string " "))))))
11636 (defvar org-last-todo-state-is-todo nil
11637 "This is non-nil when the last TODO state change led to a TODO state.
11638 If the last change removed the TODO tag or switched to DONE, then
11639 this is nil.")
11641 (defvar org-setting-tags nil) ; dynamically skipped
11643 (defvar org-todo-setup-filter-hook nil
11644 "Hook for functions that pre-filter todo specs.
11645 Each function takes a todo spec and returns either nil or the spec
11646 transformed into canonical form." )
11648 (defvar org-todo-get-default-hook nil
11649 "Hook for functions that get a default item for todo.
11650 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11651 nil or a string to be used for the todo mark." )
11653 (defvar org-agenda-headline-snapshot-before-repeat)
11655 (defun org-current-effective-time ()
11656 "Return current time adjusted for `org-extend-today-until' variable."
11657 (let* ((ct (org-current-time))
11658 (dct (decode-time ct))
11659 (ct1
11660 (cond
11661 (org-use-last-clock-out-time-as-effective-time
11662 (or (org-clock-get-last-clock-out-time) ct))
11663 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11664 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11665 (t ct))))
11666 ct1))
11668 (defun org-todo-yesterday (&optional arg)
11669 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11670 (interactive "P")
11671 (if (eq major-mode 'org-agenda-mode)
11672 (apply 'org-agenda-todo-yesterday arg)
11673 (let* ((hour (third (decode-time
11674 (org-current-time))))
11675 (org-extend-today-until (1+ hour)))
11676 (org-todo arg))))
11678 (defvar org-block-entry-blocking ""
11679 "First entry preventing the TODO state change.")
11681 (defun org-todo (&optional arg)
11682 "Change the TODO state of an item.
11683 The state of an item is given by a keyword at the start of the heading,
11684 like
11685 *** TODO Write paper
11686 *** DONE Call mom
11688 The different keywords are specified in the variable `org-todo-keywords'.
11689 By default the available states are \"TODO\" and \"DONE\".
11690 So for this example: when the item starts with TODO, it is changed to DONE.
11691 When it starts with DONE, the DONE is removed. And when neither TODO nor
11692 DONE are present, add TODO at the beginning of the heading.
11694 With \\[universal-argument] prefix arg, use completion to determine the new \
11695 state.
11696 With numeric prefix arg, switch to that state.
11697 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11698 keywords (nextset).
11699 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11700 With a numeric prefix arg of 0, inhibit note taking for the change.
11702 For calling through lisp, arg is also interpreted in the following way:
11703 'none -> empty state
11704 \"\"(empty string) -> switch to empty state
11705 'done -> switch to DONE
11706 'nextset -> switch to the next set of keywords
11707 'previousset -> switch to the previous set of keywords
11708 \"WAITING\" -> switch to the specified keyword, but only if it
11709 really is a member of `org-todo-keywords'."
11710 (interactive "P")
11711 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11712 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11713 'region-start-level 'region))
11714 org-loop-over-headlines-in-active-region)
11715 (org-map-entries
11716 `(org-todo ,arg)
11717 org-loop-over-headlines-in-active-region
11718 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11719 (if (equal arg '(16)) (setq arg 'nextset))
11720 (let ((org-blocker-hook org-blocker-hook)
11721 commentp
11722 case-fold-search)
11723 (when (equal arg '(64))
11724 (setq arg nil org-blocker-hook nil))
11725 (when (and org-blocker-hook
11726 (or org-inhibit-blocking
11727 (org-entry-get nil "NOBLOCKING")))
11728 (setq org-blocker-hook nil))
11729 (save-excursion
11730 (catch 'exit
11731 (org-back-to-heading t)
11732 (when (looking-at (concat "^\\*+ " org-comment-string))
11733 (org-toggle-comment)
11734 (setq commentp t))
11735 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11736 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11737 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11738 (let* ((match-data (match-data))
11739 (startpos (point-at-bol))
11740 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11741 (org-log-done org-log-done)
11742 (org-log-repeat org-log-repeat)
11743 (org-todo-log-states org-todo-log-states)
11744 (org-inhibit-logging
11745 (if (equal arg 0)
11746 (progn (setq arg nil) 'note) org-inhibit-logging))
11747 (this (match-string 1))
11748 (hl-pos (match-beginning 0))
11749 (head (org-get-todo-sequence-head this))
11750 (ass (assoc head org-todo-kwd-alist))
11751 (interpret (nth 1 ass))
11752 (done-word (nth 3 ass))
11753 (final-done-word (nth 4 ass))
11754 (org-last-state (or this ""))
11755 (completion-ignore-case t)
11756 (member (member this org-todo-keywords-1))
11757 (tail (cdr member))
11758 (org-state (cond
11759 ((and org-todo-key-trigger
11760 (or (and (equal arg '(4))
11761 (eq org-use-fast-todo-selection 'prefix))
11762 (and (not arg) org-use-fast-todo-selection
11763 (not (eq org-use-fast-todo-selection
11764 'prefix)))))
11765 ;; Use fast selection
11766 (org-fast-todo-selection))
11767 ((and (equal arg '(4))
11768 (or (not org-use-fast-todo-selection)
11769 (not org-todo-key-trigger)))
11770 ;; Read a state with completion
11771 (org-icompleting-read
11772 "State: " (mapcar (lambda(x) (list x))
11773 org-todo-keywords-1)
11774 nil t))
11775 ((eq arg 'right)
11776 (if this
11777 (if tail (car tail) nil)
11778 (car org-todo-keywords-1)))
11779 ((eq arg 'left)
11780 (if (equal member org-todo-keywords-1)
11782 (if this
11783 (nth (- (length org-todo-keywords-1)
11784 (length tail) 2)
11785 org-todo-keywords-1)
11786 (org-last org-todo-keywords-1))))
11787 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11788 (setq arg nil))) ; hack to fall back to cycling
11789 (arg
11790 ;; user or caller requests a specific state
11791 (cond
11792 ((equal arg "") nil)
11793 ((eq arg 'none) nil)
11794 ((eq arg 'done) (or done-word (car org-done-keywords)))
11795 ((eq arg 'nextset)
11796 (or (car (cdr (member head org-todo-heads)))
11797 (car org-todo-heads)))
11798 ((eq arg 'previousset)
11799 (let ((org-todo-heads (reverse org-todo-heads)))
11800 (or (car (cdr (member head org-todo-heads)))
11801 (car org-todo-heads))))
11802 ((car (member arg org-todo-keywords-1)))
11803 ((stringp arg)
11804 (error "State `%s' not valid in this file" arg))
11805 ((nth (1- (prefix-numeric-value arg))
11806 org-todo-keywords-1))))
11807 ((null member) (or head (car org-todo-keywords-1)))
11808 ((equal this final-done-word) nil) ;; -> make empty
11809 ((null tail) nil) ;; -> first entry
11810 ((memq interpret '(type priority))
11811 (if (eq this-command last-command)
11812 (car tail)
11813 (if (> (length tail) 0)
11814 (or done-word (car org-done-keywords))
11815 nil)))
11817 (car tail))))
11818 (org-state (or
11819 (run-hook-with-args-until-success
11820 'org-todo-get-default-hook org-state org-last-state)
11821 org-state))
11822 (next (if org-state (concat " " org-state " ") " "))
11823 (change-plist (list :type 'todo-state-change :from this :to org-state
11824 :position startpos))
11825 dolog now-done-p)
11826 (when org-blocker-hook
11827 (setq org-last-todo-state-is-todo
11828 (not (member this org-done-keywords)))
11829 (unless (save-excursion
11830 (save-match-data
11831 (org-with-wide-buffer
11832 (run-hook-with-args-until-failure
11833 'org-blocker-hook change-plist))))
11834 (if (org-called-interactively-p 'interactive)
11835 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11836 this org-state org-block-entry-blocking)
11837 ;; fail silently
11838 (message "TODO state change from %s to %s blocked (by \"%s\")"
11839 this org-state org-block-entry-blocking)
11840 (throw 'exit nil))))
11841 (store-match-data match-data)
11842 (replace-match next t t)
11843 (unless (pos-visible-in-window-p hl-pos)
11844 (message "TODO state changed to %s" (org-trim next)))
11845 (unless head
11846 (setq head (org-get-todo-sequence-head org-state)
11847 ass (assoc head org-todo-kwd-alist)
11848 interpret (nth 1 ass)
11849 done-word (nth 3 ass)
11850 final-done-word (nth 4 ass)))
11851 (when (memq arg '(nextset previousset))
11852 (message "Keyword-Set %d/%d: %s"
11853 (- (length org-todo-sets) -1
11854 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11855 (length org-todo-sets)
11856 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11857 (setq org-last-todo-state-is-todo
11858 (not (member org-state org-done-keywords)))
11859 (setq now-done-p (and (member org-state org-done-keywords)
11860 (not (member this org-done-keywords))))
11861 (and logging (org-local-logging logging))
11862 (when (and (or org-todo-log-states org-log-done)
11863 (not (eq org-inhibit-logging t))
11864 (not (memq arg '(nextset previousset))))
11865 ;; we need to look at recording a time and note
11866 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11867 (nth 2 (assoc this org-todo-log-states))))
11868 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11869 (setq dolog 'time))
11870 (when (and org-state
11871 (member org-state org-not-done-keywords)
11872 (not (member this org-not-done-keywords)))
11873 ;; This is now a todo state and was not one before
11874 ;; If there was a CLOSED time stamp, get rid of it.
11875 (org-add-planning-info nil nil 'closed))
11876 (when (and now-done-p org-log-done)
11877 ;; It is now done, and it was not done before
11878 (org-add-planning-info 'closed (org-current-effective-time))
11879 (if (and (not dolog) (eq 'note org-log-done))
11880 (org-add-log-setup 'done org-state this 'findpos 'note)))
11881 (when (and org-state dolog)
11882 ;; This is a non-nil state, and we need to log it
11883 (org-add-log-setup 'state org-state this 'findpos dolog)))
11884 ;; Fixup tag positioning
11885 (org-todo-trigger-tag-changes org-state)
11886 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11887 (when org-provide-todo-statistics
11888 (org-update-parent-todo-statistics))
11889 (run-hooks 'org-after-todo-state-change-hook)
11890 (if (and arg (not (member org-state org-done-keywords)))
11891 (setq head (org-get-todo-sequence-head org-state)))
11892 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11893 ;; Do we need to trigger a repeat?
11894 (when now-done-p
11895 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11896 ;; This is for the agenda, take a snapshot of the headline.
11897 (save-match-data
11898 (setq org-agenda-headline-snapshot-before-repeat
11899 (org-get-heading))))
11900 (org-auto-repeat-maybe org-state))
11901 ;; Fixup cursor location if close to the keyword
11902 (if (and (outline-on-heading-p)
11903 (not (bolp))
11904 (save-excursion (beginning-of-line 1)
11905 (looking-at org-todo-line-regexp))
11906 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11907 (progn
11908 (goto-char (or (match-end 2) (match-end 1)))
11909 (and (looking-at " ") (just-one-space))))
11910 (when org-trigger-hook
11911 (save-excursion
11912 (run-hook-with-args 'org-trigger-hook change-plist)))
11913 (when commentp (org-toggle-comment))))))))
11915 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11916 "Block turning an entry into a TODO, using the hierarchy.
11917 This checks whether the current task should be blocked from state
11918 changes. Such blocking occurs when:
11920 1. The task has children which are not all in a completed state.
11922 2. A task has a parent with the property :ORDERED:, and there
11923 are siblings prior to the current task with incomplete
11924 status.
11926 3. The parent of the task is blocked because it has siblings that should
11927 be done first, or is child of a block grandparent TODO entry."
11929 (if (not org-enforce-todo-dependencies)
11930 t ; if locally turned off don't block
11931 (catch 'dont-block
11932 ;; If this is not a todo state change, or if this entry is already DONE,
11933 ;; do not block
11934 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11935 (member (plist-get change-plist :from)
11936 (cons 'done org-done-keywords))
11937 (member (plist-get change-plist :to)
11938 (cons 'todo org-not-done-keywords))
11939 (not (plist-get change-plist :to)))
11940 (throw 'dont-block t))
11941 ;; If this task has children, and any are undone, it's blocked
11942 (save-excursion
11943 (org-back-to-heading t)
11944 (let ((this-level (funcall outline-level)))
11945 (outline-next-heading)
11946 (let ((child-level (funcall outline-level)))
11947 (while (and (not (eobp))
11948 (> child-level this-level))
11949 ;; this todo has children, check whether they are all
11950 ;; completed
11951 (if (and (not (org-entry-is-done-p))
11952 (org-entry-is-todo-p))
11953 (progn (setq org-block-entry-blocking (org-get-heading))
11954 (throw 'dont-block nil)))
11955 (outline-next-heading)
11956 (setq child-level (funcall outline-level))))))
11957 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11958 ;; any previous siblings are undone, it's blocked
11959 (save-excursion
11960 (org-back-to-heading t)
11961 (let* ((pos (point))
11962 (parent-pos (and (org-up-heading-safe) (point))))
11963 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11964 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11965 (forward-line 1)
11966 (re-search-forward org-not-done-heading-regexp pos t))
11967 (setq org-block-entry-blocking (match-string 0))
11968 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11969 ;; Search further up the hierarchy, to see if an ancestor is blocked
11970 (while t
11971 (goto-char parent-pos)
11972 (if (not (looking-at org-not-done-heading-regexp))
11973 (throw 'dont-block t)) ; do not block, parent is not a TODO
11974 (setq pos (point))
11975 (setq 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 (org-get-heading)))
11981 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11983 (defcustom org-track-ordered-property-with-tag nil
11984 "Should the ORDERED property also be shown as a tag?
11985 The ORDERED property decides if an entry should require subtasks to be
11986 completed in sequence. Since a property is not very visible, setting
11987 this option means that toggling the ORDERED property with the command
11988 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11989 not relevant for the behavior, but it makes things more visible.
11991 Note that toggling the tag with tags commands will not change the property
11992 and therefore not influence behavior!
11994 This can be t, meaning the tag ORDERED should be used, It can also be a
11995 string to select a different tag for this task."
11996 :group 'org-todo
11997 :type '(choice
11998 (const :tag "No tracking" nil)
11999 (const :tag "Track with ORDERED tag" t)
12000 (string :tag "Use other tag")))
12002 (defun org-toggle-ordered-property ()
12003 "Toggle the ORDERED property of the current entry.
12004 For better visibility, you can track the value of this property with a tag.
12005 See variable `org-track-ordered-property-with-tag'."
12006 (interactive)
12007 (let* ((t1 org-track-ordered-property-with-tag)
12008 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12009 (save-excursion
12010 (org-back-to-heading)
12011 (if (org-entry-get nil "ORDERED")
12012 (progn
12013 (org-delete-property "ORDERED")
12014 (and tag (org-toggle-tag tag 'off))
12015 (message "Subtasks can be completed in arbitrary order"))
12016 (org-entry-put nil "ORDERED" "t")
12017 (and tag (org-toggle-tag tag 'on))
12018 (message "Subtasks must be completed in sequence")))))
12020 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12021 (defun org-block-todo-from-checkboxes (change-plist)
12022 "Block turning an entry into a TODO, using checkboxes.
12023 This checks whether the current task should be blocked from state
12024 changes because there are unchecked boxes in this entry."
12025 (if (not org-enforce-todo-checkbox-dependencies)
12026 t ; if locally turned off don't block
12027 (catch 'dont-block
12028 ;; If this is not a todo state change, or if this entry is already DONE,
12029 ;; do not block
12030 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12031 (member (plist-get change-plist :from)
12032 (cons 'done org-done-keywords))
12033 (member (plist-get change-plist :to)
12034 (cons 'todo org-not-done-keywords))
12035 (not (plist-get change-plist :to)))
12036 (throw 'dont-block t))
12037 ;; If this task has checkboxes that are not checked, it's blocked
12038 (save-excursion
12039 (org-back-to-heading t)
12040 (let ((beg (point)) end)
12041 (outline-next-heading)
12042 (setq end (point))
12043 (goto-char beg)
12044 (if (org-list-search-forward
12045 (concat (org-item-beginning-re)
12046 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12047 "\\[[- ]\\]")
12048 end t)
12049 (progn
12050 (if (boundp 'org-blocked-by-checkboxes)
12051 (setq org-blocked-by-checkboxes t))
12052 (throw 'dont-block nil)))))
12053 t))) ; do not block
12055 (defun org-entry-blocked-p ()
12056 "Is the current entry blocked?"
12057 (org-with-buffer-modified-unmodified
12058 (if (org-entry-get nil "NOBLOCKING")
12059 nil ;; Never block this entry
12060 (not
12061 (run-hook-with-args-until-failure
12062 'org-blocker-hook
12063 (list :type 'todo-state-change
12064 :position (point)
12065 :from 'todo
12066 :to 'done))))))
12068 (defun org-update-statistics-cookies (all)
12069 "Update the statistics cookie, either from TODO or from checkboxes.
12070 This should be called with the cursor in a line with a statistics cookie."
12071 (interactive "P")
12072 (if all
12073 (progn
12074 (org-update-checkbox-count 'all)
12075 (org-map-entries 'org-update-parent-todo-statistics))
12076 (if (not (org-at-heading-p))
12077 (org-update-checkbox-count)
12078 (let ((pos (point-marker))
12079 end l1 l2)
12080 (ignore-errors (org-back-to-heading t))
12081 (if (not (org-at-heading-p))
12082 (org-update-checkbox-count)
12083 (setq l1 (org-outline-level))
12084 (setq end (save-excursion
12085 (outline-next-heading)
12086 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12087 (point)))
12088 (if (and (save-excursion
12089 (re-search-forward
12090 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12091 (not (save-excursion (re-search-forward
12092 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12093 (org-update-checkbox-count)
12094 (if (and l2 (> l2 l1))
12095 (progn
12096 (goto-char end)
12097 (org-update-parent-todo-statistics))
12098 (goto-char pos)
12099 (beginning-of-line 1)
12100 (while (re-search-forward
12101 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12102 (point-at-eol) t)
12103 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12104 (goto-char pos)
12105 (move-marker pos nil)))))
12107 (defvar org-entry-property-inherited-from) ;; defined below
12108 (defun org-update-parent-todo-statistics ()
12109 "Update any statistics cookie in the parent of the current headline.
12110 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12111 the entire subtree and this will travel up the hierarchy and update
12112 statistics everywhere."
12113 (let* ((prop (save-excursion (org-up-heading-safe)
12114 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12115 (recursive (or (not org-hierarchical-todo-statistics)
12116 (and prop (string-match "\\<recursive\\>" prop))))
12117 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12119 (first t)
12120 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12121 level ltoggle l1 new ndel
12122 (cnt-all 0) (cnt-done 0) is-percent kwd
12123 checkbox-beg ov ovs ove cookie-present)
12124 (catch 'exit
12125 (save-excursion
12126 (beginning-of-line 1)
12127 (setq ltoggle (funcall outline-level))
12128 ;; Three situations are to consider:
12130 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12131 ;; to the top-level ancestor on the headline;
12133 ;; 2. If parent has "recursive" property, repeat up to the
12134 ;; headline setting that property, taking inheritance into
12135 ;; account;
12137 ;; 3. Else, move up to direct parent and proceed only once.
12138 (while (and (setq level (org-up-heading-safe))
12139 (or recursive first)
12140 (>= (point) lim))
12141 (setq first nil cookie-present nil)
12142 (unless (and level
12143 (not (string-match
12144 "\\<checkbox\\>"
12145 (downcase (or (org-entry-get nil "COOKIE_DATA")
12146 "")))))
12147 (throw 'exit nil))
12148 (while (re-search-forward box-re (point-at-eol) t)
12149 (setq cnt-all 0 cnt-done 0 cookie-present t)
12150 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12151 (save-match-data
12152 (unless (outline-next-heading) (throw 'exit nil))
12153 (while (and (looking-at org-complex-heading-regexp)
12154 (> (setq l1 (length (match-string 1))) level))
12155 (setq kwd (and (or recursive (= l1 ltoggle))
12156 (match-string 2)))
12157 (if (or (eq org-provide-todo-statistics 'all-headlines)
12158 (and (listp org-provide-todo-statistics)
12159 (or (member kwd org-provide-todo-statistics)
12160 (member kwd org-done-keywords))))
12161 (setq cnt-all (1+ cnt-all))
12162 (if (eq org-provide-todo-statistics t)
12163 (and kwd (setq cnt-all (1+ cnt-all)))))
12164 (and (member kwd org-done-keywords)
12165 (setq cnt-done (1+ cnt-done)))
12166 (outline-next-heading)))
12167 (setq new
12168 (if is-percent
12169 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12170 (format "[%d/%d]" cnt-done cnt-all))
12171 ndel (- (match-end 0) checkbox-beg))
12172 ;; handle overlays when updating cookie from column view
12173 (when (setq ov (car (overlays-at checkbox-beg)))
12174 (setq ovs (overlay-start ov) ove (overlay-end ov))
12175 (delete-overlay ov))
12176 (goto-char checkbox-beg)
12177 (insert new)
12178 (delete-region (point) (+ (point) ndel))
12179 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12180 (when ov (move-overlay ov ovs ove)))
12181 (when cookie-present
12182 (run-hook-with-args 'org-after-todo-statistics-hook
12183 cnt-done (- cnt-all cnt-done))))))
12184 (run-hooks 'org-todo-statistics-hook)))
12186 (defvar org-after-todo-statistics-hook nil
12187 "Hook that is called after a TODO statistics cookie has been updated.
12188 Each function is called with two arguments: the number of not-done entries
12189 and the number of done entries.
12191 For example, the following function, when added to this hook, will switch
12192 an entry to DONE when all children are done, and back to TODO when new
12193 entries are set to a TODO status. Note that this hook is only called
12194 when there is a statistics cookie in the headline!
12196 (defun org-summary-todo (n-done n-not-done)
12197 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12198 (let (org-log-done org-log-states) ; turn off logging
12199 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12202 (defvar org-todo-statistics-hook nil
12203 "Hook that is run whenever Org thinks TODO statistics should be updated.
12204 This hook runs even if there is no statistics cookie present, in which case
12205 `org-after-todo-statistics-hook' would not run.")
12207 (defun org-todo-trigger-tag-changes (state)
12208 "Apply the changes defined in `org-todo-state-tags-triggers'."
12209 (let ((l org-todo-state-tags-triggers)
12210 changes)
12211 (when (or (not state) (equal state ""))
12212 (setq changes (append changes (cdr (assoc "" l)))))
12213 (when (and (stringp state) (> (length state) 0))
12214 (setq changes (append changes (cdr (assoc state l)))))
12215 (when (member state org-not-done-keywords)
12216 (setq changes (append changes (cdr (assoc 'todo l)))))
12217 (when (member state org-done-keywords)
12218 (setq changes (append changes (cdr (assoc 'done l)))))
12219 (dolist (c changes)
12220 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12222 (defun org-local-logging (value)
12223 "Get logging settings from a property VALUE."
12224 (let* (words w a)
12225 ;; directly set the variables, they are already local.
12226 (setq org-log-done nil
12227 org-log-repeat nil
12228 org-todo-log-states nil)
12229 (setq words (org-split-string value))
12230 (while (setq w (pop words))
12231 (cond
12232 ((setq a (assoc w org-startup-options))
12233 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12234 (set (nth 1 a) (nth 2 a))))
12235 ((setq a (org-extract-log-state-settings w))
12236 (and (member (car a) org-todo-keywords-1)
12237 (push a org-todo-log-states)))))))
12239 (defun org-get-todo-sequence-head (kwd)
12240 "Return the head of the TODO sequence to which KWD belongs.
12241 If KWD is not set, check if there is a text property remembering the
12242 right sequence."
12243 (let (p)
12244 (cond
12245 ((not kwd)
12246 (or (get-text-property (point-at-bol) 'org-todo-head)
12247 (progn
12248 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12249 nil (point-at-eol)))
12250 (get-text-property p 'org-todo-head))))
12251 ((not (member kwd org-todo-keywords-1))
12252 (car org-todo-keywords-1))
12253 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12255 (defun org-fast-todo-selection ()
12256 "Fast TODO keyword selection with single keys.
12257 Returns the new TODO keyword, or nil if no state change should occur."
12258 (let* ((fulltable org-todo-key-alist)
12259 (done-keywords org-done-keywords) ;; needed for the faces.
12260 (maxlen (apply 'max (mapcar
12261 (lambda (x)
12262 (if (stringp (car x)) (string-width (car x)) 0))
12263 fulltable)))
12264 (expert nil)
12265 (fwidth (+ maxlen 3 1 3))
12266 (ncol (/ (- (window-width) 4) fwidth))
12267 tg cnt e c tbl
12268 groups ingroup)
12269 (save-excursion
12270 (save-window-excursion
12271 (if expert
12272 (set-buffer (get-buffer-create " *Org todo*"))
12273 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12274 (erase-buffer)
12275 (org-set-local 'org-done-keywords done-keywords)
12276 (setq tbl fulltable cnt 0)
12277 (while (setq e (pop tbl))
12278 (cond
12279 ((equal e '(:startgroup))
12280 (push '() groups) (setq ingroup t)
12281 (when (not (= cnt 0))
12282 (setq cnt 0)
12283 (insert "\n"))
12284 (insert "{ "))
12285 ((equal e '(:endgroup))
12286 (setq ingroup nil cnt 0)
12287 (insert "}\n"))
12288 ((equal e '(:newline))
12289 (when (not (= cnt 0))
12290 (setq cnt 0)
12291 (insert "\n")
12292 (setq e (car tbl))
12293 (while (equal (car tbl) '(:newline))
12294 (insert "\n")
12295 (setq tbl (cdr tbl)))))
12297 (setq tg (car e) c (cdr e))
12298 (if ingroup (push tg (car groups)))
12299 (setq tg (org-add-props tg nil 'face
12300 (org-get-todo-face tg)))
12301 (if (and (= cnt 0) (not ingroup)) (insert " "))
12302 (insert "[" c "] " tg (make-string
12303 (- fwidth 4 (length tg)) ?\ ))
12304 (when (= (setq cnt (1+ cnt)) ncol)
12305 (insert "\n")
12306 (if ingroup (insert " "))
12307 (setq cnt 0)))))
12308 (insert "\n")
12309 (goto-char (point-min))
12310 (if (not expert) (org-fit-window-to-buffer))
12311 (message "[a-z..]:Set [SPC]:clear")
12312 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12313 (cond
12314 ((or (= c ?\C-g)
12315 (and (= c ?q) (not (rassoc c fulltable))))
12316 (setq quit-flag t))
12317 ((= c ?\ ) nil)
12318 ((setq e (rassoc c fulltable) tg (car e))
12320 (t (setq quit-flag t)))))))
12322 (defun org-entry-is-todo-p ()
12323 (member (org-get-todo-state) org-not-done-keywords))
12325 (defun org-entry-is-done-p ()
12326 (member (org-get-todo-state) org-done-keywords))
12328 (defun org-get-todo-state ()
12329 (save-excursion
12330 (org-back-to-heading t)
12331 (and (looking-at org-todo-line-regexp)
12332 (match-end 2)
12333 (match-string 2))))
12335 (defun org-at-date-range-p (&optional inactive-ok)
12336 "Is the cursor inside a date range?"
12337 (interactive)
12338 (save-excursion
12339 (catch 'exit
12340 (let ((pos (point)))
12341 (skip-chars-backward "^[<\r\n")
12342 (skip-chars-backward "<[")
12343 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12344 (>= (match-end 0) pos)
12345 (throw 'exit t))
12346 (skip-chars-backward "^<[\r\n")
12347 (skip-chars-backward "<[")
12348 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12349 (>= (match-end 0) pos)
12350 (throw 'exit t)))
12351 nil)))
12353 (defun org-get-repeat (&optional tagline)
12354 "Check if there is a deadline/schedule with repeater in this entry."
12355 (save-match-data
12356 (save-excursion
12357 (org-back-to-heading t)
12358 (and (re-search-forward (if tagline
12359 (concat tagline "\\s-*" org-repeat-re)
12360 org-repeat-re)
12361 (org-entry-end-position) t)
12362 (match-string-no-properties 1)))))
12364 (defvar org-last-changed-timestamp)
12365 (defvar org-last-inserted-timestamp)
12366 (defvar org-log-post-message)
12367 (defvar org-log-note-purpose)
12368 (defvar org-log-note-how)
12369 (defvar org-log-note-extra)
12370 (defun org-auto-repeat-maybe (done-word)
12371 "Check if the current headline contains a repeated deadline/schedule.
12372 If yes, set TODO state back to what it was and change the base date
12373 of repeating deadline/scheduled time stamps to new date.
12374 This function is run automatically after each state change to a DONE state."
12375 ;; last-state is dynamically scoped into this function
12376 (let* ((repeat (org-get-repeat))
12377 (aa (assoc org-last-state org-todo-kwd-alist))
12378 (interpret (nth 1 aa))
12379 (head (nth 2 aa))
12380 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12381 (msg "Entry repeats: ")
12382 (org-log-done nil)
12383 (org-todo-log-states nil)
12384 re type n what ts time to-state)
12385 (when repeat
12386 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12387 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12388 org-todo-repeat-to-state))
12389 (unless (and to-state (member to-state org-todo-keywords-1))
12390 (setq to-state (if (eq interpret 'type) org-last-state head)))
12391 (org-todo to-state)
12392 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12393 (org-entry-put nil "LAST_REPEAT" (format-time-string
12394 (org-time-stamp-format t t))))
12395 (when org-log-repeat
12396 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12397 (memq 'org-add-log-note post-command-hook))
12398 ;; OK, we are already setup for some record
12399 (if (eq org-log-repeat 'note)
12400 ;; make sure we take a note, not only a time stamp
12401 (setq org-log-note-how 'note))
12402 ;; Set up for taking a record
12403 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12404 org-last-state
12405 'findpos org-log-repeat)))
12406 (org-back-to-heading t)
12407 (org-add-planning-info nil nil 'closed)
12408 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12409 org-deadline-time-regexp "\\)\\|\\("
12410 org-ts-regexp "\\)"))
12411 (while (re-search-forward
12412 re (save-excursion (outline-next-heading) (point)) t)
12413 (setq type (if (match-end 1) org-scheduled-string
12414 (if (match-end 3) org-deadline-string "Plain:"))
12415 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12416 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12417 (setq n (string-to-number (match-string 2 ts))
12418 what (match-string 3 ts))
12419 (if (equal what "w") (setq n (* n 7) what "d"))
12420 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12421 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12422 ;; Preparation, see if we need to modify the start date for the change
12423 (when (match-end 1)
12424 (setq time (save-match-data (org-time-string-to-time ts)))
12425 (cond
12426 ((equal (match-string 1 ts) ".")
12427 ;; Shift starting date to today
12428 (org-timestamp-change
12429 (- (org-today) (time-to-days time))
12430 'day))
12431 ((equal (match-string 1 ts) "+")
12432 (let ((nshiftmax 10) (nshift 0))
12433 (while (or (= nshift 0)
12434 (<= (time-to-days time)
12435 (time-to-days (current-time))))
12436 (when (= (incf nshift) nshiftmax)
12437 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12438 (error "Abort")))
12439 (org-timestamp-change n (cdr (assoc what whata)))
12440 (org-at-timestamp-p t)
12441 (setq ts (match-string 1))
12442 (setq time (save-match-data (org-time-string-to-time ts)))))
12443 (org-timestamp-change (- n) (cdr (assoc what whata)))
12444 ;; rematch, so that we have everything in place for the real shift
12445 (org-at-timestamp-p t)
12446 (setq ts (match-string 1))
12447 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12448 (org-timestamp-change n (cdr (assoc what whata)))
12449 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12450 (setq org-log-post-message msg)
12451 (message "%s" msg))))
12453 (defun org-show-todo-tree (arg)
12454 "Make a compact tree which shows all headlines marked with TODO.
12455 The tree will show the lines where the regexp matches, and all higher
12456 headlines above the match.
12457 With a \\[universal-argument] prefix, prompt for a regexp to match.
12458 With a numeric prefix N, construct a sparse tree for the Nth element
12459 of `org-todo-keywords-1'."
12460 (interactive "P")
12461 (let ((case-fold-search nil)
12462 (kwd-re
12463 (cond ((null arg) org-not-done-regexp)
12464 ((equal arg '(4))
12465 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12466 (mapcar 'list org-todo-keywords-1))))
12467 (concat "\\("
12468 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12469 "\\)\\>")))
12470 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12471 (regexp-quote (nth (1- (prefix-numeric-value arg))
12472 org-todo-keywords-1)))
12473 (t (error "Invalid prefix argument: %s" arg)))))
12474 (message "%d TODO entries found"
12475 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12477 (defun org-deadline (&optional remove time)
12478 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12479 With argument REMOVE, remove any deadline from the item.
12480 With argument TIME, set the deadline at the corresponding date. TIME
12481 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12482 (interactive "P")
12483 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12484 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12485 'region-start-level 'region))
12486 org-loop-over-headlines-in-active-region)
12487 (org-map-entries
12488 `(org-deadline ',remove ,time)
12489 org-loop-over-headlines-in-active-region
12490 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12491 (let* ((old-date (org-entry-get nil "DEADLINE"))
12492 (repeater (and old-date
12493 (string-match
12494 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12495 old-date)
12496 (match-string 1 old-date))))
12497 (if remove
12498 (progn
12499 (when (and old-date org-log-redeadline)
12500 (org-add-log-setup 'deldeadline nil old-date 'findpos
12501 org-log-redeadline))
12502 (org-remove-timestamp-with-keyword org-deadline-string)
12503 (message "Item no longer has a deadline."))
12504 (org-add-planning-info 'deadline time 'closed)
12505 (when (and old-date org-log-redeadline
12506 (not (equal old-date
12507 (substring org-last-inserted-timestamp 1 -1))))
12508 (org-add-log-setup 'redeadline nil old-date 'findpos
12509 org-log-redeadline))
12510 (when repeater
12511 (save-excursion
12512 (org-back-to-heading t)
12513 (when (re-search-forward (concat org-deadline-string " "
12514 org-last-inserted-timestamp)
12515 (save-excursion
12516 (outline-next-heading) (point)) t)
12517 (goto-char (1- (match-end 0)))
12518 (insert " " repeater)
12519 (setq org-last-inserted-timestamp
12520 (concat (substring org-last-inserted-timestamp 0 -1)
12521 " " repeater
12522 (substring org-last-inserted-timestamp -1))))))
12523 (message "Deadline on %s" org-last-inserted-timestamp)))))
12525 (defun org-schedule (&optional remove time)
12526 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12527 With argument REMOVE, remove any scheduling date from the item.
12528 With argument TIME, scheduled at the corresponding date. TIME can
12529 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12530 (interactive "P")
12531 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12532 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12533 'region-start-level 'region))
12534 org-loop-over-headlines-in-active-region)
12535 (org-map-entries
12536 `(org-schedule ',remove ,time)
12537 org-loop-over-headlines-in-active-region
12538 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12539 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12540 (repeater (and old-date
12541 (string-match
12542 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12543 old-date)
12544 (match-string 1 old-date))))
12545 (if remove
12546 (progn
12547 (when (and old-date org-log-reschedule)
12548 (org-add-log-setup 'delschedule nil old-date 'findpos
12549 org-log-reschedule))
12550 (org-remove-timestamp-with-keyword org-scheduled-string)
12551 (message "Item is no longer scheduled."))
12552 (org-add-planning-info 'scheduled time 'closed)
12553 (when (and old-date org-log-reschedule
12554 (not (equal old-date
12555 (substring org-last-inserted-timestamp 1 -1))))
12556 (org-add-log-setup 'reschedule nil old-date 'findpos
12557 org-log-reschedule))
12558 (when repeater
12559 (save-excursion
12560 (org-back-to-heading t)
12561 (when (re-search-forward (concat org-scheduled-string " "
12562 org-last-inserted-timestamp)
12563 (save-excursion
12564 (outline-next-heading) (point)) t)
12565 (goto-char (1- (match-end 0)))
12566 (insert " " repeater)
12567 (setq org-last-inserted-timestamp
12568 (concat (substring org-last-inserted-timestamp 0 -1)
12569 " " repeater
12570 (substring org-last-inserted-timestamp -1))))))
12571 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12573 (defun org-get-scheduled-time (pom &optional inherit)
12574 "Get the scheduled time as a time tuple, of a format suitable
12575 for calling org-schedule with, or if there is no scheduling,
12576 returns nil."
12577 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12578 (when time
12579 (apply 'encode-time (org-parse-time-string time)))))
12581 (defun org-get-deadline-time (pom &optional inherit)
12582 "Get the deadline as a time tuple, of a format suitable for
12583 calling org-deadline with, or if there is no scheduling, returns
12584 nil."
12585 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12586 (when time
12587 (apply 'encode-time (org-parse-time-string time)))))
12589 (defun org-remove-timestamp-with-keyword (keyword)
12590 "Remove all time stamps with KEYWORD in the current entry."
12591 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12592 beg)
12593 (save-excursion
12594 (org-back-to-heading t)
12595 (setq beg (point))
12596 (outline-next-heading)
12597 (while (re-search-backward re beg t)
12598 (replace-match "")
12599 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12600 (equal (char-before) ?\ ))
12601 (backward-delete-char 1)
12602 (if (string-match "^[ \t]*$" (buffer-substring
12603 (point-at-bol) (point-at-eol)))
12604 (delete-region (point-at-bol)
12605 (min (point-max) (1+ (point-at-eol))))))))))
12607 (defun org-add-planning-info (what &optional time &rest remove)
12608 "Insert new timestamp with keyword in the line directly after the headline.
12609 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12610 If non is given, the user is prompted for a date.
12611 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12612 be removed."
12613 (interactive)
12614 (let (org-time-was-given org-end-time-was-given ts
12615 end default-time default-input)
12617 (catch 'exit
12618 (when (and (memq what '(scheduled deadline))
12619 (or (not time)
12620 (and (stringp time)
12621 (string-match "^[-+]+[0-9]" time))))
12622 ;; Try to get a default date/time from existing timestamp
12623 (save-excursion
12624 (org-back-to-heading t)
12625 (setq end (save-excursion (outline-next-heading) (point)))
12626 (when (re-search-forward (if (eq what 'scheduled)
12627 org-scheduled-time-regexp
12628 org-deadline-time-regexp)
12629 end t)
12630 (setq ts (match-string 1)
12631 default-time
12632 (apply 'encode-time (org-parse-time-string ts))
12633 default-input (and ts (org-get-compact-tod ts))))))
12634 (when what
12635 (setq time
12636 (if (stringp time)
12637 ;; This is a string (relative or absolute), set proper date
12638 (apply 'encode-time
12639 (org-read-date-analyze
12640 time default-time (decode-time default-time)))
12641 ;; If necessary, get the time from the user
12642 (or time (org-read-date nil 'to-time nil nil
12643 default-time default-input)))))
12645 (when (and org-insert-labeled-timestamps-at-point
12646 (member what '(scheduled deadline)))
12647 (insert
12648 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12649 (org-insert-time-stamp time org-time-was-given
12650 nil nil nil (list org-end-time-was-given))
12651 (setq what nil))
12652 (save-excursion
12653 (save-restriction
12654 (let (col list elt ts buffer-invisibility-spec)
12655 (org-back-to-heading t)
12656 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12657 (goto-char (match-end 1))
12658 (setq col (current-column))
12659 (goto-char (match-end 0))
12660 (if (eobp) (insert "\n") (forward-char 1))
12661 (when (and (not what)
12662 (not (looking-at
12663 (concat "[ \t]*"
12664 org-keyword-time-not-clock-regexp))))
12665 ;; Nothing to add, nothing to remove...... :-)
12666 (throw 'exit nil))
12667 (if (and (not (looking-at org-outline-regexp))
12668 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12669 "[^\r\n]*"))
12670 (not (equal (match-string 1) org-clock-string)))
12671 (narrow-to-region (match-beginning 0) (match-end 0))
12672 (insert-before-markers "\n")
12673 (backward-char 1)
12674 (narrow-to-region (point) (point))
12675 (and org-adapt-indentation (org-indent-to-column col)))
12676 ;; Check if we have to remove something.
12677 (setq list (cons what remove))
12678 (while list
12679 (setq elt (pop list))
12680 (when (or (and (eq elt 'scheduled)
12681 (re-search-forward org-scheduled-time-regexp nil t))
12682 (and (eq elt 'deadline)
12683 (re-search-forward org-deadline-time-regexp nil t))
12684 (and (eq elt 'closed)
12685 (re-search-forward org-closed-time-regexp nil t)))
12686 (replace-match "")
12687 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12688 (and (looking-at "[ \t]+") (replace-match ""))
12689 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12690 (when what
12691 (insert
12692 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12693 (cond ((eq what 'scheduled) org-scheduled-string)
12694 ((eq what 'deadline) org-deadline-string)
12695 ((eq what 'closed) org-closed-string))
12696 " ")
12697 (setq ts (org-insert-time-stamp
12698 time
12699 (or org-time-was-given
12700 (and (eq what 'closed) org-log-done-with-time))
12701 (eq what 'closed)
12702 nil nil (list org-end-time-was-given)))
12703 (insert
12704 (if (not (or (bolp) (eq (char-before) ?\ )
12705 (memq (char-after) '(32 10))
12706 (eobp))) " " ""))
12707 (end-of-line 1))
12708 (goto-char (point-min))
12709 (widen)
12710 (if (and (looking-at "[ \t]*\n")
12711 (equal (char-before) ?\n))
12712 (delete-region (1- (point)) (point-at-eol)))
12713 ts))))))
12715 (defvar org-log-note-marker (make-marker))
12716 (defvar org-log-note-purpose nil)
12717 (defvar org-log-note-state nil)
12718 (defvar org-log-note-previous-state nil)
12719 (defvar org-log-note-how nil)
12720 (defvar org-log-note-extra nil)
12721 (defvar org-log-note-window-configuration nil)
12722 (defvar org-log-note-return-to (make-marker))
12723 (defvar org-log-note-effective-time nil
12724 "Remembered current time so that dynamically scoped
12725 `org-extend-today-until' affects tha timestamps in state change
12726 log")
12728 (defvar org-log-post-message nil
12729 "Message to be displayed after a log note has been stored.
12730 The auto-repeater uses this.")
12732 (defun org-add-note ()
12733 "Add a note to the current entry.
12734 This is done in the same way as adding a state change note."
12735 (interactive)
12736 (org-add-log-setup 'note nil nil 'findpos nil))
12738 (defvar org-property-end-re)
12739 (defun org-add-log-setup (&optional purpose state prev-state
12740 findpos how extra)
12741 "Set up the post command hook to take a note.
12742 If this is about to TODO state change, the new state is expected in STATE.
12743 When FINDPOS is non-nil, find the correct position for the note in
12744 the current entry. If not, assume that it can be inserted at point.
12745 HOW is an indicator what kind of note should be created.
12746 EXTRA is additional text that will be inserted into the notes buffer."
12747 (let* ((org-log-into-drawer (org-log-into-drawer))
12748 (drawer (cond ((stringp org-log-into-drawer)
12749 org-log-into-drawer)
12750 (org-log-into-drawer "LOGBOOK"))))
12751 (save-restriction
12752 (save-excursion
12753 (when findpos
12754 (org-back-to-heading t)
12755 (narrow-to-region (point) (save-excursion
12756 (outline-next-heading) (point)))
12757 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12758 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12759 "[^\r\n]*\\)?"))
12760 (goto-char (match-end 0))
12761 (cond
12762 (drawer
12763 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12764 nil t)
12765 (progn
12766 (goto-char (match-end 0))
12767 (or org-log-states-order-reversed
12768 (and (re-search-forward org-property-end-re nil t)
12769 (goto-char (1- (match-beginning 0))))))
12770 (insert "\n:" drawer ":\n:END:")
12771 (beginning-of-line 0)
12772 (org-indent-line)
12773 (beginning-of-line 2)
12774 (org-indent-line)
12775 (end-of-line 0)))
12776 ((and org-log-state-notes-insert-after-drawers
12777 (save-excursion
12778 (forward-line) (looking-at org-drawer-regexp)))
12779 (forward-line)
12780 (while (looking-at org-drawer-regexp)
12781 (goto-char (match-end 0))
12782 (re-search-forward org-property-end-re (point-max) t)
12783 (forward-line))
12784 (forward-line -1)))
12785 (unless org-log-states-order-reversed
12786 (and (= (char-after) ?\n) (forward-char 1))
12787 (org-skip-over-state-notes)
12788 (skip-chars-backward " \t\n\r")))
12789 (move-marker org-log-note-marker (point))
12790 (setq org-log-note-purpose purpose
12791 org-log-note-state state
12792 org-log-note-previous-state prev-state
12793 org-log-note-how how
12794 org-log-note-extra extra
12795 org-log-note-effective-time (org-current-effective-time))
12796 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12798 (defun org-skip-over-state-notes ()
12799 "Skip past the list of State notes in an entry."
12800 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12801 (when (ignore-errors (goto-char (org-in-item-p)))
12802 (let* ((struct (org-list-struct))
12803 (prevs (org-list-prevs-alist struct)))
12804 (while (looking-at "[ \t]*- State")
12805 (goto-char (or (org-list-get-next-item (point) struct prevs)
12806 (org-list-get-item-end (point) struct)))))))
12808 (defun org-add-log-note (&optional purpose)
12809 "Pop up a window for taking a note, and add this note later at point."
12810 (remove-hook 'post-command-hook 'org-add-log-note)
12811 (setq org-log-note-window-configuration (current-window-configuration))
12812 (delete-other-windows)
12813 (move-marker org-log-note-return-to (point))
12814 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12815 (goto-char org-log-note-marker)
12816 (org-switch-to-buffer-other-window "*Org Note*")
12817 (erase-buffer)
12818 (if (memq org-log-note-how '(time state))
12819 (let (current-prefix-arg) (org-store-log-note))
12820 (let ((org-inhibit-startup t)) (org-mode))
12821 (insert (format "# Insert note for %s.
12822 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12823 (cond
12824 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12825 ((eq org-log-note-purpose 'done) "closed todo item")
12826 ((eq org-log-note-purpose 'state)
12827 (format "state change from \"%s\" to \"%s\""
12828 (or org-log-note-previous-state "")
12829 (or org-log-note-state "")))
12830 ((eq org-log-note-purpose 'reschedule)
12831 "rescheduling")
12832 ((eq org-log-note-purpose 'delschedule)
12833 "no longer scheduled")
12834 ((eq org-log-note-purpose 'redeadline)
12835 "changing deadline")
12836 ((eq org-log-note-purpose 'deldeadline)
12837 "removing deadline")
12838 ((eq org-log-note-purpose 'refile)
12839 "refiling")
12840 ((eq org-log-note-purpose 'note)
12841 "this entry")
12842 (t (error "This should not happen")))))
12843 (if org-log-note-extra (insert org-log-note-extra))
12844 (org-set-local 'org-finish-function 'org-store-log-note)
12845 (run-hooks 'org-log-buffer-setup-hook)))
12847 (defvar org-note-abort nil) ; dynamically scoped
12848 (defun org-store-log-note ()
12849 "Finish taking a log note, and insert it to where it belongs."
12850 (let ((txt (buffer-string)))
12851 (kill-buffer (current-buffer))
12852 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12853 lines ind bul)
12854 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12855 (setq txt (replace-match "" t t txt)))
12856 (if (string-match "\\s-+\\'" txt)
12857 (setq txt (replace-match "" t t txt)))
12858 (setq lines (org-split-string txt "\n"))
12859 (when (and note (string-match "\\S-" note))
12860 (setq note
12861 (org-replace-escapes
12862 note
12863 (list (cons "%u" (user-login-name))
12864 (cons "%U" user-full-name)
12865 (cons "%t" (format-time-string
12866 (org-time-stamp-format 'long 'inactive)
12867 org-log-note-effective-time))
12868 (cons "%T" (format-time-string
12869 (org-time-stamp-format 'long nil)
12870 org-log-note-effective-time))
12871 (cons "%d" (format-time-string
12872 (org-time-stamp-format nil 'inactive)
12873 org-log-note-effective-time))
12874 (cons "%D" (format-time-string
12875 (org-time-stamp-format nil nil)
12876 org-log-note-effective-time))
12877 (cons "%s" (if org-log-note-state
12878 (concat "\"" org-log-note-state "\"")
12879 ""))
12880 (cons "%S" (if org-log-note-previous-state
12881 (concat "\"" org-log-note-previous-state "\"")
12882 "\"\"")))))
12883 (if lines (setq note (concat note " \\\\")))
12884 (push note lines))
12885 (when (or current-prefix-arg org-note-abort)
12886 (when org-log-into-drawer
12887 (org-remove-empty-drawer-at
12888 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12889 org-log-note-marker))
12890 (setq lines nil))
12891 (when lines
12892 (with-current-buffer (marker-buffer org-log-note-marker)
12893 (save-excursion
12894 (goto-char org-log-note-marker)
12895 (move-marker org-log-note-marker nil)
12896 (end-of-line 1)
12897 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12898 (setq ind (save-excursion
12899 (if (ignore-errors (goto-char (org-in-item-p)))
12900 (let ((struct (org-list-struct)))
12901 (org-list-get-ind
12902 (org-list-get-top-point struct) struct))
12903 (skip-chars-backward " \r\t\n")
12904 (cond
12905 ((and (org-at-heading-p)
12906 org-adapt-indentation)
12907 (1+ (org-current-level)))
12908 ((org-at-heading-p) 0)
12909 (t (org-get-indentation))))))
12910 (setq bul (org-list-bullet-string "-"))
12911 (org-indent-line-to ind)
12912 (insert bul (pop lines))
12913 (let ((ind-body (+ (length bul) ind)))
12914 (while lines
12915 (insert "\n")
12916 (org-indent-line-to ind-body)
12917 (insert (pop lines))))
12918 (message "Note stored")
12919 (org-back-to-heading t)
12920 (org-cycle-hide-drawers 'children))))))
12921 (set-window-configuration org-log-note-window-configuration)
12922 (with-current-buffer (marker-buffer org-log-note-return-to)
12923 (goto-char org-log-note-return-to))
12924 (move-marker org-log-note-return-to nil)
12925 (and org-log-post-message (message "%s" org-log-post-message)))
12927 (defun org-remove-empty-drawer-at (drawer pos)
12928 "Remove an empty drawer DRAWER at position POS.
12929 POS may also be a marker."
12930 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12931 (save-excursion
12932 (save-restriction
12933 (widen)
12934 (goto-char pos)
12935 (if (org-in-regexp
12936 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12937 (replace-match ""))))))
12939 (defvar org-ts-type nil)
12940 (defun org-sparse-tree (&optional arg type)
12941 "Create a sparse tree, prompt for the details.
12942 This command can create sparse trees. You first need to select the type
12943 of match used to create the tree:
12945 t Show all TODO entries.
12946 T Show entries with a specific TODO keyword.
12947 m Show entries selected by a tags/property match.
12948 p Enter a property name and its value (both with completion on existing
12949 names/values) and show entries with that property.
12950 r Show entries matching a regular expression (`/' can be used as well).
12951 b Show deadlines and scheduled items before a date.
12952 a Show deadlines and scheduled items after a date.
12953 d Show deadlines due within `org-deadline-warning-days'.
12954 D Show deadlines and scheduled items between a date range."
12955 (interactive "P")
12956 (let (ans kwd value ts-type)
12957 (setq type (or type org-sparse-tree-default-date-type))
12958 (setq org-ts-type type)
12959 (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"
12960 (cond ((eq type 'all) "all timestamps")
12961 ((eq type 'scheduled) "only scheduled")
12962 ((eq type 'deadline) "only deadline")
12963 ((eq type 'active) "only active timestamps")
12964 ((eq type 'inactive) "only inactive timestamps")
12965 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12966 (t "scheduled/deadline")))
12967 (setq ans (read-char-exclusive))
12968 (cond
12969 ((equal ans ?c)
12970 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12971 ((equal ans ?d)
12972 (call-interactively 'org-check-deadlines))
12973 ((equal ans ?b)
12974 (call-interactively 'org-check-before-date))
12975 ((equal ans ?a)
12976 (call-interactively 'org-check-after-date))
12977 ((equal ans ?D)
12978 (call-interactively 'org-check-dates-range))
12979 ((equal ans ?t)
12980 (call-interactively 'org-show-todo-tree))
12981 ((equal ans ?T)
12982 (org-show-todo-tree '(4)))
12983 ((member ans '(?T ?m))
12984 (call-interactively 'org-match-sparse-tree))
12985 ((member ans '(?p ?P))
12986 (setq kwd (org-icompleting-read "Property: "
12987 (mapcar 'list (org-buffer-property-keys))))
12988 (setq value (org-icompleting-read "Value: "
12989 (mapcar 'list (org-property-values kwd))))
12990 (unless (string-match "\\`{.*}\\'" value)
12991 (setq value (concat "\"" value "\"")))
12992 (org-match-sparse-tree arg (concat kwd "=" value)))
12993 ((member ans '(?r ?R ?/))
12994 (call-interactively 'org-occur))
12995 (t (error "No such sparse tree command \"%c\"" ans)))))
12997 (defvar org-occur-highlights nil
12998 "List of overlays used for occur matches.")
12999 (make-variable-buffer-local 'org-occur-highlights)
13000 (defvar org-occur-parameters nil
13001 "Parameters of the active org-occur calls.
13002 This is a list, each call to org-occur pushes as cons cell,
13003 containing the regular expression and the callback, onto the list.
13004 The list can contain several entries if `org-occur' has been called
13005 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13006 will only contain one set of parameters. When the highlights are
13007 removed (for example with `C-c C-c', or with the next edit (depending
13008 on `org-remove-highlights-with-change'), this variable is emptied
13009 as well.")
13010 (make-variable-buffer-local 'org-occur-parameters)
13012 (defun org-occur (regexp &optional keep-previous callback)
13013 "Make a compact tree which shows all matches of REGEXP.
13014 The tree will show the lines where the regexp matches, and all higher
13015 headlines above the match. It will also show the heading after the match,
13016 to make sure editing the matching entry is easy.
13017 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13018 call to `org-occur' will be kept, to allow stacking of calls to this
13019 command.
13020 If CALLBACK is non-nil, it is a function which is called to confirm
13021 that the match should indeed be shown."
13022 (interactive "sRegexp: \nP")
13023 (when (equal regexp "")
13024 (error "Regexp cannot be empty"))
13025 (unless keep-previous
13026 (org-remove-occur-highlights nil nil t))
13027 (push (cons regexp callback) org-occur-parameters)
13028 (let ((cnt 0))
13029 (save-excursion
13030 (goto-char (point-min))
13031 (if (or (not keep-previous) ; do not want to keep
13032 (not org-occur-highlights)) ; no previous matches
13033 ;; hide everything
13034 (org-overview))
13035 (while (re-search-forward regexp nil t)
13036 (when (or (not callback)
13037 (save-match-data (funcall callback)))
13038 (setq cnt (1+ cnt))
13039 (when org-highlight-sparse-tree-matches
13040 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13041 (org-show-context 'occur-tree))))
13042 (when org-remove-highlights-with-change
13043 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13044 nil 'local))
13045 (unless org-sparse-tree-open-archived-trees
13046 (org-hide-archived-subtrees (point-min) (point-max)))
13047 (run-hooks 'org-occur-hook)
13048 (if (org-called-interactively-p 'interactive)
13049 (message "%d match(es) for regexp %s" cnt regexp))
13050 cnt))
13052 (defun org-occur-next-match (&optional n reset)
13053 "Function for `next-error-function' to find sparse tree matches.
13054 N is the number of matches to move, when negative move backwards.
13055 RESET is entirely ignored - this function always goes back to the
13056 starting point when no match is found."
13057 (let* ((limit (if (< n 0) (point-min) (point-max)))
13058 (search-func (if (< n 0)
13059 'previous-single-char-property-change
13060 'next-single-char-property-change))
13061 (n (abs n))
13062 (pos (point))
13064 (catch 'exit
13065 (while (setq p1 (funcall search-func (point) 'org-type))
13066 (when (equal p1 limit)
13067 (goto-char pos)
13068 (error "No more matches"))
13069 (when (equal (get-char-property p1 'org-type) 'org-occur)
13070 (setq n (1- n))
13071 (when (= n 0)
13072 (goto-char p1)
13073 (throw 'exit (point))))
13074 (goto-char p1))
13075 (goto-char p1)
13076 (error "No more matches"))))
13078 (defun org-show-context (&optional key)
13079 "Make sure point and context are visible.
13080 How much context is shown depends upon the variables
13081 `org-show-hierarchy-above', `org-show-following-heading',
13082 `org-show-entry-below' and `org-show-siblings'."
13083 (let ((heading-p (org-at-heading-p t))
13084 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13085 (following-p (org-get-alist-option org-show-following-heading key))
13086 (entry-p (org-get-alist-option org-show-entry-below key))
13087 (siblings-p (org-get-alist-option org-show-siblings key)))
13088 (catch 'exit
13089 ;; Show heading or entry text
13090 (if (and heading-p (not entry-p))
13091 (org-flag-heading nil) ; only show the heading
13092 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13093 (org-show-hidden-entry))) ; show entire entry
13094 (when following-p
13095 ;; Show next sibling, or heading below text
13096 (save-excursion
13097 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13098 (org-flag-heading nil))))
13099 (when siblings-p (org-show-siblings))
13100 (when hierarchy-p
13101 ;; show all higher headings, possibly with siblings
13102 (save-excursion
13103 (while (and (condition-case nil
13104 (progn (org-up-heading-all 1) t)
13105 (error nil))
13106 (not (bobp)))
13107 (org-flag-heading nil)
13108 (when siblings-p (org-show-siblings))))))))
13110 (defvar org-reveal-start-hook nil
13111 "Hook run before revealing a location.")
13113 (defun org-reveal (&optional siblings)
13114 "Show current entry, hierarchy above it, and the following headline.
13115 This can be used to show a consistent set of context around locations
13116 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13117 not t for the search context.
13119 With optional argument SIBLINGS, on each level of the hierarchy all
13120 siblings are shown. This repairs the tree structure to what it would
13121 look like when opened with hierarchical calls to `org-cycle'.
13122 With double optional argument \\[universal-argument] \\[universal-argument], \
13123 go to the parent and show the
13124 entire tree."
13125 (interactive "P")
13126 (run-hooks 'org-reveal-start-hook)
13127 (let ((org-show-hierarchy-above t)
13128 (org-show-following-heading t)
13129 (org-show-siblings (if siblings t org-show-siblings)))
13130 (org-show-context nil))
13131 (when (equal siblings '(16))
13132 (save-excursion
13133 (when (org-up-heading-safe)
13134 (org-show-subtree)
13135 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13137 (defun org-highlight-new-match (beg end)
13138 "Highlight from BEG to END and mark the highlight is an occur headline."
13139 (let ((ov (make-overlay beg end)))
13140 (overlay-put ov 'face 'secondary-selection)
13141 (overlay-put ov 'org-type 'org-occur)
13142 (push ov org-occur-highlights)))
13144 (defun org-remove-occur-highlights (&optional beg end noremove)
13145 "Remove the occur highlights from the buffer.
13146 BEG and END are ignored. If NOREMOVE is nil, remove this function
13147 from the `before-change-functions' in the current buffer."
13148 (interactive)
13149 (unless org-inhibit-highlight-removal
13150 (mapc 'delete-overlay org-occur-highlights)
13151 (setq org-occur-highlights nil)
13152 (setq org-occur-parameters nil)
13153 (unless noremove
13154 (remove-hook 'before-change-functions
13155 'org-remove-occur-highlights 'local))))
13157 ;;;; Priorities
13159 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13160 "Regular expression matching the priority indicator.")
13162 (defvar org-remove-priority-next-time nil)
13164 (defun org-priority-up ()
13165 "Increase the priority of the current item."
13166 (interactive)
13167 (org-priority 'up))
13169 (defun org-priority-down ()
13170 "Decrease the priority of the current item."
13171 (interactive)
13172 (org-priority 'down))
13174 (defun org-priority (&optional action show)
13175 "Change the priority of an item.
13176 ACTION can be `set', `up', `down', or a character."
13177 (interactive "P")
13178 (if (equal action '(4))
13179 (org-show-priority)
13180 (unless org-enable-priority-commands
13181 (error "Priority commands are disabled"))
13182 (setq action (or action 'set))
13183 (let (current new news have remove)
13184 (save-excursion
13185 (org-back-to-heading t)
13186 (if (looking-at org-priority-regexp)
13187 (setq current (string-to-char (match-string 2))
13188 have t))
13189 (cond
13190 ((eq action 'remove)
13191 (setq remove t new ?\ ))
13192 ((or (eq action 'set)
13193 (if (featurep 'xemacs) (characterp action) (integerp action)))
13194 (if (not (eq action 'set))
13195 (setq new action)
13196 (message "Priority %c-%c, SPC to remove: "
13197 org-highest-priority org-lowest-priority)
13198 (save-match-data
13199 (setq new (read-char-exclusive))))
13200 (if (and (= (upcase org-highest-priority) org-highest-priority)
13201 (= (upcase org-lowest-priority) org-lowest-priority))
13202 (setq new (upcase new)))
13203 (cond ((equal new ?\ ) (setq remove t))
13204 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13205 (error "Priority must be between `%c' and `%c'"
13206 org-highest-priority org-lowest-priority))))
13207 ((eq action 'up)
13208 (setq new (if have
13209 (1- current) ; normal cycling
13210 ;; last priority was empty
13211 (if (eq last-command this-command)
13212 org-lowest-priority ; wrap around empty to lowest
13213 ;; default
13214 (if org-priority-start-cycle-with-default
13215 org-default-priority
13216 (1- org-default-priority))))))
13217 ((eq action 'down)
13218 (setq new (if have
13219 (1+ current) ; normal cycling
13220 ;; last priority was empty
13221 (if (eq last-command this-command)
13222 org-highest-priority ; wrap around empty to highest
13223 ;; default
13224 (if org-priority-start-cycle-with-default
13225 org-default-priority
13226 (1+ org-default-priority))))))
13227 (t (error "Invalid action")))
13228 (if (or (< (upcase new) org-highest-priority)
13229 (> (upcase new) org-lowest-priority))
13230 (if (and (memq action '(up down))
13231 (not have) (not (eq last-command this-command)))
13232 ;; `new' is from default priority
13233 (error
13234 "The default can not be set, see `org-default-priority' why")
13235 ;; normal cycling: `new' is beyond highest/lowest priority
13236 ;; and is wrapped around to the empty priority
13237 (setq remove t)))
13238 (setq news (format "%c" new))
13239 (if have
13240 (if remove
13241 (replace-match "" t t nil 1)
13242 (replace-match news t t nil 2))
13243 (if remove
13244 (error "No priority cookie found in line")
13245 (let ((case-fold-search nil))
13246 (looking-at org-todo-line-regexp))
13247 (if (match-end 2)
13248 (progn
13249 (goto-char (match-end 2))
13250 (insert " [#" news "]"))
13251 (goto-char (match-beginning 3))
13252 (insert "[#" news "] "))))
13253 (org-preserve-lc (org-set-tags nil 'align)))
13254 (if remove
13255 (message "Priority removed")
13256 (message "Priority of current item set to %s" news)))))
13258 (defun org-show-priority ()
13259 "Show the priority of the current item.
13260 This priority is composed of the main priority given with the [#A] cookies,
13261 and by additional input from the age of a schedules or deadline entry."
13262 (interactive)
13263 (let ((pri (if (eq major-mode 'org-agenda-mode)
13264 (org-get-at-bol 'priority)
13265 (save-excursion
13266 (save-match-data
13267 (beginning-of-line)
13268 (and (looking-at org-heading-regexp)
13269 (org-get-priority (match-string 0))))))))
13270 (message "Priority is %d" (if pri pri -1000))))
13272 (defun org-get-priority (s)
13273 "Find priority cookie and return priority."
13274 (save-match-data
13275 (if (functionp org-get-priority-function)
13276 (funcall org-get-priority-function)
13277 (if (not (string-match org-priority-regexp s))
13278 (* 1000 (- org-lowest-priority org-default-priority))
13279 (* 1000 (- org-lowest-priority
13280 (string-to-char (match-string 2 s))))))))
13282 ;;;; Tags
13284 (defvar org-agenda-archives-mode)
13285 (defvar org-map-continue-from nil
13286 "Position from where mapping should continue.
13287 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13289 (defvar org-scanner-tags nil
13290 "The current tag list while the tags scanner is running.")
13291 (defvar org-trust-scanner-tags nil
13292 "Should `org-get-tags-at' use the tags for the scanner.
13293 This is for internal dynamical scoping only.
13294 When this is non-nil, the function `org-get-tags-at' will return the value
13295 of `org-scanner-tags' instead of building the list by itself. This
13296 can lead to large speed-ups when the tags scanner is used in a file with
13297 many entries, and when the list of tags is retrieved, for example to
13298 obtain a list of properties. Building the tags list for each entry in such
13299 a file becomes an N^2 operation - but with this variable set, it scales
13300 as N.")
13302 (defun org-scan-tags (action matcher todo-only &optional start-level)
13303 "Scan headline tags with inheritance and produce output ACTION.
13305 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13306 or `agenda' to produce an entry list for an agenda view. It can also be
13307 a Lisp form or a function that should be called at each matched headline, in
13308 this case the return value is a list of all return values from these calls.
13310 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13311 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13312 only lines with a not-done TODO keyword are included in the output.
13313 This should be the same variable that was scoped into
13314 and set by `org-make-tags-matcher' when it constructed MATCHER.
13316 START-LEVEL can be a string with asterisks, reducing the scope to
13317 headlines matching this string."
13318 (require 'org-agenda)
13319 (let* ((re (concat "^"
13320 (if start-level
13321 ;; Get the correct level to match
13322 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13323 org-outline-regexp)
13324 " *\\(\\<\\("
13325 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13326 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13327 (props (list 'face 'default
13328 'done-face 'org-agenda-done
13329 'undone-face 'default
13330 'mouse-face 'highlight
13331 'org-not-done-regexp org-not-done-regexp
13332 'org-todo-regexp org-todo-regexp
13333 'org-complex-heading-regexp org-complex-heading-regexp
13334 'help-echo
13335 (format "mouse-2 or RET jump to org file %s"
13336 (abbreviate-file-name
13337 (or (buffer-file-name (buffer-base-buffer))
13338 (buffer-name (buffer-base-buffer)))))))
13339 (case-fold-search nil)
13340 (org-map-continue-from nil)
13341 lspos tags tags-list
13342 (tags-alist (list (cons 0 org-file-tags)))
13343 (llast 0) rtn rtn1 level category i txt
13344 todo marker entry priority)
13345 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13346 (setq action (list 'lambda nil action)))
13347 (save-excursion
13348 (goto-char (point-min))
13349 (when (eq action 'sparse-tree)
13350 (org-overview)
13351 (org-remove-occur-highlights))
13352 (while (re-search-forward re nil t)
13353 (setq org-map-continue-from nil)
13354 (catch :skip
13355 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13356 tags (if (match-end 4) (org-match-string-no-properties 4)))
13357 (goto-char (setq lspos (match-beginning 0)))
13358 (setq level (org-reduced-level (org-outline-level))
13359 category (org-get-category))
13360 (setq i llast llast level)
13361 ;; remove tag lists from same and sublevels
13362 (while (>= i level)
13363 (when (setq entry (assoc i tags-alist))
13364 (setq tags-alist (delete entry tags-alist)))
13365 (setq i (1- i)))
13366 ;; add the next tags
13367 (when tags
13368 (setq tags (org-split-string tags ":")
13369 tags-alist
13370 (cons (cons level tags) tags-alist)))
13371 ;; compile tags for current headline
13372 (setq tags-list
13373 (if org-use-tag-inheritance
13374 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13375 tags)
13376 org-scanner-tags tags-list)
13377 (when org-use-tag-inheritance
13378 (setcdr (car tags-alist)
13379 (mapcar (lambda (x)
13380 (setq x (copy-sequence x))
13381 (org-add-prop-inherited x))
13382 (cdar tags-alist))))
13383 (when (and tags org-use-tag-inheritance
13384 (or (not (eq t org-use-tag-inheritance))
13385 org-tags-exclude-from-inheritance))
13386 ;; selective inheritance, remove uninherited ones
13387 (setcdr (car tags-alist)
13388 (org-remove-uninherited-tags (cdar tags-alist))))
13389 (when (and
13391 ;; eval matcher only when the todo condition is OK
13392 (and (or (not todo-only) (member todo org-not-done-keywords))
13393 (let ((case-fold-search t) (org-trust-scanner-tags t))
13394 (eval matcher)))
13396 ;; Call the skipper, but return t if it does not skip,
13397 ;; so that the `and' form continues evaluating
13398 (progn
13399 (unless (eq action 'sparse-tree) (org-agenda-skip))
13402 ;; Check if timestamps are deselecting this entry
13403 (or (not todo-only)
13404 (and (member todo org-not-done-keywords)
13405 (or (not org-agenda-tags-todo-honor-ignore-options)
13406 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13408 ;; select this headline
13409 (cond
13410 ((eq action 'sparse-tree)
13411 (and org-highlight-sparse-tree-matches
13412 (org-get-heading) (match-end 0)
13413 (org-highlight-new-match
13414 (match-beginning 1) (match-end 1)))
13415 (org-show-context 'tags-tree))
13416 ((eq action 'agenda)
13417 (setq txt (org-agenda-format-item
13419 (concat
13420 (if (eq org-tags-match-list-sublevels 'indented)
13421 (make-string (1- level) ?.) "")
13422 (org-get-heading))
13423 level category
13424 tags-list)
13425 priority (org-get-priority txt))
13426 (goto-char lspos)
13427 (setq marker (org-agenda-new-marker))
13428 (org-add-props txt props
13429 'org-marker marker 'org-hd-marker marker 'org-category category
13430 'todo-state todo
13431 'priority priority 'type "tagsmatch")
13432 (push txt rtn))
13433 ((functionp action)
13434 (setq org-map-continue-from nil)
13435 (save-excursion
13436 (setq rtn1 (funcall action))
13437 (push rtn1 rtn)))
13438 (t (error "Invalid action")))
13440 ;; if we are to skip sublevels, jump to end of subtree
13441 (unless org-tags-match-list-sublevels
13442 (org-end-of-subtree t)
13443 (backward-char 1))))
13444 ;; Get the correct position from where to continue
13445 (if org-map-continue-from
13446 (goto-char org-map-continue-from)
13447 (and (= (point) lspos) (end-of-line 1)))))
13448 (when (and (eq action 'sparse-tree)
13449 (not org-sparse-tree-open-archived-trees))
13450 (org-hide-archived-subtrees (point-min) (point-max)))
13451 (nreverse rtn)))
13453 (defun org-remove-uninherited-tags (tags)
13454 "Remove all tags that are not inherited from the list TAGS."
13455 (cond
13456 ((eq org-use-tag-inheritance t)
13457 (if org-tags-exclude-from-inheritance
13458 (org-delete-all org-tags-exclude-from-inheritance tags)
13459 tags))
13460 ((not org-use-tag-inheritance) nil)
13461 ((stringp org-use-tag-inheritance)
13462 (delq nil (mapcar
13463 (lambda (x)
13464 (if (and (string-match org-use-tag-inheritance x)
13465 (not (member x org-tags-exclude-from-inheritance)))
13466 x nil))
13467 tags)))
13468 ((listp org-use-tag-inheritance)
13469 (delq nil (mapcar
13470 (lambda (x)
13471 (if (member x org-use-tag-inheritance) x nil))
13472 tags)))))
13474 (defun org-match-sparse-tree (&optional todo-only match)
13475 "Create a sparse tree according to tags string MATCH.
13476 MATCH can contain positive and negative selection of tags, like
13477 \"+WORK+URGENT-WITHBOSS\".
13478 If optional argument TODO-ONLY is non-nil, only select lines that are
13479 also TODO lines."
13480 (interactive "P")
13481 (org-agenda-prepare-buffers (list (current-buffer)))
13482 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13484 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13486 (defvar org-cached-props nil)
13487 (defun org-cached-entry-get (pom property)
13488 (if (or (eq t org-use-property-inheritance)
13489 (and (stringp org-use-property-inheritance)
13490 (string-match org-use-property-inheritance property))
13491 (and (listp org-use-property-inheritance)
13492 (member property org-use-property-inheritance)))
13493 ;; Caching is not possible, check it directly
13494 (org-entry-get pom property 'inherit)
13495 ;; Get all properties, so that we can do complicated checks easily
13496 (cdr (assoc property (or org-cached-props
13497 (setq org-cached-props
13498 (org-entry-properties pom)))))))
13500 (defun org-global-tags-completion-table (&optional files)
13501 "Return the list of all tags in all agenda buffer/files.
13502 Optional FILES argument is a list of files which can be used
13503 instead of the agenda files."
13504 (save-excursion
13505 (org-uniquify
13506 (delq nil
13507 (apply 'append
13508 (mapcar
13509 (lambda (file)
13510 (set-buffer (find-file-noselect file))
13511 (append (org-get-buffer-tags)
13512 (mapcar (lambda (x) (if (stringp (car-safe x))
13513 (list (car-safe x)) nil))
13514 org-tag-alist)))
13515 (if (and files (car files))
13516 files
13517 (org-agenda-files))))))))
13519 (defun org-make-tags-matcher (match)
13520 "Create the TAGS/TODO matcher form for the selection string MATCH.
13522 The variable `todo-only' is scoped dynamically into this function.
13523 It will be set to t if the matcher restricts matching to TODO entries,
13524 otherwise will not be touched.
13526 Returns a cons of the selection string MATCH and the constructed
13527 lisp form implementing the matcher. The matcher is to be evaluated
13528 at an Org entry, with point on the headline, and returns t if the
13529 entry matches the selection string MATCH. The returned lisp form
13530 references two variables with information about the entry, which
13531 must be bound around the form's evaluation: todo, the TODO keyword
13532 at the entry (or nil of none); and tags-list, the list of all tags
13533 at the entry including inherited ones. Additionally, the category
13534 of the entry (if any) must be specified as the text property
13535 'org-category on the headline.
13537 See also `org-scan-tags'.
13539 (declare (special todo-only))
13540 (unless (boundp 'todo-only)
13541 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13542 (unless match
13543 ;; Get a new match request, with completion
13544 (let ((org-last-tags-completion-table
13545 (org-global-tags-completion-table)))
13546 (setq match (org-completing-read-no-i
13547 "Match: " 'org-tags-completion-function nil nil nil
13548 'org-tags-history))))
13550 ;; Parse the string and create a lisp form
13551 (let ((match0 match)
13552 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13553 minus tag mm
13554 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13555 orterms term orlist re-p str-p level-p level-op time-p
13556 prop-p pn pv po gv rest)
13557 (if (string-match "/+" match)
13558 ;; match contains also a todo-matching request
13559 (progn
13560 (setq tagsmatch (substring match 0 (match-beginning 0))
13561 todomatch (substring match (match-end 0)))
13562 (if (string-match "^!" todomatch)
13563 (setq todo-only t todomatch (substring todomatch 1)))
13564 (if (string-match "^\\s-*$" todomatch)
13565 (setq todomatch nil)))
13566 ;; only matching tags
13567 (setq tagsmatch match todomatch nil))
13569 ;; Make the tags matcher
13570 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13571 (setq tagsmatcher t)
13572 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13573 (while (setq term (pop orterms))
13574 (while (and (equal (substring term -1) "\\") orterms)
13575 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13576 (while (string-match re term)
13577 (setq rest (substring term (match-end 0))
13578 minus (and (match-end 1)
13579 (equal (match-string 1 term) "-"))
13580 tag (save-match-data (replace-regexp-in-string
13581 "\\\\-" "-"
13582 (match-string 2 term)))
13583 re-p (equal (string-to-char tag) ?{)
13584 level-p (match-end 4)
13585 prop-p (match-end 5)
13586 mm (cond
13587 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13588 (level-p
13589 (setq level-op (org-op-to-function (match-string 3 term)))
13590 `(,level-op level ,(string-to-number
13591 (match-string 4 term))))
13592 (prop-p
13593 (setq pn (match-string 5 term)
13594 po (match-string 6 term)
13595 pv (match-string 7 term)
13596 re-p (equal (string-to-char pv) ?{)
13597 str-p (equal (string-to-char pv) ?\")
13598 time-p (save-match-data
13599 (string-match "^\"[[<].*[]>]\"$" pv))
13600 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13601 (if time-p (setq pv (org-matcher-time pv)))
13602 (setq po (org-op-to-function po (if time-p 'time str-p)))
13603 (cond
13604 ((equal pn "CATEGORY")
13605 (setq gv '(get-text-property (point) 'org-category)))
13606 ((equal pn "TODO")
13607 (setq gv 'todo))
13609 (setq gv `(org-cached-entry-get nil ,pn))))
13610 (if re-p
13611 (if (eq po 'org<>)
13612 `(not (string-match ,pv (or ,gv "")))
13613 `(string-match ,pv (or ,gv "")))
13614 (if str-p
13615 `(,po (or ,gv "") ,pv)
13616 `(,po (string-to-number (or ,gv ""))
13617 ,(string-to-number pv) ))))
13618 (t `(member ,tag tags-list)))
13619 mm (if minus (list 'not mm) mm)
13620 term rest)
13621 (push mm tagsmatcher))
13622 (push (if (> (length tagsmatcher) 1)
13623 (cons 'and tagsmatcher)
13624 (car tagsmatcher))
13625 orlist)
13626 (setq tagsmatcher nil))
13627 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13628 (setq tagsmatcher
13629 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13630 ;; Make the todo matcher
13631 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13632 (setq todomatcher t)
13633 (setq orterms (org-split-string todomatch "|") orlist nil)
13634 (while (setq term (pop orterms))
13635 (while (string-match re term)
13636 (setq minus (and (match-end 1)
13637 (equal (match-string 1 term) "-"))
13638 kwd (match-string 2 term)
13639 re-p (equal (string-to-char kwd) ?{)
13640 term (substring term (match-end 0))
13641 mm (if re-p
13642 `(string-match ,(substring kwd 1 -1) todo)
13643 (list 'equal 'todo kwd))
13644 mm (if minus (list 'not mm) mm))
13645 (push mm todomatcher))
13646 (push (if (> (length todomatcher) 1)
13647 (cons 'and todomatcher)
13648 (car todomatcher))
13649 orlist)
13650 (setq todomatcher nil))
13651 (setq todomatcher (if (> (length orlist) 1)
13652 (cons 'or orlist) (car orlist))))
13654 ;; Return the string and lisp forms of the matcher
13655 (setq matcher (if todomatcher
13656 (list 'and tagsmatcher todomatcher)
13657 tagsmatcher))
13658 (when todo-only
13659 (setq matcher (list 'and '(member todo org-not-done-keywords)
13660 matcher)))
13661 (cons match0 matcher)))
13663 (defun org-op-to-function (op &optional stringp)
13664 "Turn an operator into the appropriate function."
13665 (setq op
13666 (cond
13667 ((equal op "<" ) '(< string< org-time<))
13668 ((equal op ">" ) '(> org-string> org-time>))
13669 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13670 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13671 ((member op '("=" "==")) '(= string= org-time=))
13672 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13673 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13675 (defun org<> (a b) (not (= a b)))
13676 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13677 (defun org-string>= (a b) (not (string< a b)))
13678 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13679 (defun org-string<> (a b) (not (string= a b)))
13680 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13681 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13682 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13683 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13684 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13685 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13686 (defun org-2ft (s)
13687 "Convert S to a floating point time.
13688 If S is already a number, just return it. If it is a string, parse
13689 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13690 (cond
13691 ((numberp s) s)
13692 ((stringp s)
13693 (condition-case nil
13694 (float-time (apply 'encode-time (org-parse-time-string s)))
13695 (error 0.)))
13696 (t 0.)))
13698 (defun org-time-today ()
13699 "Time in seconds today at 0:00.
13700 Returns the float number of seconds since the beginning of the
13701 epoch to the beginning of today (00:00)."
13702 (float-time (apply 'encode-time
13703 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13705 (defun org-matcher-time (s)
13706 "Interpret a time comparison value."
13707 (save-match-data
13708 (cond
13709 ((string= s "<now>") (float-time))
13710 ((string= s "<today>") (org-time-today))
13711 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13712 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13713 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13714 (+ (org-time-today)
13715 (* (string-to-number (match-string 1 s))
13716 (cdr (assoc (match-string 2 s)
13717 '(("d" . 86400.0) ("w" . 604800.0)
13718 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13719 (t (org-2ft s)))))
13721 (defun org-match-any-p (re list)
13722 "Does re match any element of list?"
13723 (setq list (mapcar (lambda (x) (string-match re x)) list))
13724 (delq nil list))
13726 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13727 (defvar org-tags-overlay (make-overlay 1 1))
13728 (org-detach-overlay org-tags-overlay)
13730 (defun org-get-local-tags-at (&optional pos)
13731 "Get a list of tags defined in the current headline."
13732 (org-get-tags-at pos 'local))
13734 (defun org-get-local-tags ()
13735 "Get a list of tags defined in the current headline."
13736 (org-get-tags-at nil 'local))
13738 (defun org-get-tags-at (&optional pos local)
13739 "Get a list of all headline tags applicable at POS.
13740 POS defaults to point. If tags are inherited, the list contains
13741 the targets in the same sequence as the headlines appear, i.e.
13742 the tags of the current headline come last.
13743 When LOCAL is non-nil, only return tags from the current headline,
13744 ignore inherited ones."
13745 (interactive)
13746 (if (and org-trust-scanner-tags
13747 (or (not pos) (equal pos (point)))
13748 (not local))
13749 org-scanner-tags
13750 (let (tags ltags lastpos parent)
13751 (save-excursion
13752 (save-restriction
13753 (widen)
13754 (goto-char (or pos (point)))
13755 (save-match-data
13756 (catch 'done
13757 (condition-case nil
13758 (progn
13759 (org-back-to-heading t)
13760 (while (not (equal lastpos (point)))
13761 (setq lastpos (point))
13762 (when (looking-at
13763 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13764 (setq ltags (org-split-string
13765 (org-match-string-no-properties 1) ":"))
13766 (when parent
13767 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13768 (setq tags (append
13769 (if parent
13770 (org-remove-uninherited-tags ltags)
13771 ltags)
13772 tags)))
13773 (or org-use-tag-inheritance (throw 'done t))
13774 (if local (throw 'done t))
13775 (or (org-up-heading-safe) (error nil))
13776 (setq parent t)))
13777 (error nil)))))
13778 (if local
13779 tags
13780 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13782 (defun org-add-prop-inherited (s)
13783 (add-text-properties 0 (length s) '(inherited t) s)
13786 (defun org-toggle-tag (tag &optional onoff)
13787 "Toggle the tag TAG for the current line.
13788 If ONOFF is `on' or `off', don't toggle but set to this state."
13789 (let (res current)
13790 (save-excursion
13791 (org-back-to-heading t)
13792 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13793 (point-at-eol) t)
13794 (progn
13795 (setq current (match-string 1))
13796 (replace-match ""))
13797 (setq current ""))
13798 (setq current (nreverse (org-split-string current ":")))
13799 (cond
13800 ((eq onoff 'on)
13801 (setq res t)
13802 (or (member tag current) (push tag current)))
13803 ((eq onoff 'off)
13804 (or (not (member tag current)) (setq current (delete tag current))))
13805 (t (if (member tag current)
13806 (setq current (delete tag current))
13807 (setq res t)
13808 (push tag current))))
13809 (end-of-line 1)
13810 (if current
13811 (progn
13812 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13813 (org-set-tags nil t))
13814 (delete-horizontal-space))
13815 (run-hooks 'org-after-tags-change-hook))
13816 res))
13818 (defun org-align-tags-here (to-col)
13819 ;; Assumes that this is a headline
13820 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13821 (beginning-of-line 1)
13822 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13823 (< pos (match-beginning 2)))
13824 (progn
13825 (setq tags-l (- (match-end 2) (match-beginning 2)))
13826 (goto-char (match-beginning 1))
13827 (insert " ")
13828 (delete-region (point) (1+ (match-beginning 2)))
13829 (setq ncol (max (current-column)
13830 (1+ col)
13831 (if (> to-col 0)
13832 to-col
13833 (- (abs to-col) tags-l))))
13834 (setq p (point))
13835 (insert (make-string (- ncol (current-column)) ?\ ))
13836 (setq ncol (current-column))
13837 (when indent-tabs-mode (tabify p (point-at-eol)))
13838 (org-move-to-column (min ncol col) t))
13839 (goto-char pos))))
13841 (defun org-set-tags-command (&optional arg just-align)
13842 "Call the set-tags command for the current entry."
13843 (interactive "P")
13844 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13845 (org-set-tags arg just-align)
13846 (save-excursion
13847 (org-back-to-heading t)
13848 (org-set-tags arg just-align))))
13850 (defun org-set-tags-to (data)
13851 "Set the tags of the current entry to DATA, replacing the current tags.
13852 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13853 If DATA is nil or the empty string, any tags will be removed."
13854 (interactive "sTags: ")
13855 (setq data
13856 (cond
13857 ((eq data nil) "")
13858 ((equal data "") "")
13859 ((stringp data)
13860 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13861 ":"))
13862 ((listp data)
13863 (concat ":" (mapconcat 'identity data ":") ":"))))
13864 (when data
13865 (save-excursion
13866 (org-back-to-heading t)
13867 (when (looking-at org-complex-heading-regexp)
13868 (if (match-end 5)
13869 (progn
13870 (goto-char (match-beginning 5))
13871 (insert data)
13872 (delete-region (point) (point-at-eol))
13873 (org-set-tags nil 'align))
13874 (goto-char (point-at-eol))
13875 (insert " " data)
13876 (org-set-tags nil 'align)))
13877 (beginning-of-line 1)
13878 (if (looking-at ".*?\\([ \t]+\\)$")
13879 (delete-region (match-beginning 1) (match-end 1))))))
13881 (defun org-align-all-tags ()
13882 "Align the tags i all headings."
13883 (interactive)
13884 (save-excursion
13885 (or (ignore-errors (org-back-to-heading t))
13886 (outline-next-heading))
13887 (if (org-at-heading-p)
13888 (org-set-tags t)
13889 (message "No headings"))))
13891 (defvar org-indent-indentation-per-level)
13892 (defun org-set-tags (&optional arg just-align)
13893 "Set the tags for the current headline.
13894 With prefix ARG, realign all tags in headings in the current buffer."
13895 (interactive "P")
13896 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13897 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13898 'region-start-level 'region))
13899 org-loop-over-headlines-in-active-region)
13900 (org-map-entries
13901 ;; We don't use ARG and JUST-ALIGN here these args are not
13902 ;; useful when looping over headlines
13903 `(org-set-tags)
13904 org-loop-over-headlines-in-active-region
13905 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13906 (let* ((re org-outline-regexp-bol)
13907 (current (unless arg (org-get-tags-string)))
13908 (col (current-column))
13909 (org-setting-tags t)
13910 table current-tags inherited-tags ; computed below when needed
13911 tags p0 c0 c1 rpl di tc level)
13912 (if arg
13913 (save-excursion
13914 (goto-char (point-min))
13915 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13916 (while (re-search-forward re nil t)
13917 (org-set-tags nil t)
13918 (end-of-line 1)))
13919 (message "All tags realigned to column %d" org-tags-column))
13920 (if just-align
13921 (setq tags current)
13922 ;; Get a new set of tags from the user
13923 (save-excursion
13924 (setq table (append org-tag-persistent-alist
13925 (or org-tag-alist (org-get-buffer-tags))
13926 (and
13927 org-complete-tags-always-offer-all-agenda-tags
13928 (org-global-tags-completion-table
13929 (org-agenda-files))))
13930 org-last-tags-completion-table table
13931 current-tags (org-split-string current ":")
13932 inherited-tags (nreverse
13933 (nthcdr (length current-tags)
13934 (nreverse (org-get-tags-at))))
13935 tags
13936 (if (or (eq t org-use-fast-tag-selection)
13937 (and org-use-fast-tag-selection
13938 (delq nil (mapcar 'cdr table))))
13939 (org-fast-tag-selection
13940 current-tags inherited-tags table
13941 (if org-fast-tag-selection-include-todo
13942 org-todo-key-alist))
13943 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13944 (org-trim
13945 (org-icompleting-read "Tags: "
13946 'org-tags-completion-function
13947 nil nil current 'org-tags-history))))))
13948 (while (string-match "[-+&]+" tags)
13949 ;; No boolean logic, just a list
13950 (setq tags (replace-match ":" t t tags))))
13952 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13954 (if org-tags-sort-function
13955 (setq tags (mapconcat 'identity
13956 (sort (org-split-string
13957 tags (org-re "[^[:alnum:]_@#%]+"))
13958 org-tags-sort-function) ":")))
13960 (if (string-match "\\`[\t ]*\\'" tags)
13961 (setq tags "")
13962 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13963 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13965 ;; Insert new tags at the correct column
13966 (beginning-of-line 1)
13967 (setq level (or (and (looking-at org-outline-regexp)
13968 (- (match-end 0) (point) 1))
13970 (cond
13971 ((and (equal current "") (equal tags "")))
13972 ((re-search-forward
13973 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13974 (point-at-eol) t)
13975 (if (equal tags "")
13976 (setq rpl "")
13977 (goto-char (match-beginning 0))
13978 (setq c0 (current-column)
13979 ;; compute offset for the case of org-indent-mode active
13980 di (if org-indent-mode
13981 (* (1- org-indent-indentation-per-level) (1- level))
13983 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13984 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13985 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13986 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13987 (replace-match rpl t t)
13988 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13989 tags)
13990 (t (error "Tags alignment failed")))
13991 (org-move-to-column col)
13992 (unless just-align
13993 (run-hooks 'org-after-tags-change-hook))))))
13995 (defun org-change-tag-in-region (beg end tag off)
13996 "Add or remove TAG for each entry in the region.
13997 This works in the agenda, and also in an org-mode buffer."
13998 (interactive
13999 (list (region-beginning) (region-end)
14000 (let ((org-last-tags-completion-table
14001 (if (derived-mode-p 'org-mode)
14002 (org-get-buffer-tags)
14003 (org-global-tags-completion-table))))
14004 (org-icompleting-read
14005 "Tag: " 'org-tags-completion-function nil nil nil
14006 'org-tags-history))
14007 (progn
14008 (message "[s]et or [r]emove? ")
14009 (equal (read-char-exclusive) ?r))))
14010 (if (fboundp 'deactivate-mark) (deactivate-mark))
14011 (let ((agendap (equal major-mode 'org-agenda-mode))
14012 l1 l2 m buf pos newhead (cnt 0))
14013 (goto-char end)
14014 (setq l2 (1- (org-current-line)))
14015 (goto-char beg)
14016 (setq l1 (org-current-line))
14017 (loop for l from l1 to l2 do
14018 (org-goto-line l)
14019 (setq m (get-text-property (point) 'org-hd-marker))
14020 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14021 (and agendap m))
14022 (setq buf (if agendap (marker-buffer m) (current-buffer))
14023 pos (if agendap m (point)))
14024 (with-current-buffer buf
14025 (save-excursion
14026 (save-restriction
14027 (goto-char pos)
14028 (setq cnt (1+ cnt))
14029 (org-toggle-tag tag (if off 'off 'on))
14030 (setq newhead (org-get-heading)))))
14031 (and agendap (org-agenda-change-all-lines newhead m))))
14032 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14034 (defun org-tags-completion-function (string predicate &optional flag)
14035 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14036 (confirm (lambda (x) (stringp (car x)))))
14037 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14038 (setq s1 (match-string 1 string)
14039 s2 (match-string 2 string))
14040 (setq s1 "" s2 string))
14041 (cond
14042 ((eq flag nil)
14043 ;; try completion
14044 (setq rtn (try-completion s2 ctable confirm))
14045 (if (stringp rtn)
14046 (setq rtn
14047 (concat s1 s2 (substring rtn (length s2))
14048 (if (and org-add-colon-after-tag-completion
14049 (assoc rtn ctable))
14050 ":" ""))))
14051 rtn)
14052 ((eq flag t)
14053 ;; all-completions
14054 (all-completions s2 ctable confirm)
14056 ((eq flag 'lambda)
14057 ;; exact match?
14058 (assoc s2 ctable)))
14061 (defun org-fast-tag-insert (kwd tags face &optional end)
14062 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14063 (insert (format "%-12s" (concat kwd ":"))
14064 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14065 (or end "")))
14067 (defun org-fast-tag-show-exit (flag)
14068 (save-excursion
14069 (org-goto-line 3)
14070 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14071 (replace-match ""))
14072 (when flag
14073 (end-of-line 1)
14074 (org-move-to-column (- (window-width) 19) t)
14075 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14077 (defun org-set-current-tags-overlay (current prefix)
14078 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14079 (if (featurep 'xemacs)
14080 (org-overlay-display org-tags-overlay (concat prefix s)
14081 'secondary-selection)
14082 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14083 (org-overlay-display org-tags-overlay (concat prefix s)))))
14085 (defvar org-last-tag-selection-key nil)
14086 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14087 "Fast tag selection with single keys.
14088 CURRENT is the current list of tags in the headline, INHERITED is the
14089 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14090 possibly with grouping information. TODO-TABLE is a similar table with
14091 TODO keywords, should these have keys assigned to them.
14092 If the keys are nil, a-z are automatically assigned.
14093 Returns the new tags string, or nil to not change the current settings."
14094 (let* ((fulltable (append table todo-table))
14095 (maxlen (apply 'max (mapcar
14096 (lambda (x)
14097 (if (stringp (car x)) (string-width (car x)) 0))
14098 fulltable)))
14099 (buf (current-buffer))
14100 (expert (eq org-fast-tag-selection-single-key 'expert))
14101 (buffer-tags nil)
14102 (fwidth (+ maxlen 3 1 3))
14103 (ncol (/ (- (window-width) 4) fwidth))
14104 (i-face 'org-done)
14105 (c-face 'org-todo)
14106 tg cnt e c char c1 c2 ntable tbl rtn
14107 ov-start ov-end ov-prefix
14108 (exit-after-next org-fast-tag-selection-single-key)
14109 (done-keywords org-done-keywords)
14110 groups ingroup)
14111 (save-excursion
14112 (beginning-of-line 1)
14113 (if (looking-at
14114 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14115 (setq ov-start (match-beginning 1)
14116 ov-end (match-end 1)
14117 ov-prefix "")
14118 (setq ov-start (1- (point-at-eol))
14119 ov-end (1+ ov-start))
14120 (skip-chars-forward "^\n\r")
14121 (setq ov-prefix
14122 (concat
14123 (buffer-substring (1- (point)) (point))
14124 (if (> (current-column) org-tags-column)
14126 (make-string (- org-tags-column (current-column)) ?\ ))))))
14127 (move-overlay org-tags-overlay ov-start ov-end)
14128 (save-window-excursion
14129 (if expert
14130 (set-buffer (get-buffer-create " *Org tags*"))
14131 (delete-other-windows)
14132 (split-window-vertically)
14133 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14134 (erase-buffer)
14135 (org-set-local 'org-done-keywords done-keywords)
14136 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14137 (org-fast-tag-insert "Current" current c-face "\n\n")
14138 (org-fast-tag-show-exit exit-after-next)
14139 (org-set-current-tags-overlay current ov-prefix)
14140 (setq tbl fulltable char ?a cnt 0)
14141 (while (setq e (pop tbl))
14142 (cond
14143 ((equal (car e) :startgroup)
14144 (push '() groups) (setq ingroup t)
14145 (when (not (= cnt 0))
14146 (setq cnt 0)
14147 (insert "\n"))
14148 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14149 ((equal (car e) :endgroup)
14150 (setq ingroup nil cnt 0)
14151 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14152 ((equal e '(:newline))
14153 (when (not (= cnt 0))
14154 (setq cnt 0)
14155 (insert "\n")
14156 (setq e (car tbl))
14157 (while (equal (car tbl) '(:newline))
14158 (insert "\n")
14159 (setq tbl (cdr tbl)))))
14161 (setq tg (copy-sequence (car e)) c2 nil)
14162 (if (cdr e)
14163 (setq c (cdr e))
14164 ;; automatically assign a character.
14165 (setq c1 (string-to-char
14166 (downcase (substring
14167 tg (if (= (string-to-char tg) ?@) 1 0)))))
14168 (if (or (rassoc c1 ntable) (rassoc c1 table))
14169 (while (or (rassoc char ntable) (rassoc char table))
14170 (setq char (1+ char)))
14171 (setq c2 c1))
14172 (setq c (or c2 char)))
14173 (if ingroup (push tg (car groups)))
14174 (setq tg (org-add-props tg nil 'face
14175 (cond
14176 ((not (assoc tg table))
14177 (org-get-todo-face tg))
14178 ((member tg current) c-face)
14179 ((member tg inherited) i-face))))
14180 (if (and (= cnt 0) (not ingroup)) (insert " "))
14181 (insert "[" c "] " tg (make-string
14182 (- fwidth 4 (length tg)) ?\ ))
14183 (push (cons tg c) ntable)
14184 (when (= (setq cnt (1+ cnt)) ncol)
14185 (insert "\n")
14186 (if ingroup (insert " "))
14187 (setq cnt 0)))))
14188 (setq ntable (nreverse ntable))
14189 (insert "\n")
14190 (goto-char (point-min))
14191 (if (not expert) (org-fit-window-to-buffer))
14192 (setq rtn
14193 (catch 'exit
14194 (while t
14195 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14196 (if (not groups) "no " "")
14197 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14198 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14199 (setq org-last-tag-selection-key c)
14200 (cond
14201 ((= c ?\r) (throw 'exit t))
14202 ((= c ?!)
14203 (setq groups (not groups))
14204 (goto-char (point-min))
14205 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14206 ((= c ?\C-c)
14207 (if (not expert)
14208 (org-fast-tag-show-exit
14209 (setq exit-after-next (not exit-after-next)))
14210 (setq expert nil)
14211 (delete-other-windows)
14212 (set-window-buffer (split-window-vertically) " *Org tags*")
14213 (org-switch-to-buffer-other-window " *Org tags*")
14214 (org-fit-window-to-buffer)))
14215 ((or (= c ?\C-g)
14216 (and (= c ?q) (not (rassoc c ntable))))
14217 (org-detach-overlay org-tags-overlay)
14218 (setq quit-flag t))
14219 ((= c ?\ )
14220 (setq current nil)
14221 (if exit-after-next (setq exit-after-next 'now)))
14222 ((= c ?\t)
14223 (condition-case nil
14224 (setq tg (org-icompleting-read
14225 "Tag: "
14226 (or buffer-tags
14227 (with-current-buffer buf
14228 (org-get-buffer-tags)))))
14229 (quit (setq tg "")))
14230 (when (string-match "\\S-" tg)
14231 (add-to-list 'buffer-tags (list tg))
14232 (if (member tg current)
14233 (setq current (delete tg current))
14234 (push tg current)))
14235 (if exit-after-next (setq exit-after-next 'now)))
14236 ((setq e (rassoc c todo-table) tg (car e))
14237 (with-current-buffer buf
14238 (save-excursion (org-todo tg)))
14239 (if exit-after-next (setq exit-after-next 'now)))
14240 ((setq e (rassoc c ntable) tg (car e))
14241 (if (member tg current)
14242 (setq current (delete tg current))
14243 (loop for g in groups do
14244 (if (member tg g)
14245 (mapc (lambda (x)
14246 (setq current (delete x current)))
14247 g)))
14248 (push tg current))
14249 (if exit-after-next (setq exit-after-next 'now))))
14251 ;; Create a sorted list
14252 (setq current
14253 (sort current
14254 (lambda (a b)
14255 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14256 (if (eq exit-after-next 'now) (throw 'exit t))
14257 (goto-char (point-min))
14258 (beginning-of-line 2)
14259 (delete-region (point) (point-at-eol))
14260 (org-fast-tag-insert "Current" current c-face)
14261 (org-set-current-tags-overlay current ov-prefix)
14262 (while (re-search-forward
14263 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14264 (setq tg (match-string 1))
14265 (add-text-properties
14266 (match-beginning 1) (match-end 1)
14267 (list 'face
14268 (cond
14269 ((member tg current) c-face)
14270 ((member tg inherited) i-face)
14271 (t (get-text-property (match-beginning 1) 'face))))))
14272 (goto-char (point-min)))))
14273 (org-detach-overlay org-tags-overlay)
14274 (if rtn
14275 (mapconcat 'identity current ":")
14276 nil))))
14278 (defun org-get-tags-string ()
14279 "Get the TAGS string in the current headline."
14280 (unless (org-at-heading-p t)
14281 (error "Not on a heading"))
14282 (save-excursion
14283 (beginning-of-line 1)
14284 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14285 (org-match-string-no-properties 1)
14286 "")))
14288 (defun org-get-tags ()
14289 "Get the list of tags specified in the current headline."
14290 (org-split-string (org-get-tags-string) ":"))
14292 (defun org-get-buffer-tags ()
14293 "Get a table of all tags used in the buffer, for completion."
14294 (let (tags)
14295 (save-excursion
14296 (goto-char (point-min))
14297 (while (re-search-forward
14298 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14299 (when (equal (char-after (point-at-bol 0)) ?*)
14300 (mapc (lambda (x) (add-to-list 'tags x))
14301 (org-split-string (org-match-string-no-properties 1) ":")))))
14302 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14303 (mapcar 'list tags)))
14305 ;;;; The mapping API
14307 (defun org-map-entries (func &optional match scope &rest skip)
14308 "Call FUNC at each headline selected by MATCH in SCOPE.
14310 FUNC is a function or a lisp form. The function will be called without
14311 arguments, with the cursor positioned at the beginning of the headline.
14312 The return values of all calls to the function will be collected and
14313 returned as a list.
14315 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14316 does not need to preserve point. After evaluation, the cursor will be
14317 moved to the end of the line (presumably of the headline of the
14318 processed entry) and search continues from there. Under some
14319 circumstances, this may not produce the wanted results. For example,
14320 if you have removed (e.g. archived) the current (sub)tree it could
14321 mean that the next entry will be skipped entirely. In such cases, you
14322 can specify the position from where search should continue by making
14323 FUNC set the variable `org-map-continue-from' to the desired buffer
14324 position.
14326 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14327 Only headlines that are matched by this query will be considered during
14328 the iteration. When MATCH is nil or t, all headlines will be
14329 visited by the iteration.
14331 SCOPE determines the scope of this command. It can be any of:
14333 nil The current buffer, respecting the restriction if any
14334 tree The subtree started with the entry at point
14335 region The entries within the active region, if any
14336 region-start-level
14337 The entries within the active region, but only those at
14338 the same level than the first one.
14339 file The current buffer, without restriction
14340 file-with-archives
14341 The current buffer, and any archives associated with it
14342 agenda All agenda files
14343 agenda-with-archives
14344 All agenda files with any archive files associated with them
14345 \(file1 file2 ...)
14346 If this is a list, all files in the list will be scanned
14348 The remaining args are treated as settings for the skipping facilities of
14349 the scanner. The following items can be given here:
14351 archive skip trees with the archive tag.
14352 comment skip trees with the COMMENT keyword
14353 function or Emacs Lisp form:
14354 will be used as value for `org-agenda-skip-function', so whenever
14355 the function returns t, FUNC will not be called for that
14356 entry and search will continue from the point where the
14357 function leaves it.
14359 If your function needs to retrieve the tags including inherited tags
14360 at the *current* entry, you can use the value of the variable
14361 `org-scanner-tags' which will be much faster than getting the value
14362 with `org-get-tags-at'. If your function gets properties with
14363 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14364 to t around the call to `org-entry-properties' to get the same speedup.
14365 Note that if your function moves around to retrieve tags and properties at
14366 a *different* entry, you cannot use these techniques."
14367 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14368 (not (org-region-active-p)))
14369 (let* ((org-agenda-archives-mode nil) ; just to make sure
14370 (org-agenda-skip-archived-trees (memq 'archive skip))
14371 (org-agenda-skip-comment-trees (memq 'comment skip))
14372 (org-agenda-skip-function
14373 (car (org-delete-all '(comment archive) skip)))
14374 (org-tags-match-list-sublevels t)
14375 (start-level (eq scope 'region-start-level))
14376 matcher file res
14377 org-todo-keywords-for-agenda
14378 org-done-keywords-for-agenda
14379 org-todo-keyword-alist-for-agenda
14380 org-drawers-for-agenda
14381 org-tag-alist-for-agenda
14382 todo-only)
14384 (cond
14385 ((eq match t) (setq matcher t))
14386 ((eq match nil) (setq matcher t))
14387 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14389 (save-excursion
14390 (save-restriction
14391 (cond ((eq scope 'tree)
14392 (org-back-to-heading t)
14393 (org-narrow-to-subtree)
14394 (setq scope nil))
14395 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14396 (org-region-active-p))
14397 ;; If needed, set start-level to a string like "2"
14398 (when start-level
14399 (save-excursion
14400 (goto-char (region-beginning))
14401 (unless (org-at-heading-p) (outline-next-heading))
14402 (setq start-level (org-current-level))))
14403 (narrow-to-region (region-beginning)
14404 (save-excursion
14405 (goto-char (region-end))
14406 (unless (and (bolp) (org-at-heading-p))
14407 (outline-next-heading))
14408 (point)))
14409 (setq scope nil)))
14411 (if (not scope)
14412 (progn
14413 (org-agenda-prepare-buffers
14414 (list (buffer-file-name (current-buffer))))
14415 (setq res (org-scan-tags func matcher todo-only start-level)))
14416 ;; Get the right scope
14417 (cond
14418 ((and scope (listp scope) (symbolp (car scope)))
14419 (setq scope (eval scope)))
14420 ((eq scope 'agenda)
14421 (setq scope (org-agenda-files t)))
14422 ((eq scope 'agenda-with-archives)
14423 (setq scope (org-agenda-files t))
14424 (setq scope (org-add-archive-files scope)))
14425 ((eq scope 'file)
14426 (setq scope (list (buffer-file-name))))
14427 ((eq scope 'file-with-archives)
14428 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14429 (org-agenda-prepare-buffers scope)
14430 (while (setq file (pop scope))
14431 (with-current-buffer (org-find-base-buffer-visiting file)
14432 (save-excursion
14433 (save-restriction
14434 (widen)
14435 (goto-char (point-min))
14436 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14437 res)))
14439 ;;;; Properties
14441 ;;; Setting and retrieving properties
14443 (defconst org-special-properties
14444 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14445 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14446 "The special properties valid in Org-mode.
14448 These are properties that are not defined in the property drawer,
14449 but in some other way.")
14451 (defconst org-default-properties
14452 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14453 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14454 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14455 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14456 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14457 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14458 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14459 "Some properties that are used by Org-mode for various purposes.
14460 Being in this list makes sure that they are offered for completion.")
14462 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14463 "Regular expression matching the first line of a property drawer.")
14465 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14466 "Regular expression matching the last line of a property drawer.")
14468 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14469 "Regular expression matching the first line of a property drawer.")
14471 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14472 "Regular expression matching the first line of a property drawer.")
14474 (defconst org-property-drawer-re
14475 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14476 org-property-end-re "\\)\n?")
14477 "Matches an entire property drawer.")
14479 (defconst org-clock-drawer-re
14480 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14481 org-property-end-re "\\)\n?")
14482 "Matches an entire clock drawer.")
14484 (defsubst org-re-property (property)
14485 "Return a regexp matching a PROPERTY line.
14486 Match group 1 will be set to the value."
14487 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14489 (defsubst org-re-property-keyword (property)
14490 "Return a regexp matching a PROPERTY line, possibly with no
14491 value for the property."
14492 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14494 (defun org-property-action ()
14495 "Do an action on properties."
14496 (interactive)
14497 (let (c)
14498 (org-at-property-p)
14499 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14500 (setq c (read-char-exclusive))
14501 (cond
14502 ((equal c ?s)
14503 (call-interactively 'org-set-property))
14504 ((equal c ?d)
14505 (call-interactively 'org-delete-property))
14506 ((equal c ?D)
14507 (call-interactively 'org-delete-property-globally))
14508 ((equal c ?c)
14509 (call-interactively 'org-compute-property-at-point))
14510 (t (error "No such property action %c" c)))))
14512 (defun org-inc-effort ()
14513 "Increment the value of the effort property in the current entry."
14514 (interactive)
14515 (org-set-effort nil t))
14517 (defun org-set-effort (&optional value increment)
14518 "Set the effort property of the current entry.
14519 With numerical prefix arg, use the nth allowed value, 0 stands for the
14520 10th allowed value.
14522 When INCREMENT is non-nil, set the property to the next allowed value."
14523 (interactive "P")
14524 (if (equal value 0) (setq value 10))
14525 (let* ((completion-ignore-case t)
14526 (prop org-effort-property)
14527 (cur (org-entry-get nil prop))
14528 (allowed (org-property-get-allowed-values nil prop 'table))
14529 (existing (mapcar 'list (org-property-values prop)))
14531 (val (cond
14532 ((stringp value) value)
14533 ((and allowed (integerp value))
14534 (or (car (nth (1- value) allowed))
14535 (car (org-last allowed))))
14536 ((and allowed increment)
14537 (or (caadr (member (list cur) allowed))
14538 (error "Allowed effort values are not set")))
14539 (allowed
14540 (message "Select 1-9,0, [RET%s]: %s"
14541 (if cur (concat "=" cur) "")
14542 (mapconcat 'car allowed " "))
14543 (setq rpl (read-char-exclusive))
14544 (if (equal rpl ?\r)
14546 (setq rpl (- rpl ?0))
14547 (if (equal rpl 0) (setq rpl 10))
14548 (if (and (> rpl 0) (<= rpl (length allowed)))
14549 (car (nth (1- rpl) allowed))
14550 (org-completing-read "Effort: " allowed nil))))
14552 (let (org-completion-use-ido org-completion-use-iswitchb)
14553 (org-completing-read
14554 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14555 (concat "[" cur "]") "")
14556 ": ")
14557 existing nil nil "" nil cur))))))
14558 (unless (equal (org-entry-get nil prop) val)
14559 (org-entry-put nil prop val))
14560 (save-excursion
14561 (org-back-to-heading t)
14562 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14563 (message "%s is now %s" prop val)))
14565 (defun org-at-property-p ()
14566 "Is cursor inside a property drawer?"
14567 (save-excursion
14568 (beginning-of-line 1)
14569 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14570 (save-match-data ;; Used by calling procedures
14571 (let ((p (point))
14572 (range (unless (org-before-first-heading-p)
14573 (org-get-property-block))))
14574 (and range (<= (car range) p) (< p (cdr range))))))))
14576 (defun org-get-property-block (&optional beg end force)
14577 "Return the (beg . end) range of the body of the property drawer.
14578 BEG and END are the beginning and end of the current subtree, or of
14579 the part before the first headline. If they are not given, they will
14580 be found. If the drawer does not exist and FORCE is non-nil, create
14581 the drawer."
14582 (catch 'exit
14583 (save-excursion
14584 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14585 (progn (org-back-to-heading t) (point))))
14586 (end (or end (and (not (outline-next-heading)) (point-max))
14587 (point))))
14588 (goto-char beg)
14589 (if (re-search-forward org-property-start-re end t)
14590 (setq beg (1+ (match-end 0)))
14591 (if force
14592 (save-excursion
14593 (org-insert-property-drawer)
14594 (setq end (progn (outline-next-heading) (point))))
14595 (throw 'exit nil))
14596 (goto-char beg)
14597 (if (re-search-forward org-property-start-re end t)
14598 (setq beg (1+ (match-end 0)))))
14599 (if (re-search-forward org-property-end-re end t)
14600 (setq end (match-beginning 0))
14601 (or force (throw 'exit nil))
14602 (goto-char beg)
14603 (setq end beg)
14604 (org-indent-line)
14605 (insert ":END:\n"))
14606 (cons beg end)))))
14608 (defun org-entry-properties (&optional pom which specific)
14609 "Get all properties of the entry at point-or-marker POM.
14610 This includes the TODO keyword, the tags, time strings for deadline,
14611 scheduled, and clocking, and any additional properties defined in the
14612 entry. The return value is an alist, keys may occur multiple times
14613 if the property key was used several times.
14614 POM may also be nil, in which case the current entry is used.
14615 If WHICH is nil or `all', get all properties. If WHICH is
14616 `special' or `standard', only get that subclass. If WHICH
14617 is a string only get exactly this property. SPECIFIC can be a string, the
14618 specific property we are interested in. Specifying it can speed
14619 things up because then unnecessary parsing is avoided."
14620 (setq which (or which 'all))
14621 (org-with-point-at pom
14622 (let ((clockstr (substring org-clock-string 0 -1))
14623 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14624 (case-fold-search nil)
14625 beg end range props sum-props key key1 value string clocksum clocksumt)
14626 (save-excursion
14627 (when (condition-case nil
14628 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14629 (error nil))
14630 (setq beg (point))
14631 (setq sum-props (get-text-property (point) 'org-summaries))
14632 (setq clocksum (get-text-property (point) :org-clock-minutes)
14633 clocksumt (get-text-property (point) :org-clock-minutes-today))
14634 (outline-next-heading)
14635 (setq end (point))
14636 (when (memq which '(all special))
14637 ;; Get the special properties, like TODO and tags
14638 (goto-char beg)
14639 (when (and (or (not specific) (string= specific "TODO"))
14640 (looking-at org-todo-line-regexp) (match-end 2))
14641 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14642 (when (and (or (not specific) (string= specific "PRIORITY"))
14643 (looking-at org-priority-regexp))
14644 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14645 (when (or (not specific) (string= specific "FILE"))
14646 (push (cons "FILE" buffer-file-name) props))
14647 (when (and (or (not specific) (string= specific "TAGS"))
14648 (setq value (org-get-tags-string))
14649 (string-match "\\S-" value))
14650 (push (cons "TAGS" value) props))
14651 (when (and (or (not specific) (string= specific "ALLTAGS"))
14652 (setq value (org-get-tags-at)))
14653 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14654 ":"))
14655 props))
14656 (when (or (not specific) (string= specific "BLOCKED"))
14657 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14658 (when (or (not specific)
14659 (member specific
14660 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14661 "TIMESTAMP" "TIMESTAMP_IA")))
14662 (catch 'match
14663 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14664 (setq key (if (match-end 1)
14665 (substring (org-match-string-no-properties 1)
14666 0 -1))
14667 string (if (equal key clockstr)
14668 (org-trim
14669 (buffer-substring-no-properties
14670 (match-beginning 3) (goto-char
14671 (point-at-eol))))
14672 (substring (org-match-string-no-properties 3)
14673 1 -1)))
14674 ;; Get the correct property name from the key. This is
14675 ;; necessary if the user has configured time keywords.
14676 (setq key1 (concat key ":"))
14677 (cond
14678 ((not key)
14679 (setq key
14680 (if (= (char-after (match-beginning 3)) ?\[)
14681 "TIMESTAMP_IA" "TIMESTAMP")))
14682 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14683 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14684 ((equal key1 org-closed-string) (setq key "CLOSED"))
14685 ((equal key1 org-clock-string) (setq key "CLOCK")))
14686 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14687 (progn
14688 (push (cons key string) props)
14689 ;; no need to search further if match is found
14690 (throw 'match t))
14691 (when (or (equal key "CLOCK") (not (assoc key props)))
14692 (push (cons key string) props)))))))
14694 (when (memq which '(all standard))
14695 ;; Get the standard properties, like :PROP: ...
14696 (setq range (org-get-property-block beg end))
14697 (when range
14698 (goto-char (car range))
14699 (while (re-search-forward
14700 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14701 (cdr range) t)
14702 (setq key (org-match-string-no-properties 1)
14703 value (org-trim (or (org-match-string-no-properties 2) "")))
14704 (unless (member key excluded)
14705 (push (cons key (or value "")) props)))))
14706 (if clocksum
14707 (push (cons "CLOCKSUM"
14708 (org-columns-number-to-string (/ (float clocksum) 60.)
14709 'add_times))
14710 props))
14711 (if clocksumt
14712 (push (cons "CLOCKSUM_T"
14713 (org-columns-number-to-string (/ (float clocksumt) 60.)
14714 'add_times))
14715 props))
14716 (unless (assoc "CATEGORY" props)
14717 (push (cons "CATEGORY" (org-get-category)) props))
14718 (append sum-props (nreverse props)))))))
14720 (defun org-entry-get (pom property &optional inherit literal-nil)
14721 "Get value of PROPERTY for entry or content at point-or-marker POM.
14722 If INHERIT is non-nil and the entry does not have the property,
14723 then also check higher levels of the hierarchy.
14724 If INHERIT is the symbol `selective', use inheritance only if the setting
14725 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14726 If the property is present but empty, the return value is the empty string.
14727 If the property is not present at all, nil is returned.
14729 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14730 do not interpret it as the list atom nil. This is used for inheritance
14731 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14732 (org-with-point-at pom
14733 (if (and inherit (if (eq inherit 'selective)
14734 (org-property-inherit-p property)
14736 (org-entry-get-with-inheritance property literal-nil)
14737 (if (member property org-special-properties)
14738 ;; We need a special property. Use `org-entry-properties' to
14739 ;; retrieve it, but specify the wanted property
14740 (cdr (assoc property (org-entry-properties nil 'special property)))
14741 (let ((range (org-get-property-block)))
14742 (when (and range (not (eq (car range) (cdr range))))
14743 (let* ((props (list (or (assoc property org-file-properties)
14744 (assoc property org-global-properties)
14745 (assoc property org-global-properties-fixed))))
14746 (ap (lambda (key)
14747 (when (re-search-forward
14748 (org-re-property key) (cdr range) t)
14749 (setq props
14750 (org-update-property-plist
14752 (if (match-end 1)
14753 (org-match-string-no-properties 1) "")
14754 props)))))
14755 val)
14756 (goto-char (car range))
14757 (funcall ap property)
14758 (goto-char (car range))
14759 (while (funcall ap (concat property "+")))
14760 (setq val (cdr (assoc property props)))
14761 (when val (if literal-nil val (org-not-nil val))))))))))
14763 (defun org-property-or-variable-value (var &optional inherit)
14764 "Check if there is a property fixing the value of VAR.
14765 If yes, return this value. If not, return the current value of the variable."
14766 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14767 (if (and prop (stringp prop) (string-match "\\S-" prop))
14768 (read prop)
14769 (symbol-value var))))
14771 (defun org-entry-delete (pom property)
14772 "Delete the property PROPERTY from entry at point-or-marker POM."
14773 (org-with-point-at pom
14774 (if (member property org-special-properties)
14775 nil ; cannot delete these properties.
14776 (let ((range (org-get-property-block)))
14777 (if (and range
14778 (goto-char (car range))
14779 (re-search-forward
14780 (org-re-property property)
14781 (cdr range) t))
14782 (progn
14783 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14785 nil)))))
14787 ;; Multi-values properties are properties that contain multiple values
14788 ;; These values are assumed to be single words, separated by whitespace.
14789 (defun org-entry-add-to-multivalued-property (pom property value)
14790 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14791 (let* ((old (org-entry-get pom property))
14792 (values (and old (org-split-string old "[ \t]"))))
14793 (setq value (org-entry-protect-space value))
14794 (unless (member value values)
14795 (setq values (cons value values))
14796 (org-entry-put pom property
14797 (mapconcat 'identity values " ")))))
14799 (defun org-entry-remove-from-multivalued-property (pom property value)
14800 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14801 (let* ((old (org-entry-get pom property))
14802 (values (and old (org-split-string old "[ \t]"))))
14803 (setq value (org-entry-protect-space value))
14804 (when (member value values)
14805 (setq values (delete value values))
14806 (org-entry-put pom property
14807 (mapconcat 'identity values " ")))))
14809 (defun org-entry-member-in-multivalued-property (pom property value)
14810 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14811 (let* ((old (org-entry-get pom property))
14812 (values (and old (org-split-string old "[ \t]"))))
14813 (setq value (org-entry-protect-space value))
14814 (member value values)))
14816 (defun org-entry-get-multivalued-property (pom property)
14817 "Return a list of values in a multivalued property."
14818 (let* ((value (org-entry-get pom property))
14819 (values (and value (org-split-string value "[ \t]"))))
14820 (mapcar 'org-entry-restore-space values)))
14822 (defun org-entry-put-multivalued-property (pom property &rest values)
14823 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14824 VALUES should be a list of strings. Spaces will be protected."
14825 (org-entry-put pom property
14826 (mapconcat 'org-entry-protect-space values " "))
14827 (let* ((value (org-entry-get pom property))
14828 (values (and value (org-split-string value "[ \t]"))))
14829 (mapcar 'org-entry-restore-space values)))
14831 (defun org-entry-protect-space (s)
14832 "Protect spaces and newline in string S."
14833 (while (string-match " " s)
14834 (setq s (replace-match "%20" t t s)))
14835 (while (string-match "\n" s)
14836 (setq s (replace-match "%0A" t t s)))
14839 (defun org-entry-restore-space (s)
14840 "Restore spaces and newline in string S."
14841 (while (string-match "%20" s)
14842 (setq s (replace-match " " t t s)))
14843 (while (string-match "%0A" s)
14844 (setq s (replace-match "\n" t t s)))
14847 (defvar org-entry-property-inherited-from (make-marker)
14848 "Marker pointing to the entry from where a property was inherited.
14849 Each call to `org-entry-get-with-inheritance' will set this marker to the
14850 location of the entry where the inheritance search matched. If there was
14851 no match, the marker will point nowhere.
14852 Note that also `org-entry-get' calls this function, if the INHERIT flag
14853 is set.")
14855 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14856 "Get PROPERTY of entry or content at point, search higher levels if needed.
14857 The search will stop at the first ancestor which has the property defined.
14858 If the value found is \"nil\", return nil to show that the property
14859 should be considered as undefined (this is the meaning of nil here).
14860 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14861 (move-marker org-entry-property-inherited-from nil)
14862 (let (tmp)
14863 (save-excursion
14864 (save-restriction
14865 (widen)
14866 (catch 'ex
14867 (while t
14868 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14869 (or (ignore-errors (org-back-to-heading t))
14870 (goto-char (point-min)))
14871 (move-marker org-entry-property-inherited-from (point))
14872 (throw 'ex tmp))
14873 (or (ignore-errors (org-up-heading-safe))
14874 (throw 'ex nil))))))
14875 (setq tmp (or tmp
14876 (cdr (assoc property org-file-properties))
14877 (cdr (assoc property org-global-properties))
14878 (cdr (assoc property org-global-properties-fixed))))
14879 (if literal-nil tmp (org-not-nil tmp))))
14881 (defvar org-property-changed-functions nil
14882 "Hook called when the value of a property has changed.
14883 Each hook function should accept two arguments, the name of the property
14884 and the new value.")
14886 (defun org-entry-put (pom property value)
14887 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14888 (org-with-point-at pom
14889 (org-back-to-heading t)
14890 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14891 range)
14892 (cond
14893 ((equal property "TODO")
14894 (when (and (stringp value) (string-match "\\S-" value)
14895 (not (member value org-todo-keywords-1)))
14896 (error "\"%s\" is not a valid TODO state" value))
14897 (if (or (not value)
14898 (not (string-match "\\S-" value)))
14899 (setq value 'none))
14900 (org-todo value)
14901 (org-set-tags nil 'align))
14902 ((equal property "PRIORITY")
14903 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14904 (string-to-char value) ?\ ))
14905 (org-set-tags nil 'align))
14906 ((equal property "CLOCKSUM")
14907 (if (not (re-search-forward
14908 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14909 (error "Cannot find a clock log")
14910 (goto-char (- (match-end 1) 2))
14911 (cond
14912 ((eq value 'earlier) (org-timestamp-down))
14913 ((eq value 'later) (org-timestamp-up)))
14914 (org-clock-sum-current-item)))
14915 ((equal property "SCHEDULED")
14916 (if (re-search-forward org-scheduled-time-regexp end t)
14917 (cond
14918 ((eq value 'earlier) (org-timestamp-change -1 'day))
14919 ((eq value 'later) (org-timestamp-change 1 'day))
14920 (t (call-interactively 'org-schedule)))
14921 (call-interactively 'org-schedule)))
14922 ((equal property "DEADLINE")
14923 (if (re-search-forward org-deadline-time-regexp end t)
14924 (cond
14925 ((eq value 'earlier) (org-timestamp-change -1 'day))
14926 ((eq value 'later) (org-timestamp-change 1 'day))
14927 (t (call-interactively 'org-deadline)))
14928 (call-interactively 'org-deadline)))
14929 ((member property org-special-properties)
14930 (error "The %s property can not yet be set with `org-entry-put'"
14931 property))
14932 (t ; a non-special property
14933 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14934 (setq range (org-get-property-block beg end 'force))
14935 (goto-char (car range))
14936 (if (re-search-forward
14937 (org-re-property-keyword property) (cdr range) t)
14938 (progn
14939 (delete-region (match-beginning 0) (match-end 0))
14940 (goto-char (match-beginning 0)))
14941 (goto-char (cdr range))
14942 (insert "\n")
14943 (backward-char 1)
14944 (org-indent-line))
14945 (insert ":" property ":")
14946 (and value (insert " " value))
14947 (org-indent-line)))))
14948 (run-hook-with-args 'org-property-changed-functions property value)))
14950 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14951 "Get all property keys in the current buffer.
14952 With INCLUDE-SPECIALS, also list the special properties that reflect things
14953 like tags and TODO state.
14954 With INCLUDE-DEFAULTS, also include properties that has special meaning
14955 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14956 and others.
14957 With INCLUDE-COLUMNS, also include property names given in COLUMN
14958 formats in the current buffer."
14959 (let (rtn range cfmt s p)
14960 (save-excursion
14961 (save-restriction
14962 (widen)
14963 (goto-char (point-min))
14964 (while (re-search-forward org-property-start-re nil t)
14965 (setq range (org-get-property-block))
14966 (goto-char (car range))
14967 (while (re-search-forward
14968 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14969 (cdr range) t)
14970 (add-to-list 'rtn (org-match-string-no-properties 1)))
14971 (outline-next-heading))))
14973 (when include-specials
14974 (setq rtn (append org-special-properties rtn)))
14976 (when include-defaults
14977 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14978 (add-to-list 'rtn org-effort-property))
14980 (when include-columns
14981 (save-excursion
14982 (save-restriction
14983 (widen)
14984 (goto-char (point-min))
14985 (while (re-search-forward
14986 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14987 nil t)
14988 (setq cfmt (match-string 2) s 0)
14989 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14990 cfmt s)
14991 (setq s (match-end 0)
14992 p (match-string 1 cfmt))
14993 (unless (or (equal p "ITEM")
14994 (member p org-special-properties))
14995 (add-to-list 'rtn (match-string 1 cfmt))))))))
14997 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14999 (defun org-property-values (key)
15000 "Return a list of all values of property KEY in the current buffer."
15001 (save-excursion
15002 (save-restriction
15003 (widen)
15004 (goto-char (point-min))
15005 (let ((re (org-re-property key))
15006 values)
15007 (while (re-search-forward re nil t)
15008 (add-to-list 'values (org-trim (match-string 1))))
15009 (delete "" values)))))
15011 (defun org-insert-property-drawer ()
15012 "Insert a property drawer into the current entry."
15013 (org-back-to-heading t)
15014 (looking-at org-outline-regexp)
15015 (let ((indent (if org-adapt-indentation
15016 (- (match-end 0) (match-beginning 0))
15018 (beg (point))
15019 (re (concat "^[ \t]*" org-keyword-time-regexp))
15020 end hiddenp)
15021 (outline-next-heading)
15022 (setq end (point))
15023 (goto-char beg)
15024 (while (re-search-forward re end t))
15025 (setq hiddenp (outline-invisible-p))
15026 (end-of-line 1)
15027 (and (equal (char-after) ?\n) (forward-char 1))
15028 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15029 (if (member (match-string 1) '("CLOCK:" ":END:"))
15030 ;; just skip this line
15031 (beginning-of-line 2)
15032 ;; Drawer start, find the end
15033 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15034 (beginning-of-line 1)))
15035 (org-skip-over-state-notes)
15036 (skip-chars-backward " \t\n\r")
15037 (if (eq (char-before) ?*) (forward-char 1))
15038 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15039 (beginning-of-line 0)
15040 (org-indent-to-column indent)
15041 (beginning-of-line 2)
15042 (org-indent-to-column indent)
15043 (beginning-of-line 0)
15044 (if hiddenp
15045 (save-excursion
15046 (org-back-to-heading t)
15047 (hide-entry))
15048 (org-flag-drawer t))))
15050 (defun org-insert-drawer (&optional arg drawer)
15051 "Insert a drawer at point.
15053 Optional argument DRAWER, when non-nil, is a string representing
15054 drawer's name. Otherwise, the user is prompted for a name.
15056 If a region is active, insert the drawer around that region
15057 instead.
15059 Point is left between drawer's boundaries."
15060 (interactive "P")
15061 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15062 "LOGBOOK"))
15063 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15064 ;; internally by Org. They are meant to be inserted
15065 ;; automatically.
15066 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15067 ;; Remove system drawers from list. Note: For some reason,
15068 ;; `org-completing-read' ignores the predicate while
15069 ;; `completing-read' handles it fine.
15070 (drawer (if arg "PROPERTIES"
15071 (or drawer
15072 (completing-read
15073 "Drawer: " org-drawers
15074 (lambda (d) (not (member d system-drawers))))))))
15075 (cond
15076 ;; With C-u, fall back on `org-insert-property-drawer'
15077 (arg (org-insert-property-drawer))
15078 ;; With an active region, insert a drawer at point.
15079 ((not (org-region-active-p))
15080 (progn
15081 (unless (bolp) (insert "\n"))
15082 (insert (format ":%s:\n\n:END:\n" drawer))
15083 (forward-line -2)))
15084 ;; Otherwise, insert the drawer at point
15086 (let ((rbeg (region-beginning))
15087 (rend (copy-marker (region-end))))
15088 (unwind-protect
15089 (progn
15090 (goto-char rbeg)
15091 (beginning-of-line)
15092 (when (save-excursion
15093 (re-search-forward org-outline-regexp-bol rend t))
15094 (error "Drawers cannot contain headlines"))
15095 ;; Position point at the beginning of the first
15096 ;; non-blank line in region. Insert drawer's opening
15097 ;; there, then indent it.
15098 (org-skip-whitespace)
15099 (beginning-of-line)
15100 (insert ":" drawer ":\n")
15101 (forward-line -1)
15102 (indent-for-tab-command)
15103 ;; Move point to the beginning of the first blank line
15104 ;; after the last non-blank line in region. Insert
15105 ;; drawer's closing, then indent it.
15106 (goto-char rend)
15107 (skip-chars-backward " \r\t\n")
15108 (insert "\n:END:")
15109 (deactivate-mark t)
15110 (indent-for-tab-command)
15111 (unless (eolp) (insert "\n")))
15112 ;; Clear marker, whatever the outcome of insertion is.
15113 (set-marker rend nil)))))))
15115 (defvar org-property-set-functions-alist nil
15116 "Property set function alist.
15117 Each entry should have the following format:
15119 (PROPERTY . READ-FUNCTION)
15121 The read function will be called with the same argument as
15122 `org-completing-read'.")
15124 (defun org-set-property-function (property)
15125 "Get the function that should be used to set PROPERTY.
15126 This is computed according to `org-property-set-functions-alist'."
15127 (or (cdr (assoc property org-property-set-functions-alist))
15128 'org-completing-read))
15130 (defun org-read-property-value (property)
15131 "Read PROPERTY value from user."
15132 (let* ((completion-ignore-case t)
15133 (allowed (org-property-get-allowed-values nil property 'table))
15134 (cur (org-entry-get nil property))
15135 (prompt (concat property " value"
15136 (if (and cur (string-match "\\S-" cur))
15137 (concat " [" cur "]") "") ": "))
15138 (set-function (org-set-property-function property))
15139 (val (if allowed
15140 (funcall set-function prompt allowed nil
15141 (not (get-text-property 0 'org-unrestricted
15142 (caar allowed))))
15143 (let (org-completion-use-ido org-completion-use-iswitchb)
15144 (funcall set-function prompt
15145 (mapcar 'list (org-property-values property))
15146 nil nil "" nil cur)))))
15147 (if (equal val "")
15149 val)))
15151 (defvar org-last-set-property nil)
15152 (defvar org-last-set-property-value nil)
15153 (defun org-read-property-name ()
15154 "Read a property name."
15155 (let* ((completion-ignore-case t)
15156 (keys (org-buffer-property-keys nil t t))
15157 (default-prop (or (save-excursion
15158 (save-match-data
15159 (beginning-of-line)
15160 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15161 (null (string= (match-string 1) "END"))
15162 (match-string 1))))
15163 org-last-set-property))
15164 (property (org-icompleting-read
15165 (concat "Property"
15166 (if default-prop (concat " [" default-prop "]") "")
15167 ": ")
15168 (mapcar 'list keys)
15169 nil nil nil nil
15170 default-prop)))
15171 (if (member property keys)
15172 property
15173 (or (cdr (assoc (downcase property)
15174 (mapcar (lambda (x) (cons (downcase x) x))
15175 keys)))
15176 property))))
15178 (defun org-set-property-and-value (use-last)
15179 "Allow to set [PROPERTY]: [value] direction from prompt.
15180 When use-default, don't even ask, just use the last
15181 \"[PROPERTY]: [value]\" string from the history."
15182 (interactive "P")
15183 (let* ((completion-ignore-case t)
15184 (pv (or (and use-last org-last-set-property-value)
15185 (org-completing-read
15186 "Enter a \"[Property]: [value]\" pair: "
15187 nil nil nil nil nil
15188 org-last-set-property-value)))
15189 prop val)
15190 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15191 (setq prop (match-string 1 pv)
15192 val (match-string 2 pv))
15193 (org-set-property prop val))))
15195 (defun org-set-property (property value)
15196 "In the current entry, set PROPERTY to VALUE.
15197 When called interactively, this will prompt for a property name, offering
15198 completion on existing and default properties. And then it will prompt
15199 for a value, offering completion either on allowed values (via an inherited
15200 xxx_ALL property) or on existing values in other instances of this property
15201 in the current file."
15202 (interactive (list nil nil))
15203 (let* ((property (or property (org-read-property-name)))
15204 (value (or value (org-read-property-value property)))
15205 (fn (cdr (assoc property org-properties-postprocess-alist))))
15206 (setq org-last-set-property property)
15207 (setq org-last-set-property-value (concat property ": " value))
15208 ;; Possibly postprocess the inserted value:
15209 (when fn (setq value (funcall fn value)))
15210 (unless (equal (org-entry-get nil property) value)
15211 (org-entry-put nil property value))))
15213 (defun org-delete-property (property)
15214 "In the current entry, delete PROPERTY."
15215 (interactive
15216 (let* ((completion-ignore-case t)
15217 (prop (org-icompleting-read "Property: "
15218 (org-entry-properties nil 'standard))))
15219 (list prop)))
15220 (message "Property %s %s" property
15221 (if (org-entry-delete nil property)
15222 "deleted"
15223 "was not present in the entry")))
15225 (defun org-delete-property-globally (property)
15226 "Remove PROPERTY globally, from all entries."
15227 (interactive
15228 (let* ((completion-ignore-case t)
15229 (prop (org-icompleting-read
15230 "Globally remove property: "
15231 (mapcar 'list (org-buffer-property-keys)))))
15232 (list prop)))
15233 (save-excursion
15234 (save-restriction
15235 (widen)
15236 (goto-char (point-min))
15237 (let ((cnt 0))
15238 (while (re-search-forward
15239 (org-re-property property)
15240 nil t)
15241 (setq cnt (1+ cnt))
15242 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15243 (message "Property \"%s\" removed from %d entries" property cnt)))))
15245 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15247 (defun org-compute-property-at-point ()
15248 "Compute the property at point.
15249 This looks for an enclosing column format, extracts the operator and
15250 then applies it to the property in the column format's scope."
15251 (interactive)
15252 (unless (org-at-property-p)
15253 (error "Not at a property"))
15254 (let ((prop (org-match-string-no-properties 2)))
15255 (org-columns-get-format-and-top-level)
15256 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15257 (error "No operator defined for property %s" prop))
15258 (org-columns-compute prop)))
15260 (defvar org-property-allowed-value-functions nil
15261 "Hook for functions supplying allowed values for a specific property.
15262 The functions must take a single argument, the name of the property, and
15263 return a flat list of allowed values. If \":ETC\" is one of
15264 the values, this means that these values are intended as defaults for
15265 completion, but that other values should be allowed too.
15266 The functions must return nil if they are not responsible for this
15267 property.")
15269 (defun org-property-get-allowed-values (pom property &optional table)
15270 "Get allowed values for the property PROPERTY.
15271 When TABLE is non-nil, return an alist that can directly be used for
15272 completion."
15273 (let (vals)
15274 (cond
15275 ((equal property "TODO")
15276 (setq vals (org-with-point-at pom
15277 (append org-todo-keywords-1 '("")))))
15278 ((equal property "PRIORITY")
15279 (let ((n org-lowest-priority))
15280 (while (>= n org-highest-priority)
15281 (push (char-to-string n) vals)
15282 (setq n (1- n)))))
15283 ((member property org-special-properties))
15284 ((setq vals (run-hook-with-args-until-success
15285 'org-property-allowed-value-functions property)))
15287 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15288 (when (and vals (string-match "\\S-" vals))
15289 (setq vals (car (read-from-string (concat "(" vals ")"))))
15290 (setq vals (mapcar (lambda (x)
15291 (cond ((stringp x) x)
15292 ((numberp x) (number-to-string x))
15293 ((symbolp x) (symbol-name x))
15294 (t "???")))
15295 vals)))))
15296 (when (member ":ETC" vals)
15297 (setq vals (remove ":ETC" vals))
15298 (org-add-props (car vals) '(org-unrestricted t)))
15299 (if table (mapcar 'list vals) vals)))
15301 (defun org-property-previous-allowed-value (&optional previous)
15302 "Switch to the next allowed value for this property."
15303 (interactive)
15304 (org-property-next-allowed-value t))
15306 (defun org-property-next-allowed-value (&optional previous)
15307 "Switch to the next allowed value for this property."
15308 (interactive)
15309 (unless (org-at-property-p)
15310 (error "Not at a property"))
15311 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15312 (key (match-string 2))
15313 (value (match-string 3))
15314 (allowed (or (org-property-get-allowed-values (point) key)
15315 (and (member value '("[ ]" "[-]" "[X]"))
15316 '("[ ]" "[X]"))))
15317 nval)
15318 (unless allowed
15319 (error "Allowed values for this property have not been defined"))
15320 (if previous (setq allowed (reverse allowed)))
15321 (if (member value allowed)
15322 (setq nval (car (cdr (member value allowed)))))
15323 (setq nval (or nval (car allowed)))
15324 (if (equal nval value)
15325 (error "Only one allowed value for this property"))
15326 (org-at-property-p)
15327 (replace-match (concat " :" key ": " nval) t t)
15328 (org-indent-line)
15329 (beginning-of-line 1)
15330 (skip-chars-forward " \t")
15331 (when (equal prop org-effort-property)
15332 (save-excursion
15333 (org-back-to-heading t)
15334 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15335 (run-hook-with-args 'org-property-changed-functions key nval)))
15337 (defun org-find-olp (path &optional this-buffer)
15338 "Return a marker pointing to the entry at outline path OLP.
15339 If anything goes wrong, throw an error.
15340 You can wrap this call to catch the error like this:
15342 (condition-case msg
15343 (org-mobile-locate-entry (match-string 4))
15344 (error (nth 1 msg)))
15346 The return value will then be either a string with the error message,
15347 or a marker if everything is OK.
15349 If THIS-BUFFER is set, the outline path does not contain a file,
15350 only headings."
15351 (let* ((file (if this-buffer buffer-file-name (pop path)))
15352 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15353 (level 1)
15354 (lmin 1)
15355 (lmax 1)
15356 limit re end found pos heading cnt flevel)
15357 (unless buffer (error "File not found :%s" file))
15358 (with-current-buffer buffer
15359 (save-excursion
15360 (save-restriction
15361 (widen)
15362 (setq limit (point-max))
15363 (goto-char (point-min))
15364 (while (setq heading (pop path))
15365 (setq re (format org-complex-heading-regexp-format
15366 (regexp-quote heading)))
15367 (setq cnt 0 pos (point))
15368 (while (re-search-forward re end t)
15369 (setq level (- (match-end 1) (match-beginning 1)))
15370 (if (and (>= level lmin) (<= level lmax))
15371 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15372 (when (= cnt 0) (error "Heading not found on level %d: %s"
15373 lmax heading))
15374 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15375 lmax heading))
15376 (goto-char found)
15377 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15378 (setq end (save-excursion (org-end-of-subtree t t))))
15379 (when (org-at-heading-p)
15380 (point-marker)))))))
15382 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15383 "Find node HEADING in BUFFER.
15384 Return a marker to the heading if it was found, or nil if not.
15385 If POS-ONLY is set, return just the position instead of a marker.
15387 The heading text must match exact, but it may have a TODO keyword,
15388 a priority cookie and tags in the standard locations."
15389 (with-current-buffer (or buffer (current-buffer))
15390 (save-excursion
15391 (save-restriction
15392 (widen)
15393 (goto-char (point-min))
15394 (let (case-fold-search)
15395 (if (re-search-forward
15396 (format org-complex-heading-regexp-format
15397 (regexp-quote heading)) nil t)
15398 (if pos-only
15399 (match-beginning 0)
15400 (move-marker (make-marker) (match-beginning 0)))))))))
15402 (defun org-find-exact-heading-in-directory (heading &optional dir)
15403 "Find Org node headline HEADING in all .org files in directory DIR.
15404 When the target headline is found, return a marker to this location."
15405 (let ((files (directory-files (or dir default-directory)
15406 nil "\\`[^.#].*\\.org\\'"))
15407 file visiting m buffer)
15408 (catch 'found
15409 (while (setq file (pop files))
15410 (message "trying %s" file)
15411 (setq visiting (org-find-base-buffer-visiting file))
15412 (setq buffer (or visiting (find-file-noselect file)))
15413 (setq m (org-find-exact-headline-in-buffer
15414 heading buffer))
15415 (when (and (not m) (not visiting)) (kill-buffer buffer))
15416 (and m (throw 'found m))))))
15418 (defun org-find-entry-with-id (ident)
15419 "Locate the entry that contains the ID property with exact value IDENT.
15420 IDENT can be a string, a symbol or a number, this function will search for
15421 the string representation of it.
15422 Return the position where this entry starts, or nil if there is no such entry."
15423 (interactive "sID: ")
15424 (let ((id (cond
15425 ((stringp ident) ident)
15426 ((symbol-name ident) (symbol-name ident))
15427 ((numberp ident) (number-to-string ident))
15428 (t (error "IDENT %s must be a string, symbol or number" ident))))
15429 (case-fold-search nil))
15430 (save-excursion
15431 (save-restriction
15432 (widen)
15433 (goto-char (point-min))
15434 (when (re-search-forward
15435 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15436 nil t)
15437 (org-back-to-heading t)
15438 (point))))))
15440 ;;;; Timestamps
15442 (defvar org-last-changed-timestamp nil)
15443 (defvar org-last-inserted-timestamp nil
15444 "The last time stamp inserted with `org-insert-time-stamp'.")
15445 (defvar org-time-was-given) ; dynamically scoped parameter
15446 (defvar org-end-time-was-given) ; dynamically scoped parameter
15447 (defvar org-ts-what) ; dynamically scoped parameter
15449 (defun org-time-stamp (arg &optional inactive)
15450 "Prompt for a date/time and insert a time stamp.
15451 If the user specifies a time like HH:MM or if this command is
15452 called with at least one prefix argument, the time stamp contains
15453 the date and the time. Otherwise, only the date is be included.
15455 All parts of a date not specified by the user is filled in from
15456 the current date/time. So if you just press return without
15457 typing anything, the time stamp will represent the current
15458 date/time.
15460 If there is already a timestamp at the cursor, it will be
15461 modified.
15463 With two universal prefix arguments, insert an active timestamp
15464 with the current time without prompting the user."
15465 (interactive "P")
15466 (let* ((ts nil)
15467 (default-time
15468 ;; Default time is either today, or, when entering a range,
15469 ;; the range start.
15470 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15471 (save-excursion
15472 (re-search-backward
15473 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15474 (- (point) 20) t)))
15475 (apply 'encode-time (org-parse-time-string (match-string 1)))
15476 (current-time)))
15477 (default-input (and ts (org-get-compact-tod ts)))
15478 (repeater (save-excursion
15479 (save-match-data
15480 (beginning-of-line)
15481 (when (re-search-forward
15482 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15483 (save-excursion (progn (end-of-line) (point))) t)
15484 (match-string 0)))))
15485 org-time-was-given org-end-time-was-given time)
15486 (cond
15487 ((and (org-at-timestamp-p t)
15488 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15489 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15490 (insert "--")
15491 (setq time (let ((this-command this-command))
15492 (org-read-date arg 'totime nil nil
15493 default-time default-input inactive)))
15494 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15495 ((org-at-timestamp-p t)
15496 (setq time (let ((this-command this-command))
15497 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15498 (when (org-at-timestamp-p t) ; just to get the match data
15499 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15500 (replace-match "")
15501 (setq org-last-changed-timestamp
15502 (org-insert-time-stamp
15503 time (or org-time-was-given arg)
15504 inactive nil nil (list org-end-time-was-given)))
15505 (when repeater (goto-char (1- (point))) (insert " " repeater)
15506 (setq org-last-changed-timestamp
15507 (concat (substring org-last-inserted-timestamp 0 -1)
15508 " " repeater ">"))))
15509 (message "Timestamp updated"))
15510 ((equal arg '(16))
15511 (org-insert-time-stamp (current-time) t))
15513 (setq time (let ((this-command this-command))
15514 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15515 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15516 nil nil (list org-end-time-was-given))))))
15518 ;; FIXME: can we use this for something else, like computing time differences?
15519 (defun org-get-compact-tod (s)
15520 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15521 (let* ((t1 (match-string 1 s))
15522 (h1 (string-to-number (match-string 2 s)))
15523 (m1 (string-to-number (match-string 3 s)))
15524 (t2 (and (match-end 4) (match-string 5 s)))
15525 (h2 (and t2 (string-to-number (match-string 6 s))))
15526 (m2 (and t2 (string-to-number (match-string 7 s))))
15527 dh dm)
15528 (if (not t2)
15530 (setq dh (- h2 h1) dm (- m2 m1))
15531 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15532 (concat t1 "+" (number-to-string dh)
15533 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15535 (defun org-time-stamp-inactive (&optional arg)
15536 "Insert an inactive time stamp.
15537 An inactive time stamp is enclosed in square brackets instead of angle
15538 brackets. It is inactive in the sense that it does not trigger agenda entries,
15539 does not link to the calendar and cannot be changed with the S-cursor keys.
15540 So these are more for recording a certain time/date."
15541 (interactive "P")
15542 (org-time-stamp arg 'inactive))
15544 (defvar org-date-ovl (make-overlay 1 1))
15545 (overlay-put org-date-ovl 'face 'org-date-selected)
15546 (org-detach-overlay org-date-ovl)
15548 (defvar org-ans1) ; dynamically scoped parameter
15549 (defvar org-ans2) ; dynamically scoped parameter
15551 (defvar org-plain-time-of-day-regexp) ; defined below
15553 (defvar org-overriding-default-time nil) ; dynamically scoped
15554 (defvar org-read-date-overlay nil)
15555 (defvar org-dcst nil) ; dynamically scoped
15556 (defvar org-read-date-history nil)
15557 (defvar org-read-date-final-answer nil)
15558 (defvar org-read-date-analyze-futurep nil)
15559 (defvar org-read-date-analyze-forced-year nil)
15560 (defvar org-read-date-inactive)
15562 (defun org-read-date (&optional org-with-time to-time from-string prompt
15563 default-time default-input inactive)
15564 "Read a date, possibly a time, and make things smooth for the user.
15565 The prompt will suggest to enter an ISO date, but you can also enter anything
15566 which will at least partially be understood by `parse-time-string'.
15567 Unrecognized parts of the date will default to the current day, month, year,
15568 hour and minute. If this command is called to replace a timestamp at point,
15569 or to enter the second timestamp of a range, the default time is taken
15570 from the existing stamp. Furthermore, the command prefers the future,
15571 so if you are giving a date where the year is not given, and the day-month
15572 combination is already past in the current year, it will assume you
15573 mean next year. For details, see the manual. A few examples:
15575 3-2-5 --> 2003-02-05
15576 feb 15 --> currentyear-02-15
15577 2/15 --> currentyear-02-15
15578 sep 12 9 --> 2009-09-12
15579 12:45 --> today 12:45
15580 22 sept 0:34 --> currentyear-09-22 0:34
15581 12 --> currentyear-currentmonth-12
15582 Fri --> nearest Friday (today or later)
15583 etc.
15585 Furthermore you can specify a relative date by giving, as the *first* thing
15586 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15587 change in days weeks, months, years.
15588 With a single plus or minus, the date is relative to today. With a double
15589 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15590 +4d --> four days from today
15591 +4 --> same as above
15592 +2w --> two weeks from today
15593 ++5 --> five days from default date
15595 The function understands only English month and weekday abbreviations.
15597 While prompting, a calendar is popped up - you can also select the
15598 date with the mouse (button 1). The calendar shows a period of three
15599 months. To scroll it to other months, use the keys `>' and `<'.
15600 If you don't like the calendar, turn it off with
15601 \(setq org-read-date-popup-calendar nil)
15603 With optional argument TO-TIME, the date will immediately be converted
15604 to an internal time.
15605 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15606 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15607 still enter a time, and this function will inform the calling routine
15608 about this change. The calling routine may then choose to change the
15609 format used to insert the time stamp into the buffer to include the time.
15610 With optional argument FROM-STRING, read from this string instead from
15611 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15612 the time/date that is used for everything that is not specified by the
15613 user."
15614 (require 'parse-time)
15615 (let* ((org-time-stamp-rounding-minutes
15616 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15617 (org-dcst org-display-custom-times)
15618 (ct (org-current-time))
15619 (org-def (or org-overriding-default-time default-time ct))
15620 (org-defdecode (decode-time org-def))
15621 (dummy (progn
15622 (when (< (nth 2 org-defdecode) org-extend-today-until)
15623 (setcar (nthcdr 2 org-defdecode) -1)
15624 (setcar (nthcdr 1 org-defdecode) 59)
15625 (setq org-def (apply 'encode-time org-defdecode)
15626 org-defdecode (decode-time org-def)))))
15627 (mouse-autoselect-window nil) ; Don't let the mouse jump
15628 (calendar-frame-setup nil)
15629 (calendar-setup nil)
15630 (calendar-move-hook nil)
15631 (calendar-view-diary-initially-flag nil)
15632 (calendar-view-holidays-initially-flag nil)
15633 (timestr (format-time-string
15634 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15635 (prompt (concat (if prompt (concat prompt " ") "")
15636 (format "Date+time [%s]: " timestr)))
15637 ans (org-ans0 "") org-ans1 org-ans2 final)
15639 (cond
15640 (from-string (setq ans from-string))
15641 (org-read-date-popup-calendar
15642 (save-excursion
15643 (save-window-excursion
15644 (calendar)
15645 (org-eval-in-calendar '(setq cursor-type nil) t)
15646 (unwind-protect
15647 (progn
15648 (calendar-forward-day (- (time-to-days org-def)
15649 (calendar-absolute-from-gregorian
15650 (calendar-current-date))))
15651 (org-eval-in-calendar nil t)
15652 (let* ((old-map (current-local-map))
15653 (map (copy-keymap calendar-mode-map))
15654 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15655 (org-defkey map (kbd "RET") 'org-calendar-select)
15656 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15657 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15658 (org-defkey minibuffer-local-map [(meta shift left)]
15659 (lambda () (interactive)
15660 (org-eval-in-calendar '(calendar-backward-month 1))))
15661 (org-defkey minibuffer-local-map [(meta shift right)]
15662 (lambda () (interactive)
15663 (org-eval-in-calendar '(calendar-forward-month 1))))
15664 (org-defkey minibuffer-local-map [(meta shift up)]
15665 (lambda () (interactive)
15666 (org-eval-in-calendar '(calendar-backward-year 1))))
15667 (org-defkey minibuffer-local-map [(meta shift down)]
15668 (lambda () (interactive)
15669 (org-eval-in-calendar '(calendar-forward-year 1))))
15670 (org-defkey minibuffer-local-map [?\e (shift left)]
15671 (lambda () (interactive)
15672 (org-eval-in-calendar '(calendar-backward-month 1))))
15673 (org-defkey minibuffer-local-map [?\e (shift right)]
15674 (lambda () (interactive)
15675 (org-eval-in-calendar '(calendar-forward-month 1))))
15676 (org-defkey minibuffer-local-map [?\e (shift up)]
15677 (lambda () (interactive)
15678 (org-eval-in-calendar '(calendar-backward-year 1))))
15679 (org-defkey minibuffer-local-map [?\e (shift down)]
15680 (lambda () (interactive)
15681 (org-eval-in-calendar '(calendar-forward-year 1))))
15682 (org-defkey minibuffer-local-map [(shift up)]
15683 (lambda () (interactive)
15684 (org-eval-in-calendar '(calendar-backward-week 1))))
15685 (org-defkey minibuffer-local-map [(shift down)]
15686 (lambda () (interactive)
15687 (org-eval-in-calendar '(calendar-forward-week 1))))
15688 (org-defkey minibuffer-local-map [(shift left)]
15689 (lambda () (interactive)
15690 (org-eval-in-calendar '(calendar-backward-day 1))))
15691 (org-defkey minibuffer-local-map [(shift right)]
15692 (lambda () (interactive)
15693 (org-eval-in-calendar '(calendar-forward-day 1))))
15694 (org-defkey minibuffer-local-map ">"
15695 (lambda () (interactive)
15696 (org-eval-in-calendar '(scroll-calendar-left 1))))
15697 (org-defkey minibuffer-local-map "<"
15698 (lambda () (interactive)
15699 (org-eval-in-calendar '(scroll-calendar-right 1))))
15700 (org-defkey minibuffer-local-map "\C-v"
15701 (lambda () (interactive)
15702 (org-eval-in-calendar
15703 '(calendar-scroll-left-three-months 1))))
15704 (org-defkey minibuffer-local-map "\M-v"
15705 (lambda () (interactive)
15706 (org-eval-in-calendar
15707 '(calendar-scroll-right-three-months 1))))
15708 (run-hooks 'org-read-date-minibuffer-setup-hook)
15709 (unwind-protect
15710 (progn
15711 (use-local-map map)
15712 (setq org-read-date-inactive inactive)
15713 (add-hook 'post-command-hook 'org-read-date-display)
15714 (setq org-ans0 (read-string prompt default-input
15715 'org-read-date-history nil))
15716 ;; org-ans0: from prompt
15717 ;; org-ans1: from mouse click
15718 ;; org-ans2: from calendar motion
15719 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15720 (remove-hook 'post-command-hook 'org-read-date-display)
15721 (use-local-map old-map)
15722 (when org-read-date-overlay
15723 (delete-overlay org-read-date-overlay)
15724 (setq org-read-date-overlay nil)))))
15725 (bury-buffer "*Calendar*")))))
15727 (t ; Naked prompt only
15728 (unwind-protect
15729 (setq ans (read-string prompt default-input
15730 'org-read-date-history timestr))
15731 (when org-read-date-overlay
15732 (delete-overlay org-read-date-overlay)
15733 (setq org-read-date-overlay nil)))))
15735 (setq final (org-read-date-analyze ans org-def org-defdecode))
15737 (when org-read-date-analyze-forced-year
15738 (message "Year was forced into %s"
15739 (if org-read-date-force-compatible-dates
15740 "compatible range (1970-2037)"
15741 "range representable on this machine"))
15742 (ding))
15744 ;; One round trip to get rid of 34th of August and stuff like that....
15745 (setq final (decode-time (apply 'encode-time final)))
15747 (setq org-read-date-final-answer ans)
15749 (if to-time
15750 (apply 'encode-time final)
15751 (if (and (boundp 'org-time-was-given) org-time-was-given)
15752 (format "%04d-%02d-%02d %02d:%02d"
15753 (nth 5 final) (nth 4 final) (nth 3 final)
15754 (nth 2 final) (nth 1 final))
15755 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15757 (defvar org-def)
15758 (defvar org-defdecode)
15759 (defvar org-with-time)
15760 (defun org-read-date-display ()
15761 "Display the current date prompt interpretation in the minibuffer."
15762 (when org-read-date-display-live
15763 (when org-read-date-overlay
15764 (delete-overlay org-read-date-overlay))
15765 (when (minibufferp (current-buffer))
15766 (save-excursion
15767 (end-of-line 1)
15768 (while (not (equal (buffer-substring
15769 (max (point-min) (- (point) 4)) (point))
15770 " "))
15771 (insert " ")))
15772 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15773 " " (or org-ans1 org-ans2)))
15774 (org-end-time-was-given nil)
15775 (f (org-read-date-analyze ans org-def org-defdecode))
15776 (fmts (if org-dcst
15777 org-time-stamp-custom-formats
15778 org-time-stamp-formats))
15779 (fmt (if (or org-with-time
15780 (and (boundp 'org-time-was-given) org-time-was-given))
15781 (cdr fmts)
15782 (car fmts)))
15783 (txt (format-time-string fmt (apply 'encode-time f)))
15784 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15785 (txt (concat "=> " txt)))
15786 (when (and org-end-time-was-given
15787 (string-match org-plain-time-of-day-regexp txt))
15788 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15789 org-end-time-was-given
15790 (substring txt (match-end 0)))))
15791 (when org-read-date-analyze-futurep
15792 (setq txt (concat txt " (=>F)")))
15793 (setq org-read-date-overlay
15794 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15795 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15797 (defun org-read-date-analyze (ans org-def org-defdecode)
15798 "Analyze the combined answer of the date prompt."
15799 ;; FIXME: cleanup and comment
15800 (let ((nowdecode (decode-time (current-time)))
15801 delta deltan deltaw deltadef year month day
15802 hour minute second wday pm h2 m2 tl wday1
15803 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15804 (setq org-read-date-analyze-futurep nil
15805 org-read-date-analyze-forced-year nil)
15806 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15807 (setq ans "+0"))
15809 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15810 (setq ans (replace-match "" t t ans)
15811 deltan (car delta)
15812 deltaw (nth 1 delta)
15813 deltadef (nth 2 delta)))
15815 ;; Check if there is an iso week date in there. If yes, store the
15816 ;; info and postpone interpreting it until the rest of the parsing
15817 ;; is done.
15818 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15819 (setq iso-year (if (match-end 1)
15820 (org-small-year-to-year
15821 (string-to-number (match-string 1 ans))))
15822 iso-weekday (if (match-end 3)
15823 (string-to-number (match-string 3 ans)))
15824 iso-week (string-to-number (match-string 2 ans)))
15825 (setq ans (replace-match "" t t ans)))
15827 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15828 (when (string-match
15829 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15830 (setq year (if (match-end 2)
15831 (string-to-number (match-string 2 ans))
15832 (progn (setq kill-year t)
15833 (string-to-number (format-time-string "%Y"))))
15834 month (string-to-number (match-string 3 ans))
15835 day (string-to-number (match-string 4 ans)))
15836 (if (< year 100) (setq year (+ 2000 year)))
15837 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15838 t nil ans)))
15840 ;; Help matching dotted european dates
15841 (when (string-match
15842 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15843 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15844 (setq kill-year t)
15845 (string-to-number (format-time-string "%Y")))
15846 day (string-to-number (match-string 1 ans))
15847 month (string-to-number (match-string 2 ans))
15848 ans (replace-match (format "%04d-%02d-%02d" year month day)
15849 t nil ans)))
15851 ;; Help matching american dates, like 5/30 or 5/30/7
15852 (when (string-match
15853 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15854 (setq year (if (match-end 4)
15855 (string-to-number (match-string 4 ans))
15856 (progn (setq kill-year t)
15857 (string-to-number (format-time-string "%Y"))))
15858 month (string-to-number (match-string 1 ans))
15859 day (string-to-number (match-string 2 ans)))
15860 (if (< year 100) (setq year (+ 2000 year)))
15861 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15862 t nil ans)))
15863 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15864 ;; If there is a time with am/pm, and *no* time without it, we convert
15865 ;; so that matching will be successful.
15866 (loop for i from 1 to 2 do ; twice, for end time as well
15867 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15868 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15869 (setq hour (string-to-number (match-string 1 ans))
15870 minute (if (match-end 3)
15871 (string-to-number (match-string 3 ans))
15873 pm (equal ?p
15874 (string-to-char (downcase (match-string 4 ans)))))
15875 (if (and (= hour 12) (not pm))
15876 (setq hour 0)
15877 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15878 (setq ans (replace-match (format "%02d:%02d" hour minute)
15879 t t ans))))
15881 ;; Check if a time range is given as a duration
15882 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15883 (setq hour (string-to-number (match-string 1 ans))
15884 h2 (+ hour (string-to-number (match-string 3 ans)))
15885 minute (string-to-number (match-string 2 ans))
15886 m2 (+ minute (if (match-end 5) (string-to-number
15887 (match-string 5 ans))0)))
15888 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15889 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15890 t t ans)))
15892 ;; Check if there is a time range
15893 (when (boundp 'org-end-time-was-given)
15894 (setq org-time-was-given nil)
15895 (when (and (string-match org-plain-time-of-day-regexp ans)
15896 (match-end 8))
15897 (setq org-end-time-was-given (match-string 8 ans))
15898 (setq ans (concat (substring ans 0 (match-beginning 7))
15899 (substring ans (match-end 7))))))
15901 (setq tl (parse-time-string ans)
15902 day (or (nth 3 tl) (nth 3 org-defdecode))
15903 month (or (nth 4 tl)
15904 (if (and org-read-date-prefer-future
15905 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15906 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15907 (nth 4 org-defdecode)))
15908 year (or (and (not kill-year) (nth 5 tl))
15909 (if (and org-read-date-prefer-future
15910 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15911 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15912 (nth 5 org-defdecode)))
15913 hour (or (nth 2 tl) (nth 2 org-defdecode))
15914 minute (or (nth 1 tl) (nth 1 org-defdecode))
15915 second (or (nth 0 tl) 0)
15916 wday (nth 6 tl))
15918 (when (and (eq org-read-date-prefer-future 'time)
15919 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15920 (equal day (nth 3 nowdecode))
15921 (equal month (nth 4 nowdecode))
15922 (equal year (nth 5 nowdecode))
15923 (nth 2 tl)
15924 (or (< (nth 2 tl) (nth 2 nowdecode))
15925 (and (= (nth 2 tl) (nth 2 nowdecode))
15926 (nth 1 tl)
15927 (< (nth 1 tl) (nth 1 nowdecode)))))
15928 (setq day (1+ day)
15929 futurep t))
15931 ;; Special date definitions below
15932 (cond
15933 (iso-week
15934 ;; There was an iso week
15935 (require 'cal-iso)
15936 (setq futurep nil)
15937 (setq year (or iso-year year)
15938 day (or iso-weekday wday 1)
15939 wday nil ; to make sure that the trigger below does not match
15940 iso-date (calendar-gregorian-from-absolute
15941 (calendar-absolute-from-iso
15942 (list iso-week day year))))
15943 ; FIXME: Should we also push ISO weeks into the future?
15944 ; (when (and org-read-date-prefer-future
15945 ; (not iso-year)
15946 ; (< (calendar-absolute-from-gregorian iso-date)
15947 ; (time-to-days (current-time))))
15948 ; (setq year (1+ year)
15949 ; iso-date (calendar-gregorian-from-absolute
15950 ; (calendar-absolute-from-iso
15951 ; (list iso-week day year)))))
15952 (setq month (car iso-date)
15953 year (nth 2 iso-date)
15954 day (nth 1 iso-date)))
15955 (deltan
15956 (setq futurep nil)
15957 (unless deltadef
15958 (let ((now (decode-time (current-time))))
15959 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15960 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15961 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15962 ((equal deltaw "m") (setq month (+ month deltan)))
15963 ((equal deltaw "y") (setq year (+ year deltan)))))
15964 ((and wday (not (nth 3 tl)))
15965 ;; Weekday was given, but no day, so pick that day in the week
15966 ;; on or after the derived date.
15967 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15968 (unless (equal wday wday1)
15969 (setq day (+ day (% (- wday wday1 -7) 7))))))
15970 (if (and (boundp 'org-time-was-given)
15971 (nth 2 tl))
15972 (setq org-time-was-given t))
15973 (if (< year 100) (setq year (+ 2000 year)))
15974 ;; Check of the date is representable
15975 (if org-read-date-force-compatible-dates
15976 (progn
15977 (if (< year 1970)
15978 (setq year 1970 org-read-date-analyze-forced-year t))
15979 (if (> year 2037)
15980 (setq year 2037 org-read-date-analyze-forced-year t)))
15981 (condition-case nil
15982 (ignore (encode-time second minute hour day month year))
15983 (error
15984 (setq year (nth 5 org-defdecode))
15985 (setq org-read-date-analyze-forced-year t))))
15986 (setq org-read-date-analyze-futurep futurep)
15987 (list second minute hour day month year)))
15989 (defvar parse-time-weekdays)
15990 (defun org-read-date-get-relative (s today default)
15991 "Check string S for special relative date string.
15992 TODAY and DEFAULT are internal times, for today and for a default.
15993 Return shift list (N what def-flag)
15994 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15995 N is the number of WHATs to shift.
15996 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15997 the DEFAULT date rather than TODAY."
15998 (require 'parse-time)
15999 (when (and
16000 (string-match
16001 (concat
16002 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16003 "\\([0-9]+\\)?"
16004 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16005 "\\([ \t]\\|$\\)") s)
16006 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16007 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16008 (string-to-char (substring (match-string 1 s) -1))
16009 ?+))
16010 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16011 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16012 (what (if (match-end 3) (match-string 3 s) "d"))
16013 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16014 (date (if rel default today))
16015 (wday (nth 6 (decode-time date)))
16016 delta)
16017 (if wday1
16018 (progn
16019 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16020 (if (= dir ?-) (setq delta (- delta 7)))
16021 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16022 (list delta "d" rel))
16023 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16025 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16026 "Turn a user-specified date into the internal representation.
16027 The internal representation needed by the calendar is (month day year).
16028 This is a wrapper to handle the brain-dead convention in calendar that
16029 user function argument order change dependent on argument order."
16030 (if (boundp 'calendar-date-style)
16031 (cond
16032 ((eq calendar-date-style 'american)
16033 (list arg1 arg2 arg3))
16034 ((eq calendar-date-style 'european)
16035 (list arg2 arg1 arg3))
16036 ((eq calendar-date-style 'iso)
16037 (list arg2 arg3 arg1)))
16038 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16039 (if (org-bound-and-true-p european-calendar-style)
16040 (list arg2 arg1 arg3)
16041 (list arg1 arg2 arg3)))))
16043 (defun org-eval-in-calendar (form &optional keepdate)
16044 "Eval FORM in the calendar window and return to current window.
16045 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16046 otherwise stick to the current value of `org-ans2'."
16047 (let ((sf (selected-frame))
16048 (sw (selected-window)))
16049 (select-window (get-buffer-window "*Calendar*" t))
16050 (eval form)
16051 (when (and (not keepdate) (calendar-cursor-to-date))
16052 (let* ((date (calendar-cursor-to-date))
16053 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16054 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16055 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16056 (select-window sw)
16057 (org-select-frame-set-input-focus sf)))
16059 (defun org-calendar-select ()
16060 "Return to `org-read-date' with the date currently selected.
16061 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16062 (interactive)
16063 (when (calendar-cursor-to-date)
16064 (let* ((date (calendar-cursor-to-date))
16065 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16066 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16067 (if (active-minibuffer-window) (exit-minibuffer))))
16069 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16070 "Insert a date stamp for the date given by the internal TIME.
16071 WITH-HM means use the stamp format that includes the time of the day.
16072 INACTIVE means use square brackets instead of angular ones, so that the
16073 stamp will not contribute to the agenda.
16074 PRE and POST are optional strings to be inserted before and after the
16075 stamp.
16076 The command returns the inserted time stamp."
16077 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16078 stamp)
16079 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16080 (insert-before-markers (or pre ""))
16081 (when (listp extra)
16082 (setq extra (car extra))
16083 (if (and (stringp extra)
16084 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16085 (setq extra (format "-%02d:%02d"
16086 (string-to-number (match-string 1 extra))
16087 (string-to-number (match-string 2 extra))))
16088 (setq extra nil)))
16089 (when extra
16090 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16091 (insert-before-markers (setq stamp (format-time-string fmt time)))
16092 (insert-before-markers (or post ""))
16093 (setq org-last-inserted-timestamp stamp)))
16095 (defun org-toggle-time-stamp-overlays ()
16096 "Toggle the use of custom time stamp formats."
16097 (interactive)
16098 (setq org-display-custom-times (not org-display-custom-times))
16099 (unless org-display-custom-times
16100 (let ((p (point-min)) (bmp (buffer-modified-p)))
16101 (while (setq p (next-single-property-change p 'display))
16102 (if (and (get-text-property p 'display)
16103 (eq (get-text-property p 'face) 'org-date))
16104 (remove-text-properties
16105 p (setq p (next-single-property-change p 'display))
16106 '(display t))))
16107 (set-buffer-modified-p bmp)))
16108 (if (featurep 'xemacs)
16109 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16110 (org-restart-font-lock)
16111 (setq org-table-may-need-update t)
16112 (if org-display-custom-times
16113 (message "Time stamps are overlaid with custom format")
16114 (message "Time stamp overlays removed")))
16116 (defun org-display-custom-time (beg end)
16117 "Overlay modified time stamp format over timestamp between BEG and END."
16118 (let* ((ts (buffer-substring beg end))
16119 t1 w1 with-hm tf time str w2 (off 0))
16120 (save-match-data
16121 (setq t1 (org-parse-time-string ts t))
16122 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16123 (setq off (- (match-end 0) (match-beginning 0)))))
16124 (setq end (- end off))
16125 (setq w1 (- end beg)
16126 with-hm (and (nth 1 t1) (nth 2 t1))
16127 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16128 time (org-fix-decoded-time t1)
16129 str (org-add-props
16130 (format-time-string
16131 (substring tf 1 -1) (apply 'encode-time time))
16132 nil 'mouse-face 'highlight)
16133 w2 (length str))
16134 (if (not (= w2 w1))
16135 (add-text-properties (1+ beg) (+ 2 beg)
16136 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16137 (if (featurep 'xemacs)
16138 (progn
16139 (put-text-property beg end 'invisible t)
16140 (put-text-property beg end 'end-glyph (make-glyph str)))
16141 (put-text-property beg end 'display str))))
16143 (defun org-translate-time (string)
16144 "Translate all timestamps in STRING to custom format.
16145 But do this only if the variable `org-display-custom-times' is set."
16146 (when org-display-custom-times
16147 (save-match-data
16148 (let* ((start 0)
16149 (re org-ts-regexp-both)
16150 t1 with-hm inactive tf time str beg end)
16151 (while (setq start (string-match re string start))
16152 (setq beg (match-beginning 0)
16153 end (match-end 0)
16154 t1 (save-match-data
16155 (org-parse-time-string (substring string beg end) t))
16156 with-hm (and (nth 1 t1) (nth 2 t1))
16157 inactive (equal (substring string beg (1+ beg)) "[")
16158 tf (funcall (if with-hm 'cdr 'car)
16159 org-time-stamp-custom-formats)
16160 time (org-fix-decoded-time t1)
16161 str (format-time-string
16162 (concat
16163 (if inactive "[" "<") (substring tf 1 -1)
16164 (if inactive "]" ">"))
16165 (apply 'encode-time time))
16166 string (replace-match str t t string)
16167 start (+ start (length str)))))))
16168 string)
16170 (defun org-fix-decoded-time (time)
16171 "Set 0 instead of nil for the first 6 elements of time.
16172 Don't touch the rest."
16173 (let ((n 0))
16174 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16176 (org-define-obsolete-function-alias
16177 'org-days-to-time 'org-time-stamp-to-now "24.3")
16179 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16180 "Difference between TIMESTAMP-STRING and now in days.
16181 If SECONDS is non-nil, return the difference in seconds."
16182 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16183 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16184 (funcall fdiff (current-time)))))
16186 (defun org-deadline-close (timestamp-string &optional ndays)
16187 "Is the time in TIMESTAMP-STRING close to the current date?"
16188 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16189 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16190 (not (org-entry-is-done-p))))
16192 (defun org-get-wdays (ts)
16193 "Get the deadline lead time appropriate for timestring TS."
16194 (cond
16195 ((<= org-deadline-warning-days 0)
16196 ;; 0 or negative, enforce this value no matter what
16197 (- org-deadline-warning-days))
16198 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16199 ;; lead time is specified.
16200 (floor (* (string-to-number (match-string 1 ts))
16201 (cdr (assoc (match-string 2 ts)
16202 '(("d" . 1) ("w" . 7)
16203 ("m" . 30.4) ("y" . 365.25)))))))
16204 ;; go for the default.
16205 (t org-deadline-warning-days)))
16207 (defun org-calendar-select-mouse (ev)
16208 "Return to `org-read-date' with the date currently selected.
16209 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16210 (interactive "e")
16211 (mouse-set-point ev)
16212 (when (calendar-cursor-to-date)
16213 (let* ((date (calendar-cursor-to-date))
16214 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16215 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16216 (if (active-minibuffer-window) (exit-minibuffer))))
16218 (defun org-check-deadlines (ndays)
16219 "Check if there are any deadlines due or past due.
16220 A deadline is considered due if it happens within `org-deadline-warning-days'
16221 days from today's date. If the deadline appears in an entry marked DONE,
16222 it is not shown. The prefix arg NDAYS can be used to test that many
16223 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16224 (interactive "P")
16225 (let* ((org-warn-days
16226 (cond
16227 ((equal ndays '(4)) 100000)
16228 (ndays (prefix-numeric-value ndays))
16229 (t (abs org-deadline-warning-days))))
16230 (case-fold-search nil)
16231 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16232 (callback
16233 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16235 (message "%d deadlines past-due or due within %d days"
16236 (org-occur regexp nil callback)
16237 org-warn-days)))
16239 (defsubst org-re-timestamp (type)
16240 "Return a regexp for timestamp TYPE.
16241 Allowed values for TYPE are:
16243 all: all timestamps
16244 active: only active timestamps (<...>)
16245 inactive: only inactive timestamps ([...])
16246 scheduled: only scheduled timestamps
16247 deadline: only deadline timestamps
16249 When TYPE is nil, fall back on returning a regexp that matches
16250 both scheduled and deadline timestamps."
16251 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16252 ((eq type 'active) org-ts-regexp)
16253 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16254 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16255 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16256 ((eq type 'scheduled-or-deadline)
16257 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16259 (defun org-check-before-date (date)
16260 "Check if there are deadlines or scheduled entries before DATE."
16261 (interactive (list (org-read-date)))
16262 (let ((case-fold-search nil)
16263 (regexp (org-re-timestamp org-ts-type))
16264 (callback
16265 (lambda () (time-less-p
16266 (org-time-string-to-time (match-string 1))
16267 (org-time-string-to-time date)))))
16268 (message "%d entries before %s"
16269 (org-occur regexp nil callback) date)))
16271 (defun org-check-after-date (date)
16272 "Check if there are deadlines or scheduled entries after DATE."
16273 (interactive (list (org-read-date)))
16274 (let ((case-fold-search nil)
16275 (regexp (org-re-timestamp org-ts-type))
16276 (callback
16277 (lambda () (not
16278 (time-less-p
16279 (org-time-string-to-time (match-string 1))
16280 (org-time-string-to-time date))))))
16281 (message "%d entries after %s"
16282 (org-occur regexp nil callback) date)))
16284 (defun org-check-dates-range (start-date end-date)
16285 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16286 (interactive (list (org-read-date nil nil nil "Range starts")
16287 (org-read-date nil nil nil "Range end")))
16288 (let ((case-fold-search nil)
16289 (regexp (org-re-timestamp org-ts-type))
16290 (callback
16291 (lambda ()
16292 (let ((match (match-string 1)))
16293 (and
16294 (not (time-less-p
16295 (org-time-string-to-time match)
16296 (org-time-string-to-time start-date)))
16297 (time-less-p
16298 (org-time-string-to-time match)
16299 (org-time-string-to-time end-date)))))))
16300 (message "%d entries between %s and %s"
16301 (org-occur regexp nil callback) start-date end-date)))
16303 (defun org-evaluate-time-range (&optional to-buffer)
16304 "Evaluate a time range by computing the difference between start and end.
16305 Normally the result is just printed in the echo area, but with prefix arg
16306 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16307 If the time range is actually in a table, the result is inserted into the
16308 next column.
16309 For time difference computation, a year is assumed to be exactly 365
16310 days in order to avoid rounding problems."
16311 (interactive "P")
16313 (org-clock-update-time-maybe)
16314 (save-excursion
16315 (unless (org-at-date-range-p t)
16316 (goto-char (point-at-bol))
16317 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16318 (if (not (org-at-date-range-p t))
16319 (error "Not at a time-stamp range, and none found in current line")))
16320 (let* ((ts1 (match-string 1))
16321 (ts2 (match-string 2))
16322 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16323 (match-end (match-end 0))
16324 (time1 (org-time-string-to-time ts1))
16325 (time2 (org-time-string-to-time ts2))
16326 (t1 (org-float-time time1))
16327 (t2 (org-float-time time2))
16328 (diff (abs (- t2 t1)))
16329 (negative (< (- t2 t1) 0))
16330 ;; (ys (floor (* 365 24 60 60)))
16331 (ds (* 24 60 60))
16332 (hs (* 60 60))
16333 (fy "%dy %dd %02d:%02d")
16334 (fy1 "%dy %dd")
16335 (fd "%dd %02d:%02d")
16336 (fd1 "%dd")
16337 (fh "%02d:%02d")
16338 y d h m align)
16339 (if havetime
16340 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16342 d (floor (/ diff ds)) diff (mod diff ds)
16343 h (floor (/ diff hs)) diff (mod diff hs)
16344 m (floor (/ diff 60)))
16345 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16347 d (floor (+ (/ diff ds) 0.5))
16348 h 0 m 0))
16349 (if (not to-buffer)
16350 (message "%s" (org-make-tdiff-string y d h m))
16351 (if (org-at-table-p)
16352 (progn
16353 (goto-char match-end)
16354 (setq align t)
16355 (and (looking-at " *|") (goto-char (match-end 0))))
16356 (goto-char match-end))
16357 (if (looking-at
16358 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16359 (replace-match ""))
16360 (if negative (insert " -"))
16361 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16362 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16363 (insert " " (format fh h m))))
16364 (if align (org-table-align))
16365 (message "Time difference inserted")))))
16367 (defun org-make-tdiff-string (y d h m)
16368 (let ((fmt "")
16369 (l nil))
16370 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16371 l (push y l)))
16372 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16373 l (push d l)))
16374 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16375 l (push h l)))
16376 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16377 l (push m l)))
16378 (apply 'format fmt (nreverse l))))
16380 (defun org-time-string-to-time (s &optional buffer pos)
16381 "Convert a timestamp string into internal time."
16382 (condition-case errdata
16383 (apply 'encode-time (org-parse-time-string s))
16384 (error (error "Bad timestamp `%s'%s\nError was: %s"
16385 s (if (not (and buffer pos))
16387 (format " at %d in buffer `%s'" pos buffer))
16388 (cdr errdata)))))
16390 (defun org-time-string-to-seconds (s)
16391 "Convert a timestamp string to a number of seconds."
16392 (org-float-time (org-time-string-to-time s)))
16394 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16395 "Convert a time stamp to an absolute day number.
16396 If there is a specifier for a cyclic time stamp, get the closest date to
16397 DAYNR.
16398 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16399 The variable date is bound by the calendar when this is called."
16400 (cond
16401 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16402 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16403 daynr
16404 (+ daynr 1000)))
16405 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16406 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16407 (time-to-days (current-time))) (match-string 0 s)
16408 prefer show-all))
16409 (t (time-to-days
16410 (condition-case errdata
16411 (apply 'encode-time (org-parse-time-string s))
16412 (error (error "Bad timestamp `%s'%s\nError was: %s"
16413 s (if (not (and buffer pos))
16415 (format " at %d in buffer `%s'" pos buffer))
16416 (cdr errdata))))))))
16418 (defun org-days-to-iso-week (days)
16419 "Return the iso week number."
16420 (require 'cal-iso)
16421 (car (calendar-iso-from-absolute days)))
16423 (defun org-small-year-to-year (year)
16424 "Convert 2-digit years into 4-digit years.
16425 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16426 The year 2000 cannot be abbreviated. Any year larger than 99
16427 is returned unchanged."
16428 (if (< year 38)
16429 (setq year (+ 2000 year))
16430 (if (< year 100)
16431 (setq year (+ 1900 year))))
16432 year)
16434 (defun org-time-from-absolute (d)
16435 "Return the time corresponding to date D.
16436 D may be an absolute day number, or a calendar-type list (month day year)."
16437 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16438 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16440 (defun org-calendar-holiday ()
16441 "List of holidays, for Diary display in Org-mode."
16442 (require 'holidays)
16443 (let ((hl (funcall
16444 (if (fboundp 'calendar-check-holidays)
16445 'calendar-check-holidays 'check-calendar-holidays) date)))
16446 (if hl (mapconcat 'identity hl "; "))))
16448 (defun org-diary-sexp-entry (sexp entry date)
16449 "Process a SEXP diary ENTRY for DATE."
16450 (require 'diary-lib)
16451 (let ((result (if calendar-debug-sexp
16452 (let ((stack-trace-on-error t))
16453 (eval (car (read-from-string sexp))))
16454 (condition-case nil
16455 (eval (car (read-from-string sexp)))
16456 (error
16457 (beep)
16458 (message "Bad sexp at line %d in %s: %s"
16459 (org-current-line)
16460 (buffer-file-name) sexp)
16461 (sleep-for 2))))))
16462 (cond ((stringp result) (split-string result "; "))
16463 ((and (consp result)
16464 (not (consp (cdr result)))
16465 (stringp (cdr result))) (cdr result))
16466 ((and (consp result)
16467 (stringp (car result))) result)
16468 (result entry))))
16470 (defun org-diary-to-ical-string (frombuf)
16471 "Get iCalendar entries from diary entries in buffer FROMBUF.
16472 This uses the icalendar.el library."
16473 (let* ((tmpdir (if (featurep 'xemacs)
16474 (temp-directory)
16475 temporary-file-directory))
16476 (tmpfile (make-temp-name
16477 (expand-file-name "orgics" tmpdir)))
16478 buf rtn b e)
16479 (with-current-buffer frombuf
16480 (icalendar-export-region (point-min) (point-max) tmpfile)
16481 (setq buf (find-buffer-visiting tmpfile))
16482 (set-buffer buf)
16483 (goto-char (point-min))
16484 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16485 (setq b (match-beginning 0)))
16486 (goto-char (point-max))
16487 (if (re-search-backward "^END:VEVENT" nil t)
16488 (setq e (match-end 0)))
16489 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16490 (kill-buffer buf)
16491 (delete-file tmpfile)
16492 rtn))
16494 (defun org-closest-date (start current change prefer show-all)
16495 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16496 When PREFER is `past', return a date that is either CURRENT or past.
16497 When PREFER is `future', return a date that is either CURRENT or future.
16498 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16499 ;; Make the proper lists from the dates
16500 (catch 'exit
16501 (let ((a1 '(("h" . hour)
16502 ("d" . day)
16503 ("w" . week)
16504 ("m" . month)
16505 ("y" . year)))
16506 (shour (nth 2 (org-parse-time-string start)))
16507 dn dw sday cday n1 n2 n0
16508 d m y y1 y2 date1 date2 nmonths nm ny m2)
16510 (setq start (org-date-to-gregorian start)
16511 current (org-date-to-gregorian
16512 (if show-all
16513 current
16514 (time-to-days (current-time))))
16515 sday (calendar-absolute-from-gregorian start)
16516 cday (calendar-absolute-from-gregorian current))
16518 (if (<= cday sday) (throw 'exit sday))
16520 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16521 (setq dn (string-to-number (match-string 1 change))
16522 dw (cdr (assoc (match-string 2 change) a1)))
16523 (error "Invalid change specifier: %s" change))
16524 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16525 (cond
16526 ((eq dw 'hour)
16527 (let ((missing-hours
16528 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16529 dn)))
16530 (setq n1 (if (zerop missing-hours) cday
16531 (- cday (1+ (floor (/ missing-hours 24)))))
16532 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16533 ((eq dw 'day)
16534 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16535 n2 (+ n1 dn)))
16536 ((eq dw 'year)
16537 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16538 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16539 (setq date1 (list m d y1)
16540 n1 (calendar-absolute-from-gregorian date1)
16541 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16542 n2 (calendar-absolute-from-gregorian date2)))
16543 ((eq dw 'month)
16544 ;; approx number of month between the two dates
16545 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16546 ;; How often does dn fit in there?
16547 (setq d (nth 1 start) m (car start) y (nth 2 start)
16548 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16549 m (+ m nm)
16550 ny (floor (/ m 12))
16551 y (+ y ny)
16552 m (- m (* ny 12)))
16553 (while (> m 12) (setq m (- m 12) y (1+ y)))
16554 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16555 (setq m2 (+ m dn) y2 y)
16556 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16557 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16558 (while (<= n2 cday)
16559 (setq n1 n2 m m2 y y2)
16560 (setq m2 (+ m dn) y2 y)
16561 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16562 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16563 ;; Make sure n1 is the earlier date
16564 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16565 (if show-all
16566 (cond
16567 ((eq prefer 'past) (if (= cday n2) n2 n1))
16568 ((eq prefer 'future) (if (= cday n1) n1 n2))
16569 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16570 (cond
16571 ((eq prefer 'past) (if (= cday n2) n2 n1))
16572 ((eq prefer 'future) (if (= cday n1) n1 n2))
16573 (t (if (= cday n1) n1 n2)))))))
16575 (defun org-date-to-gregorian (date)
16576 "Turn any specification of DATE into a Gregorian date for the calendar."
16577 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16578 ((and (listp date) (= (length date) 3)) date)
16579 ((stringp date)
16580 (setq date (org-parse-time-string date))
16581 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16582 ((listp date)
16583 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16585 (defun org-parse-time-string (s &optional nodefault)
16586 "Parse the standard Org-mode time string.
16587 This should be a lot faster than the normal `parse-time-string'.
16588 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16589 hour and minute fields will be nil if not given."
16590 (cond ((string-match org-ts-regexp0 s)
16591 (list 0
16592 (if (or (match-beginning 8) (not nodefault))
16593 (string-to-number (or (match-string 8 s) "0")))
16594 (if (or (match-beginning 7) (not nodefault))
16595 (string-to-number (or (match-string 7 s) "0")))
16596 (string-to-number (match-string 4 s))
16597 (string-to-number (match-string 3 s))
16598 (string-to-number (match-string 2 s))
16599 nil nil nil))
16600 ((string-match "^<[^>]+>$" s)
16601 (decode-time (seconds-to-time (org-matcher-time s))))
16602 (t (error "Not a standard Org-mode time string: %s" s))))
16604 (defun org-timestamp-up (&optional arg)
16605 "Increase the date item at the cursor by one.
16606 If the cursor is on the year, change the year. If it is on the month,
16607 the day or the time, change that.
16608 With prefix ARG, change by that many units."
16609 (interactive "p")
16610 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16612 (defun org-timestamp-down (&optional arg)
16613 "Decrease the date item at the cursor by one.
16614 If the cursor is on the year, change the year. If it is on the month,
16615 the day or the time, change that.
16616 With prefix ARG, change by that many units."
16617 (interactive "p")
16618 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16620 (defun org-timestamp-up-day (&optional arg)
16621 "Increase the date in the time stamp by one day.
16622 With prefix ARG, change that many days."
16623 (interactive "p")
16624 (if (and (not (org-at-timestamp-p t))
16625 (org-at-heading-p))
16626 (org-todo 'up)
16627 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16629 (defun org-timestamp-down-day (&optional arg)
16630 "Decrease the date in the time stamp by one day.
16631 With prefix ARG, change that many days."
16632 (interactive "p")
16633 (if (and (not (org-at-timestamp-p t))
16634 (org-at-heading-p))
16635 (org-todo 'down)
16636 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16638 (defun org-at-timestamp-p (&optional inactive-ok)
16639 "Determine if the cursor is in or at a timestamp."
16640 (interactive)
16641 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16642 (pos (point))
16643 (ans (or (looking-at tsr)
16644 (save-excursion
16645 (skip-chars-backward "^[<\n\r\t")
16646 (if (> (point) (point-min)) (backward-char 1))
16647 (and (looking-at tsr)
16648 (> (- (match-end 0) pos) -1))))))
16649 (and ans
16650 (boundp 'org-ts-what)
16651 (setq org-ts-what
16652 (cond
16653 ((= pos (match-beginning 0)) 'bracket)
16654 ;; Point is considered to be "on the bracket" whether
16655 ;; it's really on it or right after it.
16656 ((= pos (1- (match-end 0))) 'bracket)
16657 ((= pos (match-end 0)) 'after)
16658 ((org-pos-in-match-range pos 2) 'year)
16659 ((org-pos-in-match-range pos 3) 'month)
16660 ((org-pos-in-match-range pos 7) 'hour)
16661 ((org-pos-in-match-range pos 8) 'minute)
16662 ((or (org-pos-in-match-range pos 4)
16663 (org-pos-in-match-range pos 5)) 'day)
16664 ((and (> pos (or (match-end 8) (match-end 5)))
16665 (< pos (match-end 0)))
16666 (- pos (or (match-end 8) (match-end 5))))
16667 (t 'day))))
16668 ans))
16670 (defun org-toggle-timestamp-type ()
16671 "Toggle the type (<active> or [inactive]) of a time stamp."
16672 (interactive)
16673 (when (org-at-timestamp-p t)
16674 (let ((beg (match-beginning 0)) (end (match-end 0))
16675 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16676 (save-excursion
16677 (goto-char beg)
16678 (while (re-search-forward "[][<>]" end t)
16679 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16680 t t)))
16681 (message "Timestamp is now %sactive"
16682 (if (equal (char-after beg) ?<) "" "in")))))
16684 (defvar org-clock-history) ; defined in org-clock.el
16685 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16686 (defun org-timestamp-change (n &optional what updown)
16687 "Change the date in the time stamp at point.
16688 The date will be changed by N times WHAT. WHAT can be `day', `month',
16689 `year', `minute', `second'. If WHAT is not given, the cursor position
16690 in the timestamp determines what will be changed."
16691 (let ((origin (point)) origin-cat
16692 with-hm inactive
16693 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16694 org-ts-what
16695 extra rem
16696 ts time time0 fixnext clrgx)
16697 (if (not (org-at-timestamp-p t))
16698 (error "Not at a timestamp"))
16699 (if (and (not what) (eq org-ts-what 'bracket))
16700 (org-toggle-timestamp-type)
16701 ;; Point isn't on brackets. Remember the part of the time-stamp
16702 ;; the point was in. Indeed, size of time-stamps may change,
16703 ;; but point must be kept in the same category nonetheless.
16704 (setq origin-cat org-ts-what)
16705 (if (and (not what) (not (eq org-ts-what 'day))
16706 org-display-custom-times
16707 (get-text-property (point) 'display)
16708 (not (get-text-property (1- (point)) 'display)))
16709 (setq org-ts-what 'day))
16710 (setq org-ts-what (or what org-ts-what)
16711 inactive (= (char-after (match-beginning 0)) ?\[)
16712 ts (match-string 0))
16713 (replace-match "")
16714 (if (string-match
16715 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16717 (setq extra (match-string 1 ts)))
16718 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16719 (setq with-hm t))
16720 (setq time0 (org-parse-time-string ts))
16721 (when (and updown
16722 (eq org-ts-what 'minute)
16723 (not current-prefix-arg))
16724 ;; This looks like s-up and s-down. Change by one rounding step.
16725 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16726 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16727 (setcar (cdr time0) (+ (nth 1 time0)
16728 (if (> n 0) (- rem) (- dm rem))))))
16729 (setq time
16730 (encode-time (or (car time0) 0)
16731 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16732 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16733 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16734 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16735 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16736 (nthcdr 6 time0)))
16737 (when (and (member org-ts-what '(hour minute))
16738 extra
16739 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16740 (setq extra (org-modify-ts-extra
16741 extra
16742 (if (eq org-ts-what 'hour) 2 5)
16743 n dm)))
16744 (when (integerp org-ts-what)
16745 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16746 (if (eq what 'calendar)
16747 (let ((cal-date (org-get-date-from-calendar)))
16748 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16749 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16750 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16751 (setcar time0 (or (car time0) 0))
16752 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16753 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16754 (setq time (apply 'encode-time time0))))
16755 ;; Insert the new time-stamp, and ensure point stays in the same
16756 ;; category as before (i.e. not after the last position in that
16757 ;; category).
16758 (let ((pos (point)))
16759 ;; Stay before inserted string. `save-excursion' is of no use.
16760 (setq org-last-changed-timestamp
16761 (org-insert-time-stamp time with-hm inactive nil nil extra))
16762 (goto-char pos))
16763 (save-match-data
16764 (looking-at org-ts-regexp3)
16765 (goto-char (cond
16766 ;; `day' category ends before `hour' if any, or at
16767 ;; the end of the day name.
16768 ((eq origin-cat 'day)
16769 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16770 ((eq origin-cat 'hour) (min (match-end 7) origin))
16771 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16772 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16773 ;; `year' and `month' have both fixed size: point
16774 ;; couldn't have moved into another part.
16775 (t origin))))
16776 ;; Update clock if on a CLOCK line.
16777 (org-clock-update-time-maybe)
16778 ;; Maybe adjust the closest clock in `org-clock-history'
16779 (when org-clock-adjust-closest
16780 (if (not (and (org-at-clock-log-p)
16781 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16782 org-clock-history))))))
16783 (message "No clock to adjust")
16784 (cond ((save-excursion ; fix previous clock?
16785 (re-search-backward org-ts-regexp0 nil t)
16786 (org-looking-back (concat org-clock-string " \\[")))
16787 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16788 ((save-excursion ; fix next clock?
16789 (re-search-backward org-ts-regexp0 nil t)
16790 (looking-at (concat org-ts-regexp0 "\\] =>")))
16791 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16792 (save-window-excursion
16793 ;; Find closest clock to point, adjust the previous/next one in history
16794 (let* ((p (save-excursion (org-back-to-heading t)))
16795 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16796 (clfixnth
16797 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16798 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16799 (if (not clfixpos)
16800 (message "No clock to adjust")
16801 (save-excursion
16802 (org-goto-marker-or-bmk clfixpos)
16803 (org-show-subtree)
16804 (when (re-search-forward clrgx nil t)
16805 (goto-char (match-beginning 1))
16806 (let (org-clock-adjust-closest)
16807 (org-timestamp-change n org-ts-what updown))
16808 (message "Clock adjusted in %s for heading: %s"
16809 (file-name-nondirectory (buffer-file-name))
16810 (org-get-heading t t)))))))))
16811 ;; Try to recenter the calendar window, if any.
16812 (if (and org-calendar-follow-timestamp-change
16813 (get-buffer-window "*Calendar*" t)
16814 (memq org-ts-what '(day month year)))
16815 (org-recenter-calendar (time-to-days time))))))
16817 (defun org-modify-ts-extra (s pos n dm)
16818 "Change the different parts of the lead-time and repeat fields in timestamp."
16819 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16820 ng h m new rem)
16821 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16822 (cond
16823 ((or (org-pos-in-match-range pos 2)
16824 (org-pos-in-match-range pos 3))
16825 (setq m (string-to-number (match-string 3 s))
16826 h (string-to-number (match-string 2 s)))
16827 (if (org-pos-in-match-range pos 2)
16828 (setq h (+ h n))
16829 (setq n (* dm (org-no-warnings (signum n))))
16830 (when (not (= 0 (setq rem (% m dm))))
16831 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16832 (setq m (+ m n)))
16833 (if (< m 0) (setq m (+ m 60) h (1- h)))
16834 (if (> m 59) (setq m (- m 60) h (1+ h)))
16835 (setq h (min 24 (max 0 h)))
16836 (setq ng 1 new (format "-%02d:%02d" h m)))
16837 ((org-pos-in-match-range pos 6)
16838 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16839 ((org-pos-in-match-range pos 5)
16840 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16842 ((org-pos-in-match-range pos 9)
16843 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16844 ((org-pos-in-match-range pos 8)
16845 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16847 (when ng
16848 (setq s (concat
16849 (substring s 0 (match-beginning ng))
16851 (substring s (match-end ng))))))
16854 (defun org-recenter-calendar (date)
16855 "If the calendar is visible, recenter it to DATE."
16856 (let ((cwin (get-buffer-window "*Calendar*" t)))
16857 (when cwin
16858 (let ((calendar-move-hook nil))
16859 (with-selected-window cwin
16860 (calendar-goto-date (if (listp date) date
16861 (calendar-gregorian-from-absolute date))))))))
16863 (defun org-goto-calendar (&optional arg)
16864 "Go to the Emacs calendar at the current date.
16865 If there is a time stamp in the current line, go to that date.
16866 A prefix ARG can be used to force the current date."
16867 (interactive "P")
16868 (let ((tsr org-ts-regexp) diff
16869 (calendar-move-hook nil)
16870 (calendar-view-holidays-initially-flag nil)
16871 (calendar-view-diary-initially-flag nil))
16872 (if (or (org-at-timestamp-p)
16873 (save-excursion
16874 (beginning-of-line 1)
16875 (looking-at (concat ".*" tsr))))
16876 (let ((d1 (time-to-days (current-time)))
16877 (d2 (time-to-days
16878 (org-time-string-to-time (match-string 1)))))
16879 (setq diff (- d2 d1))))
16880 (calendar)
16881 (calendar-goto-today)
16882 (if (and diff (not arg)) (calendar-forward-day diff))))
16884 (defun org-get-date-from-calendar ()
16885 "Return a list (month day year) of date at point in calendar."
16886 (with-current-buffer "*Calendar*"
16887 (save-match-data
16888 (calendar-cursor-to-date))))
16890 (defun org-date-from-calendar ()
16891 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16892 If there is already a time stamp at the cursor position, update it."
16893 (interactive)
16894 (if (org-at-timestamp-p t)
16895 (org-timestamp-change 0 'calendar)
16896 (let ((cal-date (org-get-date-from-calendar)))
16897 (org-insert-time-stamp
16898 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16900 (defun org-minutes-to-clocksum-string (m)
16901 "Format number of minutes as a clocksum string.
16902 The format is determined by `org-time-clocksum-format',
16903 `org-time-clocksum-use-fractional' and
16904 `org-time-clocksum-fractional-format' and
16905 `org-time-clocksum-use-effort-durations'."
16906 (let ((clocksum "") h d w mo y fmt n)
16907 (setq h (if org-time-clocksum-use-effort-durations
16908 (cdr (assoc "h" org-effort-durations)) 60)
16909 d (if org-time-clocksum-use-effort-durations
16910 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
16911 w (if org-time-clocksum-use-effort-durations
16912 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
16913 mo (if org-time-clocksum-use-effort-durations
16914 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
16915 y (if org-time-clocksum-use-effort-durations
16916 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
16917 ;; fractional format
16918 (if org-time-clocksum-use-fractional
16919 (cond
16920 ;; single format string
16921 ((stringp org-time-clocksum-fractional-format)
16922 (format org-time-clocksum-fractional-format (/ m (float h))))
16923 ;; choice of fractional formats for different time units
16924 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16925 (> (/ (truncate m) (* y d h)) 0))
16926 (format fmt (/ m (* y d (float h)))))
16927 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16928 (> (/ (truncate m) (* mo d h)) 0))
16929 (format fmt (/ m (* mo d (float h)))))
16930 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16931 (> (/ (truncate m) (* w d h)) 0))
16932 (format fmt (/ m (* w d (float h)))))
16933 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16934 (> (/ (truncate m) (* d h)) 0))
16935 (format fmt (/ m (* d (float h)))))
16936 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16937 (> (/ (truncate m) h) 0))
16938 (format fmt (/ m (float h))))
16939 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16940 (format fmt m))
16941 ;; fall back to smallest time unit with a format
16942 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16943 (format fmt (/ m (float h))))
16944 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16945 (format fmt (/ m (* d (float h)))))
16946 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16947 (format fmt (/ m (* w d (float h)))))
16948 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16949 (format fmt (/ m (* mo d (float h)))))
16950 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16951 (format fmt (/ m (* y d (float h))))))
16952 ;; standard (non-fractional) format, with single format string
16953 (if (stringp org-time-clocksum-format)
16954 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
16955 ;; separate formats components
16956 (and (setq fmt (plist-get org-time-clocksum-format :years))
16957 (or (> (setq n (/ (truncate m) (* y d h))) 0)
16958 (plist-get org-time-clocksum-format :require-years))
16959 (setq clocksum (concat clocksum (format fmt n))
16960 m (- m (* n y d h))))
16961 (and (setq fmt (plist-get org-time-clocksum-format :months))
16962 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
16963 (plist-get org-time-clocksum-format :require-months))
16964 (setq clocksum (concat clocksum (format fmt n))
16965 m (- m (* n mo d h))))
16966 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16967 (or (> (setq n (/ (truncate m) (* w d h))) 0)
16968 (plist-get org-time-clocksum-format :require-weeks))
16969 (setq clocksum (concat clocksum (format fmt n))
16970 m (- m (* n w d h))))
16971 (and (setq fmt (plist-get org-time-clocksum-format :days))
16972 (or (> (setq n (/ (truncate m) (* d h))) 0)
16973 (plist-get org-time-clocksum-format :require-days))
16974 (setq clocksum (concat clocksum (format fmt n))
16975 m (- m (* n d h))))
16976 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16977 (or (> (setq n (/ (truncate m) h)) 0)
16978 (plist-get org-time-clocksum-format :require-hours))
16979 (setq clocksum (concat clocksum (format fmt n))
16980 m (- m (* n h))))
16981 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16982 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16983 (setq clocksum (concat clocksum (format fmt m))))
16984 ;; return formatted time duration
16985 clocksum))))
16987 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16988 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16989 "Org mode version 8.0")
16991 (defun org-hours-to-clocksum-string (n)
16992 (org-minutes-to-clocksum-string (* n 60)))
16994 (defun org-hh:mm-string-to-minutes (s)
16995 "Convert a string H:MM to a number of minutes.
16996 If the string is just a number, interpret it as minutes.
16997 In fact, the first hh:mm or number in the string will be taken,
16998 there can be extra stuff in the string.
16999 If no number is found, the return value is 0."
17000 (cond
17001 ((integerp s) s)
17002 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17003 (+ (* (string-to-number (match-string 1 s)) 60)
17004 (string-to-number (match-string 2 s))))
17005 ((string-match "\\([0-9]+\\)" s)
17006 (string-to-number (match-string 1 s)))
17007 (t 0)))
17009 (defcustom org-effort-durations
17010 `(("h" . 60)
17011 ("d" . ,(* 60 8))
17012 ("w" . ,(* 60 8 5))
17013 ("m" . ,(* 60 8 5 4))
17014 ("y" . ,(* 60 8 5 40)))
17015 "Conversion factor to minutes for an effort modifier.
17017 Each entry has the form (MODIFIER . MINUTES).
17019 In an effort string, a number followed by MODIFIER is multiplied
17020 by the specified number of MINUTES to obtain an effort in
17021 minutes.
17023 For example, if the value of this variable is ((\"hours\" . 60)), then an
17024 effort string \"2hours\" is equivalent to 120 minutes."
17025 :group 'org-agenda
17026 :version "24.1"
17027 :type '(alist :key-type (string :tag "Modifier")
17028 :value-type (number :tag "Minutes")))
17030 (defcustom org-image-actual-width t
17031 "Should we use the actual width of images when inlining them?
17033 When set to `t', always use the image width.
17035 When set to a number, use imagemagick (when available) to set
17036 the image's width to this value.
17038 When set to a number in a list, try to get the width from the
17039 #+ATTR.* keyword if it matches a width specification like
17040 width=\"[0-9]+\", and fall back on that number if none is found.
17042 When set to nil, try to get the width from an #+ATTR.* keyword
17043 and fall back on the original width if none is found.
17045 This requires Emacs >= 24.1, build with imagemagick support."
17046 :group 'org-appearance
17047 :version "24.3"
17048 :type '(choice
17049 (const :tag "Use the image width" t)
17050 (integer :tag "Use a number of pixels")
17051 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17052 (const :tag "Use #+ATTR* or don't resize" nil)))
17054 (defun org-duration-string-to-minutes (s &optional output-to-string)
17055 "Convert a duration string S to minutes.
17057 A bare number is interpreted as minutes, modifiers can be set by
17058 customizing `org-effort-durations' (which see).
17060 Entries containing a colon are interpreted as H:MM by
17061 `org-hh:mm-string-to-minutes'."
17062 (let ((result 0)
17063 (re (concat "\\([0-9.]+\\) *\\("
17064 (regexp-opt (mapcar 'car org-effort-durations))
17065 "\\)")))
17066 (while (string-match re s)
17067 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17068 (string-to-number (match-string 1 s))))
17069 (setq s (replace-match "" nil t s)))
17070 (setq result (floor result))
17071 (incf result (org-hh:mm-string-to-minutes s))
17072 (if output-to-string (number-to-string result) result)))
17074 ;;;; Files
17076 (defun org-save-all-org-buffers ()
17077 "Save all Org-mode buffers without user confirmation."
17078 (interactive)
17079 (message "Saving all Org-mode buffers...")
17080 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17081 (when (featurep 'org-id) (org-id-locations-save))
17082 (message "Saving all Org-mode buffers... done"))
17084 (defun org-revert-all-org-buffers ()
17085 "Revert all Org-mode buffers.
17086 Prompt for confirmation when there are unsaved changes.
17087 Be sure you know what you are doing before letting this function
17088 overwrite your changes.
17090 This function is useful in a setup where one tracks org files
17091 with a version control system, to revert on one machine after pulling
17092 changes from another. I believe the procedure must be like this:
17094 1. M-x org-save-all-org-buffers
17095 2. Pull changes from the other machine, resolve conflicts
17096 3. M-x org-revert-all-org-buffers"
17097 (interactive)
17098 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17099 (error "Abort"))
17100 (save-excursion
17101 (save-window-excursion
17102 (mapc
17103 (lambda (b)
17104 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17105 (with-current-buffer b buffer-file-name))
17106 (org-pop-to-buffer-same-window b)
17107 (revert-buffer t 'no-confirm)))
17108 (buffer-list))
17109 (when (and (featurep 'org-id) org-id-track-globally)
17110 (org-id-locations-load)))))
17112 ;;;; Agenda files
17114 ;;;###autoload
17115 (defun org-switchb (&optional arg)
17116 "Switch between Org buffers.
17117 With one prefix argument, restrict available buffers to files.
17118 With two prefix arguments, restrict available buffers to agenda files.
17120 Defaults to `iswitchb' for buffer name completion.
17121 Set `org-completion-use-ido' to make it use ido instead."
17122 (interactive "P")
17123 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17124 ((equal arg '(16)) (org-buffer-list 'agenda))
17125 (t (org-buffer-list))))
17126 (org-completion-use-iswitchb org-completion-use-iswitchb)
17127 (org-completion-use-ido org-completion-use-ido))
17128 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17129 (setq org-completion-use-iswitchb t))
17130 (org-pop-to-buffer-same-window
17131 (org-icompleting-read "Org buffer: "
17132 (mapcar 'list (mapcar 'buffer-name blist))
17133 nil t))))
17135 ;;; Define some older names previously used for this functionality
17136 ;;;###autoload
17137 (defalias 'org-ido-switchb 'org-switchb)
17138 ;;;###autoload
17139 (defalias 'org-iswitchb 'org-switchb)
17141 (defun org-buffer-list (&optional predicate exclude-tmp)
17142 "Return a list of Org buffers.
17143 PREDICATE can be `export', `files' or `agenda'.
17145 export restrict the list to Export buffers.
17146 files restrict the list to buffers visiting Org files.
17147 agenda restrict the list to buffers visiting agenda files.
17149 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17150 (let* ((bfn nil)
17151 (agenda-files (and (eq predicate 'agenda)
17152 (mapcar 'file-truename (org-agenda-files t))))
17153 (filter
17154 (cond
17155 ((eq predicate 'files)
17156 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17157 ((eq predicate 'export)
17158 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17159 ((eq predicate 'agenda)
17160 (lambda (b)
17161 (with-current-buffer b
17162 (and (derived-mode-p 'org-mode)
17163 (setq bfn (buffer-file-name b))
17164 (member (file-truename bfn) agenda-files)))))
17165 (t (lambda (b) (with-current-buffer b
17166 (or (derived-mode-p 'org-mode)
17167 (string-match "\*Org .*Export"
17168 (buffer-name b)))))))))
17169 (delq nil
17170 (mapcar
17171 (lambda(b)
17172 (if (and (funcall filter b)
17173 (or (not exclude-tmp)
17174 (not (string-match "tmp" (buffer-name b)))))
17176 nil))
17177 (buffer-list)))))
17179 (defun org-agenda-files (&optional unrestricted archives)
17180 "Get the list of agenda files.
17181 Optional UNRESTRICTED means return the full list even if a restriction
17182 is currently in place.
17183 When ARCHIVES is t, include all archive files that are really being
17184 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17185 `org-agenda-archives-mode' is t."
17186 (let ((files
17187 (cond
17188 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17189 ((stringp org-agenda-files) (org-read-agenda-file-list))
17190 ((listp org-agenda-files) org-agenda-files)
17191 (t (error "Invalid value of `org-agenda-files'")))))
17192 (setq files (apply 'append
17193 (mapcar (lambda (f)
17194 (if (file-directory-p f)
17195 (directory-files
17196 f t org-agenda-file-regexp)
17197 (list f)))
17198 files)))
17199 (when org-agenda-skip-unavailable-files
17200 (setq files (delq nil
17201 (mapcar (function
17202 (lambda (file)
17203 (and (file-readable-p file) file)))
17204 files))))
17205 (when (or (eq archives t)
17206 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17207 (setq files (org-add-archive-files files)))
17208 files))
17210 (defun org-agenda-file-p (&optional file)
17211 "Return non-nil, if FILE is an agenda file.
17212 If FILE is omitted, use the file associated with the current
17213 buffer."
17214 (member (or file (buffer-file-name))
17215 (org-agenda-files t)))
17217 (defun org-edit-agenda-file-list ()
17218 "Edit the list of agenda files.
17219 Depending on setup, this either uses customize to edit the variable
17220 `org-agenda-files', or it visits the file that is holding the list. In the
17221 latter case, the buffer is set up in a way that saving it automatically kills
17222 the buffer and restores the previous window configuration."
17223 (interactive)
17224 (if (stringp org-agenda-files)
17225 (let ((cw (current-window-configuration)))
17226 (find-file org-agenda-files)
17227 (org-set-local 'org-window-configuration cw)
17228 (org-add-hook 'after-save-hook
17229 (lambda ()
17230 (set-window-configuration
17231 (prog1 org-window-configuration
17232 (kill-buffer (current-buffer))))
17233 (org-install-agenda-files-menu)
17234 (message "New agenda file list installed"))
17235 nil 'local)
17236 (message "%s" (substitute-command-keys
17237 "Edit list and finish with \\[save-buffer]")))
17238 (customize-variable 'org-agenda-files)))
17240 (defun org-store-new-agenda-file-list (list)
17241 "Set new value for the agenda file list and save it correctly."
17242 (if (stringp org-agenda-files)
17243 (let ((fe (org-read-agenda-file-list t)) b u)
17244 (while (setq b (find-buffer-visiting org-agenda-files))
17245 (kill-buffer b))
17246 (with-temp-file org-agenda-files
17247 (insert
17248 (mapconcat
17249 (lambda (f) ;; Keep un-expanded entries.
17250 (if (setq u (assoc f fe))
17251 (cdr u)
17253 list "\n")
17254 "\n")))
17255 (let ((org-mode-hook nil) (org-inhibit-startup t)
17256 (org-insert-mode-line-in-empty-file nil))
17257 (setq org-agenda-files list)
17258 (customize-save-variable 'org-agenda-files org-agenda-files))))
17260 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17261 "Read the list of agenda files from a file.
17262 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17263 filenames, used by `org-store-new-agenda-file-list' to write back
17264 un-expanded file names."
17265 (when (file-directory-p org-agenda-files)
17266 (error "`org-agenda-files' cannot be a single directory"))
17267 (when (stringp org-agenda-files)
17268 (with-temp-buffer
17269 (insert-file-contents org-agenda-files)
17270 (mapcar
17271 (lambda (f)
17272 (let ((e (expand-file-name (substitute-in-file-name f)
17273 org-directory)))
17274 (if pair-with-expansion
17275 (cons e f)
17276 e)))
17277 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17279 ;;;###autoload
17280 (defun org-cycle-agenda-files ()
17281 "Cycle through the files in `org-agenda-files'.
17282 If the current buffer visits an agenda file, find the next one in the list.
17283 If the current buffer does not, find the first agenda file."
17284 (interactive)
17285 (let* ((fs (org-agenda-files t))
17286 (files (append fs (list (car fs))))
17287 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17288 file)
17289 (unless files (error "No agenda files"))
17290 (catch 'exit
17291 (while (setq file (pop files))
17292 (if (equal (file-truename file) tcf)
17293 (when (car files)
17294 (find-file (car files))
17295 (throw 'exit t))))
17296 (find-file (car fs)))
17297 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17299 (defun org-agenda-file-to-front (&optional to-end)
17300 "Move/add the current file to the top of the agenda file list.
17301 If the file is not present in the list, it is added to the front. If it is
17302 present, it is moved there. With optional argument TO-END, add/move to the
17303 end of the list."
17304 (interactive "P")
17305 (let ((org-agenda-skip-unavailable-files nil)
17306 (file-alist (mapcar (lambda (x)
17307 (cons (file-truename x) x))
17308 (org-agenda-files t)))
17309 (ctf (file-truename
17310 (or buffer-file-name
17311 (error "Please save the current buffer to a file"))))
17312 x had)
17313 (setq x (assoc ctf file-alist) had x)
17315 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17316 (if to-end
17317 (setq file-alist (append (delq x file-alist) (list x)))
17318 (setq file-alist (cons x (delq x file-alist))))
17319 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17320 (org-install-agenda-files-menu)
17321 (message "File %s to %s of agenda file list"
17322 (if had "moved" "added") (if to-end "end" "front"))))
17324 (defun org-remove-file (&optional file)
17325 "Remove current file from the list of files in variable `org-agenda-files'.
17326 These are the files which are being checked for agenda entries.
17327 Optional argument FILE means use this file instead of the current."
17328 (interactive)
17329 (let* ((org-agenda-skip-unavailable-files nil)
17330 (file (or file buffer-file-name
17331 (error "Current buffer does not visit a file")))
17332 (true-file (file-truename file))
17333 (afile (abbreviate-file-name file))
17334 (files (delq nil (mapcar
17335 (lambda (x)
17336 (if (equal true-file
17337 (file-truename x))
17338 nil x))
17339 (org-agenda-files t)))))
17340 (if (not (= (length files) (length (org-agenda-files t))))
17341 (progn
17342 (org-store-new-agenda-file-list files)
17343 (org-install-agenda-files-menu)
17344 (message "Removed file: %s" afile))
17345 (message "File was not in list: %s (not removed)" afile))))
17347 (defun org-file-menu-entry (file)
17348 (vector file (list 'find-file file) t))
17350 (defun org-check-agenda-file (file)
17351 "Make sure FILE exists. If not, ask user what to do."
17352 (when (not (file-exists-p file))
17353 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17354 (abbreviate-file-name file))
17355 (let ((r (downcase (read-char-exclusive))))
17356 (cond
17357 ((equal r ?r)
17358 (org-remove-file file)
17359 (throw 'nextfile t))
17360 (t (error "Abort"))))))
17362 (defun org-get-agenda-file-buffer (file)
17363 "Get a buffer visiting FILE. If the buffer needs to be created, add
17364 it to the list of buffers which might be released later."
17365 (let ((buf (org-find-base-buffer-visiting file)))
17366 (if buf
17367 buf ; just return it
17368 ;; Make a new buffer and remember it
17369 (setq buf (find-file-noselect file))
17370 (if buf (push buf org-agenda-new-buffers))
17371 buf)))
17373 (defun org-release-buffers (blist)
17374 "Release all buffers in list, asking the user for confirmation when needed.
17375 When a buffer is unmodified, it is just killed. When modified, it is saved
17376 \(if the user agrees) and then killed."
17377 (let (buf file)
17378 (while (setq buf (pop blist))
17379 (setq file (buffer-file-name buf))
17380 (when (and (buffer-modified-p buf)
17381 file
17382 (y-or-n-p (format "Save file %s? " file)))
17383 (with-current-buffer buf (save-buffer)))
17384 (kill-buffer buf))))
17386 (defun org-agenda-prepare-buffers (files)
17387 "Create buffers for all agenda files, protect archived trees and comments."
17388 (interactive)
17389 (let ((pa '(:org-archived t))
17390 (pc '(:org-comment t))
17391 (pall '(:org-archived t :org-comment t))
17392 (inhibit-read-only t)
17393 (rea (concat ":" org-archive-tag ":"))
17394 bmp file re)
17395 (save-excursion
17396 (save-restriction
17397 (while (setq file (pop files))
17398 (catch 'nextfile
17399 (if (bufferp file)
17400 (set-buffer file)
17401 (org-check-agenda-file file)
17402 (set-buffer (org-get-agenda-file-buffer file)))
17403 (widen)
17404 (setq bmp (buffer-modified-p))
17405 (org-refresh-category-properties)
17406 (org-refresh-properties org-effort-property 'org-effort)
17407 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17408 (setq org-todo-keywords-for-agenda
17409 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17410 (setq org-done-keywords-for-agenda
17411 (append org-done-keywords-for-agenda org-done-keywords))
17412 (setq org-todo-keyword-alist-for-agenda
17413 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17414 (setq org-drawers-for-agenda
17415 (append org-drawers-for-agenda org-drawers))
17416 (setq org-tag-alist-for-agenda
17417 (append org-tag-alist-for-agenda org-tag-alist))
17419 (save-excursion
17420 (remove-text-properties (point-min) (point-max) pall)
17421 (when org-agenda-skip-archived-trees
17422 (goto-char (point-min))
17423 (while (re-search-forward rea nil t)
17424 (if (org-at-heading-p t)
17425 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17426 (goto-char (point-min))
17427 (setq re (format org-heading-keyword-regexp-format
17428 org-comment-string))
17429 (while (re-search-forward re nil t)
17430 (add-text-properties
17431 (match-beginning 0) (org-end-of-subtree t) pc)))
17432 (set-buffer-modified-p bmp)))))
17433 (setq org-todo-keywords-for-agenda
17434 (org-uniquify org-todo-keywords-for-agenda))
17435 (setq org-todo-keyword-alist-for-agenda
17436 (org-uniquify org-todo-keyword-alist-for-agenda)
17437 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17439 ;;;; Embedded LaTeX
17441 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17442 "Keymap for the minor `org-cdlatex-mode'.")
17444 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17445 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17446 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17447 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17448 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17450 (defvar org-cdlatex-texmathp-advice-is-done nil
17451 "Flag remembering if we have applied the advice to texmathp already.")
17453 (define-minor-mode org-cdlatex-mode
17454 "Toggle the minor `org-cdlatex-mode'.
17455 This mode supports entering LaTeX environment and math in LaTeX fragments
17456 in Org-mode.
17457 \\{org-cdlatex-mode-map}"
17458 nil " OCDL" nil
17459 (when org-cdlatex-mode
17460 (require 'cdlatex)
17461 (run-hooks 'cdlatex-mode-hook)
17462 (cdlatex-compute-tables))
17463 (unless org-cdlatex-texmathp-advice-is-done
17464 (setq org-cdlatex-texmathp-advice-is-done t)
17465 (defadvice texmathp (around org-math-always-on activate)
17466 "Always return t in org-mode buffers.
17467 This is because we want to insert math symbols without dollars even outside
17468 the LaTeX math segments. If Orgmode thinks that point is actually inside
17469 an embedded LaTeX fragment, let texmathp do its job.
17470 \\[org-cdlatex-mode-map]"
17471 (interactive)
17472 (let (p)
17473 (cond
17474 ((not (derived-mode-p 'org-mode)) ad-do-it)
17475 ((eq this-command 'cdlatex-math-symbol)
17476 (setq ad-return-value t
17477 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17479 (let ((p (org-inside-LaTeX-fragment-p)))
17480 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17481 (setq ad-return-value t
17482 texmathp-why '("Org-mode embedded math" . 0))
17483 (if p ad-do-it)))))))))
17485 (defun turn-on-org-cdlatex ()
17486 "Unconditionally turn on `org-cdlatex-mode'."
17487 (org-cdlatex-mode 1))
17489 (defun org-inside-LaTeX-fragment-p ()
17490 "Test if point is inside a LaTeX fragment.
17491 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17492 sequence appearing also before point.
17493 Even though the matchers for math are configurable, this function assumes
17494 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17495 delimiters are skipped when they have been removed by customization.
17496 The return value is nil, or a cons cell with the delimiter and the
17497 position of this delimiter.
17499 This function does a reasonably good job, but can locally be fooled by
17500 for example currency specifications. For example it will assume being in
17501 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17502 fragments that are properly closed, but during editing, we have to live
17503 with the uncertainty caused by missing closing delimiters. This function
17504 looks only before point, not after."
17505 (catch 'exit
17506 (let ((pos (point))
17507 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17508 (lim (progn
17509 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17510 (point)))
17511 dd-on str (start 0) m re)
17512 (goto-char pos)
17513 (when dodollar
17514 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17515 re (nth 1 (assoc "$" org-latex-regexps)))
17516 (while (string-match re str start)
17517 (cond
17518 ((= (match-end 0) (length str))
17519 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17520 ((= (match-end 0) (- (length str) 5))
17521 (throw 'exit nil))
17522 (t (setq start (match-end 0))))))
17523 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17524 (goto-char pos)
17525 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17526 (and (match-beginning 2) (throw 'exit nil))
17527 ;; count $$
17528 (while (re-search-backward "\\$\\$" lim t)
17529 (setq dd-on (not dd-on)))
17530 (goto-char pos)
17531 (if dd-on (cons "$$" m))))))
17533 (defun org-inside-latex-macro-p ()
17534 "Is point inside a LaTeX macro or its arguments?"
17535 (save-match-data
17536 (org-in-regexp
17537 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17539 (defun org-try-cdlatex-tab ()
17540 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17541 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17542 - inside a LaTeX fragment, or
17543 - after the first word in a line, where an abbreviation expansion could
17544 insert a LaTeX environment."
17545 (when org-cdlatex-mode
17546 (cond
17547 ;; Before any word on the line: No expansion possible.
17548 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17549 ;; Just after first word on the line: Expand it. Make sure it
17550 ;; cannot happen on headlines, though.
17551 ((save-excursion
17552 (skip-chars-backward "a-zA-Z0-9*")
17553 (skip-chars-backward " \t")
17554 (and (bolp) (not (org-at-heading-p))))
17555 (cdlatex-tab) t)
17556 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17558 (defun org-cdlatex-underscore-caret (&optional arg)
17559 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17560 Revert to the normal definition outside of these fragments."
17561 (interactive "P")
17562 (if (org-inside-LaTeX-fragment-p)
17563 (call-interactively 'cdlatex-sub-superscript)
17564 (let (org-cdlatex-mode)
17565 (call-interactively (key-binding (vector last-input-event))))))
17567 (defun org-cdlatex-math-modify (&optional arg)
17568 "Execute `cdlatex-math-modify' in LaTeX fragments.
17569 Revert to the normal definition outside of these fragments."
17570 (interactive "P")
17571 (if (org-inside-LaTeX-fragment-p)
17572 (call-interactively 'cdlatex-math-modify)
17573 (let (org-cdlatex-mode)
17574 (call-interactively (key-binding (vector last-input-event))))))
17576 (defvar org-latex-fragment-image-overlays nil
17577 "List of overlays carrying the images of latex fragments.")
17578 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17580 (defun org-remove-latex-fragment-image-overlays ()
17581 "Remove all overlays with LaTeX fragment images in current buffer."
17582 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17583 (setq org-latex-fragment-image-overlays nil))
17585 (defun org-preview-latex-fragment (&optional subtree)
17586 "Preview the LaTeX fragment at point, or all locally or globally.
17587 If the cursor is in a LaTeX fragment, create the image and overlay
17588 it over the source code. If there is no fragment at point, display
17589 all fragments in the current text, from one headline to the next. With
17590 prefix SUBTREE, display all fragments in the current subtree. With a
17591 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17592 the cursor is before the first headline,
17593 display all fragments in the buffer.
17594 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17595 (interactive "P")
17596 (unless buffer-file-name
17597 (error "Can't preview LaTeX fragment in a non-file buffer"))
17598 (org-remove-latex-fragment-image-overlays)
17599 (save-excursion
17600 (save-restriction
17601 (let (beg end at msg)
17602 (cond
17603 ((or (equal subtree '(16))
17604 (not (save-excursion
17605 (re-search-backward org-outline-regexp-bol nil t))))
17606 (setq beg (point-min) end (point-max)
17607 msg "Creating images for buffer...%s"))
17608 ((equal subtree '(4))
17609 (org-back-to-heading)
17610 (setq beg (point) end (org-end-of-subtree t)
17611 msg "Creating images for subtree...%s"))
17613 (if (setq at (org-inside-LaTeX-fragment-p))
17614 (goto-char (max (point-min) (- (cdr at) 2)))
17615 (org-back-to-heading))
17616 (setq beg (point) end (progn (outline-next-heading) (point))
17617 msg (if at "Creating image...%s"
17618 "Creating images for entry...%s"))))
17619 (message msg "")
17620 (narrow-to-region beg end)
17621 (goto-char beg)
17622 (org-format-latex
17623 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17624 (file-name-nondirectory
17625 buffer-file-name)))
17626 default-directory 'overlays msg at 'forbuffer
17627 org-latex-create-formula-image-program)
17628 (message msg "done. Use `C-c C-c' to remove images.")))))
17630 (defvar org-latex-regexps
17631 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17632 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17633 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17634 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17635 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17636 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17637 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17638 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17639 "Regular expressions for matching embedded LaTeX.")
17641 (defvar org-export-have-math nil) ;; dynamic scoping
17642 (defun org-format-latex (prefix &optional dir overlays msg at
17643 forbuffer processing-type)
17644 "Replace LaTeX fragments with links to an image, and produce images.
17645 Some of the options can be changed using the variable
17646 `org-format-latex-options'."
17647 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17648 (let* ((prefixnodir (file-name-nondirectory prefix))
17649 (absprefix (expand-file-name prefix dir))
17650 (todir (file-name-directory absprefix))
17651 (opt org-format-latex-options)
17652 (optnew org-format-latex-options)
17653 (matchers (plist-get opt :matchers))
17654 (re-list org-latex-regexps)
17655 (org-format-latex-header-extra
17656 (plist-get (org-infile-export-plist) :latex-header-extra))
17657 (cnt 0) txt hash link beg end re e checkdir
17658 string
17659 m n block-type block linkfile movefile ov)
17660 ;; Check the different regular expressions
17661 (while (setq e (pop re-list))
17662 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17663 block (if block-type "\n\n" ""))
17664 (when (member m matchers)
17665 (goto-char (point-min))
17666 (while (re-search-forward re nil t)
17667 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17668 (not (get-text-property (match-beginning n)
17669 'org-protected))
17670 (or (not overlays)
17671 (not (eq (get-char-property (match-beginning n)
17672 'org-overlay-type)
17673 'org-latex-overlay))))
17674 (setq org-export-have-math t)
17675 (cond
17676 ((eq processing-type 'verbatim)
17677 ;; Leave the text verbatim, just protect it
17678 (add-text-properties (match-beginning n) (match-end n)
17679 '(org-protected t)))
17680 ((eq processing-type 'mathjax)
17681 ;; Prepare for MathJax processing
17682 (setq string (match-string n))
17683 (if (member m '("$" "$1"))
17684 (save-excursion
17685 (delete-region (match-beginning n) (match-end n))
17686 (goto-char (match-beginning n))
17687 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17688 "\\)")
17689 '(org-protected t))))
17690 (add-text-properties (match-beginning n) (match-end n)
17691 '(org-protected t))))
17692 ((or (eq processing-type 'dvipng)
17693 (eq processing-type 'imagemagick))
17694 ;; Process to an image
17695 (setq txt (match-string n)
17696 beg (match-beginning n) end (match-end n)
17697 cnt (1+ cnt))
17698 (let ((face (face-at-point))
17699 (fg (plist-get opt :foreground))
17700 (bg (plist-get opt :background))
17701 print-length print-level) ; make sure full list is printed
17702 (when forbuffer
17703 ; Get the colors from the face at point
17704 (goto-char beg)
17705 (when (eq fg 'auto)
17706 (setq fg (face-attribute face :foreground nil 'default)))
17707 (when (eq bg 'auto)
17708 (setq bg (face-attribute face :background nil 'default)))
17709 (setq optnew (copy-sequence opt))
17710 (plist-put optnew :foreground fg)
17711 (plist-put optnew :background bg))
17712 (setq hash (sha1 (prin1-to-string
17713 (list org-format-latex-header
17714 org-format-latex-header-extra
17715 org-export-latex-default-packages-alist
17716 org-export-latex-packages-alist
17717 org-format-latex-options
17718 forbuffer txt fg bg)))
17719 linkfile (format "%s_%s.png" prefix hash)
17720 movefile (format "%s_%s.png" absprefix hash)))
17721 (setq link (concat block "[[file:" linkfile "]]" block))
17722 (if msg (message msg cnt))
17723 (goto-char beg)
17724 (unless checkdir ; make sure the directory exists
17725 (setq checkdir t)
17726 (or (file-directory-p todir) (make-directory todir t)))
17727 (unless (file-exists-p movefile)
17728 (org-create-formula-image
17729 txt movefile optnew forbuffer processing-type))
17730 (if overlays
17731 (progn
17732 (mapc (lambda (o)
17733 (if (eq (overlay-get o 'org-overlay-type)
17734 'org-latex-overlay)
17735 (delete-overlay o)))
17736 (overlays-in beg end))
17737 (setq ov (make-overlay beg end))
17738 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17739 (if (featurep 'xemacs)
17740 (progn
17741 (overlay-put ov 'invisible t)
17742 (overlay-put
17743 ov 'end-glyph
17744 (make-glyph (vector 'png :file movefile))))
17745 (overlay-put
17746 ov 'display
17747 (list 'image :type 'png :file movefile :ascent 'center)))
17748 (push ov org-latex-fragment-image-overlays)
17749 (goto-char end))
17750 (delete-region beg end)
17751 (insert (org-add-props link
17752 (list 'org-latex-src
17753 (replace-regexp-in-string
17754 "\"" "" txt)
17755 'org-latex-src-embed-type
17756 (if block-type 'paragraph 'character))))))
17757 ((eq processing-type 'mathml)
17758 ;; Process to MathML
17759 (unless (save-match-data (org-format-latex-mathml-available-p))
17760 (error "LaTeX to MathML converter not configured"))
17761 (setq txt (match-string n)
17762 beg (match-beginning n) end (match-end n)
17763 cnt (1+ cnt))
17764 (if msg (message msg cnt))
17765 (goto-char beg)
17766 (delete-region beg end)
17767 (insert (org-format-latex-as-mathml
17768 txt block-type prefix dir)))
17770 (error "Unknown conversion type %s for latex fragments"
17771 processing-type)))))))))
17773 (defun org-create-math-formula (latex-frag &optional mathml-file)
17774 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17775 Use `org-latex-to-mathml-convert-command'. If the conversion is
17776 sucessful, return the portion between \"<math...> </math>\"
17777 elements otherwise return nil. When MATHML-FILE is specified,
17778 write the results in to that file. When invoked as an
17779 interactive command, prompt for LATEX-FRAG, with initial value
17780 set to the current active region and echo the results for user
17781 inspection."
17782 (interactive (list (let ((frag (when (org-region-active-p)
17783 (buffer-substring-no-properties
17784 (region-beginning) (region-end)))))
17785 (read-string "LaTeX Fragment: " frag nil frag))))
17786 (unless latex-frag (error "Invalid latex-frag"))
17787 (let* ((tmp-in-file (file-relative-name
17788 (make-temp-name (expand-file-name "ltxmathml-in"))))
17789 (ignore (write-region latex-frag nil tmp-in-file))
17790 (tmp-out-file (file-relative-name
17791 (make-temp-name (expand-file-name "ltxmathml-out"))))
17792 (cmd (format-spec
17793 org-latex-to-mathml-convert-command
17794 `((?j . ,(shell-quote-argument
17795 (expand-file-name org-latex-to-mathml-jar-file)))
17796 (?I . ,(shell-quote-argument tmp-in-file))
17797 (?o . ,(shell-quote-argument tmp-out-file)))))
17798 mathml shell-command-output)
17799 (when (org-called-interactively-p 'any)
17800 (unless (org-format-latex-mathml-available-p)
17801 (error "LaTeX to MathML converter not configured")))
17802 (message "Running %s" cmd)
17803 (setq shell-command-output (shell-command-to-string cmd))
17804 (setq mathml
17805 (when (file-readable-p tmp-out-file)
17806 (with-current-buffer (find-file-noselect tmp-out-file t)
17807 (goto-char (point-min))
17808 (when (re-search-forward
17809 (concat
17810 (regexp-quote
17811 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17812 "\\(.\\|\n\\)*"
17813 (regexp-quote "</math>")) nil t)
17814 (prog1 (match-string 0) (kill-buffer))))))
17815 (cond
17816 (mathml
17817 (setq mathml
17818 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17819 (when mathml-file
17820 (write-region mathml nil mathml-file))
17821 (when (org-called-interactively-p 'any)
17822 (message mathml)))
17823 ((message "LaTeX to MathML conversion failed")
17824 (message shell-command-output)))
17825 (delete-file tmp-in-file)
17826 (when (file-exists-p tmp-out-file)
17827 (delete-file tmp-out-file))
17828 mathml))
17830 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17831 prefix &optional dir)
17832 "Use `org-create-math-formula' but check local cache first."
17833 (let* ((absprefix (expand-file-name prefix dir))
17834 (print-length nil) (print-level nil)
17835 (formula-id (concat
17836 "formula-"
17837 (sha1
17838 (prin1-to-string
17839 (list latex-frag
17840 org-latex-to-mathml-convert-command)))))
17841 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17842 (formula-cache-dir (file-name-directory formula-cache)))
17844 (unless (file-directory-p formula-cache-dir)
17845 (make-directory formula-cache-dir t))
17847 (unless (file-exists-p formula-cache)
17848 (org-create-math-formula latex-frag formula-cache))
17850 (if (file-exists-p formula-cache)
17851 ;; Successful conversion. Return the link to MathML file.
17852 (org-add-props
17853 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17854 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17855 'org-latex-src-embed-type (if latex-frag-type
17856 'paragraph 'character)))
17857 ;; Failed conversion. Return the LaTeX fragment verbatim
17858 (add-text-properties
17859 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17860 latex-frag)))
17862 (defun org-create-formula-image (string tofile options buffer &optional type)
17863 "Create an image from LaTeX source using dvipng or convert.
17864 This function calls either `org-create-formula-image-with-dvipng'
17865 or `org-create-formula-image-with-imagemagick' depending on the
17866 value of `org-latex-create-formula-image-program' or on the value
17867 of the optional TYPE variable.
17869 Note: ultimately these two function should be combined as they
17870 share a good deal of logic."
17871 (org-check-external-command
17872 "latex" "needed to convert LaTeX fragments to images")
17873 (funcall
17874 (case (or type org-latex-create-formula-image-program)
17875 ('dvipng
17876 (org-check-external-command
17877 "dvipng" "needed to convert LaTeX fragments to images")
17878 #'org-create-formula-image-with-dvipng)
17879 ('imagemagick
17880 (org-check-external-command
17881 "convert" "you need to install imagemagick")
17882 #'org-create-formula-image-with-imagemagick)
17883 (t (error
17884 "invalid value of `org-latex-create-formula-image-program'")))
17885 string tofile options buffer))
17887 ;; This function borrows from Ganesh Swami's latex2png.el
17888 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17889 "This calls dvipng."
17890 (require 'org-latex)
17891 (let* ((tmpdir (if (featurep 'xemacs)
17892 (temp-directory)
17893 temporary-file-directory))
17894 (texfilebase (make-temp-name
17895 (expand-file-name "orgtex" tmpdir)))
17896 (texfile (concat texfilebase ".tex"))
17897 (dvifile (concat texfilebase ".dvi"))
17898 (pngfile (concat texfilebase ".png"))
17899 (fnh (if (featurep 'xemacs)
17900 (font-height (face-font 'default))
17901 (face-attribute 'default :height nil)))
17902 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17903 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17904 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17905 "Black"))
17906 (bg (or (plist-get options (if buffer :background :html-background))
17907 "Transparent")))
17908 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17909 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17910 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17911 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17912 (with-temp-file texfile
17913 (insert (org-splice-latex-header
17914 org-format-latex-header
17915 org-export-latex-default-packages-alist
17916 org-export-latex-packages-alist t
17917 org-format-latex-header-extra))
17918 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17919 (require 'org-latex)
17920 (org-export-latex-fix-inputenc))
17921 (let ((dir default-directory))
17922 (condition-case nil
17923 (progn
17924 (cd tmpdir)
17925 (call-process "latex" nil nil nil texfile))
17926 (error nil))
17927 (cd dir))
17928 (if (not (file-exists-p dvifile))
17929 (progn (message "Failed to create dvi file from %s" texfile) nil)
17930 (condition-case nil
17931 (if (featurep 'xemacs)
17932 (call-process "dvipng" nil nil nil
17933 "-fg" fg "-bg" bg
17934 "-T" "tight"
17935 "-o" pngfile
17936 dvifile)
17937 (call-process "dvipng" nil nil nil
17938 "-fg" fg "-bg" bg
17939 "-D" dpi
17940 ;;"-x" scale "-y" scale
17941 "-T" "tight"
17942 "-o" pngfile
17943 dvifile))
17944 (error nil))
17945 (if (not (file-exists-p pngfile))
17946 (if org-format-latex-signal-error
17947 (error "Failed to create png file from %s" texfile)
17948 (message "Failed to create png file from %s" texfile)
17949 nil)
17950 ;; Use the requested file name and clean up
17951 (copy-file pngfile tofile 'replace)
17952 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17953 (if (file-exists-p (concat texfilebase e))
17954 (delete-file (concat texfilebase e))))
17955 pngfile))))
17957 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17958 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17959 "This calls convert, which is included into imagemagick."
17960 (require 'org-latex)
17961 (let* ((tmpdir (if (featurep 'xemacs)
17962 (temp-directory)
17963 temporary-file-directory))
17964 (texfilebase (make-temp-name
17965 (expand-file-name "orgtex" tmpdir)))
17966 (texfile (concat texfilebase ".tex"))
17967 (pdffile (concat texfilebase ".pdf"))
17968 (pngfile (concat texfilebase ".png"))
17969 (fnh (if (featurep 'xemacs)
17970 (font-height (face-font 'default))
17971 (face-attribute 'default :height nil)))
17972 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17973 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17974 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17975 "black"))
17976 (bg (or (plist-get options (if buffer :background :html-background))
17977 "white")))
17978 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17979 (setq fg (org-latex-color-format fg)))
17980 (if (eq bg 'default) (setq bg (org-latex-color :background))
17981 (setq bg (org-latex-color-format
17982 (if (string= bg "Transparent") "white" bg))))
17983 (with-temp-file texfile
17984 (insert (org-splice-latex-header
17985 org-format-latex-header
17986 org-export-latex-default-packages-alist
17987 org-export-latex-packages-alist t
17988 org-format-latex-header-extra))
17989 (insert "\n\\begin{document}\n"
17990 "\\definecolor{fg}{rgb}{" fg "}\n"
17991 "\\definecolor{bg}{rgb}{" bg "}\n"
17992 "\n\\pagecolor{bg}\n"
17993 "\n{\\color{fg}\n"
17994 string
17995 "\n}\n"
17996 "\n\\end{document}\n" )
17997 (require 'org-latex)
17998 (org-export-latex-fix-inputenc))
17999 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18000 (condition-case nil
18001 (progn
18002 (cd tmpdir)
18003 (setq cmds org-latex-to-pdf-process)
18004 (while cmds
18005 (setq latex-frags-cmds (pop cmds))
18006 (if (listp latex-frags-cmds)
18007 (setq cmds nil)
18008 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
18009 (while latex-frags-cmds
18010 (setq cmd (pop latex-frags-cmds))
18011 (while (string-match "%b" cmd)
18012 (setq cmd (replace-match
18013 (save-match-data
18014 (shell-quote-argument texfile))
18015 t t cmd)))
18016 (while (string-match "%f" cmd)
18017 (setq cmd (replace-match
18018 (save-match-data
18019 (shell-quote-argument (file-name-nondirectory texfile)))
18020 t t cmd)))
18021 (while (string-match "%o" cmd)
18022 (setq cmd (replace-match
18023 (save-match-data
18024 (shell-quote-argument (file-name-directory texfile)))
18025 t t cmd)))
18026 (setq cmd (split-string cmd))
18027 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18028 (error nil))
18029 (cd dir))
18030 (if (not (file-exists-p pdffile))
18031 (progn (message "Failed to create pdf file from %s" texfile) nil)
18032 (condition-case nil
18033 (if (featurep 'xemacs)
18034 (call-process "convert" nil nil nil
18035 "-density" "96"
18036 "-trim"
18037 "-antialias"
18038 pdffile
18039 "-quality" "100"
18040 ;; "-sharpen" "0x1.0"
18041 pngfile)
18042 (call-process "convert" nil nil nil
18043 "-density" dpi
18044 "-trim"
18045 "-antialias"
18046 pdffile
18047 "-quality" "100"
18048 ; "-sharpen" "0x1.0"
18049 pngfile))
18050 (error nil))
18051 (if (not (file-exists-p pngfile))
18052 (if org-format-latex-signal-error
18053 (error "Failed to create png file from %s" texfile)
18054 (message "Failed to create png file from %s" texfile)
18055 nil)
18056 ;; Use the requested file name and clean up
18057 (copy-file pngfile tofile 'replace)
18058 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18059 (if (file-exists-p (concat texfilebase e))
18060 (delete-file (concat texfilebase e))))
18061 pngfile))))
18063 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18064 "Fill a LaTeX header template TPL.
18065 In the template, the following place holders will be recognized:
18067 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18068 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18069 [PACKAGES] \\usepackage statements for PKG
18070 [NO-PACKAGES] do not include PKG
18071 [EXTRA] the string EXTRA
18072 [NO-EXTRA] do not include EXTRA
18074 For backward compatibility, if both the positive and the negative place
18075 holder is missing, the positive one (without the \"NO-\") will be
18076 assumed to be present at the end of the template.
18077 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18078 EXTRA is a string.
18079 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18080 (let (rpl (end ""))
18081 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18082 (setq rpl (if (or (match-end 1) (not def-pkg))
18083 "" (org-latex-packages-to-string def-pkg snippets-p t))
18084 tpl (replace-match rpl t t tpl))
18085 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18087 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18088 (setq rpl (if (or (match-end 1) (not pkg))
18089 "" (org-latex-packages-to-string pkg snippets-p t))
18090 tpl (replace-match rpl t t tpl))
18091 (if pkg (setq end
18092 (concat end "\n"
18093 (org-latex-packages-to-string pkg snippets-p)))))
18095 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18096 (setq rpl (if (or (match-end 1) (not extra))
18097 "" (concat extra "\n"))
18098 tpl (replace-match rpl t t tpl))
18099 (if (and extra (string-match "\\S-" extra))
18100 (setq end (concat end "\n" extra))))
18102 (if (string-match "\\S-" end)
18103 (concat tpl "\n" end)
18104 tpl)))
18106 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18107 "Turn an alist of packages into a string with the \\usepackage macros."
18108 (setq pkg (mapconcat (lambda(p)
18109 (cond
18110 ((stringp p) p)
18111 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18112 (format "%% Package %s omitted" (cadr p)))
18113 ((equal "" (car p))
18114 (format "\\usepackage{%s}" (cadr p)))
18116 (format "\\usepackage[%s]{%s}"
18117 (car p) (cadr p)))))
18119 "\n"))
18120 (if newline (concat pkg "\n") pkg))
18122 (defun org-dvipng-color (attr)
18123 "Return a RGB color specification for dvipng."
18124 (apply 'format "rgb %s %s %s"
18125 (mapcar 'org-normalize-color
18126 (if (featurep 'xemacs)
18127 (color-rgb-components
18128 (face-property 'default
18129 (cond ((eq attr :foreground) 'foreground)
18130 ((eq attr :background) 'background))))
18131 (color-values (face-attribute 'default attr nil))))))
18133 (defun org-dvipng-color-format (color-name)
18134 "Convert COLOR-NAME to a RGB color value for dvipng."
18135 (apply 'format "rgb %s %s %s"
18136 (mapcar 'org-normalize-color
18137 (color-values color-name))))
18139 (defun org-latex-color (attr)
18140 "Return a RGB color for the LaTeX color package."
18141 (apply 'format "%s,%s,%s"
18142 (mapcar 'org-normalize-color
18143 (if (featurep 'xemacs)
18144 (color-rgb-components
18145 (face-property 'default
18146 (cond ((eq attr :foreground) 'foreground)
18147 ((eq attr :background) 'background))))
18148 (color-values (face-attribute 'default attr nil))))))
18150 (defun org-latex-color-format (color-name)
18151 "Convert COLOR-NAME to a RGB color value."
18152 (apply 'format "%s,%s,%s"
18153 (mapcar 'org-normalize-color
18154 (color-values color-name))))
18156 (defun org-normalize-color (value)
18157 "Return string to be used as color value for an RGB component."
18158 (format "%g" (/ value 65535.0)))
18160 ;; Image display
18163 (defvar org-inline-image-overlays nil)
18164 (make-variable-buffer-local 'org-inline-image-overlays)
18166 (defun org-toggle-inline-images (&optional include-linked)
18167 "Toggle the display of inline images.
18168 INCLUDE-LINKED is passed to `org-display-inline-images'."
18169 (interactive "P")
18170 (if org-inline-image-overlays
18171 (progn
18172 (org-remove-inline-images)
18173 (message "Inline image display turned off"))
18174 (org-display-inline-images include-linked)
18175 (if (and (org-called-interactively-p)
18176 org-inline-image-overlays)
18177 (message "%d images displayed inline"
18178 (length org-inline-image-overlays))
18179 (message "No images to display inline"))))
18181 (defun org-redisplay-inline-images ()
18182 "Refresh the display of inline images."
18183 (interactive)
18184 (if (not org-inline-image-overlays)
18185 (org-toggle-inline-images)
18186 (org-toggle-inline-images)
18187 (org-toggle-inline-images)))
18189 (defun org-display-inline-images (&optional include-linked refresh beg end)
18190 "Display inline images.
18191 Normally only links without a description part are inlined, because this
18192 is how it will work for export. When INCLUDE-LINKED is set, also links
18193 with a description part will be inlined. This can be nice for a quick
18194 look at those images, but it does not reflect what exported files will look
18195 like.
18196 When REFRESH is set, refresh existing images between BEG and END.
18197 This will create new image displays only if necessary.
18198 BEG and END default to the buffer boundaries."
18199 (interactive "P")
18200 (unless refresh
18201 (org-remove-inline-images)
18202 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18203 (save-excursion
18204 (save-restriction
18205 (widen)
18206 (setq beg (or beg (point-min)) end (or end (point-max)))
18207 (goto-char beg)
18208 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18209 (substring (org-image-file-name-regexp) 0 -2)
18210 "\\)\\]" (if include-linked "" "\\]")))
18211 old file ov img type attrwidth width)
18212 (while (re-search-forward re end t)
18213 (setq old (get-char-property-and-overlay (match-beginning 1)
18214 'org-image-overlay)
18215 file (expand-file-name
18216 (concat (or (match-string 3) "") (match-string 4))))
18217 (when (image-type-available-p 'imagemagick)
18218 (setq attrwidth (if (or (listp org-image-actual-width)
18219 (null org-image-actual-width))
18220 (save-excursion
18221 (save-match-data
18222 (when (re-search-backward
18223 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18224 (save-excursion
18225 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18226 (string-to-number (match-string 1))))))
18227 width (cond ((eq org-image-actual-width t) nil)
18228 ((null org-image-actual-width) attrwidth)
18229 ((numberp org-image-actual-width)
18230 org-image-actual-width)
18231 ((listp org-image-actual-width)
18232 (or attrwidth (car org-image-actual-width))))
18233 type (if width 'imagemagick)))
18234 (when (file-exists-p file)
18235 (if (and (car-safe old) refresh)
18236 (image-refresh (overlay-get (cdr old) 'display))
18237 (setq img (save-match-data (create-image file type nil :width width)))
18238 (when img
18239 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18240 (overlay-put ov 'display img)
18241 (overlay-put ov 'face 'default)
18242 (overlay-put ov 'org-image-overlay t)
18243 (overlay-put ov 'modification-hooks
18244 (list 'org-display-inline-remove-overlay))
18245 (push ov org-inline-image-overlays)))))))))
18247 (org-define-obsolete-function-alias
18248 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18250 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18251 "Remove inline-display overlay if a corresponding region is modified."
18252 (let ((inhibit-modification-hooks t))
18253 (when (and ov after)
18254 (delete ov org-inline-image-overlays)
18255 (delete-overlay ov))))
18257 (defun org-remove-inline-images ()
18258 "Remove inline display of images."
18259 (interactive)
18260 (mapc 'delete-overlay org-inline-image-overlays)
18261 (setq org-inline-image-overlays nil))
18263 ;;;; Key bindings
18265 ;; Outline functions from `outline-mode-prefix-map'
18266 ;; that can be remapped in Org:
18267 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18268 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18269 (define-key org-mode-map [remap outline-forward-same-level]
18270 'org-forward-heading-same-level)
18271 (define-key org-mode-map [remap outline-backward-same-level]
18272 'org-backward-heading-same-level)
18273 (define-key org-mode-map [remap show-branches]
18274 'org-kill-note-or-show-branches)
18275 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18276 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18277 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18279 ;; Outline functions from `outline-mode-prefix-map' that can not
18280 ;; be remapped in Org:
18282 ;; - the column "key binding" shows whether the Outline function is still
18283 ;; available in Org mode on the same key that it has been bound to in
18284 ;; Outline mode:
18285 ;; - "overridden": key used for a different functionality in Org mode
18286 ;; - else: key still bound to the same Outline function in Org mode
18288 ;; | Outline function | key binding | Org replacement |
18289 ;; |------------------------------------+-------------+-----------------------|
18290 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18291 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18292 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18293 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18294 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18295 ;; | `show-entry' | overridden | no replacement |
18296 ;; | `show-children' | `C-c C-i' | visibility cycling |
18297 ;; | `show-branches' | `C-c C-k' | still same function |
18298 ;; | `show-subtree' | overridden | visibility cycling |
18299 ;; | `show-all' | overridden | no replacement |
18300 ;; | `hide-subtree' | overridden | visibility cycling |
18301 ;; | `hide-body' | overridden | no replacement |
18302 ;; | `hide-entry' | overridden | visibility cycling |
18303 ;; | `hide-leaves' | overridden | no replacement |
18304 ;; | `hide-sublevels' | overridden | no replacement |
18305 ;; | `hide-other' | overridden | no replacement |
18307 ;; Make `C-c C-x' a prefix key
18308 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18310 ;; TAB key with modifiers
18311 (org-defkey org-mode-map "\C-i" 'org-cycle)
18312 (org-defkey org-mode-map [(tab)] 'org-cycle)
18313 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18314 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18315 ;; The following line is necessary under Suse GNU/Linux
18316 (unless (featurep 'xemacs)
18317 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18318 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18319 (define-key org-mode-map [backtab] 'org-shifttab)
18321 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18322 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18323 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18325 ;; Cursor keys with modifiers
18326 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18327 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18328 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18329 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18331 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18332 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18333 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18334 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18336 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18337 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18338 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18339 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18341 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18342 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18343 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18344 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18346 ;; Babel keys
18347 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18348 (mapc (lambda (pair)
18349 (define-key org-babel-map (car pair) (cdr pair)))
18350 org-babel-key-bindings)
18352 ;;; Extra keys for tty access.
18353 ;; We only set them when really needed because otherwise the
18354 ;; menus don't show the simple keys
18356 (when (or org-use-extra-keys
18357 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18358 (not window-system))
18359 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18360 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18361 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18362 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18363 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18364 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18365 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18366 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18367 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18368 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18369 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18370 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18371 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18372 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18373 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18374 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18375 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18376 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18377 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18378 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18379 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18380 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18381 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18382 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18383 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18384 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18385 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18386 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18388 ;; All the other keys
18390 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18391 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18392 (if (boundp 'narrow-map)
18393 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18394 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18395 (if (boundp 'narrow-map)
18396 (org-defkey narrow-map "b" 'org-narrow-to-block)
18397 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18398 (if (boundp 'narrow-map)
18399 (org-defkey narrow-map "e" 'org-narrow-to-element)
18400 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18401 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18402 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18403 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18404 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18405 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18406 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18407 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18408 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18409 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18410 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18411 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18412 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18413 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18414 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18415 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18416 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18417 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18418 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18419 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18420 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18421 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18422 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18423 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18424 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18425 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18426 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18427 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18428 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18429 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18430 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18431 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18432 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18433 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18434 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18435 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18436 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18437 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18438 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18439 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18440 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18441 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18442 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18443 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18444 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18445 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18446 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18447 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18448 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18449 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18450 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18451 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18452 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18453 (org-defkey org-mode-map "\C-c^" 'org-sort)
18454 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18455 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18456 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18457 (org-defkey org-mode-map "\C-m" 'org-return)
18458 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18459 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18460 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18461 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18462 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18463 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18464 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18465 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18466 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18467 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18468 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18469 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18470 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18471 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18472 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18473 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18474 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18475 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18476 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18477 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18478 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18479 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18480 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18482 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18483 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18484 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18486 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18487 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18488 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18489 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18490 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18491 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18492 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18493 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18494 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18495 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18496 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18497 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18498 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18499 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18500 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18501 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18502 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18503 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18504 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18505 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18506 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18507 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18508 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18510 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18511 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18512 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18513 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18514 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18516 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18518 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18520 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18521 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18523 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18526 (when (featurep 'xemacs)
18527 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18530 (defconst org-speed-commands-default
18532 ("Outline Navigation")
18533 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18534 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18535 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18536 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18537 ("u" . (org-speed-move-safe 'outline-up-heading))
18538 ("j" . org-goto)
18539 ("g" . (org-refile t))
18540 ("Outline Visibility")
18541 ("c" . org-cycle)
18542 ("C" . org-shifttab)
18543 (" " . org-display-outline-path)
18544 ("=" . org-columns)
18545 ("Outline Structure Editing")
18546 ("U" . org-shiftmetaup)
18547 ("D" . org-shiftmetadown)
18548 ("r" . org-metaright)
18549 ("l" . org-metaleft)
18550 ("R" . org-shiftmetaright)
18551 ("L" . org-shiftmetaleft)
18552 ("i" . (progn (forward-char 1) (call-interactively
18553 'org-insert-heading-respect-content)))
18554 ("^" . org-sort)
18555 ("w" . org-refile)
18556 ("a" . org-archive-subtree-default-with-confirmation)
18557 ("." . org-mark-subtree)
18558 ("#" . org-toggle-comment)
18559 ("Clock Commands")
18560 ("I" . org-clock-in)
18561 ("O" . org-clock-out)
18562 ("Meta Data Editing")
18563 ("t" . org-todo)
18564 ("," . (org-priority))
18565 ("0" . (org-priority ?\ ))
18566 ("1" . (org-priority ?A))
18567 ("2" . (org-priority ?B))
18568 ("3" . (org-priority ?C))
18569 (":" . org-set-tags-command)
18570 ("e" . org-set-effort)
18571 ("E" . org-inc-effort)
18572 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18573 (org-entry-put (point) "APPT_WARNTIME" m)))
18574 ("Agenda Views etc")
18575 ("v" . org-agenda)
18576 ("/" . org-sparse-tree)
18577 ("Misc")
18578 ("o" . org-open-at-point)
18579 ("?" . org-speed-command-help)
18580 ("<" . (org-agenda-set-restriction-lock 'subtree))
18581 (">" . (org-agenda-remove-restriction-lock))
18583 "The default speed commands.")
18585 (defun org-print-speed-command (e)
18586 (if (> (length (car e)) 1)
18587 (progn
18588 (princ "\n")
18589 (princ (car e))
18590 (princ "\n")
18591 (princ (make-string (length (car e)) ?-))
18592 (princ "\n"))
18593 (princ (car e))
18594 (princ " ")
18595 (if (symbolp (cdr e))
18596 (princ (symbol-name (cdr e)))
18597 (prin1 (cdr e)))
18598 (princ "\n")))
18600 (defun org-speed-command-help ()
18601 "Show the available speed commands."
18602 (interactive)
18603 (if (not org-use-speed-commands)
18604 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18605 (with-output-to-temp-buffer "*Help*"
18606 (princ "User-defined Speed commands\n===========================\n")
18607 (mapc 'org-print-speed-command org-speed-commands-user)
18608 (princ "\n")
18609 (princ "Built-in Speed commands\n=======================\n")
18610 (mapc 'org-print-speed-command org-speed-commands-default))
18611 (with-current-buffer "*Help*"
18612 (setq truncate-lines t))))
18614 (defun org-speed-move-safe (cmd)
18615 "Execute CMD, but make sure that the cursor always ends up in a headline.
18616 If not, return to the original position and throw an error."
18617 (interactive)
18618 (let ((pos (point)))
18619 (call-interactively cmd)
18620 (unless (and (bolp) (org-at-heading-p))
18621 (goto-char pos)
18622 (error "Boundary reached while executing %s" cmd))))
18624 (defvar org-self-insert-command-undo-counter 0)
18626 (defvar org-table-auto-blank-field) ; defined in org-table.el
18627 (defvar org-speed-command nil)
18629 (org-define-obsolete-function-alias
18630 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18632 (defun org-speed-command-activate (keys)
18633 "Hook for activating single-letter speed commands.
18634 `org-speed-commands-default' specifies a minimal command set.
18635 Use `org-speed-commands-user' for further customization."
18636 (when (or (and (bolp) (looking-at org-outline-regexp))
18637 (and (functionp org-use-speed-commands)
18638 (funcall org-use-speed-commands)))
18639 (cdr (assoc keys (append org-speed-commands-user
18640 org-speed-commands-default)))))
18642 (org-define-obsolete-function-alias
18643 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18645 (defun org-babel-speed-command-activate (keys)
18646 "Hook for activating single-letter code block commands."
18647 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18648 (cdr (assoc keys org-babel-key-bindings))))
18650 (defcustom org-speed-command-hook
18651 '(org-speed-command-default-hook org-babel-speed-command-hook)
18652 "Hook for activating speed commands at strategic locations.
18653 Hook functions are called in sequence until a valid handler is
18654 found.
18656 Each hook takes a single argument, a user-pressed command key
18657 which is also a `self-insert-command' from the global map.
18659 Within the hook, examine the cursor position and the command key
18660 and return nil or a valid handler as appropriate. Handler could
18661 be one of an interactive command, a function, or a form.
18663 Set `org-use-speed-commands' to non-nil value to enable this
18664 hook. The default setting is `org-speed-command-activate'."
18665 :group 'org-structure
18666 :version "24.1"
18667 :type 'hook)
18669 (defun org-self-insert-command (N)
18670 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18671 If the cursor is in a table looking at whitespace, the whitespace is
18672 overwritten, and the table is not marked as requiring realignment."
18673 (interactive "p")
18674 (org-check-before-invisible-edit 'insert)
18675 (cond
18676 ((and org-use-speed-commands
18677 (setq org-speed-command
18678 (run-hook-with-args-until-success
18679 'org-speed-command-hook (this-command-keys))))
18680 (cond
18681 ((commandp org-speed-command)
18682 (setq this-command org-speed-command)
18683 (call-interactively org-speed-command))
18684 ((functionp org-speed-command)
18685 (funcall org-speed-command))
18686 ((and org-speed-command (listp org-speed-command))
18687 (eval org-speed-command))
18688 (t (let (org-use-speed-commands)
18689 (call-interactively 'org-self-insert-command)))))
18690 ((and
18691 (org-table-p)
18692 (progn
18693 ;; check if we blank the field, and if that triggers align
18694 (and (featurep 'org-table) org-table-auto-blank-field
18695 (member last-command
18696 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18697 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18698 ;; got extra space, this field does not determine column width
18699 (let (org-table-may-need-update) (org-table-blank-field))
18700 ;; no extra space, this field may determine column width
18701 (org-table-blank-field)))
18703 (eq N 1)
18704 (looking-at "[^|\n]* |"))
18705 (let (org-table-may-need-update)
18706 (goto-char (1- (match-end 0)))
18707 (backward-delete-char 1)
18708 (goto-char (match-beginning 0))
18709 (self-insert-command N)))
18711 (setq org-table-may-need-update t)
18712 (self-insert-command N)
18713 (org-fix-tags-on-the-fly)
18714 (if org-self-insert-cluster-for-undo
18715 (if (not (eq last-command 'org-self-insert-command))
18716 (setq org-self-insert-command-undo-counter 1)
18717 (if (>= org-self-insert-command-undo-counter 20)
18718 (setq org-self-insert-command-undo-counter 1)
18719 (and (> org-self-insert-command-undo-counter 0)
18720 buffer-undo-list (listp buffer-undo-list)
18721 (not (cadr buffer-undo-list)) ; remove nil entry
18722 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18723 (setq org-self-insert-command-undo-counter
18724 (1+ org-self-insert-command-undo-counter))))))))
18726 (defun org-check-before-invisible-edit (kind)
18727 "Check is editing if kind KIND would be dangerous with invisible text around.
18728 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18729 ;; First, try to get out of here as quickly as possible, to reduce overhead
18730 (if (and org-catch-invisible-edits
18731 (or (not (boundp 'visible-mode)) (not visible-mode))
18732 (or (get-char-property (point) 'invisible)
18733 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18734 ;; OK, we need to take a closer look
18735 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18736 (invisible-before-point (if (bobp) nil (get-char-property
18737 (1- (point)) 'invisible)))
18738 (border-and-ok-direction
18740 ;; Check if we are acting predictably before invisible text
18741 (and invisible-at-point (not invisible-before-point)
18742 (memq kind '(insert delete-backward)))
18743 ;; Check if we are acting predictably after invisible text
18744 ;; This works not well, and I have turned it off. It seems
18745 ;; better to always show and stop after invisible text.
18746 ;; (and (not invisible-at-point) invisible-before-point
18747 ;; (memq kind '(insert delete)))
18749 (when (or (memq invisible-at-point '(outline org-hide-block t))
18750 (memq invisible-before-point '(outline org-hide-block t)))
18751 (if (eq org-catch-invisible-edits 'error)
18752 (error "Editing in invisible areas is prohibited - make visible first"))
18753 (if (and org-custom-properties-overlays
18754 (y-or-n-p "Display invisible properties in this buffer? "))
18755 (org-toggle-custom-properties-visibility)
18756 ;; Make the area visible
18757 (save-excursion
18758 (if invisible-before-point
18759 (goto-char (previous-single-char-property-change
18760 (point) 'invisible)))
18761 (org-cycle))
18762 (cond
18763 ((eq org-catch-invisible-edits 'show)
18764 ;; That's it, we do the edit after showing
18765 (message
18766 "Unfolding invisible region around point before editing")
18767 (sit-for 1))
18768 ((and (eq org-catch-invisible-edits 'smart)
18769 border-and-ok-direction)
18770 (message "Unfolding invisible region around point before editing"))
18772 ;; Don't do the edit, make the user repeat it in full visibility
18773 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18775 (defun org-fix-tags-on-the-fly ()
18776 (when (and (equal (char-after (point-at-bol)) ?*)
18777 (org-at-heading-p))
18778 (org-align-tags-here org-tags-column)))
18780 (defun org-delete-backward-char (N)
18781 "Like `delete-backward-char', insert whitespace at field end in tables.
18782 When deleting backwards, in tables this function will insert whitespace in
18783 front of the next \"|\" separator, to keep the table aligned. The table will
18784 still be marked for re-alignment if the field did fill the entire column,
18785 because, in this case the deletion might narrow the column."
18786 (interactive "p")
18787 (save-match-data
18788 (org-check-before-invisible-edit 'delete-backward)
18789 (if (and (org-table-p)
18790 (eq N 1)
18791 (string-match "|" (buffer-substring (point-at-bol) (point)))
18792 (looking-at ".*?|"))
18793 (let ((pos (point))
18794 (noalign (looking-at "[^|\n\r]* |"))
18795 (c org-table-may-need-update))
18796 (backward-delete-char N)
18797 (if (not overwrite-mode)
18798 (progn
18799 (skip-chars-forward "^|")
18800 (insert " ")
18801 (goto-char (1- pos))))
18802 ;; noalign: if there were two spaces at the end, this field
18803 ;; does not determine the width of the column.
18804 (if noalign (setq org-table-may-need-update c)))
18805 (backward-delete-char N)
18806 (org-fix-tags-on-the-fly))))
18808 (defun org-delete-char (N)
18809 "Like `delete-char', but insert whitespace at field end in tables.
18810 When deleting characters, in tables this function will insert whitespace in
18811 front of the next \"|\" separator, to keep the table aligned. The table will
18812 still be marked for re-alignment if the field did fill the entire column,
18813 because, in this case the deletion might narrow the column."
18814 (interactive "p")
18815 (save-match-data
18816 (org-check-before-invisible-edit 'delete)
18817 (if (and (org-table-p)
18818 (not (bolp))
18819 (not (= (char-after) ?|))
18820 (eq N 1))
18821 (if (looking-at ".*?|")
18822 (let ((pos (point))
18823 (noalign (looking-at "[^|\n\r]* |"))
18824 (c org-table-may-need-update))
18825 (replace-match (concat
18826 (substring (match-string 0) 1 -1)
18827 " |"))
18828 (goto-char pos)
18829 ;; noalign: if there were two spaces at the end, this field
18830 ;; does not determine the width of the column.
18831 (if noalign (setq org-table-may-need-update c)))
18832 (delete-char N))
18833 (delete-char N)
18834 (org-fix-tags-on-the-fly))))
18836 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18837 (put 'org-self-insert-command 'delete-selection t)
18838 (put 'orgtbl-self-insert-command 'delete-selection t)
18839 (put 'org-delete-char 'delete-selection 'supersede)
18840 (put 'org-delete-backward-char 'delete-selection 'supersede)
18841 (put 'org-yank 'delete-selection 'yank)
18843 ;; Make `flyspell-mode' delay after some commands
18844 (put 'org-self-insert-command 'flyspell-delayed t)
18845 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18846 (put 'org-delete-char 'flyspell-delayed t)
18847 (put 'org-delete-backward-char 'flyspell-delayed t)
18849 ;; Make pabbrev-mode expand after org-mode commands
18850 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18851 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18853 ;; How to do this: Measure non-white length of current string
18854 ;; If equal to column width, we should realign.
18856 (defun org-remap (map &rest commands)
18857 "In MAP, remap the functions given in COMMANDS.
18858 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18859 (let (new old)
18860 (while commands
18861 (setq old (pop commands) new (pop commands))
18862 (if (fboundp 'command-remapping)
18863 (org-defkey map (vector 'remap old) new)
18864 (substitute-key-definition old new map global-map)))))
18866 (when (eq org-enable-table-editor 'optimized)
18867 ;; If the user wants maximum table support, we need to hijack
18868 ;; some standard editing functions
18869 (org-remap org-mode-map
18870 'self-insert-command 'org-self-insert-command
18871 'delete-char 'org-delete-char
18872 'delete-backward-char 'org-delete-backward-char)
18873 (org-defkey org-mode-map "|" 'org-force-self-insert))
18875 (defvar org-ctrl-c-ctrl-c-hook nil
18876 "Hook for functions attaching themselves to `C-c C-c'.
18878 This can be used to add additional functionality to the C-c C-c
18879 key which executes context-dependent commands. This hook is run
18880 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18881 run after the last test.
18883 Each function will be called with no arguments. The function
18884 must check if the context is appropriate for it to act. If yes,
18885 it should do its thing and then return a non-nil value. If the
18886 context is wrong, just do nothing and return nil.")
18888 (defvar org-ctrl-c-ctrl-c-final-hook nil
18889 "Hook for functions attaching themselves to `C-c C-c'.
18891 This can be used to add additional functionality to the C-c C-c
18892 key which executes context-dependent commands. This hook is run
18893 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18894 before the first test.
18896 Each function will be called with no arguments. The function
18897 must check if the context is appropriate for it to act. If yes,
18898 it should do its thing and then return a non-nil value. If the
18899 context is wrong, just do nothing and return nil.")
18901 (defvar org-tab-first-hook nil
18902 "Hook for functions to attach themselves to TAB.
18903 See `org-ctrl-c-ctrl-c-hook' for more information.
18904 This hook runs as the first action when TAB is pressed, even before
18905 `org-cycle' messes around with the `outline-regexp' to cater for
18906 inline tasks and plain list item folding.
18907 If any function in this hook returns t, any other actions that
18908 would have been caused by TAB (such as table field motion or visibility
18909 cycling) will not occur.")
18911 (defvar org-tab-after-check-for-table-hook nil
18912 "Hook for functions to attach themselves to TAB.
18913 See `org-ctrl-c-ctrl-c-hook' for more information.
18914 This hook runs after it has been established that the cursor is not in a
18915 table, but before checking if the cursor is in a headline or if global cycling
18916 should be done.
18917 If any function in this hook returns t, not other actions like visibility
18918 cycling will be done.")
18920 (defvar org-tab-after-check-for-cycling-hook nil
18921 "Hook for functions to attach themselves to TAB.
18922 See `org-ctrl-c-ctrl-c-hook' for more information.
18923 This hook runs after it has been established that not table field motion and
18924 not visibility should be done because of current context. This is probably
18925 the place where a package like yasnippets can hook in.")
18927 (defvar org-tab-before-tab-emulation-hook nil
18928 "Hook for functions to attach themselves to TAB.
18929 See `org-ctrl-c-ctrl-c-hook' for more information.
18930 This hook runs after every other options for TAB have been exhausted, but
18931 before indentation and \t insertion takes place.")
18933 (defvar org-metaleft-hook nil
18934 "Hook for functions attaching themselves to `M-left'.
18935 See `org-ctrl-c-ctrl-c-hook' for more information.")
18936 (defvar org-metaright-hook nil
18937 "Hook for functions attaching themselves to `M-right'.
18938 See `org-ctrl-c-ctrl-c-hook' for more information.")
18939 (defvar org-metaup-hook nil
18940 "Hook for functions attaching themselves to `M-up'.
18941 See `org-ctrl-c-ctrl-c-hook' for more information.")
18942 (defvar org-metadown-hook nil
18943 "Hook for functions attaching themselves to `M-down'.
18944 See `org-ctrl-c-ctrl-c-hook' for more information.")
18945 (defvar org-shiftmetaleft-hook nil
18946 "Hook for functions attaching themselves to `M-S-left'.
18947 See `org-ctrl-c-ctrl-c-hook' for more information.")
18948 (defvar org-shiftmetaright-hook nil
18949 "Hook for functions attaching themselves to `M-S-right'.
18950 See `org-ctrl-c-ctrl-c-hook' for more information.")
18951 (defvar org-shiftmetaup-hook nil
18952 "Hook for functions attaching themselves to `M-S-up'.
18953 See `org-ctrl-c-ctrl-c-hook' for more information.")
18954 (defvar org-shiftmetadown-hook nil
18955 "Hook for functions attaching themselves to `M-S-down'.
18956 See `org-ctrl-c-ctrl-c-hook' for more information.")
18957 (defvar org-metareturn-hook nil
18958 "Hook for functions attaching themselves to `M-RET'.
18959 See `org-ctrl-c-ctrl-c-hook' for more information.")
18960 (defvar org-shiftup-hook nil
18961 "Hook for functions attaching themselves to `S-up'.
18962 See `org-ctrl-c-ctrl-c-hook' for more information.")
18963 (defvar org-shiftup-final-hook nil
18964 "Hook for functions attaching themselves to `S-up'.
18965 This one runs after all other options except shift-select have been excluded.
18966 See `org-ctrl-c-ctrl-c-hook' for more information.")
18967 (defvar org-shiftdown-hook nil
18968 "Hook for functions attaching themselves to `S-down'.
18969 See `org-ctrl-c-ctrl-c-hook' for more information.")
18970 (defvar org-shiftdown-final-hook nil
18971 "Hook for functions attaching themselves to `S-down'.
18972 This one runs after all other options except shift-select have been excluded.
18973 See `org-ctrl-c-ctrl-c-hook' for more information.")
18974 (defvar org-shiftleft-hook nil
18975 "Hook for functions attaching themselves to `S-left'.
18976 See `org-ctrl-c-ctrl-c-hook' for more information.")
18977 (defvar org-shiftleft-final-hook nil
18978 "Hook for functions attaching themselves to `S-left'.
18979 This one runs after all other options except shift-select have been excluded.
18980 See `org-ctrl-c-ctrl-c-hook' for more information.")
18981 (defvar org-shiftright-hook nil
18982 "Hook for functions attaching themselves to `S-right'.
18983 See `org-ctrl-c-ctrl-c-hook' for more information.")
18984 (defvar org-shiftright-final-hook nil
18985 "Hook for functions attaching themselves to `S-right'.
18986 This one runs after all other options except shift-select have been excluded.
18987 See `org-ctrl-c-ctrl-c-hook' for more information.")
18989 (defun org-modifier-cursor-error ()
18990 "Throw an error, a modified cursor command was applied in wrong context."
18991 (error "This command is active in special context like tables, headlines or items"))
18993 (defun org-shiftselect-error ()
18994 "Throw an error because Shift-Cursor command was applied in wrong context."
18995 (if (and (boundp 'shift-select-mode) shift-select-mode)
18996 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18997 (error "This command works only in special context like headlines or timestamps")))
18999 (defun org-call-for-shift-select (cmd)
19000 (let ((this-command-keys-shift-translated t))
19001 (call-interactively cmd)))
19003 (defun org-shifttab (&optional arg)
19004 "Global visibility cycling or move to previous table field.
19005 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19006 on context.
19007 See the individual commands for more information."
19008 (interactive "P")
19009 (cond
19010 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19011 ((integerp arg)
19012 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19013 (message "Content view to level: %d" arg)
19014 (org-content (prefix-numeric-value arg2))
19015 (setq org-cycle-global-status 'overview)))
19016 (t (call-interactively 'org-global-cycle))))
19018 (defun org-shiftmetaleft ()
19019 "Promote subtree or delete table column.
19020 Calls `org-promote-subtree', `org-outdent-item-tree', or
19021 `org-table-delete-column', depending on context. See the
19022 individual commands for more information."
19023 (interactive)
19024 (cond
19025 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19026 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19027 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19028 ((if (not (org-region-active-p)) (org-at-item-p)
19029 (save-excursion (goto-char (region-beginning))
19030 (org-at-item-p)))
19031 (call-interactively 'org-outdent-item-tree))
19032 (t (org-modifier-cursor-error))))
19034 (defun org-shiftmetaright ()
19035 "Demote subtree or insert table column.
19036 Calls `org-demote-subtree', `org-indent-item-tree', or
19037 `org-table-insert-column', depending on context. See the
19038 individual commands for more information."
19039 (interactive)
19040 (cond
19041 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19042 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19043 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19044 ((if (not (org-region-active-p)) (org-at-item-p)
19045 (save-excursion (goto-char (region-beginning))
19046 (org-at-item-p)))
19047 (call-interactively 'org-indent-item-tree))
19048 (t (org-modifier-cursor-error))))
19050 (defun org-shiftmetaup (&optional arg)
19051 "Move subtree up or kill table row.
19052 Calls `org-move-subtree-up' or `org-table-kill-row' or
19053 `org-move-item-up' or `org-timestamp-up', depending on context.
19054 See the individual commands for more information."
19055 (interactive "P")
19056 (cond
19057 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19058 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19059 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19060 ((org-at-item-p) (call-interactively 'org-move-item-up))
19061 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19062 (call-interactively 'org-timestamp-up)))
19063 (t (org-modifier-cursor-error))))
19065 (defun org-shiftmetadown (&optional arg)
19066 "Move subtree down or insert table row.
19067 Calls `org-move-subtree-down' or `org-table-insert-row' or
19068 `org-move-item-down' or `org-timestamp-up', depending on context.
19069 See the individual commands for more information."
19070 (interactive "P")
19071 (cond
19072 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19073 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19074 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19075 ((org-at-item-p) (call-interactively 'org-move-item-down))
19076 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19077 (call-interactively 'org-timestamp-down)))
19078 (t (org-modifier-cursor-error))))
19080 (defsubst org-hidden-tree-error ()
19081 (error
19082 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19084 (defun org-metaleft (&optional arg)
19085 "Promote heading or move table column to left.
19086 Calls `org-do-promote' or `org-table-move-column', depending on context.
19087 With no specific context, calls the Emacs default `backward-word'.
19088 See the individual commands for more information."
19089 (interactive "P")
19090 (cond
19091 ((run-hook-with-args-until-success 'org-metaleft-hook))
19092 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19093 ((org-with-limited-levels
19094 (or (org-at-heading-p)
19095 (and (org-region-active-p)
19096 (save-excursion
19097 (goto-char (region-beginning))
19098 (org-at-heading-p)))))
19099 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19100 (call-interactively 'org-do-promote))
19101 ;; At an inline task.
19102 ((org-at-heading-p)
19103 (call-interactively 'org-inlinetask-promote))
19104 ((or (org-at-item-p)
19105 (and (org-region-active-p)
19106 (save-excursion
19107 (goto-char (region-beginning))
19108 (org-at-item-p))))
19109 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19110 (call-interactively 'org-outdent-item))
19111 (t (call-interactively 'backward-word))))
19113 (defun org-metaright (&optional arg)
19114 "Demote a subtree, a list item or move table column to right.
19115 In front of a drawer or a block keyword, indent it correctly.
19116 With no specific context, calls the Emacs default `forward-word'.
19117 See the individual commands for more information."
19118 (interactive "P")
19119 (cond
19120 ((run-hook-with-args-until-success 'org-metaright-hook))
19121 ((org-at-table-p) (call-interactively 'org-table-move-column))
19122 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19123 ((org-at-block-p) (call-interactively 'org-indent-block))
19124 ((org-with-limited-levels
19125 (or (org-at-heading-p)
19126 (and (org-region-active-p)
19127 (save-excursion
19128 (goto-char (region-beginning))
19129 (org-at-heading-p)))))
19130 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19131 (call-interactively 'org-do-demote))
19132 ;; At an inline task.
19133 ((org-at-heading-p)
19134 (call-interactively 'org-inlinetask-demote))
19135 ((or (org-at-item-p)
19136 (and (org-region-active-p)
19137 (save-excursion
19138 (goto-char (region-beginning))
19139 (org-at-item-p))))
19140 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19141 (call-interactively 'org-indent-item))
19142 (t (call-interactively 'forward-word))))
19144 (defun org-check-for-hidden (what)
19145 "Check if there are hidden headlines/items in the current visual line.
19146 WHAT can be either `headlines' or `items'. If the current line is
19147 an outline or item heading and it has a folded subtree below it,
19148 this function returns t, nil otherwise."
19149 (let ((re (cond
19150 ((eq what 'headlines) org-outline-regexp-bol)
19151 ((eq what 'items) (org-item-beginning-re))
19152 (t (error "This should not happen"))))
19153 beg end)
19154 (save-excursion
19155 (catch 'exit
19156 (unless (org-region-active-p)
19157 (setq beg (point-at-bol))
19158 (beginning-of-line 2)
19159 (while (and (not (eobp)) ;; this is like `next-line'
19160 (get-char-property (1- (point)) 'invisible))
19161 (beginning-of-line 2))
19162 (setq end (point))
19163 (goto-char beg)
19164 (goto-char (point-at-eol))
19165 (setq end (max end (point)))
19166 (while (re-search-forward re end t)
19167 (if (get-char-property (match-beginning 0) 'invisible)
19168 (throw 'exit t))))
19169 nil))))
19171 (defun org-metaup (&optional arg)
19172 "Move subtree up or move table row up.
19173 Calls `org-move-subtree-up' or `org-table-move-row' or
19174 `org-move-item-up', depending on context. See the individual commands
19175 for more information."
19176 (interactive "P")
19177 (cond
19178 ((run-hook-with-args-until-success 'org-metaup-hook))
19179 ((org-region-active-p)
19180 (let* ((a (min (region-beginning) (region-end)))
19181 (b (1- (max (region-beginning) (region-end))))
19182 (c (save-excursion (goto-char a)
19183 (move-beginning-of-line 0)))
19184 (d (save-excursion (goto-char a)
19185 (move-end-of-line 0) (point))))
19186 (transpose-regions a b c d)
19187 (goto-char c)))
19188 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19189 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19190 ((org-at-item-p) (call-interactively 'org-move-item-up))
19191 (t (org-drag-element-backward))))
19193 (defun org-metadown (&optional arg)
19194 "Move subtree down or move table row down.
19195 Calls `org-move-subtree-down' or `org-table-move-row' or
19196 `org-move-item-down', depending on context. See the individual
19197 commands for more information."
19198 (interactive "P")
19199 (cond
19200 ((run-hook-with-args-until-success 'org-metadown-hook))
19201 ((org-region-active-p)
19202 (let* ((a (min (region-beginning) (region-end)))
19203 (b (max (region-beginning) (region-end)))
19204 (c (save-excursion (goto-char b)
19205 (move-beginning-of-line 1)))
19206 (d (save-excursion (goto-char b)
19207 (move-end-of-line 1) (1+ (point)))))
19208 (transpose-regions a b c d)
19209 (goto-char d)))
19210 ((org-at-table-p) (call-interactively 'org-table-move-row))
19211 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19212 ((org-at-item-p) (call-interactively 'org-move-item-down))
19213 (t (org-drag-element-forward))))
19215 (defun org-shiftup (&optional arg)
19216 "Increase item in timestamp or increase priority of current headline.
19217 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19218 depending on context. See the individual commands for more information."
19219 (interactive "P")
19220 (cond
19221 ((run-hook-with-args-until-success 'org-shiftup-hook))
19222 ((and org-support-shift-select (org-region-active-p))
19223 (org-call-for-shift-select 'previous-line))
19224 ((org-at-timestamp-p t)
19225 (call-interactively (if org-edit-timestamp-down-means-later
19226 'org-timestamp-down 'org-timestamp-up)))
19227 ((and (not (eq org-support-shift-select 'always))
19228 org-enable-priority-commands
19229 (org-at-heading-p))
19230 (call-interactively 'org-priority-up))
19231 ((and (not org-support-shift-select) (org-at-item-p))
19232 (call-interactively 'org-previous-item))
19233 ((org-clocktable-try-shift 'up arg))
19234 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19235 (org-support-shift-select
19236 (org-call-for-shift-select 'previous-line))
19237 (t (org-shiftselect-error))))
19239 (defun org-shiftdown (&optional arg)
19240 "Decrease item in timestamp or decrease priority of current headline.
19241 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19242 depending on context. See the individual commands for more information."
19243 (interactive "P")
19244 (cond
19245 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19246 ((and org-support-shift-select (org-region-active-p))
19247 (org-call-for-shift-select 'next-line))
19248 ((org-at-timestamp-p t)
19249 (call-interactively (if org-edit-timestamp-down-means-later
19250 'org-timestamp-up 'org-timestamp-down)))
19251 ((and (not (eq org-support-shift-select 'always))
19252 org-enable-priority-commands
19253 (org-at-heading-p))
19254 (call-interactively 'org-priority-down))
19255 ((and (not org-support-shift-select) (org-at-item-p))
19256 (call-interactively 'org-next-item))
19257 ((org-clocktable-try-shift 'down arg))
19258 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19259 (org-support-shift-select
19260 (org-call-for-shift-select 'next-line))
19261 (t (org-shiftselect-error))))
19263 (defun org-shiftright (&optional arg)
19264 "Cycle the thing at point or in the current line, depending on context.
19265 Depending on context, this does one of the following:
19267 - switch a timestamp at point one day into the future
19268 - on a headline, switch to the next TODO keyword.
19269 - on an item, switch entire list to the next bullet type
19270 - on a property line, switch to the next allowed value
19271 - on a clocktable definition line, move time block into the future"
19272 (interactive "P")
19273 (cond
19274 ((run-hook-with-args-until-success 'org-shiftright-hook))
19275 ((and org-support-shift-select (org-region-active-p))
19276 (org-call-for-shift-select 'forward-char))
19277 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19278 ((and (not (eq org-support-shift-select 'always))
19279 (org-at-heading-p))
19280 (let ((org-inhibit-logging
19281 (not org-treat-S-cursor-todo-selection-as-state-change))
19282 (org-inhibit-blocking
19283 (not org-treat-S-cursor-todo-selection-as-state-change)))
19284 (org-call-with-arg 'org-todo 'right)))
19285 ((or (and org-support-shift-select
19286 (not (eq org-support-shift-select 'always))
19287 (org-at-item-bullet-p))
19288 (and (not org-support-shift-select) (org-at-item-p)))
19289 (org-call-with-arg 'org-cycle-list-bullet nil))
19290 ((and (not (eq org-support-shift-select 'always))
19291 (org-at-property-p))
19292 (call-interactively 'org-property-next-allowed-value))
19293 ((org-clocktable-try-shift 'right arg))
19294 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19295 (org-support-shift-select
19296 (org-call-for-shift-select 'forward-char))
19297 (t (org-shiftselect-error))))
19299 (defun org-shiftleft (&optional arg)
19300 "Cycle the thing at point or in the current line, depending on context.
19301 Depending on context, this does one of the following:
19303 - switch a timestamp at point one day into the past
19304 - on a headline, switch to the previous TODO keyword.
19305 - on an item, switch entire list to the previous bullet type
19306 - on a property line, switch to the previous allowed value
19307 - on a clocktable definition line, move time block into the past"
19308 (interactive "P")
19309 (cond
19310 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19311 ((and org-support-shift-select (org-region-active-p))
19312 (org-call-for-shift-select 'backward-char))
19313 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19314 ((and (not (eq org-support-shift-select 'always))
19315 (org-at-heading-p))
19316 (let ((org-inhibit-logging
19317 (not org-treat-S-cursor-todo-selection-as-state-change))
19318 (org-inhibit-blocking
19319 (not org-treat-S-cursor-todo-selection-as-state-change)))
19320 (org-call-with-arg 'org-todo 'left)))
19321 ((or (and org-support-shift-select
19322 (not (eq org-support-shift-select 'always))
19323 (org-at-item-bullet-p))
19324 (and (not org-support-shift-select) (org-at-item-p)))
19325 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19326 ((and (not (eq org-support-shift-select 'always))
19327 (org-at-property-p))
19328 (call-interactively 'org-property-previous-allowed-value))
19329 ((org-clocktable-try-shift 'left arg))
19330 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19331 (org-support-shift-select
19332 (org-call-for-shift-select 'backward-char))
19333 (t (org-shiftselect-error))))
19335 (defun org-shiftcontrolright ()
19336 "Switch to next TODO set."
19337 (interactive)
19338 (cond
19339 ((and org-support-shift-select (org-region-active-p))
19340 (org-call-for-shift-select 'forward-word))
19341 ((and (not (eq org-support-shift-select 'always))
19342 (org-at-heading-p))
19343 (org-call-with-arg 'org-todo 'nextset))
19344 (org-support-shift-select
19345 (org-call-for-shift-select 'forward-word))
19346 (t (org-shiftselect-error))))
19348 (defun org-shiftcontrolleft ()
19349 "Switch to previous TODO set."
19350 (interactive)
19351 (cond
19352 ((and org-support-shift-select (org-region-active-p))
19353 (org-call-for-shift-select 'backward-word))
19354 ((and (not (eq org-support-shift-select 'always))
19355 (org-at-heading-p))
19356 (org-call-with-arg 'org-todo 'previousset))
19357 (org-support-shift-select
19358 (org-call-for-shift-select 'backward-word))
19359 (t (org-shiftselect-error))))
19361 (defun org-shiftcontrolup (&optional n)
19362 "Change timestamps synchronously up in CLOCK log lines.
19363 Optional argument N tells to change by that many units."
19364 (interactive "P")
19365 (cond ((and (not org-support-shift-select)
19366 (org-at-clock-log-p)
19367 (org-at-timestamp-p t))
19368 (org-clock-timestamps-up n))
19369 (t (org-shiftselect-error))))
19371 (defun org-shiftcontroldown (&optional n)
19372 "Change timestamps synchronously down in CLOCK log lines.
19373 Optional argument N tells to change by that many units."
19374 (interactive "P")
19375 (cond ((and (not org-support-shift-select)
19376 (org-at-clock-log-p)
19377 (org-at-timestamp-p t))
19378 (org-clock-timestamps-down n))
19379 (t (org-shiftselect-error))))
19381 (defun org-ctrl-c-ret ()
19382 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19383 (interactive)
19384 (cond
19385 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19386 (t (call-interactively 'org-insert-heading))))
19388 (defun org-find-visible ()
19389 (let ((s (point)))
19390 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19391 (get-char-property s 'invisible)))
19393 (defun org-find-invisible ()
19394 (let ((s (point)))
19395 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19396 (not (get-char-property s 'invisible))))
19399 (defun org-copy-visible (beg end)
19400 "Copy the visible parts of the region."
19401 (interactive "r")
19402 (let (snippets s)
19403 (save-excursion
19404 (save-restriction
19405 (narrow-to-region beg end)
19406 (setq s (goto-char (point-min)))
19407 (while (not (= (point) (point-max)))
19408 (goto-char (org-find-invisible))
19409 (push (buffer-substring s (point)) snippets)
19410 (setq s (goto-char (org-find-visible))))))
19411 (kill-new (apply 'concat (nreverse snippets)))))
19413 (defun org-copy-special ()
19414 "Copy region in table or copy current subtree.
19415 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19416 See the individual commands for more information."
19417 (interactive)
19418 (call-interactively
19419 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19421 (defun org-cut-special ()
19422 "Cut region in table or cut current subtree.
19423 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19424 See the individual commands for more information."
19425 (interactive)
19426 (call-interactively
19427 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19429 (defun org-paste-special (arg)
19430 "Paste rectangular region into table, or past subtree relative to level.
19431 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19432 See the individual commands for more information."
19433 (interactive "P")
19434 (if (org-at-table-p)
19435 (org-table-paste-rectangle)
19436 (org-paste-subtree arg)))
19438 (defsubst org-in-fixed-width-region-p ()
19439 "Is point in a fixed-width region?"
19440 (save-match-data
19441 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19443 (defun org-edit-special (&optional arg)
19444 "Call a special editor for the element at point.
19445 When at a table, call the formula editor with `org-table-edit-formulas'.
19446 When in a source code block, call `org-edit-src-code'.
19447 When in a fixed-width region, call `org-edit-fixed-width-region'.
19448 When at an #+INCLUDE keyword, visit the included file.
19449 On a link, call `ffap' to visit the link at point.
19450 Otherwise, return an user error."
19451 (interactive)
19452 (let ((element (org-element-at-point)))
19453 (case (org-element-type element)
19454 (src-block
19455 (if (not arg) (org-edit-src-code)
19456 (let* ((info (org-babel-get-src-block-info))
19457 (lang (nth 0 info))
19458 (params (nth 2 info))
19459 (session (cdr (assq :session params))))
19460 (if (not session) (org-edit-src-code)
19461 ;; At a src-block with a session and function called with
19462 ;; an ARG: switch to the buffer related to the inferior
19463 ;; process.
19464 (funcall (intern (concat "org-babel-prep-session:" lang))
19465 session params)))))
19466 (keyword
19467 (if (equal (org-element-property :key element) "INCLUDE")
19468 (find-file
19469 (org-remove-double-quotes
19470 (car (org-split-string (org-element-property :value element)))))
19471 (user-error "No special environment to edit here")))
19472 (table
19473 (if (eq (org-element-property :type element) 'table.el)
19474 (org-edit-src-code)
19475 (call-interactively 'org-table-edit-formulas)))
19476 ;; Only Org tables contain `table-row' type elements.
19477 (table-row (call-interactively 'org-table-edit-formulas))
19478 ((example-block export-block) (org-edit-src-code))
19479 (fixed-width (org-edit-fixed-width-region))
19480 (otherwise
19481 ;; No notable element at point. Though, we may be at a link,
19482 ;; which is an object. Thus, scan deeper.
19483 (if (eq (org-element-type (org-element-context element)) 'link)
19484 (call-interactively 'ffap)
19485 (user-error "No special environment to edit here"))))))
19487 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19488 (defun org-ctrl-c-ctrl-c (&optional arg)
19489 "Set tags in headline, or update according to changed information at point.
19491 This command does many different things, depending on context:
19493 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19494 this is what we do.
19496 - If the cursor is on a statistics cookie, update it.
19498 - If the cursor is in a headline, prompt for tags and insert them
19499 into the current line, aligned to `org-tags-column'. When called
19500 with prefix arg, realign all tags in the current buffer.
19502 - If the cursor is in one of the special #+KEYWORD lines, this
19503 triggers scanning the buffer for these lines and updating the
19504 information.
19506 - If the cursor is inside a table, realign the table. This command
19507 works even if the automatic table editor has been turned off.
19509 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19510 the entire table.
19512 - If the cursor is at a footnote reference or definition, jump to
19513 the corresponding definition or references, respectively.
19515 - If the cursor is a the beginning of a dynamic block, update it.
19517 - If the current buffer is a capture buffer, close note and file it.
19519 - If the cursor is on a <<<target>>>, update radio targets and
19520 corresponding links in this buffer.
19522 - If the cursor is on a numbered item in a plain list, renumber the
19523 ordered list.
19525 - If the cursor is on a checkbox, toggle it.
19527 - If the cursor is on a code block, evaluate it. The variable
19528 `org-confirm-babel-evaluate' can be used to control prompting
19529 before code block evaluation, by default every code block
19530 evaluation requires confirmation. Code block evaluation can be
19531 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19532 (interactive "P")
19533 (let ((org-enable-table-editor t))
19534 (cond
19535 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19536 org-occur-highlights
19537 org-latex-fragment-image-overlays)
19538 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19539 (org-remove-occur-highlights)
19540 (org-remove-latex-fragment-image-overlays)
19541 (message "Temporary highlights/overlays removed from current buffer"))
19542 ((and (local-variable-p 'org-finish-function (current-buffer))
19543 (fboundp org-finish-function))
19544 (funcall org-finish-function))
19545 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19546 ((org-in-regexp org-ts-regexp-both)
19547 (org-timestamp-change 0 'day))
19548 ((or (looking-at org-property-start-re)
19549 (org-at-property-p))
19550 (call-interactively 'org-property-action))
19551 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19552 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19553 (or (org-at-heading-p) (org-at-item-p)))
19554 (call-interactively 'org-update-statistics-cookies))
19555 ((org-at-heading-p) (call-interactively 'org-set-tags))
19556 ((org-at-table.el-p)
19557 (message "Use C-c ' to edit table.el tables"))
19558 ((org-at-table-p)
19559 (org-table-maybe-eval-formula)
19560 (if arg
19561 (call-interactively 'org-table-recalculate)
19562 (org-table-maybe-recalculate-line))
19563 (call-interactively 'org-table-align)
19564 (orgtbl-send-table 'maybe))
19565 ((or (org-footnote-at-reference-p)
19566 (org-footnote-at-definition-p))
19567 (call-interactively 'org-footnote-action))
19568 ((org-at-item-checkbox-p)
19569 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19570 ;; list only if at top item.
19571 (let* ((cbox (match-string 1))
19572 (struct (org-list-struct))
19573 (old-struct (copy-tree struct))
19574 (parents (org-list-parents-alist struct))
19575 (orderedp (org-entry-get nil "ORDERED"))
19576 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19577 block-item)
19578 ;; Use a light version of `org-toggle-checkbox' to avoid
19579 ;; computing list structure twice.
19580 (let ((new-box (cond
19581 ((equal arg '(16)) "[-]")
19582 ((equal arg '(4)) nil)
19583 ((equal "[X]" cbox) "[ ]")
19584 (t "[X]"))))
19585 (if (and firstp arg)
19586 ;; If at first item of sub-list, remove check-box from
19587 ;; every item at the same level.
19588 (mapc
19589 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19590 (org-list-get-all-items
19591 (point-at-bol) struct (org-list-prevs-alist struct)))
19592 (org-list-set-checkbox (point-at-bol) struct new-box)))
19593 ;; Replicate `org-list-write-struct', while grabbing a return
19594 ;; value from `org-list-struct-fix-box'.
19595 (org-list-struct-fix-ind struct parents 2)
19596 (org-list-struct-fix-item-end struct)
19597 (let ((prevs (org-list-prevs-alist struct)))
19598 (org-list-struct-fix-bul struct prevs)
19599 (org-list-struct-fix-ind struct parents)
19600 (setq block-item
19601 (org-list-struct-fix-box struct parents prevs orderedp)))
19602 (if (equal struct old-struct)
19603 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19604 (org-list-struct-apply-struct struct old-struct)
19605 (org-update-checkbox-count-maybe))
19606 (when block-item
19607 (message
19608 "Checkboxes were removed due to unchecked box at line %d"
19609 (org-current-line block-item)))
19610 (when firstp (org-list-send-list 'maybe))))
19611 ((org-at-item-p)
19612 ;; Cursor at an item: repair list. Do checkbox related actions
19613 ;; only if function was called with an argument. Send list only
19614 ;; if at top item.
19615 (let* ((struct (org-list-struct))
19616 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19617 old-struct)
19618 (when arg
19619 (setq old-struct (copy-tree struct))
19620 (if firstp
19621 ;; If at first item of sub-list, add check-box to every
19622 ;; item at the same level.
19623 (mapc
19624 (lambda (pos)
19625 (unless (org-list-get-checkbox pos struct)
19626 (org-list-set-checkbox pos struct "[ ]")))
19627 (org-list-get-all-items
19628 (point-at-bol) struct (org-list-prevs-alist struct)))
19629 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19630 (org-list-write-struct
19631 struct (org-list-parents-alist struct) old-struct)
19632 (when arg (org-update-checkbox-count-maybe))
19633 (when firstp (org-list-send-list 'maybe))))
19634 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19635 ;; Dynamic block
19636 (beginning-of-line 1)
19637 (save-excursion (org-update-dblock)))
19638 ((save-excursion
19639 (let ((case-fold-search t))
19640 (beginning-of-line 1)
19641 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19642 (cond
19643 ((or (equal (match-string 1) "TBLFM")
19644 (equal (match-string 1) "tblfm"))
19645 ;; Recalculate the table before this line
19646 (save-excursion
19647 (beginning-of-line 1)
19648 (skip-chars-backward " \r\n\t")
19649 (if (org-at-table-p)
19650 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19652 (let ((org-inhibit-startup-visibility-stuff t)
19653 (org-startup-align-all-tables nil))
19654 (when (boundp 'org-table-coordinate-overlays)
19655 (mapc 'delete-overlay org-table-coordinate-overlays)
19656 (setq org-table-coordinate-overlays nil))
19657 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19658 (message "Local setup has been refreshed"))))
19659 ((org-clock-update-time-maybe))
19661 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19662 (error "C-c C-c can do nothing useful at this location"))))))
19664 (defun org-mode-restart ()
19665 "Restart Org-mode, to scan again for special lines.
19666 Also updates the keyword regular expressions."
19667 (interactive)
19668 (org-mode)
19669 (message "Org-mode restarted"))
19671 (defun org-kill-note-or-show-branches ()
19672 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19673 (interactive)
19674 (if (not org-finish-function)
19675 (progn
19676 (hide-subtree)
19677 (call-interactively 'show-branches))
19678 (let ((org-note-abort t))
19679 (funcall org-finish-function))))
19681 (defun org-return (&optional indent)
19682 "Goto next table row or insert a newline.
19683 Calls `org-table-next-row' or `newline', depending on context.
19684 See the individual commands for more information."
19685 (interactive)
19686 (let (org-ts-what)
19687 (cond
19688 ((or (bobp) (org-in-src-block-p))
19689 (if indent (newline-and-indent) (newline)))
19690 ((org-at-table-p)
19691 (org-table-justify-field-maybe)
19692 (call-interactively 'org-table-next-row))
19693 ;; when `newline-and-indent' is called within a list, make sure
19694 ;; text moved stays inside the item.
19695 ((and (org-in-item-p) indent)
19696 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19697 (progn
19698 (save-match-data (newline))
19699 (org-indent-line-to (length (match-string 0))))
19700 (let ((ind (org-get-indentation)))
19701 (newline)
19702 (if (org-looking-back org-list-end-re)
19703 (org-indent-line)
19704 (org-indent-line-to ind)))))
19705 ((and org-return-follows-link
19706 (org-at-timestamp-p t)
19707 (not (eq org-ts-what 'after)))
19708 (org-follow-timestamp-link))
19709 ((and org-return-follows-link
19710 (let ((tprop (get-text-property (point) 'face)))
19711 (or (eq tprop 'org-link)
19712 (and (listp tprop) (memq 'org-link tprop)))))
19713 (call-interactively 'org-open-at-point))
19714 ((and (org-at-heading-p)
19715 (looking-at
19716 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19717 (org-show-entry)
19718 (end-of-line 1)
19719 (newline))
19720 (t (if indent (newline-and-indent) (newline))))))
19722 (defun org-return-indent ()
19723 "Goto next table row or insert a newline and indent.
19724 Calls `org-table-next-row' or `newline-and-indent', depending on
19725 context. See the individual commands for more information."
19726 (interactive)
19727 (org-return t))
19729 (defun org-ctrl-c-star ()
19730 "Compute table, or change heading status of lines.
19731 Calls `org-table-recalculate' or `org-toggle-heading',
19732 depending on context."
19733 (interactive)
19734 (cond
19735 ((org-at-table-p)
19736 (call-interactively 'org-table-recalculate))
19738 ;; Convert all lines in region to list items
19739 (call-interactively 'org-toggle-heading))))
19741 (defun org-ctrl-c-minus ()
19742 "Insert separator line in table or modify bullet status of line.
19743 Also turns a plain line or a region of lines into list items.
19744 Calls `org-table-insert-hline', `org-toggle-item', or
19745 `org-cycle-list-bullet', depending on context."
19746 (interactive)
19747 (cond
19748 ((org-at-table-p)
19749 (call-interactively 'org-table-insert-hline))
19750 ((org-region-active-p)
19751 (call-interactively 'org-toggle-item))
19752 ((org-in-item-p)
19753 (call-interactively 'org-cycle-list-bullet))
19755 (call-interactively 'org-toggle-item))))
19757 (defun org-toggle-item (arg)
19758 "Convert headings or normal lines to items, items to normal lines.
19759 If there is no active region, only the current line is considered.
19761 If the first non blank line in the region is an headline, convert
19762 all headlines to items, shifting text accordingly.
19764 If it is an item, convert all items to normal lines.
19766 If it is normal text, change region into an item. With a prefix
19767 argument ARG, change each line in region into an item."
19768 (interactive "P")
19769 (let ((shift-text
19770 (function
19771 ;; Shift text in current section to IND, from point to END.
19772 ;; The function leaves point to END line.
19773 (lambda (ind end)
19774 (let ((min-i 1000) (end (copy-marker end)))
19775 ;; First determine the minimum indentation (MIN-I) of
19776 ;; the text.
19777 (save-excursion
19778 (catch 'exit
19779 (while (< (point) end)
19780 (let ((i (org-get-indentation)))
19781 (cond
19782 ;; Skip blank lines and inline tasks.
19783 ((looking-at "^[ \t]*$"))
19784 ((looking-at org-outline-regexp-bol))
19785 ;; We can't find less than 0 indentation.
19786 ((zerop i) (throw 'exit (setq min-i 0)))
19787 ((< i min-i) (setq min-i i))))
19788 (forward-line))))
19789 ;; Then indent each line so that a line indented to
19790 ;; MIN-I becomes indented to IND. Ignore blank lines
19791 ;; and inline tasks in the process.
19792 (let ((delta (- ind min-i)))
19793 (while (< (point) end)
19794 (unless (or (looking-at "^[ \t]*$")
19795 (looking-at org-outline-regexp-bol))
19796 (org-indent-line-to (+ (org-get-indentation) delta)))
19797 (forward-line)))))))
19798 (skip-blanks
19799 (function
19800 ;; Return beginning of first non-blank line, starting from
19801 ;; line at POS.
19802 (lambda (pos)
19803 (save-excursion
19804 (goto-char pos)
19805 (skip-chars-forward " \r\t\n")
19806 (point-at-bol)))))
19807 beg end)
19808 ;; Determine boundaries of changes.
19809 (if (org-region-active-p)
19810 (setq beg (funcall skip-blanks (region-beginning))
19811 end (copy-marker (region-end)))
19812 (setq beg (funcall skip-blanks (point-at-bol))
19813 end (copy-marker (point-at-eol))))
19814 ;; Depending on the starting line, choose an action on the text
19815 ;; between BEG and END.
19816 (org-with-limited-levels
19817 (save-excursion
19818 (goto-char beg)
19819 (cond
19820 ;; Case 1. Start at an item: de-itemize. Note that it only
19821 ;; happens when a region is active: `org-ctrl-c-minus'
19822 ;; would call `org-cycle-list-bullet' otherwise.
19823 ((org-at-item-p)
19824 (while (< (point) end)
19825 (when (org-at-item-p)
19826 (skip-chars-forward " \t")
19827 (delete-region (point) (match-end 0)))
19828 (forward-line)))
19829 ;; Case 2. Start at an heading: convert to items.
19830 ((org-at-heading-p)
19831 (let* ((bul (org-list-bullet-string "-"))
19832 (bul-len (length bul))
19833 ;; Indentation of the first heading. It should be
19834 ;; relative to the indentation of its parent, if any.
19835 (start-ind (save-excursion
19836 (cond
19837 ((not org-adapt-indentation) 0)
19838 ((not (outline-previous-heading)) 0)
19839 (t (length (match-string 0))))))
19840 ;; Level of first heading. Further headings will be
19841 ;; compared to it to determine hierarchy in the list.
19842 (ref-level (org-reduced-level (org-outline-level))))
19843 (while (< (point) end)
19844 (let* ((level (org-reduced-level (org-outline-level)))
19845 (delta (max 0 (- level ref-level))))
19846 ;; If current headline is less indented than the first
19847 ;; one, set it as reference, in order to preserve
19848 ;; subtrees.
19849 (when (< level ref-level) (setq ref-level level))
19850 (replace-match bul t t)
19851 (org-indent-line-to (+ start-ind (* delta bul-len)))
19852 ;; Ensure all text down to END (or SECTION-END) belongs
19853 ;; to the newly created item.
19854 (let ((section-end (save-excursion
19855 (or (outline-next-heading) (point)))))
19856 (forward-line)
19857 (funcall shift-text
19858 (+ start-ind (* (1+ delta) bul-len))
19859 (min end section-end)))))))
19860 ;; Case 3. Normal line with ARG: turn each non-item line into
19861 ;; an item.
19862 (arg
19863 (while (< (point) end)
19864 (unless (or (org-at-heading-p) (org-at-item-p))
19865 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19866 (replace-match
19867 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19868 (forward-line)))
19869 ;; Case 4. Normal line without ARG: make the first line of
19870 ;; region an item, and shift indentation of others
19871 ;; lines to set them as item's body.
19872 (t (let* ((bul (org-list-bullet-string "-"))
19873 (bul-len (length bul))
19874 (ref-ind (org-get-indentation)))
19875 (skip-chars-forward " \t")
19876 (insert bul)
19877 (forward-line)
19878 (while (< (point) end)
19879 ;; Ensure that lines less indented than first one
19880 ;; still get included in item body.
19881 (funcall shift-text
19882 (+ ref-ind bul-len)
19883 (min end (save-excursion (or (outline-next-heading)
19884 (point)))))
19885 (forward-line)))))))))
19887 (defun org-toggle-heading (&optional nstars)
19888 "Convert headings to normal text, or items or text to headings.
19889 If there is no active region, only the current line is considered.
19891 With a \\[universal-argument] prefix, convert the whole list at
19892 point into heading.
19894 In a region:
19896 - If the first non blank line is an headline, remove the stars
19897 from all headlines in the region.
19899 - If it is a normal line turn each and every normal line (i.e. not an
19900 heading or an item) in the region into a heading.
19902 - If it is a plain list item, turn all plain list items into headings.
19904 When converting a line into a heading, the number of stars is chosen
19905 such that the lines become children of the current entry. However,
19906 when a prefix argument is given, its value determines the number of
19907 stars to add."
19908 (interactive "P")
19909 (let ((skip-blanks
19910 (function
19911 ;; Return beginning of first non-blank line, starting from
19912 ;; line at POS.
19913 (lambda (pos)
19914 (save-excursion
19915 (goto-char pos)
19916 (while (org-at-comment-p) (forward-line))
19917 (skip-chars-forward " \r\t\n")
19918 (point-at-bol)))))
19919 beg end toggled)
19920 ;; Determine boundaries of changes. If a universal prefix has
19921 ;; been given, put the list in a region. If region ends at a bol,
19922 ;; do not consider the last line to be in the region.
19924 (when (and current-prefix-arg (org-at-item-p))
19925 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19926 (org-mark-element))
19928 (if (org-region-active-p)
19929 (setq beg (funcall skip-blanks (region-beginning))
19930 end (copy-marker (save-excursion
19931 (goto-char (region-end))
19932 (if (bolp) (point) (point-at-eol)))))
19933 (setq beg (funcall skip-blanks (point-at-bol))
19934 end (copy-marker (point-at-eol))))
19935 ;; Ensure inline tasks don't count as headings.
19936 (org-with-limited-levels
19937 (save-excursion
19938 (goto-char beg)
19939 (cond
19940 ;; Case 1. Started at an heading: de-star headings.
19941 ((org-at-heading-p)
19942 (while (< (point) end)
19943 (when (org-at-heading-p t)
19944 (looking-at org-outline-regexp) (replace-match "")
19945 (setq toggled t))
19946 (forward-line)))
19947 ;; Case 2. Started at an item: change items into headlines.
19948 ;; One star will be added by `org-list-to-subtree'.
19949 ((org-at-item-p)
19950 (let* ((stars (make-string
19951 (if nstars
19952 ;; subtract the star that will be added again by
19953 ;; `org-list-to-subtree'
19954 (1- (prefix-numeric-value current-prefix-arg))
19955 (or (org-current-level) 0))
19956 ?*))
19957 (add-stars
19958 (cond (nstars "") ; stars from prefix only
19959 ((equal stars "") "") ; before first heading
19960 (org-odd-levels-only "*") ; inside heading, odd
19961 (t "")))) ; inside heading, oddeven
19962 (while (< (point) end)
19963 (when (org-at-item-p)
19964 ;; Pay attention to cases when region ends before list.
19965 (let* ((struct (org-list-struct))
19966 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19967 (save-restriction
19968 (narrow-to-region (point) list-end)
19969 (insert
19970 (org-list-to-subtree
19971 (org-list-parse-list t)
19972 '(:istart (concat stars add-stars (funcall get-stars depth))
19973 :icount (concat stars add-stars (funcall get-stars depth)))))))
19974 (setq toggled t))
19975 (forward-line))))
19976 ;; Case 3. Started at normal text: make every line an heading,
19977 ;; skipping headlines and items.
19978 (t (let* ((stars (make-string
19979 (if nstars
19980 (prefix-numeric-value current-prefix-arg)
19981 (or (org-current-level) 0))
19982 ?*))
19983 (add-stars
19984 (cond (nstars "") ; stars from prefix only
19985 ((equal stars "") "*") ; before first heading
19986 (org-odd-levels-only "**") ; inside heading, odd
19987 (t "*"))) ; inside heading, oddeven
19988 (rpl (concat stars add-stars " ")))
19989 (while (< (point) end)
19990 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19991 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19992 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19993 (forward-line)))))))
19994 (unless toggled (message "Cannot toggle heading from here"))))
19996 (defun org-meta-return (&optional arg)
19997 "Insert a new heading or wrap a region in a table.
19998 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19999 See the individual commands for more information."
20000 (interactive "P")
20001 (cond
20002 ((run-hook-with-args-until-success 'org-metareturn-hook))
20003 ((or (org-at-drawer-p) (org-at-property-p))
20004 (newline-and-indent))
20005 ((org-at-table-p)
20006 (call-interactively 'org-table-wrap-region))
20007 (t (call-interactively 'org-insert-heading))))
20009 ;;; Menu entries
20011 (defsubst org-in-subtree-not-table-p ()
20012 "Are we in a subtree and not in a table?"
20013 (and (not (org-before-first-heading-p))
20014 (not (org-at-table-p))))
20016 ;; Define the Org-mode menus
20017 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20018 '("Tbl"
20019 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20020 ["Next Field" org-cycle (org-at-table-p)]
20021 ["Previous Field" org-shifttab (org-at-table-p)]
20022 ["Next Row" org-return (org-at-table-p)]
20023 "--"
20024 ["Blank Field" org-table-blank-field (org-at-table-p)]
20025 ["Edit Field" org-table-edit-field (org-at-table-p)]
20026 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20027 "--"
20028 ("Column"
20029 ["Move Column Left" org-metaleft (org-at-table-p)]
20030 ["Move Column Right" org-metaright (org-at-table-p)]
20031 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20032 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20033 ("Row"
20034 ["Move Row Up" org-metaup (org-at-table-p)]
20035 ["Move Row Down" org-metadown (org-at-table-p)]
20036 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20037 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20038 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20039 "--"
20040 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20041 ("Rectangle"
20042 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20043 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20044 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20045 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20046 "--"
20047 ("Calculate"
20048 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20049 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20050 ["Edit Formulas" org-edit-special (org-at-table-p)]
20051 "--"
20052 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20053 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20054 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20055 "--"
20056 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20057 "--"
20058 ["Sum Column/Rectangle" org-table-sum
20059 (or (org-at-table-p) (org-region-active-p))]
20060 ["Which Column?" org-table-current-column (org-at-table-p)])
20061 ["Debug Formulas"
20062 org-table-toggle-formula-debugger
20063 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20064 ["Show Col/Row Numbers"
20065 org-table-toggle-coordinate-overlays
20066 :style toggle
20067 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20068 "--"
20069 ["Create" org-table-create (and (not (org-at-table-p))
20070 org-enable-table-editor)]
20071 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20072 ["Import from File" org-table-import (not (org-at-table-p))]
20073 ["Export to File" org-table-export (org-at-table-p)]
20074 "--"
20075 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20077 (easy-menu-define org-org-menu org-mode-map "Org menu"
20078 '("Org"
20079 ("Show/Hide"
20080 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20081 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20082 ["Sparse Tree..." org-sparse-tree t]
20083 ["Reveal Context" org-reveal t]
20084 ["Show All" show-all t]
20085 "--"
20086 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20087 "--"
20088 ["New Heading" org-insert-heading t]
20089 ("Navigate Headings"
20090 ["Up" outline-up-heading t]
20091 ["Next" outline-next-visible-heading t]
20092 ["Previous" outline-previous-visible-heading t]
20093 ["Next Same Level" outline-forward-same-level t]
20094 ["Previous Same Level" outline-backward-same-level t]
20095 "--"
20096 ["Jump" org-goto t])
20097 ("Edit Structure"
20098 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20099 "--"
20100 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20101 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20102 "--"
20103 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20104 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20105 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20106 "--"
20107 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20108 "--"
20109 ["Copy visible text" org-copy-visible t]
20110 "--"
20111 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20112 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20113 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20114 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20115 "--"
20116 ["Sort Region/Children" org-sort t]
20117 "--"
20118 ["Convert to odd levels" org-convert-to-odd-levels t]
20119 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20120 ("Editing"
20121 ["Emphasis..." org-emphasize t]
20122 ["Edit Source Example" org-edit-special t]
20123 "--"
20124 ["Footnote new/jump" org-footnote-action t]
20125 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20126 ("Archive"
20127 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20128 "--"
20129 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20130 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20131 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20133 "--"
20134 ("Hyperlinks"
20135 ["Store Link (Global)" org-store-link t]
20136 ["Find existing link to here" org-occur-link-in-agenda-files t]
20137 ["Insert Link" org-insert-link t]
20138 ["Follow Link" org-open-at-point t]
20139 "--"
20140 ["Next link" org-next-link t]
20141 ["Previous link" org-previous-link t]
20142 "--"
20143 ["Descriptive Links"
20144 org-toggle-link-display
20145 :style radio
20146 :selected org-descriptive-links
20148 ["Literal Links"
20149 org-toggle-link-display
20150 :style radio
20151 :selected (not org-descriptive-links)])
20152 "--"
20153 ("TODO Lists"
20154 ["TODO/DONE/-" org-todo t]
20155 ("Select keyword"
20156 ["Next keyword" org-shiftright (org-at-heading-p)]
20157 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20158 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20159 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20160 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20161 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20162 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20163 "--"
20164 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20165 :selected org-enforce-todo-dependencies :style toggle :active t]
20166 "Settings for tree at point"
20167 ["Do Children sequentially" org-toggle-ordered-property :style radio
20168 :selected (org-entry-get nil "ORDERED")
20169 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20170 ["Do Children parallel" org-toggle-ordered-property :style radio
20171 :selected (not (org-entry-get nil "ORDERED"))
20172 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20173 "--"
20174 ["Set Priority" org-priority t]
20175 ["Priority Up" org-shiftup t]
20176 ["Priority Down" org-shiftdown t]
20177 "--"
20178 ["Get news from all feeds" org-feed-update-all t]
20179 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20180 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20181 ("TAGS and Properties"
20182 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20183 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20184 "--"
20185 ["Set property" org-set-property (not (org-before-first-heading-p))]
20186 ["Column view of properties" org-columns t]
20187 ["Insert Column View DBlock" org-insert-columns-dblock t])
20188 ("Dates and Scheduling"
20189 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20190 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20191 ("Change Date"
20192 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20193 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20194 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20195 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20196 ["Compute Time Range" org-evaluate-time-range t]
20197 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20198 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20199 "--"
20200 ["Custom time format" org-toggle-time-stamp-overlays
20201 :style radio :selected org-display-custom-times]
20202 "--"
20203 ["Goto Calendar" org-goto-calendar t]
20204 ["Date from Calendar" org-date-from-calendar t]
20205 "--"
20206 ["Start/Restart Timer" org-timer-start t]
20207 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20208 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20209 ["Insert Timer String" org-timer t]
20210 ["Insert Timer Item" org-timer-item t])
20211 ("Logging work"
20212 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20213 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20214 ["Clock out" org-clock-out t]
20215 ["Clock cancel" org-clock-cancel t]
20216 "--"
20217 ["Mark as default task" org-clock-mark-default-task t]
20218 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20219 ["Goto running clock" org-clock-goto t]
20220 "--"
20221 ["Display times" org-clock-display t]
20222 ["Create clock table" org-clock-report t]
20223 "--"
20224 ["Record DONE time"
20225 (progn (setq org-log-done (not org-log-done))
20226 (message "Switching to %s will %s record a timestamp"
20227 (car org-done-keywords)
20228 (if org-log-done "automatically" "not")))
20229 :style toggle :selected org-log-done])
20230 "--"
20231 ["Agenda Command..." org-agenda t]
20232 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20233 ("File List for Agenda")
20234 ("Special views current file"
20235 ["TODO Tree" org-show-todo-tree t]
20236 ["Check Deadlines" org-check-deadlines t]
20237 ["Timeline" org-timeline t]
20238 ["Tags/Property tree" org-match-sparse-tree t])
20239 "--"
20240 ["Export/Publish..." org-export t]
20241 ("LaTeX"
20242 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20243 :selected org-cdlatex-mode]
20244 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20245 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20246 ["Modify math symbol" org-cdlatex-math-modify
20247 (org-inside-LaTeX-fragment-p)]
20248 ["Insert citation" org-reftex-citation t]
20249 "--"
20250 ["Template for BEAMER" (progn (require 'org-beamer)
20251 (org-insert-beamer-options-template)) t])
20252 "--"
20253 ("MobileOrg"
20254 ["Push Files and Views" org-mobile-push t]
20255 ["Get Captured and Flagged" org-mobile-pull t]
20256 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20257 "--"
20258 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20259 "--"
20260 ("Documentation"
20261 ["Show Version" org-version t]
20262 ["Info Documentation" org-info t])
20263 ("Customize"
20264 ["Browse Org Group" org-customize t]
20265 "--"
20266 ["Expand This Menu" org-create-customize-menu
20267 (fboundp 'customize-menu-create)])
20268 ["Send bug report" org-submit-bug-report t]
20269 "--"
20270 ("Refresh/Reload"
20271 ["Refresh setup current buffer" org-mode-restart t]
20272 ["Reload Org (after update)" org-reload t]
20273 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20276 (defun org-info (&optional node)
20277 "Read documentation for Org-mode in the info system.
20278 With optional NODE, go directly to that node."
20279 (interactive)
20280 (info (format "(org)%s" (or node ""))))
20282 ;;;###autoload
20283 (defun org-submit-bug-report ()
20284 "Submit a bug report on Org-mode via mail.
20286 Don't hesitate to report any problems or inaccurate documentation.
20288 If you don't have setup sending mail from (X)Emacs, please copy the
20289 output buffer into your mail program, as it gives us important
20290 information about your Org-mode version and configuration."
20291 (interactive)
20292 (require 'reporter)
20293 (org-load-modules-maybe)
20294 (org-require-autoloaded-modules)
20295 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20296 (reporter-submit-bug-report
20297 "emacs-orgmode@gnu.org"
20298 (org-version nil 'full)
20299 (let (list)
20300 (save-window-excursion
20301 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20302 (delete-other-windows)
20303 (erase-buffer)
20304 (insert "You are about to submit a bug report to the Org-mode mailing list.
20306 We would like to add your full Org-mode and Outline configuration to the
20307 bug report. This greatly simplifies the work of the maintainer and
20308 other experts on the mailing list.
20310 HOWEVER, some variables you have customized may contain private
20311 information. The names of customers, colleagues, or friends, might
20312 appear in the form of file names, tags, todo states, or search strings.
20313 If you answer yes to the prompt, you might want to check and remove
20314 such private information before sending the email.")
20315 (add-text-properties (point-min) (point-max) '(face org-warning))
20316 (when (yes-or-no-p "Include your Org-mode configuration ")
20317 (mapatoms
20318 (lambda (v)
20319 (and (boundp v)
20320 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20321 (or (and (symbol-value v)
20322 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20323 (and
20324 (get v 'custom-type) (get v 'standard-value)
20325 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20326 (push v list)))))
20327 (kill-buffer (get-buffer "*Warn about privacy*"))
20328 list))
20329 nil nil
20330 "Remember to cover the basics, that is, what you expected to happen and
20331 what in fact did happen. You don't know how to make a good report? See
20333 http://orgmode.org/manual/Feedback.html#Feedback
20335 Your bug report will be posted to the Org-mode mailing list.
20336 ------------------------------------------------------------------------")
20337 (save-excursion
20338 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20339 (replace-match "\\1Bug: \\3 [\\2]")))))
20342 (defun org-install-agenda-files-menu ()
20343 (let ((bl (buffer-list)))
20344 (save-excursion
20345 (while bl
20346 (set-buffer (pop bl))
20347 (if (derived-mode-p 'org-mode) (setq bl nil)))
20348 (when (derived-mode-p 'org-mode)
20349 (easy-menu-change
20350 '("Org") "File List for Agenda"
20351 (append
20352 (list
20353 ["Edit File List" (org-edit-agenda-file-list) t]
20354 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20355 ["Remove Current File from List" org-remove-file t]
20356 ["Cycle through agenda files" org-cycle-agenda-files t]
20357 ["Occur in all agenda files" org-occur-in-agenda-files t]
20358 "--")
20359 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20361 ;;;; Documentation
20363 (defun org-require-autoloaded-modules ()
20364 (interactive)
20365 (mapc 'require
20366 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20367 org-docbook org-exp org-html org-icalendar
20368 org-id org-latex
20369 org-publish org-remember org-table
20370 org-timer org-xoxo)))
20372 ;;;###autoload
20373 (defun org-reload (&optional uncompiled)
20374 "Reload all org lisp files.
20375 With prefix arg UNCOMPILED, load the uncompiled versions."
20376 (interactive "P")
20377 (require 'loadhist)
20378 (let* ((org-dir (org-find-library-dir "org"))
20379 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20380 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20381 (remove-re (mapconcat 'identity
20382 (mapcar (lambda (f) (concat "^" f "$"))
20383 (list (if (featurep 'xemacs)
20384 "org-colview"
20385 "org-colview-xemacs")
20386 "org" "org-loaddefs" "org-version"))
20387 "\\|"))
20388 (feats (delete-dups
20389 (mapcar 'file-name-sans-extension
20390 (mapcar 'file-name-nondirectory
20391 (delq nil
20392 (mapcar 'feature-file
20393 features))))))
20394 (lfeat (append
20395 (sort
20396 (setq feats
20397 (delq nil (mapcar
20398 (lambda (f)
20399 (if (and (string-match feature-re f)
20400 (not (string-match remove-re f)))
20401 f nil))
20402 feats)))
20403 'string-lessp)
20404 (list "org-version" "org")))
20405 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20406 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20407 load-uncore load-misses)
20408 (setq load-misses
20409 (delq 't
20410 (mapcar (lambda (f)
20411 (or (org-load-noerror-mustsuffix (concat org-dir f))
20412 (and (string= org-dir contrib-dir)
20413 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20414 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20415 (add-to-list 'load-uncore f 'append)
20418 lfeat)))
20419 (if load-uncore
20420 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20421 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20422 (if load-misses
20423 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20424 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20425 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20427 ;;;###autoload
20428 (defun org-customize ()
20429 "Call the customize function with org as argument."
20430 (interactive)
20431 (org-load-modules-maybe)
20432 (org-require-autoloaded-modules)
20433 (customize-browse 'org))
20435 (defun org-create-customize-menu ()
20436 "Create a full customization menu for Org-mode, insert it into the menu."
20437 (interactive)
20438 (org-load-modules-maybe)
20439 (org-require-autoloaded-modules)
20440 (if (fboundp 'customize-menu-create)
20441 (progn
20442 (easy-menu-change
20443 '("Org") "Customize"
20444 `(["Browse Org group" org-customize t]
20445 "--"
20446 ,(customize-menu-create 'org)
20447 ["Set" Custom-set t]
20448 ["Save" Custom-save t]
20449 ["Reset to Current" Custom-reset-current t]
20450 ["Reset to Saved" Custom-reset-saved t]
20451 ["Reset to Standard Settings" Custom-reset-standard t]))
20452 (message "\"Org\"-menu now contains full customization menu"))
20453 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20455 ;;;; Miscellaneous stuff
20457 ;;; Generally useful functions
20459 (defun org-get-at-bol (property)
20460 "Get text property PROPERTY at beginning of line."
20461 (get-text-property (point-at-bol) property))
20463 (defun org-find-text-property-in-string (prop s)
20464 "Return the first non-nil value of property PROP in string S."
20465 (or (get-text-property 0 prop s)
20466 (get-text-property (or (next-single-property-change 0 prop s) 0)
20467 prop s)))
20469 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20470 "Display the given MESSAGE as a warning."
20471 (if (fboundp 'display-warning)
20472 (display-warning 'org message
20473 (if (featurep 'xemacs) 'warning :warning))
20474 (let ((buf (get-buffer-create "*Org warnings*")))
20475 (with-current-buffer buf
20476 (goto-char (point-max))
20477 (insert "Warning (Org): " message)
20478 (unless (bolp)
20479 (newline)))
20480 (display-buffer buf)
20481 (sit-for 0))))
20483 (defun org-eval (form)
20484 "Eval FORM and return result."
20485 (condition-case error
20486 (eval form)
20487 (error (format "%%![Error: %s]" error))))
20489 (defun org-in-clocktable-p ()
20490 "Check if the cursor is in a clocktable."
20491 (let ((pos (point)) start)
20492 (save-excursion
20493 (end-of-line 1)
20494 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20495 (setq start (match-beginning 0))
20496 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20497 (>= (match-end 0) pos)
20498 start))))
20500 (defun org-in-commented-line ()
20501 "Is point in a line starting with `#'?"
20502 (equal (char-after (point-at-bol)) ?#))
20504 (defun org-in-indented-comment-line ()
20505 "Is point in a line starting with `#' after some white space?"
20506 (save-excursion
20507 (save-match-data
20508 (goto-char (point-at-bol))
20509 (looking-at "[ \t]*#"))))
20511 (defun org-in-verbatim-emphasis ()
20512 (save-match-data
20513 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20515 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20516 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20517 (if (and marker (marker-buffer marker)
20518 (buffer-live-p (marker-buffer marker)))
20519 (progn
20520 (org-pop-to-buffer-same-window (marker-buffer marker))
20521 (if (or (> marker (point-max)) (< marker (point-min)))
20522 (widen))
20523 (goto-char marker)
20524 (org-show-context 'org-goto))
20525 (if bookmark
20526 (bookmark-jump bookmark)
20527 (error "Cannot find location"))))
20529 (defun org-quote-csv-field (s)
20530 "Quote field for inclusion in CSV material."
20531 (if (string-match "[\",]" s)
20532 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20535 (defun org-force-self-insert (N)
20536 "Needed to enforce self-insert under remapping."
20537 (interactive "p")
20538 (self-insert-command N))
20540 (defun org-string-width (s)
20541 "Compute width of string, ignoring invisible characters.
20542 This ignores character with invisibility property `org-link', and also
20543 characters with property `org-cwidth', because these will become invisible
20544 upon the next fontification round."
20545 (let (b l)
20546 (when (or (eq t buffer-invisibility-spec)
20547 (assq 'org-link buffer-invisibility-spec))
20548 (while (setq b (text-property-any 0 (length s)
20549 'invisible 'org-link s))
20550 (setq s (concat (substring s 0 b)
20551 (substring s (or (next-single-property-change
20552 b 'invisible s) (length s)))))))
20553 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20554 (setq s (concat (substring s 0 b)
20555 (substring s (or (next-single-property-change
20556 b 'org-cwidth s) (length s))))))
20557 (setq l (string-width s) b -1)
20558 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20559 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20562 (defun org-shorten-string (s maxlength)
20563 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20564 If the string is shorter or has length MAXLENGTH, just return the
20565 original string. If it is longer, the functions finds a space in the
20566 string, breaks this string off at that locations and adds three dots
20567 as ellipsis. Including the ellipsis, the string will not be longer
20568 than MAXLENGTH. If finding a good breaking point in the string does
20569 not work, the string is just chopped off in the middle of a word
20570 if necessary."
20571 (if (<= (length s) maxlength)
20573 (let* ((n (max (- maxlength 4) 1))
20574 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20575 (if (string-match re s)
20576 (concat (match-string 1 s) "...")
20577 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20579 (defun org-get-indentation (&optional line)
20580 "Get the indentation of the current line, interpreting tabs.
20581 When LINE is given, assume it represents a line and compute its indentation."
20582 (if line
20583 (if (string-match "^ *" (org-remove-tabs line))
20584 (match-end 0))
20585 (save-excursion
20586 (beginning-of-line 1)
20587 (skip-chars-forward " \t")
20588 (current-column))))
20590 (defun org-get-string-indentation (s)
20591 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20592 (let ((n -1) (i 0) (w tab-width) c)
20593 (catch 'exit
20594 (while (< (setq n (1+ n)) (length s))
20595 (setq c (aref s n))
20596 (cond ((= c ?\ ) (setq i (1+ i)))
20597 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20598 (t (throw 'exit t)))))
20601 (defun org-remove-tabs (s &optional width)
20602 "Replace tabulators in S with spaces.
20603 Assumes that s is a single line, starting in column 0."
20604 (setq width (or width tab-width))
20605 (while (string-match "\t" s)
20606 (setq s (replace-match
20607 (make-string
20608 (- (* width (/ (+ (match-beginning 0) width) width))
20609 (match-beginning 0)) ?\ )
20610 t t s)))
20613 (defun org-fix-indentation (line ind)
20614 "Fix indentation in LINE.
20615 IND is a cons cell with target and minimum indentation.
20616 If the current indentation in LINE is smaller than the minimum,
20617 leave it alone. If it is larger than ind, set it to the target."
20618 (let* ((l (org-remove-tabs line))
20619 (i (org-get-indentation l))
20620 (i1 (car ind)) (i2 (cdr ind)))
20621 (if (>= i i2) (setq l (substring line i2)))
20622 (if (> i1 0)
20623 (concat (make-string i1 ?\ ) l)
20624 l)))
20626 (defun org-remove-indentation (code &optional n)
20627 "Remove the maximum common indentation from the lines in CODE.
20628 N may optionally be the number of spaces to remove."
20629 (with-temp-buffer
20630 (insert code)
20631 (org-do-remove-indentation n)
20632 (buffer-string)))
20634 (defun org-do-remove-indentation (&optional n)
20635 "Remove the maximum common indentation from the buffer."
20636 (untabify (point-min) (point-max))
20637 (let ((min 10000) re)
20638 (if n
20639 (setq min n)
20640 (goto-char (point-min))
20641 (while (re-search-forward "^ *[^ \n]" nil t)
20642 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20643 (unless (or (= min 0) (= min 10000))
20644 (setq re (format "^ \\{%d\\}" min))
20645 (goto-char (point-min))
20646 (while (re-search-forward re nil t)
20647 (replace-match "")
20648 (end-of-line 1))
20649 min)))
20651 (defun org-fill-template (template alist)
20652 "Find each %key of ALIST in TEMPLATE and replace it."
20653 (let ((case-fold-search nil)
20654 entry key value)
20655 (setq alist (sort (copy-sequence alist)
20656 (lambda (a b) (< (length (car a)) (length (car b))))))
20657 (while (setq entry (pop alist))
20658 (setq template
20659 (replace-regexp-in-string
20660 (concat "%" (regexp-quote (car entry)))
20661 (or (cdr entry) "") template t t)))
20662 template))
20664 (defun org-base-buffer (buffer)
20665 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20666 (if (not buffer)
20667 buffer
20668 (or (buffer-base-buffer buffer)
20669 buffer)))
20671 (defun org-trim (s)
20672 "Remove whitespace at beginning and end of string."
20673 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20674 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20677 (defun org-wrap (string &optional width lines)
20678 "Wrap string to either a number of lines, or a width in characters.
20679 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20680 that costs. If there is a word longer than WIDTH, the text is actually
20681 wrapped to the length of that word.
20682 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20683 many lines, whatever width that takes.
20684 The return value is a list of lines, without newlines at the end."
20685 (let* ((words (org-split-string string "[ \t\n]+"))
20686 (maxword (apply 'max (mapcar 'org-string-width words)))
20687 w ll)
20688 (cond (width
20689 (org-do-wrap words (max maxword width)))
20690 (lines
20691 (setq w maxword)
20692 (setq ll (org-do-wrap words maxword))
20693 (if (<= (length ll) lines)
20695 (setq ll words)
20696 (while (> (length ll) lines)
20697 (setq w (1+ w))
20698 (setq ll (org-do-wrap words w)))
20699 ll))
20700 (t (error "Cannot wrap this")))))
20702 (defun org-do-wrap (words width)
20703 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20704 (let (lines line)
20705 (while words
20706 (setq line (pop words))
20707 (while (and words (< (+ (length line) (length (car words))) width))
20708 (setq line (concat line " " (pop words))))
20709 (setq lines (push line lines)))
20710 (nreverse lines)))
20712 (defun org-split-string (string &optional separators)
20713 "Splits STRING into substrings at SEPARATORS.
20714 No empty strings are returned if there are matches at the beginning
20715 and end of string."
20716 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20717 (start 0)
20718 notfirst
20719 (list nil))
20720 (while (and (string-match rexp string
20721 (if (and notfirst
20722 (= start (match-beginning 0))
20723 (< start (length string)))
20724 (1+ start) start))
20725 (< (match-beginning 0) (length string)))
20726 (setq notfirst t)
20727 (or (eq (match-beginning 0) 0)
20728 (and (eq (match-beginning 0) (match-end 0))
20729 (eq (match-beginning 0) start))
20730 (setq list
20731 (cons (substring string start (match-beginning 0))
20732 list)))
20733 (setq start (match-end 0)))
20734 (or (eq start (length string))
20735 (setq list
20736 (cons (substring string start)
20737 list)))
20738 (nreverse list)))
20740 (defun org-quote-vert (s)
20741 "Replace \"|\" with \"\\vert\"."
20742 (while (string-match "|" s)
20743 (setq s (replace-match "\\vert" t t s)))
20746 (defun org-uuidgen-p (s)
20747 "Is S an ID created by UUIDGEN?"
20748 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20750 (defun org-in-src-block-p (&optional inside)
20751 "Whether point is in a code source block.
20752 When INSIDE is non-nil, don't consider we are within a src block
20753 when point is at #+BEGIN_SRC or #+END_SRC."
20754 (let ((case-fold-search t) ov)
20755 (or (and (setq ov (overlays-at (point)))
20756 (memq 'org-block-background
20757 (overlay-properties (car ov))))
20758 (and (not inside)
20759 (save-match-data
20760 (save-excursion
20761 (beginning-of-line)
20762 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20764 (defun org-context ()
20765 "Return a list of contexts of the current cursor position.
20766 If several contexts apply, all are returned.
20767 Each context entry is a list with a symbol naming the context, and
20768 two positions indicating start and end of the context. Possible
20769 contexts are:
20771 :headline anywhere in a headline
20772 :headline-stars on the leading stars in a headline
20773 :todo-keyword on a TODO keyword (including DONE) in a headline
20774 :tags on the TAGS in a headline
20775 :priority on the priority cookie in a headline
20776 :item on the first line of a plain list item
20777 :item-bullet on the bullet/number of a plain list item
20778 :checkbox on the checkbox in a plain list item
20779 :table in an org-mode table
20780 :table-special on a special filed in a table
20781 :table-table in a table.el table
20782 :clocktable in a clocktable
20783 :src-block in a source block
20784 :link on a hyperlink
20785 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20786 :target on a <<target>>
20787 :radio-target on a <<<radio-target>>>
20788 :latex-fragment on a LaTeX fragment
20789 :latex-preview on a LaTeX fragment with overlaid preview image
20791 This function expects the position to be visible because it uses font-lock
20792 faces as a help to recognize the following contexts: :table-special, :link,
20793 and :keyword."
20794 (let* ((f (get-text-property (point) 'face))
20795 (faces (if (listp f) f (list f)))
20796 (case-fold-search t)
20797 (p (point)) clist o)
20798 ;; First the large context
20799 (cond
20800 ((org-at-heading-p t)
20801 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20802 (when (progn
20803 (beginning-of-line 1)
20804 (looking-at org-todo-line-tags-regexp))
20805 (push (org-point-in-group p 1 :headline-stars) clist)
20806 (push (org-point-in-group p 2 :todo-keyword) clist)
20807 (push (org-point-in-group p 4 :tags) clist))
20808 (goto-char p)
20809 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20810 (if (looking-at "\\[#[A-Z0-9]\\]")
20811 (push (org-point-in-group p 0 :priority) clist)))
20813 ((org-at-item-p)
20814 (push (org-point-in-group p 2 :item-bullet) clist)
20815 (push (list :item (point-at-bol)
20816 (save-excursion (org-end-of-item) (point)))
20817 clist)
20818 (and (org-at-item-checkbox-p)
20819 (push (org-point-in-group p 0 :checkbox) clist)))
20821 ((org-at-table-p)
20822 (push (list :table (org-table-begin) (org-table-end)) clist)
20823 (if (memq 'org-formula faces)
20824 (push (list :table-special
20825 (previous-single-property-change p 'face)
20826 (next-single-property-change p 'face)) clist)))
20827 ((org-at-table-p 'any)
20828 (push (list :table-table) clist)))
20829 (goto-char p)
20831 (let ((case-fold-search t))
20832 ;; New the "medium" contexts: clocktables, source blocks
20833 (cond ((org-in-clocktable-p)
20834 (push (list :clocktable
20835 (and (or (looking-at "#\\+BEGIN: clocktable")
20836 (search-backward "#+BEGIN: clocktable" nil t))
20837 (match-beginning 0))
20838 (and (re-search-forward "#\\+END:?" nil t)
20839 (match-end 0))) clist))
20840 ((org-in-src-block-p)
20841 (push (list :src-block
20842 (and (or (looking-at "#\\+BEGIN_SRC")
20843 (search-backward "#+BEGIN_SRC" nil t))
20844 (match-beginning 0))
20845 (and (search-forward "#+END_SRC" nil t)
20846 (match-beginning 0))) clist))))
20847 (goto-char p)
20849 ;; Now the small context
20850 (cond
20851 ((org-at-timestamp-p)
20852 (push (org-point-in-group p 0 :timestamp) clist))
20853 ((memq 'org-link faces)
20854 (push (list :link
20855 (previous-single-property-change p 'face)
20856 (next-single-property-change p 'face)) clist))
20857 ((memq 'org-special-keyword faces)
20858 (push (list :keyword
20859 (previous-single-property-change p 'face)
20860 (next-single-property-change p 'face)) clist))
20861 ((org-at-target-p)
20862 (push (org-point-in-group p 0 :target) clist)
20863 (goto-char (1- (match-beginning 0)))
20864 (if (looking-at org-radio-target-regexp)
20865 (push (org-point-in-group p 0 :radio-target) clist))
20866 (goto-char p))
20867 ((setq o (car (delq nil
20868 (mapcar
20869 (lambda (x)
20870 (if (memq x org-latex-fragment-image-overlays) x))
20871 (overlays-at (point))))))
20872 (push (list :latex-fragment
20873 (overlay-start o) (overlay-end o)) clist)
20874 (push (list :latex-preview
20875 (overlay-start o) (overlay-end o)) clist))
20876 ((org-inside-LaTeX-fragment-p)
20877 ;; FIXME: positions wrong.
20878 (push (list :latex-fragment (point) (point)) clist)))
20880 (setq clist (nreverse (delq nil clist)))
20881 clist))
20883 ;; FIXME: Compare with at-regexp-p Do we need both?
20884 (defun org-in-regexp (re &optional nlines visually)
20885 "Check if point is inside a match of regexp.
20886 Normally only the current line is checked, but you can include NLINES extra
20887 lines both before and after point into the search.
20888 If VISUALLY is set, require that the cursor is not after the match but
20889 really on, so that the block visually is on the match."
20890 (catch 'exit
20891 (let ((pos (point))
20892 (eol (point-at-eol (+ 1 (or nlines 0))))
20893 (inc (if visually 1 0)))
20894 (save-excursion
20895 (beginning-of-line (- 1 (or nlines 0)))
20896 (while (re-search-forward re eol t)
20897 (if (and (<= (match-beginning 0) pos)
20898 (>= (+ inc (match-end 0)) pos))
20899 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20901 (defun org-at-regexp-p (regexp)
20902 "Is point inside a match of REGEXP in the current line?"
20903 (catch 'exit
20904 (save-excursion
20905 (let ((pos (point)) (end (point-at-eol)))
20906 (beginning-of-line 1)
20907 (while (re-search-forward regexp end t)
20908 (if (and (<= (match-beginning 0) pos)
20909 (>= (match-end 0) pos))
20910 (throw 'exit t)))
20911 nil))))
20913 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20914 "Non-nil when point is between matches of START-RE and END-RE.
20916 Also return a non-nil value when point is on one of the matches.
20918 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20919 buffer positions. Default values are the positions of headlines
20920 surrounding the point.
20922 The functions returns a cons cell whose car (resp. cdr) is the
20923 position before START-RE (resp. after END-RE)."
20924 (save-match-data
20925 (let ((pos (point))
20926 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20927 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20928 beg end)
20929 (save-excursion
20930 ;; Point is on a block when on START-RE or if START-RE can be
20931 ;; found before it...
20932 (and (or (org-at-regexp-p start-re)
20933 (re-search-backward start-re limit-up t))
20934 (setq beg (match-beginning 0))
20935 ;; ... and END-RE after it...
20936 (goto-char (match-end 0))
20937 (re-search-forward end-re limit-down t)
20938 (> (setq end (match-end 0)) pos)
20939 ;; ... without another START-RE in-between.
20940 (goto-char (match-beginning 0))
20941 (not (re-search-backward start-re (1+ beg) t))
20942 ;; Return value.
20943 (cons beg end))))))
20945 (defun org-in-block-p (names)
20946 "Non-nil when point belongs to a block whose name belongs to NAMES.
20948 NAMES is a list of strings containing names of blocks.
20950 Return first block name matched, or nil. Beware that in case of
20951 nested blocks, the returned name may not belong to the closest
20952 block from point."
20953 (save-match-data
20954 (catch 'exit
20955 (let ((case-fold-search t)
20956 (lim-up (save-excursion (outline-previous-heading)))
20957 (lim-down (save-excursion (outline-next-heading))))
20958 (mapc (lambda (name)
20959 (let ((n (regexp-quote name)))
20960 (when (org-between-regexps-p
20961 (concat "^[ \t]*#\\+begin_" n)
20962 (concat "^[ \t]*#\\+end_" n)
20963 lim-up lim-down)
20964 (throw 'exit n))))
20965 names))
20966 nil)))
20968 (defun org-occur-in-agenda-files (regexp &optional nlines)
20969 "Call `multi-occur' with buffers for all agenda files."
20970 (interactive "sOrg-files matching: \np")
20971 (let* ((files (org-agenda-files))
20972 (tnames (mapcar 'file-truename files))
20973 (extra org-agenda-text-search-extra-files)
20975 (when (eq (car extra) 'agenda-archives)
20976 (setq extra (cdr extra))
20977 (setq files (org-add-archive-files files)))
20978 (while (setq f (pop extra))
20979 (unless (member (file-truename f) tnames)
20980 (add-to-list 'files f 'append)
20981 (add-to-list 'tnames (file-truename f) 'append)))
20982 (multi-occur
20983 (mapcar (lambda (x)
20984 (with-current-buffer
20985 (or (get-file-buffer x) (find-file-noselect x))
20986 (widen)
20987 (current-buffer)))
20988 files)
20989 regexp)))
20991 (if (boundp 'occur-mode-find-occurrence-hook)
20992 ;; Emacs 23
20993 (add-hook 'occur-mode-find-occurrence-hook
20994 (lambda ()
20995 (when (derived-mode-p 'org-mode)
20996 (org-reveal))))
20997 ;; Emacs 22
20998 (defadvice occur-mode-goto-occurrence
20999 (after org-occur-reveal activate)
21000 (and (derived-mode-p 'org-mode) (org-reveal)))
21001 (defadvice occur-mode-goto-occurrence-other-window
21002 (after org-occur-reveal activate)
21003 (and (derived-mode-p 'org-mode) (org-reveal)))
21004 (defadvice occur-mode-display-occurrence
21005 (after org-occur-reveal activate)
21006 (when (derived-mode-p 'org-mode)
21007 (let ((pos (occur-mode-find-occurrence)))
21008 (with-current-buffer (marker-buffer pos)
21009 (save-excursion
21010 (goto-char pos)
21011 (org-reveal)))))))
21013 (defun org-occur-link-in-agenda-files ()
21014 "Create a link and search for it in the agendas.
21015 The link is not stored in `org-stored-links', it is just created
21016 for the search purpose."
21017 (interactive)
21018 (let ((link (condition-case nil
21019 (org-store-link nil)
21020 (error "Unable to create a link to here"))))
21021 (org-occur-in-agenda-files (regexp-quote link))))
21023 (defun org-uniquify (list)
21024 "Remove duplicate elements from LIST."
21025 (let (res)
21026 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21027 res))
21029 (defun org-delete-all (elts list)
21030 "Remove all elements in ELTS from LIST."
21031 (while elts
21032 (setq list (delete (pop elts) list)))
21033 list)
21035 (defun org-count (cl-item cl-seq)
21036 "Count the number of occurrences of ITEM in SEQ.
21037 Taken from `count' in cl-seq.el with all keyword arguments removed."
21038 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21039 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21040 (while (< cl-start cl-end)
21041 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21042 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21043 (setq cl-start (1+ cl-start)))
21044 cl-count))
21046 (defun org-remove-if (predicate seq)
21047 "Remove everything from SEQ that fulfills PREDICATE."
21048 (let (res e)
21049 (while seq
21050 (setq e (pop seq))
21051 (if (not (funcall predicate e)) (push e res)))
21052 (nreverse res)))
21054 (defun org-remove-if-not (predicate seq)
21055 "Remove everything from SEQ that does not fulfill PREDICATE."
21056 (let (res e)
21057 (while seq
21058 (setq e (pop seq))
21059 (if (funcall predicate e) (push e res)))
21060 (nreverse res)))
21062 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21063 "Reduce two-argument FUNCTION across SEQ.
21064 Taken from `reduce' in cl-seq.el with all keyword arguments but
21065 \":initial-value\" removed."
21066 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21067 (cadr (memq :initial-value cl-keys)))
21068 (cl-seq (pop cl-seq))
21069 (t (funcall cl-func)))))
21070 (while cl-seq
21071 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21072 cl-accum))
21074 (defun org-back-over-empty-lines ()
21075 "Move backwards over whitespace, to the beginning of the first empty line.
21076 Returns the number of empty lines passed."
21077 (let ((pos (point)))
21078 (if (cdr (assoc 'heading org-blank-before-new-entry))
21079 (skip-chars-backward " \t\n\r")
21080 (unless (eobp)
21081 (forward-line -1)))
21082 (beginning-of-line 2)
21083 (goto-char (min (point) pos))
21084 (count-lines (point) pos)))
21086 (defun org-skip-whitespace ()
21087 (skip-chars-forward " \t\n\r"))
21089 (defun org-point-in-group (point group &optional context)
21090 "Check if POINT is in match-group GROUP.
21091 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21092 match. If the match group does not exist or point is not inside it,
21093 return nil."
21094 (and (match-beginning group)
21095 (>= point (match-beginning group))
21096 (<= point (match-end group))
21097 (if context
21098 (list context (match-beginning group) (match-end group))
21099 t)))
21101 (defun org-switch-to-buffer-other-window (&rest args)
21102 "Switch to buffer in a second window on the current frame.
21103 In particular, do not allow pop-up frames.
21104 Returns the newly created buffer."
21105 (org-no-popups
21106 (apply 'switch-to-buffer-other-window args)))
21108 (defun org-combine-plists (&rest plists)
21109 "Create a single property list from all plists in PLISTS.
21110 The process starts by copying the first list, and then setting properties
21111 from the other lists. Settings in the last list are the most significant
21112 ones and overrule settings in the other lists."
21113 (let ((rtn (copy-sequence (pop plists)))
21114 p v ls)
21115 (while plists
21116 (setq ls (pop plists))
21117 (while ls
21118 (setq p (pop ls) v (pop ls))
21119 (setq rtn (plist-put rtn p v))))
21120 rtn))
21122 (defun org-replace-escapes (string table)
21123 "Replace %-escapes in STRING with values in TABLE.
21124 TABLE is an association list with keys like \"%a\" and string values.
21125 The sequences in STRING may contain normal field width and padding information,
21126 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21127 so values can contain further %-escapes if they are define later in TABLE."
21128 (let ((tbl (copy-alist table))
21129 (case-fold-search nil)
21130 (pchg 0)
21131 e re rpl)
21132 (while (setq e (pop tbl))
21133 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21134 (when (and (cdr e) (string-match re (cdr e)))
21135 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21136 (safe "SREF"))
21137 (add-text-properties 0 3 (list 'sref sref) safe)
21138 (setcdr e (replace-match safe t t (cdr e)))))
21139 (while (string-match re string)
21140 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21141 (cdr e)))
21142 (setq string (replace-match rpl t t string))))
21143 (while (setq pchg (next-property-change pchg string))
21144 (let ((sref (get-text-property pchg 'sref string)))
21145 (when (and sref (string-match "SREF" string pchg))
21146 (setq string (replace-match sref t t string)))))
21147 string))
21149 (defun org-sublist (list start end)
21150 "Return a section of LIST, from START to END.
21151 Counting starts at 1."
21152 (let (rtn (c start))
21153 (setq list (nthcdr (1- start) list))
21154 (while (and list (<= c end))
21155 (push (pop list) rtn)
21156 (setq c (1+ c)))
21157 (nreverse rtn)))
21159 (defun org-find-base-buffer-visiting (file)
21160 "Like `find-buffer-visiting' but always return the base buffer and
21161 not an indirect buffer."
21162 (let ((buf (or (get-file-buffer file)
21163 (find-buffer-visiting file))))
21164 (if buf
21165 (or (buffer-base-buffer buf) buf)
21166 nil)))
21168 (defun org-image-file-name-regexp (&optional extensions)
21169 "Return regexp matching the file names of images.
21170 If EXTENSIONS is given, only match these."
21171 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21172 (image-file-name-regexp)
21173 (let ((image-file-name-extensions
21174 (or extensions
21175 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21176 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21177 (concat "\\."
21178 (regexp-opt (nconc (mapcar 'upcase
21179 image-file-name-extensions)
21180 image-file-name-extensions)
21182 "\\'"))))
21184 (defun org-file-image-p (file &optional extensions)
21185 "Return non-nil if FILE is an image."
21186 (save-match-data
21187 (string-match (org-image-file-name-regexp extensions) file)))
21189 (defun org-get-cursor-date (&optional with-time)
21190 "Return the date at cursor in as a time.
21191 This works in the calendar and in the agenda, anywhere else it just
21192 returns the current time.
21193 If WITH-TIME is non-nil, returns the time of the event at point (in
21194 the agenda) or the current time of the day."
21195 (let (date day defd tp tm hod mod)
21196 (when with-time
21197 (setq tp (get-text-property (point) 'time))
21198 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21199 (setq hod (string-to-number (match-string 1 tp))
21200 mod (string-to-number (match-string 2 tp))))
21201 (or tp (setq hod (nth 2 (decode-time (current-time)))
21202 mod (nth 1 (decode-time (current-time))))))
21203 (cond
21204 ((eq major-mode 'calendar-mode)
21205 (setq date (calendar-cursor-to-date)
21206 defd (encode-time 0 (or mod 0) (or hod 0)
21207 (nth 1 date) (nth 0 date) (nth 2 date))))
21208 ((eq major-mode 'org-agenda-mode)
21209 (setq day (get-text-property (point) 'day))
21210 (if day
21211 (setq date (calendar-gregorian-from-absolute day)
21212 defd (encode-time 0 (or mod 0) (or hod 0)
21213 (nth 1 date) (nth 0 date) (nth 2 date))))))
21214 (or defd (current-time))))
21216 (defun org-mark-subtree (&optional up)
21217 "Mark the current subtree.
21218 This puts point at the start of the current subtree, and mark at
21219 the end. If a numeric prefix UP is given, move up into the
21220 hierarchy of headlines by UP levels before marking the subtree."
21221 (interactive "P")
21222 (org-with-limited-levels
21223 (cond ((org-at-heading-p) (beginning-of-line))
21224 ((org-before-first-heading-p) (error "Not in a subtree"))
21225 (t (outline-previous-visible-heading 1))))
21226 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21227 (if (org-called-interactively-p 'any)
21228 (call-interactively 'org-mark-element)
21229 (org-mark-element)))
21232 ;;; Macros
21234 ;; Macros are expanded with `org-macro-replace-all', which relies
21235 ;; internally on `org-macro-expand'.
21237 ;; Default templates for expansion are stored in the buffer-local
21238 ;; variable `org-macro-templates'. This variable is updated by
21239 ;; `org-macro-initialize-templates'.
21241 ;; Along with macros defined through #+MACRO: keyword, default
21242 ;; templates include the following hard-coded macros:
21243 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21244 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21246 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21247 ;; {{{title}}} will also be provided.
21250 (defvar org-macro-templates nil
21251 "Alist containing all macro templates in current buffer.
21252 Associations are in the shape of (NAME . TEMPLATE) where NAME
21253 stands for macro's name and template for its replacement value,
21254 both as strings. This is an internal variable. Do not set it
21255 directly, use instead:
21257 #+MACRO: name template")
21258 (make-variable-buffer-local 'org-macro-templates)
21260 (defun org-macro-expand (macro templates)
21261 "Return expanded MACRO, as a string.
21262 MACRO is an object, obtained, for example, with
21263 `org-element-context'. TEMPLATES is an alist of templates used
21264 for expansion. See `org-macro-templates' for a buffer-local
21265 default value. Return nil if no template was found."
21266 (let ((template
21267 ;; Macro names are case-insensitive.
21268 (cdr (assoc-string (org-element-property :key macro) templates t))))
21269 (when template
21270 (let ((value (replace-regexp-in-string
21271 "\\$[0-9]+"
21272 (lambda (arg)
21273 (or (nth (1- (string-to-number (substring arg 1)))
21274 (org-element-property :args macro))
21275 ;; No argument provided: remove
21276 ;; place-holder.
21277 ""))
21278 template)))
21279 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21280 (when (string-match "\\`(eval\\>" value)
21281 (setq value (eval (read value))))
21282 ;; Return string.
21283 (format "%s" (or value ""))))))
21285 (defun org-macro-replace-all (templates)
21286 "Replace all macros in current buffer by their expansion.
21287 TEMPLATES is an alist of templates used for expansion. See
21288 `org-macro-templates' for a buffer-local default value."
21289 (save-excursion
21290 (goto-char (point-min))
21291 (let (record)
21292 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21293 (let ((object (org-element-context)))
21294 (when (eq (org-element-type object) 'macro)
21295 (let* ((value (org-macro-expand object templates))
21296 (begin (org-element-property :begin object))
21297 (signature (list begin
21298 object
21299 (org-element-property :args object))))
21300 ;; Avoid circular dependencies by checking if the same
21301 ;; macro with the same arguments is expanded at the same
21302 ;; position twice.
21303 (if (member signature record)
21304 (error "Circular macro expansion: %s"
21305 (org-element-property :key object))
21306 (when value
21307 (push signature record)
21308 (delete-region
21309 begin
21310 ;; Preserve white spaces after the macro.
21311 (progn (goto-char (org-element-property :end object))
21312 (skip-chars-backward " \t")
21313 (point)))
21314 ;; Leave point before replacement in case of recursive
21315 ;; expansions.
21316 (save-excursion (insert value)))))))))))
21318 (defun org-macro-initialize-templates ()
21319 "Collect macro templates defined in current buffer.
21320 Templates are stored in buffer-local variable
21321 `org-macro-templates'. In addition to buffer-defined macros, the
21322 function installs the following ones: \"property\",
21323 \"time\". and, if the buffer is associated to a file,
21324 \"input-file\" and \"modification-time\"."
21325 (let ((case-fold-search t)
21326 (set-template
21327 (lambda (cell)
21328 ;; Add CELL to `org-macro-templates' if there's no
21329 ;; association matching its name already. Otherwise,
21330 ;; replace old association with the new one in that
21331 ;; variable.
21332 (let ((old-template (assoc (car cell) org-macro-templates)))
21333 (if old-template (setcdr old-template (cdr cell))
21334 (push cell org-macro-templates))))))
21335 ;; Install buffer-local macros.
21336 (org-with-wide-buffer
21337 (goto-char (point-min))
21338 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21339 (let ((element (org-element-at-point)))
21340 (when (eq (org-element-type element) 'keyword)
21341 (let ((value (org-element-property :value element)))
21342 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21343 (funcall set-template
21344 (cons (match-string 1 value)
21345 (or (match-string 2 value) "")))))))))
21346 ;; Install hard-coded macros.
21347 (mapc (lambda (cell) (funcall set-template cell))
21348 (list
21349 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21350 (cons "time" "(eval (format-time-string \"$1\"))")))
21351 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21352 (when (and visited-file (file-exists-p visited-file))
21353 (mapc (lambda (cell) (funcall set-template cell))
21354 (list
21355 (cons "input-file" (file-name-nondirectory visited-file))
21356 (cons "modification-time"
21357 (format "(eval (format-time-string \"$1\" '%s))"
21358 (prin1-to-string
21359 (nth 5 (file-attributes visited-file)))))))))))
21362 ;;; Indentation
21364 (defun org-indent-line ()
21365 "Indent line depending on context."
21366 (interactive)
21367 (let* ((pos (point))
21368 (itemp (org-at-item-p))
21369 (case-fold-search t)
21370 (org-drawer-regexp (or org-drawer-regexp "\000"))
21371 (inline-task-p (and (featurep 'org-inlinetask)
21372 (org-inlinetask-in-task-p)))
21373 (inline-re (and inline-task-p
21374 (org-inlinetask-outline-regexp)))
21375 column)
21376 (if (and orgstruct-is-++ (eq pos (point)))
21377 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21378 (indent-according-to-mode))
21379 (beginning-of-line 1)
21380 (cond
21381 ;; Headings
21382 ((looking-at org-outline-regexp) (setq column 0))
21383 ;; Included files
21384 ((looking-at "#\\+include:") (setq column 0))
21385 ;; Footnote definition
21386 ((looking-at org-footnote-definition-re) (setq column 0))
21387 ;; Literal examples
21388 ((looking-at "[ \t]*:\\( \\|$\\)")
21389 (setq column (org-get-indentation))) ; do nothing
21390 ;; Lists
21391 ((ignore-errors (goto-char (org-in-item-p)))
21392 (setq column (if itemp
21393 (org-get-indentation)
21394 (org-list-item-body-column (point))))
21395 (goto-char pos))
21396 ;; Drawers
21397 ((and (looking-at "[ \t]*:END:")
21398 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21399 (save-excursion
21400 (goto-char (1- (match-beginning 1)))
21401 (setq column (current-column))))
21402 ;; Special blocks
21403 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21404 (save-excursion
21405 (re-search-backward
21406 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21407 (setq column (org-get-indentation (match-string 0))))
21408 ((and (not (looking-at "[ \t]*#\\+begin_"))
21409 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21410 (save-excursion
21411 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21412 (setq column
21413 (cond ((equal (downcase (match-string 1)) "src")
21414 ;; src blocks: let `org-edit-src-exit' handle them
21415 (org-get-indentation))
21416 ((equal (downcase (match-string 1)) "example")
21417 (max (org-get-indentation)
21418 (org-get-indentation (match-string 0))))
21420 (org-get-indentation (match-string 0))))))
21421 ;; This line has nothing special, look at the previous relevant
21422 ;; line to compute indentation
21424 (beginning-of-line 0)
21425 (while (and (not (bobp))
21426 (not (looking-at org-table-line-regexp))
21427 (not (looking-at org-drawer-regexp))
21428 ;; When point started in an inline task, do not move
21429 ;; above task starting line.
21430 (not (and inline-task-p (looking-at inline-re)))
21431 ;; Skip drawers, blocks, empty lines, verbatim,
21432 ;; comments, tables, footnotes definitions, lists,
21433 ;; inline tasks.
21434 (or (and (looking-at "[ \t]*:END:")
21435 (re-search-backward org-drawer-regexp nil t))
21436 (and (looking-at "[ \t]*#\\+end_")
21437 (re-search-backward "[ \t]*#\\+begin_"nil t))
21438 (looking-at "[ \t]*[\n:#|]")
21439 (looking-at org-footnote-definition-re)
21440 (and (ignore-errors (goto-char (org-in-item-p)))
21441 (goto-char
21442 (org-list-get-top-point (org-list-struct))))
21443 (and (not inline-task-p)
21444 (featurep 'org-inlinetask)
21445 (org-inlinetask-in-task-p)
21446 (or (org-inlinetask-goto-beginning) t))))
21447 (beginning-of-line 0))
21448 (cond
21449 ;; There was an heading above.
21450 ((looking-at "\\*+[ \t]+")
21451 (if (not org-adapt-indentation)
21452 (setq column 0)
21453 (goto-char (match-end 0))
21454 (setq column (current-column))))
21455 ;; A drawer had started and is unfinished
21456 ((looking-at org-drawer-regexp)
21457 (goto-char (1- (match-beginning 1)))
21458 (setq column (current-column)))
21459 ;; Else, nothing noticeable found: get indentation and go on.
21460 (t (setq column (org-get-indentation))))))
21461 ;; Now apply indentation and move cursor accordingly
21462 (goto-char pos)
21463 (if (<= (current-column) (current-indentation))
21464 (org-indent-line-to column)
21465 (save-excursion (org-indent-line-to column)))
21466 ;; Special polishing for properties, see `org-property-format'
21467 (setq column (current-column))
21468 (beginning-of-line 1)
21469 (if (looking-at
21470 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21471 (replace-match (concat (match-string 1)
21472 (format org-property-format
21473 (match-string 2) (match-string 3)))
21474 t t))
21475 (org-move-to-column column))))
21477 (defun org-indent-drawer ()
21478 "Indent the drawer at point."
21479 (interactive)
21480 (let ((p (point))
21481 (e (and (save-excursion (re-search-forward ":END:" nil t))
21482 (match-end 0)))
21483 (folded
21484 (save-excursion
21485 (end-of-line)
21486 (when (overlays-at (point))
21487 (member 'invisible (overlay-properties
21488 (car (overlays-at (point)))))))))
21489 (when folded (org-cycle))
21490 (indent-for-tab-command)
21491 (while (and (move-beginning-of-line 2) (< (point) e))
21492 (indent-for-tab-command))
21493 (goto-char p)
21494 (when folded (org-cycle)))
21495 (message "Drawer at point indented"))
21497 (defun org-indent-block ()
21498 "Indent the block at point."
21499 (interactive)
21500 (let ((p (point))
21501 (case-fold-search t)
21502 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21503 (match-end 0)))
21504 (folded
21505 (save-excursion
21506 (end-of-line)
21507 (when (overlays-at (point))
21508 (member 'invisible (overlay-properties
21509 (car (overlays-at (point)))))))))
21510 (when folded (org-cycle))
21511 (indent-for-tab-command)
21512 (while (and (move-beginning-of-line 2) (< (point) e))
21513 (indent-for-tab-command))
21514 (goto-char p)
21515 (when folded (org-cycle)))
21516 (message "Block at point indented"))
21518 (defun org-indent-region (start end)
21519 "Indent region."
21520 (interactive "r")
21521 (save-excursion
21522 (let ((line-end (org-current-line end)))
21523 (goto-char start)
21524 (while (< (org-current-line) line-end)
21525 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21526 (t (call-interactively 'org-indent-line)))
21527 (move-beginning-of-line 2)))))
21530 ;;; Filling
21532 ;; We use our own fill-paragraph and auto-fill functions.
21534 ;; `org-fill-paragraph' relies on adaptive filling and context
21535 ;; checking. Appropriate `fill-prefix' is computed with
21536 ;; `org-adaptive-fill-function'.
21538 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21539 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21540 ;; `org-adaptive-fill-function' value. Internally,
21541 ;; `org-comment-line-break-function' breaks the line.
21543 ;; `org-setup-filling' installs filling and auto-filling related
21544 ;; variables during `org-mode' initialization.
21546 (defun org-setup-filling ()
21547 (interactive)
21548 ;; Prevent auto-fill from inserting unwanted new items.
21549 (when (boundp 'fill-nobreak-predicate)
21550 (org-set-local
21551 'fill-nobreak-predicate
21552 (org-uniquify
21553 (append fill-nobreak-predicate
21554 '(org-fill-paragraph-separate-nobreak-p
21555 org-fill-line-break-nobreak-p)))))
21556 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21557 (org-set-local 'auto-fill-inhibit-regexp nil)
21558 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21559 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21560 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21562 (defvar org-element-paragraph-separate) ; org-element.el
21563 (defun org-fill-paragraph-separate-nobreak-p ()
21564 "Non-nil when a line break at point would insert a new item."
21565 (looking-at (substring org-element-paragraph-separate 1)))
21567 (defun org-fill-line-break-nobreak-p ()
21568 "Non-nil when a line break at point would create an Org line break."
21569 (save-excursion
21570 (skip-chars-backward "[ \t]")
21571 (skip-chars-backward "\\\\")
21572 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21574 (declare-function message-in-body-p "message" ())
21575 (defun org-adaptive-fill-function ()
21576 "Compute a fill prefix for the current line.
21577 Return fill prefix, as a string, or nil if current line isn't
21578 meant to be filled."
21579 (let (prefix)
21580 (when (and (derived-mode-p 'message-mode) (message-in-body-p))
21581 (save-excursion
21582 (beginning-of-line)
21583 (cond ((looking-at message-cite-prefix-regexp)
21584 (setq prefix (match-string-no-properties 0)))
21585 ((looking-at org-outline-regexp)
21586 (setq prefix "")))))
21587 (or prefix
21588 (org-with-wide-buffer
21589 (let* ((p (line-beginning-position))
21590 (element (save-excursion (beginning-of-line)
21591 (org-element-at-point)))
21592 (type (org-element-type element))
21593 (post-affiliated (org-element-property :post-affiliated element)))
21594 (unless (and post-affiliated (< p post-affiliated))
21595 (case type
21596 (comment (looking-at "[ \t]*# ?") (match-string 0))
21597 (footnote-definition "")
21598 ((item plain-list)
21599 (make-string (org-list-item-body-column
21600 (or post-affiliated
21601 (org-element-property :begin element)))
21602 ? ))
21603 (paragraph
21604 ;; Fill prefix is usually the same as the current line,
21605 ;; except if the paragraph is at the beginning of an item.
21606 (let ((parent (org-element-property :parent element)))
21607 (cond ((eq (org-element-type parent) 'item)
21608 (make-string (org-list-item-body-column
21609 (org-element-property :begin parent))
21610 ? ))
21611 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21612 (match-string 0))
21613 (t ""))))
21614 (comment-block
21615 ;; Only fill contents if P is within block boundaries.
21616 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21617 (forward-line)
21618 (point)))
21619 (cend (save-excursion
21620 (goto-char (org-element-property :end element))
21621 (skip-chars-backward " \r\t\n")
21622 (line-beginning-position))))
21623 (when (and (>= p cbeg) (< p cend))
21624 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21625 (match-string 0)
21626 "")))))))))))
21628 (declare-function message-goto-body "message" ())
21629 (defvar message-cite-prefix-regexp) ; From message.el
21630 (defvar org-element-all-objects) ; From org-element.el
21631 (defun org-fill-paragraph (&optional justify)
21632 "Fill element at point, when applicable.
21634 This function only applies to comment blocks, comments, example
21635 blocks and paragraphs. Also, as a special case, re-align table
21636 when point is at one.
21638 If JUSTIFY is non-nil (interactively, with prefix argument),
21639 justify as well. If `sentence-end-double-space' is non-nil, then
21640 period followed by one space does not end a sentence, so don't
21641 break a line there. The variable `fill-column' controls the
21642 width for filling.
21644 For convenience, when point is at a plain list, an item or
21645 a footnote definition, try to fill the first paragraph within."
21646 (interactive)
21647 (if (and (derived-mode-p 'message-mode)
21648 (or (not (message-in-body-p))
21649 (save-excursion (move-beginning-of-line 1)
21650 (looking-at message-cite-prefix-regexp))))
21651 ;; First ensure filling is correct in message-mode.
21652 (let ((fill-paragraph-function
21653 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21654 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21655 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21656 (paragraph-separate
21657 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21658 (fill-paragraph nil))
21659 (save-excursion
21660 ;; Move to end of line in order to get the first paragraph
21661 ;; within a plain list or a footnote definition.
21662 (end-of-line)
21663 (let ((element (org-element-at-point)))
21664 ;; First check if point is in a blank line at the beginning of
21665 ;; the buffer. In that case, ignore filling.
21666 (if (< (point) (org-element-property :begin element)) t
21667 (case (org-element-type element)
21668 ;; Use major mode filling function is src blocks.
21669 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21670 ;; Align Org tables, leave table.el tables as-is.
21671 (table-row (org-table-align) t)
21672 (table
21673 (when (eq (org-element-property :type element) 'org)
21674 (org-table-align))
21676 (paragraph
21677 ;; Paragraphs may contain `line-break' type objects.
21678 (let ((beg (max (point-min)
21679 (org-element-property :contents-begin element)))
21680 (end (min (point-max)
21681 (org-element-property :contents-end element))))
21682 ;; Do nothing if point is at an affiliated keyword.
21683 (if (< (point) beg) t
21684 (when (derived-mode-p 'message-mode)
21685 ;; In `message-mode', do not fill following
21686 ;; citation in current paragraph nor text before
21687 ;; message body.
21688 (let ((body-start (save-excursion (message-goto-body))))
21689 (when body-start (setq beg (max body-start beg))))
21690 (when (save-excursion
21691 (re-search-forward
21692 (concat "^" message-cite-prefix-regexp) end t))
21693 (setq end (match-beginning 0))))
21694 ;; Fill paragraph, taking line breaks into
21695 ;; consideration. For that, slice the paragraph
21696 ;; using line breaks as separators, and fill the
21697 ;; parts in reverse order to avoid messing with
21698 ;; markers.
21699 (save-excursion
21700 (goto-char end)
21701 (mapc
21702 (lambda (pos)
21703 (fill-region-as-paragraph pos (point) justify)
21704 (goto-char pos))
21705 ;; Find the list of ending positions for line
21706 ;; breaks in the current paragraph. Add paragraph
21707 ;; beginning to include first slice.
21708 (nreverse
21709 (cons
21711 (org-element-map
21712 (org-element--parse-objects
21713 beg end nil org-element-all-objects)
21714 'line-break
21715 (lambda (lb) (org-element-property :end lb)))))))
21716 t)))
21717 ;; Contents of `comment-block' type elements should be
21718 ;; filled as plain text, but only if point is within block
21719 ;; markers.
21720 (comment-block
21721 (let* ((case-fold-search t)
21722 (beg (save-excursion
21723 (goto-char (org-element-property :begin element))
21724 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21725 (forward-line)
21726 (point)))
21727 (end (save-excursion
21728 (goto-char (org-element-property :end element))
21729 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21730 (line-beginning-position))))
21731 (when (and (>= (point) beg) (< (point) end))
21732 (fill-region-as-paragraph
21733 (save-excursion
21734 (end-of-line)
21735 (re-search-backward "^[ \t]*$" beg 'move)
21736 (line-beginning-position))
21737 (save-excursion
21738 (beginning-of-line)
21739 (re-search-forward "^[ \t]*$" end 'move)
21740 (line-beginning-position))
21741 justify)))
21743 ;; Fill comments.
21744 (comment (fill-comment-paragraph justify))
21745 ;; Ignore every other element.
21746 (otherwise t)))))))
21748 (defun org-auto-fill-function ()
21749 "Auto-fill function."
21750 ;; Check if auto-filling is meaningful.
21751 (let ((fc (current-fill-column)))
21752 (when (and fc (> (current-column) fc))
21753 (let* ((fill-prefix (org-adaptive-fill-function))
21754 ;; Enforce empty fill prefix, if required. Otherwise, it
21755 ;; will be computed again.
21756 (adaptive-fill-mode (not (equal fill-prefix ""))))
21757 (when fill-prefix (do-auto-fill))))))
21759 (defun org-comment-line-break-function (&optional soft)
21760 "Break line at point and indent, continuing comment if within one.
21761 The inserted newline is marked hard if variable
21762 `use-hard-newlines' is true, unless optional argument SOFT is
21763 non-nil."
21764 (if soft (insert-and-inherit ?\n) (newline 1))
21765 (save-excursion (forward-char -1) (delete-horizontal-space))
21766 (delete-horizontal-space)
21767 (indent-to-left-margin)
21768 (insert-before-markers-and-inherit fill-prefix))
21771 ;;; Comments
21773 ;; Org comments syntax is quite complex. It requires the entire line
21774 ;; to be just a comment. Also, even with the right syntax at the
21775 ;; beginning of line, some some elements (i.e. verse-block or
21776 ;; example-block) don't accept comments. Usual Emacs comment commands
21777 ;; cannot cope with those requirements. Therefore, Org replaces them.
21779 ;; Org still relies on `comment-dwim', but cannot trust
21780 ;; `comment-only-p'. So, `comment-region-function' and
21781 ;; `uncomment-region-function' both point
21782 ;; to`org-comment-or-uncomment-region'. Eventually,
21783 ;; `org-insert-comment' takes care of insertion of comments at the
21784 ;; beginning of line.
21786 ;; `org-setup-comments-handling' install comments related variables
21787 ;; during `org-mode' initialization.
21789 (defun org-setup-comments-handling ()
21790 (interactive)
21791 (org-set-local 'comment-use-syntax nil)
21792 (org-set-local 'comment-start "# ")
21793 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21794 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21795 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21796 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21798 (defun org-insert-comment ()
21799 "Insert an empty comment above current line.
21800 If the line is empty, insert comment at its beginning."
21801 (beginning-of-line)
21802 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21803 (org-indent-line)
21804 (insert "# "))
21806 (defvar comment-empty-lines) ; From newcomment.el.
21807 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21808 "Comment or uncomment each non-blank line in the region.
21809 Uncomment each non-blank line between BEG and END if it only
21810 contains commented lines. Otherwise, comment them."
21811 (save-restriction
21812 ;; Restrict region
21813 (narrow-to-region (save-excursion (goto-char beg)
21814 (skip-chars-forward " \r\t\n" end)
21815 (line-beginning-position))
21816 (save-excursion (goto-char end)
21817 (skip-chars-backward " \r\t\n" beg)
21818 (line-end-position)))
21819 (let ((uncommentp
21820 ;; UNCOMMENTP is non-nil when every non blank line between
21821 ;; BEG and END is a comment.
21822 (save-excursion
21823 (goto-char (point-min))
21824 (while (and (not (eobp))
21825 (let ((element (org-element-at-point)))
21826 (and (eq (org-element-type element) 'comment)
21827 (goto-char (min (point-max)
21828 (org-element-property
21829 :end element)))))))
21830 (eobp))))
21831 (if uncommentp
21832 ;; Only blank lines and comments in region: uncomment it.
21833 (save-excursion
21834 (goto-char (point-min))
21835 (while (not (eobp))
21836 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21837 (replace-match "" nil nil nil 1))
21838 (forward-line)))
21839 ;; Comment each line in region.
21840 (let ((min-indent (point-max)))
21841 ;; First find the minimum indentation across all lines.
21842 (save-excursion
21843 (goto-char (point-min))
21844 (while (and (not (eobp)) (not (zerop min-indent)))
21845 (unless (looking-at "[ \t]*$")
21846 (setq min-indent (min min-indent (current-indentation))))
21847 (forward-line)))
21848 ;; Then loop over all lines.
21849 (save-excursion
21850 (goto-char (point-min))
21851 (while (not (eobp))
21852 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21853 (org-move-to-column min-indent t)
21854 (insert comment-start))
21855 (forward-line))))))))
21858 ;;; Other stuff.
21860 (defun org-toggle-fixed-width-section (arg)
21861 "Toggle the fixed-width export.
21862 If there is no active region, the QUOTE keyword at the current headline is
21863 inserted or removed. When present, it causes the text between this headline
21864 and the next to be exported as fixed-width text, and unmodified.
21865 If there is an active region, this command adds or removes a colon as the
21866 first character of this line. If the first character of a line is a colon,
21867 this line is also exported in fixed-width font."
21868 (interactive "P")
21869 (let* ((cc 0)
21870 (regionp (org-region-active-p))
21871 (beg (if regionp (region-beginning) (point)))
21872 (end (if regionp (region-end)))
21873 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21874 (case-fold-search nil)
21875 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21876 off)
21877 (if regionp
21878 (save-excursion
21879 (goto-char beg)
21880 (setq cc (current-column))
21881 (beginning-of-line 1)
21882 (setq off (looking-at re))
21883 (while (> nlines 0)
21884 (setq nlines (1- nlines))
21885 (beginning-of-line 1)
21886 (cond
21887 (arg
21888 (org-move-to-column cc t)
21889 (insert ": \n")
21890 (forward-line -1))
21891 ((and off (looking-at re))
21892 (replace-match "" t t nil 1))
21893 ((not off) (org-move-to-column cc t) (insert ": ")))
21894 (forward-line 1)))
21895 (save-excursion
21896 (org-back-to-heading)
21897 (cond
21898 ((looking-at (format org-heading-keyword-regexp-format
21899 org-quote-string))
21900 (goto-char (match-end 1))
21901 (looking-at (concat " +" org-quote-string))
21902 (replace-match "" t t)
21903 (when (eolp) (insert " ")))
21904 ((looking-at org-outline-regexp)
21905 (goto-char (match-end 0))
21906 (insert org-quote-string " ")))))))
21908 (defun org-reftex-citation ()
21909 "Use reftex-citation to insert a citation into the buffer.
21910 This looks for a line like
21912 #+BIBLIOGRAPHY: foo plain option:-d
21914 and derives from it that foo.bib is the bibliography file relevant
21915 for this document. It then installs the necessary environment for RefTeX
21916 to work in this buffer and calls `reftex-citation' to insert a citation
21917 into the buffer.
21919 Export of such citations to both LaTeX and HTML is handled by the contributed
21920 package org-exp-bibtex by Taru Karttunen."
21921 (interactive)
21922 (let ((reftex-docstruct-symbol 'rds)
21923 (reftex-cite-format "\\cite{%l}")
21924 rds bib)
21925 (save-excursion
21926 (save-restriction
21927 (widen)
21928 (let ((case-fold-search t)
21929 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21930 (if (not (save-excursion
21931 (or (re-search-forward re nil t)
21932 (re-search-backward re nil t))))
21933 (error "No bibliography defined in file")
21934 (setq bib (concat (match-string 1) ".bib")
21935 rds (list (list 'bib bib)))))))
21936 (call-interactively 'reftex-citation)))
21938 ;;;; Functions extending outline functionality
21940 (defun org-beginning-of-line (&optional arg)
21941 "Go to the beginning of the current line. If that is invisible, continue
21942 to a visible line beginning. This makes the function of C-a more intuitive.
21943 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21944 first attempt, and only move to after the tags when the cursor is already
21945 beyond the end of the headline."
21946 (interactive "P")
21947 (let ((pos (point))
21948 (special (if (consp org-special-ctrl-a/e)
21949 (car org-special-ctrl-a/e)
21950 org-special-ctrl-a/e))
21951 refpos)
21952 (if (org-bound-and-true-p visual-line-mode)
21953 (beginning-of-visual-line 1)
21954 (beginning-of-line 1))
21955 (if (and arg (fboundp 'move-beginning-of-line))
21956 (call-interactively 'move-beginning-of-line)
21957 (if (bobp)
21959 (backward-char 1)
21960 (if (org-truely-invisible-p)
21961 (while (and (not (bobp)) (org-truely-invisible-p))
21962 (backward-char 1)
21963 (beginning-of-line 1))
21964 (forward-char 1))))
21965 (when special
21966 (cond
21967 ((and (looking-at org-complex-heading-regexp)
21968 (= (char-after (match-end 1)) ?\ ))
21969 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21970 (point-at-eol)))
21971 (goto-char
21972 (if (eq special t)
21973 (cond ((> pos refpos) refpos)
21974 ((= pos (point)) refpos)
21975 (t (point)))
21976 (cond ((> pos (point)) (point))
21977 ((not (eq last-command this-command)) (point))
21978 (t refpos)))))
21979 ((org-at-item-p)
21980 ;; Being at an item and not looking at an the item means point
21981 ;; was previously moved to beginning of a visual line, which
21982 ;; doesn't contain the item. Therefore, do nothing special,
21983 ;; just stay here.
21984 (when (looking-at org-list-full-item-re)
21985 ;; Set special position at first white space character after
21986 ;; bullet, and check-box, if any.
21987 (let ((after-bullet
21988 (let ((box (match-end 3)))
21989 (if (not box) (match-end 1)
21990 (let ((after (char-after box)))
21991 (if (and after (= after ? )) (1+ box) box))))))
21992 ;; Special case: Move point to special position when
21993 ;; currently after it or at beginning of line.
21994 (if (eq special t)
21995 (when (or (> pos after-bullet) (= (point) pos))
21996 (goto-char after-bullet))
21997 ;; Reversed case: Move point to special position when
21998 ;; point was already at beginning of line and command is
21999 ;; repeated.
22000 (when (and (= (point) pos) (eq last-command this-command))
22001 (goto-char after-bullet))))))))
22002 (org-no-warnings
22003 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22005 (defun org-end-of-line (&optional arg)
22006 "Go to the end of the line.
22007 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22008 tags on the first attempt, and only move to after the tags when
22009 the cursor is already beyond the end of the headline."
22010 (interactive "P")
22011 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22012 org-special-ctrl-a/e))
22013 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22014 'end-of-visual-line)
22015 ((fboundp 'move-end-of-line) 'move-end-of-line)
22016 (t 'end-of-line))))
22017 (if (or (not special) arg) (call-interactively move-fun)
22018 (let* ((element (save-excursion (beginning-of-line)
22019 (org-element-at-point)))
22020 (type (org-element-type element)))
22021 (cond
22022 ((memq type '(headline inlinetask))
22023 (let ((pos (point)))
22024 (beginning-of-line 1)
22025 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22026 (if (eq special t)
22027 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22028 (goto-char (match-beginning 1))
22029 (goto-char (match-end 0)))
22030 (if (or (< pos (match-end 0))
22031 (not (eq this-command last-command)))
22032 (goto-char (match-end 0))
22033 (goto-char (match-beginning 1))))
22034 (call-interactively move-fun))))
22035 ((org-element-property :hiddenp element)
22036 ;; If element is hidden, `move-end-of-line' would put point
22037 ;; after it. Use `end-of-line' to stay on current line.
22038 (call-interactively 'end-of-line))
22039 (t (call-interactively move-fun)))))
22040 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22042 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22043 (define-key org-mode-map "\C-e" 'org-end-of-line)
22045 (defun org-backward-sentence (&optional arg)
22046 "Go to beginning of sentence, or beginning of table field.
22047 This will call `backward-sentence' or `org-table-beginning-of-field',
22048 depending on context."
22049 (interactive "P")
22050 (cond
22051 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22052 (t (call-interactively 'backward-sentence))))
22054 (defun org-forward-sentence (&optional arg)
22055 "Go to end of sentence, or end of table field.
22056 This will call `forward-sentence' or `org-table-end-of-field',
22057 depending on context."
22058 (interactive "P")
22059 (cond
22060 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22061 (t (call-interactively 'forward-sentence))))
22063 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22064 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22066 (defun org-kill-line (&optional arg)
22067 "Kill line, to tags or end of line."
22068 (interactive "P")
22069 (cond
22070 ((or (not org-special-ctrl-k)
22071 (bolp)
22072 (not (org-at-heading-p)))
22073 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22074 org-ctrl-k-protect-subtree)
22075 (if (or (eq org-ctrl-k-protect-subtree 'error)
22076 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22077 (error "C-k aborted - would kill hidden subtree")))
22078 (call-interactively
22079 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22080 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22081 (kill-region (point) (match-beginning 1))
22082 (org-set-tags nil t))
22083 (t (kill-region (point) (point-at-eol)))))
22085 (define-key org-mode-map "\C-k" 'org-kill-line)
22087 (defun org-yank (&optional arg)
22088 "Yank. If the kill is a subtree, treat it specially.
22089 This command will look at the current kill and check if is a single
22090 subtree, or a series of subtrees[1]. If it passes the test, and if the
22091 cursor is at the beginning of a line or after the stars of a currently
22092 empty headline, then the yank is handled specially. How exactly depends
22093 on the value of the following variables, both set by default.
22095 org-yank-folded-subtrees
22096 When set, the subtree(s) will be folded after insertion, but only
22097 if doing so would now swallow text after the yanked text.
22099 org-yank-adjusted-subtrees
22100 When set, the subtree will be promoted or demoted in order to
22101 fit into the local outline tree structure, which means that the level
22102 will be adjusted so that it becomes the smaller one of the two
22103 *visible* surrounding headings.
22105 Any prefix to this command will cause `yank' to be called directly with
22106 no special treatment. In particular, a simple \\[universal-argument] prefix \
22107 will just
22108 plainly yank the text as it is.
22110 \[1] The test checks if the first non-white line is a heading
22111 and if there are no other headings with fewer stars."
22112 (interactive "P")
22113 (org-yank-generic 'yank arg))
22115 (defun org-yank-generic (command arg)
22116 "Perform some yank-like command.
22118 This function implements the behavior described in the `org-yank'
22119 documentation. However, it has been generalized to work for any
22120 interactive command with similar behavior."
22122 ;; pretend to be command COMMAND
22123 (setq this-command command)
22125 (if arg
22126 (call-interactively command)
22128 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22129 (and (org-kill-is-subtree-p)
22130 (or (bolp)
22131 (and (looking-at "[ \t]*$")
22132 (string-match
22133 "\\`\\*+\\'"
22134 (buffer-substring (point-at-bol) (point)))))))
22135 swallowp)
22136 (cond
22137 ((and subtreep org-yank-folded-subtrees)
22138 (let ((beg (point))
22139 end)
22140 (if (and subtreep org-yank-adjusted-subtrees)
22141 (org-paste-subtree nil nil 'for-yank)
22142 (call-interactively command))
22144 (setq end (point))
22145 (goto-char beg)
22146 (when (and (bolp) subtreep
22147 (not (setq swallowp
22148 (org-yank-folding-would-swallow-text beg end))))
22149 (org-with-limited-levels
22150 (or (looking-at org-outline-regexp)
22151 (re-search-forward org-outline-regexp-bol end t))
22152 (while (and (< (point) end) (looking-at org-outline-regexp))
22153 (hide-subtree)
22154 (org-cycle-show-empty-lines 'folded)
22155 (condition-case nil
22156 (outline-forward-same-level 1)
22157 (error (goto-char end))))))
22158 (when swallowp
22159 (message
22160 "Inserted text not folded because that would swallow text"))
22162 (goto-char end)
22163 (skip-chars-forward " \t\n\r")
22164 (beginning-of-line 1)
22165 (push-mark beg 'nomsg)))
22166 ((and subtreep org-yank-adjusted-subtrees)
22167 (let ((beg (point-at-bol)))
22168 (org-paste-subtree nil nil 'for-yank)
22169 (push-mark beg 'nomsg)))
22171 (call-interactively command))))))
22173 (defun org-yank-folding-would-swallow-text (beg end)
22174 "Would hide-subtree at BEG swallow any text after END?"
22175 (let (level)
22176 (org-with-limited-levels
22177 (save-excursion
22178 (goto-char beg)
22179 (when (or (looking-at org-outline-regexp)
22180 (re-search-forward org-outline-regexp-bol end t))
22181 (setq level (org-outline-level)))
22182 (goto-char end)
22183 (skip-chars-forward " \t\r\n\v\f")
22184 (if (or (eobp)
22185 (and (bolp) (looking-at org-outline-regexp)
22186 (<= (org-outline-level) level)))
22187 nil ; Nothing would be swallowed
22188 t))))) ; something would swallow
22190 (define-key org-mode-map "\C-y" 'org-yank)
22192 (defun org-truely-invisible-p ()
22193 "Check if point is at a character currently not visible.
22194 This version does not only check the character property, but also
22195 `visible-mode'."
22196 ;; Early versions of noutline don't have `outline-invisible-p'.
22197 (if (org-bound-and-true-p visible-mode)
22199 (outline-invisible-p)))
22201 (defun org-invisible-p2 ()
22202 "Check if point is at a character currently not visible."
22203 (save-excursion
22204 (if (and (eolp) (not (bobp))) (backward-char 1))
22205 ;; Early versions of noutline don't have `outline-invisible-p'.
22206 (outline-invisible-p)))
22208 (defun org-back-to-heading (&optional invisible-ok)
22209 "Call `outline-back-to-heading', but provide a better error message."
22210 (condition-case nil
22211 (outline-back-to-heading invisible-ok)
22212 (error (error "Before first headline at position %d in buffer %s"
22213 (point) (current-buffer)))))
22215 (defun org-before-first-heading-p ()
22216 "Before first heading?"
22217 (save-excursion
22218 (end-of-line)
22219 (null (re-search-backward org-outline-regexp-bol nil t))))
22221 (defun org-at-heading-p (&optional ignored)
22222 (outline-on-heading-p t))
22223 ;; Compatibility alias with Org versions < 7.8.03
22224 (defalias 'org-on-heading-p 'org-at-heading-p)
22226 (defun org-at-comment-p nil
22227 "Is cursor in a line starting with a # character?"
22228 (save-excursion
22229 (beginning-of-line)
22230 (looking-at "^#")))
22232 (defun org-at-drawer-p nil
22233 "Is cursor at a drawer keyword?"
22234 (save-excursion
22235 (move-beginning-of-line 1)
22236 (looking-at org-drawer-regexp)))
22238 (defun org-at-block-p nil
22239 "Is cursor at a block keyword?"
22240 (save-excursion
22241 (move-beginning-of-line 1)
22242 (looking-at org-block-regexp)))
22244 (defun org-point-at-end-of-empty-headline ()
22245 "If point is at the end of an empty headline, return t, else nil.
22246 If the heading only contains a TODO keyword, it is still still considered
22247 empty."
22248 (and (looking-at "[ \t]*$")
22249 (when org-todo-line-regexp
22250 (save-excursion
22251 (beginning-of-line 1)
22252 (let ((case-fold-search nil))
22253 (looking-at org-todo-line-regexp)
22254 (string= (match-string 3) ""))))))
22256 (defun org-at-heading-or-item-p ()
22257 (or (org-at-heading-p) (org-at-item-p)))
22259 (defun org-at-target-p ()
22260 (or (org-in-regexp org-radio-target-regexp)
22261 (org-in-regexp org-target-regexp)))
22262 ;; Compatibility alias with Org versions < 7.8.03
22263 (defalias 'org-on-target-p 'org-at-target-p)
22265 (defun org-up-heading-all (arg)
22266 "Move to the heading line of which the present line is a subheading.
22267 This function considers both visible and invisible heading lines.
22268 With argument, move up ARG levels."
22269 (if (fboundp 'outline-up-heading-all)
22270 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22271 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22273 (defun org-up-heading-safe ()
22274 "Move to the heading line of which the present line is a subheading.
22275 This version will not throw an error. It will return the level of the
22276 headline found, or nil if no higher level is found.
22278 Also, this function will be a lot faster than `outline-up-heading',
22279 because it relies on stars being the outline starters. This can really
22280 make a significant difference in outlines with very many siblings."
22281 (let (start-level re)
22282 (org-back-to-heading t)
22283 (setq start-level (funcall outline-level))
22284 (if (equal start-level 1)
22286 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22287 (if (re-search-backward re nil t)
22288 (funcall outline-level)))))
22290 (defun org-first-sibling-p ()
22291 "Is this heading the first child of its parents?"
22292 (interactive)
22293 (let ((re org-outline-regexp-bol)
22294 level l)
22295 (unless (org-at-heading-p t)
22296 (error "Not at a heading"))
22297 (setq level (funcall outline-level))
22298 (save-excursion
22299 (if (not (re-search-backward re nil t))
22301 (setq l (funcall outline-level))
22302 (< l level)))))
22304 (defun org-goto-sibling (&optional previous)
22305 "Goto the next sibling, even if it is invisible.
22306 When PREVIOUS is set, go to the previous sibling instead. Returns t
22307 when a sibling was found. When none is found, return nil and don't
22308 move point."
22309 (let ((fun (if previous 're-search-backward 're-search-forward))
22310 (pos (point))
22311 (re org-outline-regexp-bol)
22312 level l)
22313 (when (condition-case nil (org-back-to-heading t) (error nil))
22314 (setq level (funcall outline-level))
22315 (catch 'exit
22316 (or previous (forward-char 1))
22317 (while (funcall fun re nil t)
22318 (setq l (funcall outline-level))
22319 (when (< l level) (goto-char pos) (throw 'exit nil))
22320 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22321 (goto-char pos)
22322 nil))))
22324 (defun org-show-siblings ()
22325 "Show all siblings of the current headline."
22326 (save-excursion
22327 (while (org-goto-sibling) (org-flag-heading nil)))
22328 (save-excursion
22329 (while (org-goto-sibling 'previous)
22330 (org-flag-heading nil))))
22332 (defun org-goto-first-child ()
22333 "Goto the first child, even if it is invisible.
22334 Return t when a child was found. Otherwise don't move point and
22335 return nil."
22336 (let (level (pos (point)) (re org-outline-regexp-bol))
22337 (when (condition-case nil (org-back-to-heading t) (error nil))
22338 (setq level (outline-level))
22339 (forward-char 1)
22340 (if (and (re-search-forward re nil t) (> (outline-level) level))
22341 (progn (goto-char (match-beginning 0)) t)
22342 (goto-char pos) nil))))
22344 (defun org-show-hidden-entry ()
22345 "Show an entry where even the heading is hidden."
22346 (save-excursion
22347 (org-show-entry)))
22349 (defun org-flag-heading (flag &optional entry)
22350 "Flag the current heading. FLAG non-nil means make invisible.
22351 When ENTRY is non-nil, show the entire entry."
22352 (save-excursion
22353 (org-back-to-heading t)
22354 ;; Check if we should show the entire entry
22355 (if entry
22356 (progn
22357 (org-show-entry)
22358 (save-excursion
22359 (and (outline-next-heading)
22360 (org-flag-heading nil))))
22361 (outline-flag-region (max (point-min) (1- (point)))
22362 (save-excursion (outline-end-of-heading) (point))
22363 flag))))
22365 (defun org-get-next-sibling ()
22366 "Move to next heading of the same level, and return point.
22367 If there is no such heading, return nil.
22368 This is like outline-next-sibling, but invisible headings are ok."
22369 (let ((level (funcall outline-level)))
22370 (outline-next-heading)
22371 (while (and (not (eobp)) (> (funcall outline-level) level))
22372 (outline-next-heading))
22373 (if (or (eobp) (< (funcall outline-level) level))
22375 (point))))
22377 (defun org-get-last-sibling ()
22378 "Move to previous heading of the same level, and return point.
22379 If there is no such heading, return nil."
22380 (let ((opoint (point))
22381 (level (funcall outline-level)))
22382 (outline-previous-heading)
22383 (when (and (/= (point) opoint) (outline-on-heading-p t))
22384 (while (and (> (funcall outline-level) level)
22385 (not (bobp)))
22386 (outline-previous-heading))
22387 (if (< (funcall outline-level) level)
22389 (point)))))
22391 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22392 "Goto to the end of a subtree."
22393 ;; This contains an exact copy of the original function, but it uses
22394 ;; `org-back-to-heading', to make it work also in invisible
22395 ;; trees. And is uses an invisible-ok argument.
22396 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22397 ;; Furthermore, when used inside Org, finding the end of a large subtree
22398 ;; with many children and grandchildren etc, this can be much faster
22399 ;; than the outline version.
22400 (org-back-to-heading invisible-ok)
22401 (let ((first t)
22402 (level (funcall outline-level)))
22403 (if (and (derived-mode-p 'org-mode) (< level 1000))
22404 ;; A true heading (not a plain list item), in Org-mode
22405 ;; This means we can easily find the end by looking
22406 ;; only for the right number of stars. Using a regexp to do
22407 ;; this is so much faster than using a Lisp loop.
22408 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22409 (forward-char 1)
22410 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22411 ;; something else, do it the slow way
22412 (while (and (not (eobp))
22413 (or first (> (funcall outline-level) level)))
22414 (setq first nil)
22415 (outline-next-heading)))
22416 (unless to-heading
22417 (if (memq (preceding-char) '(?\n ?\^M))
22418 (progn
22419 ;; Go to end of line before heading
22420 (forward-char -1)
22421 (if (memq (preceding-char) '(?\n ?\^M))
22422 ;; leave blank line before heading
22423 (forward-char -1))))))
22424 (point))
22426 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22427 "Use Org version in org-mode, for dramatic speed-up."
22428 (if (derived-mode-p 'org-mode)
22429 (progn
22430 (org-end-of-subtree nil t)
22431 (unless (eobp) (backward-char 1)))
22432 ad-do-it))
22434 (defun org-end-of-meta-data-and-drawers ()
22435 "Jump to the first text after meta data and drawers in the current entry.
22436 This will move over empty lines, lines with planning time stamps,
22437 clocking lines, and drawers."
22438 (org-back-to-heading t)
22439 (let ((end (save-excursion (outline-next-heading) (point)))
22440 (re (concat "\\(" org-drawer-regexp "\\)"
22441 "\\|" "[ \t]*" org-keyword-time-regexp)))
22442 (forward-line 1)
22443 (while (re-search-forward re end t)
22444 (if (not (match-end 1))
22445 ;; empty or planning line
22446 (forward-line 1)
22447 ;; a drawer, find the end
22448 (re-search-forward "^[ \t]*:END:" end 'move)
22449 (forward-line 1)))
22450 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22451 (point)))
22453 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22454 "Move forward to the arg'th subheading at same level as this one.
22455 Stop at the first and last subheadings of a superior heading.
22456 Normally this only looks at visible headings, but when INVISIBLE-OK is
22457 non-nil it will also look at invisible ones."
22458 (interactive "p")
22459 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22460 (outline-next-heading)
22461 (org-at-heading-p)
22462 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22463 (re (format "^\\*\\{1,%d\\} " level))
22465 (forward-char 1)
22466 (while (> arg 0)
22467 (while (and (re-search-forward re nil 'move)
22468 (setq l (- (match-end 0) (match-beginning 0) 1))
22469 (= l level)
22470 (not invisible-ok)
22471 (progn (backward-char 1) (outline-invisible-p)))
22472 (if (< l level) (setq arg 1)))
22473 (setq arg (1- arg)))
22474 (beginning-of-line 1))))
22476 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22477 "Move backward to the arg'th subheading at same level as this one.
22478 Stop at the first and last subheadings of a superior heading."
22479 (interactive "p")
22480 (if (not (ignore-errors (org-back-to-heading)))
22481 (goto-char (point-min))
22482 (org-at-heading-p)
22483 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22484 (re (format "^\\*\\{1,%d\\} " level))
22486 (while (> arg 0)
22487 (while (and (re-search-backward re nil 'move)
22488 (setq l (- (match-end 0) (match-beginning 0) 1))
22489 (= l level)
22490 (not invisible-ok)
22491 (outline-invisible-p))
22492 (if (< l level) (setq arg 1)))
22493 (setq arg (1- arg))))))
22495 (defun org-forward-element ()
22496 "Move forward by one element.
22497 Move to the next element at the same level, when possible."
22498 (interactive)
22499 (cond ((eobp) (error "Cannot move further down"))
22500 ((org-with-limited-levels (org-at-heading-p))
22501 (let ((origin (point)))
22502 (org-forward-heading-same-level 1)
22503 (unless (org-with-limited-levels (org-at-heading-p))
22504 (goto-char origin)
22505 (error "Cannot move further down"))))
22507 (let* ((elem (org-element-at-point))
22508 (end (org-element-property :end elem))
22509 (parent (org-element-property :parent elem)))
22510 (if (and parent (= (org-element-property :contents-end parent) end))
22511 (goto-char (org-element-property :end parent))
22512 (goto-char end))))))
22514 (defun org-backward-element ()
22515 "Move backward by one element.
22516 Move to the previous element at the same level, when possible."
22517 (interactive)
22518 (cond ((bobp) (error "Cannot move further up"))
22519 ((org-with-limited-levels (org-at-heading-p))
22520 ;; At an headline, move to the previous one, if any, or stay
22521 ;; here.
22522 (let ((origin (point)))
22523 (org-backward-heading-same-level 1)
22524 (unless (org-with-limited-levels (org-at-heading-p))
22525 (goto-char origin)
22526 (error "Cannot move further up"))))
22528 (let* ((trail (org-element-at-point 'keep-trail))
22529 (elem (car trail))
22530 (prev-elem (nth 1 trail))
22531 (beg (org-element-property :begin elem)))
22532 (cond
22533 ;; Move to beginning of current element if point isn't
22534 ;; there already.
22535 ((/= (point) beg) (goto-char beg))
22536 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22537 ((org-before-first-heading-p) (goto-char (point-min)))
22538 (t (org-back-to-heading)))))))
22540 (defun org-up-element ()
22541 "Move to upper element."
22542 (interactive)
22543 (if (org-with-limited-levels (org-at-heading-p))
22544 (unless (org-up-heading-safe) (error "No surrounding element"))
22545 (let* ((elem (org-element-at-point))
22546 (parent (org-element-property :parent elem)))
22547 (if parent (goto-char (org-element-property :begin parent))
22548 (if (org-with-limited-levels (org-before-first-heading-p))
22549 (error "No surrounding element")
22550 (org-with-limited-levels (org-back-to-heading)))))))
22552 (defvar org-element-greater-elements)
22553 (defun org-down-element ()
22554 "Move to inner element."
22555 (interactive)
22556 (let ((element (org-element-at-point)))
22557 (cond
22558 ((memq (org-element-type element) '(plain-list table))
22559 (goto-char (org-element-property :contents-begin element))
22560 (forward-char))
22561 ((memq (org-element-type element) org-element-greater-elements)
22562 ;; If contents are hidden, first disclose them.
22563 (when (org-element-property :hiddenp element) (org-cycle))
22564 (goto-char (or (org-element-property :contents-begin element)
22565 (error "No content for this element"))))
22566 (t (error "No inner element")))))
22568 (defun org-drag-element-backward ()
22569 "Move backward element at point."
22570 (interactive)
22571 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22572 (let* ((trail (org-element-at-point 'keep-trail))
22573 (elem (car trail))
22574 (prev-elem (nth 1 trail)))
22575 ;; Error out if no previous element or previous element is
22576 ;; a parent of the current one.
22577 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22578 (error "Cannot drag element backward")
22579 (let ((pos (point)))
22580 (org-element-swap-A-B prev-elem elem)
22581 (goto-char (+ (org-element-property :begin prev-elem)
22582 (- pos (org-element-property :begin elem)))))))))
22584 (defun org-drag-element-forward ()
22585 "Move forward element at point."
22586 (interactive)
22587 (let* ((pos (point))
22588 (elem (org-element-at-point)))
22589 (when (= (point-max) (org-element-property :end elem))
22590 (error "Cannot drag element forward"))
22591 (goto-char (org-element-property :end elem))
22592 (let ((next-elem (org-element-at-point)))
22593 (when (or (org-element-nested-p elem next-elem)
22594 (and (eq (org-element-type next-elem) 'headline)
22595 (not (eq (org-element-type elem) 'headline))))
22596 (goto-char pos)
22597 (error "Cannot drag element forward"))
22598 ;; Compute new position of point: it's shifted by NEXT-ELEM
22599 ;; body's length (without final blanks) and by the length of
22600 ;; blanks between ELEM and NEXT-ELEM.
22601 (let ((size-next (- (save-excursion
22602 (goto-char (org-element-property :end next-elem))
22603 (skip-chars-backward " \r\t\n")
22604 (forward-line)
22605 ;; Small correction if buffer doesn't end
22606 ;; with a newline character.
22607 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22608 (org-element-property :begin next-elem)))
22609 (size-blank (- (org-element-property :end elem)
22610 (save-excursion
22611 (goto-char (org-element-property :end elem))
22612 (skip-chars-backward " \r\t\n")
22613 (forward-line)
22614 (point)))))
22615 (org-element-swap-A-B elem next-elem)
22616 (goto-char (+ pos size-next size-blank))))))
22618 (defun org-mark-element ()
22619 "Put point at beginning of this element, mark at end.
22621 Interactively, if this command is repeated or (in Transient Mark
22622 mode) if the mark is active, it marks the next element after the
22623 ones already marked."
22624 (interactive)
22625 (let (deactivate-mark)
22626 (if (and (org-called-interactively-p 'any)
22627 (or (and (eq last-command this-command) (mark t))
22628 (and transient-mark-mode mark-active)))
22629 (set-mark
22630 (save-excursion
22631 (goto-char (mark))
22632 (goto-char (org-element-property :end (org-element-at-point)))))
22633 (let ((element (org-element-at-point)))
22634 (end-of-line)
22635 (push-mark (org-element-property :end element) t t)
22636 (goto-char (org-element-property :begin element))))))
22638 (defun org-narrow-to-element ()
22639 "Narrow buffer to current element."
22640 (interactive)
22641 (let ((elem (org-element-at-point)))
22642 (cond
22643 ((eq (car elem) 'headline)
22644 (narrow-to-region
22645 (org-element-property :begin elem)
22646 (org-element-property :end elem)))
22647 ((memq (car elem) org-element-greater-elements)
22648 (narrow-to-region
22649 (org-element-property :contents-begin elem)
22650 (org-element-property :contents-end elem)))
22652 (narrow-to-region
22653 (org-element-property :begin elem)
22654 (org-element-property :end elem))))))
22656 (defun org-transpose-words ()
22657 "Transpose words, using `org-mode' syntax table."
22658 (interactive)
22659 (with-syntax-table org-syntax-table
22660 (call-interactively 'transpose-words)))
22661 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22663 (defun org-transpose-element ()
22664 "Transpose current and previous elements, keeping blank lines between.
22665 Point is moved after both elements."
22666 (interactive)
22667 (org-skip-whitespace)
22668 (let ((end (org-element-property :end (org-element-at-point))))
22669 (org-drag-element-backward)
22670 (goto-char end)))
22672 (defun org-unindent-buffer ()
22673 "Un-indent the visible part of the buffer.
22674 Relative indentation (between items, inside blocks, etc.) isn't
22675 modified."
22676 (interactive)
22677 (unless (eq major-mode 'org-mode)
22678 (error "Cannot un-indent a buffer not in Org mode"))
22679 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22680 unindent-tree ; For byte-compiler.
22681 (unindent-tree
22682 (function
22683 (lambda (contents)
22684 (mapc
22685 (lambda (element)
22686 (if (memq (org-element-type element) '(headline section))
22687 (funcall unindent-tree (org-element-contents element))
22688 (save-excursion
22689 (save-restriction
22690 (narrow-to-region
22691 (org-element-property :begin element)
22692 (org-element-property :end element))
22693 (org-do-remove-indentation)))))
22694 (reverse contents))))))
22695 (funcall unindent-tree (org-element-contents parse-tree))))
22697 (defun org-show-subtree ()
22698 "Show everything after this heading at deeper levels."
22699 (interactive)
22700 (outline-flag-region
22701 (point)
22702 (save-excursion
22703 (org-end-of-subtree t t))
22704 nil))
22706 (defun org-show-entry ()
22707 "Show the body directly following this heading.
22708 Show the heading too, if it is currently invisible."
22709 (interactive)
22710 (save-excursion
22711 (condition-case nil
22712 (progn
22713 (org-back-to-heading t)
22714 (outline-flag-region
22715 (max (point-min) (1- (point)))
22716 (save-excursion
22717 (if (re-search-forward
22718 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22719 (match-beginning 1)
22720 (point-max)))
22721 nil)
22722 (org-cycle-hide-drawers 'children))
22723 (error nil))))
22725 (defun org-make-options-regexp (kwds &optional extra)
22726 "Make a regular expression for keyword lines."
22727 (concat
22728 "^#\\+\\("
22729 (mapconcat 'regexp-quote kwds "\\|")
22730 (if extra (concat "\\|" extra))
22731 "\\):[ \t]*\\(.*\\)"))
22733 ;; Make isearch reveal the necessary context
22734 (defun org-isearch-end ()
22735 "Reveal context after isearch exits."
22736 (when isearch-success ; only if search was successful
22737 (if (featurep 'xemacs)
22738 ;; Under XEmacs, the hook is run in the correct place,
22739 ;; we directly show the context.
22740 (org-show-context 'isearch)
22741 ;; In Emacs the hook runs *before* restoring the overlays.
22742 ;; So we have to use a one-time post-command-hook to do this.
22743 ;; (Emacs 22 has a special variable, see function `org-mode')
22744 (unless (and (boundp 'isearch-mode-end-hook-quit)
22745 isearch-mode-end-hook-quit)
22746 ;; Only when the isearch was not quitted.
22747 (org-add-hook 'post-command-hook 'org-isearch-post-command
22748 'append 'local)))))
22750 (defun org-isearch-post-command ()
22751 "Remove self from hook, and show context."
22752 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22753 (org-show-context 'isearch))
22756 ;;;; Integration with and fixes for other packages
22758 ;;; Imenu support
22760 (defvar org-imenu-markers nil
22761 "All markers currently used by Imenu.")
22762 (make-variable-buffer-local 'org-imenu-markers)
22764 (defun org-imenu-new-marker (&optional pos)
22765 "Return a new marker for use by Imenu, and remember the marker."
22766 (let ((m (make-marker)))
22767 (move-marker m (or pos (point)))
22768 (push m org-imenu-markers)
22771 (defun org-imenu-get-tree ()
22772 "Produce the index for Imenu."
22773 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22774 (setq org-imenu-markers nil)
22775 (let* ((n org-imenu-depth)
22776 (re (concat "^" (org-get-limited-outline-regexp)))
22777 (subs (make-vector (1+ n) nil))
22778 (last-level 0)
22779 m level head)
22780 (save-excursion
22781 (save-restriction
22782 (widen)
22783 (goto-char (point-max))
22784 (while (re-search-backward re nil t)
22785 (setq level (org-reduced-level (funcall outline-level)))
22786 (when (and (<= level n)
22787 (looking-at org-complex-heading-regexp))
22788 (setq head (org-link-display-format
22789 (org-match-string-no-properties 4))
22790 m (org-imenu-new-marker))
22791 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22792 (if (>= level last-level)
22793 (push (cons head m) (aref subs level))
22794 (push (cons head (aref subs (1+ level))) (aref subs level))
22795 (loop for i from (1+ level) to n do (aset subs i nil)))
22796 (setq last-level level)))))
22797 (aref subs 1)))
22799 (eval-after-load "imenu"
22800 '(progn
22801 (add-hook 'imenu-after-jump-hook
22802 (lambda ()
22803 (if (derived-mode-p 'org-mode)
22804 (org-show-context 'org-goto))))))
22806 (defun org-link-display-format (link)
22807 "Replace a link with either the description, or the link target
22808 if no description is present"
22809 (save-match-data
22810 (if (string-match org-bracket-link-analytic-regexp link)
22811 (replace-match (if (match-end 5)
22812 (match-string 5 link)
22813 (concat (match-string 1 link)
22814 (match-string 3 link)))
22815 nil t link)
22816 link)))
22818 (defun org-toggle-link-display ()
22819 "Toggle the literal or descriptive display of links."
22820 (interactive)
22821 (if org-descriptive-links
22822 (progn (org-remove-from-invisibility-spec '(org-link))
22823 (org-restart-font-lock)
22824 (setq org-descriptive-links nil))
22825 (progn (add-to-invisibility-spec '(org-link))
22826 (org-restart-font-lock)
22827 (setq org-descriptive-links t))))
22829 ;; Speedbar support
22831 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22832 "Overlay marking the agenda restriction line in speedbar.")
22833 (overlay-put org-speedbar-restriction-lock-overlay
22834 'face 'org-agenda-restriction-lock)
22835 (overlay-put org-speedbar-restriction-lock-overlay
22836 'help-echo "Agendas are currently limited to this item.")
22837 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22839 (defun org-speedbar-set-agenda-restriction ()
22840 "Restrict future agenda commands to the location at point in speedbar.
22841 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22842 (interactive)
22843 (require 'org-agenda)
22844 (let (p m tp np dir txt)
22845 (cond
22846 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22847 'org-imenu t))
22848 (setq m (get-text-property p 'org-imenu-marker))
22849 (with-current-buffer (marker-buffer m)
22850 (goto-char m)
22851 (org-agenda-set-restriction-lock 'subtree)))
22852 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22853 'speedbar-function 'speedbar-find-file))
22854 (setq tp (previous-single-property-change
22855 (1+ p) 'speedbar-function)
22856 np (next-single-property-change
22857 tp 'speedbar-function)
22858 dir (speedbar-line-directory)
22859 txt (buffer-substring-no-properties (or tp (point-min))
22860 (or np (point-max))))
22861 (with-current-buffer (find-file-noselect
22862 (let ((default-directory dir))
22863 (expand-file-name txt)))
22864 (unless (derived-mode-p 'org-mode)
22865 (error "Cannot restrict to non-Org-mode file"))
22866 (org-agenda-set-restriction-lock 'file)))
22867 (t (error "Don't know how to restrict Org-mode's agenda")))
22868 (move-overlay org-speedbar-restriction-lock-overlay
22869 (point-at-bol) (point-at-eol))
22870 (setq current-prefix-arg nil)
22871 (org-agenda-maybe-redo)))
22873 (eval-after-load "speedbar"
22874 '(progn
22875 (speedbar-add-supported-extension ".org")
22876 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22877 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22878 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22879 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22880 (add-hook 'speedbar-visiting-tag-hook
22881 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22883 ;;; Fixes and Hacks for problems with other packages
22885 ;; Make flyspell not check words in links, to not mess up our keymap
22886 (defun org-mode-flyspell-verify ()
22887 "Don't let flyspell put overlays at active buttons, or on
22888 {todo,all-time,additional-option-like}-keywords."
22889 (let ((pos (max (1- (point)) (point-min)))
22890 (word (thing-at-point 'word)))
22891 (and (not (get-text-property pos 'keymap))
22892 (not (get-text-property pos 'org-no-flyspell))
22893 (not (member word org-todo-keywords-1))
22894 (not (member word org-all-time-keywords))
22895 (not (member word org-options-keywords))
22896 (not (member word (mapcar 'car org-startup-options)))
22897 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22899 (defun org-remove-flyspell-overlays-in (beg end)
22900 "Remove flyspell overlays in region."
22901 (and (org-bound-and-true-p flyspell-mode)
22902 (fboundp 'flyspell-delete-region-overlays)
22903 (flyspell-delete-region-overlays beg end))
22904 (add-text-properties beg end '(org-no-flyspell t)))
22906 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22907 (eval-after-load "bookmark"
22908 '(if (boundp 'bookmark-after-jump-hook)
22909 ;; We can use the hook
22910 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22911 ;; Hook not available, use advice
22912 (defadvice bookmark-jump (after org-make-visible activate)
22913 "Make the position visible."
22914 (org-bookmark-jump-unhide))))
22916 ;; Make sure saveplace shows the location if it was hidden
22917 (eval-after-load "saveplace"
22918 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22919 "Make the position visible."
22920 (org-bookmark-jump-unhide)))
22922 ;; Make sure ecb shows the location if it was hidden
22923 (eval-after-load "ecb"
22924 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22925 "Make hierarchy visible when jumping into location from ECB tree buffer."
22926 (if (derived-mode-p 'org-mode)
22927 (org-show-context))))
22929 (defun org-bookmark-jump-unhide ()
22930 "Unhide the current position, to show the bookmark location."
22931 (and (derived-mode-p 'org-mode)
22932 (or (outline-invisible-p)
22933 (save-excursion (goto-char (max (point-min) (1- (point))))
22934 (outline-invisible-p)))
22935 (org-show-context 'bookmark-jump)))
22937 ;; Make session.el ignore our circular variable
22938 (eval-after-load "session"
22939 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22941 ;;;; Experimental code
22943 (defun org-closed-in-range ()
22944 "Sparse tree of items closed in a certain time range.
22945 Still experimental, may disappear in the future."
22946 (interactive)
22947 ;; Get the time interval from the user.
22948 (let* ((time1 (org-float-time
22949 (org-read-date nil 'to-time nil "Starting date: ")))
22950 (time2 (org-float-time
22951 (org-read-date nil 'to-time nil "End date:")))
22952 ;; callback function
22953 (callback (lambda ()
22954 (let ((time
22955 (org-float-time
22956 (apply 'encode-time
22957 (org-parse-time-string
22958 (match-string 1))))))
22959 ;; check if time in interval
22960 (and (>= time time1) (<= time time2))))))
22961 ;; make tree, check each match with the callback
22962 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22964 ;;;; Finish up
22966 (provide 'org)
22968 (run-hooks 'org-load-hook)
22970 ;;; org.el ends here