testing/README: Fix instructions
[org-mode.git] / lisp / org.el
blob651182aab83997f8dbe27621d9d0e6c7b7a1a7b2
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro org-with-limited-levels.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches an headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-at-clock-log-p "org-clock" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function orgtbl-mode "org-table" (&optional arg))
127 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
128 (declare-function org-beamer-mode "org-beamer" ())
129 (declare-function org-table-edit-field "org-table" (arg))
130 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
131 (declare-function org-id-get-create "org-id" (&optional force))
132 (declare-function org-id-find-id-file "org-id" (id))
133 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
134 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (autoload 'org-element-at-point "org-element")
141 (autoload 'org-element-type "org-element")
143 (declare-function org-element-at-point "org-element" (&optional keep-trail))
144 (declare-function org-element-type "org-element" (element))
145 (declare-function org-element-context "org-element" (&optional element))
146 (declare-function org-element-contents "org-element" (element))
147 (declare-function org-element-property "org-element" (property element))
148 (declare-function org-element-put-property "org-element"
149 (element property value))
150 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
151 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
152 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
153 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
154 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
155 (declare-function org-element-interpret-data "org-element" (data &optional parent))
157 ;; load languages based on value of `org-babel-load-languages'
158 (defvar org-babel-load-languages)
160 ;;;###autoload
161 (defun org-babel-do-load-languages (sym value)
162 "Load the languages defined in `org-babel-load-languages'."
163 (set-default sym value)
164 (mapc (lambda (pair)
165 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
166 (if active
167 (progn
168 (require (intern (concat "ob-" lang))))
169 (progn
170 (funcall 'fmakunbound
171 (intern (concat "org-babel-execute:" lang)))
172 (funcall 'fmakunbound
173 (intern (concat "org-babel-expand-body:" lang)))))))
174 org-babel-load-languages))
176 (defcustom org-babel-load-languages '((emacs-lisp . t))
177 "Languages which can be evaluated in Org-mode buffers.
178 This list can be used to load support for any of the languages
179 below, note that each language will depend on a different set of
180 system executables and/or Emacs modes. When a language is
181 \"loaded\", then code blocks in that language can be evaluated
182 with `org-babel-execute-src-block' bound by default to C-c
183 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
184 be set to remove code block evaluation from the C-c C-c
185 keybinding. By default only Emacs Lisp (which has no
186 requirements) is loaded."
187 :group 'org-babel
188 :set 'org-babel-do-load-languages
189 :version "24.1"
190 :type '(alist :tag "Babel Languages"
191 :key-type
192 (choice
193 (const :tag "Awk" awk)
194 (const :tag "C" C)
195 (const :tag "R" R)
196 (const :tag "Asymptote" asymptote)
197 (const :tag "Calc" calc)
198 (const :tag "Clojure" clojure)
199 (const :tag "CSS" css)
200 (const :tag "Ditaa" ditaa)
201 (const :tag "Dot" dot)
202 (const :tag "Emacs Lisp" emacs-lisp)
203 (const :tag "Fortran" fortran)
204 (const :tag "Gnuplot" gnuplot)
205 (const :tag "Haskell" haskell)
206 (const :tag "IO" io)
207 (const :tag "Java" java)
208 (const :tag "Javascript" js)
209 (const :tag "LaTeX" latex)
210 (const :tag "Ledger" ledger)
211 (const :tag "Lilypond" lilypond)
212 (const :tag "Lisp" lisp)
213 (const :tag "Makefile" makefile)
214 (const :tag "Maxima" maxima)
215 (const :tag "Matlab" matlab)
216 (const :tag "Mscgen" mscgen)
217 (const :tag "Ocaml" ocaml)
218 (const :tag "Octave" octave)
219 (const :tag "Org" org)
220 (const :tag "Perl" perl)
221 (const :tag "Pico Lisp" picolisp)
222 (const :tag "PlantUML" plantuml)
223 (const :tag "Python" python)
224 (const :tag "Ruby" ruby)
225 (const :tag "Sass" sass)
226 (const :tag "Scala" scala)
227 (const :tag "Scheme" scheme)
228 (const :tag "Screen" screen)
229 (const :tag "Shell Script" sh)
230 (const :tag "Shen" shen)
231 (const :tag "Sql" sql)
232 (const :tag "Sqlite" sqlite))
233 :value-type (boolean :tag "Activate" :value t)))
235 ;;;; Customization variables
236 (defcustom org-clone-delete-id nil
237 "Remove ID property of clones of a subtree.
238 When non-nil, clones of a subtree don't inherit the ID property.
239 Otherwise they inherit the ID property with a new unique
240 identifier."
241 :type 'boolean
242 :version "24.1"
243 :group 'org-id)
245 ;;; Version
246 (org-check-version)
248 ;;;###autoload
249 (defun org-version (&optional here full message)
250 "Show the org-mode version in the echo area.
251 With prefix argument HERE, insert it at point.
252 When FULL is non-nil, use a verbose version string.
253 When MESSAGE is non-nil, display a message with the version."
254 (interactive "P")
255 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
256 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
257 (load-suffixes (list ".el"))
258 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
259 (org-trash (or
260 (and (fboundp 'org-release) (fboundp 'org-git-version))
261 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
262 (load-suffixes save-load-suffixes)
263 (org-version (org-release))
264 (git-version (org-git-version))
265 (version (format "Org-mode version %s (%s @ %s)"
266 org-version
267 git-version
268 (if org-install-dir
269 (if (string= org-dir org-install-dir)
270 org-install-dir
271 (concat "mixed installation! " org-install-dir " and " org-dir))
272 "org-loaddefs.el can not be found!")))
273 (_version (if full version org-version)))
274 (if (org-called-interactively-p 'interactive)
275 (if here
276 (insert version)
277 (message version))
278 (if message (message _version))
279 _version)))
281 (defconst org-version (org-version))
283 ;;; Compatibility constants
285 ;;; The custom variables
287 (defgroup org nil
288 "Outline-based notes management and organizer."
289 :tag "Org"
290 :group 'outlines
291 :group 'calendar)
293 (defcustom org-mode-hook nil
294 "Mode hook for Org-mode, run after the mode was turned on."
295 :group 'org
296 :type 'hook)
298 (defcustom org-load-hook nil
299 "Hook that is run after org.el has been loaded."
300 :group 'org
301 :type 'hook)
303 (defcustom org-log-buffer-setup-hook nil
304 "Hook that is run after an Org log buffer is created."
305 :group 'org
306 :version "24.1"
307 :type 'hook)
309 (defvar org-modules) ; defined below
310 (defvar org-modules-loaded nil
311 "Have the modules been loaded already?")
313 (defun org-load-modules-maybe (&optional force)
314 "Load all extensions listed in `org-modules'."
315 (when (or force (not org-modules-loaded))
316 (mapc (lambda (ext)
317 (condition-case nil (require ext)
318 (error (message "Problems while trying to load feature `%s'" ext))))
319 org-modules)
320 (setq org-modules-loaded t)))
322 (defun org-set-modules (var value)
323 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
324 (set var value)
325 (when (featurep 'org)
326 (org-load-modules-maybe 'force)))
328 (when (org-bound-and-true-p org-modules)
329 (let ((a (member 'org-infojs org-modules)))
330 (and a (setcar a 'org-jsinfo))))
332 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
333 "Modules that should always be loaded together with org.el.
334 If a description starts with <C>, the file is not part of Emacs
335 and loading it will require that you have downloaded and properly installed
336 the org-mode distribution.
338 You can also use this system to load external packages (i.e. neither Org
339 core modules, nor modules from the CONTRIB directory). Just add symbols
340 to the end of the list. If the package is called org-xyz.el, then you need
341 to add the symbol `xyz', and the package must have a call to
343 (provide 'org-xyz)"
344 :group 'org
345 :set 'org-set-modules
346 :type
347 '(set :greedy t
348 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
349 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
350 (const :tag " crypt: Encryption of subtrees" org-crypt)
351 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
352 (const :tag " docview: Links to doc-view buffers" org-docview)
353 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
354 (const :tag " id: Global IDs for identifying entries" org-id)
355 (const :tag " info: Links to Info nodes" org-info)
356 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
357 (const :tag " habit: Track your consistency with habits" org-habit)
358 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
359 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
360 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
361 (const :tag " mew Links to Mew folders/messages" org-mew)
362 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
363 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
364 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
365 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
366 (const :tag " vm: Links to VM folders/messages" org-vm)
367 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
368 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
369 (const :tag " mouse: Additional mouse support" org-mouse)
370 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
372 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
373 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
374 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
375 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
376 (const :tag "C collector: Collect properties into tables" org-collector)
377 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
378 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
379 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
380 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
381 (const :tag "C eval: Include command output as text" org-eval)
382 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
383 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
384 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
385 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
386 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
388 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
390 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
391 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
392 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
393 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
394 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
395 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
396 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
397 (const :tag "C mtags: Support for muse-like tags" org-mtags)
398 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
399 (const :tag "C registry: A registry for Org-mode links" org-registry)
400 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
401 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
402 (const :tag "C secretary: Team management with org-mode" org-secretary)
403 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
404 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
405 (const :tag "C track: Keep up with Org-mode development" org-track)
406 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
407 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
408 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
410 (defcustom org-support-shift-select nil
411 "Non-nil means make shift-cursor commands select text when possible.
413 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
414 start selecting a region, or enlarge regions started in this way.
415 In Org-mode, in special contexts, these same keys are used for
416 other purposes, important enough to compete with shift selection.
417 Org tries to balance these needs by supporting `shift-select-mode'
418 outside these special contexts, under control of this variable.
420 The default of this variable is nil, to avoid confusing behavior. Shifted
421 cursor keys will then execute Org commands in the following contexts:
422 - on a headline, changing TODO state (left/right) and priority (up/down)
423 - on a time stamp, changing the time
424 - in a plain list item, changing the bullet type
425 - in a property definition line, switching between allowed values
426 - in the BEGIN line of a clock table (changing the time block).
427 Outside these contexts, the commands will throw an error.
429 When this variable is t and the cursor is not in a special
430 context, Org-mode will support shift-selection for making and
431 enlarging regions. To make this more effective, the bullet
432 cycling will no longer happen anywhere in an item line, but only
433 if the cursor is exactly on the bullet.
435 If you set this variable to the symbol `always', then the keys
436 will not be special in headlines, property lines, and item lines,
437 to make shift selection work there as well. If this is what you
438 want, you can use the following alternative commands: `C-c C-t'
439 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
440 can be used to switch TODO sets, `C-c -' to cycle item bullet
441 types, and properties can be edited by hand or in column view.
443 However, when the cursor is on a timestamp, shift-cursor commands
444 will still edit the time stamp - this is just too good to give up.
446 XEmacs user should have this variable set to nil, because
447 `shift-select-mode' is in Emacs 23 or later only."
448 :group 'org
449 :type '(choice
450 (const :tag "Never" nil)
451 (const :tag "When outside special context" t)
452 (const :tag "Everywhere except timestamps" always)))
454 (defcustom org-loop-over-headlines-in-active-region nil
455 "Shall some commands act upon headlines in the active region?
457 When set to `t', some commands will be performed in all headlines
458 within the active region.
460 When set to `start-level', some commands will be performed in all
461 headlines within the active region, provided that these headlines
462 are of the same level than the first one.
464 When set to a string, those commands will be performed on the
465 matching headlines within the active region. Such string must be
466 a tags/property/todo match as it is used in the agenda tags view.
468 The list of commands is: `org-schedule', `org-deadline',
469 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
470 `org-archive-to-archive-sibling'. The archiving commands skip
471 already archived entries."
472 :type '(choice (const :tag "Don't loop" nil)
473 (const :tag "All headlines in active region" t)
474 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
475 (string :tag "Tags/Property/Todo matcher"))
476 :version "24.1"
477 :group 'org-todo
478 :group 'org-archive)
480 (defgroup org-startup nil
481 "Options concerning startup of Org-mode."
482 :tag "Org Startup"
483 :group 'org)
485 (defcustom org-startup-folded t
486 "Non-nil means entering Org-mode will switch to OVERVIEW.
487 This can also be configured on a per-file basis by adding one of
488 the following lines anywhere in the buffer:
490 #+STARTUP: fold (or `overview', this is equivalent)
491 #+STARTUP: nofold (or `showall', this is equivalent)
492 #+STARTUP: content
493 #+STARTUP: showeverything"
494 :group 'org-startup
495 :type '(choice
496 (const :tag "nofold: show all" nil)
497 (const :tag "fold: overview" t)
498 (const :tag "content: all headlines" content)
499 (const :tag "show everything, even drawers" showeverything)))
501 (defcustom org-startup-truncated t
502 "Non-nil means entering Org-mode will set `truncate-lines'.
503 This is useful since some lines containing links can be very long and
504 uninteresting. Also tables look terrible when wrapped."
505 :group 'org-startup
506 :type 'boolean)
508 (defcustom org-startup-indented nil
509 "Non-nil means turn on `org-indent-mode' on startup.
510 This can also be configured on a per-file basis by adding one of
511 the following lines anywhere in the buffer:
513 #+STARTUP: indent
514 #+STARTUP: noindent"
515 :group 'org-structure
516 :type '(choice
517 (const :tag "Not" nil)
518 (const :tag "Globally (slow on startup in large files)" t)))
520 (defcustom org-use-sub-superscripts t
521 "Non-nil means interpret \"_\" and \"^\" for export.
522 When this option is turned on, you can use TeX-like syntax for sub- and
523 superscripts. Several characters after \"_\" or \"^\" will be
524 considered as a single item - so grouping with {} is normally not
525 needed. For example, the following things will be parsed as single
526 sub- or superscripts.
528 10^24 or 10^tau several digits will be considered 1 item.
529 10^-12 or 10^-tau a leading sign with digits or a word
530 x^2-y^3 will be read as x^2 - y^3, because items are
531 terminated by almost any nonword/nondigit char.
532 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
534 Still, ambiguity is possible - so when in doubt use {} to enclose the
535 sub/superscript. If you set this variable to the symbol `{}',
536 the braces are *required* in order to trigger interpretations as
537 sub/superscript. This can be helpful in documents that need \"_\"
538 frequently in plain text.
540 Not all export backends support this, but HTML does.
542 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
543 :group 'org-startup
544 :group 'org-export-translation
545 :version "24.1"
546 :type '(choice
547 (const :tag "Always interpret" t)
548 (const :tag "Only with braces" {})
549 (const :tag "Never interpret" nil)))
551 (if (fboundp 'defvaralias)
552 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
555 (defcustom org-startup-with-beamer-mode nil
556 "Non-nil means turn on `org-beamer-mode' on startup.
557 This can also be configured on a per-file basis by adding one of
558 the following lines anywhere in the buffer:
560 #+STARTUP: beamer"
561 :group 'org-startup
562 :version "24.1"
563 :type 'boolean)
565 (defcustom org-startup-align-all-tables nil
566 "Non-nil means align all tables when visiting a file.
567 This is useful when the column width in tables is forced with <N> cookies
568 in table fields. Such tables will look correct only after the first re-align.
569 This can also be configured on a per-file basis by adding one of
570 the following lines anywhere in the buffer:
571 #+STARTUP: align
572 #+STARTUP: noalign"
573 :group 'org-startup
574 :type 'boolean)
576 (defcustom org-startup-with-inline-images nil
577 "Non-nil means show inline images when loading a new Org file.
578 This can also be configured on a per-file basis by adding one of
579 the following lines anywhere in the buffer:
580 #+STARTUP: inlineimages
581 #+STARTUP: noinlineimages"
582 :group 'org-startup
583 :version "24.1"
584 :type 'boolean)
586 (defcustom org-insert-mode-line-in-empty-file nil
587 "Non-nil means insert the first line setting Org-mode in empty files.
588 When the function `org-mode' is called interactively in an empty file, this
589 normally means that the file name does not automatically trigger Org-mode.
590 To ensure that the file will always be in Org-mode in the future, a
591 line enforcing Org-mode will be inserted into the buffer, if this option
592 has been set."
593 :group 'org-startup
594 :type 'boolean)
596 (defcustom org-replace-disputed-keys nil
597 "Non-nil means use alternative key bindings for some keys.
598 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
599 These keys are also used by other packages like shift-selection-mode'
600 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
601 If you want to use Org-mode together with one of these other modes,
602 or more generally if you would like to move some Org-mode commands to
603 other keys, set this variable and configure the keys with the variable
604 `org-disputed-keys'.
606 This option is only relevant at load-time of Org-mode, and must be set
607 *before* org.el is loaded. Changing it requires a restart of Emacs to
608 become effective."
609 :group 'org-startup
610 :type 'boolean)
612 (defcustom org-use-extra-keys nil
613 "Non-nil means use extra key sequence definitions for certain commands.
614 This happens automatically if you run XEmacs or if `window-system'
615 is nil. This variable lets you do the same manually. You must
616 set it before loading org.
618 Example: on Carbon Emacs 22 running graphically, with an external
619 keyboard on a Powerbook, the default way of setting M-left might
620 not work for either Alt or ESC. Setting this variable will make
621 it work for ESC."
622 :group 'org-startup
623 :type 'boolean)
625 (if (fboundp 'defvaralias)
626 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
628 (defcustom org-disputed-keys
629 '(([(shift up)] . [(meta p)])
630 ([(shift down)] . [(meta n)])
631 ([(shift left)] . [(meta -)])
632 ([(shift right)] . [(meta +)])
633 ([(control shift right)] . [(meta shift +)])
634 ([(control shift left)] . [(meta shift -)]))
635 "Keys for which Org-mode and other modes compete.
636 This is an alist, cars are the default keys, second element specifies
637 the alternative to use when `org-replace-disputed-keys' is t.
639 Keys can be specified in any syntax supported by `define-key'.
640 The value of this option takes effect only at Org-mode's startup,
641 therefore you'll have to restart Emacs to apply it after changing."
642 :group 'org-startup
643 :type 'alist)
645 (defun org-key (key)
646 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
647 Or return the original if not disputed.
648 Also apply the translations defined in `org-xemacs-key-equivalents'."
649 (when org-replace-disputed-keys
650 (let* ((nkey (key-description key))
651 (x (org-find-if (lambda (x)
652 (equal (key-description (car x)) nkey))
653 org-disputed-keys)))
654 (setq key (if x (cdr x) key))))
655 (when (featurep 'xemacs)
656 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
657 key)
659 (defun org-find-if (predicate seq)
660 (catch 'exit
661 (while seq
662 (if (funcall predicate (car seq))
663 (throw 'exit (car seq))
664 (pop seq)))))
666 (defun org-defkey (keymap key def)
667 "Define a key, possibly translated, as returned by `org-key'."
668 (define-key keymap (org-key key) def))
670 (defcustom org-ellipsis nil
671 "The ellipsis to use in the Org-mode outline.
672 When nil, just use the standard three dots. When a string, use that instead,
673 When a face, use the standard 3 dots, but with the specified face.
674 The change affects only Org-mode (which will then use its own display table).
675 Changing this requires executing `M-x org-mode' in a buffer to become
676 effective."
677 :group 'org-startup
678 :type '(choice (const :tag "Default" nil)
679 (face :tag "Face" :value org-warning)
680 (string :tag "String" :value "...#")))
682 (defvar org-display-table nil
683 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
685 (defgroup org-keywords nil
686 "Keywords in Org-mode."
687 :tag "Org Keywords"
688 :group 'org)
690 (defcustom org-deadline-string "DEADLINE:"
691 "String to mark deadline entries.
692 A deadline is this string, followed by a time stamp. Should be a word,
693 terminated by a colon. You can insert a schedule keyword and
694 a timestamp with \\[org-deadline].
695 Changes become only effective after restarting Emacs."
696 :group 'org-keywords
697 :type 'string)
699 (defcustom org-scheduled-string "SCHEDULED:"
700 "String to mark scheduled TODO entries.
701 A schedule is this string, followed by a time stamp. Should be a word,
702 terminated by a colon. You can insert a schedule keyword and
703 a timestamp with \\[org-schedule].
704 Changes become only effective after restarting Emacs."
705 :group 'org-keywords
706 :type 'string)
708 (defcustom org-closed-string "CLOSED:"
709 "String used as the prefix for timestamps logging closing a TODO entry."
710 :group 'org-keywords
711 :type 'string)
713 (defcustom org-clock-string "CLOCK:"
714 "String used as prefix for timestamps clocking work hours on an item."
715 :group 'org-keywords
716 :type 'string)
718 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
719 org-scheduled-string "\\|"
720 org-deadline-string "\\|"
721 org-closed-string "\\|"
722 org-clock-string "\\)")
723 "Matches a line with planning or clock info.")
725 (defcustom org-comment-string "COMMENT"
726 "Entries starting with this keyword will never be exported.
727 An entry can be toggled between COMMENT and normal with
728 \\[org-toggle-comment].
729 Changes become only effective after restarting Emacs."
730 :group 'org-keywords
731 :type 'string)
733 (defcustom org-quote-string "QUOTE"
734 "Entries starting with this keyword will be exported in fixed-width font.
735 Quoting applies only to the text in the entry following the headline, and does
736 not extend beyond the next headline, even if that is lower level.
737 An entry can be toggled between QUOTE and normal with
738 \\[org-toggle-fixed-width-section]."
739 :group 'org-keywords
740 :type 'string)
742 (defconst org-repeat-re
743 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
744 "Regular expression for specifying repeated events.
745 After a match, group 1 contains the repeat expression.")
747 (defgroup org-structure nil
748 "Options concerning the general structure of Org-mode files."
749 :tag "Org Structure"
750 :group 'org)
752 (defgroup org-reveal-location nil
753 "Options about how to make context of a location visible."
754 :tag "Org Reveal Location"
755 :group 'org-structure)
757 (defconst org-context-choice
758 '(choice
759 (const :tag "Always" t)
760 (const :tag "Never" nil)
761 (repeat :greedy t :tag "Individual contexts"
762 (cons
763 (choice :tag "Context"
764 (const agenda)
765 (const org-goto)
766 (const occur-tree)
767 (const tags-tree)
768 (const link-search)
769 (const mark-goto)
770 (const bookmark-jump)
771 (const isearch)
772 (const default))
773 (boolean))))
774 "Contexts for the reveal options.")
776 (defcustom org-show-hierarchy-above '((default . t))
777 "Non-nil means show full hierarchy when revealing a location.
778 Org-mode often shows locations in an org-mode file which might have
779 been invisible before. When this is set, the hierarchy of headings
780 above the exposed location is shown.
781 Turning this off for example for sparse trees makes them very compact.
782 Instead of t, this can also be an alist specifying this option for different
783 contexts. Valid contexts are
784 agenda when exposing an entry from the agenda
785 org-goto when using the command `org-goto' on key C-c C-j
786 occur-tree when using the command `org-occur' on key C-c /
787 tags-tree when constructing a sparse tree based on tags matches
788 link-search when exposing search matches associated with a link
789 mark-goto when exposing the jump goal of a mark
790 bookmark-jump when exposing a bookmark location
791 isearch when exiting from an incremental search
792 default default for all contexts not set explicitly"
793 :group 'org-reveal-location
794 :type org-context-choice)
796 (defcustom org-show-following-heading '((default . nil))
797 "Non-nil means show following heading when revealing a location.
798 Org-mode often shows locations in an org-mode file which might have
799 been invisible before. When this is set, the heading following the
800 match is shown.
801 Turning this off for example for sparse trees makes them very compact,
802 but makes it harder to edit the location of the match. In such a case,
803 use the command \\[org-reveal] to show more context.
804 Instead of t, this can also be an alist specifying this option for different
805 contexts. See `org-show-hierarchy-above' for valid contexts."
806 :group 'org-reveal-location
807 :type org-context-choice)
809 (defcustom org-show-siblings '((default . nil) (isearch t))
810 "Non-nil means show all sibling heading when revealing a location.
811 Org-mode often shows locations in an org-mode file which might have
812 been invisible before. When this is set, the sibling of the current entry
813 heading are all made visible. If `org-show-hierarchy-above' is t,
814 the same happens on each level of the hierarchy above the current entry.
816 By default this is on for the isearch context, off for all other contexts.
817 Turning this off for example for sparse trees makes them very compact,
818 but makes it harder to edit the location of the match. In such a case,
819 use the command \\[org-reveal] to show more context.
820 Instead of t, this can also be an alist specifying this option for different
821 contexts. See `org-show-hierarchy-above' for valid contexts."
822 :group 'org-reveal-location
823 :type org-context-choice)
825 (defcustom org-show-entry-below '((default . nil))
826 "Non-nil means show the entry below a headline when revealing a location.
827 Org-mode often shows locations in an org-mode file which might have
828 been invisible before. When this is set, the text below the headline that is
829 exposed is also shown.
831 By default this is off for all contexts.
832 Instead of t, this can also be an alist specifying this option for different
833 contexts. See `org-show-hierarchy-above' for valid contexts."
834 :group 'org-reveal-location
835 :type org-context-choice)
837 (defcustom org-indirect-buffer-display 'other-window
838 "How should indirect tree buffers be displayed?
839 This applies to indirect buffers created with the commands
840 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
841 Valid values are:
842 current-window Display in the current window
843 other-window Just display in another window.
844 dedicated-frame Create one new frame, and re-use it each time.
845 new-frame Make a new frame each time. Note that in this case
846 previously-made indirect buffers are kept, and you need to
847 kill these buffers yourself."
848 :group 'org-structure
849 :group 'org-agenda-windows
850 :type '(choice
851 (const :tag "In current window" current-window)
852 (const :tag "In current frame, other window" other-window)
853 (const :tag "Each time a new frame" new-frame)
854 (const :tag "One dedicated frame" dedicated-frame)))
856 (defcustom org-use-speed-commands nil
857 "Non-nil means activate single letter commands at beginning of a headline.
858 This may also be a function to test for appropriate locations where speed
859 commands should be active."
860 :group 'org-structure
861 :type '(choice
862 (const :tag "Never" nil)
863 (const :tag "At beginning of headline stars" t)
864 (function)))
866 (defcustom org-speed-commands-user nil
867 "Alist of additional speed commands.
868 This list will be checked before `org-speed-commands-default'
869 when the variable `org-use-speed-commands' is non-nil
870 and when the cursor is at the beginning of a headline.
871 The car if each entry is a string with a single letter, which must
872 be assigned to `self-insert-command' in the global map.
873 The cdr is either a command to be called interactively, a function
874 to be called, or a form to be evaluated.
875 An entry that is just a list with a single string will be interpreted
876 as a descriptive headline that will be added when listing the speed
877 commands in the Help buffer using the `?' speed command."
878 :group 'org-structure
879 :type '(repeat :value ("k" . ignore)
880 (choice :value ("k" . ignore)
881 (list :tag "Descriptive Headline" (string :tag "Headline"))
882 (cons :tag "Letter and Command"
883 (string :tag "Command letter")
884 (choice
885 (function)
886 (sexp))))))
888 (defgroup org-cycle nil
889 "Options concerning visibility cycling in Org-mode."
890 :tag "Org Cycle"
891 :group 'org-structure)
893 (defcustom org-cycle-skip-children-state-if-no-children t
894 "Non-nil means skip CHILDREN state in entries that don't have any."
895 :group 'org-cycle
896 :type 'boolean)
898 (defcustom org-cycle-max-level nil
899 "Maximum level which should still be subject to visibility cycling.
900 Levels higher than this will, for cycling, be treated as text, not a headline.
901 When `org-odd-levels-only' is set, a value of N in this variable actually
902 means 2N-1 stars as the limiting headline.
903 When nil, cycle all levels.
904 Note that the limiting level of cycling is also influenced by
905 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
906 `org-inlinetask-min-level' is, cycling will be limited to levels one less
907 than its value."
908 :group 'org-cycle
909 :type '(choice
910 (const :tag "No limit" nil)
911 (integer :tag "Maximum level")))
913 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
914 "Names of drawers. Drawers are not opened by cycling on the headline above.
915 Drawers only open with a TAB on the drawer line itself. A drawer looks like
916 this:
917 :DRAWERNAME:
918 .....
919 :END:
920 The drawer \"PROPERTIES\" is special for capturing properties through
921 the property API.
923 Drawers can be defined on the per-file basis with a line like:
925 #+DRAWERS: HIDDEN STATE PROPERTIES"
926 :group 'org-structure
927 :group 'org-cycle
928 :type '(repeat (string :tag "Drawer Name")))
930 (defcustom org-hide-block-startup nil
931 "Non-nil means entering Org-mode will fold all blocks.
932 This can also be set in on a per-file basis with
934 #+STARTUP: hideblocks
935 #+STARTUP: showblocks"
936 :group 'org-startup
937 :group 'org-cycle
938 :type 'boolean)
940 (defcustom org-cycle-global-at-bob nil
941 "Cycle globally if cursor is at beginning of buffer and not at a headline.
942 This makes it possible to do global cycling without having to use S-TAB or
943 \\[universal-argument] TAB. For this special case to work, the first line
944 of the buffer must not be a headline -- it may be empty or some other text.
945 When used in this way, `org-cycle-hook' is disabled temporarily to make
946 sure the cursor stays at the beginning of the buffer. When this option is
947 nil, don't do anything special at the beginning of the buffer."
948 :group 'org-cycle
949 :type 'boolean)
951 (defcustom org-cycle-level-after-item/entry-creation t
952 "Non-nil means cycle entry level or item indentation in new empty entries.
954 When the cursor is at the end of an empty headline, i.e with only stars
955 and maybe a TODO keyword, TAB will then switch the entry to become a child,
956 and then all possible ancestor states, before returning to the original state.
957 This makes data entry extremely fast: M-RET to create a new headline,
958 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
960 When the cursor is at the end of an empty plain list item, one TAB will
961 make it a subitem, two or more tabs will back up to make this an item
962 higher up in the item hierarchy."
963 :group 'org-cycle
964 :type 'boolean)
966 (defcustom org-cycle-emulate-tab t
967 "Where should `org-cycle' emulate TAB.
968 nil Never
969 white Only in completely white lines
970 whitestart Only at the beginning of lines, before the first non-white char
971 t Everywhere except in headlines
972 exc-hl-bol Everywhere except at the start of a headline
973 If TAB is used in a place where it does not emulate TAB, the current subtree
974 visibility is cycled."
975 :group 'org-cycle
976 :type '(choice (const :tag "Never" nil)
977 (const :tag "Only in completely white lines" white)
978 (const :tag "Before first char in a line" whitestart)
979 (const :tag "Everywhere except in headlines" t)
980 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
983 (defcustom org-cycle-separator-lines 2
984 "Number of empty lines needed to keep an empty line between collapsed trees.
985 If you leave an empty line between the end of a subtree and the following
986 headline, this empty line is hidden when the subtree is folded.
987 Org-mode will leave (exactly) one empty line visible if the number of
988 empty lines is equal or larger to the number given in this variable.
989 So the default 2 means at least 2 empty lines after the end of a subtree
990 are needed to produce free space between a collapsed subtree and the
991 following headline.
993 If the number is negative, and the number of empty lines is at least -N,
994 all empty lines are shown.
996 Special case: when 0, never leave empty lines in collapsed view."
997 :group 'org-cycle
998 :type 'integer)
999 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1001 (defcustom org-pre-cycle-hook nil
1002 "Hook that is run before visibility cycling is happening.
1003 The function(s) in this hook must accept a single argument which indicates
1004 the new state that will be set right after running this hook. The
1005 argument is a symbol. Before a global state change, it can have the values
1006 `overview', `content', or `all'. Before a local state change, it can have
1007 the values `folded', `children', or `subtree'."
1008 :group 'org-cycle
1009 :type 'hook)
1011 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1012 org-cycle-hide-drawers
1013 org-cycle-hide-inline-tasks
1014 org-cycle-show-empty-lines
1015 org-optimize-window-after-visibility-change)
1016 "Hook that is run after `org-cycle' has changed the buffer visibility.
1017 The function(s) in this hook must accept a single argument which indicates
1018 the new state that was set by the most recent `org-cycle' command. The
1019 argument is a symbol. After a global state change, it can have the values
1020 `overview', `contents', or `all'. After a local state change, it can have
1021 the values `folded', `children', or `subtree'."
1022 :group 'org-cycle
1023 :type 'hook)
1025 (defgroup org-edit-structure nil
1026 "Options concerning structure editing in Org-mode."
1027 :tag "Org Edit Structure"
1028 :group 'org-structure)
1030 (defcustom org-odd-levels-only nil
1031 "Non-nil means skip even levels and only use odd levels for the outline.
1032 This has the effect that two stars are being added/taken away in
1033 promotion/demotion commands. It also influences how levels are
1034 handled by the exporters.
1035 Changing it requires restart of `font-lock-mode' to become effective
1036 for fontification also in regions already fontified.
1037 You may also set this on a per-file basis by adding one of the following
1038 lines to the buffer:
1040 #+STARTUP: odd
1041 #+STARTUP: oddeven"
1042 :group 'org-edit-structure
1043 :group 'org-appearance
1044 :type 'boolean)
1046 (defcustom org-adapt-indentation t
1047 "Non-nil means adapt indentation to outline node level.
1049 When this variable is set, Org assumes that you write outlines by
1050 indenting text in each node to align with the headline (after the stars).
1051 The following issues are influenced by this variable:
1053 - When this is set and the *entire* text in an entry is indented, the
1054 indentation is increased by one space in a demotion command, and
1055 decreased by one in a promotion command. If any line in the entry
1056 body starts with text at column 0, indentation is not changed at all.
1058 - Property drawers and planning information is inserted indented when
1059 this variable s set. When nil, they will not be indented.
1061 - TAB indents a line relative to context. The lines below a headline
1062 will be indented when this variable is set.
1064 Note that this is all about true indentation, by adding and removing
1065 space characters. See also `org-indent.el' which does level-dependent
1066 indentation in a virtual way, i.e. at display time in Emacs."
1067 :group 'org-edit-structure
1068 :type 'boolean)
1070 (defcustom org-special-ctrl-a/e nil
1071 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1073 When t, `C-a' will bring back the cursor to the beginning of the
1074 headline text, i.e. after the stars and after a possible TODO
1075 keyword. In an item, this will be the position after bullet and
1076 check-box, if any. When the cursor is already at that position,
1077 another `C-a' will bring it to the beginning of the line.
1079 `C-e' will jump to the end of the headline, ignoring the presence
1080 of tags in the headline. A second `C-e' will then jump to the
1081 true end of the line, after any tags. This also means that, when
1082 this variable is non-nil, `C-e' also will never jump beyond the
1083 end of the heading of a folded section, i.e. not after the
1084 ellipses.
1086 When set to the symbol `reversed', the first `C-a' or `C-e' works
1087 normally, going to the true line boundary first. Only a directly
1088 following, identical keypress will bring the cursor to the
1089 special positions.
1091 This may also be a cons cell where the behavior for `C-a' and
1092 `C-e' is set separately."
1093 :group 'org-edit-structure
1094 :type '(choice
1095 (const :tag "off" nil)
1096 (const :tag "on: after stars/bullet and before tags first" t)
1097 (const :tag "reversed: true line boundary first" reversed)
1098 (cons :tag "Set C-a and C-e separately"
1099 (choice :tag "Special C-a"
1100 (const :tag "off" nil)
1101 (const :tag "on: after stars/bullet first" t)
1102 (const :tag "reversed: before stars/bullet first" reversed))
1103 (choice :tag "Special C-e"
1104 (const :tag "off" nil)
1105 (const :tag "on: before tags first" t)
1106 (const :tag "reversed: after tags first" reversed)))))
1107 (if (fboundp 'defvaralias)
1108 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1110 (defcustom org-special-ctrl-k nil
1111 "Non-nil means `C-k' will behave specially in headlines.
1112 When nil, `C-k' will call the default `kill-line' command.
1113 When t, the following will happen while the cursor is in the headline:
1115 - When the cursor is at the beginning of a headline, kill the entire
1116 line and possible the folded subtree below the line.
1117 - When in the middle of the headline text, kill the headline up to the tags.
1118 - When after the headline text, kill the tags."
1119 :group 'org-edit-structure
1120 :type 'boolean)
1122 (defcustom org-ctrl-k-protect-subtree nil
1123 "Non-nil means, do not delete a hidden subtree with C-k.
1124 When set to the symbol `error', simply throw an error when C-k is
1125 used to kill (part-of) a headline that has hidden text behind it.
1126 Any other non-nil value will result in a query to the user, if it is
1127 OK to kill that hidden subtree. When nil, kill without remorse."
1128 :group 'org-edit-structure
1129 :version "24.1"
1130 :type '(choice
1131 (const :tag "Do not protect hidden subtrees" nil)
1132 (const :tag "Protect hidden subtrees with a security query" t)
1133 (const :tag "Never kill a hidden subtree with C-k" error)))
1135 (defcustom org-catch-invisible-edits nil
1136 "Check if in invisible region before inserting or deleting a character.
1137 Valid values are:
1139 nil Do not check, so just do invisible edits.
1140 error Throw an error and do nothing.
1141 show Make point visible, and do the requested edit.
1142 show-and-error Make point visible, then throw an error and abort the edit.
1143 smart Make point visible, and do insertion/deletion if it is
1144 adjacent to visible text and the change feels predictable.
1145 Never delete a previously invisible character or add in the
1146 middle or right after an invisible region. Basically, this
1147 allows insertion and backward-delete right before ellipses.
1148 FIXME: maybe in this case we should not even show?"
1149 :group 'org-edit-structure
1150 :version "24.1"
1151 :type '(choice
1152 (const :tag "Do not check" nil)
1153 (const :tag "Throw error when trying to edit" error)
1154 (const :tag "Unhide, but do not do the edit" show-and-error)
1155 (const :tag "Show invisible part and do the edit" show)
1156 (const :tag "Be smart and do the right thing" smart)))
1158 (defcustom org-yank-folded-subtrees t
1159 "Non-nil means when yanking subtrees, fold them.
1160 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1161 it starts with a heading and all other headings in it are either children
1162 or siblings, then fold all the subtrees. However, do this only if no
1163 text after the yank would be swallowed into a folded tree by this action."
1164 :group 'org-edit-structure
1165 :type 'boolean)
1167 (defcustom org-yank-adjusted-subtrees nil
1168 "Non-nil means when yanking subtrees, adjust the level.
1169 With this setting, `org-paste-subtree' is used to insert the subtree, see
1170 this function for details."
1171 :group 'org-edit-structure
1172 :type 'boolean)
1174 (defcustom org-M-RET-may-split-line '((default . t))
1175 "Non-nil means M-RET will split the line at the cursor position.
1176 When nil, it will go to the end of the line before making a
1177 new line.
1178 You may also set this option in a different way for different
1179 contexts. Valid contexts are:
1181 headline when creating a new headline
1182 item when creating a new item
1183 table in a table field
1184 default the value to be used for all contexts not explicitly
1185 customized"
1186 :group 'org-structure
1187 :group 'org-table
1188 :type '(choice
1189 (const :tag "Always" t)
1190 (const :tag "Never" nil)
1191 (repeat :greedy t :tag "Individual contexts"
1192 (cons
1193 (choice :tag "Context"
1194 (const headline)
1195 (const item)
1196 (const table)
1197 (const default))
1198 (boolean)))))
1201 (defcustom org-insert-heading-respect-content nil
1202 "Non-nil means insert new headings after the current subtree.
1203 When nil, the new heading is created directly after the current line.
1204 The commands \\[org-insert-heading-respect-content] and
1205 \\[org-insert-todo-heading-respect-content] turn this variable on
1206 for the duration of the command."
1207 :group 'org-structure
1208 :type 'boolean)
1210 (defcustom org-blank-before-new-entry '((heading . auto)
1211 (plain-list-item . auto))
1212 "Should `org-insert-heading' leave a blank line before new heading/item?
1213 The value is an alist, with `heading' and `plain-list-item' as CAR,
1214 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1215 which case Org will look at the surrounding headings/items and try to
1216 make an intelligent decision whether to insert a blank line or not.
1218 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1219 set, the setting here is ignored and no empty line is inserted, to avoid
1220 breaking the list structure."
1221 :group 'org-edit-structure
1222 :type '(list
1223 (cons (const heading)
1224 (choice (const :tag "Never" nil)
1225 (const :tag "Always" t)
1226 (const :tag "Auto" auto)))
1227 (cons (const plain-list-item)
1228 (choice (const :tag "Never" nil)
1229 (const :tag "Always" t)
1230 (const :tag "Auto" auto)))))
1232 (defcustom org-insert-heading-hook nil
1233 "Hook being run after inserting a new heading."
1234 :group 'org-edit-structure
1235 :type 'hook)
1237 (defcustom org-enable-fixed-width-editor t
1238 "Non-nil means lines starting with \":\" are treated as fixed-width.
1239 This currently only means they are never auto-wrapped.
1240 When nil, such lines will be treated like ordinary lines.
1241 See also the QUOTE keyword."
1242 :group 'org-edit-structure
1243 :type 'boolean)
1245 (defcustom org-goto-auto-isearch t
1246 "Non-nil means typing characters in `org-goto' starts incremental search.
1247 When nil, you can use these keybindings to navigate the buffer:
1249 q Quit the org-goto interface
1250 n Go to the next visible heading
1251 p Go to the previous visible heading
1252 f Go one heading forward on same level
1253 b Go one heading backward on same level
1254 u Go one heading up"
1255 :group 'org-edit-structure
1256 :type 'boolean)
1258 (defgroup org-sparse-trees nil
1259 "Options concerning sparse trees in Org-mode."
1260 :tag "Org Sparse Trees"
1261 :group 'org-structure)
1263 (defcustom org-highlight-sparse-tree-matches t
1264 "Non-nil means highlight all matches that define a sparse tree.
1265 The highlights will automatically disappear the next time the buffer is
1266 changed by an edit command."
1267 :group 'org-sparse-trees
1268 :type 'boolean)
1270 (defcustom org-remove-highlights-with-change t
1271 "Non-nil means any change to the buffer will remove temporary highlights.
1272 Such highlights are created by `org-occur' and `org-clock-display'.
1273 When nil, `C-c C-c needs to be used to get rid of the highlights.
1274 The highlights created by `org-preview-latex-fragment' always need
1275 `C-c C-c' to be removed."
1276 :group 'org-sparse-trees
1277 :group 'org-time
1278 :type 'boolean)
1281 (defcustom org-occur-hook '(org-first-headline-recenter)
1282 "Hook that is run after `org-occur' has constructed a sparse tree.
1283 This can be used to recenter the window to show as much of the structure
1284 as possible."
1285 :group 'org-sparse-trees
1286 :type 'hook)
1288 (defgroup org-imenu-and-speedbar nil
1289 "Options concerning imenu and speedbar in Org-mode."
1290 :tag "Org Imenu and Speedbar"
1291 :group 'org-structure)
1293 (defcustom org-imenu-depth 2
1294 "The maximum level for Imenu access to Org-mode headlines.
1295 This also applied for speedbar access."
1296 :group 'org-imenu-and-speedbar
1297 :type 'integer)
1299 (defgroup org-table nil
1300 "Options concerning tables in Org-mode."
1301 :tag "Org Table"
1302 :group 'org)
1304 (defcustom org-enable-table-editor 'optimized
1305 "Non-nil means lines starting with \"|\" are handled by the table editor.
1306 When nil, such lines will be treated like ordinary lines.
1308 When equal to the symbol `optimized', the table editor will be optimized to
1309 do the following:
1310 - Automatic overwrite mode in front of whitespace in table fields.
1311 This makes the structure of the table stay in tact as long as the edited
1312 field does not exceed the column width.
1313 - Minimize the number of realigns. Normally, the table is aligned each time
1314 TAB or RET are pressed to move to another field. With optimization this
1315 happens only if changes to a field might have changed the column width.
1316 Optimization requires replacing the functions `self-insert-command',
1317 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1318 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1319 very good at guessing when a re-align will be necessary, but you can always
1320 force one with \\[org-ctrl-c-ctrl-c].
1322 If you would like to use the optimized version in Org-mode, but the
1323 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1325 This variable can be used to turn on and off the table editor during a session,
1326 but in order to toggle optimization, a restart is required.
1328 See also the variable `org-table-auto-blank-field'."
1329 :group 'org-table
1330 :type '(choice
1331 (const :tag "off" nil)
1332 (const :tag "on" t)
1333 (const :tag "on, optimized" optimized)))
1335 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1336 (version<= emacs-version "24.1"))
1337 "Non-nil means cluster self-insert commands for undo when possible.
1338 If this is set, then, like in the Emacs command loop, 20 consecutive
1339 characters will be undone together.
1340 This is configurable, because there is some impact on typing performance."
1341 :group 'org-table
1342 :type 'boolean)
1344 (defcustom org-table-tab-recognizes-table.el t
1345 "Non-nil means TAB will automatically notice a table.el table.
1346 When it sees such a table, it moves point into it and - if necessary -
1347 calls `table-recognize-table'."
1348 :group 'org-table-editing
1349 :type 'boolean)
1351 (defgroup org-link nil
1352 "Options concerning links in Org-mode."
1353 :tag "Org Link"
1354 :group 'org)
1356 (defvar org-link-abbrev-alist-local nil
1357 "Buffer-local version of `org-link-abbrev-alist', which see.
1358 The value of this is taken from the #+LINK lines.")
1359 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1361 (defcustom org-link-abbrev-alist nil
1362 "Alist of link abbreviations.
1363 The car of each element is a string, to be replaced at the start of a link.
1364 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1365 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1367 [[linkkey:tag][description]]
1369 The 'linkkey' must be a word word, starting with a letter, followed
1370 by letters, numbers, '-' or '_'.
1372 If REPLACE is a string, the tag will simply be appended to create the link.
1373 If the string contains \"%s\", the tag will be inserted there. If the string
1374 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1375 at that point (see the function `url-hexify-string'). If the string contains
1376 the specifier \"%(my-function)\", then the custom function `my-function' will
1377 be invoked: this function takes the tag as its only argument and must return
1378 a string.
1380 REPLACE may also be a function that will be called with the tag as the
1381 only argument to create the link, which should be returned as a string.
1383 See the manual for examples."
1384 :group 'org-link
1385 :type '(repeat
1386 (cons
1387 (string :tag "Protocol")
1388 (choice
1389 (string :tag "Format")
1390 (function)))))
1392 (defcustom org-descriptive-links t
1393 "Non-nil means Org will display descriptive links.
1394 E.g. [[http://orgmode.org][Org website]] will be displayed as
1395 \"Org Website\", hiding the link itself and just displaying its
1396 description. When set to `nil', Org will display the full links
1397 literally.
1399 You can interactively set the value of this variable by calling
1400 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1401 :group 'org-link
1402 :type 'boolean)
1404 (defcustom org-link-file-path-type 'adaptive
1405 "How the path name in file links should be stored.
1406 Valid values are:
1408 relative Relative to the current directory, i.e. the directory of the file
1409 into which the link is being inserted.
1410 absolute Absolute path, if possible with ~ for home directory.
1411 noabbrev Absolute path, no abbreviation of home directory.
1412 adaptive Use relative path for files in the current directory and sub-
1413 directories of it. For other files, use an absolute path."
1414 :group 'org-link
1415 :type '(choice
1416 (const relative)
1417 (const absolute)
1418 (const noabbrev)
1419 (const adaptive)))
1421 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1422 "Types of links that should be activated in Org-mode files.
1423 This is a list of symbols, each leading to the activation of a certain link
1424 type. In principle, it does not hurt to turn on most link types - there may
1425 be a small gain when turning off unused link types. The types are:
1427 bracket The recommended [[link][description]] or [[link]] links with hiding.
1428 angle Links in angular brackets that may contain whitespace like
1429 <bbdb:Carsten Dominik>.
1430 plain Plain links in normal text, no whitespace, like http://google.com.
1431 radio Text that is matched by a radio target, see manual for details.
1432 tag Tag settings in a headline (link to tag search).
1433 date Time stamps (link to calendar).
1434 footnote Footnote labels.
1436 Changing this variable requires a restart of Emacs to become effective."
1437 :group 'org-link
1438 :type '(set :greedy t
1439 (const :tag "Double bracket links" bracket)
1440 (const :tag "Angular bracket links" angle)
1441 (const :tag "Plain text links" plain)
1442 (const :tag "Radio target matches" radio)
1443 (const :tag "Tags" tag)
1444 (const :tag "Timestamps" date)
1445 (const :tag "Footnotes" footnote)))
1447 (defcustom org-make-link-description-function nil
1448 "Function to use for generating link descriptions from links.
1449 When nil, the link location will be used. This function must take
1450 two parameters: the first one is the link, the second one is the
1451 description generated by `org-insert-link'. The function should
1452 return the description to use."
1453 :group 'org-link
1454 :type 'function)
1456 (defgroup org-link-store nil
1457 "Options concerning storing links in Org-mode."
1458 :tag "Org Store Link"
1459 :group 'org-link)
1461 (defcustom org-url-hexify-p t
1462 "When non-nil, hexify URL when creating a link."
1463 :type 'boolean
1464 :version "24.3"
1465 :group 'org-link-store)
1467 (defcustom org-email-link-description-format "Email %c: %.30s"
1468 "Format of the description part of a link to an email or usenet message.
1469 The following %-escapes will be replaced by corresponding information:
1471 %F full \"From\" field
1472 %f name, taken from \"From\" field, address if no name
1473 %T full \"To\" field
1474 %t first name in \"To\" field, address if no name
1475 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1476 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1477 %s subject
1478 %d date
1479 %m message-id.
1481 You may use normal field width specification between the % and the letter.
1482 This is for example useful to limit the length of the subject.
1484 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1485 :group 'org-link-store
1486 :type 'string)
1488 (defcustom org-from-is-user-regexp
1489 (let (r1 r2)
1490 (when (and user-mail-address (not (string= user-mail-address "")))
1491 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1492 (when (and user-full-name (not (string= user-full-name "")))
1493 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1494 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1495 "Regexp matched against the \"From:\" header of an email or usenet message.
1496 It should match if the message is from the user him/herself."
1497 :group 'org-link-store
1498 :type 'regexp)
1500 (defcustom org-context-in-file-links t
1501 "Non-nil means file links from `org-store-link' contain context.
1502 A search string will be added to the file name with :: as separator and
1503 used to find the context when the link is activated by the command
1504 `org-open-at-point'. When this option is t, the entire active region
1505 will be placed in the search string of the file link. If set to a
1506 positive integer, only the first n lines of context will be stored.
1508 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1509 negates this setting for the duration of the command."
1510 :group 'org-link-store
1511 :type '(choice boolean integer))
1513 (defcustom org-keep-stored-link-after-insertion nil
1514 "Non-nil means keep link in list for entire session.
1516 The command `org-store-link' adds a link pointing to the current
1517 location to an internal list. These links accumulate during a session.
1518 The command `org-insert-link' can be used to insert links into any
1519 Org-mode file (offering completion for all stored links). When this
1520 option is nil, every link which has been inserted once using \\[org-insert-link]
1521 will be removed from the list, to make completing the unused links
1522 more efficient."
1523 :group 'org-link-store
1524 :type 'boolean)
1526 (defgroup org-link-follow nil
1527 "Options concerning following links in Org-mode."
1528 :tag "Org Follow Link"
1529 :group 'org-link)
1531 (defcustom org-link-translation-function nil
1532 "Function to translate links with different syntax to Org syntax.
1533 This can be used to translate links created for example by the Planner
1534 or emacs-wiki packages to Org syntax.
1535 The function must accept two parameters, a TYPE containing the link
1536 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1537 which is everything after the link protocol. It should return a cons
1538 with possibly modified values of type and path.
1539 Org contains a function for this, so if you set this variable to
1540 `org-translate-link-from-planner', you should be able follow many
1541 links created by planner."
1542 :group 'org-link-follow
1543 :type 'function)
1545 (defcustom org-follow-link-hook nil
1546 "Hook that is run after a link has been followed."
1547 :group 'org-link-follow
1548 :type 'hook)
1550 (defcustom org-tab-follows-link nil
1551 "Non-nil means on links TAB will follow the link.
1552 Needs to be set before org.el is loaded.
1553 This really should not be used, it does not make sense, and the
1554 implementation is bad."
1555 :group 'org-link-follow
1556 :type 'boolean)
1558 (defcustom org-return-follows-link nil
1559 "Non-nil means on links RET will follow the link."
1560 :group 'org-link-follow
1561 :type 'boolean)
1563 (defcustom org-mouse-1-follows-link
1564 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1565 "Non-nil means mouse-1 on a link will follow the link.
1566 A longer mouse click will still set point. Does not work on XEmacs.
1567 Needs to be set before org.el is loaded."
1568 :group 'org-link-follow
1569 :type 'boolean)
1571 (defcustom org-mark-ring-length 4
1572 "Number of different positions to be recorded in the ring.
1573 Changing this requires a restart of Emacs to work correctly."
1574 :group 'org-link-follow
1575 :type 'integer)
1577 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1578 "Non-nil means internal links in Org files must exactly match a headline.
1579 When nil, the link search tries to match a phrase with all words
1580 in the search text."
1581 :group 'org-link-follow
1582 :version "24.1"
1583 :type '(choice
1584 (const :tag "Use fuzzy text search" nil)
1585 (const :tag "Match only exact headline" t)
1586 (const :tag "Match exact headline or query to create it"
1587 query-to-create)))
1589 (defcustom org-link-frame-setup
1590 '((vm . vm-visit-folder-other-frame)
1591 (vm-imap . vm-visit-imap-folder-other-frame)
1592 (gnus . org-gnus-no-new-news)
1593 (file . find-file-other-window)
1594 (wl . wl-other-frame))
1595 "Setup the frame configuration for following links.
1596 When following a link with Emacs, it may often be useful to display
1597 this link in another window or frame. This variable can be used to
1598 set this up for the different types of links.
1599 For VM, use any of
1600 `vm-visit-folder'
1601 `vm-visit-folder-other-window'
1602 `vm-visit-folder-other-frame'
1603 For Gnus, use any of
1604 `gnus'
1605 `gnus-other-frame'
1606 `org-gnus-no-new-news'
1607 For FILE, use any of
1608 `find-file'
1609 `find-file-other-window'
1610 `find-file-other-frame'
1611 For Wanderlust use any of
1612 `wl'
1613 `wl-other-frame'
1614 For the calendar, use the variable `calendar-setup'.
1615 For BBDB, it is currently only possible to display the matches in
1616 another window."
1617 :group 'org-link-follow
1618 :type '(list
1619 (cons (const vm)
1620 (choice
1621 (const vm-visit-folder)
1622 (const vm-visit-folder-other-window)
1623 (const vm-visit-folder-other-frame)))
1624 (cons (const gnus)
1625 (choice
1626 (const gnus)
1627 (const gnus-other-frame)
1628 (const org-gnus-no-new-news)))
1629 (cons (const file)
1630 (choice
1631 (const find-file)
1632 (const find-file-other-window)
1633 (const find-file-other-frame)))
1634 (cons (const wl)
1635 (choice
1636 (const wl)
1637 (const wl-other-frame)))))
1639 (defcustom org-display-internal-link-with-indirect-buffer nil
1640 "Non-nil means use indirect buffer to display infile links.
1641 Activating internal links (from one location in a file to another location
1642 in the same file) normally just jumps to the location. When the link is
1643 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1644 is displayed in
1645 another window. When this option is set, the other window actually displays
1646 an indirect buffer clone of the current buffer, to avoid any visibility
1647 changes to the current buffer."
1648 :group 'org-link-follow
1649 :type 'boolean)
1651 (defcustom org-open-non-existing-files nil
1652 "Non-nil means `org-open-file' will open non-existing files.
1653 When nil, an error will be generated.
1654 This variable applies only to external applications because they
1655 might choke on non-existing files. If the link is to a file that
1656 will be opened in Emacs, the variable is ignored."
1657 :group 'org-link-follow
1658 :type 'boolean)
1660 (defcustom org-open-directory-means-index-dot-org nil
1661 "Non-nil means a link to a directory really means to index.org.
1662 When nil, following a directory link will run dired or open a finder/explorer
1663 window on that directory."
1664 :group 'org-link-follow
1665 :type 'boolean)
1667 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1668 "Function and arguments to call for following mailto links.
1669 This is a list with the first element being a Lisp function, and the
1670 remaining elements being arguments to the function. In string arguments,
1671 %a will be replaced by the address, and %s will be replaced by the subject
1672 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1673 :group 'org-link-follow
1674 :type '(choice
1675 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1676 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1677 (const :tag "message-mail" (message-mail "%a" "%s"))
1678 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1680 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1681 "Non-nil means ask for confirmation before executing shell links.
1682 Shell links can be dangerous: just think about a link
1684 [[shell:rm -rf ~/*][Google Search]]
1686 This link would show up in your Org-mode document as \"Google Search\",
1687 but really it would remove your entire home directory.
1688 Therefore we advise against setting this variable to nil.
1689 Just change it to `y-or-n-p' if you want to confirm with a
1690 single keystroke rather than having to type \"yes\"."
1691 :group 'org-link-follow
1692 :type '(choice
1693 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1694 (const :tag "with y-or-n (faster)" y-or-n-p)
1695 (const :tag "no confirmation (dangerous)" nil)))
1696 (put 'org-confirm-shell-link-function
1697 'safe-local-variable
1698 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1700 (defcustom org-confirm-shell-link-not-regexp ""
1701 "A regexp to skip confirmation for shell links."
1702 :group 'org-link-follow
1703 :version "24.1"
1704 :type 'regexp)
1706 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1707 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1708 Elisp links can be dangerous: just think about a link
1710 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1712 This link would show up in your Org-mode document as \"Google Search\",
1713 but really it would remove your entire home directory.
1714 Therefore we advise against setting this variable to nil.
1715 Just change it to `y-or-n-p' if you want to confirm with a
1716 single keystroke rather than having to type \"yes\"."
1717 :group 'org-link-follow
1718 :type '(choice
1719 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1720 (const :tag "with y-or-n (faster)" y-or-n-p)
1721 (const :tag "no confirmation (dangerous)" nil)))
1722 (put 'org-confirm-shell-link-function
1723 'safe-local-variable
1724 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1726 (defcustom org-confirm-elisp-link-not-regexp ""
1727 "A regexp to skip confirmation for Elisp links."
1728 :group 'org-link-follow
1729 :version "24.1"
1730 :type 'regexp)
1732 (defconst org-file-apps-defaults-gnu
1733 '((remote . emacs)
1734 (system . mailcap)
1735 (t . mailcap))
1736 "Default file applications on a UNIX or GNU/Linux system.
1737 See `org-file-apps'.")
1739 (defconst org-file-apps-defaults-macosx
1740 '((remote . emacs)
1741 (t . "open %s")
1742 (system . "open %s")
1743 ("ps.gz" . "gv %s")
1744 ("eps.gz" . "gv %s")
1745 ("dvi" . "xdvi %s")
1746 ("fig" . "xfig %s"))
1747 "Default file applications on a MacOS X system.
1748 The system \"open\" is known as a default, but we use X11 applications
1749 for some files for which the OS does not have a good default.
1750 See `org-file-apps'.")
1752 (defconst org-file-apps-defaults-windowsnt
1753 (list
1754 '(remote . emacs)
1755 (cons t
1756 (list (if (featurep 'xemacs)
1757 'mswindows-shell-execute
1758 'w32-shell-execute)
1759 "open" 'file))
1760 (cons 'system
1761 (list (if (featurep 'xemacs)
1762 'mswindows-shell-execute
1763 'w32-shell-execute)
1764 "open" 'file)))
1765 "Default file applications on a Windows NT system.
1766 The system \"open\" is used for most files.
1767 See `org-file-apps'.")
1769 (defcustom org-file-apps
1771 (auto-mode . emacs)
1772 ("\\.mm\\'" . default)
1773 ("\\.x?html?\\'" . default)
1774 ("\\.pdf\\'" . default)
1776 "External applications for opening `file:path' items in a document.
1777 Org-mode uses system defaults for different file types, but
1778 you can use this variable to set the application for a given file
1779 extension. The entries in this list are cons cells where the car identifies
1780 files and the cdr the corresponding command. Possible values for the
1781 file identifier are
1782 \"string\" A string as a file identifier can be interpreted in different
1783 ways, depending on its contents:
1785 - Alphanumeric characters only:
1786 Match links with this file extension.
1787 Example: (\"pdf\" . \"evince %s\")
1788 to open PDFs with evince.
1790 - Regular expression: Match links where the
1791 filename matches the regexp. If you want to
1792 use groups here, use shy groups.
1794 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1795 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1796 to open *.html and *.xhtml with firefox.
1798 - Regular expression which contains (non-shy) groups:
1799 Match links where the whole link, including \"::\", and
1800 anything after that, matches the regexp.
1801 In a custom command string, %1, %2, etc. are replaced with
1802 the parts of the link that were matched by the groups.
1803 For backwards compatibility, if a command string is given
1804 that does not use any of the group matches, this case is
1805 handled identically to the second one (i.e. match against
1806 file name only).
1807 In a custom lisp form, you can access the group matches with
1808 (match-string n link).
1810 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1811 to open [[file:document.pdf::5]] with evince at page 5.
1813 `directory' Matches a directory
1814 `remote' Matches a remote file, accessible through tramp or efs.
1815 Remote files most likely should be visited through Emacs
1816 because external applications cannot handle such paths.
1817 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1818 so all files Emacs knows how to handle. Using this with
1819 command `emacs' will open most files in Emacs. Beware that this
1820 will also open html files inside Emacs, unless you add
1821 (\"html\" . default) to the list as well.
1822 t Default for files not matched by any of the other options.
1823 `system' The system command to open files, like `open' on Windows
1824 and Mac OS X, and mailcap under GNU/Linux. This is the command
1825 that will be selected if you call `C-c C-o' with a double
1826 \\[universal-argument] \\[universal-argument] prefix.
1828 Possible values for the command are:
1829 `emacs' The file will be visited by the current Emacs process.
1830 `default' Use the default application for this file type, which is the
1831 association for t in the list, most likely in the system-specific
1832 part.
1833 This can be used to overrule an unwanted setting in the
1834 system-specific variable.
1835 `system' Use the system command for opening files, like \"open\".
1836 This command is specified by the entry whose car is `system'.
1837 Most likely, the system-specific version of this variable
1838 does define this command, but you can overrule/replace it
1839 here.
1840 string A command to be executed by a shell; %s will be replaced
1841 by the path to the file.
1842 sexp A Lisp form which will be evaluated. The file path will
1843 be available in the Lisp variable `file'.
1844 For more examples, see the system specific constants
1845 `org-file-apps-defaults-macosx'
1846 `org-file-apps-defaults-windowsnt'
1847 `org-file-apps-defaults-gnu'."
1848 :group 'org-link-follow
1849 :type '(repeat
1850 (cons (choice :value ""
1851 (string :tag "Extension")
1852 (const :tag "System command to open files" system)
1853 (const :tag "Default for unrecognized files" t)
1854 (const :tag "Remote file" remote)
1855 (const :tag "Links to a directory" directory)
1856 (const :tag "Any files that have Emacs modes"
1857 auto-mode))
1858 (choice :value ""
1859 (const :tag "Visit with Emacs" emacs)
1860 (const :tag "Use default" default)
1861 (const :tag "Use the system command" system)
1862 (string :tag "Command")
1863 (sexp :tag "Lisp form")))))
1865 (defcustom org-doi-server-url "http://dx.doi.org/"
1866 "The URL of the DOI server."
1867 :type 'string
1868 :version "24.3"
1869 :group 'org-link-follow)
1871 (defgroup org-refile nil
1872 "Options concerning refiling entries in Org-mode."
1873 :tag "Org Refile"
1874 :group 'org)
1876 (defcustom org-directory "~/org"
1877 "Directory with org files.
1878 This is just a default location to look for Org files. There is no need
1879 at all to put your files into this directory. It is only used in the
1880 following situations:
1882 1. When a capture template specifies a target file that is not an
1883 absolute path. The path will then be interpreted relative to
1884 `org-directory'
1885 2. When a capture note is filed away in an interactive way (when exiting the
1886 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1887 with `org-directory' as the default path."
1888 :group 'org-refile
1889 :group 'org-remember
1890 :group 'org-capture
1891 :type 'directory)
1893 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1894 "Default target for storing notes.
1895 Used as a fall back file for org-remember.el and org-capture.el, for
1896 templates that do not specify a target file."
1897 :group 'org-refile
1898 :group 'org-remember
1899 :group 'org-capture
1900 :type '(choice
1901 (const :tag "Default from remember-data-file" nil)
1902 file))
1904 (defcustom org-goto-interface 'outline
1905 "The default interface to be used for `org-goto'.
1906 Allowed values are:
1907 outline The interface shows an outline of the relevant file
1908 and the correct heading is found by moving through
1909 the outline or by searching with incremental search.
1910 outline-path-completion Headlines in the current buffer are offered via
1911 completion. This is the interface also used by
1912 the refile command."
1913 :group 'org-refile
1914 :type '(choice
1915 (const :tag "Outline" outline)
1916 (const :tag "Outline-path-completion" outline-path-completion)))
1918 (defcustom org-goto-max-level 5
1919 "Maximum target level when running `org-goto' with refile interface."
1920 :group 'org-refile
1921 :type 'integer)
1923 (defcustom org-reverse-note-order nil
1924 "Non-nil means store new notes at the beginning of a file or entry.
1925 When nil, new notes will be filed to the end of a file or entry.
1926 This can also be a list with cons cells of regular expressions that
1927 are matched against file names, and values."
1928 :group 'org-remember
1929 :group 'org-capture
1930 :group 'org-refile
1931 :type '(choice
1932 (const :tag "Reverse always" t)
1933 (const :tag "Reverse never" nil)
1934 (repeat :tag "By file name regexp"
1935 (cons regexp boolean))))
1937 (defcustom org-log-refile nil
1938 "Information to record when a task is refiled.
1940 Possible values are:
1942 nil Don't add anything
1943 time Add a time stamp to the task
1944 note Prompt for a note and add it with template `org-log-note-headings'
1946 This option can also be set with on a per-file-basis with
1948 #+STARTUP: nologrefile
1949 #+STARTUP: logrefile
1950 #+STARTUP: lognoterefile
1952 You can have local logging settings for a subtree by setting the LOGGING
1953 property to one or more of these keywords.
1955 When bulk-refiling from the agenda, the value `note' is forbidden and
1956 will temporarily be changed to `time'."
1957 :group 'org-refile
1958 :group 'org-progress
1959 :version "24.1"
1960 :type '(choice
1961 (const :tag "No logging" nil)
1962 (const :tag "Record timestamp" time)
1963 (const :tag "Record timestamp with note." note)))
1965 (defcustom org-refile-targets nil
1966 "Targets for refiling entries with \\[org-refile].
1967 This is a list of cons cells. Each cell contains:
1968 - a specification of the files to be considered, either a list of files,
1969 or a symbol whose function or variable value will be used to retrieve
1970 a file name or a list of file names. If you use `org-agenda-files' for
1971 that, all agenda files will be scanned for targets. Nil means consider
1972 headings in the current buffer.
1973 - A specification of how to find candidate refile targets. This may be
1974 any of:
1975 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1976 This tag has to be present in all target headlines, inheritance will
1977 not be considered.
1978 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1979 todo keyword.
1980 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1981 headlines that are refiling targets.
1982 - a cons cell (:level . N). Any headline of level N is considered a target.
1983 Note that, when `org-odd-levels-only' is set, level corresponds to
1984 order in hierarchy, not to the number of stars.
1985 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1986 Note that, when `org-odd-levels-only' is set, level corresponds to
1987 order in hierarchy, not to the number of stars.
1989 Each element of this list generates a set of possible targets.
1990 The union of these sets is presented (with completion) to
1991 the user by `org-refile'.
1993 You can set the variable `org-refile-target-verify-function' to a function
1994 to verify each headline found by the simple criteria above.
1996 When this variable is nil, all top-level headlines in the current buffer
1997 are used, equivalent to the value `((nil . (:level . 1))'."
1998 :group 'org-refile
1999 :type '(repeat
2000 (cons
2001 (choice :value org-agenda-files
2002 (const :tag "All agenda files" org-agenda-files)
2003 (const :tag "Current buffer" nil)
2004 (function) (variable) (file))
2005 (choice :tag "Identify target headline by"
2006 (cons :tag "Specific tag" (const :value :tag) (string))
2007 (cons :tag "TODO keyword" (const :value :todo) (string))
2008 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2009 (cons :tag "Level number" (const :value :level) (integer))
2010 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2012 (defcustom org-refile-target-verify-function nil
2013 "Function to verify if the headline at point should be a refile target.
2014 The function will be called without arguments, with point at the
2015 beginning of the headline. It should return t and leave point
2016 where it is if the headline is a valid target for refiling.
2018 If the target should not be selected, the function must return nil.
2019 In addition to this, it may move point to a place from where the search
2020 should be continued. For example, the function may decide that the entire
2021 subtree of the current entry should be excluded and move point to the end
2022 of the subtree."
2023 :group 'org-refile
2024 :type 'function)
2026 (defcustom org-refile-use-cache nil
2027 "Non-nil means cache refile targets to speed up the process.
2028 The cache for a particular file will be updated automatically when
2029 the buffer has been killed, or when any of the marker used for flagging
2030 refile targets no longer points at a live buffer.
2031 If you have added new entries to a buffer that might themselves be targets,
2032 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2033 find that easier, `C-u C-u C-u C-c C-w'."
2034 :group 'org-refile
2035 :version "24.1"
2036 :type 'boolean)
2038 (defcustom org-refile-use-outline-path nil
2039 "Non-nil means provide refile targets as paths.
2040 So a level 3 headline will be available as level1/level2/level3.
2042 When the value is `file', also include the file name (without directory)
2043 into the path. In this case, you can also stop the completion after
2044 the file name, to get entries inserted as top level in the file.
2046 When `full-file-path', include the full file path."
2047 :group 'org-refile
2048 :type '(choice
2049 (const :tag "Not" nil)
2050 (const :tag "Yes" t)
2051 (const :tag "Start with file name" file)
2052 (const :tag "Start with full file path" full-file-path)))
2054 (defcustom org-outline-path-complete-in-steps t
2055 "Non-nil means complete the outline path in hierarchical steps.
2056 When Org-mode uses the refile interface to select an outline path
2057 \(see variable `org-refile-use-outline-path'), the completion of
2058 the path can be done is a single go, or if can be done in steps down
2059 the headline hierarchy. Going in steps is probably the best if you
2060 do not use a special completion package like `ido' or `icicles'.
2061 However, when using these packages, going in one step can be very
2062 fast, while still showing the whole path to the entry."
2063 :group 'org-refile
2064 :type 'boolean)
2066 (defcustom org-refile-allow-creating-parent-nodes nil
2067 "Non-nil means allow to create new nodes as refile targets.
2068 New nodes are then created by adding \"/new node name\" to the completion
2069 of an existing node. When the value of this variable is `confirm',
2070 new node creation must be confirmed by the user (recommended)
2071 When nil, the completion must match an existing entry.
2073 Note that, if the new heading is not seen by the criteria
2074 listed in `org-refile-targets', multiple instances of the same
2075 heading would be created by trying again to file under the new
2076 heading."
2077 :group 'org-refile
2078 :type '(choice
2079 (const :tag "Never" nil)
2080 (const :tag "Always" t)
2081 (const :tag "Prompt for confirmation" confirm)))
2083 (defcustom org-refile-active-region-within-subtree nil
2084 "Non-nil means also refile active region within a subtree.
2086 By default `org-refile' doesn't allow refiling regions if they
2087 don't contain a set of subtrees, but it might be convenient to
2088 do so sometimes: in that case, the first line of the region is
2089 converted to a headline before refiling."
2090 :group 'org-refile
2091 :version "24.1"
2092 :type 'boolean)
2094 (defgroup org-todo nil
2095 "Options concerning TODO items in Org-mode."
2096 :tag "Org TODO"
2097 :group 'org)
2099 (defgroup org-progress nil
2100 "Options concerning Progress logging in Org-mode."
2101 :tag "Org Progress"
2102 :group 'org-time)
2104 (defvar org-todo-interpretation-widgets
2105 '((:tag "Sequence (cycling hits every state)" sequence)
2106 (:tag "Type (cycling directly to DONE)" type))
2107 "The available interpretation symbols for customizing `org-todo-keywords'.
2108 Interested libraries should add to this list.")
2110 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2111 "List of TODO entry keyword sequences and their interpretation.
2112 \\<org-mode-map>This is a list of sequences.
2114 Each sequence starts with a symbol, either `sequence' or `type',
2115 indicating if the keywords should be interpreted as a sequence of
2116 action steps, or as different types of TODO items. The first
2117 keywords are states requiring action - these states will select a headline
2118 for inclusion into the global TODO list Org-mode produces. If one of
2119 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2120 signify that no further action is necessary. If \"|\" is not found,
2121 the last keyword is treated as the only DONE state of the sequence.
2123 The command \\[org-todo] cycles an entry through these states, and one
2124 additional state where no keyword is present. For details about this
2125 cycling, see the manual.
2127 TODO keywords and interpretation can also be set on a per-file basis with
2128 the special #+SEQ_TODO and #+TYP_TODO lines.
2130 Each keyword can optionally specify a character for fast state selection
2131 \(in combination with the variable `org-use-fast-todo-selection')
2132 and specifiers for state change logging, using the same syntax that
2133 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2134 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2135 indicates to record a time stamp each time this state is selected.
2137 Each keyword may also specify if a timestamp or a note should be
2138 recorded when entering or leaving the state, by adding additional
2139 characters in the parenthesis after the keyword. This looks like this:
2140 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2141 record only the time of the state change. With X and Y being either
2142 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2143 Y when leaving the state if and only if the *target* state does not
2144 define X. You may omit any of the fast-selection key or X or /Y,
2145 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2147 For backward compatibility, this variable may also be just a list
2148 of keywords. In this case the interpretation (sequence or type) will be
2149 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2150 :group 'org-todo
2151 :group 'org-keywords
2152 :type '(choice
2153 (repeat :tag "Old syntax, just keywords"
2154 (string :tag "Keyword"))
2155 (repeat :tag "New syntax"
2156 (cons
2157 (choice
2158 :tag "Interpretation"
2159 ;;Quick and dirty way to see
2160 ;;`org-todo-interpretations'. This takes the
2161 ;;place of item arguments
2162 :convert-widget
2163 (lambda (widget)
2164 (widget-put widget
2165 :args (mapcar
2166 #'(lambda (x)
2167 (widget-convert
2168 (cons 'const x)))
2169 org-todo-interpretation-widgets))
2170 widget))
2171 (repeat
2172 (string :tag "Keyword"))))))
2174 (defvar org-todo-keywords-1 nil
2175 "All TODO and DONE keywords active in a buffer.")
2176 (make-variable-buffer-local 'org-todo-keywords-1)
2177 (defvar org-todo-keywords-for-agenda nil)
2178 (defvar org-done-keywords-for-agenda nil)
2179 (defvar org-drawers-for-agenda nil)
2180 (defvar org-todo-keyword-alist-for-agenda nil)
2181 (defvar org-tag-alist-for-agenda nil)
2182 (defvar org-agenda-contributing-files nil)
2183 (defvar org-not-done-keywords nil)
2184 (make-variable-buffer-local 'org-not-done-keywords)
2185 (defvar org-done-keywords nil)
2186 (make-variable-buffer-local 'org-done-keywords)
2187 (defvar org-todo-heads nil)
2188 (make-variable-buffer-local 'org-todo-heads)
2189 (defvar org-todo-sets nil)
2190 (make-variable-buffer-local 'org-todo-sets)
2191 (defvar org-todo-log-states nil)
2192 (make-variable-buffer-local 'org-todo-log-states)
2193 (defvar org-todo-kwd-alist nil)
2194 (make-variable-buffer-local 'org-todo-kwd-alist)
2195 (defvar org-todo-key-alist nil)
2196 (make-variable-buffer-local 'org-todo-key-alist)
2197 (defvar org-todo-key-trigger nil)
2198 (make-variable-buffer-local 'org-todo-key-trigger)
2200 (defcustom org-todo-interpretation 'sequence
2201 "Controls how TODO keywords are interpreted.
2202 This variable is in principle obsolete and is only used for
2203 backward compatibility, if the interpretation of todo keywords is
2204 not given already in `org-todo-keywords'. See that variable for
2205 more information."
2206 :group 'org-todo
2207 :group 'org-keywords
2208 :type '(choice (const sequence)
2209 (const type)))
2211 (defcustom org-use-fast-todo-selection t
2212 "Non-nil means use the fast todo selection scheme with C-c C-t.
2213 This variable describes if and under what circumstances the cycling
2214 mechanism for TODO keywords will be replaced by a single-key, direct
2215 selection scheme.
2217 When nil, fast selection is never used.
2219 When the symbol `prefix', it will be used when `org-todo' is called
2220 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2221 `C-u t' in an agenda buffer.
2223 When t, fast selection is used by default. In this case, the prefix
2224 argument forces cycling instead.
2226 In all cases, the special interface is only used if access keys have
2227 actually been assigned by the user, i.e. if keywords in the configuration
2228 are followed by a letter in parenthesis, like TODO(t)."
2229 :group 'org-todo
2230 :type '(choice
2231 (const :tag "Never" nil)
2232 (const :tag "By default" t)
2233 (const :tag "Only with C-u C-c C-t" prefix)))
2235 (defcustom org-provide-todo-statistics t
2236 "Non-nil means update todo statistics after insert and toggle.
2237 ALL-HEADLINES means update todo statistics by including headlines
2238 with no TODO keyword as well, counting them as not done.
2239 A list of TODO keywords means the same, but skip keywords that are
2240 not in this list.
2242 When this is set, todo statistics is updated in the parent of the
2243 current entry each time a todo state is changed."
2244 :group 'org-todo
2245 :type '(choice
2246 (const :tag "Yes, only for TODO entries" t)
2247 (const :tag "Yes, including all entries" 'all-headlines)
2248 (repeat :tag "Yes, for TODOs in this list"
2249 (string :tag "TODO keyword"))
2250 (other :tag "No TODO statistics" nil)))
2252 (defcustom org-hierarchical-todo-statistics t
2253 "Non-nil means TODO statistics covers just direct children.
2254 When nil, all entries in the subtree are considered.
2255 This has only an effect if `org-provide-todo-statistics' is set.
2256 To set this to nil for only a single subtree, use a COOKIE_DATA
2257 property and include the word \"recursive\" into the value."
2258 :group 'org-todo
2259 :type 'boolean)
2261 (defcustom org-after-todo-state-change-hook nil
2262 "Hook which is run after the state of a TODO item was changed.
2263 The new state (a string with a TODO keyword, or nil) is available in the
2264 Lisp variable `org-state'."
2265 :group 'org-todo
2266 :type 'hook)
2268 (defvar org-blocker-hook nil
2269 "Hook for functions that are allowed to block a state change.
2271 Functions in this hook should not modify the buffer.
2272 Each function gets as its single argument a property list,
2273 see `org-trigger-hook' for more information about this list.
2275 If any of the functions in this hook returns nil, the state change
2276 is blocked.")
2278 (defvar org-trigger-hook nil
2279 "Hook for functions that are triggered by a state change.
2281 Each function gets as its single argument a property list with at
2282 least the following elements:
2284 (:type type-of-change :position pos-at-entry-start
2285 :from old-state :to new-state)
2287 Depending on the type, more properties may be present.
2289 This mechanism is currently implemented for:
2291 TODO state changes
2292 ------------------
2293 :type todo-state-change
2294 :from previous state (keyword as a string), or nil, or a symbol
2295 'todo' or 'done', to indicate the general type of state.
2296 :to new state, like in :from")
2298 (defcustom org-enforce-todo-dependencies nil
2299 "Non-nil means undone TODO entries will block switching the parent to DONE.
2300 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2301 be blocked if any prior sibling is not yet done.
2302 Finally, if the parent is blocked because of ordered siblings of its own,
2303 the child will also be blocked."
2304 :set (lambda (var val)
2305 (set var val)
2306 (if val
2307 (add-hook 'org-blocker-hook
2308 'org-block-todo-from-children-or-siblings-or-parent)
2309 (remove-hook 'org-blocker-hook
2310 'org-block-todo-from-children-or-siblings-or-parent)))
2311 :group 'org-todo
2312 :type 'boolean)
2314 (defcustom org-enforce-todo-checkbox-dependencies nil
2315 "Non-nil means unchecked boxes will block switching the parent to DONE.
2316 When this is nil, checkboxes have no influence on switching TODO states.
2317 When non-nil, you first need to check off all check boxes before the TODO
2318 entry can be switched to DONE.
2319 This variable needs to be set before org.el is loaded, and you need to
2320 restart Emacs after a change to make the change effective. The only way
2321 to change is while Emacs is running is through the customize interface."
2322 :set (lambda (var val)
2323 (set var val)
2324 (if val
2325 (add-hook 'org-blocker-hook
2326 'org-block-todo-from-checkboxes)
2327 (remove-hook 'org-blocker-hook
2328 'org-block-todo-from-checkboxes)))
2329 :group 'org-todo
2330 :type 'boolean)
2332 (defcustom org-treat-insert-todo-heading-as-state-change nil
2333 "Non-nil means inserting a TODO heading is treated as state change.
2334 So when the command \\[org-insert-todo-heading] is used, state change
2335 logging will apply if appropriate. When nil, the new TODO item will
2336 be inserted directly, and no logging will take place."
2337 :group 'org-todo
2338 :type 'boolean)
2340 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2341 "Non-nil means switching TODO states with S-cursor counts as state change.
2342 This is the default behavior. However, setting this to nil allows a
2343 convenient way to select a TODO state and bypass any logging associated
2344 with that."
2345 :group 'org-todo
2346 :type 'boolean)
2348 (defcustom org-todo-state-tags-triggers nil
2349 "Tag changes that should be triggered by TODO state changes.
2350 This is a list. Each entry is
2352 (state-change (tag . flag) .......)
2354 State-change can be a string with a state, and empty string to indicate the
2355 state that has no TODO keyword, or it can be one of the symbols `todo'
2356 or `done', meaning any not-done or done state, respectively."
2357 :group 'org-todo
2358 :group 'org-tags
2359 :type '(repeat
2360 (cons (choice :tag "When changing to"
2361 (const :tag "Not-done state" todo)
2362 (const :tag "Done state" done)
2363 (string :tag "State"))
2364 (repeat
2365 (cons :tag "Tag action"
2366 (string :tag "Tag")
2367 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2369 (defcustom org-log-done nil
2370 "Information to record when a task moves to the DONE state.
2372 Possible values are:
2374 nil Don't add anything, just change the keyword
2375 time Add a time stamp to the task
2376 note Prompt for a note and add it with template `org-log-note-headings'
2378 This option can also be set with on a per-file-basis with
2380 #+STARTUP: nologdone
2381 #+STARTUP: logdone
2382 #+STARTUP: lognotedone
2384 You can have local logging settings for a subtree by setting the LOGGING
2385 property to one or more of these keywords."
2386 :group 'org-todo
2387 :group 'org-progress
2388 :type '(choice
2389 (const :tag "No logging" nil)
2390 (const :tag "Record CLOSED timestamp" time)
2391 (const :tag "Record CLOSED timestamp with note." note)))
2393 ;; Normalize old uses of org-log-done.
2394 (cond
2395 ((eq org-log-done t) (setq org-log-done 'time))
2396 ((and (listp org-log-done) (memq 'done org-log-done))
2397 (setq org-log-done 'note)))
2399 (defcustom org-log-reschedule nil
2400 "Information to record when the scheduling date of a tasks is modified.
2402 Possible values are:
2404 nil Don't add anything, just change the date
2405 time Add a time stamp to the task
2406 note Prompt for a note and add it with template `org-log-note-headings'
2408 This option can also be set with on a per-file-basis with
2410 #+STARTUP: nologreschedule
2411 #+STARTUP: logreschedule
2412 #+STARTUP: lognotereschedule"
2413 :group 'org-todo
2414 :group 'org-progress
2415 :type '(choice
2416 (const :tag "No logging" nil)
2417 (const :tag "Record timestamp" time)
2418 (const :tag "Record timestamp with note." note)))
2420 (defcustom org-log-redeadline nil
2421 "Information to record when the deadline date of a tasks is modified.
2423 Possible values are:
2425 nil Don't add anything, just change the date
2426 time Add a time stamp to the task
2427 note Prompt for a note and add it with template `org-log-note-headings'
2429 This option can also be set with on a per-file-basis with
2431 #+STARTUP: nologredeadline
2432 #+STARTUP: logredeadline
2433 #+STARTUP: lognoteredeadline
2435 You can have local logging settings for a subtree by setting the LOGGING
2436 property to one or more of these keywords."
2437 :group 'org-todo
2438 :group 'org-progress
2439 :type '(choice
2440 (const :tag "No logging" nil)
2441 (const :tag "Record timestamp" time)
2442 (const :tag "Record timestamp with note." note)))
2444 (defcustom org-log-note-clock-out nil
2445 "Non-nil means record a note when clocking out of an item.
2446 This can also be configured on a per-file basis by adding one of
2447 the following lines anywhere in the buffer:
2449 #+STARTUP: lognoteclock-out
2450 #+STARTUP: nolognoteclock-out"
2451 :group 'org-todo
2452 :group 'org-progress
2453 :type 'boolean)
2455 (defcustom org-log-done-with-time t
2456 "Non-nil means the CLOSED time stamp will contain date and time.
2457 When nil, only the date will be recorded."
2458 :group 'org-progress
2459 :type 'boolean)
2461 (defcustom org-log-note-headings
2462 '((done . "CLOSING NOTE %t")
2463 (state . "State %-12s from %-12S %t")
2464 (note . "Note taken on %t")
2465 (reschedule . "Rescheduled from %S on %t")
2466 (delschedule . "Not scheduled, was %S on %t")
2467 (redeadline . "New deadline from %S on %t")
2468 (deldeadline . "Removed deadline, was %S on %t")
2469 (refile . "Refiled on %t")
2470 (clock-out . ""))
2471 "Headings for notes added to entries.
2472 The value is an alist, with the car being a symbol indicating the note
2473 context, and the cdr is the heading to be used. The heading may also be the
2474 empty string.
2475 %t in the heading will be replaced by a time stamp.
2476 %T will be an active time stamp instead the default inactive one
2477 %d will be replaced by a short-format time stamp.
2478 %D will be replaced by an active short-format time stamp.
2479 %s will be replaced by the new TODO state, in double quotes.
2480 %S will be replaced by the old TODO state, in double quotes.
2481 %u will be replaced by the user name.
2482 %U will be replaced by the full user name.
2484 In fact, it is not a good idea to change the `state' entry, because
2485 agenda log mode depends on the format of these entries."
2486 :group 'org-todo
2487 :group 'org-progress
2488 :type '(list :greedy t
2489 (cons (const :tag "Heading when closing an item" done) string)
2490 (cons (const :tag
2491 "Heading when changing todo state (todo sequence only)"
2492 state) string)
2493 (cons (const :tag "Heading when just taking a note" note) string)
2494 (cons (const :tag "Heading when clocking out" clock-out) string)
2495 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2496 (cons (const :tag "Heading when rescheduling" reschedule) string)
2497 (cons (const :tag "Heading when changing deadline" redeadline) string)
2498 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2499 (cons (const :tag "Heading when refiling" refile) string)))
2501 (unless (assq 'note org-log-note-headings)
2502 (push '(note . "%t") org-log-note-headings))
2504 (defcustom org-log-into-drawer nil
2505 "Non-nil means insert state change notes and time stamps into a drawer.
2506 When nil, state changes notes will be inserted after the headline and
2507 any scheduling and clock lines, but not inside a drawer.
2509 The value of this variable should be the name of the drawer to use.
2510 LOGBOOK is proposed as the default drawer for this purpose, you can
2511 also set this to a string to define the drawer of your choice.
2513 A value of t is also allowed, representing \"LOGBOOK\".
2515 A value of t or nil can also be set with on a per-file-basis with
2517 #+STARTUP: logdrawer
2518 #+STARTUP: nologdrawer
2520 If this variable is set, `org-log-state-notes-insert-after-drawers'
2521 will be ignored.
2523 You can set the property LOG_INTO_DRAWER to overrule this setting for
2524 a subtree."
2525 :group 'org-todo
2526 :group 'org-progress
2527 :type '(choice
2528 (const :tag "Not into a drawer" nil)
2529 (const :tag "LOGBOOK" t)
2530 (string :tag "Other")))
2532 (if (fboundp 'defvaralias)
2533 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2535 (defun org-log-into-drawer ()
2536 "Return the value of `org-log-into-drawer', but let properties overrule.
2537 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2538 used instead of the default value."
2539 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2540 (cond
2541 ((not p) org-log-into-drawer)
2542 ((equal p "nil") nil)
2543 ((equal p "t") "LOGBOOK")
2544 (t p))))
2546 (defcustom org-log-state-notes-insert-after-drawers nil
2547 "Non-nil means insert state change notes after any drawers in entry.
2548 Only the drawers that *immediately* follow the headline and the
2549 deadline/scheduled line are skipped.
2550 When nil, insert notes right after the heading and perhaps the line
2551 with deadline/scheduling if present.
2553 This variable will have no effect if `org-log-into-drawer' is
2554 set."
2555 :group 'org-todo
2556 :group 'org-progress
2557 :type 'boolean)
2559 (defcustom org-log-states-order-reversed t
2560 "Non-nil means the latest state note will be directly after heading.
2561 When nil, the state change notes will be ordered according to time.
2563 This option can also be set with on a per-file-basis with
2565 #+STARTUP: logstatesreversed
2566 #+STARTUP: nologstatesreversed"
2567 :group 'org-todo
2568 :group 'org-progress
2569 :type 'boolean)
2571 (defcustom org-todo-repeat-to-state nil
2572 "The TODO state to which a repeater should return the repeating task.
2573 By default this is the first task in a TODO sequence, or the previous state
2574 in a TODO_TYP set. But you can specify another task here.
2575 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2576 :group 'org-todo
2577 :version "24.1"
2578 :type '(choice (const :tag "Head of sequence" nil)
2579 (string :tag "Specific state")))
2581 (defcustom org-log-repeat 'time
2582 "Non-nil means record moving through the DONE state when triggering repeat.
2583 An auto-repeating task is immediately switched back to TODO when
2584 marked DONE. If you are not logging state changes (by adding \"@\"
2585 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2586 record a closing note, there will be no record of the task moving
2587 through DONE. This variable forces taking a note anyway.
2589 nil Don't force a record
2590 time Record a time stamp
2591 note Prompt for a note and add it with template `org-log-note-headings'
2593 This option can also be set with on a per-file-basis with
2595 #+STARTUP: nologrepeat
2596 #+STARTUP: logrepeat
2597 #+STARTUP: lognoterepeat
2599 You can have local logging settings for a subtree by setting the LOGGING
2600 property to one or more of these keywords."
2601 :group 'org-todo
2602 :group 'org-progress
2603 :type '(choice
2604 (const :tag "Don't force a record" nil)
2605 (const :tag "Force recording the DONE state" time)
2606 (const :tag "Force recording a note with the DONE state" note)))
2609 (defgroup org-priorities nil
2610 "Priorities in Org-mode."
2611 :tag "Org Priorities"
2612 :group 'org-todo)
2614 (defcustom org-enable-priority-commands t
2615 "Non-nil means priority commands are active.
2616 When nil, these commands will be disabled, so that you never accidentally
2617 set a priority."
2618 :group 'org-priorities
2619 :type 'boolean)
2621 (defcustom org-highest-priority ?A
2622 "The highest priority of TODO items. A character like ?A, ?B etc.
2623 Must have a smaller ASCII number than `org-lowest-priority'."
2624 :group 'org-priorities
2625 :type 'character)
2627 (defcustom org-lowest-priority ?C
2628 "The lowest priority of TODO items. A character like ?A, ?B etc.
2629 Must have a larger ASCII number than `org-highest-priority'."
2630 :group 'org-priorities
2631 :type 'character)
2633 (defcustom org-default-priority ?B
2634 "The default priority of TODO items.
2635 This is the priority an item gets if no explicit priority is given.
2636 When starting to cycle on an empty priority the first step in the cycle
2637 depends on `org-priority-start-cycle-with-default'. The resulting first
2638 step priority must not exceed the range from `org-highest-priority' to
2639 `org-lowest-priority' which means that `org-default-priority' has to be
2640 in this range exclusive or inclusive the range boundaries. Else the
2641 first step refuses to set the default and the second will fall back
2642 to (depending on the command used) the highest or lowest priority."
2643 :group 'org-priorities
2644 :type 'character)
2646 (defcustom org-priority-start-cycle-with-default t
2647 "Non-nil means start with default priority when starting to cycle.
2648 When this is nil, the first step in the cycle will be (depending on the
2649 command used) one higher or lower than the default priority.
2650 See also `org-default-priority'."
2651 :group 'org-priorities
2652 :type 'boolean)
2654 (defcustom org-get-priority-function nil
2655 "Function to extract the priority from a string.
2656 The string is normally the headline. If this is nil Org computes the
2657 priority from the priority cookie like [#A] in the headline. It returns
2658 an integer, increasing by 1000 for each priority level.
2659 The user can set a different function here, which should take a string
2660 as an argument and return the numeric priority."
2661 :group 'org-priorities
2662 :version "24.1"
2663 :type 'function)
2665 (defgroup org-time nil
2666 "Options concerning time stamps and deadlines in Org-mode."
2667 :tag "Org Time"
2668 :group 'org)
2670 (defcustom org-insert-labeled-timestamps-at-point nil
2671 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2672 When nil, these labeled time stamps are forces into the second line of an
2673 entry, just after the headline. When scheduling from the global TODO list,
2674 the time stamp will always be forced into the second line."
2675 :group 'org-time
2676 :type 'boolean)
2678 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2679 "Formats for `format-time-string' which are used for time stamps.
2680 It is not recommended to change this constant.")
2682 (defcustom org-time-stamp-rounding-minutes '(0 5)
2683 "Number of minutes to round time stamps to.
2684 These are two values, the first applies when first creating a time stamp.
2685 The second applies when changing it with the commands `S-up' and `S-down'.
2686 When changing the time stamp, this means that it will change in steps
2687 of N minutes, as given by the second value.
2689 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2690 numbers should be factors of 60, so for example 5, 10, 15.
2692 When this is larger than 1, you can still force an exact time stamp by using
2693 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2694 and by using a prefix arg to `S-up/down' to specify the exact number
2695 of minutes to shift."
2696 :group 'org-time
2697 :get #'(lambda (var) ; Make sure both elements are there
2698 (if (integerp (default-value var))
2699 (list (default-value var) 5)
2700 (default-value var)))
2701 :type '(list
2702 (integer :tag "when inserting times")
2703 (integer :tag "when modifying times")))
2705 ;; Normalize old customizations of this variable.
2706 (when (integerp org-time-stamp-rounding-minutes)
2707 (setq org-time-stamp-rounding-minutes
2708 (list org-time-stamp-rounding-minutes
2709 org-time-stamp-rounding-minutes)))
2711 (defcustom org-display-custom-times nil
2712 "Non-nil means overlay custom formats over all time stamps.
2713 The formats are defined through the variable `org-time-stamp-custom-formats'.
2714 To turn this on on a per-file basis, insert anywhere in the file:
2715 #+STARTUP: customtime"
2716 :group 'org-time
2717 :set 'set-default
2718 :type 'sexp)
2719 (make-variable-buffer-local 'org-display-custom-times)
2721 (defcustom org-time-stamp-custom-formats
2722 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2723 "Custom formats for time stamps. See `format-time-string' for the syntax.
2724 These are overlaid over the default ISO format if the variable
2725 `org-display-custom-times' is set. Time like %H:%M should be at the
2726 end of the second format. The custom formats are also honored by export
2727 commands, if custom time display is turned on at the time of export."
2728 :group 'org-time
2729 :type 'sexp)
2731 (defun org-time-stamp-format (&optional long inactive)
2732 "Get the right format for a time string."
2733 (let ((f (if long (cdr org-time-stamp-formats)
2734 (car org-time-stamp-formats))))
2735 (if inactive
2736 (concat "[" (substring f 1 -1) "]")
2737 f)))
2739 (defcustom org-time-clocksum-format
2740 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2741 "The format string used when creating CLOCKSUM lines.
2742 This is also used when Org mode generates a time duration.
2744 The value can be a single format string containing two
2745 %-sequences, which will be filled with the number of hours and
2746 minutes in that order.
2748 Alternatively, the value can be a plist associating any of the
2749 keys :years, :months, :weeks, :days, :hours or :minutes with
2750 format strings. The time duration is formatted using only the
2751 time components that are needed and concatenating the results.
2752 If a time unit in absent, it falls back to the next smallest
2753 unit.
2755 The keys :require-years, :require-months, :require-days,
2756 :require-weeks, :require-hours, :require-minutes are also
2757 meaningful. A non-nil value for these keys indicates that the
2758 corresponding time component should always be included, even if
2759 its value is 0.
2762 For example,
2764 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2765 :require-minutes t)
2767 means durations longer than a day will be expressed in days,
2768 hours and minutes, and durations less than a day will always be
2769 expressed in hours and minutes (even for durations less than an
2770 hour).
2772 The value
2774 \(:days \"%dd\" :minutes \"%dm\")
2776 means durations longer than a day will be expressed in days and
2777 minutes, and durations less than a day will be expressed entirely
2778 in minutes (even for durations longer than an hour)."
2779 :group 'org-time
2780 :group 'org-clock
2781 :version "24.3"
2782 :type '(choice (string :tag "Format string")
2783 (set :tag "Plist"
2784 (group :inline t (const :tag "Years" :years)
2785 (string :tag "Format string"))
2786 (group :inline t
2787 (const :tag "Always show years" :require-years)
2788 (const t))
2789 (group :inline t (const :tag "Months" :months)
2790 (string :tag "Format string"))
2791 (group :inline t
2792 (const :tag "Always show months" :require-months)
2793 (const t))
2794 (group :inline t (const :tag "Weeks" :weeks)
2795 (string :tag "Format string"))
2796 (group :inline t
2797 (const :tag "Always show weeks" :require-weeks)
2798 (const t))
2799 (group :inline t (const :tag "Days" :days)
2800 (string :tag "Format string"))
2801 (group :inline t
2802 (const :tag "Always show days" :require-days)
2803 (const t))
2804 (group :inline t (const :tag "Hours" :hours)
2805 (string :tag "Format string"))
2806 (group :inline t
2807 (const :tag "Always show hours" :require-hours)
2808 (const t))
2809 (group :inline t (const :tag "Minutes" :minutes)
2810 (string :tag "Format string"))
2811 (group :inline t
2812 (const :tag "Always show minutes" :require-minutes)
2813 (const t)))))
2815 (defcustom org-time-clocksum-use-fractional nil
2816 "When non-nil, \\[org-clock-display] uses fractional times.
2817 See `org-time-clocksum-format' for more on time clock formats."
2818 :group 'org-time
2819 :group 'org-clock
2820 :version "24.3"
2821 :type 'boolean)
2823 (defcustom org-time-clocksum-use-effort-durations t
2824 "When non-nil, \\[org-clock-display] uses effort durations.
2825 E.g. by default, one day is considered to be a 8 hours effort,
2826 so a task that has been clocked for 16 hours will be displayed
2827 as during 2 days in the clock display or in the clocktable.
2829 See `org-effort-durations' on how to set effort durations
2830 and `org-time-clocksum-format' for more on time clock formats."
2831 :group 'org-time
2832 :group 'org-clock
2833 :version "24.3"
2834 :type 'boolean)
2836 (defcustom org-time-clocksum-fractional-format "%.2f"
2837 "The format string used when creating CLOCKSUM lines,
2838 or when Org mode generates a time duration, if
2839 `org-time-clocksum-use-fractional' is enabled.
2841 The value can be a single format string containing one
2842 %-sequence, which will be filled with the number of hours as
2843 a float.
2845 Alternatively, the value can be a plist associating any of the
2846 keys :years, :months, :weeks, :days, :hours or :minutes with
2847 a format string. The time duration is formatted using the
2848 largest time unit which gives a non-zero integer part. If all
2849 specified formats have zero integer part, the smallest time unit
2850 is used."
2851 :group 'org-time
2852 :type '(choice (string :tag "Format string")
2853 (set (group :inline t (const :tag "Years" :years)
2854 (string :tag "Format string"))
2855 (group :inline t (const :tag "Months" :months)
2856 (string :tag "Format string"))
2857 (group :inline t (const :tag "Weeks" :weeks)
2858 (string :tag "Format string"))
2859 (group :inline t (const :tag "Days" :days)
2860 (string :tag "Format string"))
2861 (group :inline t (const :tag "Hours" :hours)
2862 (string :tag "Format string"))
2863 (group :inline t (const :tag "Minutes" :minutes)
2864 (string :tag "Format string")))))
2866 (defcustom org-deadline-warning-days 14
2867 "No. of days before expiration during which a deadline becomes active.
2868 This variable governs the display in sparse trees and in the agenda.
2869 When 0 or negative, it means use this number (the absolute value of it)
2870 even if a deadline has a different individual lead time specified.
2872 Custom commands can set this variable in the options section."
2873 :group 'org-time
2874 :group 'org-agenda-daily/weekly
2875 :type 'integer)
2877 (defcustom org-read-date-prefer-future t
2878 "Non-nil means assume future for incomplete date input from user.
2879 This affects the following situations:
2880 1. The user gives a month but not a year.
2881 For example, if it is April and you enter \"feb 2\", this will be read
2882 as Feb 2, *next* year. \"May 5\", however, will be this year.
2883 2. The user gives a day, but no month.
2884 For example, if today is the 15th, and you enter \"3\", Org-mode will
2885 read this as the third of *next* month. However, if you enter \"17\",
2886 it will be considered as *this* month.
2888 If you set this variable to the symbol `time', then also the following
2889 will work:
2891 3. If the user gives a time.
2892 If the time is before now, it will be interpreted as tomorrow.
2894 Currently none of this works for ISO week specifications.
2896 When this option is nil, the current day, month and year will always be
2897 used as defaults.
2899 See also `org-agenda-jump-prefer-future'."
2900 :group 'org-time
2901 :type '(choice
2902 (const :tag "Never" nil)
2903 (const :tag "Check month and day" t)
2904 (const :tag "Check month, day, and time" time)))
2906 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2907 "Should the agenda jump command prefer the future for incomplete dates?
2908 The default is to do the same as configured in `org-read-date-prefer-future'.
2909 But you can also set a deviating value here.
2910 This may t or nil, or the symbol `org-read-date-prefer-future'."
2911 :group 'org-agenda
2912 :group 'org-time
2913 :version "24.1"
2914 :type '(choice
2915 (const :tag "Use org-read-date-prefer-future"
2916 org-read-date-prefer-future)
2917 (const :tag "Never" nil)
2918 (const :tag "Always" t)))
2920 (defcustom org-read-date-force-compatible-dates t
2921 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2923 Depending on the system Emacs is running on, certain dates cannot
2924 be represented with the type used internally to represent time.
2925 Dates between 1970-1-1 and 2038-1-1 can always be represented
2926 correctly. Some systems allow for earlier dates, some for later,
2927 some for both. One way to find out it to insert any date into an
2928 Org buffer, putting the cursor on the year and hitting S-up and
2929 S-down to test the range.
2931 When this variable is set to t, the date/time prompt will not let
2932 you specify dates outside the 1970-2037 range, so it is certain that
2933 these dates will work in whatever version of Emacs you are
2934 running, and also that you can move a file from one Emacs implementation
2935 to another. WHenever Org is forcing the year for you, it will display
2936 a message and beep.
2938 When this variable is nil, Org will check if the date is
2939 representable in the specific Emacs implementation you are using.
2940 If not, it will force a year, usually the current year, and beep
2941 to remind you. Currently this setting is not recommended because
2942 the likelihood that you will open your Org files in an Emacs that
2943 has limited date range is not negligible.
2945 A workaround for this problem is to use diary sexp dates for time
2946 stamps outside of this range."
2947 :group 'org-time
2948 :version "24.1"
2949 :type 'boolean)
2951 (defcustom org-read-date-display-live t
2952 "Non-nil means display current interpretation of date prompt live.
2953 This display will be in an overlay, in the minibuffer."
2954 :group 'org-time
2955 :type 'boolean)
2957 (defcustom org-read-date-popup-calendar t
2958 "Non-nil means pop up a calendar when prompting for a date.
2959 In the calendar, the date can be selected with mouse-1. However, the
2960 minibuffer will also be active, and you can simply enter the date as well.
2961 When nil, only the minibuffer will be available."
2962 :group 'org-time
2963 :type 'boolean)
2964 (if (fboundp 'defvaralias)
2965 (defvaralias 'org-popup-calendar-for-date-prompt
2966 'org-read-date-popup-calendar))
2968 (make-obsolete-variable
2969 'org-read-date-minibuffer-setup-hook
2970 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
2971 (defcustom org-read-date-minibuffer-setup-hook nil
2972 "Hook to be used to set up keys for the date/time interface.
2973 Add key definitions to `minibuffer-local-map', which will be a
2974 temporary copy.
2976 WARNING: This option is obsolete, you should use
2977 `org-read-date-minibuffer-local-map' to set up keys."
2978 :group 'org-time
2979 :type 'hook)
2981 (defcustom org-extend-today-until 0
2982 "The hour when your day really ends. Must be an integer.
2983 This has influence for the following applications:
2984 - When switching the agenda to \"today\". It it is still earlier than
2985 the time given here, the day recognized as TODAY is actually yesterday.
2986 - When a date is read from the user and it is still before the time given
2987 here, the current date and time will be assumed to be yesterday, 23:59.
2988 Also, timestamps inserted in capture templates follow this rule.
2990 IMPORTANT: This is a feature whose implementation is and likely will
2991 remain incomplete. Really, it is only here because past midnight seems to
2992 be the favorite working time of John Wiegley :-)"
2993 :group 'org-time
2994 :type 'integer)
2996 (defcustom org-use-effective-time nil
2997 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2998 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2999 \"effective time\" of any timestamps between midnight and 8am will be
3000 23:59 of the previous day."
3001 :group 'org-time
3002 :version "24.1"
3003 :type 'boolean)
3005 (defcustom org-use-last-clock-out-time-as-effective-time nil
3006 "When non-nil, use the last clock out time for `org-todo'.
3007 Note that this option has precedence over the combined use of
3008 `org-use-effective-time' and `org-extend-today-until'."
3009 :group 'org-time
3010 ;; :version "24.3"
3011 :type 'boolean)
3013 (defcustom org-edit-timestamp-down-means-later nil
3014 "Non-nil means S-down will increase the time in a time stamp.
3015 When nil, S-up will increase."
3016 :group 'org-time
3017 :type 'boolean)
3019 (defcustom org-calendar-follow-timestamp-change t
3020 "Non-nil means make the calendar window follow timestamp changes.
3021 When a timestamp is modified and the calendar window is visible, it will be
3022 moved to the new date."
3023 :group 'org-time
3024 :type 'boolean)
3026 (defgroup org-tags nil
3027 "Options concerning tags in Org-mode."
3028 :tag "Org Tags"
3029 :group 'org)
3031 (defcustom org-tag-alist nil
3032 "List of tags allowed in Org-mode files.
3033 When this list is nil, Org-mode will base TAG input on what is already in the
3034 buffer.
3035 The value of this variable is an alist, the car of each entry must be a
3036 keyword as a string, the cdr may be a character that is used to select
3037 that tag through the fast-tag-selection interface.
3038 See the manual for details."
3039 :group 'org-tags
3040 :type '(repeat
3041 (choice
3042 (cons (string :tag "Tag name")
3043 (character :tag "Access char"))
3044 (list :tag "Start radio group"
3045 (const :startgroup)
3046 (option (string :tag "Group description")))
3047 (list :tag "End radio group"
3048 (const :endgroup)
3049 (option (string :tag "Group description")))
3050 (const :tag "New line" (:newline)))))
3052 (defcustom org-tag-persistent-alist nil
3053 "List of tags that will always appear in all Org-mode files.
3054 This is in addition to any in buffer settings or customizations
3055 of `org-tag-alist'.
3056 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3057 The value of this variable is an alist, the car of each entry must be a
3058 keyword as a string, the cdr may be a character that is used to select
3059 that tag through the fast-tag-selection interface.
3060 See the manual for details.
3061 To disable these tags on a per-file basis, insert anywhere in the file:
3062 #+STARTUP: noptag"
3063 :group 'org-tags
3064 :type '(repeat
3065 (choice
3066 (cons (string :tag "Tag name")
3067 (character :tag "Access char"))
3068 (const :tag "Start radio group" (:startgroup))
3069 (const :tag "End radio group" (:endgroup))
3070 (const :tag "New line" (:newline)))))
3072 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3073 "If non-nil, always offer completion for all tags of all agenda files.
3074 Instead of customizing this variable directly, you might want to
3075 set it locally for capture buffers, because there no list of
3076 tags in that file can be created dynamically (there are none).
3078 (add-hook 'org-capture-mode-hook
3079 (lambda ()
3080 (set (make-local-variable
3081 'org-complete-tags-always-offer-all-agenda-tags)
3082 t)))"
3083 :group 'org-tags
3084 :version "24.1"
3085 :type 'boolean)
3087 (defvar org-file-tags nil
3088 "List of tags that can be inherited by all entries in the file.
3089 The tags will be inherited if the variable `org-use-tag-inheritance'
3090 says they should be.
3091 This variable is populated from #+FILETAGS lines.")
3093 (defcustom org-use-fast-tag-selection 'auto
3094 "Non-nil means use fast tag selection scheme.
3095 This is a special interface to select and deselect tags with single keys.
3096 When nil, fast selection is never used.
3097 When the symbol `auto', fast selection is used if and only if selection
3098 characters for tags have been configured, either through the variable
3099 `org-tag-alist' or through a #+TAGS line in the buffer.
3100 When t, fast selection is always used and selection keys are assigned
3101 automatically if necessary."
3102 :group 'org-tags
3103 :type '(choice
3104 (const :tag "Always" t)
3105 (const :tag "Never" nil)
3106 (const :tag "When selection characters are configured" 'auto)))
3108 (defcustom org-fast-tag-selection-single-key nil
3109 "Non-nil means fast tag selection exits after first change.
3110 When nil, you have to press RET to exit it.
3111 During fast tag selection, you can toggle this flag with `C-c'.
3112 This variable can also have the value `expert'. In this case, the window
3113 displaying the tags menu is not even shown, until you press C-c again."
3114 :group 'org-tags
3115 :type '(choice
3116 (const :tag "No" nil)
3117 (const :tag "Yes" t)
3118 (const :tag "Expert" expert)))
3120 (defvar org-fast-tag-selection-include-todo nil
3121 "Non-nil means fast tags selection interface will also offer TODO states.
3122 This is an undocumented feature, you should not rely on it.")
3124 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3125 "The column to which tags should be indented in a headline.
3126 If this number is positive, it specifies the column. If it is negative,
3127 it means that the tags should be flushright to that column. For example,
3128 -80 works well for a normal 80 character screen.
3129 When 0, place tags directly after headline text, with only one space in
3130 between."
3131 :group 'org-tags
3132 :type 'integer)
3134 (defcustom org-auto-align-tags t
3135 "Non-nil keeps tags aligned when modifying headlines.
3136 Some operations (i.e. demoting) change the length of a headline and
3137 therefore shift the tags around. With this option turned on, after
3138 each such operation the tags are again aligned to `org-tags-column'."
3139 :group 'org-tags
3140 :type 'boolean)
3142 (defcustom org-use-tag-inheritance t
3143 "Non-nil means tags in levels apply also for sublevels.
3144 When nil, only the tags directly given in a specific line apply there.
3145 This may also be a list of tags that should be inherited, or a regexp that
3146 matches tags that should be inherited. Additional control is possible
3147 with the variable `org-tags-exclude-from-inheritance' which gives an
3148 explicit list of tags to be excluded from inheritance, even if the value of
3149 `org-use-tag-inheritance' would select it for inheritance.
3151 If this option is t, a match early-on in a tree can lead to a large
3152 number of matches in the subtree when constructing the agenda or creating
3153 a sparse tree. If you only want to see the first match in a tree during
3154 a search, check out the variable `org-tags-match-list-sublevels'."
3155 :group 'org-tags
3156 :type '(choice
3157 (const :tag "Not" nil)
3158 (const :tag "Always" t)
3159 (repeat :tag "Specific tags" (string :tag "Tag"))
3160 (regexp :tag "Tags matched by regexp")))
3162 (defcustom org-tags-exclude-from-inheritance nil
3163 "List of tags that should never be inherited.
3164 This is a way to exclude a few tags from inheritance. For way to do
3165 the opposite, to actively allow inheritance for selected tags,
3166 see the variable `org-use-tag-inheritance'."
3167 :group 'org-tags
3168 :type '(repeat (string :tag "Tag")))
3170 (defun org-tag-inherit-p (tag)
3171 "Check if TAG is one that should be inherited."
3172 (cond
3173 ((member tag org-tags-exclude-from-inheritance) nil)
3174 ((eq org-use-tag-inheritance t) t)
3175 ((not org-use-tag-inheritance) nil)
3176 ((stringp org-use-tag-inheritance)
3177 (string-match org-use-tag-inheritance tag))
3178 ((listp org-use-tag-inheritance)
3179 (member tag org-use-tag-inheritance))
3180 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3182 (defcustom org-tags-match-list-sublevels t
3183 "Non-nil means list also sublevels of headlines matching a search.
3184 This variable applies to tags/property searches, and also to stuck
3185 projects because this search is based on a tags match as well.
3187 When set to the symbol `indented', sublevels are indented with
3188 leading dots.
3190 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3191 the sublevels of a headline matching a tag search often also match
3192 the same search. Listing all of them can create very long lists.
3193 Setting this variable to nil causes subtrees of a match to be skipped.
3195 This variable is semi-obsolete and probably should always be true. It
3196 is better to limit inheritance to certain tags using the variables
3197 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3198 :group 'org-tags
3199 :type '(choice
3200 (const :tag "No, don't list them" nil)
3201 (const :tag "Yes, do list them" t)
3202 (const :tag "List them, indented with leading dots" indented)))
3204 (defcustom org-tags-sort-function nil
3205 "When set, tags are sorted using this function as a comparator."
3206 :group 'org-tags
3207 :type '(choice
3208 (const :tag "No sorting" nil)
3209 (const :tag "Alphabetical" string<)
3210 (const :tag "Reverse alphabetical" string>)
3211 (function :tag "Custom function" nil)))
3213 (defvar org-tags-history nil
3214 "History of minibuffer reads for tags.")
3215 (defvar org-last-tags-completion-table nil
3216 "The last used completion table for tags.")
3217 (defvar org-after-tags-change-hook nil
3218 "Hook that is run after the tags in a line have changed.")
3220 (defgroup org-properties nil
3221 "Options concerning properties in Org-mode."
3222 :tag "Org Properties"
3223 :group 'org)
3225 (defcustom org-property-format "%-10s %s"
3226 "How property key/value pairs should be formatted by `indent-line'.
3227 When `indent-line' hits a property definition, it will format the line
3228 according to this format, mainly to make sure that the values are
3229 lined-up with respect to each other."
3230 :group 'org-properties
3231 :type 'string)
3233 (defcustom org-properties-postprocess-alist nil
3234 "Alist of properties and functions to adjust inserted values.
3235 Elements of this alist must be of the form
3237 ([string] [function])
3239 where [string] must be a property name and [function] must be a
3240 lambda expression: this lambda expression must take one argument,
3241 the value to adjust, and return the new value as a string.
3243 For example, this element will allow the property \"Remaining\"
3244 to be updated wrt the relation between the \"Effort\" property
3245 and the clock summary:
3247 ((\"Remaining\" (lambda(value)
3248 (let ((clocksum (org-clock-sum-current-item))
3249 (effort (org-duration-string-to-minutes
3250 (org-entry-get (point) \"Effort\"))))
3251 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3252 :group 'org-properties
3253 :version "24.1"
3254 :type '(alist :key-type (string :tag "Property")
3255 :value-type (function :tag "Function")))
3257 (defcustom org-use-property-inheritance nil
3258 "Non-nil means properties apply also for sublevels.
3260 This setting is chiefly used during property searches. Turning it on can
3261 cause significant overhead when doing a search, which is why it is not
3262 on by default.
3264 When nil, only the properties directly given in the current entry count.
3265 When t, every property is inherited. The value may also be a list of
3266 properties that should have inheritance, or a regular expression matching
3267 properties that should be inherited.
3269 However, note that some special properties use inheritance under special
3270 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3271 and the properties ending in \"_ALL\" when they are used as descriptor
3272 for valid values of a property.
3274 Note for programmers:
3275 When querying an entry with `org-entry-get', you can control if inheritance
3276 should be used. By default, `org-entry-get' looks only at the local
3277 properties. You can request inheritance by setting the inherit argument
3278 to t (to force inheritance) or to `selective' (to respect the setting
3279 in this variable)."
3280 :group 'org-properties
3281 :type '(choice
3282 (const :tag "Not" nil)
3283 (const :tag "Always" t)
3284 (repeat :tag "Specific properties" (string :tag "Property"))
3285 (regexp :tag "Properties matched by regexp")))
3287 (defun org-property-inherit-p (property)
3288 "Check if PROPERTY is one that should be inherited."
3289 (cond
3290 ((eq org-use-property-inheritance t) t)
3291 ((not org-use-property-inheritance) nil)
3292 ((stringp org-use-property-inheritance)
3293 (string-match org-use-property-inheritance property))
3294 ((listp org-use-property-inheritance)
3295 (member property org-use-property-inheritance))
3296 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3298 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3299 "The default column format, if no other format has been defined.
3300 This variable can be set on the per-file basis by inserting a line
3302 #+COLUMNS: %25ITEM ....."
3303 :group 'org-properties
3304 :type 'string)
3306 (defcustom org-columns-ellipses ".."
3307 "The ellipses to be used when a field in column view is truncated.
3308 When this is the empty string, as many characters as possible are shown,
3309 but then there will be no visual indication that the field has been truncated.
3310 When this is a string of length N, the last N characters of a truncated
3311 field are replaced by this string. If the column is narrower than the
3312 ellipses string, only part of the ellipses string will be shown."
3313 :group 'org-properties
3314 :type 'string)
3316 (defcustom org-columns-modify-value-for-display-function nil
3317 "Function that modifies values for display in column view.
3318 For example, it can be used to cut out a certain part from a time stamp.
3319 The function must take 2 arguments:
3321 column-title The title of the column (*not* the property name)
3322 value The value that should be modified.
3324 The function should return the value that should be displayed,
3325 or nil if the normal value should be used."
3326 :group 'org-properties
3327 :type 'function)
3329 (defcustom org-effort-property "Effort"
3330 "The property that is being used to keep track of effort estimates.
3331 Effort estimates given in this property need to have the format H:MM."
3332 :group 'org-properties
3333 :group 'org-progress
3334 :type '(string :tag "Property"))
3336 (defconst org-global-properties-fixed
3337 '(("VISIBILITY_ALL" . "folded children content all")
3338 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3339 "List of property/value pairs that can be inherited by any entry.
3341 These are fixed values, for the preset properties. The user variable
3342 that can be used to add to this list is `org-global-properties'.
3344 The entries in this list are cons cells where the car is a property
3345 name and cdr is a string with the value. If the value represents
3346 multiple items like an \"_ALL\" property, separate the items by
3347 spaces.")
3349 (defcustom org-global-properties nil
3350 "List of property/value pairs that can be inherited by any entry.
3352 This list will be combined with the constant `org-global-properties-fixed'.
3354 The entries in this list are cons cells where the car is a property
3355 name and cdr is a string with the value.
3357 You can set buffer-local values for the same purpose in the variable
3358 `org-file-properties' this by adding lines like
3360 #+PROPERTY: NAME VALUE"
3361 :group 'org-properties
3362 :type '(repeat
3363 (cons (string :tag "Property")
3364 (string :tag "Value"))))
3366 (defvar org-file-properties nil
3367 "List of property/value pairs that can be inherited by any entry.
3368 Valid for the current buffer.
3369 This variable is populated from #+PROPERTY lines.")
3370 (make-variable-buffer-local 'org-file-properties)
3372 (defgroup org-agenda nil
3373 "Options concerning agenda views in Org-mode."
3374 :tag "Org Agenda"
3375 :group 'org)
3377 (defvar org-category nil
3378 "Variable used by org files to set a category for agenda display.
3379 Such files should use a file variable to set it, for example
3381 # -*- mode: org; org-category: \"ELisp\"
3383 or contain a special line
3385 #+CATEGORY: ELisp
3387 If the file does not specify a category, then file's base name
3388 is used instead.")
3389 (make-variable-buffer-local 'org-category)
3390 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3392 (defcustom org-agenda-files nil
3393 "The files to be used for agenda display.
3394 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3395 \\[org-remove-file]. You can also use customize to edit the list.
3397 If an entry is a directory, all files in that directory that are matched by
3398 `org-agenda-file-regexp' will be part of the file list.
3400 If the value of the variable is not a list but a single file name, then
3401 the list of agenda files is actually stored and maintained in that file, one
3402 agenda file per line. In this file paths can be given relative to
3403 `org-directory'. Tilde expansion and environment variable substitution
3404 are also made."
3405 :group 'org-agenda
3406 :type '(choice
3407 (repeat :tag "List of files and directories" file)
3408 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3410 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3411 "Regular expression to match files for `org-agenda-files'.
3412 If any element in the list in that variable contains a directory instead
3413 of a normal file, all files in that directory that are matched by this
3414 regular expression will be included."
3415 :group 'org-agenda
3416 :type 'regexp)
3418 (defcustom org-agenda-text-search-extra-files nil
3419 "List of extra files to be searched by text search commands.
3420 These files will be search in addition to the agenda files by the
3421 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3422 Note that these files will only be searched for text search commands,
3423 not for the other agenda views like todo lists, tag searches or the weekly
3424 agenda. This variable is intended to list notes and possibly archive files
3425 that should also be searched by these two commands.
3426 In fact, if the first element in the list is the symbol `agenda-archives',
3427 than all archive files of all agenda files will be added to the search
3428 scope."
3429 :group 'org-agenda
3430 :type '(set :greedy t
3431 (const :tag "Agenda Archives" agenda-archives)
3432 (repeat :inline t (file))))
3434 (if (fboundp 'defvaralias)
3435 (defvaralias 'org-agenda-multi-occur-extra-files
3436 'org-agenda-text-search-extra-files))
3438 (defcustom org-agenda-skip-unavailable-files nil
3439 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3440 A nil value means to remove them, after a query, from the list."
3441 :group 'org-agenda
3442 :type 'boolean)
3444 (defcustom org-calendar-to-agenda-key [?c]
3445 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3446 The command `org-calendar-goto-agenda' will be bound to this key. The
3447 default is the character `c' because then `c' can be used to switch back and
3448 forth between agenda and calendar."
3449 :group 'org-agenda
3450 :type 'sexp)
3452 (defcustom org-calendar-insert-diary-entry-key [?i]
3453 "The key to be installed in `calendar-mode-map' for adding diary entries.
3454 This option is irrelevant until `org-agenda-diary-file' has been configured
3455 to point to an Org-mode file. When that is the case, the command
3456 `org-agenda-diary-entry' will be bound to the key given here, by default
3457 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3458 if you want to continue doing this, you need to change this to a different
3459 key."
3460 :group 'org-agenda
3461 :type 'sexp)
3463 (defcustom org-agenda-diary-file 'diary-file
3464 "File to which to add new entries with the `i' key in agenda and calendar.
3465 When this is the symbol `diary-file', the functionality in the Emacs
3466 calendar will be used to add entries to the `diary-file'. But when this
3467 points to a file, `org-agenda-diary-entry' will be used instead."
3468 :group 'org-agenda
3469 :type '(choice
3470 (const :tag "The standard Emacs diary file" diary-file)
3471 (file :tag "Special Org file diary entries")))
3473 (eval-after-load "calendar"
3474 '(progn
3475 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3476 'org-calendar-goto-agenda)
3477 (add-hook 'calendar-mode-hook
3478 (lambda ()
3479 (unless (eq org-agenda-diary-file 'diary-file)
3480 (define-key calendar-mode-map
3481 org-calendar-insert-diary-entry-key
3482 'org-agenda-diary-entry))))))
3484 (defgroup org-latex nil
3485 "Options for embedding LaTeX code into Org-mode."
3486 :tag "Org LaTeX"
3487 :group 'org)
3489 (defcustom org-format-latex-options
3490 '(:foreground default :background default :scale 1.0
3491 :html-foreground "Black" :html-background "Transparent"
3492 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3493 "Options for creating images from LaTeX fragments.
3494 This is a property list with the following properties:
3495 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3496 `default' means use the foreground of the default face.
3497 `auto' means use the foreground from the text face.
3498 :background the background color, or \"Transparent\".
3499 `default' means use the background of the default face.
3500 `auto' means use the background from the text face.
3501 :scale a scaling factor for the size of the images, to get more pixels
3502 :html-foreground, :html-background, :html-scale
3503 the same numbers for HTML export.
3504 :matchers a list indicating which matchers should be used to
3505 find LaTeX fragments. Valid members of this list are:
3506 \"begin\" find environments
3507 \"$1\" find single characters surrounded by $.$
3508 \"$\" find math expressions surrounded by $...$
3509 \"$$\" find math expressions surrounded by $$....$$
3510 \"\\(\" find math expressions surrounded by \\(...\\)
3511 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3512 :group 'org-latex
3513 :type 'plist)
3515 (defcustom org-format-latex-signal-error t
3516 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3517 When nil, just push out a message."
3518 :group 'org-latex
3519 :version "24.1"
3520 :type 'boolean)
3522 (defcustom org-latex-to-mathml-jar-file nil
3523 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3524 Use this to specify additional executable file say a jar file.
3526 When using MathToWeb as the converter, specify the full-path to
3527 your mathtoweb.jar file."
3528 :group 'org-latex
3529 :version "24.1"
3530 :type '(choice
3531 (const :tag "None" nil)
3532 (file :tag "JAR file" :must-match t)))
3534 (defcustom org-latex-to-mathml-convert-command nil
3535 "Command to convert LaTeX fragments to MathML.
3536 Replace format-specifiers in the command as noted below and use
3537 `shell-command' to convert LaTeX to MathML.
3538 %j: Executable file in fully expanded form as specified by
3539 `org-latex-to-mathml-jar-file'.
3540 %I: Input LaTeX file in fully expanded form
3541 %o: Output MathML file
3542 This command is used by `org-create-math-formula'.
3544 When using MathToWeb as the converter, set this to
3545 \"java -jar %j -unicode -force -df %o %I\"."
3546 :group 'org-latex
3547 :version "24.1"
3548 :type '(choice
3549 (const :tag "None" nil)
3550 (string :tag "\nShell command")))
3552 (defcustom org-latex-create-formula-image-program 'dvipng
3553 "Program to convert LaTeX fragments with.
3555 dvipng Process the LaTeX fragments to dvi file, then convert
3556 dvi files to png files using dvipng.
3557 This will also include processing of non-math environments.
3558 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3559 to convert pdf files to png files"
3560 :group 'org-latex
3561 :version "24.1"
3562 :type '(choice
3563 (const :tag "dvipng" dvipng)
3564 (const :tag "imagemagick" imagemagick)))
3566 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3567 "Path to store latex preview images.
3568 A relative path here creates many directories relative to the
3569 processed org files paths. An absolute path puts all preview
3570 images at the same place."
3571 :group 'org-latex
3572 :version "24.3"
3573 :type 'string)
3575 (defun org-format-latex-mathml-available-p ()
3576 "Return t if `org-latex-to-mathml-convert-command' is usable."
3577 (save-match-data
3578 (when (and (boundp 'org-latex-to-mathml-convert-command)
3579 org-latex-to-mathml-convert-command)
3580 (let ((executable (car (split-string
3581 org-latex-to-mathml-convert-command))))
3582 (when (executable-find executable)
3583 (if (string-match
3584 "%j" org-latex-to-mathml-convert-command)
3585 (file-readable-p org-latex-to-mathml-jar-file)
3586 t))))))
3588 (defcustom org-format-latex-header "\\documentclass{article}
3589 \\usepackage[usenames]{color}
3590 \\usepackage{amsmath}
3591 \\usepackage[mathscr]{eucal}
3592 \\pagestyle{empty} % do not remove
3593 \[PACKAGES]
3594 \[DEFAULT-PACKAGES]
3595 % The settings below are copied from fullpage.sty
3596 \\setlength{\\textwidth}{\\paperwidth}
3597 \\addtolength{\\textwidth}{-3cm}
3598 \\setlength{\\oddsidemargin}{1.5cm}
3599 \\addtolength{\\oddsidemargin}{-2.54cm}
3600 \\setlength{\\evensidemargin}{\\oddsidemargin}
3601 \\setlength{\\textheight}{\\paperheight}
3602 \\addtolength{\\textheight}{-\\headheight}
3603 \\addtolength{\\textheight}{-\\headsep}
3604 \\addtolength{\\textheight}{-\\footskip}
3605 \\addtolength{\\textheight}{-3cm}
3606 \\setlength{\\topmargin}{1.5cm}
3607 \\addtolength{\\topmargin}{-2.54cm}"
3608 "The document header used for processing LaTeX fragments.
3609 It is imperative that this header make sure that no page number
3610 appears on the page. The package defined in the variables
3611 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3612 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3613 will be appended."
3614 :group 'org-latex
3615 :type 'string)
3617 (defvar org-format-latex-header-extra nil)
3619 (defun org-set-packages-alist (var val)
3620 "Set the packages alist and make sure it has 3 elements per entry."
3621 (set var (mapcar (lambda (x)
3622 (if (and (consp x) (= (length x) 2))
3623 (list (car x) (nth 1 x) t)
3625 val)))
3627 (defun org-get-packages-alist (var)
3629 "Get the packages alist and make sure it has 3 elements per entry."
3630 (mapcar (lambda (x)
3631 (if (and (consp x) (= (length x) 2))
3632 (list (car x) (nth 1 x) t)
3634 (default-value var)))
3636 ;; The following variables are defined here because is it also used
3637 ;; when formatting latex fragments. Originally it was part of the
3638 ;; LaTeX exporter, which is why the name includes "export".
3639 (defcustom org-export-latex-default-packages-alist
3640 '(("AUTO" "inputenc" t)
3641 ("T1" "fontenc" t)
3642 ("" "fixltx2e" nil)
3643 ("" "graphicx" t)
3644 ("" "longtable" nil)
3645 ("" "float" nil)
3646 ("" "wrapfig" nil)
3647 ("" "soul" t)
3648 ("" "textcomp" t)
3649 ("" "marvosym" t)
3650 ("" "wasysym" t)
3651 ("" "latexsym" t)
3652 ("" "amssymb" t)
3653 ("" "hyperref" nil)
3654 "\\tolerance=1000"
3656 "Alist of default packages to be inserted in the header.
3657 Change this only if one of the packages here causes an incompatibility
3658 with another package you are using.
3659 The packages in this list are needed by one part or another of Org-mode
3660 to function properly.
3662 - inputenc, fontenc: for basic font and character selection
3663 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3664 for interpreting the entities in `org-entities'. You can skip some of these
3665 packages if you don't use any of the symbols in it.
3666 - graphicx: for including images
3667 - float, wrapfig: for figure placement
3668 - longtable: for long tables
3669 - hyperref: for cross references
3671 Therefore you should not modify this variable unless you know what you
3672 are doing. The one reason to change it anyway is that you might be loading
3673 some other package that conflicts with one of the default packages.
3674 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3675 If SNIPPET-FLAG is t, the package also needs to be included when
3676 compiling LaTeX snippets into images for inclusion into HTML."
3677 :group 'org-export-latex
3678 :set 'org-set-packages-alist
3679 :get 'org-get-packages-alist
3680 :version "24.1"
3681 :type '(repeat
3682 (choice
3683 (list :tag "options/package pair"
3684 (string :tag "options")
3685 (string :tag "package")
3686 (boolean :tag "Snippet"))
3687 (string :tag "A line of LaTeX"))))
3689 (defcustom org-export-latex-packages-alist nil
3690 "Alist of packages to be inserted in every LaTeX header.
3691 These will be inserted after `org-export-latex-default-packages-alist'.
3692 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3693 SNIPPET-FLAG, when t, indicates that this package is also needed when
3694 turning LaTeX snippets into images for inclusion into HTML.
3695 Make sure that you only list packages here which:
3696 - you want in every file
3697 - do not conflict with the default packages in
3698 `org-export-latex-default-packages-alist'
3699 - do not conflict with the setup in `org-format-latex-header'."
3700 :group 'org-export-latex
3701 :set 'org-set-packages-alist
3702 :get 'org-get-packages-alist
3703 :type '(repeat
3704 (choice
3705 (list :tag "options/package pair"
3706 (string :tag "options")
3707 (string :tag "package")
3708 (boolean :tag "Snippet"))
3709 (string :tag "A line of LaTeX"))))
3712 (defgroup org-appearance nil
3713 "Settings for Org-mode appearance."
3714 :tag "Org Appearance"
3715 :group 'org)
3717 (defcustom org-level-color-stars-only nil
3718 "Non-nil means fontify only the stars in each headline.
3719 When nil, the entire headline is fontified.
3720 Changing it requires restart of `font-lock-mode' to become effective
3721 also in regions already fontified."
3722 :group 'org-appearance
3723 :type 'boolean)
3725 (defcustom org-hide-leading-stars nil
3726 "Non-nil means hide the first N-1 stars in a headline.
3727 This works by using the face `org-hide' for these stars. This
3728 face is white for a light background, and black for a dark
3729 background. You may have to customize the face `org-hide' to
3730 make this work.
3731 Changing it requires restart of `font-lock-mode' to become effective
3732 also in regions already fontified.
3733 You may also set this on a per-file basis by adding one of the following
3734 lines to the buffer:
3736 #+STARTUP: hidestars
3737 #+STARTUP: showstars"
3738 :group 'org-appearance
3739 :type 'boolean)
3741 (defcustom org-hidden-keywords nil
3742 "List of symbols corresponding to keywords to be hidden the org buffer.
3743 For example, a value '(title) for this list will make the document's title
3744 appear in the buffer without the initial #+TITLE: keyword."
3745 :group 'org-appearance
3746 :version "24.1"
3747 :type '(set (const :tag "#+AUTHOR" author)
3748 (const :tag "#+DATE" date)
3749 (const :tag "#+EMAIL" email)
3750 (const :tag "#+TITLE" title)))
3752 (defcustom org-custom-properties nil
3753 "List of properties (as strings) with a special meaning.
3754 The default use of these custom properties is to let the user
3755 hide them with `org-toggle-custom-properties-visibility'."
3756 :group 'org-properties
3757 :group 'org-appearance
3758 :version "24.3"
3759 :type '(repeat (string :tag "Property Name")))
3761 (defcustom org-fontify-done-headline nil
3762 "Non-nil means change the face of a headline if it is marked DONE.
3763 Normally, only the TODO/DONE keyword indicates the state of a headline.
3764 When this is non-nil, the headline after the keyword is set to the
3765 `org-headline-done' as an additional indication."
3766 :group 'org-appearance
3767 :type 'boolean)
3769 (defcustom org-fontify-emphasized-text t
3770 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3771 Changing this variable requires a restart of Emacs to take effect."
3772 :group 'org-appearance
3773 :type 'boolean)
3775 (defcustom org-fontify-whole-heading-line nil
3776 "Non-nil means fontify the whole line for headings.
3777 This is useful when setting a background color for the
3778 org-level-* faces."
3779 :group 'org-appearance
3780 :type 'boolean)
3782 (defcustom org-highlight-latex-fragments-and-specials nil
3783 "Non-nil means fontify what is treated specially by the exporters."
3784 :group 'org-appearance
3785 :type 'boolean)
3787 (defcustom org-hide-emphasis-markers nil
3788 "Non-nil mean font-lock should hide the emphasis marker characters."
3789 :group 'org-appearance
3790 :type 'boolean)
3792 (defcustom org-pretty-entities nil
3793 "Non-nil means show entities as UTF8 characters.
3794 When nil, the \\name form remains in the buffer."
3795 :group 'org-appearance
3796 :version "24.1"
3797 :type 'boolean)
3799 (defcustom org-pretty-entities-include-sub-superscripts t
3800 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3801 :group 'org-appearance
3802 :version "24.1"
3803 :type 'boolean)
3805 (defvar org-emph-re nil
3806 "Regular expression for matching emphasis.
3807 After a match, the match groups contain these elements:
3808 0 The match of the full regular expression, including the characters
3809 before and after the proper match
3810 1 The character before the proper match, or empty at beginning of line
3811 2 The proper match, including the leading and trailing markers
3812 3 The leading marker like * or /, indicating the type of highlighting
3813 4 The text between the emphasis markers, not including the markers
3814 5 The character after the match, empty at the end of a line")
3815 (defvar org-verbatim-re nil
3816 "Regular expression for matching verbatim text.")
3817 (defvar org-emphasis-regexp-components) ; defined just below
3818 (defvar org-emphasis-alist) ; defined just below
3819 (defun org-set-emph-re (var val)
3820 "Set variable and compute the emphasis regular expression."
3821 (set var val)
3822 (when (and (boundp 'org-emphasis-alist)
3823 (boundp 'org-emphasis-regexp-components)
3824 org-emphasis-alist org-emphasis-regexp-components)
3825 (let* ((e org-emphasis-regexp-components)
3826 (pre (car e))
3827 (post (nth 1 e))
3828 (border (nth 2 e))
3829 (body (nth 3 e))
3830 (nl (nth 4 e))
3831 (body1 (concat body "*?"))
3832 (markers (mapconcat 'car org-emphasis-alist ""))
3833 (vmarkers (mapconcat
3834 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3835 org-emphasis-alist "")))
3836 ;; make sure special characters appear at the right position in the class
3837 (if (string-match "\\^" markers)
3838 (setq markers (concat (replace-match "" t t markers) "^")))
3839 (if (string-match "-" markers)
3840 (setq markers (concat (replace-match "" t t markers) "-")))
3841 (if (string-match "\\^" vmarkers)
3842 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3843 (if (string-match "-" vmarkers)
3844 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3845 (if (> nl 0)
3846 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3847 (int-to-string nl) "\\}")))
3848 ;; Make the regexp
3849 (setq org-emph-re
3850 (concat "\\([" pre "]\\|^\\)"
3851 "\\("
3852 "\\([" markers "]\\)"
3853 "\\("
3854 "[^" border "]\\|"
3855 "[^" border "]"
3856 body1
3857 "[^" border "]"
3858 "\\)"
3859 "\\3\\)"
3860 "\\([" post "]\\|$\\)"))
3861 (setq org-verbatim-re
3862 (concat "\\([" pre "]\\|^\\)"
3863 "\\("
3864 "\\([" vmarkers "]\\)"
3865 "\\("
3866 "[^" border "]\\|"
3867 "[^" border "]"
3868 body1
3869 "[^" border "]"
3870 "\\)"
3871 "\\3\\)"
3872 "\\([" post "]\\|$\\)")))))
3874 (defcustom org-emphasis-regexp-components
3875 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3876 "Components used to build the regular expression for emphasis.
3877 This is a list with five entries. Terminology: In an emphasis string
3878 like \" *strong word* \", we call the initial space PREMATCH, the final
3879 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3880 and \"trong wor\" is the body. The different components in this variable
3881 specify what is allowed/forbidden in each part:
3883 pre Chars allowed as prematch. Beginning of line will be allowed too.
3884 post Chars allowed as postmatch. End of line will be allowed too.
3885 border The chars *forbidden* as border characters.
3886 body-regexp A regexp like \".\" to match a body character. Don't use
3887 non-shy groups here, and don't allow newline here.
3888 newline The maximum number of newlines allowed in an emphasis exp.
3890 Use customize to modify this, or restart Emacs after changing it."
3891 :group 'org-appearance
3892 :set 'org-set-emph-re
3893 :type '(list
3894 (sexp :tag "Allowed chars in pre ")
3895 (sexp :tag "Allowed chars in post ")
3896 (sexp :tag "Forbidden chars in border ")
3897 (sexp :tag "Regexp for body ")
3898 (integer :tag "number of newlines allowed")
3899 (option (boolean :tag "Please ignore this button"))))
3901 (defcustom org-emphasis-alist
3902 `(("*" bold "<b>" "</b>")
3903 ("/" italic "<i>" "</i>")
3904 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3905 ("=" org-code "<code>" "</code>" verbatim)
3906 ("~" org-verbatim "<code>" "</code>" verbatim)
3907 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3908 "<del>" "</del>")
3910 "Special syntax for emphasized text.
3911 Text starting and ending with a special character will be emphasized, for
3912 example *bold*, _underlined_ and /italic/. This variable sets the marker
3913 characters, the face to be used by font-lock for highlighting in Org-mode
3914 Emacs buffers, and the HTML tags to be used for this.
3915 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3916 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3917 Use customize to modify this, or restart Emacs after changing it."
3918 :group 'org-appearance
3919 :set 'org-set-emph-re
3920 :type '(repeat
3921 (list
3922 (string :tag "Marker character")
3923 (choice
3924 (face :tag "Font-lock-face")
3925 (plist :tag "Face property list"))
3926 (string :tag "HTML start tag")
3927 (string :tag "HTML end tag")
3928 (option (const verbatim)))))
3930 (defvar org-syntax-table
3931 (let ((st (make-syntax-table)))
3932 (mapc (lambda(c) (modify-syntax-entry
3933 (string-to-char (car c)) "w p" st))
3934 org-emphasis-alist)
3935 st))
3937 (defvar org-protecting-blocks
3938 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3939 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3940 This is needed for font-lock setup.")
3942 ;;; Miscellaneous options
3944 (defgroup org-completion nil
3945 "Completion in Org-mode."
3946 :tag "Org Completion"
3947 :group 'org)
3949 (defcustom org-completion-use-ido nil
3950 "Non-nil means use ido completion wherever possible.
3951 Note that `ido-mode' must be active for this variable to be relevant.
3952 If you decide to turn this variable on, you might well want to turn off
3953 `org-outline-path-complete-in-steps'.
3954 See also `org-completion-use-iswitchb'."
3955 :group 'org-completion
3956 :type 'boolean)
3958 (defcustom org-completion-use-iswitchb nil
3959 "Non-nil means use iswitchb completion wherever possible.
3960 Note that `iswitchb-mode' must be active for this variable to be relevant.
3961 If you decide to turn this variable on, you might well want to turn off
3962 `org-outline-path-complete-in-steps'.
3963 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3964 :group 'org-completion
3965 :type 'boolean)
3967 (defcustom org-completion-fallback-command 'hippie-expand
3968 "The expansion command called by \\[pcomplete] in normal context.
3969 Normal means, no org-mode-specific context."
3970 :group 'org-completion
3971 :type 'function)
3973 ;;; Functions and variables from their packages
3974 ;; Declared here to avoid compiler warnings
3976 ;; XEmacs only
3977 (defvar outline-mode-menu-heading)
3978 (defvar outline-mode-menu-show)
3979 (defvar outline-mode-menu-hide)
3980 (defvar zmacs-regions) ; XEmacs regions
3982 ;; Emacs only
3983 (defvar mark-active)
3985 ;; Various packages
3986 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3987 (declare-function calendar-forward-day "cal-move" (arg))
3988 (declare-function calendar-goto-date "cal-move" (date))
3989 (declare-function calendar-goto-today "cal-move" ())
3990 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3991 (defvar calc-embedded-close-formula)
3992 (defvar calc-embedded-open-formula)
3993 (declare-function cdlatex-tab "ext:cdlatex" ())
3994 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3995 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3996 (defvar font-lock-unfontify-region-function)
3997 (declare-function iswitchb-read-buffer "iswitchb"
3998 (prompt &optional default require-match start matches-set))
3999 (defvar iswitchb-temp-buflist)
4000 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4001 (defvar org-agenda-tags-todo-honor-ignore-options)
4002 (declare-function org-agenda-skip "org-agenda" ())
4003 (declare-function
4004 org-agenda-format-item "org-agenda"
4005 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4006 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4007 (declare-function org-agenda-change-all-lines "org-agenda"
4008 (newhead hdmarker &optional fixface just-this))
4009 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4010 (declare-function org-agenda-maybe-redo "org-agenda" ())
4011 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4012 (beg end))
4013 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4014 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4015 "org-agenda" (&optional end))
4016 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4017 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4018 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4019 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4020 (declare-function org-indent-mode "org-indent" (&optional arg))
4021 (declare-function parse-time-string "parse-time" (string))
4022 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4023 (declare-function org-export-latex-fix-inputenc "org-latex" ())
4024 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4025 (defvar remember-data-file)
4026 (defvar texmathp-why)
4027 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4028 (declare-function table--at-cell-p "table" (position &optional object at-column))
4030 (defvar org-latex-regexps)
4032 ;;; Autoload and prepare some org modules
4034 ;; Some table stuff that needs to be defined here, because it is used
4035 ;; by the functions setting up org-mode or checking for table context.
4037 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4038 "Detect an org-type or table-type table.")
4039 (defconst org-table-line-regexp "^[ \t]*|"
4040 "Detect an org-type table line.")
4041 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4042 "Detect an org-type table line.")
4043 (defconst org-table-hline-regexp "^[ \t]*|-"
4044 "Detect an org-type table hline.")
4045 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4046 "Detect a table-type table hline.")
4047 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4048 "Detect the first line outside a table when searching from within it.
4049 This works for both table types.")
4051 ;; Autoload the functions in org-table.el that are needed by functions here.
4053 (eval-and-compile
4054 (org-autoload "org-table"
4055 '(org-table-begin org-table-blank-field org-table-end)))
4057 ;;;###autoload
4058 (defun turn-on-orgtbl ()
4059 "Unconditionally turn on `orgtbl-mode'."
4060 (require 'org-table)
4061 (orgtbl-mode 1))
4063 (defun org-at-table-p (&optional table-type)
4064 "Return t if the cursor is inside an org-type table.
4065 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4066 (if org-enable-table-editor
4067 (save-excursion
4068 (beginning-of-line 1)
4069 (looking-at (if table-type org-table-any-line-regexp
4070 org-table-line-regexp)))
4071 nil))
4072 (defsubst org-table-p () (org-at-table-p))
4074 (defun org-at-table.el-p ()
4075 "Return t if and only if we are at a table.el table."
4076 (and (org-at-table-p 'any)
4077 (save-excursion
4078 (goto-char (org-table-begin 'any))
4079 (looking-at org-table1-hline-regexp))))
4080 (defun org-table-recognize-table.el ()
4081 "If there is a table.el table nearby, recognize it and move into it."
4082 (if org-table-tab-recognizes-table.el
4083 (if (org-at-table.el-p)
4084 (progn
4085 (beginning-of-line 1)
4086 (if (looking-at org-table-dataline-regexp)
4088 (if (looking-at org-table1-hline-regexp)
4089 (progn
4090 (beginning-of-line 2)
4091 (if (looking-at org-table-any-border-regexp)
4092 (beginning-of-line -1)))))
4093 (if (re-search-forward "|" (org-table-end t) t)
4094 (progn
4095 (require 'table)
4096 (if (table--at-cell-p (point))
4098 (message "recognizing table.el table...")
4099 (table-recognize-table)
4100 (message "recognizing table.el table...done")))
4101 (error "This should not happen"))
4103 nil)
4104 nil))
4106 (defun org-at-table-hline-p ()
4107 "Return t if the cursor is inside a hline in a table."
4108 (if org-enable-table-editor
4109 (save-excursion
4110 (beginning-of-line 1)
4111 (looking-at org-table-hline-regexp))
4112 nil))
4114 (defvar org-table-clean-did-remove-column nil)
4116 (defun org-table-map-tables (function &optional quietly)
4117 "Apply FUNCTION to the start of all tables in the buffer."
4118 (save-excursion
4119 (save-restriction
4120 (widen)
4121 (goto-char (point-min))
4122 (while (re-search-forward org-table-any-line-regexp nil t)
4123 (unless quietly
4124 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4125 (beginning-of-line 1)
4126 (when (and (looking-at org-table-line-regexp)
4127 ;; Exclude tables in src/example/verbatim/clocktable blocks
4128 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4129 (save-excursion (funcall function))
4130 (or (looking-at org-table-line-regexp)
4131 (forward-char 1)))
4132 (re-search-forward org-table-any-border-regexp nil 1))))
4133 (unless quietly (message "Mapping tables: done")))
4135 ;; Declare and autoload functions from org-exp.el & Co
4137 (declare-function org-default-export-plist "org-exp")
4138 (declare-function org-infile-export-plist "org-exp")
4139 (declare-function org-get-current-options "org-exp")
4141 ;; Declare and autoload functions from org-agenda.el
4143 (eval-and-compile
4144 (org-autoload "org-agenda"
4145 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4147 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4148 (declare-function org-clock-update-mode-line "org-clock" ())
4149 (declare-function org-resolve-clocks "org-clock"
4150 (&optional also-non-dangling-p prompt last-valid))
4151 (defvar org-clock-start-time)
4152 (defvar org-clock-marker (make-marker)
4153 "Marker recording the last clock-in.")
4154 (defvar org-clock-hd-marker (make-marker)
4155 "Marker recording the last clock-in, but the headline position.")
4156 (defvar org-clock-heading ""
4157 "The heading of the current clock entry.")
4158 (defun org-clock-is-active ()
4159 "Return non-nil if clock is currently running.
4160 The return value is actually the clock marker."
4161 (marker-buffer org-clock-marker))
4163 (eval-and-compile
4164 (org-autoload "org-clock" '(org-clock-remove-overlays
4165 org-clock-update-time-maybe
4166 org-clocktable-shift)))
4168 (defun org-check-running-clock ()
4169 "Check if the current buffer contains the running clock.
4170 If yes, offer to stop it and to save the buffer with the changes."
4171 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4172 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4173 (buffer-name))))
4174 (org-clock-out)
4175 (when (y-or-n-p "Save changed buffer?")
4176 (save-buffer))))
4178 (defun org-clocktable-try-shift (dir n)
4179 "Check if this line starts a clock table, if yes, shift the time block."
4180 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4181 (org-clocktable-shift dir n)))
4183 ;;;###autoload
4184 (defun org-clock-persistence-insinuate ()
4185 "Set up hooks for clock persistence."
4186 (require 'org-clock)
4187 (add-hook 'org-mode-hook 'org-clock-load)
4188 (add-hook 'kill-emacs-hook 'org-clock-save))
4190 ;; Define the variable already here, to make sure we have it.
4191 (defvar org-indent-mode nil
4192 "Non-nil if Org-Indent mode is enabled.
4193 Use the command `org-indent-mode' to change this variable.")
4195 ;; Autoload archiving code
4196 ;; The stuff that is needed for cycling and tags has to be defined here.
4198 (defgroup org-archive nil
4199 "Options concerning archiving in Org-mode."
4200 :tag "Org Archive"
4201 :group 'org-structure)
4203 (defcustom org-archive-location "%s_archive::"
4204 "The location where subtrees should be archived.
4206 The value of this variable is a string, consisting of two parts,
4207 separated by a double-colon. The first part is a filename and
4208 the second part is a headline.
4210 When the filename is omitted, archiving happens in the same file.
4211 %s in the filename will be replaced by the current file
4212 name (without the directory part). Archiving to a different file
4213 is useful to keep archived entries from contributing to the
4214 Org-mode Agenda.
4216 The archived entries will be filed as subtrees of the specified
4217 headline. When the headline is omitted, the subtrees are simply
4218 filed away at the end of the file, as top-level entries. Also in
4219 the heading you can use %s to represent the file name, this can be
4220 useful when using the same archive for a number of different files.
4222 Here are a few examples:
4223 \"%s_archive::\"
4224 If the current file is Projects.org, archive in file
4225 Projects.org_archive, as top-level trees. This is the default.
4227 \"::* Archived Tasks\"
4228 Archive in the current file, under the top-level headline
4229 \"* Archived Tasks\".
4231 \"~/org/archive.org::\"
4232 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4234 \"~/org/archive.org::* From %s\"
4235 Archive in file ~/org/archive.org (absolute path), under headlines
4236 \"From FILENAME\" where file name is the current file name.
4238 \"~/org/datetree.org::datetree/* Finished Tasks\"
4239 The \"datetree/\" string is special, signifying to archive
4240 items to the datetree. Items are placed in either the CLOSED
4241 date of the item, or the current date if there is no CLOSED date.
4242 The heading will be a subentry to the current date. There doesn't
4243 need to be a heading, but there always needs to be a slash after
4244 datetree. For example, to store archived items directly in the
4245 datetree, use \"~/org/datetree.org::datetree/\".
4247 \"basement::** Finished Tasks\"
4248 Archive in file ./basement (relative path), as level 3 trees
4249 below the level 2 heading \"** Finished Tasks\".
4251 You may set this option on a per-file basis by adding to the buffer a
4252 line like
4254 #+ARCHIVE: basement::** Finished Tasks
4256 You may also define it locally for a subtree by setting an ARCHIVE property
4257 in the entry. If such a property is found in an entry, or anywhere up
4258 the hierarchy, it will be used."
4259 :group 'org-archive
4260 :type 'string)
4262 (defcustom org-archive-tag "ARCHIVE"
4263 "The tag that marks a subtree as archived.
4264 An archived subtree does not open during visibility cycling, and does
4265 not contribute to the agenda listings.
4266 After changing this, font-lock must be restarted in the relevant buffers to
4267 get the proper fontification."
4268 :group 'org-archive
4269 :group 'org-keywords
4270 :type 'string)
4272 (defcustom org-agenda-skip-archived-trees t
4273 "Non-nil means the agenda will skip any items located in archived trees.
4274 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4275 variable is no longer recommended, you should leave it at the value t.
4276 Instead, use the key `v' to cycle the archives-mode in the agenda."
4277 :group 'org-archive
4278 :group 'org-agenda-skip
4279 :type 'boolean)
4281 (defcustom org-columns-skip-archived-trees t
4282 "Non-nil means ignore archived trees when creating column view."
4283 :group 'org-archive
4284 :group 'org-properties
4285 :type 'boolean)
4287 (defcustom org-cycle-open-archived-trees nil
4288 "Non-nil means `org-cycle' will open archived trees.
4289 An archived tree is a tree marked with the tag ARCHIVE.
4290 When nil, archived trees will stay folded. You can still open them with
4291 normal outline commands like `show-all', but not with the cycling commands."
4292 :group 'org-archive
4293 :group 'org-cycle
4294 :type 'boolean)
4296 (defcustom org-sparse-tree-open-archived-trees nil
4297 "Non-nil means sparse tree construction shows matches in archived trees.
4298 When nil, matches in these trees are highlighted, but the trees are kept in
4299 collapsed state."
4300 :group 'org-archive
4301 :group 'org-sparse-trees
4302 :type 'boolean)
4304 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4305 "The default date type when building a sparse tree.
4306 When this is nil, a date is a scheduled or a deadline timestamp.
4307 Otherwise, these types are allowed:
4309 all: all timestamps
4310 active: only active timestamps (<...>)
4311 inactive: only inactive timestamps (<...)
4312 scheduled: only scheduled timestamps
4313 deadline: only deadline timestamps"
4314 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4315 (const :tag "All timestamps" all)
4316 (const :tag "Only active timestamps" active)
4317 (const :tag "Only inactive timestamps" inactive)
4318 (const :tag "Only scheduled timestamps" scheduled)
4319 (const :tag "Only deadline timestamps" deadline))
4320 :version "24.3"
4321 :group 'org-sparse-trees)
4323 (defun org-cycle-hide-archived-subtrees (state)
4324 "Re-hide all archived subtrees after a visibility state change."
4325 (when (and (not org-cycle-open-archived-trees)
4326 (not (memq state '(overview folded))))
4327 (save-excursion
4328 (let* ((globalp (memq state '(contents all)))
4329 (beg (if globalp (point-min) (point)))
4330 (end (if globalp (point-max) (org-end-of-subtree t))))
4331 (org-hide-archived-subtrees beg end)
4332 (goto-char beg)
4333 (if (looking-at (concat ".*:" org-archive-tag ":"))
4334 (message "%s" (substitute-command-keys
4335 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4337 (defun org-force-cycle-archived ()
4338 "Cycle subtree even if it is archived."
4339 (interactive)
4340 (setq this-command 'org-cycle)
4341 (let ((org-cycle-open-archived-trees t))
4342 (call-interactively 'org-cycle)))
4344 (defun org-hide-archived-subtrees (beg end)
4345 "Re-hide all archived subtrees after a visibility state change."
4346 (save-excursion
4347 (let* ((re (concat ":" org-archive-tag ":")))
4348 (goto-char beg)
4349 (while (re-search-forward re end t)
4350 (when (org-at-heading-p)
4351 (org-flag-subtree t)
4352 (org-end-of-subtree t))))))
4354 (declare-function outline-end-of-heading "outline" ())
4355 (declare-function outline-flag-region "outline" (from to flag))
4356 (defun org-flag-subtree (flag)
4357 (save-excursion
4358 (org-back-to-heading t)
4359 (outline-end-of-heading)
4360 (outline-flag-region (point)
4361 (progn (org-end-of-subtree t) (point))
4362 flag)))
4364 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4366 (eval-and-compile
4367 (org-autoload "org-archive"
4368 '(org-add-archive-files)))
4370 ;; Autoload Column View Code
4372 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4373 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4374 (declare-function org-columns-compute "org-colview" (property))
4376 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4377 '(org-columns-number-to-string
4378 org-columns-get-format-and-top-level
4379 org-columns-compute
4380 org-columns-remove-overlays))
4382 ;; Autoload ID code
4384 (declare-function org-id-store-link "org-id")
4385 (declare-function org-id-locations-load "org-id")
4386 (declare-function org-id-locations-save "org-id")
4387 (defvar org-id-track-globally)
4388 (org-autoload "org-id"
4389 '(org-id-new
4390 org-id-copy
4391 org-id-get-with-outline-path-completion
4392 org-id-get-with-outline-drilling))
4394 ;;; Variables for pre-computed regular expressions, all buffer local
4396 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4397 "Matches first line of a hidden block.")
4398 (make-variable-buffer-local 'org-drawer-regexp)
4399 (defvar org-todo-regexp nil
4400 "Matches any of the TODO state keywords.")
4401 (make-variable-buffer-local 'org-todo-regexp)
4402 (defvar org-not-done-regexp nil
4403 "Matches any of the TODO state keywords except the last one.")
4404 (make-variable-buffer-local 'org-not-done-regexp)
4405 (defvar org-not-done-heading-regexp nil
4406 "Matches a TODO headline that is not done.")
4407 (make-variable-buffer-local 'org-not-done-regexp)
4408 (defvar org-todo-line-regexp nil
4409 "Matches a headline and puts TODO state into group 2 if present.")
4410 (make-variable-buffer-local 'org-todo-line-regexp)
4411 (defvar org-complex-heading-regexp nil
4412 "Matches a headline and puts everything into groups:
4413 group 1: the stars
4414 group 2: The todo keyword, maybe
4415 group 3: Priority cookie
4416 group 4: True headline
4417 group 5: Tags")
4418 (make-variable-buffer-local 'org-complex-heading-regexp)
4419 (defvar org-complex-heading-regexp-format nil
4420 "Printf format to make regexp to match an exact headline.
4421 This regexp will match the headline of any node which has the
4422 exact headline text that is put into the format, but may have any
4423 TODO state, priority and tags.")
4424 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4425 (defvar org-todo-line-tags-regexp nil
4426 "Matches a headline and puts TODO state into group 2 if present.
4427 Also put tags into group 4 if tags are present.")
4428 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4429 (defvar org-ds-keyword-length 12
4430 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4431 (make-variable-buffer-local 'org-ds-keyword-length)
4432 (defvar org-deadline-regexp nil
4433 "Matches the DEADLINE keyword.")
4434 (make-variable-buffer-local 'org-deadline-regexp)
4435 (defvar org-deadline-time-regexp nil
4436 "Matches the DEADLINE keyword together with a time stamp.")
4437 (make-variable-buffer-local 'org-deadline-time-regexp)
4438 (defvar org-deadline-line-regexp nil
4439 "Matches the DEADLINE keyword and the rest of the line.")
4440 (make-variable-buffer-local 'org-deadline-line-regexp)
4441 (defvar org-scheduled-regexp nil
4442 "Matches the SCHEDULED keyword.")
4443 (make-variable-buffer-local 'org-scheduled-regexp)
4444 (defvar org-scheduled-time-regexp nil
4445 "Matches the SCHEDULED keyword together with a time stamp.")
4446 (make-variable-buffer-local 'org-scheduled-time-regexp)
4447 (defvar org-closed-time-regexp nil
4448 "Matches the CLOSED keyword together with a time stamp.")
4449 (make-variable-buffer-local 'org-closed-time-regexp)
4451 (defvar org-keyword-time-regexp nil
4452 "Matches any of the 4 keywords, together with the time stamp.")
4453 (make-variable-buffer-local 'org-keyword-time-regexp)
4454 (defvar org-keyword-time-not-clock-regexp nil
4455 "Matches any of the 3 keywords, together with the time stamp.")
4456 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4457 (defvar org-maybe-keyword-time-regexp nil
4458 "Matches a timestamp, possibly preceded by a keyword.")
4459 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4460 (defvar org-all-time-keywords nil
4461 "List of time keywords.")
4462 (make-variable-buffer-local 'org-all-time-keywords)
4464 (defconst org-plain-time-of-day-regexp
4465 (concat
4466 "\\(\\<[012]?[0-9]"
4467 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4468 "\\(--?"
4469 "\\(\\<[012]?[0-9]"
4470 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4471 "\\)?")
4472 "Regular expression to match a plain time or time range.
4473 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4474 groups carry important information:
4475 0 the full match
4476 1 the first time, range or not
4477 8 the second time, if it is a range.")
4479 (defconst org-plain-time-extension-regexp
4480 (concat
4481 "\\(\\<[012]?[0-9]"
4482 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4483 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4484 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4485 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4486 groups carry important information:
4487 0 the full match
4488 7 hours of duration
4489 9 minutes of duration")
4491 (defconst org-stamp-time-of-day-regexp
4492 (concat
4493 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4494 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4495 "\\(--?"
4496 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4497 "Regular expression to match a timestamp time or time range.
4498 After a match, the following groups carry important information:
4499 0 the full match
4500 1 date plus weekday, for back referencing to make sure both times are on the same day
4501 2 the first time, range or not
4502 4 the second time, if it is a range.")
4504 (defconst org-startup-options
4505 '(("fold" org-startup-folded t)
4506 ("overview" org-startup-folded t)
4507 ("nofold" org-startup-folded nil)
4508 ("showall" org-startup-folded nil)
4509 ("showeverything" org-startup-folded showeverything)
4510 ("content" org-startup-folded content)
4511 ("indent" org-startup-indented t)
4512 ("noindent" org-startup-indented nil)
4513 ("hidestars" org-hide-leading-stars t)
4514 ("showstars" org-hide-leading-stars nil)
4515 ("odd" org-odd-levels-only t)
4516 ("oddeven" org-odd-levels-only nil)
4517 ("align" org-startup-align-all-tables t)
4518 ("noalign" org-startup-align-all-tables nil)
4519 ("inlineimages" org-startup-with-inline-images t)
4520 ("noinlineimages" org-startup-with-inline-images nil)
4521 ("customtime" org-display-custom-times t)
4522 ("logdone" org-log-done time)
4523 ("lognotedone" org-log-done note)
4524 ("nologdone" org-log-done nil)
4525 ("lognoteclock-out" org-log-note-clock-out t)
4526 ("nolognoteclock-out" org-log-note-clock-out nil)
4527 ("logrepeat" org-log-repeat state)
4528 ("lognoterepeat" org-log-repeat note)
4529 ("logdrawer" org-log-into-drawer t)
4530 ("nologdrawer" org-log-into-drawer nil)
4531 ("logstatesreversed" org-log-states-order-reversed t)
4532 ("nologstatesreversed" org-log-states-order-reversed nil)
4533 ("nologrepeat" org-log-repeat nil)
4534 ("logreschedule" org-log-reschedule time)
4535 ("lognotereschedule" org-log-reschedule note)
4536 ("nologreschedule" org-log-reschedule nil)
4537 ("logredeadline" org-log-redeadline time)
4538 ("lognoteredeadline" org-log-redeadline note)
4539 ("nologredeadline" org-log-redeadline nil)
4540 ("logrefile" org-log-refile time)
4541 ("lognoterefile" org-log-refile note)
4542 ("nologrefile" org-log-refile nil)
4543 ("fninline" org-footnote-define-inline t)
4544 ("nofninline" org-footnote-define-inline nil)
4545 ("fnlocal" org-footnote-section nil)
4546 ("fnauto" org-footnote-auto-label t)
4547 ("fnprompt" org-footnote-auto-label nil)
4548 ("fnconfirm" org-footnote-auto-label confirm)
4549 ("fnplain" org-footnote-auto-label plain)
4550 ("fnadjust" org-footnote-auto-adjust t)
4551 ("nofnadjust" org-footnote-auto-adjust nil)
4552 ("constcgs" constants-unit-system cgs)
4553 ("constSI" constants-unit-system SI)
4554 ("noptag" org-tag-persistent-alist nil)
4555 ("hideblocks" org-hide-block-startup t)
4556 ("nohideblocks" org-hide-block-startup nil)
4557 ("beamer" org-startup-with-beamer-mode t)
4558 ("entitiespretty" org-pretty-entities t)
4559 ("entitiesplain" org-pretty-entities nil))
4560 "Variable associated with STARTUP options for org-mode.
4561 Each element is a list of three items: the startup options (as written
4562 in the #+STARTUP line), the corresponding variable, and the value to set
4563 this variable to if the option is found. An optional forth element PUSH
4564 means to push this value onto the list in the variable.")
4566 (defun org-update-property-plist (key val props)
4567 "Update PROPS with KEY and VAL."
4568 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4569 (key (if appending (substring key 0 (- (length key) 1)) key))
4570 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4571 (previous (cdr (assoc key props))))
4572 (if appending
4573 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4574 (cons (cons key val) remainder))))
4576 (defconst org-block-regexp
4577 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4578 "Regular expression for hiding blocks.")
4579 (defconst org-heading-keyword-regexp-format
4580 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4581 "Printf format for a regexp matching an headline with some keyword.
4582 This regexp will match the headline of any node which has the
4583 exact keyword that is put into the format. The keyword isn't in
4584 any group by default, but the stars and the body are.")
4585 (defconst org-heading-keyword-maybe-regexp-format
4586 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4587 "Printf format for a regexp matching an headline, possibly with some keyword.
4588 This regexp can match any headline with the specified keyword, or
4589 without a keyword. The keyword isn't in any group by default,
4590 but the stars and the body are.")
4592 (defun org-set-regexps-and-options ()
4593 "Precompute regular expressions for current buffer."
4594 (when (derived-mode-p 'org-mode)
4595 (org-set-local 'org-todo-kwd-alist nil)
4596 (org-set-local 'org-todo-key-alist nil)
4597 (org-set-local 'org-todo-key-trigger nil)
4598 (org-set-local 'org-todo-keywords-1 nil)
4599 (org-set-local 'org-done-keywords nil)
4600 (org-set-local 'org-todo-heads nil)
4601 (org-set-local 'org-todo-sets nil)
4602 (org-set-local 'org-todo-log-states nil)
4603 (org-set-local 'org-file-properties nil)
4604 (org-set-local 'org-file-tags nil)
4605 (let ((re (org-make-options-regexp
4606 '("CATEGORY" "TODO" "COLUMNS"
4607 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4608 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4609 "OPTIONS")
4610 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4611 (splitre "[ \t]+")
4612 (scripts org-use-sub-superscripts)
4613 kwds kws0 kwsa key log value cat arch tags const links hw dws
4614 tail sep kws1 prio props ftags drawers beamer-p
4615 ext-setup-or-nil setup-contents (start 0))
4616 (save-excursion
4617 (save-restriction
4618 (widen)
4619 (goto-char (point-min))
4620 (while (or (and ext-setup-or-nil
4621 (string-match re ext-setup-or-nil start)
4622 (setq start (match-end 0)))
4623 (and (setq ext-setup-or-nil nil start 0)
4624 (re-search-forward re nil t)))
4625 (setq key (upcase (match-string 1 ext-setup-or-nil))
4626 value (org-match-string-no-properties 2 ext-setup-or-nil))
4627 (if (stringp value) (setq value (org-trim value)))
4628 (cond
4629 ((equal key "CATEGORY")
4630 (setq cat value))
4631 ((member key '("SEQ_TODO" "TODO"))
4632 (push (cons 'sequence (org-split-string value splitre)) kwds))
4633 ((equal key "TYP_TODO")
4634 (push (cons 'type (org-split-string value splitre)) kwds))
4635 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4636 ;; general TODO-like setup
4637 (push (cons (intern (downcase (match-string 1 key)))
4638 (org-split-string value splitre)) kwds))
4639 ((equal key "TAGS")
4640 (setq tags (append tags (if tags '("\\n") nil)
4641 (org-split-string value splitre))))
4642 ((equal key "COLUMNS")
4643 (org-set-local 'org-columns-default-format value))
4644 ((equal key "LINK")
4645 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4646 (push (cons (match-string 1 value)
4647 (org-trim (match-string 2 value)))
4648 links)))
4649 ((equal key "PRIORITIES")
4650 (setq prio (org-split-string value " +")))
4651 ((equal key "PROPERTY")
4652 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4653 (setq props (org-update-property-plist (match-string 1 value)
4654 (match-string 2 value)
4655 props))))
4656 ((equal key "FILETAGS")
4657 (when (string-match "\\S-" value)
4658 (setq ftags
4659 (append
4660 ftags
4661 (apply 'append
4662 (mapcar (lambda (x) (org-split-string x ":"))
4663 (org-split-string value)))))))
4664 ((equal key "DRAWERS")
4665 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4666 ((equal key "CONSTANTS")
4667 (setq const (append const (org-split-string value splitre))))
4668 ((equal key "STARTUP")
4669 (let ((opts (org-split-string value splitre))
4670 l var val)
4671 (while (setq l (pop opts))
4672 (when (setq l (assoc l org-startup-options))
4673 (setq var (nth 1 l) val (nth 2 l))
4674 (if (not (nth 3 l))
4675 (set (make-local-variable var) val)
4676 (if (not (listp (symbol-value var)))
4677 (set (make-local-variable var) nil))
4678 (set (make-local-variable var) (symbol-value var))
4679 (add-to-list var val))))))
4680 ((equal key "ARCHIVE")
4681 (setq arch value)
4682 (remove-text-properties 0 (length arch)
4683 '(face t fontified t) arch))
4684 ((equal key "LATEX_CLASS")
4685 (setq beamer-p (equal value "beamer")))
4686 ((equal key "OPTIONS")
4687 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4688 (setq scripts (read (match-string 2 value)))))
4689 ((equal key "SETUPFILE")
4690 (setq setup-contents (org-file-contents
4691 (expand-file-name
4692 (org-remove-double-quotes value))
4693 'noerror))
4694 (if (not ext-setup-or-nil)
4695 (setq ext-setup-or-nil setup-contents start 0)
4696 (setq ext-setup-or-nil
4697 (concat (substring ext-setup-or-nil 0 start)
4698 "\n" setup-contents "\n"
4699 (substring ext-setup-or-nil start)))))))
4700 ;; search for property blocks
4701 (goto-char (point-min))
4702 (while (re-search-forward org-block-regexp nil t)
4703 (when (equal "PROPERTY" (upcase (match-string 1)))
4704 (setq value (replace-regexp-in-string
4705 "[\n\r]" " " (match-string 4)))
4706 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4707 (setq props (org-update-property-plist (match-string 1 value)
4708 (match-string 2 value)
4709 props)))))))
4710 (org-set-local 'org-use-sub-superscripts scripts)
4711 (when cat
4712 (org-set-local 'org-category (intern cat))
4713 (push (cons "CATEGORY" cat) props))
4714 (when prio
4715 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4716 (setq prio (mapcar 'string-to-char prio))
4717 (org-set-local 'org-highest-priority (nth 0 prio))
4718 (org-set-local 'org-lowest-priority (nth 1 prio))
4719 (org-set-local 'org-default-priority (nth 2 prio)))
4720 (and props (org-set-local 'org-file-properties (nreverse props)))
4721 (and ftags (org-set-local 'org-file-tags
4722 (mapcar 'org-add-prop-inherited ftags)))
4723 (and drawers (org-set-local 'org-drawers drawers))
4724 (and arch (org-set-local 'org-archive-location arch))
4725 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4726 ;; Process the TODO keywords
4727 (unless kwds
4728 ;; Use the global values as if they had been given locally.
4729 (setq kwds (default-value 'org-todo-keywords))
4730 (if (stringp (car kwds))
4731 (setq kwds (list (cons org-todo-interpretation
4732 (default-value 'org-todo-keywords)))))
4733 (setq kwds (reverse kwds)))
4734 (setq kwds (nreverse kwds))
4735 (let (inter kws kw)
4736 (while (setq kws (pop kwds))
4737 (let ((kws (or
4738 (run-hook-with-args-until-success
4739 'org-todo-setup-filter-hook kws)
4740 kws)))
4741 (setq inter (pop kws) sep (member "|" kws)
4742 kws0 (delete "|" (copy-sequence kws))
4743 kwsa nil
4744 kws1 (mapcar
4745 (lambda (x)
4746 ;; 1 2
4747 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4748 (progn
4749 (setq kw (match-string 1 x)
4750 key (and (match-end 2) (match-string 2 x))
4751 log (org-extract-log-state-settings x))
4752 (push (cons kw (and key (string-to-char key))) kwsa)
4753 (and log (push log org-todo-log-states))
4755 (error "Invalid TODO keyword %s" x)))
4756 kws0)
4757 kwsa (if kwsa (append '((:startgroup))
4758 (nreverse kwsa)
4759 '((:endgroup))))
4760 hw (car kws1)
4761 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4762 tail (list inter hw (car dws) (org-last dws))))
4763 (add-to-list 'org-todo-heads hw 'append)
4764 (push kws1 org-todo-sets)
4765 (setq org-done-keywords (append org-done-keywords dws nil))
4766 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4767 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4768 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4769 (setq org-todo-sets (nreverse org-todo-sets)
4770 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4771 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4772 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4773 ;; Process the constants
4774 (when const
4775 (let (e cst)
4776 (while (setq e (pop const))
4777 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4778 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4779 (setq org-table-formula-constants-local cst)))
4781 ;; Process the tags.
4782 (when tags
4783 (let (e tgs)
4784 (while (setq e (pop tags))
4785 (cond
4786 ((equal e "{") (push '(:startgroup) tgs))
4787 ((equal e "}") (push '(:endgroup) tgs))
4788 ((equal e "\\n") (push '(:newline) tgs))
4789 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4790 (push (cons (match-string 1 e)
4791 (string-to-char (match-string 2 e)))
4792 tgs))
4793 (t (push (list e) tgs))))
4794 (org-set-local 'org-tag-alist nil)
4795 (while (setq e (pop tgs))
4796 (or (and (stringp (car e))
4797 (assoc (car e) org-tag-alist))
4798 (push e org-tag-alist)))))
4800 ;; Compute the regular expressions and other local variables.
4801 ;; Using `org-outline-regexp-bol' would complicate them much,
4802 ;; because of the fixed white space at the end of that string.
4803 (if (not org-done-keywords)
4804 (setq org-done-keywords (and org-todo-keywords-1
4805 (list (org-last org-todo-keywords-1)))))
4806 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4807 (length org-scheduled-string)
4808 (length org-clock-string)
4809 (length org-closed-string)))
4810 org-drawer-regexp
4811 (concat "^[ \t]*:\\("
4812 (mapconcat 'regexp-quote org-drawers "\\|")
4813 "\\):[ \t]*$")
4814 org-not-done-keywords
4815 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4816 org-todo-regexp
4817 (concat "\\("
4818 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4819 "\\)")
4820 org-not-done-regexp
4821 (concat "\\("
4822 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4823 "\\)")
4824 org-not-done-heading-regexp
4825 (format org-heading-keyword-regexp-format org-not-done-regexp)
4826 org-todo-line-regexp
4827 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4828 org-complex-heading-regexp
4829 (concat "^\\(\\*+\\)"
4830 "\\(?: +" org-todo-regexp "\\)?"
4831 "\\(?: +\\(\\[#.\\]\\)\\)?"
4832 "\\(?: +\\(.*?\\)\\)??"
4833 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4834 "[ \t]*$")
4835 org-complex-heading-regexp-format
4836 (concat "^\\(\\*+\\)"
4837 "\\(?: +" org-todo-regexp "\\)?"
4838 "\\(?: +\\(\\[#.\\]\\)\\)?"
4839 "\\(?: +"
4840 ;; Stats cookies can be stuck to body.
4841 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4842 "\\(%s\\)"
4843 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4844 "\\)"
4845 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4846 "[ \t]*$")
4847 org-todo-line-tags-regexp
4848 (concat "^\\(\\*+\\)"
4849 "\\(?: +" org-todo-regexp "\\)?"
4850 "\\(?: +\\(.*?\\)\\)??"
4851 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4852 "[ \t]*$")
4853 org-deadline-regexp (concat "\\<" org-deadline-string)
4854 org-deadline-time-regexp
4855 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4856 org-deadline-line-regexp
4857 (concat "\\<\\(" org-deadline-string "\\).*")
4858 org-scheduled-regexp
4859 (concat "\\<" org-scheduled-string)
4860 org-scheduled-time-regexp
4861 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4862 org-closed-time-regexp
4863 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4864 org-keyword-time-regexp
4865 (concat "\\<\\(" org-scheduled-string
4866 "\\|" org-deadline-string
4867 "\\|" org-closed-string
4868 "\\|" org-clock-string "\\)"
4869 " *[[<]\\([^]>]+\\)[]>]")
4870 org-keyword-time-not-clock-regexp
4871 (concat "\\<\\(" org-scheduled-string
4872 "\\|" org-deadline-string
4873 "\\|" org-closed-string
4874 "\\)"
4875 " *[[<]\\([^]>]+\\)[]>]")
4876 org-maybe-keyword-time-regexp
4877 (concat "\\(\\<\\(" org-scheduled-string
4878 "\\|" org-deadline-string
4879 "\\|" org-closed-string
4880 "\\|" org-clock-string "\\)\\)?"
4881 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4882 org-all-time-keywords
4883 (mapcar (lambda (w) (substring w 0 -1))
4884 (list org-scheduled-string org-deadline-string
4885 org-clock-string org-closed-string))
4887 (org-compute-latex-and-specials-regexp)
4888 (org-set-font-lock-defaults))))
4890 (defun org-file-contents (file &optional noerror)
4891 "Return the contents of FILE, as a string."
4892 (if (or (not file)
4893 (not (file-readable-p file)))
4894 (if noerror
4895 (progn
4896 (message "Cannot read file \"%s\"" file)
4897 (ding) (sit-for 2)
4899 (error "Cannot read file \"%s\"" file))
4900 (with-temp-buffer
4901 (insert-file-contents file)
4902 (buffer-string))))
4904 (defun org-extract-log-state-settings (x)
4905 "Extract the log state setting from a TODO keyword string.
4906 This will extract info from a string like \"WAIT(w@/!)\"."
4907 (let (kw key log1 log2)
4908 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4909 (setq kw (match-string 1 x)
4910 key (and (match-end 2) (match-string 2 x))
4911 log1 (and (match-end 3) (match-string 3 x))
4912 log2 (and (match-end 4) (match-string 4 x)))
4913 (and (or log1 log2)
4914 (list kw
4915 (and log1 (if (equal log1 "!") 'time 'note))
4916 (and log2 (if (equal log2 "!") 'time 'note)))))))
4918 (defun org-remove-keyword-keys (list)
4919 "Remove a pair of parenthesis at the end of each string in LIST."
4920 (mapcar (lambda (x)
4921 (if (string-match "(.*)$" x)
4922 (substring x 0 (match-beginning 0))
4924 list))
4926 (defun org-assign-fast-keys (alist)
4927 "Assign fast keys to a keyword-key alist.
4928 Respect keys that are already there."
4929 (let (new e (alt ?0))
4930 (while (setq e (pop alist))
4931 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4932 (cdr e)) ;; Key already assigned.
4933 (push e new)
4934 (let ((clist (string-to-list (downcase (car e))))
4935 (used (append new alist)))
4936 (when (= (car clist) ?@)
4937 (pop clist))
4938 (while (and clist (rassoc (car clist) used))
4939 (pop clist))
4940 (unless clist
4941 (while (rassoc alt used)
4942 (incf alt)))
4943 (push (cons (car e) (or (car clist) alt)) new))))
4944 (nreverse new)))
4946 ;;; Some variables used in various places
4948 (defvar org-window-configuration nil
4949 "Used in various places to store a window configuration.")
4950 (defvar org-selected-window nil
4951 "Used in various places to store a window configuration.")
4952 (defvar org-finish-function nil
4953 "Function to be called when `C-c C-c' is used.
4954 This is for getting out of special buffers like capture.")
4957 ;; FIXME: Occasionally check by commenting these, to make sure
4958 ;; no other functions uses these, forgetting to let-bind them.
4959 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4960 (defvar org-last-state)
4961 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4963 ;; Defined somewhere in this file, but used before definition.
4964 (defvar org-entities) ;; defined in org-entities.el
4965 (defvar org-struct-menu)
4966 (defvar org-org-menu)
4967 (defvar org-tbl-menu)
4969 ;;;; Define the Org-mode
4971 ;; We use a before-change function to check if a table might need
4972 ;; an update.
4973 (defvar org-table-may-need-update t
4974 "Indicates that a table might need an update.
4975 This variable is set by `org-before-change-function'.
4976 `org-table-align' sets it back to nil.")
4977 (defun org-before-change-function (beg end)
4978 "Every change indicates that a table might need an update."
4979 (setq org-table-may-need-update t))
4980 (defvar org-mode-map)
4981 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4982 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4983 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4984 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4985 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4986 (defvar org-table-buffer-is-an nil)
4988 (defvar bidi-paragraph-direction)
4989 (defvar buffer-face-mode-face)
4991 (require 'outline)
4992 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4993 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4994 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4996 ;; Other stuff we need.
4997 (require 'time-date)
4998 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4999 (require 'easymenu)
5000 (require 'overlay)
5002 ;; (require 'org-macs) moved higher up in the file before it is first used
5003 (require 'org-entities)
5004 ;; (require 'org-compat) moved higher up in the file before it is first used
5005 (require 'org-faces)
5006 (require 'org-list)
5007 (require 'org-pcomplete)
5008 (require 'org-src)
5009 (require 'org-footnote)
5011 ;; babel
5012 (require 'ob)
5014 ;;;###autoload
5015 (define-derived-mode org-mode outline-mode "Org"
5016 "Outline-based notes management and organizer, alias
5017 \"Carsten's outline-mode for keeping track of everything.\"
5019 Org-mode develops organizational tasks around a NOTES file which
5020 contains information about projects as plain text. Org-mode is
5021 implemented on top of outline-mode, which is ideal to keep the content
5022 of large files well structured. It supports ToDo items, deadlines and
5023 time stamps, which magically appear in the diary listing of the Emacs
5024 calendar. Tables are easily created with a built-in table editor.
5025 Plain text URL-like links connect to websites, emails (VM), Usenet
5026 messages (Gnus), BBDB entries, and any files related to the project.
5027 For printing and sharing of notes, an Org-mode file (or a part of it)
5028 can be exported as a structured ASCII or HTML file.
5030 The following commands are available:
5032 \\{org-mode-map}"
5034 ;; Get rid of Outline menus, they are not needed
5035 ;; Need to do this here because define-derived-mode sets up
5036 ;; the keymap so late. Still, it is a waste to call this each time
5037 ;; we switch another buffer into org-mode.
5038 (if (featurep 'xemacs)
5039 (when (boundp 'outline-mode-menu-heading)
5040 ;; Assume this is Greg's port, it uses easymenu
5041 (easy-menu-remove outline-mode-menu-heading)
5042 (easy-menu-remove outline-mode-menu-show)
5043 (easy-menu-remove outline-mode-menu-hide))
5044 (define-key org-mode-map [menu-bar headings] 'undefined)
5045 (define-key org-mode-map [menu-bar hide] 'undefined)
5046 (define-key org-mode-map [menu-bar show] 'undefined))
5048 (org-load-modules-maybe)
5049 (easy-menu-add org-org-menu)
5050 (easy-menu-add org-tbl-menu)
5051 (org-install-agenda-files-menu)
5052 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5053 (add-to-invisibility-spec '(org-cwidth))
5054 (add-to-invisibility-spec '(org-hide-block . t))
5055 (when (featurep 'xemacs)
5056 (org-set-local 'line-move-ignore-invisible t))
5057 (org-set-local 'outline-regexp org-outline-regexp)
5058 (org-set-local 'outline-level 'org-outline-level)
5059 (setq bidi-paragraph-direction 'left-to-right)
5060 (when (and org-ellipsis
5061 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5062 (fboundp 'make-glyph-code))
5063 (unless org-display-table
5064 (setq org-display-table (make-display-table)))
5065 (set-display-table-slot
5066 org-display-table 4
5067 (vconcat (mapcar
5068 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5069 org-ellipsis)))
5070 (if (stringp org-ellipsis) org-ellipsis "..."))))
5071 (setq buffer-display-table org-display-table))
5072 (org-set-regexps-and-options)
5073 (when (and org-tag-faces (not org-tags-special-faces-re))
5074 ;; tag faces set outside customize.... force initialization.
5075 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5076 ;; Calc embedded
5077 (org-set-local 'calc-embedded-open-mode "# ")
5078 (modify-syntax-entry ?@ "w")
5079 (modify-syntax-entry ?\" "\"")
5080 (if org-startup-truncated (setq truncate-lines t))
5081 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5082 (org-set-local 'font-lock-unfontify-region-function
5083 'org-unfontify-region)
5084 ;; Activate before-change-function
5085 (org-set-local 'org-table-may-need-update t)
5086 (org-add-hook 'before-change-functions 'org-before-change-function nil
5087 'local)
5088 ;; Check for running clock before killing a buffer
5089 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5090 ;; Initialize macros templates.
5091 (org-macro-initialize-templates)
5092 ;; Initialize radio targets.
5093 (org-update-radio-target-regexp)
5094 ;; Indentation.
5095 (org-set-local 'indent-line-function 'org-indent-line)
5096 (org-set-local 'indent-region-function 'org-indent-region)
5097 ;; Filling and auto-filling.
5098 (org-setup-filling)
5099 ;; Comments.
5100 (org-setup-comments-handling)
5101 ;; Beginning/end of defun
5102 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5103 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5104 ;; Next error for sparse trees
5105 (org-set-local 'next-error-function 'org-occur-next-match)
5106 ;; Make sure dependence stuff works reliably, even for users who set it
5107 ;; too late :-(
5108 (if org-enforce-todo-dependencies
5109 (add-hook 'org-blocker-hook
5110 'org-block-todo-from-children-or-siblings-or-parent)
5111 (remove-hook 'org-blocker-hook
5112 'org-block-todo-from-children-or-siblings-or-parent))
5113 (if org-enforce-todo-checkbox-dependencies
5114 (add-hook 'org-blocker-hook
5115 'org-block-todo-from-checkboxes)
5116 (remove-hook 'org-blocker-hook
5117 'org-block-todo-from-checkboxes))
5119 ;; Align options lines
5120 (org-set-local
5121 'align-mode-rules-list
5122 '((org-in-buffer-settings
5123 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5124 (modes . '(org-mode)))))
5126 ;; Imenu
5127 (org-set-local 'imenu-create-index-function
5128 'org-imenu-get-tree)
5130 ;; Make isearch reveal context
5131 (if (or (featurep 'xemacs)
5132 (not (boundp 'outline-isearch-open-invisible-function)))
5133 ;; Emacs 21 and XEmacs make use of the hook
5134 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5135 ;; Emacs 22 deals with this through a special variable
5136 (org-set-local 'outline-isearch-open-invisible-function
5137 (lambda (&rest ignore) (org-show-context 'isearch))))
5139 ;; Setup the pcomplete hooks
5140 (set (make-local-variable 'pcomplete-command-completion-function)
5141 'org-pcomplete-initial)
5142 (set (make-local-variable 'pcomplete-command-name-function)
5143 'org-command-at-point)
5144 (set (make-local-variable 'pcomplete-default-completion-function)
5145 'ignore)
5146 (set (make-local-variable 'pcomplete-parse-arguments-function)
5147 'org-parse-arguments)
5148 (set (make-local-variable 'pcomplete-termination-string) "")
5149 (when (>= emacs-major-version 23)
5150 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5152 ;; If empty file that did not turn on org-mode automatically, make it to.
5153 (if (and org-insert-mode-line-in-empty-file
5154 (org-called-interactively-p 'any)
5155 (= (point-min) (point-max)))
5156 (insert "# -*- mode: org -*-\n\n"))
5157 (unless org-inhibit-startup
5158 (and org-startup-with-beamer-mode (org-beamer-mode))
5159 (when org-startup-align-all-tables
5160 (let ((bmp (buffer-modified-p)))
5161 (org-table-map-tables 'org-table-align 'quietly)
5162 (set-buffer-modified-p bmp)))
5163 (when org-startup-with-inline-images
5164 (org-display-inline-images))
5165 (unless org-inhibit-startup-visibility-stuff
5166 (org-set-startup-visibility)))
5167 ;; Try to set org-hide correctly
5168 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5170 (when (fboundp 'abbrev-table-put)
5171 (abbrev-table-put org-mode-abbrev-table
5172 :parents (list text-mode-abbrev-table)))
5174 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5177 (defun org-find-invisible-foreground ()
5178 (let ((candidates (remove
5179 "unspecified-bg"
5180 (nconc
5181 (list (face-background 'default)
5182 (face-background 'org-default))
5183 (mapcar
5184 (lambda (alist)
5185 (when (boundp alist)
5186 (cdr (assoc 'background-color (symbol-value alist)))))
5187 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5188 (list (face-foreground 'org-hide))))))
5189 (car (remove nil candidates))))
5191 (defun org-current-time (&optional rounding-minutes)
5192 "Current time, possibly rounded to ROUNDING-MINUTES.
5193 When ROUNDING-MINUTES is not an integer, fall back on the car of
5194 `org-time-stamp-rounding-minutes'."
5195 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5196 (car org-time-stamp-rounding-minutes)))
5197 (time (decode-time)))
5198 (if (> r 1)
5199 (apply 'encode-time
5200 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5201 (nthcdr 2 time)))
5202 (current-time))))
5204 (defun org-today ()
5205 "Return today date, considering `org-extend-today-until'."
5206 (time-to-days
5207 (time-subtract (current-time)
5208 (list 0 (* 3600 org-extend-today-until) 0))))
5210 ;;;; Font-Lock stuff, including the activators
5212 (defvar org-mouse-map (make-sparse-keymap))
5213 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5214 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5215 (when org-mouse-1-follows-link
5216 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5217 (when org-tab-follows-link
5218 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5219 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5221 (require 'font-lock)
5223 (defconst org-non-link-chars "]\t\n\r<>")
5224 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5225 "shell" "elisp" "doi" "message"))
5226 (defvar org-link-types-re nil
5227 "Matches a link that has a url-like prefix like \"http:\"")
5228 (defvar org-link-re-with-space nil
5229 "Matches a link with spaces, optional angular brackets around it.")
5230 (defvar org-link-re-with-space2 nil
5231 "Matches a link with spaces, optional angular brackets around it.")
5232 (defvar org-link-re-with-space3 nil
5233 "Matches a link with spaces, only for internal part in bracket links.")
5234 (defvar org-angle-link-re nil
5235 "Matches link with angular brackets, spaces are allowed.")
5236 (defvar org-plain-link-re nil
5237 "Matches plain link, without spaces.")
5238 (defvar org-bracket-link-regexp nil
5239 "Matches a link in double brackets.")
5240 (defvar org-bracket-link-analytic-regexp nil
5241 "Regular expression used to analyze links.
5242 Here is what the match groups contain after a match:
5243 1: http:
5244 2: http
5245 3: path
5246 4: [desc]
5247 5: desc")
5248 (defvar org-bracket-link-analytic-regexp++ nil
5249 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5250 (defvar org-any-link-re nil
5251 "Regular expression matching any link.")
5253 (defcustom org-match-sexp-depth 3
5254 "Number of stacked braces for sub/superscript matching.
5255 This has to be set before loading org.el to be effective."
5256 :group 'org-export-translation ; ??????????????????????????/
5257 :type 'integer)
5259 (defun org-create-multibrace-regexp (left right n)
5260 "Create a regular expression which will match a balanced sexp.
5261 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5262 as single character strings.
5263 The regexp returned will match the entire expression including the
5264 delimiters. It will also define a single group which contains the
5265 match except for the outermost delimiters. The maximum depth of
5266 stacked delimiters is N. Escaping delimiters is not possible."
5267 (let* ((nothing (concat "[^" left right "]*?"))
5268 (or "\\|")
5269 (re nothing)
5270 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5271 (while (> n 1)
5272 (setq n (1- n)
5273 re (concat re or next)
5274 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5275 (concat left "\\(" re "\\)" right)))
5277 (defvar org-match-substring-regexp
5278 (concat
5279 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5280 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5281 "\\|"
5282 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5283 "\\|"
5284 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5285 "The regular expression matching a sub- or superscript.")
5287 (defvar org-match-substring-with-braces-regexp
5288 (concat
5289 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5290 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5291 "\\)")
5292 "The regular expression matching a sub- or superscript, forcing braces.")
5294 (defun org-make-link-regexps ()
5295 "Update the link regular expressions.
5296 This should be called after the variable `org-link-types' has changed."
5297 (setq org-link-types-re
5298 (concat
5299 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5300 org-link-re-with-space
5301 (concat
5302 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5303 "\\([^" org-non-link-chars " ]"
5304 "[^" org-non-link-chars "]*"
5305 "[^" org-non-link-chars " ]\\)>?")
5306 org-link-re-with-space2
5307 (concat
5308 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5309 "\\([^" org-non-link-chars " ]"
5310 "[^\t\n\r]*"
5311 "[^" org-non-link-chars " ]\\)>?")
5312 org-link-re-with-space3
5313 (concat
5314 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5315 "\\([^" org-non-link-chars " ]"
5316 "[^\t\n\r]*\\)")
5317 org-angle-link-re
5318 (concat
5319 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5320 "\\([^" org-non-link-chars " ]"
5321 "[^" org-non-link-chars "]*"
5322 "\\)>")
5323 org-plain-link-re
5324 (concat
5325 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5326 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5327 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5328 org-bracket-link-regexp
5329 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5330 org-bracket-link-analytic-regexp
5331 (concat
5332 "\\[\\["
5333 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5334 "\\([^]]+\\)"
5335 "\\]"
5336 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5337 "\\]")
5338 org-bracket-link-analytic-regexp++
5339 (concat
5340 "\\[\\["
5341 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5342 "\\([^]]+\\)"
5343 "\\]"
5344 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5345 "\\]")
5346 org-any-link-re
5347 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5348 org-angle-link-re "\\)\\|\\("
5349 org-plain-link-re "\\)")))
5351 (org-make-link-regexps)
5353 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5354 "Regular expression for fast time stamp matching.")
5355 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5356 "Regular expression for fast time stamp matching.")
5357 (defconst org-ts-regexp0
5358 "\\(\\([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 This one does not require the space after the date, so it can be used
5361 on a string that terminates immediately after the date.")
5362 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5363 "Regular expression matching time strings for analysis.")
5364 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5365 "Regular expression matching time stamps, with groups.")
5366 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5367 "Regular expression matching time stamps (also [..]), with groups.")
5368 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5369 "Regular expression matching a time stamp range.")
5370 (defconst org-tr-regexp-both
5371 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5372 "Regular expression matching a time stamp range.")
5373 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5374 org-ts-regexp "\\)?")
5375 "Regular expression matching a time stamp or time stamp range.")
5376 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5377 org-ts-regexp-both "\\)?")
5378 "Regular expression matching a time stamp or time stamp range.
5379 The time stamps may be either active or inactive.")
5381 (defvar org-emph-face nil)
5383 (defun org-do-emphasis-faces (limit)
5384 "Run through the buffer and add overlays to emphasized strings."
5385 (let (rtn a)
5386 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5387 (if (not (= (char-after (match-beginning 3))
5388 (char-after (match-beginning 4))))
5389 (progn
5390 (setq rtn t)
5391 (setq a (assoc (match-string 3) org-emphasis-alist))
5392 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5393 'face
5394 (nth 1 a))
5395 (and (nth 4 a)
5396 (org-remove-flyspell-overlays-in
5397 (match-beginning 0) (match-end 0)))
5398 (add-text-properties (match-beginning 2) (match-end 2)
5399 '(font-lock-multiline t org-emphasis t))
5400 (when org-hide-emphasis-markers
5401 (add-text-properties (match-end 4) (match-beginning 5)
5402 '(invisible org-link))
5403 (add-text-properties (match-beginning 3) (match-end 3)
5404 '(invisible org-link)))))
5405 (backward-char 1))
5406 rtn))
5408 (defun org-emphasize (&optional char)
5409 "Insert or change an emphasis, i.e. a font like bold or italic.
5410 If there is an active region, change that region to a new emphasis.
5411 If there is no region, just insert the marker characters and position
5412 the cursor between them.
5413 CHAR should be either the marker character, or the first character of the
5414 HTML tag associated with that emphasis. If CHAR is a space, the means
5415 to remove the emphasis of the selected region.
5416 If char is not given (for example in an interactive call) it
5417 will be prompted for."
5418 (interactive)
5419 (let ((eal org-emphasis-alist) e det
5420 (erc org-emphasis-regexp-components)
5421 (prompt "")
5422 (string "") beg end move tag c s)
5423 (if (org-region-active-p)
5424 (setq beg (region-beginning) end (region-end)
5425 string (buffer-substring beg end))
5426 (setq move t))
5428 (while (setq e (pop eal))
5429 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5430 c (aref tag 0))
5431 (push (cons c (string-to-char (car e))) det)
5432 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5433 (substring tag 1)))))
5434 (setq det (nreverse det))
5435 (unless char
5436 (message "%s" (concat "Emphasis marker or tag:" prompt))
5437 (setq char (read-char-exclusive)))
5438 (setq char (or (cdr (assoc char det)) char))
5439 (if (equal char ?\ )
5440 (setq s "" move nil)
5441 (unless (assoc (char-to-string char) org-emphasis-alist)
5442 (error "No such emphasis marker: \"%c\"" char))
5443 (setq s (char-to-string char)))
5444 (while (and (> (length string) 1)
5445 (equal (substring string 0 1) (substring string -1))
5446 (assoc (substring string 0 1) org-emphasis-alist))
5447 (setq string (substring string 1 -1)))
5448 (setq string (concat s string s))
5449 (if beg (delete-region beg end))
5450 (unless (or (bolp)
5451 (string-match (concat "[" (nth 0 erc) "\n]")
5452 (char-to-string (char-before (point)))))
5453 (insert " "))
5454 (unless (or (eobp)
5455 (string-match (concat "[" (nth 1 erc) "\n]")
5456 (char-to-string (char-after (point)))))
5457 (insert " ") (backward-char 1))
5458 (insert string)
5459 (and move (backward-char 1))))
5461 (defconst org-nonsticky-props
5462 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5464 (defsubst org-rear-nonsticky-at (pos)
5465 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5467 (defun org-activate-plain-links (limit)
5468 "Run through the buffer and add overlays to links."
5469 (catch 'exit
5470 (let (f hl)
5471 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5472 (not (org-in-src-block-p)))
5473 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5474 (setq f (get-text-property (match-beginning 0) 'face))
5475 (setq hl (org-match-string-no-properties 0))
5476 (if (or (eq f 'org-tag)
5477 (and (listp f) (memq 'org-tag f)))
5479 (add-text-properties (match-beginning 0) (match-end 0)
5480 (list 'mouse-face 'highlight
5481 'face 'org-link
5482 'htmlize-link `(:uri ,hl)
5483 'keymap org-mouse-map))
5484 (org-rear-nonsticky-at (match-end 0)))
5485 t))))
5487 (defun org-activate-code (limit)
5488 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5489 (progn
5490 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5491 (remove-text-properties (match-beginning 0) (match-end 0)
5492 '(display t invisible t intangible t))
5493 t)))
5495 (defcustom org-src-fontify-natively nil
5496 "When non-nil, fontify code in code blocks."
5497 :type 'boolean
5498 :version "24.1"
5499 :group 'org-appearance
5500 :group 'org-babel)
5502 (defcustom org-allow-promoting-top-level-subtree nil
5503 "When non-nil, allow promoting a top level subtree.
5504 The leading star of the top level headline will be replaced
5505 by a #."
5506 :type 'boolean
5507 :version "24.1"
5508 :group 'org-appearance)
5510 (defun org-fontify-meta-lines-and-blocks (limit)
5511 (condition-case nil
5512 (org-fontify-meta-lines-and-blocks-1 limit)
5513 (error (message "org-mode fontification error"))))
5515 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5516 "Fontify #+ lines and blocks, in the correct ways."
5517 (let ((case-fold-search t))
5518 (if (re-search-forward
5519 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5520 limit t)
5521 (let ((beg (match-beginning 0))
5522 (block-start (match-end 0))
5523 (block-end nil)
5524 (lang (match-string 7))
5525 (beg1 (line-beginning-position 2))
5526 (dc1 (downcase (match-string 2)))
5527 (dc3 (downcase (match-string 3)))
5528 end end1 quoting block-type ovl)
5529 (cond
5530 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5531 ;; a single line of backend-specific content
5532 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5533 (remove-text-properties (match-beginning 0) (match-end 0)
5534 '(display t invisible t intangible t))
5535 (add-text-properties (match-beginning 1) (match-end 3)
5536 '(font-lock-fontified t face org-meta-line))
5537 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5538 '(font-lock-fontified t face org-block))
5539 ; for backend-specific code
5541 ((and (match-end 4) (equal dc3 "+begin"))
5542 ;; Truly a block
5543 (setq block-type (downcase (match-string 5))
5544 quoting (member block-type org-protecting-blocks))
5545 (when (re-search-forward
5546 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5547 nil t) ;; on purpose, we look further than LIMIT
5548 (setq end (min (point-max) (match-end 0))
5549 end1 (min (point-max) (1- (match-beginning 0))))
5550 (setq block-end (match-beginning 0))
5551 (when quoting
5552 (remove-text-properties beg end
5553 '(display t invisible t intangible t)))
5554 (add-text-properties
5555 beg end
5556 '(font-lock-fontified t font-lock-multiline t))
5557 (add-text-properties beg beg1 '(face org-meta-line))
5558 (add-text-properties end1 (min (point-max) (1+ end))
5559 '(face org-meta-line)) ; for end_src
5560 (cond
5561 ((and lang (not (string= lang "")) org-src-fontify-natively)
5562 (org-src-font-lock-fontify-block lang block-start block-end)
5563 ;; remove old background overlays
5564 (mapc (lambda (ov)
5565 (if (eq (overlay-get ov 'face) 'org-block-background)
5566 (delete-overlay ov)))
5567 (overlays-at (/ (+ beg1 block-end) 2)))
5568 ;; add a background overlay
5569 (setq ovl (make-overlay beg1 block-end))
5570 (overlay-put ovl 'face 'org-block-background)
5571 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5572 (quoting
5573 (add-text-properties beg1 (min (point-max) (1+ end1))
5574 '(face org-block))) ; end of source block
5575 ((not org-fontify-quote-and-verse-blocks))
5576 ((string= block-type "quote")
5577 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5578 ((string= block-type "verse")
5579 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5580 (add-text-properties beg beg1 '(face org-block-begin-line))
5581 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5582 '(face org-block-end-line))
5584 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5585 (add-text-properties
5586 beg (match-end 3)
5587 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5588 '(font-lock-fontified t invisible t)
5589 '(font-lock-fontified t face org-document-info-keyword)))
5590 (add-text-properties
5591 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5592 (if (string-equal dc1 "+title:")
5593 '(font-lock-fontified t face org-document-title)
5594 '(font-lock-fontified t face org-document-info))))
5595 ((or (equal dc1 "+results")
5596 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5597 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5598 "+call:" "+header:" "+headers:" "+name:"))
5599 (and (match-end 4) (equal dc3 "+attr")))
5600 (add-text-properties
5601 beg (match-end 0)
5602 '(font-lock-fontified t face org-meta-line))
5604 ((member dc3 '(" " ""))
5605 (add-text-properties
5606 beg (match-end 0)
5607 '(font-lock-fontified t face font-lock-comment-face)))
5608 ((not (member (char-after beg) '(?\ ?\t)))
5609 ;; just any other in-buffer setting, but not indented
5610 (add-text-properties
5611 beg (match-end 0)
5612 '(font-lock-fontified t face org-meta-line))
5614 (t nil))))))
5616 (defun org-activate-angle-links (limit)
5617 "Run through the buffer and add overlays to links."
5618 (if (and (re-search-forward org-angle-link-re limit t)
5619 (not (org-in-src-block-p)))
5620 (progn
5621 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5622 (add-text-properties (match-beginning 0) (match-end 0)
5623 (list 'mouse-face 'highlight
5624 'keymap org-mouse-map))
5625 (org-rear-nonsticky-at (match-end 0))
5626 t)))
5628 (defun org-activate-footnote-links (limit)
5629 "Run through the buffer and add overlays to footnotes."
5630 (let ((fn (org-footnote-next-reference-or-definition limit)))
5631 (when fn
5632 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5633 (org-remove-flyspell-overlays-in beg end)
5634 (add-text-properties beg end
5635 (list 'mouse-face 'highlight
5636 'keymap org-mouse-map
5637 'help-echo
5638 (if (= (point-at-bol) beg)
5639 "Footnote definition"
5640 "Footnote reference")
5641 'font-lock-fontified t
5642 'font-lock-multiline t
5643 'face 'org-footnote))))))
5645 (defun org-activate-bracket-links (limit)
5646 "Run through the buffer and add overlays to bracketed links."
5647 (if (and (re-search-forward org-bracket-link-regexp limit t)
5648 (not (org-in-src-block-p)))
5649 (let* ((hl (org-match-string-no-properties 1))
5650 (help (concat "LINK: " hl))
5651 ;; FIXME: Above we should remove the escapes. But that
5652 ;; requires another match, protecting match data, a lot
5653 ;; of overhead for font-lock.
5654 (ip (org-maybe-intangible
5655 (list 'invisible 'org-link
5656 'keymap org-mouse-map 'mouse-face 'highlight
5657 'font-lock-multiline t 'help-echo help
5658 'htmlize-link `(:uri ,hl))))
5659 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5660 'font-lock-multiline t 'help-echo help
5661 'htmlize-link `(:uri ,hl))))
5662 ;; We need to remove the invisible property here. Table narrowing
5663 ;; may have made some of this invisible.
5664 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5665 (remove-text-properties (match-beginning 0) (match-end 0)
5666 '(invisible nil))
5667 (if (match-end 3)
5668 (progn
5669 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5670 (org-rear-nonsticky-at (match-beginning 3))
5671 (add-text-properties (match-beginning 3) (match-end 3) vp)
5672 (org-rear-nonsticky-at (match-end 3))
5673 (add-text-properties (match-end 3) (match-end 0) ip)
5674 (org-rear-nonsticky-at (match-end 0)))
5675 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5676 (org-rear-nonsticky-at (match-beginning 1))
5677 (add-text-properties (match-beginning 1) (match-end 1) vp)
5678 (org-rear-nonsticky-at (match-end 1))
5679 (add-text-properties (match-end 1) (match-end 0) ip)
5680 (org-rear-nonsticky-at (match-end 0)))
5681 t)))
5683 (defun org-activate-dates (limit)
5684 "Run through the buffer and add overlays to dates."
5685 (if (re-search-forward org-tsr-regexp-both limit t)
5686 (progn
5687 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5688 (add-text-properties (match-beginning 0) (match-end 0)
5689 (list 'mouse-face 'highlight
5690 'keymap org-mouse-map))
5691 (org-rear-nonsticky-at (match-end 0))
5692 (when org-display-custom-times
5693 (if (match-end 3)
5694 (org-display-custom-time (match-beginning 3) (match-end 3)))
5695 (org-display-custom-time (match-beginning 1) (match-end 1)))
5696 t)))
5698 (defvar org-target-link-regexp nil
5699 "Regular expression matching radio targets in plain text.")
5700 (make-variable-buffer-local 'org-target-link-regexp)
5701 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5702 "Regular expression matching a link target.")
5703 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5704 "Regular expression matching a radio target.")
5705 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5706 "Regular expression matching any target.")
5708 (defun org-activate-target-links (limit)
5709 "Run through the buffer and add overlays to target matches."
5710 (when org-target-link-regexp
5711 (let ((case-fold-search t))
5712 (if (re-search-forward org-target-link-regexp limit t)
5713 (progn
5714 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5715 (add-text-properties (match-beginning 0) (match-end 0)
5716 (list 'mouse-face 'highlight
5717 'keymap org-mouse-map
5718 'help-echo "Radio target link"
5719 'org-linked-text t))
5720 (org-rear-nonsticky-at (match-end 0))
5721 t)))))
5723 (defun org-update-radio-target-regexp ()
5724 "Find all radio targets in this file and update the regular expression."
5725 (interactive)
5726 (when (memq 'radio org-activate-links)
5727 (setq org-target-link-regexp
5728 (org-make-target-link-regexp (org-all-targets 'radio)))
5729 (org-restart-font-lock)))
5731 (defun org-hide-wide-columns (limit)
5732 (let (s e)
5733 (setq s (text-property-any (point) (or limit (point-max))
5734 'org-cwidth t))
5735 (when s
5736 (setq e (next-single-property-change s 'org-cwidth))
5737 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5738 (goto-char e)
5739 t)))
5741 (defvar org-latex-and-specials-regexp nil
5742 "Regular expression for highlighting export special stuff.")
5743 (defvar org-match-substring-regexp)
5744 (defvar org-match-substring-with-braces-regexp)
5746 ;; This should be with the exporter code, but we also use if for font-locking
5747 (defconst org-export-html-special-string-regexps
5748 '(("\\\\-" . "&shy;")
5749 ("---\\([^-]\\)" . "&mdash;\\1")
5750 ("--\\([^-]\\)" . "&ndash;\\1")
5751 ("\\.\\.\\." . "&hellip;"))
5752 "Regular expressions for special string conversion.")
5755 (defun org-compute-latex-and-specials-regexp ()
5756 "Compute regular expression for stuff treated specially by exporters."
5757 (if (not org-highlight-latex-fragments-and-specials)
5758 (org-set-local 'org-latex-and-specials-regexp nil)
5759 (require 'org-exp)
5760 (let*
5761 ((matchers (plist-get org-format-latex-options :matchers))
5762 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5763 org-latex-regexps)))
5764 (org-export-allow-BIND nil)
5765 (options (org-combine-plists (org-default-export-plist)
5766 (org-infile-export-plist)))
5767 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5768 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5769 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5770 (org-export-html-expand (plist-get options :expand-quoted-html))
5771 (org-export-with-special-strings (plist-get options :special-strings))
5772 (re-sub
5773 (cond
5774 ((equal org-export-with-sub-superscripts '{})
5775 (list org-match-substring-with-braces-regexp))
5776 (org-export-with-sub-superscripts
5777 (list org-match-substring-regexp))))
5778 (re-latex
5779 (if org-export-with-LaTeX-fragments
5780 (mapcar (lambda (x) (nth 1 x)) latexs)))
5781 (re-macros
5782 (if org-export-with-TeX-macros
5783 (list (concat "\\\\"
5784 (regexp-opt
5785 (append
5787 (delq nil
5788 (mapcar 'car-safe
5789 (append org-entities-user
5790 org-entities)))
5791 (if (boundp 'org-latex-entities)
5792 (mapcar (lambda (x)
5793 (or (car-safe x) x))
5794 org-latex-entities)
5795 nil))
5796 'words))) ; FIXME
5798 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5799 (re-special (if org-export-with-special-strings
5800 (mapcar (lambda (x) (car x))
5801 org-export-html-special-string-regexps)))
5802 (re-rest
5803 (delq nil
5804 (list
5805 (if org-export-html-expand "@<[^>\n]+>")
5806 ))))
5807 (org-set-local
5808 'org-latex-and-specials-regexp
5809 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5810 re-rest) "\\|")))))
5812 (defun org-do-latex-and-special-faces (limit)
5813 "Run through the buffer and add overlays to links."
5814 (when org-latex-and-specials-regexp
5815 (let (rtn d)
5816 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5817 limit t))
5818 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5819 'face))
5820 '(org-code org-verbatim underline)))
5821 (progn
5822 (setq rtn t
5823 d (cond ((member (char-after (1+ (match-beginning 0)))
5824 '(?_ ?^)) 1)
5825 (t 0)))
5826 (font-lock-prepend-text-property
5827 (+ d (match-beginning 0)) (match-end 0)
5828 'face 'org-latex-and-export-specials)
5829 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5830 '(font-lock-multiline t)))))
5831 rtn)))
5833 (defun org-restart-font-lock ()
5834 "Restart `font-lock-mode', to force refontification."
5835 (when (and (boundp 'font-lock-mode) font-lock-mode)
5836 (font-lock-mode -1)
5837 (font-lock-mode 1)))
5839 (defun org-all-targets (&optional radio)
5840 "Return a list of all targets in this file.
5841 When optional argument RADIO is non-nil, only find radio
5842 targets."
5843 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5844 (save-excursion
5845 (goto-char (point-min))
5846 (while (re-search-forward re nil t)
5847 ;; Make sure point is really within the object.
5848 (backward-char)
5849 (let ((obj (org-element-context)))
5850 (when (memq (org-element-type obj) '(radio-target target))
5851 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5852 rtn)))
5854 (defun org-make-target-link-regexp (targets)
5855 "Make regular expression matching all strings in TARGETS.
5856 The regular expression finds the targets also if there is a line break
5857 between words."
5858 (and targets
5859 (concat
5860 "\\<\\("
5861 (mapconcat
5862 (lambda (x)
5863 (setq x (regexp-quote x))
5864 (while (string-match " +" x)
5865 (setq x (replace-match "\\s-+" t t x)))
5867 targets
5868 "\\|")
5869 "\\)\\>")))
5871 (defun org-activate-tags (limit)
5872 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5873 (progn
5874 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5875 (add-text-properties (match-beginning 1) (match-end 1)
5876 (list 'mouse-face 'highlight
5877 'keymap org-mouse-map))
5878 (org-rear-nonsticky-at (match-end 1))
5879 t)))
5881 (defun org-outline-level ()
5882 "Compute the outline level of the heading at point.
5883 If this is called at a normal headline, the level is the number of stars.
5884 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5885 (save-excursion
5886 (if (not (condition-case nil
5887 (org-back-to-heading t)
5888 (error nil)))
5890 (looking-at org-outline-regexp)
5891 (1- (- (match-end 0) (match-beginning 0))))))
5893 (defvar org-font-lock-keywords nil)
5895 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5896 "Regular expression matching a property line.")
5898 (defvar org-font-lock-hook nil
5899 "Functions to be called for special font lock stuff.")
5901 (defvar org-font-lock-set-keywords-hook nil
5902 "Functions that can manipulate `org-font-lock-extra-keywords'.
5903 This is called after `org-font-lock-extra-keywords' is defined, but before
5904 it is installed to be used by font lock. This can be useful if something
5905 needs to be inserted at a specific position in the font-lock sequence.")
5907 (defun org-font-lock-hook (limit)
5908 "Run `org-font-lock-hook' within LIMIT."
5909 (run-hook-with-args 'org-font-lock-hook limit))
5911 (defun org-set-font-lock-defaults ()
5912 "Set font lock defaults for the current buffer."
5913 (let* ((em org-fontify-emphasized-text)
5914 (lk org-activate-links)
5915 (org-font-lock-extra-keywords
5916 (list
5917 ;; Call the hook
5918 '(org-font-lock-hook)
5919 ;; Headlines
5920 `(,(if org-fontify-whole-heading-line
5921 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5922 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5923 (1 (org-get-level-face 1))
5924 (2 (org-get-level-face 2))
5925 (3 (org-get-level-face 3)))
5926 ;; Table lines
5927 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5928 (1 'org-table t))
5929 ;; Table internals
5930 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5931 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5932 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5933 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5934 ;; Drawers
5935 (list org-drawer-regexp '(0 'org-special-keyword t))
5936 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5937 ;; Properties
5938 (list org-property-re
5939 '(1 'org-special-keyword t)
5940 '(3 'org-property-value t))
5941 ;; Links
5942 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5943 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5944 (if (memq 'plain lk) '(org-activate-plain-links))
5945 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5946 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5947 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5948 (if (memq 'footnote lk) '(org-activate-footnote-links))
5949 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5950 '(org-hide-wide-columns (0 nil append))
5951 ;; TODO keyword
5952 (list (format org-heading-keyword-regexp-format
5953 org-todo-regexp)
5954 '(2 (org-get-todo-face 2) t))
5955 ;; DONE
5956 (if org-fontify-done-headline
5957 (list (format org-heading-keyword-regexp-format
5958 (concat
5959 "\\(?:"
5960 (mapconcat 'regexp-quote org-done-keywords "\\|")
5961 "\\)"))
5962 '(2 'org-headline-done t))
5963 nil)
5964 ;; Priorities
5965 '(org-font-lock-add-priority-faces)
5966 ;; Tags
5967 '(org-font-lock-add-tag-faces)
5968 ;; Special keywords
5969 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5970 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5971 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5972 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5973 ;; Emphasis
5974 (if em
5975 (if (featurep 'xemacs)
5976 '(org-do-emphasis-faces (0 nil append))
5977 '(org-do-emphasis-faces)))
5978 ;; Checkboxes
5979 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5980 1 'org-checkbox prepend)
5981 (if (cdr (assq 'checkbox org-list-automatic-rules))
5982 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5983 (0 (org-get-checkbox-statistics-face) t)))
5984 ;; Description list items
5985 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5986 1 'org-list-dt prepend)
5987 ;; ARCHIVEd headings
5988 (list (concat
5989 org-outline-regexp-bol
5990 "\\(.*:" org-archive-tag ":.*\\)")
5991 '(1 'org-archived prepend))
5992 ;; Specials
5993 '(org-do-latex-and-special-faces)
5994 '(org-fontify-entities)
5995 '(org-raise-scripts)
5996 ;; Code
5997 '(org-activate-code (1 'org-code t))
5998 ;; COMMENT
5999 (list (format org-heading-keyword-regexp-format
6000 (concat "\\("
6001 org-comment-string "\\|" org-quote-string
6002 "\\)"))
6003 '(2 'org-special-keyword t))
6004 ;; Blocks and meta lines
6005 '(org-fontify-meta-lines-and-blocks)
6007 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6008 (run-hooks 'org-font-lock-set-keywords-hook)
6009 ;; Now set the full font-lock-keywords
6010 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6011 (org-set-local 'font-lock-defaults
6012 '(org-font-lock-keywords t nil nil backward-paragraph))
6013 (kill-local-variable 'font-lock-keywords) nil))
6015 (defun org-toggle-pretty-entities ()
6016 "Toggle the composition display of entities as UTF8 characters."
6017 (interactive)
6018 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6019 (org-restart-font-lock)
6020 (if org-pretty-entities
6021 (message "Entities are displayed as UTF8 characters")
6022 (save-restriction
6023 (widen)
6024 (org-decompose-region (point-min) (point-max))
6025 (message "Entities are displayed plain"))))
6027 (defvar org-custom-properties-overlays nil
6028 "List of overlays used for custom properties.")
6029 (make-variable-buffer-local 'org-custom-properties-overlays)
6031 (defun org-toggle-custom-properties-visibility ()
6032 "Display or hide properties in `org-custom-properties'."
6033 (interactive)
6034 (if org-custom-properties-overlays
6035 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6036 (setq org-custom-properties-overlays nil))
6037 (unless (not org-custom-properties)
6038 (save-excursion
6039 (save-restriction
6040 (widen)
6041 (goto-char (point-min))
6042 (while (re-search-forward org-property-re nil t)
6043 (mapc (lambda(p)
6044 (when (equal p (substring (match-string 1) 1 -1))
6045 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6046 (overlay-put o 'invisible t)
6047 (overlay-put o 'org-custom-property t)
6048 (push o org-custom-properties-overlays))))
6049 org-custom-properties)))))))
6051 (defun org-fontify-entities (limit)
6052 "Find an entity to fontify."
6053 (let (ee)
6054 (when org-pretty-entities
6055 (catch 'match
6056 (while (re-search-forward
6057 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6058 limit t)
6059 (if (and (not (org-in-indented-comment-line))
6060 (setq ee (org-entity-get (match-string 1)))
6061 (= (length (nth 6 ee)) 1))
6062 (let*
6063 ((end (if (equal (match-string 2) "{}")
6064 (match-end 2)
6065 (match-end 1))))
6066 (add-text-properties
6067 (match-beginning 0) end
6068 (list 'font-lock-fontified t))
6069 (compose-region (match-beginning 0) end
6070 (nth 6 ee) nil)
6071 (backward-char 1)
6072 (throw 'match t))))
6073 nil))))
6075 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6076 "Fontify string S like in Org-mode."
6077 (with-temp-buffer
6078 (insert s)
6079 (let ((org-odd-levels-only odd-levels))
6080 (org-mode)
6081 (font-lock-fontify-buffer)
6082 (buffer-string))))
6084 (defvar org-m nil)
6085 (defvar org-l nil)
6086 (defvar org-f nil)
6087 (defun org-get-level-face (n)
6088 "Get the right face for match N in font-lock matching of headlines."
6089 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6090 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6091 (if org-cycle-level-faces
6092 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6093 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6094 (cond
6095 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6096 ((eq n 2) org-f)
6097 (t (if org-level-color-stars-only nil org-f))))
6100 (defun org-get-todo-face (kwd)
6101 "Get the right face for a TODO keyword KWD.
6102 If KWD is a number, get the corresponding match group."
6103 (if (numberp kwd) (setq kwd (match-string kwd)))
6104 (or (org-face-from-face-or-color
6105 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6106 (and (member kwd org-done-keywords) 'org-done)
6107 'org-todo))
6109 (defun org-face-from-face-or-color (context inherit face-or-color)
6110 "Create a face list that inherits INHERIT, but sets the foreground color.
6111 When FACE-OR-COLOR is not a string, just return it."
6112 (if (stringp face-or-color)
6113 (list :inherit inherit
6114 (cdr (assoc context org-faces-easy-properties))
6115 face-or-color)
6116 face-or-color))
6118 (defun org-font-lock-add-tag-faces (limit)
6119 "Add the special tag faces."
6120 (when (and org-tag-faces org-tags-special-faces-re)
6121 (while (re-search-forward org-tags-special-faces-re limit t)
6122 (add-text-properties (match-beginning 1) (match-end 1)
6123 (list 'face (org-get-tag-face 1)
6124 'font-lock-fontified t))
6125 (backward-char 1))))
6127 (defun org-font-lock-add-priority-faces (limit)
6128 "Add the special priority faces."
6129 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6130 (when (save-match-data (org-at-heading-p))
6131 (add-text-properties
6132 (match-beginning 0) (match-end 0)
6133 (list 'face (or (org-face-from-face-or-color
6134 'priority 'org-priority
6135 (cdr (assoc (char-after (match-beginning 1))
6136 org-priority-faces)))
6137 'org-priority)
6138 'font-lock-fontified t)))))
6140 (defun org-get-tag-face (kwd)
6141 "Get the right face for a TODO keyword KWD.
6142 If KWD is a number, get the corresponding match group."
6143 (if (numberp kwd) (setq kwd (match-string kwd)))
6144 (or (org-face-from-face-or-color
6145 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6146 'org-tag))
6148 (defun org-unfontify-region (beg end &optional maybe_loudly)
6149 "Remove fontification and activation overlays from links."
6150 (font-lock-default-unfontify-region beg end)
6151 (let* ((buffer-undo-list t)
6152 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6153 (inhibit-modification-hooks t)
6154 deactivate-mark buffer-file-name buffer-file-truename)
6155 (org-decompose-region beg end)
6156 (remove-text-properties beg end
6157 '(mouse-face t keymap t org-linked-text t
6158 invisible t intangible t
6159 org-no-flyspell t org-emphasis t))
6160 (org-remove-font-lock-display-properties beg end)))
6162 (defconst org-script-display '(((raise -0.3) (height 0.7))
6163 ((raise 0.3) (height 0.7))
6164 ((raise -0.5))
6165 ((raise 0.5)))
6166 "Display properties for showing superscripts and subscripts.")
6168 (defun org-remove-font-lock-display-properties (beg end)
6169 "Remove specific display properties that have been added by font lock.
6170 The will remove the raise properties that are used to show superscripts
6171 and subscripts."
6172 (let (next prop)
6173 (while (< beg end)
6174 (setq next (next-single-property-change beg 'display nil end)
6175 prop (get-text-property beg 'display))
6176 (if (member prop org-script-display)
6177 (put-text-property beg next 'display nil))
6178 (setq beg next))))
6180 (defun org-raise-scripts (limit)
6181 "Add raise properties to sub/superscripts."
6182 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6183 (if (re-search-forward
6184 (if (eq org-use-sub-superscripts t)
6185 org-match-substring-regexp
6186 org-match-substring-with-braces-regexp)
6187 limit t)
6188 (let* ((pos (point)) table-p comment-p
6189 (mpos (match-beginning 3))
6190 (emph-p (get-text-property mpos 'org-emphasis))
6191 (link-p (get-text-property mpos 'mouse-face))
6192 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6193 (goto-char (point-at-bol))
6194 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6195 comment-p (org-looking-at-p "[ \t]*#"))
6196 (goto-char pos)
6197 ;; FIXME: Should we go back one character here, for a_b^c
6198 ;; (goto-char (1- pos)) ;????????????????????
6199 (if (or comment-p emph-p link-p keyw-p)
6201 (put-text-property (match-beginning 3) (match-end 0)
6202 'display
6203 (if (equal (char-after (match-beginning 2)) ?^)
6204 (nth (if table-p 3 1) org-script-display)
6205 (nth (if table-p 2 0) org-script-display)))
6206 (add-text-properties (match-beginning 2) (match-end 2)
6207 (list 'invisible t
6208 'org-dwidth t 'org-dwidth-n 1))
6209 (if (and (eq (char-after (match-beginning 3)) ?{)
6210 (eq (char-before (match-end 3)) ?}))
6211 (progn
6212 (add-text-properties
6213 (match-beginning 3) (1+ (match-beginning 3))
6214 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6215 (add-text-properties
6216 (1- (match-end 3)) (match-end 3)
6217 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6218 t)))))
6220 ;;;; Visibility cycling, including org-goto and indirect buffer
6222 ;;; Cycling
6224 (defvar org-cycle-global-status nil)
6225 (make-variable-buffer-local 'org-cycle-global-status)
6226 (defvar org-cycle-subtree-status nil)
6227 (make-variable-buffer-local 'org-cycle-subtree-status)
6229 (defvar org-inlinetask-min-level)
6231 ;;;###autoload
6232 (defun org-cycle (&optional arg)
6233 "TAB-action and visibility cycling for Org-mode.
6235 This is the command invoked in Org-mode by the TAB key. Its main purpose
6236 is outline visibility cycling, but it also invokes other actions
6237 in special contexts.
6239 - When this function is called with a prefix argument, rotate the entire
6240 buffer through 3 states (global cycling)
6241 1. OVERVIEW: Show only top-level headlines.
6242 2. CONTENTS: Show all headlines of all levels, but no body text.
6243 3. SHOW ALL: Show everything.
6244 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6245 determined by the variable `org-startup-folded', and by any VISIBILITY
6246 properties in the buffer.
6247 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6248 including any drawers.
6250 - When inside a table, re-align the table and move to the next field.
6252 - When point is at the beginning of a headline, rotate the subtree started
6253 by this line through 3 different states (local cycling)
6254 1. FOLDED: Only the main headline is shown.
6255 2. CHILDREN: The main headline and the direct children are shown.
6256 From this state, you can move to one of the children
6257 and zoom in further.
6258 3. SUBTREE: Show the entire subtree, including body text.
6259 If there is no subtree, switch directly from CHILDREN to FOLDED.
6261 - When point is at the beginning of an empty headline and the variable
6262 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6263 of the headline by demoting and promoting it to likely levels. This
6264 speeds up creation document structure by pressing TAB once or several
6265 times right after creating a new headline.
6267 - When there is a numeric prefix, go up to a heading with level ARG, do
6268 a `show-subtree' and return to the previous cursor position. If ARG
6269 is negative, go up that many levels.
6271 - When point is not at the beginning of a headline, execute the global
6272 binding for TAB, which is re-indenting the line. See the option
6273 `org-cycle-emulate-tab' for details.
6275 - Special case: if point is at the beginning of the buffer and there is
6276 no headline in line 1, this function will act as if called with prefix arg
6277 (C-u TAB, same as S-TAB) also when called without prefix arg.
6278 But only if also the variable `org-cycle-global-at-bob' is t."
6279 (interactive "P")
6280 (org-load-modules-maybe)
6281 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6282 (and org-cycle-level-after-item/entry-creation
6283 (or (org-cycle-level)
6284 (org-cycle-item-indentation))))
6285 (let* (message-log-max ; Don't populate the *Messages* buffer
6286 (limit-level
6287 (or org-cycle-max-level
6288 (and (boundp 'org-inlinetask-min-level)
6289 org-inlinetask-min-level
6290 (1- org-inlinetask-min-level))))
6291 (nstars (and limit-level
6292 (if org-odd-levels-only
6293 (and limit-level (1- (* limit-level 2)))
6294 limit-level)))
6295 (org-outline-regexp
6296 (if (not (derived-mode-p 'org-mode))
6297 outline-regexp
6298 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6299 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6300 (not (looking-at org-outline-regexp))))
6301 (org-cycle-hook
6302 (if bob-special
6303 (delq 'org-optimize-window-after-visibility-change
6304 (copy-sequence org-cycle-hook))
6305 org-cycle-hook))
6306 (pos (point)))
6308 (if (or bob-special (equal arg '(4)))
6309 ;; special case: use global cycling
6310 (setq arg t))
6312 (cond
6314 ((equal arg '(16))
6315 (setq last-command 'dummy)
6316 (org-set-startup-visibility)
6317 (message "Startup visibility, plus VISIBILITY properties"))
6319 ((equal arg '(64))
6320 (show-all)
6321 (message "Entire buffer visible, including drawers"))
6323 ;; Table: enter it or move to the next field.
6324 ((org-at-table-p 'any)
6325 (if (org-at-table.el-p)
6326 (message "Use C-c ' to edit table.el tables")
6327 (if arg (org-table-edit-field t)
6328 (org-table-justify-field-maybe)
6329 (call-interactively 'org-table-next-field))))
6331 ((run-hook-with-args-until-success
6332 'org-tab-after-check-for-table-hook))
6334 ;; Global cycling: delegate to `org-cycle-internal-global'.
6335 ((eq arg t) (org-cycle-internal-global))
6337 ;; Drawers: delegate to `org-flag-drawer'.
6338 ((and org-drawers org-drawer-regexp
6339 (save-excursion
6340 (beginning-of-line 1)
6341 (looking-at org-drawer-regexp)))
6342 (org-flag-drawer ; toggle block visibility
6343 (not (get-char-property (match-end 0) 'invisible))))
6345 ;; Show-subtree, ARG levels up from here.
6346 ((integerp arg)
6347 (save-excursion
6348 (org-back-to-heading)
6349 (outline-up-heading (if (< arg 0) (- arg)
6350 (- (funcall outline-level) arg)))
6351 (org-show-subtree)))
6353 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6354 ((and (featurep 'org-inlinetask)
6355 (org-inlinetask-at-task-p)
6356 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6357 (org-inlinetask-toggle-visibility))
6359 ((org-try-cdlatex-tab))
6361 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6362 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6363 (save-excursion (beginning-of-line 1)
6364 (looking-at org-outline-regexp)))
6365 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6366 (org-cycle-internal-local))
6368 ;; From there: TAB emulation and template completion.
6369 (buffer-read-only (org-back-to-heading))
6371 ((run-hook-with-args-until-success
6372 'org-tab-after-check-for-cycling-hook))
6374 ((org-try-structure-completion))
6376 ((run-hook-with-args-until-success
6377 'org-tab-before-tab-emulation-hook))
6379 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6380 (or (not (bolp))
6381 (not (looking-at org-outline-regexp))))
6382 (call-interactively (global-key-binding "\t")))
6384 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6385 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6386 (or (and (eq org-cycle-emulate-tab 'white)
6387 (= (match-end 0) (point-at-eol)))
6388 (and (eq org-cycle-emulate-tab 'whitestart)
6389 (>= (match-end 0) pos))))
6391 (eq org-cycle-emulate-tab t))
6392 (call-interactively (global-key-binding "\t")))
6394 (t (save-excursion
6395 (org-back-to-heading)
6396 (org-cycle)))))))
6398 (defun org-cycle-internal-global ()
6399 "Do the global cycling action."
6400 ;; Hack to avoid display of messages for .org attachments in Gnus
6401 (let (message-log-max ; Don't populate the *Messages* buffer
6402 (ga (string-match "\\*fontification" (buffer-name))))
6403 (cond
6404 ((and (eq last-command this-command)
6405 (eq org-cycle-global-status 'overview))
6406 ;; We just created the overview - now do table of contents
6407 ;; This can be slow in very large buffers, so indicate action
6408 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6409 (unless ga (message "CONTENTS..."))
6410 (org-content)
6411 (unless ga (message "CONTENTS...done"))
6412 (setq org-cycle-global-status 'contents)
6413 (run-hook-with-args 'org-cycle-hook 'contents))
6415 ((and (eq last-command this-command)
6416 (eq org-cycle-global-status 'contents))
6417 ;; We just showed the table of contents - now show everything
6418 (run-hook-with-args 'org-pre-cycle-hook 'all)
6419 (show-all)
6420 (unless ga (message "SHOW ALL"))
6421 (setq org-cycle-global-status 'all)
6422 (run-hook-with-args 'org-cycle-hook 'all))
6425 ;; Default action: go to overview
6426 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6427 (org-overview)
6428 (unless ga (message "OVERVIEW"))
6429 (setq org-cycle-global-status 'overview)
6430 (run-hook-with-args 'org-cycle-hook 'overview)))))
6432 (defun org-cycle-internal-local ()
6433 "Do the local cycling action."
6434 (let (message-log-max ; Don't populate the *Messages* buffer
6435 (goal-column 0) eoh eol eos has-children children-skipped struct)
6436 ;; First, determine end of headline (EOH), end of subtree or item
6437 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6438 (save-excursion
6439 (if (org-at-item-p)
6440 (progn
6441 (beginning-of-line)
6442 (setq struct (org-list-struct))
6443 (setq eoh (point-at-eol))
6444 (setq eos (org-list-get-item-end-before-blank (point) struct))
6445 (setq has-children (org-list-has-child-p (point) struct)))
6446 (org-back-to-heading)
6447 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6448 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6449 (setq has-children
6450 (or (save-excursion
6451 (let ((level (funcall outline-level)))
6452 (outline-next-heading)
6453 (and (org-at-heading-p t)
6454 (> (funcall outline-level) level))))
6455 (save-excursion
6456 (org-list-search-forward (org-item-beginning-re) eos t)))))
6457 ;; Determine end invisible part of buffer (EOL)
6458 (beginning-of-line 2)
6459 ;; XEmacs doesn't have `next-single-char-property-change'
6460 (if (featurep 'xemacs)
6461 (while (and (not (eobp)) ;; this is like `next-line'
6462 (get-char-property (1- (point)) 'invisible))
6463 (beginning-of-line 2))
6464 (while (and (not (eobp)) ;; this is like `next-line'
6465 (get-char-property (1- (point)) 'invisible))
6466 (goto-char (next-single-char-property-change (point) 'invisible))
6467 (and (eolp) (beginning-of-line 2))))
6468 (setq eol (point)))
6469 ;; Find out what to do next and set `this-command'
6470 (cond
6471 ((= eos eoh)
6472 ;; Nothing is hidden behind this heading
6473 (unless (org-before-first-heading-p)
6474 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6475 (message "EMPTY ENTRY")
6476 (setq org-cycle-subtree-status nil)
6477 (save-excursion
6478 (goto-char eos)
6479 (outline-next-heading)
6480 (if (outline-invisible-p) (org-flag-heading nil))))
6481 ((and (or (>= eol eos)
6482 (not (string-match "\\S-" (buffer-substring eol eos))))
6483 (or has-children
6484 (not (setq children-skipped
6485 org-cycle-skip-children-state-if-no-children))))
6486 ;; Entire subtree is hidden in one line: children view
6487 (unless (org-before-first-heading-p)
6488 (run-hook-with-args 'org-pre-cycle-hook 'children))
6489 (if (org-at-item-p)
6490 (org-list-set-item-visibility (point-at-bol) struct 'children)
6491 (org-show-entry)
6492 (org-with-limited-levels (show-children))
6493 ;; FIXME: This slows down the func way too much.
6494 ;; How keep drawers hidden in subtree anyway?
6495 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6496 ;; (org-cycle-hide-drawers 'subtree))
6498 ;; Fold every list in subtree to top-level items.
6499 (when (eq org-cycle-include-plain-lists 'integrate)
6500 (save-excursion
6501 (org-back-to-heading)
6502 (while (org-list-search-forward (org-item-beginning-re) eos t)
6503 (beginning-of-line 1)
6504 (let* ((struct (org-list-struct))
6505 (prevs (org-list-prevs-alist struct))
6506 (end (org-list-get-bottom-point struct)))
6507 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6508 (org-list-get-all-items (point) struct prevs))
6509 (goto-char end))))))
6510 (message "CHILDREN")
6511 (save-excursion
6512 (goto-char eos)
6513 (outline-next-heading)
6514 (if (outline-invisible-p) (org-flag-heading nil)))
6515 (setq org-cycle-subtree-status 'children)
6516 (unless (org-before-first-heading-p)
6517 (run-hook-with-args 'org-cycle-hook 'children)))
6518 ((or children-skipped
6519 (and (eq last-command this-command)
6520 (eq org-cycle-subtree-status 'children)))
6521 ;; We just showed the children, or no children are there,
6522 ;; now show everything.
6523 (unless (org-before-first-heading-p)
6524 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6525 (outline-flag-region eoh eos nil)
6526 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6527 (setq org-cycle-subtree-status 'subtree)
6528 (unless (org-before-first-heading-p)
6529 (run-hook-with-args 'org-cycle-hook 'subtree)))
6531 ;; Default action: hide the subtree.
6532 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6533 (outline-flag-region eoh eos t)
6534 (message "FOLDED")
6535 (setq org-cycle-subtree-status 'folded)
6536 (unless (org-before-first-heading-p)
6537 (run-hook-with-args 'org-cycle-hook 'folded))))))
6539 ;;;###autoload
6540 (defun org-global-cycle (&optional arg)
6541 "Cycle the global visibility. For details see `org-cycle'.
6542 With \\[universal-argument] prefix arg, switch to startup visibility.
6543 With a numeric prefix, show all headlines up to that level."
6544 (interactive "P")
6545 (let ((org-cycle-include-plain-lists
6546 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6547 (cond
6548 ((integerp arg)
6549 (show-all)
6550 (hide-sublevels arg)
6551 (setq org-cycle-global-status 'contents))
6552 ((equal arg '(4))
6553 (org-set-startup-visibility)
6554 (message "Startup visibility, plus VISIBILITY properties."))
6556 (org-cycle '(4))))))
6558 (defun org-set-startup-visibility ()
6559 "Set the visibility required by startup options and properties."
6560 (cond
6561 ((eq org-startup-folded t)
6562 (org-cycle '(4)))
6563 ((eq org-startup-folded 'content)
6564 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6565 (org-cycle '(4)) (org-cycle '(4)))))
6566 (unless (eq org-startup-folded 'showeverything)
6567 (if org-hide-block-startup (org-hide-block-all))
6568 (org-set-visibility-according-to-property 'no-cleanup)
6569 (org-cycle-hide-archived-subtrees 'all)
6570 (org-cycle-hide-drawers 'all)
6571 (org-cycle-show-empty-lines t)))
6573 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6574 "Switch subtree visibilities according to :VISIBILITY: property."
6575 (interactive)
6576 (let (org-show-entry-below state)
6577 (save-excursion
6578 (goto-char (point-min))
6579 (while (re-search-forward
6580 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6581 nil t)
6582 (setq state (match-string 1))
6583 (save-excursion
6584 (org-back-to-heading t)
6585 (hide-subtree)
6586 (org-reveal)
6587 (cond
6588 ((equal state '("fold" "folded"))
6589 (hide-subtree))
6590 ((equal state "children")
6591 (org-show-hidden-entry)
6592 (show-children))
6593 ((equal state "content")
6594 (save-excursion
6595 (save-restriction
6596 (org-narrow-to-subtree)
6597 (org-content))))
6598 ((member state '("all" "showall"))
6599 (show-subtree)))))
6600 (unless no-cleanup
6601 (org-cycle-hide-archived-subtrees 'all)
6602 (org-cycle-hide-drawers 'all)
6603 (org-cycle-show-empty-lines 'all)))))
6605 ;; This function uses outline-regexp instead of the more fundamental
6606 ;; org-outline-regexp so that org-cycle-global works outside of Org
6607 ;; buffers, where outline-regexp is needed.
6608 (defun org-overview ()
6609 "Switch to overview mode, showing only top-level headlines.
6610 Really, this shows all headlines with level equal or greater than the level
6611 of the first headline in the buffer. This is important, because if the
6612 first headline is not level one, then (hide-sublevels 1) gives confusing
6613 results."
6614 (interactive)
6615 (let ((level (save-excursion
6616 (goto-char (point-min))
6617 (if (re-search-forward (concat "^" outline-regexp) nil t)
6618 (progn
6619 (goto-char (match-beginning 0))
6620 (funcall outline-level))))))
6621 (and level (hide-sublevels level))))
6623 (defun org-content (&optional arg)
6624 "Show all headlines in the buffer, like a table of contents.
6625 With numerical argument N, show content up to level N."
6626 (interactive "P")
6627 (save-excursion
6628 ;; Visit all headings and show their offspring
6629 (and (integerp arg) (org-overview))
6630 (goto-char (point-max))
6631 (catch 'exit
6632 (while (and (progn (condition-case nil
6633 (outline-previous-visible-heading 1)
6634 (error (goto-char (point-min))))
6636 (looking-at org-outline-regexp))
6637 (if (integerp arg)
6638 (show-children (1- arg))
6639 (show-branches))
6640 (if (bobp) (throw 'exit nil))))))
6643 (defun org-optimize-window-after-visibility-change (state)
6644 "Adjust the window after a change in outline visibility.
6645 This function is the default value of the hook `org-cycle-hook'."
6646 (when (get-buffer-window (current-buffer))
6647 (cond
6648 ((eq state 'content) nil)
6649 ((eq state 'all) nil)
6650 ((eq state 'folded) nil)
6651 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6652 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6654 (defun org-remove-empty-overlays-at (pos)
6655 "Remove outline overlays that do not contain non-white stuff."
6656 (mapc
6657 (lambda (o)
6658 (and (eq 'outline (overlay-get o 'invisible))
6659 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6660 (overlay-end o))))
6661 (delete-overlay o)))
6662 (overlays-at pos)))
6664 (defun org-clean-visibility-after-subtree-move ()
6665 "Fix visibility issues after moving a subtree."
6666 ;; First, find a reasonable region to look at:
6667 ;; Start two siblings above, end three below
6668 (let* ((beg (save-excursion
6669 (and (org-get-last-sibling)
6670 (org-get-last-sibling))
6671 (point)))
6672 (end (save-excursion
6673 (and (org-get-next-sibling)
6674 (org-get-next-sibling)
6675 (org-get-next-sibling))
6676 (if (org-at-heading-p)
6677 (point-at-eol)
6678 (point))))
6679 (level (looking-at "\\*+"))
6680 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6681 (save-excursion
6682 (save-restriction
6683 (narrow-to-region beg end)
6684 (when re
6685 ;; Properly fold already folded siblings
6686 (goto-char (point-min))
6687 (while (re-search-forward re nil t)
6688 (if (and (not (outline-invisible-p))
6689 (save-excursion
6690 (goto-char (point-at-eol)) (outline-invisible-p)))
6691 (hide-entry))))
6692 (org-cycle-show-empty-lines 'overview)
6693 (org-cycle-hide-drawers 'overview)))))
6695 (defun org-cycle-show-empty-lines (state)
6696 "Show empty lines above all visible headlines.
6697 The region to be covered depends on STATE when called through
6698 `org-cycle-hook'. Lisp program can use t for STATE to get the
6699 entire buffer covered. Note that an empty line is only shown if there
6700 are at least `org-cycle-separator-lines' empty lines before the headline."
6701 (when (not (= org-cycle-separator-lines 0))
6702 (save-excursion
6703 (let* ((n (abs org-cycle-separator-lines))
6704 (re (cond
6705 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6706 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6707 (t (let ((ns (number-to-string (- n 2))))
6708 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6709 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6710 beg end b e)
6711 (cond
6712 ((memq state '(overview contents t))
6713 (setq beg (point-min) end (point-max)))
6714 ((memq state '(children folded))
6715 (setq beg (point) end (progn (org-end-of-subtree t t)
6716 (beginning-of-line 2)
6717 (point)))))
6718 (when beg
6719 (goto-char beg)
6720 (while (re-search-forward re end t)
6721 (unless (get-char-property (match-end 1) 'invisible)
6722 (setq e (match-end 1))
6723 (if (< org-cycle-separator-lines 0)
6724 (setq b (save-excursion
6725 (goto-char (match-beginning 0))
6726 (org-back-over-empty-lines)
6727 (if (save-excursion
6728 (goto-char (max (point-min) (1- (point))))
6729 (org-at-heading-p))
6730 (1- (point))
6731 (point))))
6732 (setq b (match-beginning 1)))
6733 (outline-flag-region b e nil)))))))
6734 ;; Never hide empty lines at the end of the file.
6735 (save-excursion
6736 (goto-char (point-max))
6737 (outline-previous-heading)
6738 (outline-end-of-heading)
6739 (if (and (looking-at "[ \t\n]+")
6740 (= (match-end 0) (point-max)))
6741 (outline-flag-region (point) (match-end 0) nil))))
6743 (defun org-show-empty-lines-in-parent ()
6744 "Move to the parent and re-show empty lines before visible headlines."
6745 (save-excursion
6746 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6747 (org-cycle-show-empty-lines context))))
6749 (defun org-files-list ()
6750 "Return `org-agenda-files' list, plus all open org-mode files.
6751 This is useful for operations that need to scan all of a user's
6752 open and agenda-wise Org files."
6753 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6754 (dolist (buf (buffer-list))
6755 (with-current-buffer buf
6756 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6757 (let ((file (expand-file-name (buffer-file-name))))
6758 (unless (member file files)
6759 (push file files))))))
6760 files))
6762 (defsubst org-entry-beginning-position ()
6763 "Return the beginning position of the current entry."
6764 (save-excursion (outline-back-to-heading t) (point)))
6766 (defsubst org-entry-end-position ()
6767 "Return the end position of the current entry."
6768 (save-excursion (outline-next-heading) (point)))
6770 (defun org-cycle-hide-drawers (state)
6771 "Re-hide all drawers after a visibility state change."
6772 (when (and (derived-mode-p 'org-mode)
6773 (not (memq state '(overview folded contents))))
6774 (save-excursion
6775 (let* ((globalp (memq state '(contents all)))
6776 (beg (if globalp (point-min) (point)))
6777 (end (if globalp (point-max)
6778 (if (eq state 'children)
6779 (save-excursion (outline-next-heading) (point))
6780 (org-end-of-subtree t)))))
6781 (goto-char beg)
6782 (while (re-search-forward org-drawer-regexp end t)
6783 (org-flag-drawer t))))))
6785 (defun org-cycle-hide-inline-tasks (state)
6786 "Re-hide inline task when switching to 'contents visibility state."
6787 (when (and (eq state 'contents)
6788 (boundp 'org-inlinetask-min-level)
6789 org-inlinetask-min-level)
6790 (hide-sublevels (1- org-inlinetask-min-level))))
6792 (defun org-flag-drawer (flag)
6793 "When FLAG is non-nil, hide the drawer we are within.
6794 Otherwise make it visible."
6795 (save-excursion
6796 (beginning-of-line 1)
6797 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6798 (let ((b (match-end 0)))
6799 (if (re-search-forward
6800 "^[ \t]*:END:"
6801 (save-excursion (outline-next-heading) (point)) t)
6802 (outline-flag-region b (point-at-eol) flag)
6803 (error ":END: line missing at position %s" b))))))
6805 (defun org-subtree-end-visible-p ()
6806 "Is the end of the current subtree visible?"
6807 (pos-visible-in-window-p
6808 (save-excursion (org-end-of-subtree t) (point))))
6810 (defun org-first-headline-recenter (&optional N)
6811 "Move cursor to the first headline and recenter the headline.
6812 Optional argument N means put the headline into the Nth line of the window."
6813 (goto-char (point-min))
6814 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6815 (beginning-of-line)
6816 (recenter (prefix-numeric-value N))))
6818 ;;; Saving and restoring visibility
6820 (defun org-outline-overlay-data (&optional use-markers)
6821 "Return a list of the locations of all outline overlays.
6822 These are overlays with the `invisible' property value `outline'.
6823 The return value is a list of cons cells, with start and stop
6824 positions for each overlay.
6825 If USE-MARKERS is set, return the positions as markers."
6826 (let (beg end)
6827 (save-excursion
6828 (save-restriction
6829 (widen)
6830 (delq nil
6831 (mapcar (lambda (o)
6832 (when (eq (overlay-get o 'invisible) 'outline)
6833 (setq beg (overlay-start o)
6834 end (overlay-end o))
6835 (and beg end (> end beg)
6836 (if use-markers
6837 (cons (move-marker (make-marker) beg)
6838 (move-marker (make-marker) end))
6839 (cons beg end)))))
6840 (overlays-in (point-min) (point-max))))))))
6842 (defun org-set-outline-overlay-data (data)
6843 "Create visibility overlays for all positions in DATA.
6844 DATA should have been made by `org-outline-overlay-data'."
6845 (let (o)
6846 (save-excursion
6847 (save-restriction
6848 (widen)
6849 (show-all)
6850 (mapc (lambda (c)
6851 (outline-flag-region (car c) (cdr c) t))
6852 data)))))
6854 ;;; Folding of blocks
6856 (defvar org-hide-block-overlays nil
6857 "Overlays hiding blocks.")
6858 (make-variable-buffer-local 'org-hide-block-overlays)
6860 (defun org-block-map (function &optional start end)
6861 "Call FUNCTION at the head of all source blocks in the current buffer.
6862 Optional arguments START and END can be used to limit the range."
6863 (let ((start (or start (point-min)))
6864 (end (or end (point-max))))
6865 (save-excursion
6866 (goto-char start)
6867 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6868 (save-excursion
6869 (save-match-data
6870 (goto-char (match-beginning 0))
6871 (funcall function)))))))
6873 (defun org-hide-block-toggle-all ()
6874 "Toggle the visibility of all blocks in the current buffer."
6875 (org-block-map #'org-hide-block-toggle))
6877 (defun org-hide-block-all ()
6878 "Fold all blocks in the current buffer."
6879 (interactive)
6880 (org-show-block-all)
6881 (org-block-map #'org-hide-block-toggle-maybe))
6883 (defun org-show-block-all ()
6884 "Unfold all blocks in the current buffer."
6885 (interactive)
6886 (mapc 'delete-overlay org-hide-block-overlays)
6887 (setq org-hide-block-overlays nil))
6889 (defun org-hide-block-toggle-maybe ()
6890 "Toggle visibility of block at point."
6891 (interactive)
6892 (let ((case-fold-search t))
6893 (if (save-excursion
6894 (beginning-of-line 1)
6895 (looking-at org-block-regexp))
6896 (progn (org-hide-block-toggle)
6897 t) ;; to signal that we took action
6898 nil))) ;; to signal that we did not
6900 (defun org-hide-block-toggle (&optional force)
6901 "Toggle the visibility of the current block."
6902 (interactive)
6903 (save-excursion
6904 (beginning-of-line)
6905 (if (re-search-forward org-block-regexp nil t)
6906 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6907 (end (match-end 0)) ;; end of entire body
6909 (if (memq t (mapcar (lambda (overlay)
6910 (eq (overlay-get overlay 'invisible)
6911 'org-hide-block))
6912 (overlays-at start)))
6913 (if (or (not force) (eq force 'off))
6914 (mapc (lambda (ov)
6915 (when (member ov org-hide-block-overlays)
6916 (setq org-hide-block-overlays
6917 (delq ov org-hide-block-overlays)))
6918 (when (eq (overlay-get ov 'invisible)
6919 'org-hide-block)
6920 (delete-overlay ov)))
6921 (overlays-at start)))
6922 (setq ov (make-overlay start end))
6923 (overlay-put ov 'invisible 'org-hide-block)
6924 ;; make the block accessible to isearch
6925 (overlay-put
6926 ov 'isearch-open-invisible
6927 (lambda (ov)
6928 (when (member ov org-hide-block-overlays)
6929 (setq org-hide-block-overlays
6930 (delq ov org-hide-block-overlays)))
6931 (when (eq (overlay-get ov 'invisible)
6932 'org-hide-block)
6933 (delete-overlay ov))))
6934 (push ov org-hide-block-overlays)))
6935 (error "Not looking at a source block"))))
6937 ;; org-tab-after-check-for-cycling-hook
6938 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6939 ;; Remove overlays when changing major mode
6940 (add-hook 'org-mode-hook
6941 (lambda () (org-add-hook 'change-major-mode-hook
6942 'org-show-block-all 'append 'local)))
6944 ;;; Org-goto
6946 (defvar org-goto-window-configuration nil)
6947 (defvar org-goto-marker nil)
6948 (defvar org-goto-map)
6949 (defun org-goto-map ()
6950 "Set the keymap `org-goto'."
6951 (setq org-goto-map
6952 (let ((map (make-sparse-keymap)))
6953 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6954 mouse-drag-region universal-argument org-occur))
6955 cmd)
6956 (while (setq cmd (pop cmds))
6957 (substitute-key-definition cmd cmd map global-map)))
6958 (suppress-keymap map)
6959 (org-defkey map "\C-m" 'org-goto-ret)
6960 (org-defkey map [(return)] 'org-goto-ret)
6961 (org-defkey map [(left)] 'org-goto-left)
6962 (org-defkey map [(right)] 'org-goto-right)
6963 (org-defkey map [(control ?g)] 'org-goto-quit)
6964 (org-defkey map "\C-i" 'org-cycle)
6965 (org-defkey map [(tab)] 'org-cycle)
6966 (org-defkey map [(down)] 'outline-next-visible-heading)
6967 (org-defkey map [(up)] 'outline-previous-visible-heading)
6968 (if org-goto-auto-isearch
6969 (if (fboundp 'define-key-after)
6970 (define-key-after map [t] 'org-goto-local-auto-isearch)
6971 nil)
6972 (org-defkey map "q" 'org-goto-quit)
6973 (org-defkey map "n" 'outline-next-visible-heading)
6974 (org-defkey map "p" 'outline-previous-visible-heading)
6975 (org-defkey map "f" 'outline-forward-same-level)
6976 (org-defkey map "b" 'outline-backward-same-level)
6977 (org-defkey map "u" 'outline-up-heading))
6978 (org-defkey map "/" 'org-occur)
6979 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6980 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6981 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6982 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6983 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6984 map)))
6986 (defconst org-goto-help
6987 "Browse buffer copy, to find location or copy text.%s
6988 RET=jump to location C-g=quit and return to previous location
6989 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6991 (defvar org-goto-start-pos) ; dynamically scoped parameter
6993 ;; FIXME: Docstring does not mention both interfaces
6994 (defun org-goto (&optional alternative-interface)
6995 "Look up a different location in the current file, keeping current visibility.
6997 When you want look-up or go to a different location in a
6998 document, the fastest way is often to fold the entire buffer and
6999 then dive into the tree. This method has the disadvantage, that
7000 the previous location will be folded, which may not be what you
7001 want.
7003 This command works around this by showing a copy of the current
7004 buffer in an indirect buffer, in overview mode. You can dive
7005 into the tree in that copy, use org-occur and incremental search
7006 to find a location. When pressing RET or `Q', the command
7007 returns to the original buffer in which the visibility is still
7008 unchanged. After RET it will also jump to the location selected
7009 in the indirect buffer and expose the headline hierarchy above.
7011 With a prefix argument, use the alternative interface: e.g. if
7012 `org-goto-interface' is 'outline use 'outline-path-completion."
7013 (interactive "P")
7014 (org-goto-map)
7015 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7016 (org-refile-use-outline-path t)
7017 (org-refile-target-verify-function nil)
7018 (interface
7019 (if (not alternative-interface)
7020 org-goto-interface
7021 (if (eq org-goto-interface 'outline)
7022 'outline-path-completion
7023 'outline)))
7024 (org-goto-start-pos (point))
7025 (selected-point
7026 (if (eq interface 'outline)
7027 (car (org-get-location (current-buffer) org-goto-help))
7028 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7029 (org-refile-check-position pa)
7030 (nth 3 pa)))))
7031 (if selected-point
7032 (progn
7033 (org-mark-ring-push org-goto-start-pos)
7034 (goto-char selected-point)
7035 (if (or (outline-invisible-p) (org-invisible-p2))
7036 (org-show-context 'org-goto)))
7037 (message "Quit"))))
7039 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7040 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7041 (defvar org-goto-local-auto-isearch-map) ; defined below
7043 (defun org-get-location (buf help)
7044 "Let the user select a location in the Org-mode buffer BUF.
7045 This function uses a recursive edit. It returns the selected position
7046 or nil."
7047 (org-no-popups
7048 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7049 (isearch-hide-immediately nil)
7050 (isearch-search-fun-function
7051 (lambda () 'org-goto-local-search-headings))
7052 (org-goto-selected-point org-goto-exit-command))
7053 (save-excursion
7054 (save-window-excursion
7055 (delete-other-windows)
7056 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7057 (org-pop-to-buffer-same-window
7058 (condition-case nil
7059 (make-indirect-buffer (current-buffer) "*org-goto*")
7060 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7061 (with-output-to-temp-buffer "*Org Help*"
7062 (princ (format help (if org-goto-auto-isearch
7063 " Just type for auto-isearch."
7064 " n/p/f/b/u to navigate, q to quit."))))
7065 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7066 (setq buffer-read-only nil)
7067 (let ((org-startup-truncated t)
7068 (org-startup-folded nil)
7069 (org-startup-align-all-tables nil))
7070 (org-mode)
7071 (org-overview))
7072 (setq buffer-read-only t)
7073 (if (and (boundp 'org-goto-start-pos)
7074 (integer-or-marker-p org-goto-start-pos))
7075 (let ((org-show-hierarchy-above t)
7076 (org-show-siblings t)
7077 (org-show-following-heading t))
7078 (goto-char org-goto-start-pos)
7079 (and (outline-invisible-p) (org-show-context)))
7080 (goto-char (point-min)))
7081 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7082 (message "Select location and press RET")
7083 (use-local-map org-goto-map)
7084 (recursive-edit)))
7085 (kill-buffer "*org-goto*")
7086 (cons org-goto-selected-point org-goto-exit-command))))
7088 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7089 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7090 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7091 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7093 (defun org-goto-local-search-headings (string bound noerror)
7094 "Search and make sure that any matches are in headlines."
7095 (catch 'return
7096 (while (if isearch-forward
7097 (search-forward string bound noerror)
7098 (search-backward string bound noerror))
7099 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7100 (and (member :headline context)
7101 (not (member :tags context))))
7102 (throw 'return (point))))))
7104 (defun org-goto-local-auto-isearch ()
7105 "Start isearch."
7106 (interactive)
7107 (goto-char (point-min))
7108 (let ((keys (this-command-keys)))
7109 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7110 (isearch-mode t)
7111 (isearch-process-search-char (string-to-char keys)))))
7113 (defun org-goto-ret (&optional arg)
7114 "Finish `org-goto' by going to the new location."
7115 (interactive "P")
7116 (setq org-goto-selected-point (point)
7117 org-goto-exit-command 'return)
7118 (throw 'exit nil))
7120 (defun org-goto-left ()
7121 "Finish `org-goto' by going to the new location."
7122 (interactive)
7123 (if (org-at-heading-p)
7124 (progn
7125 (beginning-of-line 1)
7126 (setq org-goto-selected-point (point)
7127 org-goto-exit-command 'left)
7128 (throw 'exit nil))
7129 (error "Not on a heading")))
7131 (defun org-goto-right ()
7132 "Finish `org-goto' by going to the new location."
7133 (interactive)
7134 (if (org-at-heading-p)
7135 (progn
7136 (setq org-goto-selected-point (point)
7137 org-goto-exit-command 'right)
7138 (throw 'exit nil))
7139 (error "Not on a heading")))
7141 (defun org-goto-quit ()
7142 "Finish `org-goto' without cursor motion."
7143 (interactive)
7144 (setq org-goto-selected-point nil)
7145 (setq org-goto-exit-command 'quit)
7146 (throw 'exit nil))
7148 ;;; Indirect buffer display of subtrees
7150 (defvar org-indirect-dedicated-frame nil
7151 "This is the frame being used for indirect tree display.")
7152 (defvar org-last-indirect-buffer nil)
7154 (defun org-tree-to-indirect-buffer (&optional arg)
7155 "Create indirect buffer and narrow it to current subtree.
7156 With a numerical prefix ARG, go up to this level and then take that tree.
7157 If ARG is negative, go up that many levels.
7159 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7160 indirect buffer previously made with this command, to avoid proliferation of
7161 indirect buffers. However, when you call the command with a \
7162 \\[universal-argument] prefix, or
7163 when `org-indirect-buffer-display' is `new-frame', the last buffer
7164 is kept so that you can work with several indirect buffers at the same time.
7165 If `org-indirect-buffer-display' is `dedicated-frame', the \
7166 \\[universal-argument] prefix also
7167 requests that a new frame be made for the new buffer, so that the dedicated
7168 frame is not changed."
7169 (interactive "P")
7170 (let ((cbuf (current-buffer))
7171 (cwin (selected-window))
7172 (pos (point))
7173 beg end level heading ibuf)
7174 (save-excursion
7175 (org-back-to-heading t)
7176 (when (numberp arg)
7177 (setq level (org-outline-level))
7178 (if (< arg 0) (setq arg (+ level arg)))
7179 (while (> (setq level (org-outline-level)) arg)
7180 (org-up-heading-safe)))
7181 (setq beg (point)
7182 heading (org-get-heading))
7183 (org-end-of-subtree t t)
7184 (if (org-at-heading-p) (backward-char 1))
7185 (setq end (point)))
7186 (if (and (buffer-live-p org-last-indirect-buffer)
7187 (not (eq org-indirect-buffer-display 'new-frame))
7188 (not arg))
7189 (kill-buffer org-last-indirect-buffer))
7190 (setq ibuf (org-get-indirect-buffer cbuf)
7191 org-last-indirect-buffer ibuf)
7192 (cond
7193 ((or (eq org-indirect-buffer-display 'new-frame)
7194 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7195 (select-frame (make-frame))
7196 (delete-other-windows)
7197 (org-pop-to-buffer-same-window ibuf)
7198 (org-set-frame-title heading))
7199 ((eq org-indirect-buffer-display 'dedicated-frame)
7200 (raise-frame
7201 (select-frame (or (and org-indirect-dedicated-frame
7202 (frame-live-p org-indirect-dedicated-frame)
7203 org-indirect-dedicated-frame)
7204 (setq org-indirect-dedicated-frame (make-frame)))))
7205 (delete-other-windows)
7206 (org-pop-to-buffer-same-window ibuf)
7207 (org-set-frame-title (concat "Indirect: " heading)))
7208 ((eq org-indirect-buffer-display 'current-window)
7209 (org-pop-to-buffer-same-window ibuf))
7210 ((eq org-indirect-buffer-display 'other-window)
7211 (pop-to-buffer ibuf))
7212 (t (error "Invalid value")))
7213 (if (featurep 'xemacs)
7214 (save-excursion (org-mode) (turn-on-font-lock)))
7215 (narrow-to-region beg end)
7216 (show-all)
7217 (goto-char pos)
7218 (run-hook-with-args 'org-cycle-hook 'all)
7219 (and (window-live-p cwin) (select-window cwin))))
7221 (defun org-get-indirect-buffer (&optional buffer)
7222 (setq buffer (or buffer (current-buffer)))
7223 (let ((n 1) (base (buffer-name buffer)) bname)
7224 (while (buffer-live-p
7225 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7226 (setq n (1+ n)))
7227 (condition-case nil
7228 (make-indirect-buffer buffer bname 'clone)
7229 (error (make-indirect-buffer buffer bname)))))
7231 (defun org-set-frame-title (title)
7232 "Set the title of the current frame to the string TITLE."
7233 ;; FIXME: how to name a single frame in XEmacs???
7234 (unless (featurep 'xemacs)
7235 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7237 ;;;; Structure editing
7239 ;;; Inserting headlines
7241 (defun org-previous-line-empty-p ()
7242 (save-excursion
7243 (and (not (bobp))
7244 (or (beginning-of-line 0) t)
7245 (save-match-data
7246 (looking-at "[ \t]*$")))))
7248 (defun org-insert-heading (&optional force-heading invisible-ok)
7249 "Insert a new heading or item with same depth at point.
7250 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7251 If point is at the beginning of a headline, insert a sibling before the
7252 current headline. If point is not at the beginning, split the line,
7253 create the new headline with the text in the current line after point
7254 \(but see also the variable `org-M-RET-may-split-line').
7256 With a double prefix arg, force the heading to be inserted at the
7257 end of the parent subtree.
7259 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7260 This is important for non-interactive uses of the command."
7261 (interactive "P")
7262 (if (or (= (buffer-size) 0)
7263 (and (not (save-excursion
7264 (and (ignore-errors (org-back-to-heading invisible-ok))
7265 (org-at-heading-p))))
7266 (or force-heading (not (org-in-item-p)))))
7267 (progn
7268 (insert "\n* ")
7269 (run-hooks 'org-insert-heading-hook))
7270 (when (or force-heading (not (org-insert-item)))
7271 (let* ((empty-line-p nil)
7272 (level nil)
7273 (on-heading (org-at-heading-p))
7274 (head (save-excursion
7275 (condition-case nil
7276 (progn
7277 (org-back-to-heading invisible-ok)
7278 (when (and (not on-heading)
7279 (featurep 'org-inlinetask)
7280 (integerp org-inlinetask-min-level)
7281 (>= (length (match-string 0))
7282 org-inlinetask-min-level))
7283 ;; Find a heading level before the inline task
7284 (while (and (setq level (org-up-heading-safe))
7285 (>= level org-inlinetask-min-level)))
7286 (if (org-at-heading-p)
7287 (org-back-to-heading invisible-ok)
7288 (error "This should not happen")))
7289 (setq empty-line-p (org-previous-line-empty-p))
7290 (match-string 0))
7291 (error "*"))))
7292 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7293 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7294 pos hide-previous previous-pos)
7295 (cond
7296 ((and (org-at-heading-p) (bolp)
7297 (or (bobp)
7298 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7299 ;; insert before the current line
7300 (open-line (if blank 2 1)))
7301 ((and (bolp)
7302 (not org-insert-heading-respect-content)
7303 (or (bobp)
7304 (save-excursion
7305 (backward-char 1) (not (outline-invisible-p)))))
7306 ;; insert right here
7307 nil)
7309 ;; somewhere in the line
7310 (save-excursion
7311 (setq previous-pos (point-at-bol))
7312 (end-of-line)
7313 (setq hide-previous (outline-invisible-p)))
7314 (and org-insert-heading-respect-content (org-show-subtree))
7315 (let ((split
7316 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7317 (save-excursion
7318 (let ((p (point)))
7319 (goto-char (point-at-bol))
7320 (and (looking-at org-complex-heading-regexp)
7321 (match-beginning 4)
7322 (> p (match-beginning 4)))))))
7323 tags pos)
7324 (cond
7325 (org-insert-heading-respect-content
7326 (if (not (equal force-heading '(16)))
7327 (org-end-of-subtree nil t)
7328 (org-up-heading-safe)
7329 (org-end-of-subtree nil t))
7330 (when (featurep 'org-inlinetask)
7331 (while (and (not (eobp))
7332 (looking-at "\\(\\*+\\)[ \t]+")
7333 (>= (length (match-string 1))
7334 org-inlinetask-min-level))
7335 (org-end-of-subtree nil t)))
7336 (or (bolp) (newline))
7337 (or (org-previous-line-empty-p)
7338 (and blank (newline)))
7339 (open-line 1))
7340 ((org-at-heading-p)
7341 (when hide-previous
7342 (show-children)
7343 (org-show-entry))
7344 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7345 (setq tags (and (match-end 2) (match-string 2)))
7346 (and (match-end 1)
7347 (delete-region (match-beginning 1) (match-end 1)))
7348 (setq pos (point-at-bol))
7349 (or split (end-of-line 1))
7350 (delete-horizontal-space)
7351 (if (string-match "\\`\\*+\\'"
7352 (buffer-substring (point-at-bol) (point)))
7353 (insert " "))
7354 (newline (if blank 2 1))
7355 (when tags
7356 (save-excursion
7357 (goto-char pos)
7358 (end-of-line 1)
7359 (insert " " tags)
7360 (org-set-tags nil 'align))))
7362 (or split (end-of-line 1))
7363 (newline (if blank 2 1)))))))
7364 (insert head) (just-one-space)
7365 (setq pos (point))
7366 (end-of-line 1)
7367 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7368 (when (and org-insert-heading-respect-content hide-previous)
7369 (save-excursion
7370 (goto-char previous-pos)
7371 (hide-subtree)))
7372 (run-hooks 'org-insert-heading-hook)))))
7374 (defun org-get-heading (&optional no-tags no-todo)
7375 "Return the heading of the current entry, without the stars.
7376 When NO-TAGS is non-nil, don't include tags.
7377 When NO-TODO is non-nil, don't include TODO keywords."
7378 (save-excursion
7379 (org-back-to-heading t)
7380 (cond
7381 ((and no-tags no-todo)
7382 (looking-at org-complex-heading-regexp)
7383 (match-string 4))
7384 (no-tags
7385 (looking-at (concat org-outline-regexp
7386 "\\(.*?\\)"
7387 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7388 (match-string 1))
7389 (no-todo
7390 (looking-at org-todo-line-regexp)
7391 (match-string 3))
7392 (t (looking-at org-heading-regexp)
7393 (match-string 2)))))
7395 (defun org-heading-components ()
7396 "Return the components of the current heading.
7397 This is a list with the following elements:
7398 - the level as an integer
7399 - the reduced level, different if `org-odd-levels-only' is set.
7400 - the TODO keyword, or nil
7401 - the priority character, like ?A, or nil if no priority is given
7402 - the headline text itself, or the tags string if no headline text
7403 - the tags string, or nil."
7404 (save-excursion
7405 (org-back-to-heading t)
7406 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7407 (list (length (match-string 1))
7408 (org-reduced-level (length (match-string 1)))
7409 (org-match-string-no-properties 2)
7410 (and (match-end 3) (aref (match-string 3) 2))
7411 (org-match-string-no-properties 4)
7412 (org-match-string-no-properties 5)))))
7414 (defun org-get-entry ()
7415 "Get the entry text, after heading, entire subtree."
7416 (save-excursion
7417 (org-back-to-heading t)
7418 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7420 (defun org-insert-heading-after-current ()
7421 "Insert a new heading with same level as current, after current subtree."
7422 (interactive)
7423 (org-back-to-heading)
7424 (org-insert-heading)
7425 (org-move-subtree-down)
7426 (end-of-line 1))
7428 (defun org-insert-heading-respect-content ()
7429 (interactive)
7430 (let ((org-insert-heading-respect-content t))
7431 (org-insert-heading t)))
7433 (defun org-insert-todo-heading-respect-content (&optional force-state)
7434 (interactive "P")
7435 (let ((org-insert-heading-respect-content t))
7436 (org-insert-todo-heading force-state t)))
7438 (defun org-insert-todo-heading (arg &optional force-heading)
7439 "Insert a new heading with the same level and TODO state as current heading.
7440 If the heading has no TODO state, or if the state is DONE, use the first
7441 state (TODO by default). Also one prefix arg, force first state. With two
7442 prefix args, force inserting at the end of the parent subtree."
7443 (interactive "P")
7444 (when (or force-heading (not (org-insert-item 'checkbox)))
7445 (org-insert-heading (or (and (equal arg '(16)) '(16))
7446 force-heading))
7447 (save-excursion
7448 (org-back-to-heading)
7449 (outline-previous-heading)
7450 (looking-at org-todo-line-regexp))
7451 (let*
7452 ((new-mark-x
7453 (if (or arg
7454 (not (match-beginning 2))
7455 (member (match-string 2) org-done-keywords))
7456 (car org-todo-keywords-1)
7457 (match-string 2)))
7458 (new-mark
7460 (run-hook-with-args-until-success
7461 'org-todo-get-default-hook new-mark-x nil)
7462 new-mark-x)))
7463 (beginning-of-line 1)
7464 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7465 (if org-treat-insert-todo-heading-as-state-change
7466 (org-todo new-mark)
7467 (insert new-mark " "))))
7468 (when org-provide-todo-statistics
7469 (org-update-parent-todo-statistics))))
7471 (defun org-insert-subheading (arg)
7472 "Insert a new subheading and demote it.
7473 Works for outline headings and for plain lists alike."
7474 (interactive "P")
7475 (org-insert-heading arg)
7476 (cond
7477 ((org-at-heading-p) (org-do-demote))
7478 ((org-at-item-p) (org-indent-item))))
7480 (defun org-insert-todo-subheading (arg)
7481 "Insert a new subheading with TODO keyword or checkbox and demote it.
7482 Works for outline headings and for plain lists alike."
7483 (interactive "P")
7484 (org-insert-todo-heading arg)
7485 (cond
7486 ((org-at-heading-p) (org-do-demote))
7487 ((org-at-item-p) (org-indent-item))))
7489 ;;; Promotion and Demotion
7491 (defvar org-after-demote-entry-hook nil
7492 "Hook run after an entry has been demoted.
7493 The cursor will be at the beginning of the entry.
7494 When a subtree is being demoted, the hook will be called for each node.")
7496 (defvar org-after-promote-entry-hook nil
7497 "Hook run after an entry has been promoted.
7498 The cursor will be at the beginning of the entry.
7499 When a subtree is being promoted, the hook will be called for each node.")
7501 (defun org-promote-subtree ()
7502 "Promote the entire subtree.
7503 See also `org-promote'."
7504 (interactive)
7505 (save-excursion
7506 (org-with-limited-levels (org-map-tree 'org-promote)))
7507 (org-fix-position-after-promote))
7509 (defun org-demote-subtree ()
7510 "Demote the entire subtree. See `org-demote'.
7511 See also `org-promote'."
7512 (interactive)
7513 (save-excursion
7514 (org-with-limited-levels (org-map-tree 'org-demote)))
7515 (org-fix-position-after-promote))
7518 (defun org-do-promote ()
7519 "Promote the current heading higher up the tree.
7520 If the region is active in `transient-mark-mode', promote all headings
7521 in the region."
7522 (interactive)
7523 (save-excursion
7524 (if (org-region-active-p)
7525 (org-map-region 'org-promote (region-beginning) (region-end))
7526 (org-promote)))
7527 (org-fix-position-after-promote))
7529 (defun org-do-demote ()
7530 "Demote the current heading lower down the tree.
7531 If the region is active in `transient-mark-mode', demote all headings
7532 in the region."
7533 (interactive)
7534 (save-excursion
7535 (if (org-region-active-p)
7536 (org-map-region 'org-demote (region-beginning) (region-end))
7537 (org-demote)))
7538 (org-fix-position-after-promote))
7540 (defun org-fix-position-after-promote ()
7541 "Make sure that after pro/demotion cursor position is right."
7542 (let ((pos (point)))
7543 (when (save-excursion
7544 (beginning-of-line 1)
7545 (looking-at org-todo-line-regexp)
7546 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7547 (cond ((eobp) (insert " "))
7548 ((eolp) (insert " "))
7549 ((equal (char-after) ?\ ) (forward-char 1))))))
7551 (defun org-current-level ()
7552 "Return the level of the current entry, or nil if before the first headline.
7553 The level is the number of stars at the beginning of the headline."
7554 (save-excursion
7555 (org-with-limited-levels
7556 (if (ignore-errors (org-back-to-heading t))
7557 (funcall outline-level)))))
7559 (defun org-get-previous-line-level ()
7560 "Return the outline depth of the last headline before the current line.
7561 Returns 0 for the first headline in the buffer, and nil if before the
7562 first headline."
7563 (let ((current-level (org-current-level))
7564 (prev-level (when (> (line-number-at-pos) 1)
7565 (save-excursion
7566 (beginning-of-line 0)
7567 (org-current-level)))))
7568 (cond ((null current-level) nil) ; Before first headline
7569 ((null prev-level) 0) ; At first headline
7570 (prev-level))))
7572 (defun org-reduced-level (l)
7573 "Compute the effective level of a heading.
7574 This takes into account the setting of `org-odd-levels-only'."
7575 (cond
7576 ((zerop l) 0)
7577 (org-odd-levels-only (1+ (floor (/ l 2))))
7578 (t l)))
7580 (defun org-level-increment ()
7581 "Return the number of stars that will be added or removed at a
7582 time to headlines when structure editing, based on the value of
7583 `org-odd-levels-only'."
7584 (if org-odd-levels-only 2 1))
7586 (defun org-get-valid-level (level &optional change)
7587 "Rectify a level change under the influence of `org-odd-levels-only'
7588 LEVEL is a current level, CHANGE is by how much the level should be
7589 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7590 even level numbers will become the next higher odd number."
7591 (if org-odd-levels-only
7592 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7593 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7594 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7595 (max 1 (+ level (or change 0)))))
7597 (if (boundp 'define-obsolete-function-alias)
7598 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7599 (define-obsolete-function-alias 'org-get-legal-level
7600 'org-get-valid-level)
7601 (define-obsolete-function-alias 'org-get-legal-level
7602 'org-get-valid-level "23.1")))
7604 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7605 ;; ̀org-with-limited-levels'
7606 (defun org-promote ()
7607 "Promote the current heading higher up the tree.
7608 If the region is active in `transient-mark-mode', promote all headings
7609 in the region."
7610 (org-back-to-heading t)
7611 (let* ((level (save-match-data (funcall outline-level)))
7612 (after-change-functions (remove 'flyspell-after-change-function
7613 after-change-functions))
7614 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7615 (diff (abs (- level (length up-head) -1))))
7616 (cond ((and (= level 1) org-called-with-limited-levels
7617 org-allow-promoting-top-level-subtree)
7618 (replace-match "# " nil t))
7619 ((= level 1)
7620 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7621 (t (replace-match up-head nil t)))
7622 ;; Fixup tag positioning
7623 (unless (= level 1)
7624 (and org-auto-align-tags (org-set-tags nil t))
7625 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7626 (run-hooks 'org-after-promote-entry-hook)))
7628 (defun org-demote ()
7629 "Demote the current heading lower down the tree.
7630 If the region is active in `transient-mark-mode', demote all headings
7631 in the region."
7632 (org-back-to-heading t)
7633 (let* ((level (save-match-data (funcall outline-level)))
7634 (after-change-functions (remove 'flyspell-after-change-function
7635 after-change-functions))
7636 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7637 (diff (abs (- level (length down-head) -1))))
7638 (replace-match down-head nil t)
7639 ;; Fixup tag positioning
7640 (and org-auto-align-tags (org-set-tags nil t))
7641 (if org-adapt-indentation (org-fixup-indentation diff))
7642 (run-hooks 'org-after-demote-entry-hook)))
7644 (defun org-cycle-level ()
7645 "Cycle the level of an empty headline through possible states.
7646 This goes first to child, then to parent, level, then up the hierarchy.
7647 After top level, it switches back to sibling level."
7648 (interactive)
7649 (let ((org-adapt-indentation nil))
7650 (when (org-point-at-end-of-empty-headline)
7651 (setq this-command 'org-cycle-level) ; Only needed for caching
7652 (let ((cur-level (org-current-level))
7653 (prev-level (org-get-previous-line-level)))
7654 (cond
7655 ;; If first headline in file, promote to top-level.
7656 ((= prev-level 0)
7657 (loop repeat (/ (- cur-level 1) (org-level-increment))
7658 do (org-do-promote)))
7659 ;; If same level as prev, demote one.
7660 ((= prev-level cur-level)
7661 (org-do-demote))
7662 ;; If parent is top-level, promote to top level if not already.
7663 ((= prev-level 1)
7664 (loop repeat (/ (- cur-level 1) (org-level-increment))
7665 do (org-do-promote)))
7666 ;; If top-level, return to prev-level.
7667 ((= cur-level 1)
7668 (loop repeat (/ (- prev-level 1) (org-level-increment))
7669 do (org-do-demote)))
7670 ;; If less than prev-level, promote one.
7671 ((< cur-level prev-level)
7672 (org-do-promote))
7673 ;; If deeper than prev-level, promote until higher than
7674 ;; prev-level.
7675 ((> cur-level prev-level)
7676 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7677 do (org-do-promote))))
7678 t))))
7680 (defun org-map-tree (fun)
7681 "Call FUN for every heading underneath the current one."
7682 (org-back-to-heading)
7683 (let ((level (funcall outline-level)))
7684 (save-excursion
7685 (funcall fun)
7686 (while (and (progn
7687 (outline-next-heading)
7688 (> (funcall outline-level) level))
7689 (not (eobp)))
7690 (funcall fun)))))
7692 (defun org-map-region (fun beg end)
7693 "Call FUN for every heading between BEG and END."
7694 (let ((org-ignore-region t))
7695 (save-excursion
7696 (setq end (copy-marker end))
7697 (goto-char beg)
7698 (if (and (re-search-forward org-outline-regexp-bol nil t)
7699 (< (point) end))
7700 (funcall fun))
7701 (while (and (progn
7702 (outline-next-heading)
7703 (< (point) end))
7704 (not (eobp)))
7705 (funcall fun)))))
7707 (defvar org-property-end-re) ; silence byte-compiler
7708 (defun org-fixup-indentation (diff)
7709 "Change the indentation in the current entry by DIFF.
7710 However, if any line in the current entry has no indentation, or if it
7711 would end up with no indentation after the change, nothing at all is done."
7712 (save-excursion
7713 (let ((end (save-excursion (outline-next-heading)
7714 (point-marker)))
7715 (prohibit (if (> diff 0)
7716 "^\\S-"
7717 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7718 col)
7719 (unless (save-excursion (end-of-line 1)
7720 (re-search-forward prohibit end t))
7721 (while (and (< (point) end)
7722 (re-search-forward "^[ \t]+" end t))
7723 (goto-char (match-end 0))
7724 (setq col (current-column))
7725 (if (< diff 0) (replace-match ""))
7726 (org-indent-to-column (+ diff col))))
7727 (move-marker end nil))))
7729 (defun org-convert-to-odd-levels ()
7730 "Convert an org-mode file with all levels allowed to one with odd levels.
7731 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7732 level 5 etc."
7733 (interactive)
7734 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7735 (let ((outline-level 'org-outline-level)
7736 (org-odd-levels-only nil) n)
7737 (save-excursion
7738 (goto-char (point-min))
7739 (while (re-search-forward "^\\*\\*+ " nil t)
7740 (setq n (- (length (match-string 0)) 2))
7741 (while (>= (setq n (1- n)) 0)
7742 (org-demote))
7743 (end-of-line 1))))))
7745 (defun org-convert-to-oddeven-levels ()
7746 "Convert an org-mode file with only odd levels to one with odd/even levels.
7747 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7748 file contains a section with an even level, conversion would
7749 destroy the structure of the file. An error is signaled in this
7750 case."
7751 (interactive)
7752 (goto-char (point-min))
7753 ;; First check if there are no even levels
7754 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7755 (org-show-context t)
7756 (error "Not all levels are odd in this file. Conversion not possible"))
7757 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7758 (let ((outline-regexp org-outline-regexp)
7759 (outline-level 'org-outline-level)
7760 (org-odd-levels-only nil) n)
7761 (save-excursion
7762 (goto-char (point-min))
7763 (while (re-search-forward "^\\*\\*+ " nil t)
7764 (setq n (/ (1- (length (match-string 0))) 2))
7765 (while (>= (setq n (1- n)) 0)
7766 (org-promote))
7767 (end-of-line 1))))))
7769 (defun org-tr-level (n)
7770 "Make N odd if required."
7771 (if org-odd-levels-only (1+ (/ n 2)) n))
7773 ;;; Vertical tree motion, cutting and pasting of subtrees
7775 (defun org-move-subtree-up (&optional arg)
7776 "Move the current subtree up past ARG headlines of the same level."
7777 (interactive "p")
7778 (org-move-subtree-down (- (prefix-numeric-value arg))))
7780 (defun org-move-subtree-down (&optional arg)
7781 "Move the current subtree down past ARG headlines of the same level."
7782 (interactive "p")
7783 (setq arg (prefix-numeric-value arg))
7784 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7785 'org-get-last-sibling))
7786 (ins-point (make-marker))
7787 (cnt (abs arg))
7788 (col (current-column))
7789 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7790 ;; Select the tree
7791 (org-back-to-heading)
7792 (setq beg0 (point))
7793 (save-excursion
7794 (setq ne-beg (org-back-over-empty-lines))
7795 (setq beg (point)))
7796 (save-match-data
7797 (save-excursion (outline-end-of-heading)
7798 (setq folded (outline-invisible-p)))
7799 (outline-end-of-subtree))
7800 (outline-next-heading)
7801 (setq ne-end (org-back-over-empty-lines))
7802 (setq end (point))
7803 (goto-char beg0)
7804 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7805 ;; include less whitespace
7806 (save-excursion
7807 (goto-char beg)
7808 (forward-line (- ne-beg ne-end))
7809 (setq beg (point))))
7810 ;; Find insertion point, with error handling
7811 (while (> cnt 0)
7812 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7813 (progn (goto-char beg0)
7814 (error "Cannot move past superior level or buffer limit")))
7815 (setq cnt (1- cnt)))
7816 (if (> arg 0)
7817 ;; Moving forward - still need to move over subtree
7818 (progn (org-end-of-subtree t t)
7819 (save-excursion
7820 (org-back-over-empty-lines)
7821 (or (bolp) (newline)))))
7822 (setq ne-ins (org-back-over-empty-lines))
7823 (move-marker ins-point (point))
7824 (setq txt (buffer-substring beg end))
7825 (org-save-markers-in-region beg end)
7826 (delete-region beg end)
7827 (org-remove-empty-overlays-at beg)
7828 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7829 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7830 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7831 (let ((bbb (point)))
7832 (insert-before-markers txt)
7833 (org-reinstall-markers-in-region bbb)
7834 (move-marker ins-point bbb))
7835 (or (bolp) (insert "\n"))
7836 (setq ins-end (point))
7837 (goto-char ins-point)
7838 (org-skip-whitespace)
7839 (when (and (< arg 0)
7840 (org-first-sibling-p)
7841 (> ne-ins ne-beg))
7842 ;; Move whitespace back to beginning
7843 (save-excursion
7844 (goto-char ins-end)
7845 (let ((kill-whole-line t))
7846 (kill-line (- ne-ins ne-beg)) (point)))
7847 (insert (make-string (- ne-ins ne-beg) ?\n)))
7848 (move-marker ins-point nil)
7849 (if folded
7850 (hide-subtree)
7851 (org-show-entry)
7852 (show-children)
7853 (org-cycle-hide-drawers 'children))
7854 (org-clean-visibility-after-subtree-move)
7855 ;; move back to the initial column we were at
7856 (move-to-column col)))
7858 (defvar org-subtree-clip ""
7859 "Clipboard for cut and paste of subtrees.
7860 This is actually only a copy of the kill, because we use the normal kill
7861 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7863 (defvar org-subtree-clip-folded nil
7864 "Was the last copied subtree folded?
7865 This is used to fold the tree back after pasting.")
7867 (defun org-cut-subtree (&optional n)
7868 "Cut the current subtree into the clipboard.
7869 With prefix arg N, cut this many sequential subtrees.
7870 This is a short-hand for marking the subtree and then cutting it."
7871 (interactive "p")
7872 (org-copy-subtree n 'cut))
7874 (defun org-copy-subtree (&optional n cut force-store-markers)
7875 "Cut the current subtree into the clipboard.
7876 With prefix arg N, cut this many sequential subtrees.
7877 This is a short-hand for marking the subtree and then copying it.
7878 If CUT is non-nil, actually cut the subtree.
7879 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7880 of some markers in the region, even if CUT is non-nil. This is
7881 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7882 (interactive "p")
7883 (let (beg end folded (beg0 (point)))
7884 (if (org-called-interactively-p 'any)
7885 (org-back-to-heading nil) ; take what looks like a subtree
7886 (org-back-to-heading t)) ; take what is really there
7887 (setq beg (point))
7888 (skip-chars-forward " \t\r\n")
7889 (save-match-data
7890 (save-excursion (outline-end-of-heading)
7891 (setq folded (outline-invisible-p)))
7892 (condition-case nil
7893 (org-forward-heading-same-level (1- n) t)
7894 (error nil))
7895 (org-end-of-subtree t t))
7896 (setq end (point))
7897 (goto-char beg0)
7898 (when (> end beg)
7899 (setq org-subtree-clip-folded folded)
7900 (when (or cut force-store-markers)
7901 (org-save-markers-in-region beg end))
7902 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7903 (setq org-subtree-clip (current-kill 0))
7904 (message "%s: Subtree(s) with %d characters"
7905 (if cut "Cut" "Copied")
7906 (length org-subtree-clip)))))
7908 (defun org-paste-subtree (&optional level tree for-yank)
7909 "Paste the clipboard as a subtree, with modification of headline level.
7910 The entire subtree is promoted or demoted in order to match a new headline
7911 level.
7913 If the cursor is at the beginning of a headline, the same level as
7914 that headline is used to paste the tree
7916 If not, the new level is derived from the *visible* headings
7917 before and after the insertion point, and taken to be the inferior headline
7918 level of the two. So if the previous visible heading is level 3 and the
7919 next is level 4 (or vice versa), level 4 will be used for insertion.
7920 This makes sure that the subtree remains an independent subtree and does
7921 not swallow low level entries.
7923 You can also force a different level, either by using a numeric prefix
7924 argument, or by inserting the heading marker by hand. For example, if the
7925 cursor is after \"*****\", then the tree will be shifted to level 5.
7927 If optional TREE is given, use this text instead of the kill ring.
7929 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7930 move back over whitespace before inserting, and move point to the end of
7931 the inserted text when done."
7932 (interactive "P")
7933 (setq tree (or tree (and kill-ring (current-kill 0))))
7934 (unless (org-kill-is-subtree-p tree)
7935 (error "%s"
7936 (substitute-command-keys
7937 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7938 (org-with-limited-levels
7939 (let* ((visp (not (outline-invisible-p)))
7940 (txt tree)
7941 (^re_ "\\(\\*+\\)[ \t]*")
7942 (old-level (if (string-match org-outline-regexp-bol txt)
7943 (- (match-end 0) (match-beginning 0) 1)
7944 -1))
7945 (force-level (cond (level (prefix-numeric-value level))
7946 ((and (looking-at "[ \t]*$")
7947 (string-match
7948 "^\\*+$" (buffer-substring
7949 (point-at-bol) (point))))
7950 (- (match-end 1) (match-beginning 1)))
7951 ((and (bolp)
7952 (looking-at org-outline-regexp))
7953 (- (match-end 0) (point) 1))))
7954 (previous-level (save-excursion
7955 (condition-case nil
7956 (progn
7957 (outline-previous-visible-heading 1)
7958 (if (looking-at ^re_)
7959 (- (match-end 0) (match-beginning 0) 1)
7961 (error 1))))
7962 (next-level (save-excursion
7963 (condition-case nil
7964 (progn
7965 (or (looking-at org-outline-regexp)
7966 (outline-next-visible-heading 1))
7967 (if (looking-at ^re_)
7968 (- (match-end 0) (match-beginning 0) 1)
7970 (error 1))))
7971 (new-level (or force-level (max previous-level next-level)))
7972 (shift (if (or (= old-level -1)
7973 (= new-level -1)
7974 (= old-level new-level))
7976 (- new-level old-level)))
7977 (delta (if (> shift 0) -1 1))
7978 (func (if (> shift 0) 'org-demote 'org-promote))
7979 (org-odd-levels-only nil)
7980 beg end newend)
7981 ;; Remove the forced level indicator
7982 (if force-level
7983 (delete-region (point-at-bol) (point)))
7984 ;; Paste
7985 (beginning-of-line (if (bolp) 1 2))
7986 (setq beg (point))
7987 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7988 (insert-before-markers txt)
7989 (unless (string-match "\n\\'" txt) (insert "\n"))
7990 (setq newend (point))
7991 (org-reinstall-markers-in-region beg)
7992 (setq end (point))
7993 (goto-char beg)
7994 (skip-chars-forward " \t\n\r")
7995 (setq beg (point))
7996 (if (and (outline-invisible-p) visp)
7997 (save-excursion (outline-show-heading)))
7998 ;; Shift if necessary
7999 (unless (= shift 0)
8000 (save-restriction
8001 (narrow-to-region beg end)
8002 (while (not (= shift 0))
8003 (org-map-region func (point-min) (point-max))
8004 (setq shift (+ delta shift)))
8005 (goto-char (point-min))
8006 (setq newend (point-max))))
8007 (when (or (org-called-interactively-p 'interactive) for-yank)
8008 (message "Clipboard pasted as level %d subtree" new-level))
8009 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8010 kill-ring
8011 (eq org-subtree-clip (current-kill 0))
8012 org-subtree-clip-folded)
8013 ;; The tree was folded before it was killed/copied
8014 (hide-subtree))
8015 (and for-yank (goto-char newend)))))
8017 (defun org-kill-is-subtree-p (&optional txt)
8018 "Check if the current kill is an outline subtree, or a set of trees.
8019 Returns nil if kill does not start with a headline, or if the first
8020 headline level is not the largest headline level in the tree.
8021 So this will actually accept several entries of equal levels as well,
8022 which is OK for `org-paste-subtree'.
8023 If optional TXT is given, check this string instead of the current kill."
8024 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8025 (re (org-get-limited-outline-regexp))
8026 (^re (concat "^" re))
8027 (start-level (and kill
8028 (string-match
8029 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8030 kill)
8031 (- (match-end 2) (match-beginning 2) 1)))
8032 (start (1+ (or (match-beginning 2) -1))))
8033 (if (not start-level)
8034 (progn
8035 nil) ;; does not even start with a heading
8036 (catch 'exit
8037 (while (setq start (string-match ^re kill (1+ start)))
8038 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8039 (throw 'exit nil)))
8040 t))))
8042 (defvar org-markers-to-move nil
8043 "Markers that should be moved with a cut-and-paste operation.
8044 Those markers are stored together with their positions relative to
8045 the start of the region.")
8047 (defun org-save-markers-in-region (beg end)
8048 "Check markers in region.
8049 If these markers are between BEG and END, record their position relative
8050 to BEG, so that after moving the block of text, we can put the markers back
8051 into place.
8052 This function gets called just before an entry or tree gets cut from the
8053 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8054 called immediately, to move the markers with the entries."
8055 (setq org-markers-to-move nil)
8056 (when (featurep 'org-clock)
8057 (org-clock-save-markers-for-cut-and-paste beg end))
8058 (when (featurep 'org-agenda)
8059 (org-agenda-save-markers-for-cut-and-paste beg end)))
8061 (defun org-check-and-save-marker (marker beg end)
8062 "Check if MARKER is between BEG and END.
8063 If yes, remember the marker and the distance to BEG."
8064 (when (and (marker-buffer marker)
8065 (equal (marker-buffer marker) (current-buffer)))
8066 (if (and (>= marker beg) (< marker end))
8067 (push (cons marker (- marker beg)) org-markers-to-move))))
8069 (defun org-reinstall-markers-in-region (beg)
8070 "Move all remembered markers to their position relative to BEG."
8071 (mapc (lambda (x)
8072 (move-marker (car x) (+ beg (cdr x))))
8073 org-markers-to-move)
8074 (setq org-markers-to-move nil))
8076 (defun org-narrow-to-subtree ()
8077 "Narrow buffer to the current subtree."
8078 (interactive)
8079 (save-excursion
8080 (save-match-data
8081 (org-with-limited-levels
8082 (narrow-to-region
8083 (progn (org-back-to-heading t) (point))
8084 (progn (org-end-of-subtree t t)
8085 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8086 (point)))))))
8088 (defun org-narrow-to-block ()
8089 "Narrow buffer to the current block."
8090 (interactive)
8091 (let* ((case-fold-search t)
8092 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8093 "^[ \t]*#\\+end_.*")))
8094 (if blockp
8095 (narrow-to-region (car blockp) (cdr blockp))
8096 (error "Not in a block"))))
8098 (eval-when-compile
8099 (defvar org-property-drawer-re))
8101 (defvar org-property-start-re) ;; defined below
8102 (defun org-clone-subtree-with-time-shift (n &optional shift)
8103 "Clone the task (subtree) at point N times.
8104 The clones will be inserted as siblings.
8106 In interactive use, the user will be prompted for the number of
8107 clones to be produced, and for a time SHIFT, which may be a
8108 repeater as used in time stamps, for example `+3d'.
8110 When a valid repeater is given and the entry contains any time
8111 stamps, the clones will become a sequence in time, with time
8112 stamps in the subtree shifted for each clone produced. If SHIFT
8113 is nil or the empty string, time stamps will be left alone. The
8114 ID property of the original subtree is removed.
8116 If the original subtree did contain time stamps with a repeater,
8117 the following will happen:
8118 - the repeater will be removed in each clone
8119 - an additional clone will be produced, with the current, unshifted
8120 date(s) in the entry.
8121 - the original entry will be placed *after* all the clones, with
8122 repeater intact.
8123 - the start days in the repeater in the original entry will be shifted
8124 to past the last clone.
8125 In this way you can spell out a number of instances of a repeating task,
8126 and still retain the repeater to cover future instances of the task."
8127 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8128 (let (beg end template task idprop
8129 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8130 (drawer-re org-drawer-regexp))
8131 (if (not (and (integerp n) (> n 0)))
8132 (error "Invalid number of replications %s" n))
8133 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8134 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8135 shift)))
8136 (error "Invalid shift specification %s" shift))
8137 (when doshift
8138 (setq shift-n (string-to-number (match-string 1 shift))
8139 shift-what (cdr (assoc (match-string 2 shift)
8140 '(("d" . day) ("w" . week)
8141 ("m" . month) ("y" . year))))))
8142 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8143 (setq nmin 1 nmax n)
8144 (org-back-to-heading t)
8145 (setq beg (point))
8146 (setq idprop (org-entry-get nil "ID"))
8147 (org-end-of-subtree t t)
8148 (or (bolp) (insert "\n"))
8149 (setq end (point))
8150 (setq template (buffer-substring beg end))
8151 (when (and doshift
8152 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8153 (delete-region beg end)
8154 (setq end beg)
8155 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8156 (goto-char end)
8157 (loop for n from nmin to nmax do
8158 ;; prepare clone
8159 (with-temp-buffer
8160 (insert template)
8161 (org-mode)
8162 (goto-char (point-min))
8163 (org-show-subtree)
8164 (and idprop (if org-clone-delete-id
8165 (org-entry-delete nil "ID")
8166 (org-id-get-create t)))
8167 (unless (= n 0)
8168 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8169 (kill-whole-line))
8170 (goto-char (point-min))
8171 (while (re-search-forward drawer-re nil t)
8172 (mapc (lambda (d)
8173 (org-remove-empty-drawer-at d (point))) org-drawers)))
8174 (goto-char (point-min))
8175 (when doshift
8176 (while (re-search-forward org-ts-regexp-both nil t)
8177 (org-timestamp-change (* n shift-n) shift-what))
8178 (unless (= n n-no-remove)
8179 (goto-char (point-min))
8180 (while (re-search-forward org-ts-regexp nil t)
8181 (save-excursion
8182 (goto-char (match-beginning 0))
8183 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8184 (delete-region (match-beginning 1) (match-end 1)))))))
8185 (setq task (buffer-string)))
8186 (insert task))
8187 (goto-char beg)))
8189 ;;; Outline Sorting
8191 (defun org-sort (with-case)
8192 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8193 Optional argument WITH-CASE means sort case-sensitively."
8194 (interactive "P")
8195 (cond
8196 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8197 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8199 (org-call-with-arg 'org-sort-entries with-case))))
8201 (defun org-sort-remove-invisible (s)
8202 (remove-text-properties 0 (length s) org-rm-props s)
8203 (while (string-match org-bracket-link-regexp s)
8204 (setq s (replace-match (if (match-end 2)
8205 (match-string 3 s)
8206 (match-string 1 s)) t t s)))
8209 (defvar org-priority-regexp) ; defined later in the file
8211 (defvar org-after-sorting-entries-or-items-hook nil
8212 "Hook that is run after a bunch of entries or items have been sorted.
8213 When children are sorted, the cursor is in the parent line when this
8214 hook gets called. When a region or a plain list is sorted, the cursor
8215 will be in the first entry of the sorted region/list.")
8217 (defun org-sort-entries
8218 (&optional with-case sorting-type getkey-func compare-func property)
8219 "Sort entries on a certain level of an outline tree.
8220 If there is an active region, the entries in the region are sorted.
8221 Else, if the cursor is before the first entry, sort the top-level items.
8222 Else, the children of the entry at point are sorted.
8224 Sorting can be alphabetically, numerically, by date/time as given by
8225 a time stamp, by a property or by priority.
8227 The command prompts for the sorting type unless it has been given to the
8228 function through the SORTING-TYPE argument, which needs to be a character,
8229 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8230 precise meaning of each character:
8232 n Numerically, by converting the beginning of the entry/item to a number.
8233 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8234 o By order of TODO keywords.
8235 t By date/time, either the first active time stamp in the entry, or, if
8236 none exist, by the first inactive one.
8237 s By the scheduled date/time.
8238 d By deadline date/time.
8239 c By creation time, which is assumed to be the first inactive time stamp
8240 at the beginning of a line.
8241 p By priority according to the cookie.
8242 r By the value of a property.
8244 Capital letters will reverse the sort order.
8246 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8247 called with point at the beginning of the record. It must return either
8248 a string or a number that should serve as the sorting key for that record.
8250 Comparing entries ignores case by default. However, with an optional argument
8251 WITH-CASE, the sorting considers case as well."
8252 (interactive "P")
8253 (let ((case-func (if with-case 'identity 'downcase))
8254 (cmstr
8255 ;; The clock marker is lost when using `sort-subr', let's
8256 ;; store the clocking string.
8257 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8258 (save-excursion
8259 (goto-char org-clock-marker)
8260 (looking-back "^.*") (match-string-no-properties 0))))
8261 start beg end stars re re2
8262 txt what tmp)
8263 ;; Find beginning and end of region to sort
8264 (cond
8265 ((org-region-active-p)
8266 ;; we will sort the region
8267 (setq end (region-end)
8268 what "region")
8269 (goto-char (region-beginning))
8270 (if (not (org-at-heading-p)) (outline-next-heading))
8271 (setq start (point)))
8272 ((or (org-at-heading-p)
8273 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8274 ;; we will sort the children of the current headline
8275 (org-back-to-heading)
8276 (setq start (point)
8277 end (progn (org-end-of-subtree t t)
8278 (or (bolp) (insert "\n"))
8279 (org-back-over-empty-lines)
8280 (point))
8281 what "children")
8282 (goto-char start)
8283 (show-subtree)
8284 (outline-next-heading))
8286 ;; we will sort the top-level entries in this file
8287 (goto-char (point-min))
8288 (or (org-at-heading-p) (outline-next-heading))
8289 (setq start (point))
8290 (goto-char (point-max))
8291 (beginning-of-line 1)
8292 (when (looking-at ".*?\\S-")
8293 ;; File ends in a non-white line
8294 (end-of-line 1)
8295 (insert "\n"))
8296 (setq end (point-max))
8297 (setq what "top-level")
8298 (goto-char start)
8299 (show-all)))
8301 (setq beg (point))
8302 (if (>= beg end) (error "Nothing to sort"))
8304 (looking-at "\\(\\*+\\)")
8305 (setq stars (match-string 1)
8306 re (concat "^" (regexp-quote stars) " +")
8307 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8308 txt (buffer-substring beg end))
8309 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8310 (if (and (not (equal stars "*")) (string-match re2 txt))
8311 (error "Region to sort contains a level above the first entry"))
8313 (unless sorting-type
8314 (message
8315 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8316 [t]ime [s]cheduled [d]eadline [c]reated
8317 A/N/P/R/O/F/T/S/D/C means reversed:"
8318 what)
8319 (setq sorting-type (read-char-exclusive))
8321 (unless getkey-func
8322 (and (= (downcase sorting-type) ?f)
8323 (setq getkey-func
8324 (org-icompleting-read "Sort using function: "
8325 obarray 'fboundp t nil nil))
8326 (setq getkey-func (intern getkey-func))))
8328 (and (= (downcase sorting-type) ?r)
8329 (not property)
8330 (setq property
8331 (org-icompleting-read "Property: "
8332 (mapcar 'list (org-buffer-property-keys t))
8333 nil t))))
8335 (message "Sorting entries...")
8337 (save-restriction
8338 (narrow-to-region start end)
8339 (let ((dcst (downcase sorting-type))
8340 (case-fold-search nil)
8341 (now (current-time)))
8342 (sort-subr
8343 (/= dcst sorting-type)
8344 ;; This function moves to the beginning character of the "record" to
8345 ;; be sorted.
8346 (lambda nil
8347 (if (re-search-forward re nil t)
8348 (goto-char (match-beginning 0))
8349 (goto-char (point-max))))
8350 ;; This function moves to the last character of the "record" being
8351 ;; sorted.
8352 (lambda nil
8353 (save-match-data
8354 (condition-case nil
8355 (outline-forward-same-level 1)
8356 (error
8357 (goto-char (point-max))))))
8358 ;; This function returns the value that gets sorted against.
8359 (lambda nil
8360 (cond
8361 ((= dcst ?n)
8362 (if (looking-at org-complex-heading-regexp)
8363 (string-to-number (match-string 4))
8364 nil))
8365 ((= dcst ?a)
8366 (if (looking-at org-complex-heading-regexp)
8367 (funcall case-func (match-string 4))
8368 nil))
8369 ((= dcst ?t)
8370 (let ((end (save-excursion (outline-next-heading) (point))))
8371 (if (or (re-search-forward org-ts-regexp end t)
8372 (re-search-forward org-ts-regexp-both end t))
8373 (org-time-string-to-seconds (match-string 0))
8374 (org-float-time now))))
8375 ((= dcst ?c)
8376 (let ((end (save-excursion (outline-next-heading) (point))))
8377 (if (re-search-forward
8378 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8379 end t)
8380 (org-time-string-to-seconds (match-string 0))
8381 (org-float-time now))))
8382 ((= dcst ?s)
8383 (let ((end (save-excursion (outline-next-heading) (point))))
8384 (if (re-search-forward org-scheduled-time-regexp end t)
8385 (org-time-string-to-seconds (match-string 1))
8386 (org-float-time now))))
8387 ((= dcst ?d)
8388 (let ((end (save-excursion (outline-next-heading) (point))))
8389 (if (re-search-forward org-deadline-time-regexp end t)
8390 (org-time-string-to-seconds (match-string 1))
8391 (org-float-time now))))
8392 ((= dcst ?p)
8393 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8394 (string-to-char (match-string 2))
8395 org-default-priority))
8396 ((= dcst ?r)
8397 (or (org-entry-get nil property) ""))
8398 ((= dcst ?o)
8399 (if (looking-at org-complex-heading-regexp)
8400 (- 9999 (length (member (match-string 2)
8401 org-todo-keywords-1)))))
8402 ((= dcst ?f)
8403 (if getkey-func
8404 (progn
8405 (setq tmp (funcall getkey-func))
8406 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8407 tmp)
8408 (error "Invalid key function `%s'" getkey-func)))
8409 (t (error "Invalid sorting type `%c'" sorting-type))))
8411 (cond
8412 ((= dcst ?a) 'string<)
8413 ((= dcst ?f) compare-func)
8414 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8415 (run-hooks 'org-after-sorting-entries-or-items-hook)
8416 ;; Reset the clock marker if needed
8417 (when cmstr
8418 (save-excursion
8419 (goto-char start)
8420 (search-forward cmstr nil t)
8421 (move-marker org-clock-marker (point))))
8422 (message "Sorting entries...done")))
8424 (defun org-do-sort (table what &optional with-case sorting-type)
8425 "Sort TABLE of WHAT according to SORTING-TYPE.
8426 The user will be prompted for the SORTING-TYPE if the call to this
8427 function does not specify it. WHAT is only for the prompt, to indicate
8428 what is being sorted. The sorting key will be extracted from
8429 the car of the elements of the table.
8430 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8431 (unless sorting-type
8432 (message
8433 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8434 what)
8435 (setq sorting-type (read-char-exclusive)))
8436 (let ((dcst (downcase sorting-type))
8437 extractfun comparefun)
8438 ;; Define the appropriate functions
8439 (cond
8440 ((= dcst ?n)
8441 (setq extractfun 'string-to-number
8442 comparefun (if (= dcst sorting-type) '< '>)))
8443 ((= dcst ?a)
8444 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8445 (lambda(x) (downcase (org-sort-remove-invisible x))))
8446 comparefun (if (= dcst sorting-type)
8447 'string<
8448 (lambda (a b) (and (not (string< a b))
8449 (not (string= a b)))))))
8450 ((= dcst ?t)
8451 (setq extractfun
8452 (lambda (x)
8453 (if (or (string-match org-ts-regexp x)
8454 (string-match org-ts-regexp-both x))
8455 (org-float-time
8456 (org-time-string-to-time (match-string 0 x)))
8458 comparefun (if (= dcst sorting-type) '< '>)))
8459 (t (error "Invalid sorting type `%c'" sorting-type)))
8461 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8462 table)
8463 (lambda (a b) (funcall comparefun (car a) (car b))))))
8466 ;;; The orgstruct minor mode
8468 ;; Define a minor mode which can be used in other modes in order to
8469 ;; integrate the org-mode structure editing commands.
8471 ;; This is really a hack, because the org-mode structure commands use
8472 ;; keys which normally belong to the major mode. Here is how it
8473 ;; works: The minor mode defines all the keys necessary to operate the
8474 ;; structure commands, but wraps the commands into a function which
8475 ;; tests if the cursor is currently at a headline or a plain list
8476 ;; item. If that is the case, the structure command is used,
8477 ;; temporarily setting many Org-mode variables like regular
8478 ;; expressions for filling etc. However, when any of those keys is
8479 ;; used at a different location, function uses `key-binding' to look
8480 ;; up if the key has an associated command in another currently active
8481 ;; keymap (minor modes, major mode, global), and executes that
8482 ;; command. There might be problems if any of the keys is otherwise
8483 ;; used as a prefix key.
8485 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8486 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8487 ;; addresses this by checking explicitly for both bindings.
8489 (defvar orgstruct-mode-map (make-sparse-keymap)
8490 "Keymap for the minor `orgstruct-mode'.")
8492 (defvar org-local-vars nil
8493 "List of local variables, for use by `orgstruct-mode'.")
8495 ;;;###autoload
8496 (define-minor-mode orgstruct-mode
8497 "Toggle the minor mode `orgstruct-mode'.
8498 This mode is for using Org-mode structure commands in other
8499 modes. The following keys behave as if Org-mode were active, if
8500 the cursor is on a headline, or on a plain list item (both as
8501 defined by Org-mode).
8503 M-up Move entry/item up
8504 M-down Move entry/item down
8505 M-left Promote
8506 M-right Demote
8507 M-S-up Move entry/item up
8508 M-S-down Move entry/item down
8509 M-S-left Promote subtree
8510 M-S-right Demote subtree
8511 M-q Fill paragraph and items like in Org-mode
8512 C-c ^ Sort entries
8513 C-c - Cycle list bullet
8514 TAB Cycle item visibility
8515 M-RET Insert new heading/item
8516 S-M-RET Insert new TODO heading / Checkbox item
8517 C-c C-c Set tags / toggle checkbox"
8518 nil " OrgStruct" nil
8519 (org-load-modules-maybe)
8520 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8522 ;;;###autoload
8523 (defun turn-on-orgstruct ()
8524 "Unconditionally turn on `orgstruct-mode'."
8525 (orgstruct-mode 1))
8527 (defvar org-fb-vars nil)
8528 (make-variable-buffer-local 'org-fb-vars)
8529 (defun orgstruct++-mode (&optional arg)
8530 "Toggle `orgstruct-mode', the enhanced version of it.
8531 In addition to setting orgstruct-mode, this also exports all
8532 indentation and autofilling variables from org-mode into the
8533 buffer. It will also recognize item context in multiline items."
8534 (interactive "P")
8535 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8536 (if (< arg 1)
8537 (progn (orgstruct-mode -1)
8538 (mapc (lambda(v)
8539 (org-set-local (car v)
8540 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8541 org-fb-vars))
8542 (orgstruct-mode 1)
8543 (setq org-fb-vars nil)
8544 (let (var val)
8545 (mapc
8546 (lambda (x)
8547 (when (string-match
8548 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8549 (symbol-name (car x)))
8550 (setq var (car x) val (nth 1 x))
8551 (push (list var `(quote ,(eval var))) org-fb-vars)
8552 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8553 org-local-vars)
8554 (org-set-local 'orgstruct-is-++ t))))
8556 (defvar orgstruct-is-++ nil
8557 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8558 (make-variable-buffer-local 'orgstruct-is-++)
8560 ;;;###autoload
8561 (defun turn-on-orgstruct++ ()
8562 "Unconditionally turn on `orgstruct++-mode'."
8563 (orgstruct++-mode 1))
8565 (defun orgstruct-error ()
8566 "Error when there is no default binding for a structure key."
8567 (interactive)
8568 (error "This key has no function outside structure elements"))
8570 (defun orgstruct-setup ()
8571 "Setup orgstruct keymaps."
8572 (let ((nfunc 0)
8573 (bindings
8574 (list
8575 '([(meta up)] org-metaup)
8576 '([(meta down)] org-metadown)
8577 '([(meta left)] org-metaleft)
8578 '([(meta right)] org-metaright)
8579 '([(meta shift up)] org-shiftmetaup)
8580 '([(meta shift down)] org-shiftmetadown)
8581 '([(meta shift left)] org-shiftmetaleft)
8582 '([(meta shift right)] org-shiftmetaright)
8583 '([?\e (up)] org-metaup)
8584 '([?\e (down)] org-metadown)
8585 '([?\e (left)] org-metaleft)
8586 '([?\e (right)] org-metaright)
8587 '([?\e (shift up)] org-shiftmetaup)
8588 '([?\e (shift down)] org-shiftmetadown)
8589 '([?\e (shift left)] org-shiftmetaleft)
8590 '([?\e (shift right)] org-shiftmetaright)
8591 '([(shift up)] org-shiftup)
8592 '([(shift down)] org-shiftdown)
8593 '([(shift left)] org-shiftleft)
8594 '([(shift right)] org-shiftright)
8595 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8596 '("\M-q" fill-paragraph)
8597 '("\C-c^" org-sort)
8598 '("\C-c-" org-cycle-list-bullet)))
8599 elt key fun cmd)
8600 (while (setq elt (pop bindings))
8601 (setq nfunc (1+ nfunc))
8602 (setq key (org-key (car elt))
8603 fun (nth 1 elt)
8604 cmd (orgstruct-make-binding fun nfunc key))
8605 (org-defkey orgstruct-mode-map key cmd))
8607 ;; Prevent an error for users who forgot to make autoloads
8608 (require 'org-element)
8610 ;; Special treatment needed for TAB and RET
8611 (org-defkey orgstruct-mode-map [(tab)]
8612 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8613 (org-defkey orgstruct-mode-map "\C-i"
8614 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8616 (org-defkey orgstruct-mode-map "\M-\C-m"
8617 (orgstruct-make-binding 'org-insert-heading 105
8618 "\M-\C-m" [(meta return)]))
8619 (org-defkey orgstruct-mode-map [(meta return)]
8620 (orgstruct-make-binding 'org-insert-heading 106
8621 [(meta return)] "\M-\C-m"))
8623 (org-defkey orgstruct-mode-map [(shift meta return)]
8624 (orgstruct-make-binding 'org-insert-todo-heading 107
8625 [(meta return)] "\M-\C-m"))
8627 (org-defkey orgstruct-mode-map "\e\C-m"
8628 (orgstruct-make-binding 'org-insert-heading 108
8629 "\e\C-m" [?\e (return)]))
8630 (org-defkey orgstruct-mode-map [?\e (return)]
8631 (orgstruct-make-binding 'org-insert-heading 109
8632 [?\e (return)] "\e\C-m"))
8633 (org-defkey orgstruct-mode-map [?\e (shift return)]
8634 (orgstruct-make-binding 'org-insert-todo-heading 110
8635 [?\e (return)] "\e\C-m"))
8637 (unless org-local-vars
8638 (setq org-local-vars (org-get-local-variables)))
8642 (defun orgstruct-make-binding (fun n &rest keys)
8643 "Create a function for binding in the structure minor mode.
8644 FUN is the command to call inside a table. N is used to create a unique
8645 command name. KEYS are keys that should be checked in for a command
8646 to execute outside of tables."
8647 (eval
8648 (list 'defun
8649 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8650 '(arg)
8651 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8652 "Outside of structure, run the binding of `"
8653 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8654 "'.")
8655 '(interactive "p")
8656 (list 'if
8657 `(org-context-p 'headline 'item
8658 (and orgstruct-is-++
8659 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8660 'item-body))
8661 (list 'org-run-like-in-org-mode (list 'quote fun))
8662 (list 'let '(orgstruct-mode)
8663 (list 'call-interactively
8664 (append '(or)
8665 (mapcar (lambda (k)
8666 (list 'key-binding k))
8667 keys)
8668 '('orgstruct-error))))))))
8670 (defun org-contextualize-keys (alist contexts)
8671 "Return valid elements in ALIST depending on CONTEXTS.
8673 `org-agenda-custom-commands' or `org-capture-templates' are the
8674 values used for ALIST, and `org-agenda-custom-commands-contexts'
8675 or `org-capture-templates-contexts' are the associated contexts
8676 definitions."
8677 (let ((contexts
8678 ;; normalize contexts
8679 (mapcar
8680 (lambda(c) (cond ((listp (cadr c))
8681 (list (car c) (car c) (cadr c)))
8682 ((string= "" (cadr c))
8683 (list (car c) (car c) (caddr c)))
8684 (t c))) contexts))
8685 (a alist) c r s)
8686 ;; loop over all commands or templates
8687 (while (setq c (pop a))
8688 (let (vrules repl)
8689 (cond
8690 ((not (assoc (car c) contexts))
8691 (push c r))
8692 ((and (assoc (car c) contexts)
8693 (setq vrules (org-contextualize-validate-key
8694 (car c) contexts)))
8695 (mapc (lambda (vr)
8696 (when (not (equal (car vr) (cadr vr)))
8697 (setq repl vr))) vrules)
8698 (if (not repl) (push c r)
8699 (push (cadr repl) s)
8700 (push
8701 (cons (car c)
8702 (cdr (or (assoc (cadr repl) alist)
8703 (error "Undefined key `%s' as contextual replacement for `%s'"
8704 (cadr repl) (car c)))))
8705 r))))))
8706 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8707 (delq
8709 (delete-dups
8710 (mapcar (lambda (x)
8711 (let ((tpl (car x)))
8712 (when (not (delq
8714 (mapcar (lambda(y)
8715 (equal y tpl)) s))) x)))
8716 (reverse r))))))
8718 (defun org-contextualize-validate-key (key contexts)
8719 "Check CONTEXTS for agenda or capture KEY."
8720 (let (r rr res)
8721 (while (setq r (pop contexts))
8722 (mapc
8723 (lambda (rr)
8724 (when
8725 (and (equal key (car r))
8726 (if (functionp rr) (funcall rr)
8727 (or (and (eq (car rr) 'in-file)
8728 (buffer-file-name)
8729 (string-match (cdr rr) (buffer-file-name)))
8730 (and (eq (car rr) 'in-mode)
8731 (string-match (cdr rr) (symbol-name major-mode)))
8732 (when (and (eq (car rr) 'not-in-file)
8733 (buffer-file-name))
8734 (not (string-match (cdr rr) (buffer-file-name))))
8735 (when (eq (car rr) 'not-in-mode)
8736 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8737 (push r res)))
8738 (car (last r))))
8739 (delete-dups (delq nil res))))
8741 (defun org-context-p (&rest contexts)
8742 "Check if local context is any of CONTEXTS.
8743 Possible values in the list of contexts are `table', `headline', and `item'."
8744 (let ((pos (point)))
8745 (goto-char (point-at-bol))
8746 (prog1 (or (and (memq 'table contexts)
8747 (looking-at "[ \t]*|"))
8748 (and (memq 'headline contexts)
8749 (looking-at org-outline-regexp))
8750 (and (memq 'item contexts)
8751 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8752 (and (memq 'item-body contexts)
8753 (org-in-item-p)))
8754 (goto-char pos))))
8756 (defun org-get-local-variables ()
8757 "Return a list of all local variables in an Org mode buffer."
8758 (let (varlist)
8759 (with-current-buffer (get-buffer-create "*Org tmp*")
8760 (erase-buffer)
8761 (org-mode)
8762 (setq varlist (buffer-local-variables)))
8763 (kill-buffer "*Org tmp*")
8764 (delq nil
8765 (mapcar
8766 (lambda (x)
8767 (setq x
8768 (if (symbolp x)
8769 (list x)
8770 (list (car x) (list 'quote (cdr x)))))
8771 (if (string-match
8772 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8773 (symbol-name (car x)))
8774 x nil))
8775 varlist))))
8777 (defun org-clone-local-variables (from-buffer &optional regexp)
8778 "Clone local variables from FROM-BUFFER.
8779 Optional argument REGEXP selects variables to clone."
8780 (mapc
8781 (lambda (pair)
8782 (and (symbolp (car pair))
8783 (or (null regexp)
8784 (string-match regexp (symbol-name (car pair))))
8785 (set (make-local-variable (car pair))
8786 (cdr pair))))
8787 (buffer-local-variables from-buffer)))
8789 ;;;###autoload
8790 (defun org-run-like-in-org-mode (cmd)
8791 "Run a command, pretending that the current buffer is in Org-mode.
8792 This will temporarily bind local variables that are typically bound in
8793 Org-mode to the values they have in Org-mode, and then interactively
8794 call CMD."
8795 (org-load-modules-maybe)
8796 (unless org-local-vars
8797 (setq org-local-vars (org-get-local-variables)))
8798 (eval (list 'let org-local-vars
8799 (list 'call-interactively (list 'quote cmd)))))
8801 ;;;; Archiving
8803 (defun org-get-category (&optional pos force-refresh)
8804 "Get the category applying to position POS."
8805 (save-match-data
8806 (if force-refresh (org-refresh-category-properties))
8807 (let ((pos (or pos (point))))
8808 (or (get-text-property pos 'org-category)
8809 (progn (org-refresh-category-properties)
8810 (get-text-property pos 'org-category))))))
8812 (defun org-refresh-category-properties ()
8813 "Refresh category text properties in the buffer."
8814 (let ((case-fold-search t)
8815 (inhibit-read-only t)
8816 (def-cat (cond
8817 ((null org-category)
8818 (if buffer-file-name
8819 (file-name-sans-extension
8820 (file-name-nondirectory buffer-file-name))
8821 "???"))
8822 ((symbolp org-category) (symbol-name org-category))
8823 (t org-category)))
8824 beg end cat pos optionp)
8825 (org-unmodified
8826 (save-excursion
8827 (save-restriction
8828 (widen)
8829 (goto-char (point-min))
8830 (put-text-property (point) (point-max) 'org-category def-cat)
8831 (while (re-search-forward
8832 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8833 (setq pos (match-end 0)
8834 optionp (equal (char-after (match-beginning 0)) ?#)
8835 cat (org-trim (match-string 2)))
8836 (if optionp
8837 (setq beg (point-at-bol) end (point-max))
8838 (org-back-to-heading t)
8839 (setq beg (point) end (org-end-of-subtree t t)))
8840 (put-text-property beg end 'org-category cat)
8841 (put-text-property beg end 'org-category-position beg)
8842 (goto-char pos)))))))
8844 (defun org-refresh-properties (dprop tprop)
8845 "Refresh buffer text properties.
8846 DPROP is the drawer property and TPROP is the corresponding text
8847 property to set."
8848 (let ((case-fold-search t)
8849 (inhibit-read-only t) p)
8850 (org-unmodified
8851 (save-excursion
8852 (save-restriction
8853 (widen)
8854 (goto-char (point-min))
8855 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8856 (setq p (org-match-string-no-properties 1))
8857 (save-excursion
8858 (org-back-to-heading t)
8859 (put-text-property
8860 (point-at-bol) (point-at-eol) tprop p))))))))
8863 ;;;; Link Stuff
8865 ;;; Link abbreviations
8867 (defun org-link-expand-abbrev (link)
8868 "Apply replacements as defined in `org-link-abbrev-alist'."
8869 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8870 (let* ((key (match-string 1 link))
8871 (as (or (assoc key org-link-abbrev-alist-local)
8872 (assoc key org-link-abbrev-alist)))
8873 (tag (and (match-end 2) (match-string 3 link)))
8874 rpl)
8875 (if (not as)
8876 link
8877 (setq rpl (cdr as))
8878 (cond
8879 ((symbolp rpl) (funcall rpl tag))
8880 ((string-match "%(\\([^)]+\\))" rpl)
8881 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8882 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8883 ((string-match "%h" rpl)
8884 (replace-match (url-hexify-string (or tag "")) t t rpl))
8885 (t (concat rpl tag)))))
8886 link))
8888 ;;; Storing and inserting links
8890 (defvar org-insert-link-history nil
8891 "Minibuffer history for links inserted with `org-insert-link'.")
8893 (defvar org-stored-links nil
8894 "Contains the links stored with `org-store-link'.")
8896 (defvar org-store-link-plist nil
8897 "Plist with info about the most recently link created with `org-store-link'.")
8899 (defvar org-link-protocols nil
8900 "Link protocols added to Org-mode using `org-add-link-type'.")
8902 (defvar org-store-link-functions nil
8903 "List of functions that are called to create and store a link.
8904 Each function will be called in turn until one returns a non-nil
8905 value. Each function should check if it is responsible for creating
8906 this link (for example by looking at the major mode).
8907 If not, it must exit and return nil.
8908 If yes, it should return a non-nil value after a calling
8909 `org-store-link-props' with a list of properties and values.
8910 Special properties are:
8912 :type The link prefix, like \"http\". This must be given.
8913 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8914 This is obligatory as well.
8915 :description Optional default description for the second pair
8916 of brackets in an Org-mode link. The user can still change
8917 this when inserting this link into an Org-mode buffer.
8919 In addition to these, any additional properties can be specified
8920 and then used in capture templates.")
8922 (defun org-add-link-type (type &optional follow export)
8923 "Add TYPE to the list of `org-link-types'.
8924 Re-compute all regular expressions depending on `org-link-types'
8926 FOLLOW and EXPORT are two functions.
8928 FOLLOW should take the link path as the single argument and do whatever
8929 is necessary to follow the link, for example find a file or display
8930 a mail message.
8932 EXPORT should format the link path for export to one of the export formats.
8933 It should be a function accepting three arguments:
8935 path the path of the link, the text after the prefix (like \"http:\")
8936 desc the description of the link, if any, or a description added by
8937 org-export-normalize-links if there is none
8938 format the export format, a symbol like `html' or `latex' or `ascii'..
8940 The function may use the FORMAT information to return different values
8941 depending on the format. The return value will be put literally into
8942 the exported file. If the return value is nil, this means Org should
8943 do what it normally does with links which do not have EXPORT defined.
8945 Org-mode has a built-in default for exporting links. If you are happy with
8946 this default, there is no need to define an export function for the link
8947 type. For a simple example of an export function, see `org-bbdb.el'."
8948 (add-to-list 'org-link-types type t)
8949 (org-make-link-regexps)
8950 (if (assoc type org-link-protocols)
8951 (setcdr (assoc type org-link-protocols) (list follow export))
8952 (push (list type follow export) org-link-protocols)))
8954 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8955 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8957 ;;;###autoload
8958 (defun org-store-link (arg)
8959 "\\<org-mode-map>Store an org-link to the current location.
8960 This link is added to `org-stored-links' and can later be inserted
8961 into an org-buffer with \\[org-insert-link].
8963 For some link types, a prefix arg is interpreted.
8964 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8965 For file links, arg negates `org-context-in-file-links'.
8967 A double prefix arg force skipping storing functions that are not
8968 part of Org's core."
8969 (interactive "P")
8970 (org-load-modules-maybe)
8971 (setq org-store-link-plist nil) ; reset
8972 (org-with-limited-levels
8973 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8974 (cond
8975 ((and (not (equal arg '(16)))
8976 (setq sfuns
8977 (delq
8978 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8979 org-store-link-functions))
8980 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8981 (or (and (cdr sfuns)
8982 (funcall (intern
8983 (completing-read "Which function for creating the link? "
8984 sfunsn t (car sfunsn)))))
8985 (funcall (caar sfuns)))
8986 (setq link (plist-get org-store-link-plist :link)
8987 desc (or (plist-get org-store-link-plist :description) link))))
8988 ((org-src-edit-buffer-p)
8989 (let (label gc)
8990 (while (or (not label)
8991 (save-excursion
8992 (save-restriction
8993 (widen)
8994 (goto-char (point-min))
8995 (re-search-forward
8996 (regexp-quote (format org-coderef-label-format label))
8997 nil t))))
8998 (when label (message "Label exists already") (sit-for 2))
8999 (setq label (read-string "Code line label: " label)))
9000 (end-of-line 1)
9001 (setq link (format org-coderef-label-format label))
9002 (setq gc (- 79 (length link)))
9003 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9004 (insert link)
9005 (setq link (concat "(" label ")") desc nil)))
9007 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9008 ;; We are in the agenda, link to referenced location
9009 (let ((m (or (get-text-property (point) 'org-hd-marker)
9010 (get-text-property (point) 'org-marker))))
9011 (when m
9012 (org-with-point-at m
9013 (setq agenda-link
9014 (if (org-called-interactively-p 'any)
9015 (call-interactively 'org-store-link)
9016 (org-store-link nil)))))))
9018 ((eq major-mode 'calendar-mode)
9019 (let ((cd (calendar-cursor-to-date)))
9020 (setq link
9021 (format-time-string
9022 (car org-time-stamp-formats)
9023 (apply 'encode-time
9024 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9025 nil nil nil))))
9026 (org-store-link-props :type "calendar" :date cd)))
9028 ((eq major-mode 'help-mode)
9029 (setq link (concat "help:" (save-excursion
9030 (goto-char (point-min))
9031 (looking-at "^[^ ]+")
9032 (match-string 0))))
9033 (org-store-link-props :type "help"))
9035 ((eq major-mode 'w3-mode)
9036 (setq cpltxt (if (and (buffer-name)
9037 (not (string-match "Untitled" (buffer-name))))
9038 (buffer-name)
9039 (url-view-url t))
9040 link (url-view-url t))
9041 (org-store-link-props :type "w3" :url (url-view-url t)))
9043 ((setq search (run-hook-with-args-until-success
9044 'org-create-file-search-functions))
9045 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9046 "::" search))
9047 (setq cpltxt (or description link)))
9049 ((eq major-mode 'image-mode)
9050 (setq cpltxt (concat "file:"
9051 (abbreviate-file-name buffer-file-name))
9052 link cpltxt)
9053 (org-store-link-props :type "image" :file buffer-file-name))
9055 ((eq major-mode 'dired-mode)
9056 ;; link to the file in the current line
9057 (let ((file (dired-get-filename nil t)))
9058 (setq file (if file
9059 (abbreviate-file-name
9060 (expand-file-name (dired-get-filename nil t)))
9061 ;; otherwise, no file so use current directory.
9062 default-directory))
9063 (setq cpltxt (concat "file:" file)
9064 link cpltxt)))
9066 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9067 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9068 (cond
9069 ((org-in-regexp "<<\\(.*?\\)>>")
9070 (setq cpltxt
9071 (concat "file:"
9072 (abbreviate-file-name
9073 (buffer-file-name (buffer-base-buffer)))
9074 "::" (match-string 1))
9075 link cpltxt))
9076 ((and (featurep 'org-id)
9077 (or (eq org-id-link-to-org-use-id t)
9078 (and (org-called-interactively-p 'any)
9079 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9080 (and (eq org-id-link-to-org-use-id
9081 'create-if-interactive-and-no-custom-id)
9082 (not custom-id))))
9083 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9084 ;; We can make a link using the ID.
9085 (setq link (condition-case nil
9086 (prog1 (org-id-store-link)
9087 (setq desc (plist-get org-store-link-plist :description)))
9088 (error
9089 ;; probably before first headline, link to file only
9090 (concat "file:"
9091 (abbreviate-file-name
9092 (buffer-file-name (buffer-base-buffer))))))))
9094 ;; Just link to current headline
9095 (setq cpltxt (concat "file:"
9096 (abbreviate-file-name
9097 (buffer-file-name (buffer-base-buffer)))))
9098 ;; Add a context search string
9099 (when (org-xor org-context-in-file-links arg)
9100 (let* ((ee (org-element-at-point))
9101 (et (org-element-type ee))
9102 (ev (plist-get (cadr ee) :value)))
9103 (setq txt (cond
9104 ((org-at-heading-p) nil)
9105 ((eq et 'keyword) ev)
9106 ((org-region-active-p)
9107 (buffer-substring (region-beginning) (region-end)))))
9108 (when (or (null txt) (string-match "\\S-" txt))
9109 (setq cpltxt
9110 (concat cpltxt "::"
9111 (condition-case nil
9112 (org-make-org-heading-search-string txt)
9113 (error "")))
9114 desc (or (and (eq et 'keyword) ev)
9115 (nth 4 (ignore-errors (org-heading-components)))
9116 "NONE")))))
9117 (if (string-match "::\\'" cpltxt)
9118 (setq cpltxt (substring cpltxt 0 -2)))
9119 (setq link cpltxt))))
9121 ((buffer-file-name (buffer-base-buffer))
9122 ;; Just link to this file here.
9123 (setq cpltxt (concat "file:"
9124 (abbreviate-file-name
9125 (buffer-file-name (buffer-base-buffer)))))
9126 ;; Add a context string
9127 (when (org-xor org-context-in-file-links arg)
9128 (setq txt (if (org-region-active-p)
9129 (buffer-substring (region-beginning) (region-end))
9130 (buffer-substring (point-at-bol) (point-at-eol))))
9131 ;; Only use search option if there is some text.
9132 (when (string-match "\\S-" txt)
9133 (setq cpltxt
9134 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9135 desc "NONE")))
9136 (setq link cpltxt))
9138 ((org-called-interactively-p 'interactive)
9139 (user-error "No method for storing a link from this buffer"))
9141 (t (setq link nil)))
9143 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9144 (setq link (or link cpltxt)
9145 desc (or desc cpltxt))
9146 (cond ((equal desc "NONE") (setq desc nil))
9147 ((string-match org-bracket-link-regexp desc)
9148 (setq desc (replace-regexp-in-string
9149 org-bracket-link-regexp
9150 (concat "\\3" (if (equal (length (match-string 0 desc))
9151 (length desc)) "*" "")) desc))))
9153 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9154 (progn
9155 (setq org-stored-links
9156 (cons (list link desc) org-stored-links))
9157 (message "Stored: %s" (or desc link))
9158 (when custom-id
9159 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9160 "::#" custom-id))
9161 (setq org-stored-links
9162 (cons (list link desc) org-stored-links))))
9163 (or agenda-link (and link (org-make-link-string link desc)))))))
9165 (defun org-store-link-props (&rest plist)
9166 "Store link properties, extract names and addresses."
9167 (let (x adr)
9168 (when (setq x (plist-get plist :from))
9169 (setq adr (mail-extract-address-components x))
9170 (setq plist (plist-put plist :fromname (car adr)))
9171 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9172 (when (setq x (plist-get plist :to))
9173 (setq adr (mail-extract-address-components x))
9174 (setq plist (plist-put plist :toname (car adr)))
9175 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9176 (let ((from (plist-get plist :from))
9177 (to (plist-get plist :to)))
9178 (when (and from to org-from-is-user-regexp)
9179 (setq plist
9180 (plist-put plist :fromto
9181 (if (string-match org-from-is-user-regexp from)
9182 (concat "to %t")
9183 (concat "from %f"))))))
9184 (setq org-store-link-plist plist))
9186 (defun org-add-link-props (&rest plist)
9187 "Add these properties to the link property list."
9188 (let (key value)
9189 (while plist
9190 (setq key (pop plist) value (pop plist))
9191 (setq org-store-link-plist
9192 (plist-put org-store-link-plist key value)))))
9194 (defun org-email-link-description (&optional fmt)
9195 "Return the description part of an email link.
9196 This takes information from `org-store-link-plist' and formats it
9197 according to FMT (default from `org-email-link-description-format')."
9198 (setq fmt (or fmt org-email-link-description-format))
9199 (let* ((p org-store-link-plist)
9200 (to (plist-get p :toaddress))
9201 (from (plist-get p :fromaddress))
9202 (table
9203 (list
9204 (cons "%c" (plist-get p :fromto))
9205 (cons "%F" (plist-get p :from))
9206 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9207 (cons "%T" (plist-get p :to))
9208 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9209 (cons "%s" (plist-get p :subject))
9210 (cons "%d" (plist-get p :date))
9211 (cons "%m" (plist-get p :message-id)))))
9212 (when (string-match "%c" fmt)
9213 ;; Check if the user wrote this message
9214 (if (and org-from-is-user-regexp from to
9215 (save-match-data (string-match org-from-is-user-regexp from)))
9216 (setq fmt (replace-match "to %t" t t fmt))
9217 (setq fmt (replace-match "from %f" t t fmt))))
9218 (org-replace-escapes fmt table)))
9220 (defun org-make-org-heading-search-string (&optional string)
9221 "Make search string for the current headline or STRING."
9222 (let ((s (or string
9223 (and (derived-mode-p 'org-mode)
9224 (save-excursion
9225 (org-back-to-heading t)
9226 (plist-get (cadr (org-element-at-point))
9227 :raw-value)))))
9228 (lines org-context-in-file-links))
9229 (or string (setq s (concat "*" s))) ; Add * for headlines
9230 (when (and string (integerp lines) (> lines 0))
9231 (let ((slines (org-split-string s "\n")))
9232 (when (< lines (length slines))
9233 (setq s (mapconcat
9234 'identity
9235 (reverse (nthcdr (- (length slines) lines)
9236 (reverse slines))) "\n")))))
9237 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9239 (defun org-make-link-string (link &optional description)
9240 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9241 (unless (string-match "\\S-" link)
9242 (error "Empty link"))
9243 (when (and description
9244 (stringp description)
9245 (not (string-match "\\S-" description)))
9246 (setq description nil))
9247 (when (stringp description)
9248 ;; Remove brackets from the description, they are fatal.
9249 (while (string-match "\\[" description)
9250 (setq description (replace-match "{" t t description)))
9251 (while (string-match "\\]" description)
9252 (setq description (replace-match "}" t t description))))
9253 (when (equal link description)
9254 ;; No description needed, it is identical
9255 (setq description nil))
9256 (when (and (not description)
9257 (not (string-match (org-image-file-name-regexp) link))
9258 (not (equal link (org-link-escape link))))
9259 (setq description (org-extract-attributes link)))
9260 (setq link
9261 (cond ((string-match (org-image-file-name-regexp) link) link)
9262 ((string-match org-link-types-re link)
9263 (concat (match-string 1 link)
9264 (org-link-escape (substring link (match-end 1)))))
9265 (t (org-link-escape link))))
9266 (concat "[[" link "]"
9267 (if description (concat "[" description "]") "")
9268 "]"))
9270 (defconst org-link-escape-chars
9271 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9272 "List of characters that should be escaped in link.
9273 This is the list that is used for internal purposes.")
9275 (defconst org-link-escape-chars-browser
9276 '(?\ )
9277 "List of escapes for characters that are problematic in links.
9278 This is the list that is used before handing over to the browser.")
9280 (defun org-link-escape (text &optional table merge)
9281 "Return percent escaped representation of TEXT.
9282 TEXT is a string with the text to escape.
9283 Optional argument TABLE is a list with characters that should be
9284 escaped. When nil, `org-link-escape-chars' is used.
9285 If optional argument MERGE is set, merge TABLE into
9286 `org-link-escape-chars'."
9287 (cond
9288 ((and table merge)
9289 (mapc (lambda (defchr)
9290 (unless (member defchr table)
9291 (setq table (cons defchr table)))) org-link-escape-chars))
9292 ((null table)
9293 (setq table org-link-escape-chars)))
9294 (mapconcat
9295 (lambda (char)
9296 (if (or (member char table)
9297 (and (or (< char 32) (= char 37) (> char 126))
9298 org-url-hexify-p))
9299 (mapconcat (lambda (sequence-element)
9300 (format "%%%.2X" sequence-element))
9301 (or (encode-coding-char char 'utf-8)
9302 (error "Unable to percent escape character: %s"
9303 (char-to-string char))) "")
9304 (char-to-string char))) text ""))
9306 (defun org-link-unescape (str)
9307 "Unhex hexified Unicode strings as returned from the JavaScript function
9308 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9309 (unless (and (null str) (string= "" str))
9310 (let ((pos 0) (case-fold-search t) unhexed)
9311 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9312 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9313 (setq str (replace-match unhexed t t str))
9314 (setq pos (+ pos (length unhexed))))))
9315 str)
9317 (defun org-link-unescape-compound (hex)
9318 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9319 Note: this function also decodes single byte encodings like
9320 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9321 (save-match-data
9322 (let* ((bytes (cdr (split-string hex "%")))
9323 (ret "")
9324 (eat 0)
9325 (sum 0))
9326 (while bytes
9327 (let* ((val (string-to-number (pop bytes) 16))
9328 (shift-xor
9329 (if (= 0 eat)
9330 (cond
9331 ((>= val 252) (cons 6 252))
9332 ((>= val 248) (cons 5 248))
9333 ((>= val 240) (cons 4 240))
9334 ((>= val 224) (cons 3 224))
9335 ((>= val 192) (cons 2 192))
9336 (t (cons 0 0)))
9337 (cons 6 128))))
9338 (if (>= val 192) (setq eat (car shift-xor)))
9339 (setq val (logxor val (cdr shift-xor)))
9340 (setq sum (+ (lsh sum (car shift-xor)) val))
9341 (if (> eat 0) (setq eat (- eat 1)))
9342 (cond
9343 ((= 0 eat) ;multi byte
9344 (setq ret (concat ret (org-char-to-string sum)))
9345 (setq sum 0))
9346 ((not bytes) ; single byte(s)
9347 (setq ret (org-link-unescape-single-byte-sequence hex))))
9348 )) ;; end (while bytes
9349 ret )))
9351 (defun org-link-unescape-single-byte-sequence (hex)
9352 "Unhexify hex-encoded single byte character sequences."
9353 (mapconcat (lambda (byte)
9354 (char-to-string (string-to-number byte 16)))
9355 (cdr (split-string hex "%")) ""))
9357 (defun org-xor (a b)
9358 "Exclusive or."
9359 (if a (not b) b))
9361 (defun org-fixup-message-id-for-http (s)
9362 "Replace special characters in a message id, so it can be used in an http query."
9363 (when (string-match "%" s)
9364 (setq s (mapconcat (lambda (c)
9365 (if (eq c ?%)
9366 "%25"
9367 (char-to-string c)))
9368 s "")))
9369 (while (string-match "<" s)
9370 (setq s (replace-match "%3C" t t s)))
9371 (while (string-match ">" s)
9372 (setq s (replace-match "%3E" t t s)))
9373 (while (string-match "@" s)
9374 (setq s (replace-match "%40" t t s)))
9377 (defun org-link-prettify (link)
9378 "Return a human-readable representation of LINK.
9379 The car of LINK must be a raw link the cdr of LINK must be either
9380 a link description or nil."
9381 (let ((desc (or (cadr link) "<no description>")))
9382 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9383 "<" (car link) ">")))
9385 ;;;###autoload
9386 (defun org-insert-link-global ()
9387 "Insert a link like Org-mode does.
9388 This command can be called in any mode to insert a link in Org-mode syntax."
9389 (interactive)
9390 (org-load-modules-maybe)
9391 (org-run-like-in-org-mode 'org-insert-link))
9393 (defun org-insert-all-links (&optional keep)
9394 "Insert all links in `org-stored-links'."
9395 (interactive "P")
9396 (let ((links (copy-sequence org-stored-links)) l)
9397 (while (setq l (if keep (pop links) (pop org-stored-links)))
9398 (insert "- ")
9399 (org-insert-link nil (car l) (cadr l))
9400 (insert "\n"))))
9402 (defun org-link-fontify-links-to-this-file ()
9403 "Fontify links to the current file in `org-stored-links'."
9404 (let ((f (buffer-file-name)) a b)
9405 (setq a (mapcar (lambda(l)
9406 (let ((ll (car l)))
9407 (when (and (string-match "^file:\\(.+\\)::" ll)
9408 (equal f (expand-file-name (match-string 1 ll))))
9409 ll)))
9410 org-stored-links))
9411 (when (featurep 'org-id)
9412 (setq b (mapcar (lambda(l)
9413 (let ((ll (car l)))
9414 (when (and (string-match "^id:\\(.+\\)$" ll)
9415 (equal f (expand-file-name
9416 (or (org-id-find-id-file
9417 (match-string 1 ll)) ""))))
9418 ll)))
9419 org-stored-links)))
9420 (mapcar (lambda(l)
9421 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9422 (delq nil (append a b)))))
9424 (defvar org-link-links-in-this-file nil)
9425 (defun org-insert-link (&optional complete-file link-location default-description)
9426 "Insert a link. At the prompt, enter the link.
9428 Completion can be used to insert any of the link protocol prefixes like
9429 http or ftp in use.
9431 The history can be used to select a link previously stored with
9432 `org-store-link'. When the empty string is entered (i.e. if you just
9433 press RET at the prompt), the link defaults to the most recently
9434 stored link. As SPC triggers completion in the minibuffer, you need to
9435 use M-SPC or C-q SPC to force the insertion of a space character.
9437 You will also be prompted for a description, and if one is given, it will
9438 be displayed in the buffer instead of the link.
9440 If there is already a link at point, this command will allow you to edit link
9441 and description parts.
9443 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9444 be selected using completion. The path to the file will be relative to the
9445 current directory if the file is in the current directory or a subdirectory.
9446 Otherwise, the link will be the absolute path as completed in the minibuffer
9447 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9448 option `org-link-file-path-type'.
9450 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9451 the current directory or below.
9453 With three \\[universal-argument] prefixes, negate the meaning of
9454 `org-keep-stored-link-after-insertion'.
9456 If `org-make-link-description-function' is non-nil, this function will be
9457 called with the link target, and the result will be the default
9458 link description.
9460 If the LINK-LOCATION parameter is non-nil, this value will be
9461 used as the link location instead of reading one interactively.
9463 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9464 be used as the default description."
9465 (interactive "P")
9466 (let* ((wcf (current-window-configuration))
9467 (origbuf (current-buffer))
9468 (region (if (org-region-active-p)
9469 (buffer-substring (region-beginning) (region-end))))
9470 (remove (and region (list (region-beginning) (region-end))))
9471 (desc region)
9472 tmphist ; byte-compile incorrectly complains about this
9473 (link link-location)
9474 (abbrevs org-link-abbrev-alist-local)
9475 entry file all-prefixes auto-desc)
9476 (cond
9477 (link-location) ; specified by arg, just use it.
9478 ((org-in-regexp org-bracket-link-regexp 1)
9479 ;; We do have a link at point, and we are going to edit it.
9480 (setq remove (list (match-beginning 0) (match-end 0)))
9481 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9482 (setq link (read-string "Link: "
9483 (org-link-unescape
9484 (org-match-string-no-properties 1)))))
9485 ((or (org-in-regexp org-angle-link-re)
9486 (org-in-regexp org-plain-link-re))
9487 ;; Convert to bracket link
9488 (setq remove (list (match-beginning 0) (match-end 0))
9489 link (read-string "Link: "
9490 (org-remove-angle-brackets (match-string 0)))))
9491 ((member complete-file '((4) (16)))
9492 ;; Completing read for file names.
9493 (setq link (org-file-complete-link complete-file)))
9495 ;; Read link, with completion for stored links.
9496 (org-link-fontify-links-to-this-file)
9497 (org-switch-to-buffer-other-window "*Org Links*")
9498 (with-current-buffer "*Org Links*"
9499 (erase-buffer)
9500 (insert "Insert a link.
9501 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9502 (when org-stored-links
9503 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9504 (insert (mapconcat 'org-link-prettify
9505 (reverse org-stored-links) "\n")))
9506 (goto-char (point-min)))
9507 (let ((cw (selected-window)))
9508 (select-window (get-buffer-window "*Org Links*" 'visible))
9509 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9510 (unless (pos-visible-in-window-p (point-max))
9511 (org-fit-window-to-buffer))
9512 (and (window-live-p cw) (select-window cw)))
9513 ;; Fake a link history, containing the stored links.
9514 (setq tmphist (append (mapcar 'car org-stored-links)
9515 org-insert-link-history))
9516 (setq all-prefixes (append (mapcar 'car abbrevs)
9517 (mapcar 'car org-link-abbrev-alist)
9518 org-link-types))
9519 (unwind-protect
9520 (progn
9521 (setq link
9522 (org-completing-read
9523 "Link: "
9524 (append
9525 (mapcar (lambda (x) (concat x ":"))
9526 all-prefixes)
9527 (mapcar 'car org-stored-links))
9528 nil nil nil
9529 'tmphist
9530 (caar org-stored-links)))
9531 (if (not (string-match "\\S-" link))
9532 (error "No link selected"))
9533 (mapc (lambda(l)
9534 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9535 org-stored-links)
9536 (if (or (member link all-prefixes)
9537 (and (equal ":" (substring link -1))
9538 (member (substring link 0 -1) all-prefixes)
9539 (setq link (substring link 0 -1))))
9540 (setq link (with-current-buffer origbuf
9541 (org-link-try-special-completion link)))))
9542 (set-window-configuration wcf)
9543 (kill-buffer "*Org Links*"))
9544 (setq entry (assoc link org-stored-links))
9545 (or entry (push link org-insert-link-history))
9546 (setq desc (or desc (nth 1 entry)))))
9548 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9549 (not org-keep-stored-link-after-insertion))
9550 (setq org-stored-links (delq (assoc link org-stored-links)
9551 org-stored-links)))
9553 (if (string-match org-plain-link-re link)
9554 ;; URL-like link, normalize the use of angular brackets.
9555 (setq link (org-remove-angle-brackets link)))
9557 ;; Check if we are linking to the current file with a search
9558 ;; option If yes, simplify the link by using only the search
9559 ;; option.
9560 (when (and buffer-file-name
9561 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9562 (let* ((path (match-string 1 link))
9563 (case-fold-search nil)
9564 (search (match-string 2 link)))
9565 (save-match-data
9566 (if (equal (file-truename buffer-file-name) (file-truename path))
9567 ;; We are linking to this same file, with a search option
9568 (setq link search)))))
9570 ;; Check if we can/should use a relative path. If yes, simplify the link
9571 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9572 (let* ((type (match-string 1 link))
9573 (path (match-string 2 link))
9574 (origpath path)
9575 (case-fold-search nil))
9576 (cond
9577 ((or (eq org-link-file-path-type 'absolute)
9578 (equal complete-file '(16)))
9579 (setq path (abbreviate-file-name (expand-file-name path))))
9580 ((eq org-link-file-path-type 'noabbrev)
9581 (setq path (expand-file-name path)))
9582 ((eq org-link-file-path-type 'relative)
9583 (setq path (file-relative-name path)))
9585 (save-match-data
9586 (if (string-match (concat "^" (regexp-quote
9587 (expand-file-name
9588 (file-name-as-directory
9589 default-directory))))
9590 (expand-file-name path))
9591 ;; We are linking a file with relative path name.
9592 (setq path (substring (expand-file-name path)
9593 (match-end 0)))
9594 (setq path (abbreviate-file-name (expand-file-name path)))))))
9595 (setq link (concat type path))
9596 (if (equal desc origpath)
9597 (setq desc path))))
9599 (if org-make-link-description-function
9600 (setq desc
9601 (or (condition-case nil
9602 (funcall org-make-link-description-function link desc)
9603 (error (progn (message "Can't get link description from `%s'"
9604 (symbol-name org-make-link-description-function))
9605 (sit-for 2) nil)))
9606 (read-string "Description: " default-description)))
9607 (if default-description (setq desc default-description)
9608 (setq desc (or (and auto-desc desc)
9609 (read-string "Description: " desc)))))
9611 (unless (string-match "\\S-" desc) (setq desc nil))
9612 (if remove (apply 'delete-region remove))
9613 (insert (org-make-link-string link desc))))
9615 (defun org-link-try-special-completion (type)
9616 "If there is completion support for link type TYPE, offer it."
9617 (let ((fun (intern (concat "org-" type "-complete-link"))))
9618 (if (functionp fun)
9619 (funcall fun)
9620 (read-string "Link (no completion support): " (concat type ":")))))
9622 (defun org-file-complete-link (&optional arg)
9623 "Create a file link using completion."
9624 (let (file link)
9625 (setq file (org-iread-file-name "File: "))
9626 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9627 (pwd1 (file-name-as-directory (abbreviate-file-name
9628 (expand-file-name ".")))))
9629 (cond
9630 ((equal arg '(16))
9631 (setq link (concat
9632 "file:"
9633 (abbreviate-file-name (expand-file-name file)))))
9634 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9635 (setq link (concat "file:" (match-string 1 file))))
9636 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9637 (expand-file-name file))
9638 (setq link (concat
9639 "file:" (match-string 1 (expand-file-name file)))))
9640 (t (setq link (concat "file:" file)))))
9641 link))
9643 (defun org-iread-file-name (&rest args)
9644 "Read-file-name using `ido-mode' speedup if available.
9645 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9646 See `read-file-name' for a description of parameters."
9647 (org-without-partial-completion
9648 (if (and org-completion-use-ido
9649 (fboundp 'ido-read-file-name)
9650 (boundp 'ido-mode) ido-mode
9651 (listp (second args)))
9652 (let ((ido-enter-matching-directory nil))
9653 (apply 'ido-read-file-name args))
9654 (apply 'read-file-name args))))
9656 (defun org-completing-read (&rest args)
9657 "Completing-read with SPACE being a normal character."
9658 (let ((enable-recursive-minibuffers t)
9659 (minibuffer-local-completion-map
9660 (copy-keymap minibuffer-local-completion-map)))
9661 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9662 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9663 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9664 (apply 'org-icompleting-read args)))
9666 (defun org-completing-read-no-i (&rest args)
9667 (let (org-completion-use-ido org-completion-use-iswitchb)
9668 (apply 'org-completing-read args)))
9670 (defun org-iswitchb-completing-read (prompt choices &rest args)
9671 "Use iswitch as a completing-read replacement to choose from choices.
9672 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9673 from."
9674 (let* ((iswitchb-use-virtual-buffers nil)
9675 (iswitchb-make-buflist-hook
9676 (lambda ()
9677 (setq iswitchb-temp-buflist choices))))
9678 (iswitchb-read-buffer prompt)))
9680 (defun org-icompleting-read (&rest args)
9681 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9682 (org-without-partial-completion
9683 (if (and org-completion-use-ido
9684 (fboundp 'ido-completing-read)
9685 (boundp 'ido-mode) ido-mode
9686 (listp (second args)))
9687 (let ((ido-enter-matching-directory nil))
9688 (apply 'ido-completing-read (concat (car args))
9689 (if (consp (car (nth 1 args)))
9690 (mapcar 'car (nth 1 args))
9691 (nth 1 args))
9692 (cddr args)))
9693 (if (and org-completion-use-iswitchb
9694 (boundp 'iswitchb-mode) iswitchb-mode
9695 (listp (second args)))
9696 (apply 'org-iswitchb-completing-read (concat (car args))
9697 (if (consp (car (nth 1 args)))
9698 (mapcar 'car (nth 1 args))
9699 (nth 1 args))
9700 (cddr args))
9701 (apply 'completing-read args)))))
9703 (defun org-extract-attributes (s)
9704 "Extract the attributes cookie from a string and set as text property."
9705 (let (a attr (start 0) key value)
9706 (save-match-data
9707 (when (string-match "{{\\([^}]+\\)}}$" s)
9708 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9709 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9710 (setq key (match-string 1 a) value (match-string 2 a)
9711 start (match-end 0)
9712 attr (plist-put attr (intern key) value))))
9713 (org-add-props s nil 'org-attr attr))
9716 (defun org-extract-attributes-from-string (tag)
9717 (let (key value attr)
9718 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9719 (setq key (match-string 1 tag) value (match-string 2 tag)
9720 tag (replace-match "" t t tag)
9721 attr (plist-put attr (intern key) value)))
9722 (cons tag attr)))
9724 (defun org-attributes-to-string (plist)
9725 "Format a property list into an HTML attribute list."
9726 (let ((s "") key value)
9727 (while plist
9728 (setq key (pop plist) value (pop plist))
9729 (and value
9730 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9733 ;;; Opening/following a link
9735 (defvar org-link-search-failed nil)
9737 (defvar org-open-link-functions nil
9738 "Hook for functions finding a plain text link.
9739 These functions must take a single argument, the link content.
9740 They will be called for links that look like [[link text][description]]
9741 when LINK TEXT does not have a protocol like \"http:\" and does not look
9742 like a filename (e.g. \"./blue.png\").
9744 These functions will be called *before* Org attempts to resolve the
9745 link by doing text searches in the current buffer - so if you want a
9746 link \"[[target]]\" to still find \"<<target>>\", your function should
9747 handle this as a special case.
9749 When the function does handle the link, it must return a non-nil value.
9750 If it decides that it is not responsible for this link, it must return
9751 nil to indicate that that Org-mode can continue with other options
9752 like exact and fuzzy text search.")
9754 (defun org-next-link ()
9755 "Move forward to the next link.
9756 If the link is in hidden text, expose it."
9757 (interactive)
9758 (when (and org-link-search-failed (eq this-command last-command))
9759 (goto-char (point-min))
9760 (message "Link search wrapped back to beginning of buffer"))
9761 (setq org-link-search-failed nil)
9762 (let* ((pos (point))
9763 (ct (org-context))
9764 (a (assoc :link ct)))
9765 (if a (goto-char (nth 2 a)))
9766 (if (re-search-forward org-any-link-re nil t)
9767 (progn
9768 (goto-char (match-beginning 0))
9769 (if (outline-invisible-p) (org-show-context)))
9770 (goto-char pos)
9771 (setq org-link-search-failed t)
9772 (error "No further link found"))))
9774 (defun org-previous-link ()
9775 "Move backward to the previous link.
9776 If the link is in hidden text, expose it."
9777 (interactive)
9778 (when (and org-link-search-failed (eq this-command last-command))
9779 (goto-char (point-max))
9780 (message "Link search wrapped back to end of buffer"))
9781 (setq org-link-search-failed nil)
9782 (let* ((pos (point))
9783 (ct (org-context))
9784 (a (assoc :link ct)))
9785 (if a (goto-char (nth 1 a)))
9786 (if (re-search-backward org-any-link-re nil t)
9787 (progn
9788 (goto-char (match-beginning 0))
9789 (if (outline-invisible-p) (org-show-context)))
9790 (goto-char pos)
9791 (setq org-link-search-failed t)
9792 (error "No further link found"))))
9794 (defun org-translate-link (s)
9795 "Translate a link string if a translation function has been defined."
9796 (if (and org-link-translation-function
9797 (fboundp org-link-translation-function)
9798 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9799 (progn
9800 (setq s (funcall org-link-translation-function
9801 (match-string 1 s) (match-string 2 s)))
9802 (concat (car s) ":" (cdr s)))
9805 (defun org-translate-link-from-planner (type path)
9806 "Translate a link from Emacs Planner syntax so that Org can follow it.
9807 This is still an experimental function, your mileage may vary."
9808 (cond
9809 ((member type '("http" "https" "news" "ftp"))
9810 ;; standard Internet links are the same.
9811 nil)
9812 ((and (equal type "irc") (string-match "^//" path))
9813 ;; Planner has two / at the beginning of an irc link, we have 1.
9814 ;; We should have zero, actually....
9815 (setq path (substring path 1)))
9816 ((and (equal type "lisp") (string-match "^/" path))
9817 ;; Planner has a slash, we do not.
9818 (setq type "elisp" path (substring path 1)))
9819 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9820 ;; A typical message link. Planner has the id after the final slash,
9821 ;; we separate it with a hash mark
9822 (setq path (concat (match-string 1 path) "#"
9823 (org-remove-angle-brackets (match-string 2 path)))))
9825 (cons type path))
9827 (defun org-find-file-at-mouse (ev)
9828 "Open file link or URL at mouse."
9829 (interactive "e")
9830 (mouse-set-point ev)
9831 (org-open-at-point 'in-emacs))
9833 (defun org-open-at-mouse (ev)
9834 "Open file link or URL at mouse.
9835 See the docstring of `org-open-file' for details."
9836 (interactive "e")
9837 (mouse-set-point ev)
9838 (if (eq major-mode 'org-agenda-mode)
9839 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9840 (org-open-at-point))
9842 (defvar org-window-config-before-follow-link nil
9843 "The window configuration before following a link.
9844 This is saved in case the need arises to restore it.")
9846 (defvar org-open-link-marker (make-marker)
9847 "Marker pointing to the location where `org-open-at-point; was called.")
9849 ;;;###autoload
9850 (defun org-open-at-point-global ()
9851 "Follow a link like Org-mode does.
9852 This command can be called in any mode to follow a link that has
9853 Org-mode syntax."
9854 (interactive)
9855 (org-run-like-in-org-mode 'org-open-at-point))
9857 ;;;###autoload
9858 (defun org-open-link-from-string (s &optional arg reference-buffer)
9859 "Open a link in the string S, as if it was in Org-mode."
9860 (interactive "sLink: \nP")
9861 (let ((reference-buffer (or reference-buffer (current-buffer))))
9862 (with-temp-buffer
9863 (let ((org-inhibit-startup (not reference-buffer)))
9864 (org-mode)
9865 (insert s)
9866 (goto-char (point-min))
9867 (when reference-buffer
9868 (setq org-link-abbrev-alist-local
9869 (with-current-buffer reference-buffer
9870 org-link-abbrev-alist-local)))
9871 (org-open-at-point arg reference-buffer)))))
9873 (defvar org-open-at-point-functions nil
9874 "Hook that is run when following a link at point.
9876 Functions in this hook must return t if they identify and follow
9877 a link at point. If they don't find anything interesting at point,
9878 they must return nil.")
9880 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9881 (defun org-open-at-point (&optional arg reference-buffer)
9882 "Open link at or after point.
9883 If there is no link at point, this function will search forward up to
9884 the end of the current line.
9885 Normally, files will be opened by an appropriate application. If the
9886 optional prefix argument ARG is non-nil, Emacs will visit the file.
9887 With a double prefix argument, try to open outside of Emacs, in the
9888 application the system uses for this file type."
9889 (interactive "P")
9890 ;; if in a code block, then open the block's results
9891 (unless (call-interactively #'org-babel-open-src-block-result)
9892 (org-load-modules-maybe)
9893 (move-marker org-open-link-marker (point))
9894 (setq org-window-config-before-follow-link (current-window-configuration))
9895 (org-remove-occur-highlights nil nil t)
9896 (cond
9897 ((and (org-at-heading-p)
9898 (not (org-at-timestamp-p t))
9899 (not (org-in-regexp
9900 (concat org-plain-link-re "\\|"
9901 org-bracket-link-regexp "\\|"
9902 org-angle-link-re "\\|"
9903 "[ \t]:[^ \t\n]+:[ \t]*$")))
9904 (not (get-text-property (point) 'org-linked-text)))
9905 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9906 (lk0 (car lkall))
9907 (lk (if (stringp lk0) (list lk0) lk0))
9908 (lkend (cdr lkall)))
9909 (mapcar (lambda(l)
9910 (search-forward l nil lkend)
9911 (goto-char (match-beginning 0))
9912 (org-open-at-point))
9913 lk))
9914 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9915 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9916 ((and (org-at-timestamp-p t)
9917 (not (org-in-regexp org-bracket-link-regexp)))
9918 (org-follow-timestamp-link))
9919 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9920 (not (org-in-regexp org-any-link-re)))
9921 (org-footnote-action))
9923 (let (type path link line search (pos (point)))
9924 (catch 'match
9925 (save-excursion
9926 (skip-chars-forward "^]\n\r")
9927 (when (org-in-regexp org-bracket-link-regexp 1)
9928 (setq link (org-extract-attributes
9929 (org-link-unescape (org-match-string-no-properties 1))))
9930 (while (string-match " *\n *" link)
9931 (setq link (replace-match " " t t link)))
9932 (setq link (org-link-expand-abbrev link))
9933 (cond
9934 ((or (file-name-absolute-p link)
9935 (string-match "^\\.\\.?/" link))
9936 (setq type "file" path link))
9937 ((string-match org-link-re-with-space3 link)
9938 (setq type (match-string 1 link) path (match-string 2 link)))
9939 ((string-match "^help:+\\(.+\\)" link)
9940 (setq type "help" path (match-string 1 link)))
9941 (t (setq type "thisfile" path link)))
9942 (throw 'match t)))
9944 (when (get-text-property (point) 'org-linked-text)
9945 (setq type "thisfile"
9946 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9947 (1+ (point)) (point))
9948 path (buffer-substring
9949 (or (previous-single-property-change pos 'org-linked-text)
9950 (point-min))
9951 (or (next-single-property-change pos 'org-linked-text)
9952 (point-max))))
9953 (throw 'match t))
9955 (save-excursion
9956 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9957 (when (or (org-in-regexp org-angle-link-re)
9958 (and plinkpos (goto-char (car plinkpos))
9959 (save-match-data (not (looking-back "\\[\\[")))))
9960 (setq type (match-string 1)
9961 path (org-link-unescape (match-string 2)))
9962 (throw 'match t))))
9963 (save-excursion
9964 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9965 (setq type "tags"
9966 path (match-string 1))
9967 (while (string-match ":" path)
9968 (setq path (replace-match "+" t t path)))
9969 (throw 'match t)))
9970 (when (org-in-regexp "<\\([^><\n]+\\)>")
9971 (setq type "tree-match"
9972 path (match-string 1))
9973 (throw 'match t)))
9974 (unless path
9975 (user-error "No link found"))
9977 ;; switch back to reference buffer
9978 ;; needed when if called in a temporary buffer through
9979 ;; org-open-link-from-string
9980 (with-current-buffer (or reference-buffer (current-buffer))
9982 ;; Remove any trailing spaces in path
9983 (if (string-match " +\\'" path)
9984 (setq path (replace-match "" t t path)))
9985 (if (and org-link-translation-function
9986 (fboundp org-link-translation-function))
9987 ;; Check if we need to translate the link
9988 (let ((tmp (funcall org-link-translation-function type path)))
9989 (setq type (car tmp) path (cdr tmp))))
9991 (cond
9993 ((assoc type org-link-protocols)
9994 (funcall (nth 1 (assoc type org-link-protocols)) path))
9996 ((equal type "help")
9997 (let ((f-or-v (intern path)))
9998 (cond ((fboundp f-or-v)
9999 (describe-function f-or-v))
10000 ((boundp f-or-v)
10001 (describe-variable f-or-v))
10002 (t (error "Not a known function or variable")))))
10004 ((equal type "mailto")
10005 (let ((cmd (car org-link-mailto-program))
10006 (args (cdr org-link-mailto-program)) args1
10007 (address path) (subject "") a)
10008 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10009 (setq address (match-string 1 path)
10010 subject (org-link-escape (match-string 2 path))))
10011 (while args
10012 (cond
10013 ((not (stringp (car args))) (push (pop args) args1))
10014 (t (setq a (pop args))
10015 (if (string-match "%a" a)
10016 (setq a (replace-match address t t a)))
10017 (if (string-match "%s" a)
10018 (setq a (replace-match subject t t a)))
10019 (push a args1))))
10020 (apply cmd (nreverse args1))))
10022 ((member type '("http" "https" "ftp" "news"))
10023 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10024 (org-link-escape
10025 path org-link-escape-chars-browser)
10026 path))))
10028 ((string= type "doi")
10029 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10030 (org-link-escape
10031 path org-link-escape-chars-browser)
10032 path))))
10034 ((member type '("message"))
10035 (browse-url (concat type ":" path)))
10037 ((string= type "tags")
10038 (org-tags-view arg path))
10040 ((string= type "tree-match")
10041 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10043 ((string= type "file")
10044 (if (string-match "::\\([0-9]+\\)\\'" path)
10045 (setq line (string-to-number (match-string 1 path))
10046 path (substring path 0 (match-beginning 0)))
10047 (if (string-match "::\\(.+\\)\\'" path)
10048 (setq search (match-string 1 path)
10049 path (substring path 0 (match-beginning 0)))))
10050 (if (string-match "[*?{]" (file-name-nondirectory path))
10051 (dired path)
10052 (org-open-file path arg line search)))
10054 ((string= type "shell")
10055 (let ((buf (generate-new-buffer "*Org Shell Output"))
10056 (cmd path))
10057 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10058 (string-match org-confirm-shell-link-not-regexp cmd))
10059 (not org-confirm-shell-link-function)
10060 (funcall org-confirm-shell-link-function
10061 (format "Execute \"%s\" in shell? "
10062 (org-add-props cmd nil
10063 'face 'org-warning))))
10064 (progn
10065 (message "Executing %s" cmd)
10066 (shell-command cmd buf)
10067 (if (featurep 'midnight)
10068 (setq clean-buffer-list-kill-buffer-names
10069 (cons buf clean-buffer-list-kill-buffer-names))))
10070 (error "Abort"))))
10072 ((string= type "elisp")
10073 (let ((cmd path))
10074 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10075 (string-match org-confirm-elisp-link-not-regexp cmd))
10076 (not org-confirm-elisp-link-function)
10077 (funcall org-confirm-elisp-link-function
10078 (format "Execute \"%s\" as elisp? "
10079 (org-add-props cmd nil
10080 'face 'org-warning))))
10081 (message "%s => %s" cmd
10082 (if (equal (string-to-char cmd) ?\()
10083 (eval (read cmd))
10084 (call-interactively (read cmd))))
10085 (error "Abort"))))
10087 ((and (string= type "thisfile")
10088 (run-hook-with-args-until-success
10089 'org-open-link-functions path)))
10091 ((string= type "thisfile")
10092 (if arg
10093 (switch-to-buffer-other-window
10094 (org-get-buffer-for-internal-link (current-buffer)))
10095 (org-mark-ring-push))
10096 (let ((cmd `(org-link-search
10097 ,path
10098 ,(cond ((equal arg '(4)) ''occur)
10099 ((equal arg '(16)) ''org-occur))
10100 ,pos)))
10101 (condition-case nil (let ((org-link-search-inhibit-query t))
10102 (eval cmd))
10103 (error (progn (widen) (eval cmd))))))
10105 (t (browse-url-at-point)))))))
10106 (move-marker org-open-link-marker nil)
10107 (run-hook-with-args 'org-follow-link-hook)))
10109 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10110 "Offer links in the current entry and return the selected link.
10111 If there is only one link, return it.
10112 If NTH is an integer, return the NTH link found.
10113 If ZERO is a string, check also this string for a link, and if
10114 there is one, return it."
10115 (with-current-buffer buffer
10116 (save-excursion
10117 (save-restriction
10118 (widen)
10119 (goto-char marker)
10120 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10121 "\\(" org-angle-link-re "\\)\\|"
10122 "\\(" org-plain-link-re "\\)"))
10123 (cnt ?0)
10124 (in-emacs (if (integerp nth) nil nth))
10125 have-zero end links link c)
10126 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10127 (push (match-string 0 zero) links)
10128 (setq cnt (1- cnt) have-zero t))
10129 (save-excursion
10130 (org-back-to-heading t)
10131 (setq end (save-excursion (outline-next-heading) (point)))
10132 (while (re-search-forward re end t)
10133 (push (match-string 0) links))
10134 (setq links (org-uniquify (reverse links))))
10135 (cond
10136 ((null links)
10137 (message "No links"))
10138 ((equal (length links) 1)
10139 (setq link (car links)))
10140 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10141 (setq link (nth (if have-zero nth (1- nth)) links)))
10142 (t ; we have to select a link
10143 (save-excursion
10144 (save-window-excursion
10145 (delete-other-windows)
10146 (with-output-to-temp-buffer "*Select Link*"
10147 (mapc (lambda (l)
10148 (if (not (string-match org-bracket-link-regexp l))
10149 (princ (format "[%c] %s\n" (incf cnt)
10150 (org-remove-angle-brackets l)))
10151 (if (match-end 3)
10152 (princ (format "[%c] %s (%s)\n" (incf cnt)
10153 (match-string 3 l) (match-string 1 l)))
10154 (princ (format "[%c] %s\n" (incf cnt)
10155 (match-string 1 l))))))
10156 links))
10157 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10158 (message "Select link to open, RET to open all:")
10159 (setq c (read-char-exclusive))
10160 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10161 (when (equal c ?q) (error "Abort"))
10162 (if (equal c ?\C-m)
10163 (setq link links)
10164 (setq nth (- c ?0))
10165 (if have-zero (setq nth (1+ nth)))
10166 (unless (and (integerp nth) (>= (length links) nth))
10167 (error "Invalid link selection"))
10168 (setq link (nth (1- nth) links)))))
10169 (cons link end))))))
10171 ;; Add special file links that specify the way of opening
10173 (org-add-link-type "file+sys" 'org-open-file-with-system)
10174 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10175 (defun org-open-file-with-system (path)
10176 "Open file at PATH using the system way of opening it."
10177 (org-open-file path 'system))
10178 (defun org-open-file-with-emacs (path)
10179 "Open file at PATH in Emacs."
10180 (org-open-file path 'emacs))
10181 (defun org-remove-file-link-modifiers ()
10182 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10183 (goto-char (point-min))
10184 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10185 (org-if-unprotected
10186 (replace-match "file:" t t))))
10187 (eval-after-load "org-exp"
10188 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10189 'org-remove-file-link-modifiers))
10191 ;;; File search
10193 (defvar org-create-file-search-functions nil
10194 "List of functions to construct the right search string for a file link.
10195 These functions are called in turn with point at the location to
10196 which the link should point.
10198 A function in the hook should first test if it would like to
10199 handle this file type, for example by checking the `major-mode'
10200 or the file extension. If it decides not to handle this file, it
10201 should just return nil to give other functions a chance. If it
10202 does handle the file, it must return the search string to be used
10203 when following the link. The search string will be part of the
10204 file link, given after a double colon, and `org-open-at-point'
10205 will automatically search for it. If special measures must be
10206 taken to make the search successful, another function should be
10207 added to the companion hook `org-execute-file-search-functions',
10208 which see.
10210 A function in this hook may also use `setq' to set the variable
10211 `description' to provide a suggestion for the descriptive text to
10212 be used for this link when it gets inserted into an Org-mode
10213 buffer with \\[org-insert-link].")
10215 (defvar org-execute-file-search-functions nil
10216 "List of functions to execute a file search triggered by a link.
10218 Functions added to this hook must accept a single argument, the
10219 search string that was part of the file link, the part after the
10220 double colon. The function must first check if it would like to
10221 handle this search, for example by checking the `major-mode' or
10222 the file extension. If it decides not to handle this search, it
10223 should just return nil to give other functions a chance. If it
10224 does handle the search, it must return a non-nil value to keep
10225 other functions from trying.
10227 Each function can access the current prefix argument through the
10228 variable `current-prefix-argument'. Note that a single prefix is
10229 used to force opening a link in Emacs, so it may be good to only
10230 use a numeric or double prefix to guide the search function.
10232 In case this is needed, a function in this hook can also restore
10233 the window configuration before `org-open-at-point' was called using:
10235 (set-window-configuration org-window-config-before-follow-link)")
10237 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10238 (defun org-link-search (s &optional type avoid-pos stealth)
10239 "Search for a link search option.
10240 If S is surrounded by forward slashes, it is interpreted as a
10241 regular expression. In org-mode files, this will create an `org-occur'
10242 sparse tree. In ordinary files, `occur' will be used to list matches.
10243 If the current buffer is in `dired-mode', grep will be used to search
10244 in all files. If AVOID-POS is given, ignore matches near that position.
10246 When optional argument STEALTH is non-nil, do not modify
10247 visibility around point, thus ignoring
10248 `org-show-hierarchy-above', `org-show-following-heading' and
10249 `org-show-siblings' variables."
10250 (let ((case-fold-search t)
10251 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10252 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10253 (append '(("") (" ") ("\t") ("\n"))
10254 org-emphasis-alist)
10255 "\\|") "\\)"))
10256 (pos (point))
10257 (pre nil) (post nil)
10258 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10259 (cond
10260 ;; First check if there are any special search functions
10261 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10262 ;; Now try the builtin stuff
10263 ((and (equal (string-to-char s0) ?#)
10264 (> (length s0) 1)
10265 (save-excursion
10266 (goto-char (point-min))
10267 (and
10268 (re-search-forward
10269 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10270 (setq type 'dedicated
10271 pos (match-beginning 0))))
10272 ;; There is an exact target for this
10273 (goto-char pos)
10274 (org-back-to-heading t)))
10275 ((save-excursion
10276 (goto-char (point-min))
10277 (and
10278 (re-search-forward
10279 (concat "<<" (regexp-quote s0) ">>") nil t)
10280 (setq type 'dedicated
10281 pos (match-beginning 0))))
10282 ;; There is an exact target for this
10283 (goto-char pos))
10284 ((save-excursion
10285 (goto-char (point-min))
10286 (and
10287 (re-search-forward
10288 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10289 (setq type 'dedicated pos (match-beginning 0))))
10290 ;; Found an invisible target.
10291 (goto-char pos))
10292 ((save-excursion
10293 (goto-char (point-min))
10294 (and
10295 (re-search-forward
10296 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10297 (setq type 'dedicated pos (match-beginning 0))))
10298 ;; Found an element with a matching #+name affiliated keyword.
10299 (goto-char pos))
10300 ((and (string-match "^(\\(.*\\))$" s0)
10301 (save-excursion
10302 (goto-char (point-min))
10303 (and
10304 (re-search-forward
10305 (concat "[^[]" (regexp-quote
10306 (format org-coderef-label-format
10307 (match-string 1 s0))))
10308 nil t)
10309 (setq type 'dedicated
10310 pos (1+ (match-beginning 0))))))
10311 ;; There is a coderef target for this
10312 (goto-char pos))
10313 ((string-match "^/\\(.*\\)/$" s)
10314 ;; A regular expression
10315 (cond
10316 ((derived-mode-p 'org-mode)
10317 (org-occur (match-string 1 s)))
10318 ;;((eq major-mode 'dired-mode)
10319 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10320 (t (org-do-occur (match-string 1 s)))))
10321 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10322 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10323 (goto-char (point-min))
10324 (cond
10325 ((let (case-fold-search)
10326 (re-search-forward (format org-complex-heading-regexp-format
10327 (regexp-quote s))
10328 nil t))
10329 ;; OK, found a match
10330 (setq type 'dedicated)
10331 (goto-char (match-beginning 0)))
10332 ((and (not org-link-search-inhibit-query)
10333 (eq org-link-search-must-match-exact-headline 'query-to-create)
10334 (y-or-n-p "No match - create this as a new heading? "))
10335 (goto-char (point-max))
10336 (or (bolp) (newline))
10337 (insert "* " s "\n")
10338 (beginning-of-line 0))
10340 (goto-char pos)
10341 (error "No match"))))
10343 ;; A normal search string
10344 (when (equal (string-to-char s) ?*)
10345 ;; Anchor on headlines, post may include tags.
10346 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10347 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10348 s (substring s 1)))
10349 (remove-text-properties
10350 0 (length s)
10351 '(face nil mouse-face nil keymap nil fontified nil) s)
10352 ;; Make a series of regular expressions to find a match
10353 (setq words (org-split-string s "[ \n\r\t]+")
10355 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10356 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10357 "\\)" markers)
10358 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10359 re2a (concat "[ \t\r\n]" re2a_)
10360 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10361 re4 (concat "[^a-zA-Z_]" re4_)
10363 re1 (concat pre re2 post)
10364 re3 (concat pre (if pre re4_ re4) post)
10365 re5 (concat pre ".*" re4)
10366 re2 (concat pre re2)
10367 re2a (concat pre (if pre re2a_ re2a))
10368 re4 (concat pre (if pre re4_ re4))
10369 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10370 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10371 re5 "\\)"
10373 (cond
10374 ((eq type 'org-occur) (org-occur reall))
10375 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10376 (t (goto-char (point-min))
10377 (setq type 'fuzzy)
10378 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10379 (org-search-not-self 1 re1 nil t)
10380 (org-search-not-self 1 re2 nil t)
10381 (org-search-not-self 1 re2a nil t)
10382 (org-search-not-self 1 re3 nil t)
10383 (org-search-not-self 1 re4 nil t)
10384 (org-search-not-self 1 re5 nil t)
10386 (goto-char (match-beginning 1))
10387 (goto-char pos)
10388 (error "No match"))))))
10389 (and (derived-mode-p 'org-mode)
10390 (not stealth)
10391 (org-show-context 'link-search))
10392 type))
10394 (defun org-search-not-self (group &rest args)
10395 "Execute `re-search-forward', but only accept matches that do not
10396 enclose the position of `org-open-link-marker'."
10397 (let ((m org-open-link-marker))
10398 (catch 'exit
10399 (while (apply 're-search-forward args)
10400 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10401 (goto-char (match-end group))
10402 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10403 (> (match-beginning 0) (marker-position m))
10404 (< (match-end 0) (marker-position m)))
10405 (save-match-data
10406 (or (not (org-in-regexp
10407 org-bracket-link-analytic-regexp 1))
10408 (not (match-end 4)) ; no description
10409 (and (<= (match-beginning 4) (point))
10410 (>= (match-end 4) (point))))))
10411 (throw 'exit (point))))))))
10413 (defun org-get-buffer-for-internal-link (buffer)
10414 "Return a buffer to be used for displaying the link target of internal links."
10415 (cond
10416 ((not org-display-internal-link-with-indirect-buffer)
10417 buffer)
10418 ((string-match "(Clone)$" (buffer-name buffer))
10419 (message "Buffer is already a clone, not making another one")
10420 ;; we also do not modify visibility in this case
10421 buffer)
10422 (t ; make a new indirect buffer for displaying the link
10423 (let* ((bn (buffer-name buffer))
10424 (ibn (concat bn "(Clone)"))
10425 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10426 (with-current-buffer ib (org-overview))
10427 ib))))
10429 (defun org-do-occur (regexp &optional cleanup)
10430 "Call the Emacs command `occur'.
10431 If CLEANUP is non-nil, remove the printout of the regular expression
10432 in the *Occur* buffer. This is useful if the regex is long and not useful
10433 to read."
10434 (occur regexp)
10435 (when cleanup
10436 (let ((cwin (selected-window)) win beg end)
10437 (when (setq win (get-buffer-window "*Occur*"))
10438 (select-window win))
10439 (goto-char (point-min))
10440 (when (re-search-forward "match[a-z]+" nil t)
10441 (setq beg (match-end 0))
10442 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10443 (setq end (1- (match-beginning 0)))))
10444 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10445 (goto-char (point-min))
10446 (select-window cwin))))
10448 ;;; The mark ring for links jumps
10450 (defvar org-mark-ring nil
10451 "Mark ring for positions before jumps in Org-mode.")
10452 (defvar org-mark-ring-last-goto nil
10453 "Last position in the mark ring used to go back.")
10454 ;; Fill and close the ring
10455 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10456 (loop for i from 1 to org-mark-ring-length do
10457 (push (make-marker) org-mark-ring))
10458 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10459 org-mark-ring)
10461 (defun org-mark-ring-push (&optional pos buffer)
10462 "Put the current position or POS into the mark ring and rotate it."
10463 (interactive)
10464 (setq pos (or pos (point)))
10465 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10466 (move-marker (car org-mark-ring)
10467 (or pos (point))
10468 (or buffer (current-buffer)))
10469 (message "%s"
10470 (substitute-command-keys
10471 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10473 (defun org-mark-ring-goto (&optional n)
10474 "Jump to the previous position in the mark ring.
10475 With prefix arg N, jump back that many stored positions. When
10476 called several times in succession, walk through the entire ring.
10477 Org-mode commands jumping to a different position in the current file,
10478 or to another Org-mode file, automatically push the old position
10479 onto the ring."
10480 (interactive "p")
10481 (let (p m)
10482 (if (eq last-command this-command)
10483 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10484 (setq p org-mark-ring))
10485 (setq org-mark-ring-last-goto p)
10486 (setq m (car p))
10487 (org-pop-to-buffer-same-window (marker-buffer m))
10488 (goto-char m)
10489 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10491 (defun org-remove-angle-brackets (s)
10492 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10493 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10495 (defun org-add-angle-brackets (s)
10496 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10497 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10499 (defun org-remove-double-quotes (s)
10500 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10501 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10504 ;;; Following specific links
10506 (defun org-follow-timestamp-link ()
10507 "Open an agenda view for the time-stamp date/range at point."
10508 (cond
10509 ((org-at-date-range-p t)
10510 (let ((org-agenda-start-on-weekday)
10511 (t1 (match-string 1))
10512 (t2 (match-string 2)) tt1 tt2)
10513 (setq tt1 (time-to-days (org-time-string-to-time t1))
10514 tt2 (time-to-days (org-time-string-to-time t2)))
10515 (let ((org-agenda-buffer-tmp-name
10516 (format "*Org Agenda(a:%s)"
10517 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10518 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10519 ((org-at-timestamp-p t)
10520 (let ((org-agenda-buffer-tmp-name
10521 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10522 (org-agenda-list nil (time-to-days (org-time-string-to-time
10523 (substring (match-string 1) 0 10)))
10524 1)))
10525 (t (error "This should not happen"))))
10528 ;;; Following file links
10529 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10530 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10531 (declare-function mailcap-mime-info
10532 "mailcap" (string &optional request no-decode))
10533 (defvar org-wait nil)
10534 (defun org-open-file (path &optional in-emacs line search)
10535 "Open the file at PATH.
10536 First, this expands any special file name abbreviations. Then the
10537 configuration variable `org-file-apps' is checked if it contains an
10538 entry for this file type, and if yes, the corresponding command is launched.
10540 If no application is found, Emacs simply visits the file.
10542 With optional prefix argument IN-EMACS, Emacs will visit the file.
10543 With a double \\[universal-argument] \\[universal-argument] \
10544 prefix arg, Org tries to avoid opening in Emacs
10545 and to use an external application to visit the file.
10547 Optional LINE specifies a line to go to, optional SEARCH a string
10548 to search for. If LINE or SEARCH is given, the file will be
10549 opened in Emacs, unless an entry from org-file-apps that makes
10550 use of groups in a regexp matches.
10552 If you want to change the way frames are used when following a
10553 link, please customize `org-link-frame-setup'.
10555 If the file does not exist, an error is thrown."
10556 (let* ((file (if (equal path "")
10557 buffer-file-name
10558 (substitute-in-file-name (expand-file-name path))))
10559 (file-apps (append org-file-apps (org-default-apps)))
10560 (apps (org-remove-if
10561 'org-file-apps-entry-match-against-dlink-p file-apps))
10562 (apps-dlink (org-remove-if-not
10563 'org-file-apps-entry-match-against-dlink-p file-apps))
10564 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10565 (dirp (if remp nil (file-directory-p file)))
10566 (file (if (and dirp org-open-directory-means-index-dot-org)
10567 (concat (file-name-as-directory file) "index.org")
10568 file))
10569 (a-m-a-p (assq 'auto-mode apps))
10570 (dfile (downcase file))
10571 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10572 (link (cond ((and (eq line nil)
10573 (eq search nil))
10574 file)
10575 (line
10576 (concat file "::" (number-to-string line)))
10577 (search
10578 (concat file "::" search))))
10579 (dlink (downcase link))
10580 (old-buffer (current-buffer))
10581 (old-pos (point))
10582 (old-mode major-mode)
10583 ext cmd link-match-data)
10584 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10585 (setq ext (match-string 1 dfile))
10586 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10587 (setq ext (match-string 1 dfile))))
10588 (cond
10589 ((member in-emacs '((16) system))
10590 (setq cmd (cdr (assoc 'system apps))))
10591 (in-emacs (setq cmd 'emacs))
10593 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10594 (and dirp (cdr (assoc 'directory apps)))
10595 ; first, try matching against apps-dlink
10596 ; if we get a match here, store the match data for later
10597 (let ((match (assoc-default dlink apps-dlink
10598 'string-match)))
10599 (if match
10600 (progn (setq link-match-data (match-data))
10601 match)
10602 (progn (setq in-emacs (or in-emacs line search))
10603 nil))) ; if we have no match in apps-dlink,
10604 ; always open the file in emacs if line or search
10605 ; is given (for backwards compatibility)
10606 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10607 'string-match)
10608 (cdr (assoc ext apps))
10609 (cdr (assoc t apps))))))
10610 (when (eq cmd 'system)
10611 (setq cmd (cdr (assoc 'system apps))))
10612 (when (eq cmd 'default)
10613 (setq cmd (cdr (assoc t apps))))
10614 (when (eq cmd 'mailcap)
10615 (require 'mailcap)
10616 (mailcap-parse-mailcaps)
10617 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10618 (command (mailcap-mime-info mime-type)))
10619 (if (stringp command)
10620 (setq cmd command)
10621 (setq cmd 'emacs))))
10622 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10623 (not (file-exists-p file))
10624 (not org-open-non-existing-files))
10625 (error "No such file: %s" file))
10626 (cond
10627 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10628 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10629 (while (string-match "['\"]%s['\"]" cmd)
10630 (setq cmd (replace-match "%s" t t cmd)))
10631 (while (string-match "%s" cmd)
10632 (setq cmd (replace-match
10633 (save-match-data
10634 (shell-quote-argument
10635 (convert-standard-filename file)))
10636 t t cmd)))
10638 ;; Replace "%1", "%2" etc. in command with group matches from regex
10639 (save-match-data
10640 (let ((match-index 1)
10641 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10642 (set-match-data link-match-data)
10643 (while (<= match-index number-of-groups)
10644 (let ((regex (concat "%" (number-to-string match-index)))
10645 (replace-with (match-string match-index dlink)))
10646 (while (string-match regex cmd)
10647 (setq cmd (replace-match replace-with t t cmd))))
10648 (setq match-index (+ match-index 1)))))
10650 (save-window-excursion
10651 (message "Running %s...done" cmd)
10652 (start-process-shell-command cmd nil cmd)
10653 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10654 ((or (stringp cmd)
10655 (eq cmd 'emacs))
10656 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10657 (widen)
10658 (if line (org-goto-line line)
10659 (if search (org-link-search search))))
10660 ((consp cmd)
10661 (let ((file (convert-standard-filename file)))
10662 (save-match-data
10663 (set-match-data link-match-data)
10664 (eval cmd))))
10665 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10666 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10667 (or (not (equal old-buffer (current-buffer)))
10668 (not (equal old-pos (point))))
10669 (org-mark-ring-push old-pos old-buffer))))
10671 (defun org-file-apps-entry-match-against-dlink-p (entry)
10672 "This function returns non-nil if `entry' uses a regular
10673 expression which should be matched against the whole link by
10674 org-open-file.
10676 It assumes that is the case when the entry uses a regular
10677 expression which has at least one grouping construct and the
10678 action is either a lisp form or a command string containing
10679 '%1', i.e. using at least one subexpression match as a
10680 parameter."
10681 (let ((selector (car entry))
10682 (action (cdr entry)))
10683 (if (stringp selector)
10684 (and (> (regexp-opt-depth selector) 0)
10685 (or (and (stringp action)
10686 (string-match "%[0-9]" action))
10687 (consp action)))
10688 nil)))
10690 (defun org-default-apps ()
10691 "Return the default applications for this operating system."
10692 (cond
10693 ((eq system-type 'darwin)
10694 org-file-apps-defaults-macosx)
10695 ((eq system-type 'windows-nt)
10696 org-file-apps-defaults-windowsnt)
10697 (t org-file-apps-defaults-gnu)))
10699 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10700 "Convert extensions to regular expressions in the cars of LIST.
10701 Also, weed out any non-string entries, because the return value is used
10702 only for regexp matching.
10703 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10704 point to the symbol `emacs', indicating that the file should
10705 be opened in Emacs."
10706 (append
10707 (delq nil
10708 (mapcar (lambda (x)
10709 (if (not (stringp (car x)))
10711 (if (string-match "\\W" (car x))
10713 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10714 list))
10715 (if add-auto-mode
10716 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10718 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10719 (defun org-file-remote-p (file)
10720 "Test whether FILE specifies a location on a remote system.
10721 Return non-nil if the location is indeed remote.
10723 For example, the filename \"/user@host:/foo\" specifies a location
10724 on the system \"/user@host:\"."
10725 (cond ((fboundp 'file-remote-p)
10726 (file-remote-p file))
10727 ((fboundp 'tramp-handle-file-remote-p)
10728 (tramp-handle-file-remote-p file))
10729 ((and (boundp 'ange-ftp-name-format)
10730 (string-match (car ange-ftp-name-format) file))
10731 t)))
10734 ;;;; Refiling
10736 (defun org-get-org-file ()
10737 "Read a filename, with default directory `org-directory'."
10738 (let ((default (or org-default-notes-file remember-data-file)))
10739 (read-file-name (format "File name [%s]: " default)
10740 (file-name-as-directory org-directory)
10741 default)))
10743 (defun org-notes-order-reversed-p ()
10744 "Check if the current file should receive notes in reversed order."
10745 (cond
10746 ((not org-reverse-note-order) nil)
10747 ((eq t org-reverse-note-order) t)
10748 ((not (listp org-reverse-note-order)) nil)
10749 (t (catch 'exit
10750 (let ((all org-reverse-note-order)
10751 entry)
10752 (while (setq entry (pop all))
10753 (if (string-match (car entry) buffer-file-name)
10754 (throw 'exit (cdr entry))))
10755 nil)))))
10757 (defvar org-refile-target-table nil
10758 "The list of refile targets, created by `org-refile'.")
10760 (defvar org-agenda-new-buffers nil
10761 "Buffers created to visit agenda files.")
10763 (defvar org-refile-cache nil
10764 "Cache for refile targets.")
10766 (defvar org-refile-markers nil
10767 "All the markers used for caching refile locations.")
10769 (defun org-refile-marker (pos)
10770 "Get a new refile marker, but only if caching is in use."
10771 (if (not org-refile-use-cache)
10773 (let ((m (make-marker)))
10774 (move-marker m pos)
10775 (push m org-refile-markers)
10776 m)))
10778 (defun org-refile-cache-clear ()
10779 "Clear the refile cache and disable all the markers."
10780 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10781 (setq org-refile-markers nil)
10782 (setq org-refile-cache nil)
10783 (message "Refile cache has been cleared"))
10785 (defun org-refile-cache-check-set (set)
10786 "Check if all the markers in the cache still have live buffers."
10787 (let (marker)
10788 (catch 'exit
10789 (while (and set (setq marker (nth 3 (pop set))))
10790 ;; if org-refile-use-outline-path is 'file, marker may be nil
10791 (when (and marker (null (marker-buffer marker)))
10792 (message "not found") (sit-for 3)
10793 (throw 'exit nil)))
10794 t)))
10796 (defun org-refile-cache-put (set &rest identifiers)
10797 "Push the refile targets SET into the cache, under IDENTIFIERS."
10798 (let* ((key (sha1 (prin1-to-string identifiers)))
10799 (entry (assoc key org-refile-cache)))
10800 (if entry
10801 (setcdr entry set)
10802 (push (cons key set) org-refile-cache))))
10804 (defun org-refile-cache-get (&rest identifiers)
10805 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10806 (cond
10807 ((not org-refile-cache) nil)
10808 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10810 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10811 org-refile-cache))))
10812 (and set (org-refile-cache-check-set set) set)))))
10814 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10815 "Produce a table with refile targets."
10816 (let ((case-fold-search nil)
10817 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10818 (entries (or org-refile-targets '((nil . (:level . 1)))))
10819 targets tgs txt re files f desc descre fast-path-p level pos0)
10820 (message "Getting targets...")
10821 (with-current-buffer (or default-buffer (current-buffer))
10822 (while (setq entry (pop entries))
10823 (setq files (car entry) desc (cdr entry))
10824 (setq fast-path-p nil)
10825 (cond
10826 ((null files) (setq files (list (current-buffer))))
10827 ((eq files 'org-agenda-files)
10828 (setq files (org-agenda-files 'unrestricted)))
10829 ((and (symbolp files) (fboundp files))
10830 (setq files (funcall files)))
10831 ((and (symbolp files) (boundp files))
10832 (setq files (symbol-value files))))
10833 (if (stringp files) (setq files (list files)))
10834 (cond
10835 ((eq (car desc) :tag)
10836 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10837 ((eq (car desc) :todo)
10838 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10839 ((eq (car desc) :regexp)
10840 (setq descre (cdr desc)))
10841 ((eq (car desc) :level)
10842 (setq descre (concat "^\\*\\{" (number-to-string
10843 (if org-odd-levels-only
10844 (1- (* 2 (cdr desc)))
10845 (cdr desc)))
10846 "\\}[ \t]")))
10847 ((eq (car desc) :maxlevel)
10848 (setq fast-path-p t)
10849 (setq descre (concat "^\\*\\{1," (number-to-string
10850 (if org-odd-levels-only
10851 (1- (* 2 (cdr desc)))
10852 (cdr desc)))
10853 "\\}[ \t]")))
10854 (t (error "Bad refiling target description %s" desc)))
10855 (while (setq f (pop files))
10856 (with-current-buffer
10857 (if (bufferp f) f (org-get-agenda-file-buffer f))
10859 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10860 (progn
10861 (if (bufferp f) (setq f (buffer-file-name
10862 (buffer-base-buffer f))))
10863 (setq f (and f (expand-file-name f)))
10864 (if (eq org-refile-use-outline-path 'file)
10865 (push (list (file-name-nondirectory f) f nil nil) tgs))
10866 (save-excursion
10867 (save-restriction
10868 (widen)
10869 (goto-char (point-min))
10870 (while (re-search-forward descre nil t)
10871 (goto-char (setq pos0 (point-at-bol)))
10872 (catch 'next
10873 (when org-refile-target-verify-function
10874 (save-match-data
10875 (or (funcall org-refile-target-verify-function)
10876 (throw 'next t))))
10877 (when (and (looking-at org-complex-heading-regexp)
10878 (not (member (match-string 4) excluded-entries))
10879 (match-string 4))
10880 (setq level (org-reduced-level
10881 (- (match-end 1) (match-beginning 1)))
10882 txt (org-link-display-format (match-string 4))
10883 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10884 re (format org-complex-heading-regexp-format
10885 (regexp-quote (match-string 4))))
10886 (when org-refile-use-outline-path
10887 (setq txt (mapconcat
10888 'org-protect-slash
10889 (append
10890 (if (eq org-refile-use-outline-path
10891 'file)
10892 (list (file-name-nondirectory
10893 (buffer-file-name
10894 (buffer-base-buffer))))
10895 (if (eq org-refile-use-outline-path
10896 'full-file-path)
10897 (list (buffer-file-name
10898 (buffer-base-buffer)))))
10899 (org-get-outline-path fast-path-p
10900 level txt)
10901 (list txt))
10902 "/")))
10903 (push (list txt f re (org-refile-marker (point)))
10904 tgs)))
10905 (when (= (point) pos0)
10906 ;; verification function has not moved point
10907 (goto-char (point-at-eol))))))))
10908 (when org-refile-use-cache
10909 (org-refile-cache-put tgs (buffer-file-name) descre))
10910 (setq targets (append tgs targets))
10911 ))))
10912 (message "Getting targets...done")
10913 (nreverse targets)))
10915 (defun org-protect-slash (s)
10916 (while (string-match "/" s)
10917 (setq s (replace-match "\\" t t s)))
10920 (defvar org-olpa (make-vector 20 nil))
10922 (defun org-get-outline-path (&optional fastp level heading)
10923 "Return the outline path to the current entry, as a list.
10925 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10926 routine which makes outline path derivations for an entire file,
10927 avoiding backtracing. Refile target collection makes use of that."
10928 (if fastp
10929 (progn
10930 (if (> level 19)
10931 (error "Outline path failure, more than 19 levels"))
10932 (loop for i from level upto 19 do
10933 (aset org-olpa i nil))
10934 (prog1
10935 (delq nil (append org-olpa nil))
10936 (aset org-olpa level heading)))
10937 (let (rtn case-fold-search)
10938 (save-excursion
10939 (save-restriction
10940 (widen)
10941 (while (org-up-heading-safe)
10942 (when (looking-at org-complex-heading-regexp)
10943 (push (org-match-string-no-properties 4) rtn)))
10944 rtn)))))
10946 (defun org-format-outline-path (path &optional width prefix separator)
10947 "Format the outline path PATH for display.
10948 WIDTH is the maximum number of characters that is available.
10949 PREFIX is a prefix to be included in the returned string,
10950 such as the file name.
10951 SEPARATOR is inserted between the different parts of the path,
10952 the default is \"/\"."
10953 (setq width (or width 79))
10954 (if prefix (setq width (- width (length prefix))))
10955 (if (not path)
10956 (or prefix "")
10957 (let* ((nsteps (length path))
10958 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10959 (maxwidth (if (<= total-width width)
10960 10000 ;; everything fits
10961 ;; we need to shorten the level headings
10962 (/ (- width nsteps) nsteps)))
10963 (org-odd-levels-only nil)
10964 (n 0)
10965 (total (1+ (length prefix))))
10966 (setq maxwidth (max maxwidth 10))
10967 (concat prefix
10968 (if prefix (or separator "/"))
10969 (mapconcat
10970 (lambda (h)
10971 (setq n (1+ n))
10972 (if (and (= n nsteps) (< maxwidth 10000))
10973 (setq maxwidth (- total-width total)))
10974 (if (< (length h) maxwidth)
10975 (progn (setq total (+ total (length h) 1)) h)
10976 (setq h (substring h 0 (- maxwidth 2))
10977 total (+ total maxwidth 1))
10978 (if (string-match "[ \t]+\\'" h)
10979 (setq h (substring h 0 (match-beginning 0))))
10980 (setq h (concat h "..")))
10981 (org-add-props h nil 'face
10982 (nth (% (1- n) org-n-level-faces)
10983 org-level-faces))
10985 path (or separator "/"))))))
10987 (defun org-display-outline-path (&optional file current separator just-return-string)
10988 "Display the current outline path in the echo area.
10990 If FILE is non-nil, prepend the output with the file name.
10991 If CURRENT is non-nil, append the current heading to the output.
10992 SEPARATOR is passed through to `org-format-outline-path'. It separates
10993 the different parts of the path and defaults to \"/\".
10994 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10995 (interactive "P")
10996 (let* (case-fold-search
10997 message-log-max ; Don't populate the *Messages* buffer
10998 (bfn (buffer-file-name (buffer-base-buffer)))
10999 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11000 res)
11001 (if current (setq path (append path
11002 (save-excursion
11003 (org-back-to-heading t)
11004 (if (looking-at org-complex-heading-regexp)
11005 (list (match-string 4)))))))
11006 (setq res
11007 (org-format-outline-path
11008 path
11009 (1- (frame-width))
11010 (and file bfn (concat (file-name-nondirectory bfn) separator))
11011 separator))
11012 (if just-return-string
11013 (org-no-properties res)
11014 (message "%s" res))))
11016 (defvar org-refile-history nil
11017 "History for refiling operations.")
11019 (defvar org-after-refile-insert-hook nil
11020 "Hook run after `org-refile' has inserted its stuff at the new location.
11021 Note that this is still *before* the stuff will be removed from
11022 the *old* location.")
11024 (defvar org-capture-last-stored-marker)
11025 (defvar org-refile-keep nil
11026 "Non-nil means `org-refile' will copy instead of refile.")
11028 (defun org-copy ()
11029 "Like `org-refile', but copy."
11030 (interactive)
11031 (let ((org-refile-keep t))
11032 (funcall 'org-refile nil nil nil "Copy")))
11034 (defun org-refile (&optional goto default-buffer rfloc msg)
11035 "Move the entry or entries at point to another heading.
11036 The list of target headings is compiled using the information in
11037 `org-refile-targets', which see.
11039 At the target location, the entry is filed as a subitem of the target
11040 heading. Depending on `org-reverse-note-order', the new subitem will
11041 either be the first or the last subitem.
11043 If there is an active region, all entries in that region will be moved.
11044 However, the region must fulfill the requirement that the first heading
11045 is the first one sets the top-level of the moved text - at most siblings
11046 below it are allowed.
11048 With prefix arg GOTO, the command will only visit the target location
11049 and not actually move anything.
11051 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11052 go to the location where the last refiling operation has put the subtree.
11053 With a prefix argument of `2', refile to the running clock.
11055 RFLOC can be a refile location obtained in a different way.
11057 MSG is a string to replace \"Refile\" in the default prompt with
11058 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11060 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11062 If you are using target caching (see `org-refile-use-cache'),
11063 you have to clear the target cache in order to find new targets.
11064 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11065 prefix argument (`C-u C-u C-u C-c C-w')."
11067 (interactive "P")
11068 (if (member goto '(0 (64)))
11069 (org-refile-cache-clear)
11070 (let* ((actionmsg (or msg "Refile"))
11071 (cbuf (current-buffer))
11072 (regionp (org-region-active-p))
11073 (region-start (and regionp (region-beginning)))
11074 (region-end (and regionp (region-end)))
11075 (region-length (and regionp (- region-end region-start)))
11076 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11077 pos it nbuf file re level reversed)
11078 (setq last-command nil)
11079 (when regionp
11080 (goto-char region-start)
11081 (or (bolp) (goto-char (point-at-bol)))
11082 (setq region-start (point))
11083 (unless (or (org-kill-is-subtree-p
11084 (buffer-substring region-start region-end))
11085 (prog1 org-refile-active-region-within-subtree
11086 (org-toggle-heading)))
11087 (error "The region is not a (sequence of) subtree(s)")))
11088 (if (equal goto '(16))
11089 (org-refile-goto-last-stored)
11090 (when (or
11091 (and (equal goto 2)
11092 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11093 (prog1
11094 (setq it (list (or org-clock-heading "running clock")
11095 (buffer-file-name
11096 (marker-buffer org-clock-hd-marker))
11098 (marker-position org-clock-hd-marker)))
11099 (setq goto nil)))
11100 (setq it (or rfloc
11101 (let (heading-text)
11102 (save-excursion
11103 (unless goto
11104 (org-back-to-heading t)
11105 (setq heading-text
11106 (nth 4 (org-heading-components))))
11108 (org-refile-get-location
11109 (cond (goto "Goto")
11110 (regionp (concat actionmsg " region to"))
11111 (t (concat actionmsg " subtree \""
11112 heading-text "\" to")))
11113 default-buffer
11114 (and (not (equal '(4) goto))
11115 org-refile-allow-creating-parent-nodes)
11116 goto))))))
11117 (setq file (nth 1 it)
11118 re (nth 2 it)
11119 pos (nth 3 it))
11120 (if (and (not goto)
11122 (equal (buffer-file-name) file)
11123 (if regionp
11124 (and (>= pos region-start)
11125 (<= pos region-end))
11126 (and (>= pos (point))
11127 (< pos (save-excursion
11128 (org-end-of-subtree t t))))))
11129 (error "Cannot refile to position inside the tree or region"))
11131 (setq nbuf (or (find-buffer-visiting file)
11132 (find-file-noselect file)))
11133 (if goto
11134 (progn
11135 (org-pop-to-buffer-same-window nbuf)
11136 (goto-char pos)
11137 (org-show-context 'org-goto))
11138 (if regionp
11139 (progn
11140 (org-kill-new (buffer-substring region-start region-end))
11141 (org-save-markers-in-region region-start region-end))
11142 (org-copy-subtree 1 nil t))
11143 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11144 (find-file-noselect file)))
11145 (setq reversed (org-notes-order-reversed-p))
11146 (save-excursion
11147 (save-restriction
11148 (widen)
11149 (if pos
11150 (progn
11151 (goto-char pos)
11152 (looking-at org-outline-regexp)
11153 (setq level (org-get-valid-level (funcall outline-level) 1))
11154 (goto-char
11155 (if reversed
11156 (or (outline-next-heading) (point-max))
11157 (or (save-excursion (org-get-next-sibling))
11158 (org-end-of-subtree t t)
11159 (point-max)))))
11160 (setq level 1)
11161 (if (not reversed)
11162 (goto-char (point-max))
11163 (goto-char (point-min))
11164 (or (outline-next-heading) (goto-char (point-max)))))
11165 (if (not (bolp)) (newline))
11166 (org-paste-subtree level)
11167 (when org-log-refile
11168 (org-add-log-setup 'refile nil nil 'findpos
11169 org-log-refile)
11170 (unless (eq org-log-refile 'note)
11171 (save-excursion (org-add-log-note))))
11172 (and org-auto-align-tags
11173 (let ((org-loop-over-headlines-in-active-region nil))
11174 (org-set-tags nil t)))
11175 (with-demoted-errors
11176 (bookmark-set "org-refile-last-stored"))
11177 ;; If we are refiling for capture, make sure that the
11178 ;; last-capture pointers point here
11179 (when (org-bound-and-true-p org-refile-for-capture)
11180 (with-demoted-errors
11181 (bookmark-set "org-capture-last-stored-marker"))
11182 (move-marker org-capture-last-stored-marker (point)))
11183 (if (fboundp 'deactivate-mark) (deactivate-mark))
11184 (run-hooks 'org-after-refile-insert-hook))))
11185 (unless org-refile-keep
11186 (if regionp
11187 (delete-region (point) (+ (point) region-length))
11188 (org-cut-subtree)))
11189 (when (featurep 'org-inlinetask)
11190 (org-inlinetask-remove-END-maybe))
11191 (setq org-markers-to-move nil)
11192 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11194 (defun org-refile-goto-last-stored ()
11195 "Go to the location where the last refile was stored."
11196 (interactive)
11197 (bookmark-jump "org-refile-last-stored")
11198 (message "This is the location of the last refile"))
11200 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11201 no-exclude)
11202 "Prompt the user for a refile location, using PROMPT.
11203 PROMPT should not be suffixed with a colon and a space, because
11204 this function appends the default value from
11205 `org-refile-history' automatically, if that is not empty.
11206 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11207 this is used for the GOTO interface."
11208 (let ((org-refile-targets org-refile-targets)
11209 (org-refile-use-outline-path org-refile-use-outline-path)
11210 excluded-entries)
11211 (when (and (derived-mode-p 'org-mode)
11212 (not org-refile-use-cache)
11213 (not no-exclude))
11214 (org-map-tree
11215 (lambda()
11216 (setq excluded-entries
11217 (append excluded-entries (list (org-get-heading t t)))))))
11218 (setq org-refile-target-table
11219 (org-refile-get-targets default-buffer excluded-entries)))
11220 (unless org-refile-target-table
11221 (error "No refile targets"))
11222 (let* ((cbuf (current-buffer))
11223 (partial-completion-mode nil)
11224 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11225 (cfunc (if (and org-refile-use-outline-path
11226 org-outline-path-complete-in-steps)
11227 'org-olpath-completing-read
11228 'org-icompleting-read))
11229 (extra (if org-refile-use-outline-path "/" ""))
11230 (cbnex (concat (buffer-name) extra))
11231 (filename (and cfn (expand-file-name cfn)))
11232 (tbl (mapcar
11233 (lambda (x)
11234 (if (and (not (member org-refile-use-outline-path
11235 '(file full-file-path)))
11236 (not (equal filename (nth 1 x))))
11237 (cons (concat (car x) extra " ("
11238 (file-name-nondirectory (nth 1 x)) ")")
11239 (cdr x))
11240 (cons (concat (car x) extra) (cdr x))))
11241 org-refile-target-table))
11242 (completion-ignore-case t)
11243 cdef
11244 (prompt (concat prompt
11245 (or (and (car org-refile-history)
11246 (concat " (default " (car org-refile-history) ")"))
11247 (and (assoc cbnex tbl) (setq cdef cbnex)
11248 (concat " (default " cbnex ")"))) ": "))
11249 pa answ parent-target child parent old-hist)
11250 (setq old-hist org-refile-history)
11251 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11252 nil 'org-refile-history (or cdef (car org-refile-history))))
11253 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11254 (org-refile-check-position pa)
11255 (if pa
11256 (progn
11257 (when (or (not org-refile-history)
11258 (not (eq old-hist org-refile-history))
11259 (not (equal (car pa) (car org-refile-history))))
11260 (setq org-refile-history
11261 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11262 org-refile-history
11263 (cdr org-refile-history))))
11264 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11265 (pop org-refile-history)))
11267 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11268 (progn
11269 (setq parent (match-string 1 answ)
11270 child (match-string 2 answ))
11271 (setq parent-target (or (assoc parent tbl)
11272 (assoc (concat parent "/") tbl)))
11273 (when (and parent-target
11274 (or (eq new-nodes t)
11275 (and (eq new-nodes 'confirm)
11276 (y-or-n-p (format "Create new node \"%s\"? "
11277 child)))))
11278 (org-refile-new-child parent-target child)))
11279 (error "Invalid target location")))))
11281 (declare-function org-string-nw-p "org-macs" (s))
11282 (defun org-refile-check-position (refile-pointer)
11283 "Check if the refile pointer matches the headline to which it points."
11284 (let* ((file (nth 1 refile-pointer))
11285 (re (nth 2 refile-pointer))
11286 (pos (nth 3 refile-pointer))
11287 buffer)
11288 (if (and (not (markerp pos)) (not file))
11289 (error "Please save the buffer to a file before refiling")
11290 (when (org-string-nw-p re)
11291 (setq buffer (if (markerp pos)
11292 (marker-buffer pos)
11293 (or (find-buffer-visiting file)
11294 (find-file-noselect file))))
11295 (with-current-buffer buffer
11296 (save-excursion
11297 (save-restriction
11298 (widen)
11299 (goto-char pos)
11300 (beginning-of-line 1)
11301 (unless (org-looking-at-p re)
11302 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11304 (defun org-refile-new-child (parent-target child)
11305 "Use refile target PARENT-TARGET to add new CHILD below it."
11306 (unless parent-target
11307 (error "Cannot find parent for new node"))
11308 (let ((file (nth 1 parent-target))
11309 (pos (nth 3 parent-target))
11310 level)
11311 (with-current-buffer (or (find-buffer-visiting file)
11312 (find-file-noselect file))
11313 (save-excursion
11314 (save-restriction
11315 (widen)
11316 (if pos
11317 (goto-char pos)
11318 (goto-char (point-max))
11319 (if (not (bolp)) (newline)))
11320 (when (looking-at org-outline-regexp)
11321 (setq level (funcall outline-level))
11322 (org-end-of-subtree t t))
11323 (org-back-over-empty-lines)
11324 (insert "\n" (make-string
11325 (if pos (org-get-valid-level level 1) 1) ?*)
11326 " " child "\n")
11327 (beginning-of-line 0)
11328 (list (concat (car parent-target) "/" child) file "" (point)))))))
11330 (defun org-olpath-completing-read (prompt collection &rest args)
11331 "Read an outline path like a file name."
11332 (let ((thetable collection)
11333 (org-completion-use-ido nil) ; does not work with ido.
11334 (org-completion-use-iswitchb nil)) ; or iswitchb
11335 (apply
11336 'org-icompleting-read prompt
11337 (lambda (string predicate &optional flag)
11338 (let (rtn r f (l (length string)))
11339 (cond
11340 ((eq flag nil)
11341 ;; try completion
11342 (try-completion string thetable))
11343 ((eq flag t)
11344 ;; all-completions
11345 (setq rtn (all-completions string thetable predicate))
11346 (mapcar
11347 (lambda (x)
11348 (setq r (substring x l))
11349 (if (string-match " ([^)]*)$" x)
11350 (setq f (match-string 0 x))
11351 (setq f ""))
11352 (if (string-match "/" r)
11353 (concat string (substring r 0 (match-end 0)) f)
11355 rtn))
11356 ((eq flag 'lambda)
11357 ;; exact match?
11358 (assoc string thetable)))))
11359 args)))
11361 ;;;; Dynamic blocks
11363 (defun org-find-dblock (name)
11364 "Find the first dynamic block with name NAME in the buffer.
11365 If not found, stay at current position and return nil."
11366 (let ((case-fold-search t) pos)
11367 (save-excursion
11368 (goto-char (point-min))
11369 (setq pos (and (re-search-forward
11370 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11371 (match-beginning 0))))
11372 (if pos (goto-char pos))
11373 pos))
11375 (defconst org-dblock-start-re
11376 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11377 "Matches the start line of a dynamic block, with parameters.")
11379 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11380 "Matches the end of a dynamic block.")
11382 (defun org-create-dblock (plist)
11383 "Create a dynamic block section, with parameters taken from PLIST.
11384 PLIST must contain a :name entry which is used as name of the block."
11385 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11386 (end-of-line 1)
11387 (newline))
11388 (let ((col (current-column))
11389 (name (plist-get plist :name)))
11390 (insert "#+BEGIN: " name)
11391 (while plist
11392 (if (eq (car plist) :name)
11393 (setq plist (cddr plist))
11394 (insert " " (prin1-to-string (pop plist)))))
11395 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11396 (beginning-of-line -2)))
11398 (defun org-prepare-dblock ()
11399 "Prepare dynamic block for refresh.
11400 This empties the block, puts the cursor at the insert position and returns
11401 the property list including an extra property :name with the block name."
11402 (unless (looking-at org-dblock-start-re)
11403 (error "Not at a dynamic block"))
11404 (let* ((begdel (1+ (match-end 0)))
11405 (name (org-no-properties (match-string 1)))
11406 (params (append (list :name name)
11407 (read (concat "(" (match-string 3) ")")))))
11408 (save-excursion
11409 (beginning-of-line 1)
11410 (skip-chars-forward " \t")
11411 (setq params (plist-put params :indentation-column (current-column))))
11412 (unless (re-search-forward org-dblock-end-re nil t)
11413 (error "Dynamic block not terminated"))
11414 (setq params
11415 (append params
11416 (list :content (buffer-substring
11417 begdel (match-beginning 0)))))
11418 (delete-region begdel (match-beginning 0))
11419 (goto-char begdel)
11420 (open-line 1)
11421 params))
11423 (defun org-map-dblocks (&optional command)
11424 "Apply COMMAND to all dynamic blocks in the current buffer.
11425 If COMMAND is not given, use `org-update-dblock'."
11426 (let ((cmd (or command 'org-update-dblock)))
11427 (save-excursion
11428 (goto-char (point-min))
11429 (while (re-search-forward org-dblock-start-re nil t)
11430 (goto-char (match-beginning 0))
11431 (save-excursion
11432 (condition-case nil
11433 (funcall cmd)
11434 (error (message "Error during update of dynamic block"))))
11435 (unless (re-search-forward org-dblock-end-re nil t)
11436 (error "Dynamic block not terminated"))))))
11438 (defun org-dblock-update (&optional arg)
11439 "User command for updating dynamic blocks.
11440 Update the dynamic block at point. With prefix ARG, update all dynamic
11441 blocks in the buffer."
11442 (interactive "P")
11443 (if arg
11444 (org-update-all-dblocks)
11445 (or (looking-at org-dblock-start-re)
11446 (org-beginning-of-dblock))
11447 (org-update-dblock)))
11449 (defun org-update-dblock ()
11450 "Update the dynamic block at point.
11451 This means to empty the block, parse for parameters and then call
11452 the correct writing function."
11453 (interactive)
11454 (save-window-excursion
11455 (let* ((pos (point))
11456 (line (org-current-line))
11457 (params (org-prepare-dblock))
11458 (name (plist-get params :name))
11459 (indent (plist-get params :indentation-column))
11460 (cmd (intern (concat "org-dblock-write:" name))))
11461 (message "Updating dynamic block `%s' at line %d..." name line)
11462 (funcall cmd params)
11463 (message "Updating dynamic block `%s' at line %d...done" name line)
11464 (goto-char pos)
11465 (when (and indent (> indent 0))
11466 (setq indent (make-string indent ?\ ))
11467 (save-excursion
11468 (org-beginning-of-dblock)
11469 (forward-line 1)
11470 (while (not (looking-at org-dblock-end-re))
11471 (insert indent)
11472 (beginning-of-line 2))
11473 (when (looking-at org-dblock-end-re)
11474 (and (looking-at "[ \t]+")
11475 (replace-match ""))
11476 (insert indent)))))))
11478 (defun org-beginning-of-dblock ()
11479 "Find the beginning of the dynamic block at point.
11480 Error if there is no such block at point."
11481 (let ((pos (point))
11482 beg)
11483 (end-of-line 1)
11484 (if (and (re-search-backward org-dblock-start-re nil t)
11485 (setq beg (match-beginning 0))
11486 (re-search-forward org-dblock-end-re nil t)
11487 (> (match-end 0) pos))
11488 (goto-char beg)
11489 (goto-char pos)
11490 (error "Not in a dynamic block"))))
11492 (defun org-update-all-dblocks ()
11493 "Update all dynamic blocks in the buffer.
11494 This function can be used in a hook."
11495 (interactive)
11496 (when (derived-mode-p 'org-mode)
11497 (org-map-dblocks 'org-update-dblock)))
11500 ;;;; Completion
11502 (defconst org-additional-option-like-keywords
11503 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11504 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11505 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11506 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11507 "BEGIN:" "END:"
11508 "ORGTBL" "TBLFM:" "TBLNAME:"
11509 "BEGIN_EXAMPLE" "END_EXAMPLE"
11510 "BEGIN_VERBATIM" "END_VERBATIM"
11511 "BEGIN_QUOTE" "END_QUOTE"
11512 "BEGIN_VERSE" "END_VERSE"
11513 "BEGIN_CENTER" "END_CENTER"
11514 "BEGIN_SRC" "END_SRC"
11515 "BEGIN_RESULT" "END_RESULT"
11516 "BEGIN_lstlisting" "END_lstlisting"
11517 "NAME:" "RESULTS:"
11518 "HEADER:" "HEADERS:"
11519 "COLUMNS:" "PROPERTY:"
11520 "CAPTION:" "LABEL:"
11521 "SETUPFILE:"
11522 "INCLUDE:" "INDEX:"
11523 "BIND:"
11524 "MACRO:"))
11526 (defconst org-options-keywords
11527 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11528 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11529 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11530 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11531 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11532 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11533 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11535 (defconst org-additional-option-like-keywords-for-flyspell
11536 (delete-dups
11537 (split-string
11538 (mapconcat (lambda(k)
11539 (replace-regexp-in-string
11540 "_\\|:" " "
11541 (concat k " " (downcase k) " " (upcase k))))
11542 (append org-options-keywords org-additional-option-like-keywords)
11543 " ")
11544 " +" t)))
11546 (defcustom org-structure-template-alist
11547 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11548 "<src lang=\"?\">\n\n</src>")
11549 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11550 "<example>\n?\n</example>")
11551 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11552 "<quote>\n?\n</quote>")
11553 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11554 "<verse>\n?\n</verse>")
11555 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11556 "<verbatim>\n?\n</verbatim>")
11557 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11558 "<center>\n?\n</center>")
11559 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11560 "<literal style=\"latex\">\n?\n</literal>")
11561 ("L" "#+LaTeX: "
11562 "<literal style=\"latex\">?</literal>")
11563 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11564 "<literal style=\"html\">\n?\n</literal>")
11565 ("H" "#+HTML: "
11566 "<literal style=\"html\">?</literal>")
11567 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11568 ("A" "#+ASCII: ")
11569 ("i" "#+INDEX: ?"
11570 "#+INDEX: ?")
11571 ("I" "#+INCLUDE: %file ?"
11572 "<include file=%file markup=\"?\">"))
11573 "Structure completion elements.
11574 This is a list of abbreviation keys and values. The value gets inserted
11575 if you type `<' followed by the key and then press the completion key,
11576 usually `M-TAB'. %file will be replaced by a file name after prompting
11577 for the file using completion. The cursor will be placed at the position
11578 of the `?` in the template.
11579 There are two templates for each key, the first uses the original Org syntax,
11580 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11581 the default when the /org-mtags.el/ module has been loaded. See also the
11582 variable `org-mtags-prefer-muse-templates'."
11583 :group 'org-completion
11584 :type '(repeat
11585 (string :tag "Key")
11586 (string :tag "Template")
11587 (string :tag "Muse Template")))
11589 (defun org-try-structure-completion ()
11590 "Try to complete a structure template before point.
11591 This looks for strings like \"<e\" on an otherwise empty line and
11592 expands them."
11593 (let ((l (buffer-substring (point-at-bol) (point)))
11595 (when (and (looking-at "[ \t]*$")
11596 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11597 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11598 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11599 (match-beginning 1)) a)
11600 t)))
11602 (defun org-complete-expand-structure-template (start cell)
11603 "Expand a structure template."
11604 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11605 (rpl (nth (if musep 2 1) cell))
11606 (ind ""))
11607 (delete-region start (point))
11608 (when (string-match "\\`#\\+" rpl)
11609 (cond
11610 ((bolp))
11611 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11612 (setq ind (buffer-substring (point-at-bol) (point))))
11613 (t (newline))))
11614 (setq start (point))
11615 (if (string-match "%file" rpl)
11616 (setq rpl (replace-match
11617 (concat
11618 "\""
11619 (save-match-data
11620 (abbreviate-file-name (read-file-name "Include file: ")))
11621 "\"")
11622 t t rpl)))
11623 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11624 (concat "\n" ind)))
11625 (insert rpl)
11626 (if (re-search-backward "\\?" start t) (delete-char 1))))
11628 ;;;; TODO, DEADLINE, Comments
11630 (defun org-toggle-comment ()
11631 "Change the COMMENT state of an entry."
11632 (interactive)
11633 (save-excursion
11634 (org-back-to-heading)
11635 (let (case-fold-search)
11636 (cond
11637 ((looking-at (format org-heading-keyword-regexp-format
11638 org-comment-string))
11639 (goto-char (match-end 1))
11640 (looking-at (concat " +" org-comment-string))
11641 (replace-match "" t t)
11642 (when (eolp) (insert " ")))
11643 ((looking-at org-outline-regexp)
11644 (goto-char (match-end 0))
11645 (insert org-comment-string " "))))))
11647 (defvar org-last-todo-state-is-todo nil
11648 "This is non-nil when the last TODO state change led to a TODO state.
11649 If the last change removed the TODO tag or switched to DONE, then
11650 this is nil.")
11652 (defvar org-setting-tags nil) ; dynamically skipped
11654 (defvar org-todo-setup-filter-hook nil
11655 "Hook for functions that pre-filter todo specs.
11656 Each function takes a todo spec and returns either nil or the spec
11657 transformed into canonical form." )
11659 (defvar org-todo-get-default-hook nil
11660 "Hook for functions that get a default item for todo.
11661 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11662 nil or a string to be used for the todo mark." )
11664 (defvar org-agenda-headline-snapshot-before-repeat)
11666 (defun org-current-effective-time ()
11667 "Return current time adjusted for `org-extend-today-until' variable."
11668 (let* ((ct (org-current-time))
11669 (dct (decode-time ct))
11670 (ct1
11671 (cond
11672 (org-use-last-clock-out-time-as-effective-time
11673 (or (org-clock-get-last-clock-out-time) ct))
11674 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11675 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11676 (t ct))))
11677 ct1))
11679 (defun org-todo-yesterday (&optional arg)
11680 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11681 (interactive "P")
11682 (if (eq major-mode 'org-agenda-mode)
11683 (apply 'org-agenda-todo-yesterday arg)
11684 (let* ((hour (third (decode-time
11685 (org-current-time))))
11686 (org-extend-today-until (1+ hour)))
11687 (org-todo arg))))
11689 (defvar org-block-entry-blocking ""
11690 "First entry preventing the TODO state change.")
11692 (defun org-todo (&optional arg)
11693 "Change the TODO state of an item.
11694 The state of an item is given by a keyword at the start of the heading,
11695 like
11696 *** TODO Write paper
11697 *** DONE Call mom
11699 The different keywords are specified in the variable `org-todo-keywords'.
11700 By default the available states are \"TODO\" and \"DONE\".
11701 So for this example: when the item starts with TODO, it is changed to DONE.
11702 When it starts with DONE, the DONE is removed. And when neither TODO nor
11703 DONE are present, add TODO at the beginning of the heading.
11705 With \\[universal-argument] prefix arg, use completion to determine the new \
11706 state.
11707 With numeric prefix arg, switch to that state.
11708 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11709 keywords (nextset).
11710 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11711 With a numeric prefix arg of 0, inhibit note taking for the change.
11713 For calling through lisp, arg is also interpreted in the following way:
11714 'none -> empty state
11715 \"\"(empty string) -> switch to empty state
11716 'done -> switch to DONE
11717 'nextset -> switch to the next set of keywords
11718 'previousset -> switch to the previous set of keywords
11719 \"WAITING\" -> switch to the specified keyword, but only if it
11720 really is a member of `org-todo-keywords'."
11721 (interactive "P")
11722 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11723 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11724 'region-start-level 'region))
11725 org-loop-over-headlines-in-active-region)
11726 (org-map-entries
11727 `(org-todo ,arg)
11728 org-loop-over-headlines-in-active-region
11729 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11730 (if (equal arg '(16)) (setq arg 'nextset))
11731 (let ((org-blocker-hook org-blocker-hook)
11732 commentp
11733 case-fold-search)
11734 (when (equal arg '(64))
11735 (setq arg nil org-blocker-hook nil))
11736 (when (and org-blocker-hook
11737 (or org-inhibit-blocking
11738 (org-entry-get nil "NOBLOCKING")))
11739 (setq org-blocker-hook nil))
11740 (save-excursion
11741 (catch 'exit
11742 (org-back-to-heading t)
11743 (when (looking-at (concat "^\\*+ " org-comment-string))
11744 (org-toggle-comment)
11745 (setq commentp t))
11746 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11747 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11748 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11749 (let* ((match-data (match-data))
11750 (startpos (point-at-bol))
11751 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11752 (org-log-done org-log-done)
11753 (org-log-repeat org-log-repeat)
11754 (org-todo-log-states org-todo-log-states)
11755 (org-inhibit-logging
11756 (if (equal arg 0)
11757 (progn (setq arg nil) 'note) org-inhibit-logging))
11758 (this (match-string 1))
11759 (hl-pos (match-beginning 0))
11760 (head (org-get-todo-sequence-head this))
11761 (ass (assoc head org-todo-kwd-alist))
11762 (interpret (nth 1 ass))
11763 (done-word (nth 3 ass))
11764 (final-done-word (nth 4 ass))
11765 (org-last-state (or this ""))
11766 (completion-ignore-case t)
11767 (member (member this org-todo-keywords-1))
11768 (tail (cdr member))
11769 (org-state (cond
11770 ((and org-todo-key-trigger
11771 (or (and (equal arg '(4))
11772 (eq org-use-fast-todo-selection 'prefix))
11773 (and (not arg) org-use-fast-todo-selection
11774 (not (eq org-use-fast-todo-selection
11775 'prefix)))))
11776 ;; Use fast selection
11777 (org-fast-todo-selection))
11778 ((and (equal arg '(4))
11779 (or (not org-use-fast-todo-selection)
11780 (not org-todo-key-trigger)))
11781 ;; Read a state with completion
11782 (org-icompleting-read
11783 "State: " (mapcar (lambda(x) (list x))
11784 org-todo-keywords-1)
11785 nil t))
11786 ((eq arg 'right)
11787 (if this
11788 (if tail (car tail) nil)
11789 (car org-todo-keywords-1)))
11790 ((eq arg 'left)
11791 (if (equal member org-todo-keywords-1)
11793 (if this
11794 (nth (- (length org-todo-keywords-1)
11795 (length tail) 2)
11796 org-todo-keywords-1)
11797 (org-last org-todo-keywords-1))))
11798 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11799 (setq arg nil))) ; hack to fall back to cycling
11800 (arg
11801 ;; user or caller requests a specific state
11802 (cond
11803 ((equal arg "") nil)
11804 ((eq arg 'none) nil)
11805 ((eq arg 'done) (or done-word (car org-done-keywords)))
11806 ((eq arg 'nextset)
11807 (or (car (cdr (member head org-todo-heads)))
11808 (car org-todo-heads)))
11809 ((eq arg 'previousset)
11810 (let ((org-todo-heads (reverse org-todo-heads)))
11811 (or (car (cdr (member head org-todo-heads)))
11812 (car org-todo-heads))))
11813 ((car (member arg org-todo-keywords-1)))
11814 ((stringp arg)
11815 (error "State `%s' not valid in this file" arg))
11816 ((nth (1- (prefix-numeric-value arg))
11817 org-todo-keywords-1))))
11818 ((null member) (or head (car org-todo-keywords-1)))
11819 ((equal this final-done-word) nil) ;; -> make empty
11820 ((null tail) nil) ;; -> first entry
11821 ((memq interpret '(type priority))
11822 (if (eq this-command last-command)
11823 (car tail)
11824 (if (> (length tail) 0)
11825 (or done-word (car org-done-keywords))
11826 nil)))
11828 (car tail))))
11829 (org-state (or
11830 (run-hook-with-args-until-success
11831 'org-todo-get-default-hook org-state org-last-state)
11832 org-state))
11833 (next (if org-state (concat " " org-state " ") " "))
11834 (change-plist (list :type 'todo-state-change :from this :to org-state
11835 :position startpos))
11836 dolog now-done-p)
11837 (when org-blocker-hook
11838 (setq org-last-todo-state-is-todo
11839 (not (member this org-done-keywords)))
11840 (unless (save-excursion
11841 (save-match-data
11842 (org-with-wide-buffer
11843 (run-hook-with-args-until-failure
11844 'org-blocker-hook change-plist))))
11845 (if (org-called-interactively-p 'interactive)
11846 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11847 this org-state org-block-entry-blocking)
11848 ;; fail silently
11849 (message "TODO state change from %s to %s blocked (by \"%s\")"
11850 this org-state org-block-entry-blocking)
11851 (throw 'exit nil))))
11852 (store-match-data match-data)
11853 (replace-match next t t)
11854 (unless (pos-visible-in-window-p hl-pos)
11855 (message "TODO state changed to %s" (org-trim next)))
11856 (unless head
11857 (setq head (org-get-todo-sequence-head org-state)
11858 ass (assoc head org-todo-kwd-alist)
11859 interpret (nth 1 ass)
11860 done-word (nth 3 ass)
11861 final-done-word (nth 4 ass)))
11862 (when (memq arg '(nextset previousset))
11863 (message "Keyword-Set %d/%d: %s"
11864 (- (length org-todo-sets) -1
11865 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11866 (length org-todo-sets)
11867 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11868 (setq org-last-todo-state-is-todo
11869 (not (member org-state org-done-keywords)))
11870 (setq now-done-p (and (member org-state org-done-keywords)
11871 (not (member this org-done-keywords))))
11872 (and logging (org-local-logging logging))
11873 (when (and (or org-todo-log-states org-log-done)
11874 (not (eq org-inhibit-logging t))
11875 (not (memq arg '(nextset previousset))))
11876 ;; we need to look at recording a time and note
11877 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11878 (nth 2 (assoc this org-todo-log-states))))
11879 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11880 (setq dolog 'time))
11881 (when (and org-state
11882 (member org-state org-not-done-keywords)
11883 (not (member this org-not-done-keywords)))
11884 ;; This is now a todo state and was not one before
11885 ;; If there was a CLOSED time stamp, get rid of it.
11886 (org-add-planning-info nil nil 'closed))
11887 (when (and now-done-p org-log-done)
11888 ;; It is now done, and it was not done before
11889 (org-add-planning-info 'closed (org-current-effective-time))
11890 (if (and (not dolog) (eq 'note org-log-done))
11891 (org-add-log-setup 'done org-state this 'findpos 'note)))
11892 (when (and org-state dolog)
11893 ;; This is a non-nil state, and we need to log it
11894 (org-add-log-setup 'state org-state this 'findpos dolog)))
11895 ;; Fixup tag positioning
11896 (org-todo-trigger-tag-changes org-state)
11897 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11898 (when org-provide-todo-statistics
11899 (org-update-parent-todo-statistics))
11900 (run-hooks 'org-after-todo-state-change-hook)
11901 (if (and arg (not (member org-state org-done-keywords)))
11902 (setq head (org-get-todo-sequence-head org-state)))
11903 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11904 ;; Do we need to trigger a repeat?
11905 (when now-done-p
11906 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11907 ;; This is for the agenda, take a snapshot of the headline.
11908 (save-match-data
11909 (setq org-agenda-headline-snapshot-before-repeat
11910 (org-get-heading))))
11911 (org-auto-repeat-maybe org-state))
11912 ;; Fixup cursor location if close to the keyword
11913 (if (and (outline-on-heading-p)
11914 (not (bolp))
11915 (save-excursion (beginning-of-line 1)
11916 (looking-at org-todo-line-regexp))
11917 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11918 (progn
11919 (goto-char (or (match-end 2) (match-end 1)))
11920 (and (looking-at " ") (just-one-space))))
11921 (when org-trigger-hook
11922 (save-excursion
11923 (run-hook-with-args 'org-trigger-hook change-plist)))
11924 (when commentp (org-toggle-comment))))))))
11926 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11927 "Block turning an entry into a TODO, using the hierarchy.
11928 This checks whether the current task should be blocked from state
11929 changes. Such blocking occurs when:
11931 1. The task has children which are not all in a completed state.
11933 2. A task has a parent with the property :ORDERED:, and there
11934 are siblings prior to the current task with incomplete
11935 status.
11937 3. The parent of the task is blocked because it has siblings that should
11938 be done first, or is child of a block grandparent TODO entry."
11940 (if (not org-enforce-todo-dependencies)
11941 t ; if locally turned off don't block
11942 (catch 'dont-block
11943 ;; If this is not a todo state change, or if this entry is already DONE,
11944 ;; do not block
11945 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11946 (member (plist-get change-plist :from)
11947 (cons 'done org-done-keywords))
11948 (member (plist-get change-plist :to)
11949 (cons 'todo org-not-done-keywords))
11950 (not (plist-get change-plist :to)))
11951 (throw 'dont-block t))
11952 ;; If this task has children, and any are undone, it's blocked
11953 (save-excursion
11954 (org-back-to-heading t)
11955 (let ((this-level (funcall outline-level)))
11956 (outline-next-heading)
11957 (let ((child-level (funcall outline-level)))
11958 (while (and (not (eobp))
11959 (> child-level this-level))
11960 ;; this todo has children, check whether they are all
11961 ;; completed
11962 (if (and (not (org-entry-is-done-p))
11963 (org-entry-is-todo-p))
11964 (progn (setq org-block-entry-blocking (org-get-heading))
11965 (throw 'dont-block nil)))
11966 (outline-next-heading)
11967 (setq child-level (funcall outline-level))))))
11968 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11969 ;; any previous siblings are undone, it's blocked
11970 (save-excursion
11971 (org-back-to-heading t)
11972 (let* ((pos (point))
11973 (parent-pos (and (org-up-heading-safe) (point))))
11974 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11975 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11976 (forward-line 1)
11977 (re-search-forward org-not-done-heading-regexp pos t))
11978 (setq org-block-entry-blocking (match-string 0))
11979 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11980 ;; Search further up the hierarchy, to see if an ancestor is blocked
11981 (while t
11982 (goto-char parent-pos)
11983 (if (not (looking-at org-not-done-heading-regexp))
11984 (throw 'dont-block t)) ; do not block, parent is not a TODO
11985 (setq pos (point))
11986 (setq parent-pos (and (org-up-heading-safe) (point)))
11987 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11988 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11989 (forward-line 1)
11990 (re-search-forward org-not-done-heading-regexp pos t)
11991 (setq org-block-entry-blocking (org-get-heading)))
11992 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11994 (defcustom org-track-ordered-property-with-tag nil
11995 "Should the ORDERED property also be shown as a tag?
11996 The ORDERED property decides if an entry should require subtasks to be
11997 completed in sequence. Since a property is not very visible, setting
11998 this option means that toggling the ORDERED property with the command
11999 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12000 not relevant for the behavior, but it makes things more visible.
12002 Note that toggling the tag with tags commands will not change the property
12003 and therefore not influence behavior!
12005 This can be t, meaning the tag ORDERED should be used, It can also be a
12006 string to select a different tag for this task."
12007 :group 'org-todo
12008 :type '(choice
12009 (const :tag "No tracking" nil)
12010 (const :tag "Track with ORDERED tag" t)
12011 (string :tag "Use other tag")))
12013 (defun org-toggle-ordered-property ()
12014 "Toggle the ORDERED property of the current entry.
12015 For better visibility, you can track the value of this property with a tag.
12016 See variable `org-track-ordered-property-with-tag'."
12017 (interactive)
12018 (let* ((t1 org-track-ordered-property-with-tag)
12019 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12020 (save-excursion
12021 (org-back-to-heading)
12022 (if (org-entry-get nil "ORDERED")
12023 (progn
12024 (org-delete-property "ORDERED")
12025 (and tag (org-toggle-tag tag 'off))
12026 (message "Subtasks can be completed in arbitrary order"))
12027 (org-entry-put nil "ORDERED" "t")
12028 (and tag (org-toggle-tag tag 'on))
12029 (message "Subtasks must be completed in sequence")))))
12031 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12032 (defun org-block-todo-from-checkboxes (change-plist)
12033 "Block turning an entry into a TODO, using checkboxes.
12034 This checks whether the current task should be blocked from state
12035 changes because there are unchecked boxes in this entry."
12036 (if (not org-enforce-todo-checkbox-dependencies)
12037 t ; if locally turned off don't block
12038 (catch 'dont-block
12039 ;; If this is not a todo state change, or if this entry is already DONE,
12040 ;; do not block
12041 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12042 (member (plist-get change-plist :from)
12043 (cons 'done org-done-keywords))
12044 (member (plist-get change-plist :to)
12045 (cons 'todo org-not-done-keywords))
12046 (not (plist-get change-plist :to)))
12047 (throw 'dont-block t))
12048 ;; If this task has checkboxes that are not checked, it's blocked
12049 (save-excursion
12050 (org-back-to-heading t)
12051 (let ((beg (point)) end)
12052 (outline-next-heading)
12053 (setq end (point))
12054 (goto-char beg)
12055 (if (org-list-search-forward
12056 (concat (org-item-beginning-re)
12057 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12058 "\\[[- ]\\]")
12059 end t)
12060 (progn
12061 (if (boundp 'org-blocked-by-checkboxes)
12062 (setq org-blocked-by-checkboxes t))
12063 (throw 'dont-block nil)))))
12064 t))) ; do not block
12066 (defun org-entry-blocked-p ()
12067 "Is the current entry blocked?"
12068 (org-with-buffer-modified-unmodified
12069 (if (org-entry-get nil "NOBLOCKING")
12070 nil ;; Never block this entry
12071 (not
12072 (run-hook-with-args-until-failure
12073 'org-blocker-hook
12074 (list :type 'todo-state-change
12075 :position (point)
12076 :from 'todo
12077 :to 'done))))))
12079 (defun org-update-statistics-cookies (all)
12080 "Update the statistics cookie, either from TODO or from checkboxes.
12081 This should be called with the cursor in a line with a statistics cookie."
12082 (interactive "P")
12083 (if all
12084 (progn
12085 (org-update-checkbox-count 'all)
12086 (org-map-entries 'org-update-parent-todo-statistics))
12087 (if (not (org-at-heading-p))
12088 (org-update-checkbox-count)
12089 (let ((pos (point-marker))
12090 end l1 l2)
12091 (ignore-errors (org-back-to-heading t))
12092 (if (not (org-at-heading-p))
12093 (org-update-checkbox-count)
12094 (setq l1 (org-outline-level))
12095 (setq end (save-excursion
12096 (outline-next-heading)
12097 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12098 (point)))
12099 (if (and (save-excursion
12100 (re-search-forward
12101 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12102 (not (save-excursion (re-search-forward
12103 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12104 (org-update-checkbox-count)
12105 (if (and l2 (> l2 l1))
12106 (progn
12107 (goto-char end)
12108 (org-update-parent-todo-statistics))
12109 (goto-char pos)
12110 (beginning-of-line 1)
12111 (while (re-search-forward
12112 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12113 (point-at-eol) t)
12114 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12115 (goto-char pos)
12116 (move-marker pos nil)))))
12118 (defvar org-entry-property-inherited-from) ;; defined below
12119 (defun org-update-parent-todo-statistics ()
12120 "Update any statistics cookie in the parent of the current headline.
12121 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12122 the entire subtree and this will travel up the hierarchy and update
12123 statistics everywhere."
12124 (let* ((prop (save-excursion (org-up-heading-safe)
12125 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12126 (recursive (or (not org-hierarchical-todo-statistics)
12127 (and prop (string-match "\\<recursive\\>" prop))))
12128 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12130 (first t)
12131 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12132 level ltoggle l1 new ndel
12133 (cnt-all 0) (cnt-done 0) is-percent kwd
12134 checkbox-beg ov ovs ove cookie-present)
12135 (catch 'exit
12136 (save-excursion
12137 (beginning-of-line 1)
12138 (setq ltoggle (funcall outline-level))
12139 ;; Three situations are to consider:
12141 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12142 ;; to the top-level ancestor on the headline;
12144 ;; 2. If parent has "recursive" property, repeat up to the
12145 ;; headline setting that property, taking inheritance into
12146 ;; account;
12148 ;; 3. Else, move up to direct parent and proceed only once.
12149 (while (and (setq level (org-up-heading-safe))
12150 (or recursive first)
12151 (>= (point) lim))
12152 (setq first nil cookie-present nil)
12153 (unless (and level
12154 (not (string-match
12155 "\\<checkbox\\>"
12156 (downcase (or (org-entry-get nil "COOKIE_DATA")
12157 "")))))
12158 (throw 'exit nil))
12159 (while (re-search-forward box-re (point-at-eol) t)
12160 (setq cnt-all 0 cnt-done 0 cookie-present t)
12161 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12162 (save-match-data
12163 (unless (outline-next-heading) (throw 'exit nil))
12164 (while (and (looking-at org-complex-heading-regexp)
12165 (> (setq l1 (length (match-string 1))) level))
12166 (setq kwd (and (or recursive (= l1 ltoggle))
12167 (match-string 2)))
12168 (if (or (eq org-provide-todo-statistics 'all-headlines)
12169 (and (listp org-provide-todo-statistics)
12170 (or (member kwd org-provide-todo-statistics)
12171 (member kwd org-done-keywords))))
12172 (setq cnt-all (1+ cnt-all))
12173 (if (eq org-provide-todo-statistics t)
12174 (and kwd (setq cnt-all (1+ cnt-all)))))
12175 (and (member kwd org-done-keywords)
12176 (setq cnt-done (1+ cnt-done)))
12177 (outline-next-heading)))
12178 (setq new
12179 (if is-percent
12180 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12181 (format "[%d/%d]" cnt-done cnt-all))
12182 ndel (- (match-end 0) checkbox-beg))
12183 ;; handle overlays when updating cookie from column view
12184 (when (setq ov (car (overlays-at checkbox-beg)))
12185 (setq ovs (overlay-start ov) ove (overlay-end ov))
12186 (delete-overlay ov))
12187 (goto-char checkbox-beg)
12188 (insert new)
12189 (delete-region (point) (+ (point) ndel))
12190 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12191 (when ov (move-overlay ov ovs ove)))
12192 (when cookie-present
12193 (run-hook-with-args 'org-after-todo-statistics-hook
12194 cnt-done (- cnt-all cnt-done))))))
12195 (run-hooks 'org-todo-statistics-hook)))
12197 (defvar org-after-todo-statistics-hook nil
12198 "Hook that is called after a TODO statistics cookie has been updated.
12199 Each function is called with two arguments: the number of not-done entries
12200 and the number of done entries.
12202 For example, the following function, when added to this hook, will switch
12203 an entry to DONE when all children are done, and back to TODO when new
12204 entries are set to a TODO status. Note that this hook is only called
12205 when there is a statistics cookie in the headline!
12207 (defun org-summary-todo (n-done n-not-done)
12208 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12209 (let (org-log-done org-log-states) ; turn off logging
12210 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12213 (defvar org-todo-statistics-hook nil
12214 "Hook that is run whenever Org thinks TODO statistics should be updated.
12215 This hook runs even if there is no statistics cookie present, in which case
12216 `org-after-todo-statistics-hook' would not run.")
12218 (defun org-todo-trigger-tag-changes (state)
12219 "Apply the changes defined in `org-todo-state-tags-triggers'."
12220 (let ((l org-todo-state-tags-triggers)
12221 changes)
12222 (when (or (not state) (equal state ""))
12223 (setq changes (append changes (cdr (assoc "" l)))))
12224 (when (and (stringp state) (> (length state) 0))
12225 (setq changes (append changes (cdr (assoc state l)))))
12226 (when (member state org-not-done-keywords)
12227 (setq changes (append changes (cdr (assoc 'todo l)))))
12228 (when (member state org-done-keywords)
12229 (setq changes (append changes (cdr (assoc 'done l)))))
12230 (dolist (c changes)
12231 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12233 (defun org-local-logging (value)
12234 "Get logging settings from a property VALUE."
12235 (let* (words w a)
12236 ;; directly set the variables, they are already local.
12237 (setq org-log-done nil
12238 org-log-repeat nil
12239 org-todo-log-states nil)
12240 (setq words (org-split-string value))
12241 (while (setq w (pop words))
12242 (cond
12243 ((setq a (assoc w org-startup-options))
12244 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12245 (set (nth 1 a) (nth 2 a))))
12246 ((setq a (org-extract-log-state-settings w))
12247 (and (member (car a) org-todo-keywords-1)
12248 (push a org-todo-log-states)))))))
12250 (defun org-get-todo-sequence-head (kwd)
12251 "Return the head of the TODO sequence to which KWD belongs.
12252 If KWD is not set, check if there is a text property remembering the
12253 right sequence."
12254 (let (p)
12255 (cond
12256 ((not kwd)
12257 (or (get-text-property (point-at-bol) 'org-todo-head)
12258 (progn
12259 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12260 nil (point-at-eol)))
12261 (get-text-property p 'org-todo-head))))
12262 ((not (member kwd org-todo-keywords-1))
12263 (car org-todo-keywords-1))
12264 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12266 (defun org-fast-todo-selection ()
12267 "Fast TODO keyword selection with single keys.
12268 Returns the new TODO keyword, or nil if no state change should occur."
12269 (let* ((fulltable org-todo-key-alist)
12270 (done-keywords org-done-keywords) ;; needed for the faces.
12271 (maxlen (apply 'max (mapcar
12272 (lambda (x)
12273 (if (stringp (car x)) (string-width (car x)) 0))
12274 fulltable)))
12275 (expert nil)
12276 (fwidth (+ maxlen 3 1 3))
12277 (ncol (/ (- (window-width) 4) fwidth))
12278 tg cnt e c tbl
12279 groups ingroup)
12280 (save-excursion
12281 (save-window-excursion
12282 (if expert
12283 (set-buffer (get-buffer-create " *Org todo*"))
12284 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12285 (erase-buffer)
12286 (org-set-local 'org-done-keywords done-keywords)
12287 (setq tbl fulltable cnt 0)
12288 (while (setq e (pop tbl))
12289 (cond
12290 ((equal e '(:startgroup))
12291 (push '() groups) (setq ingroup t)
12292 (when (not (= cnt 0))
12293 (setq cnt 0)
12294 (insert "\n"))
12295 (insert "{ "))
12296 ((equal e '(:endgroup))
12297 (setq ingroup nil cnt 0)
12298 (insert "}\n"))
12299 ((equal e '(:newline))
12300 (when (not (= cnt 0))
12301 (setq cnt 0)
12302 (insert "\n")
12303 (setq e (car tbl))
12304 (while (equal (car tbl) '(:newline))
12305 (insert "\n")
12306 (setq tbl (cdr tbl)))))
12308 (setq tg (car e) c (cdr e))
12309 (if ingroup (push tg (car groups)))
12310 (setq tg (org-add-props tg nil 'face
12311 (org-get-todo-face tg)))
12312 (if (and (= cnt 0) (not ingroup)) (insert " "))
12313 (insert "[" c "] " tg (make-string
12314 (- fwidth 4 (length tg)) ?\ ))
12315 (when (= (setq cnt (1+ cnt)) ncol)
12316 (insert "\n")
12317 (if ingroup (insert " "))
12318 (setq cnt 0)))))
12319 (insert "\n")
12320 (goto-char (point-min))
12321 (if (not expert) (org-fit-window-to-buffer))
12322 (message "[a-z..]:Set [SPC]:clear")
12323 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12324 (cond
12325 ((or (= c ?\C-g)
12326 (and (= c ?q) (not (rassoc c fulltable))))
12327 (setq quit-flag t))
12328 ((= c ?\ ) nil)
12329 ((setq e (rassoc c fulltable) tg (car e))
12331 (t (setq quit-flag t)))))))
12333 (defun org-entry-is-todo-p ()
12334 (member (org-get-todo-state) org-not-done-keywords))
12336 (defun org-entry-is-done-p ()
12337 (member (org-get-todo-state) org-done-keywords))
12339 (defun org-get-todo-state ()
12340 (save-excursion
12341 (org-back-to-heading t)
12342 (and (looking-at org-todo-line-regexp)
12343 (match-end 2)
12344 (match-string 2))))
12346 (defun org-at-date-range-p (&optional inactive-ok)
12347 "Is the cursor inside a date range?"
12348 (interactive)
12349 (save-excursion
12350 (catch 'exit
12351 (let ((pos (point)))
12352 (skip-chars-backward "^[<\r\n")
12353 (skip-chars-backward "<[")
12354 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12355 (>= (match-end 0) pos)
12356 (throw 'exit t))
12357 (skip-chars-backward "^<[\r\n")
12358 (skip-chars-backward "<[")
12359 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12360 (>= (match-end 0) pos)
12361 (throw 'exit t)))
12362 nil)))
12364 (defun org-get-repeat (&optional tagline)
12365 "Check if there is a deadline/schedule with repeater in this entry."
12366 (save-match-data
12367 (save-excursion
12368 (org-back-to-heading t)
12369 (and (re-search-forward (if tagline
12370 (concat tagline "\\s-*" org-repeat-re)
12371 org-repeat-re)
12372 (org-entry-end-position) t)
12373 (match-string-no-properties 1)))))
12375 (defvar org-last-changed-timestamp)
12376 (defvar org-last-inserted-timestamp)
12377 (defvar org-log-post-message)
12378 (defvar org-log-note-purpose)
12379 (defvar org-log-note-how)
12380 (defvar org-log-note-extra)
12381 (defun org-auto-repeat-maybe (done-word)
12382 "Check if the current headline contains a repeated deadline/schedule.
12383 If yes, set TODO state back to what it was and change the base date
12384 of repeating deadline/scheduled time stamps to new date.
12385 This function is run automatically after each state change to a DONE state."
12386 ;; last-state is dynamically scoped into this function
12387 (let* ((repeat (org-get-repeat))
12388 (aa (assoc org-last-state org-todo-kwd-alist))
12389 (interpret (nth 1 aa))
12390 (head (nth 2 aa))
12391 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12392 (msg "Entry repeats: ")
12393 (org-log-done nil)
12394 (org-todo-log-states nil)
12395 re type n what ts time to-state)
12396 (when repeat
12397 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12398 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12399 org-todo-repeat-to-state))
12400 (unless (and to-state (member to-state org-todo-keywords-1))
12401 (setq to-state (if (eq interpret 'type) org-last-state head)))
12402 (org-todo to-state)
12403 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12404 (org-entry-put nil "LAST_REPEAT" (format-time-string
12405 (org-time-stamp-format t t))))
12406 (when org-log-repeat
12407 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12408 (memq 'org-add-log-note post-command-hook))
12409 ;; OK, we are already setup for some record
12410 (if (eq org-log-repeat 'note)
12411 ;; make sure we take a note, not only a time stamp
12412 (setq org-log-note-how 'note))
12413 ;; Set up for taking a record
12414 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12415 org-last-state
12416 'findpos org-log-repeat)))
12417 (org-back-to-heading t)
12418 (org-add-planning-info nil nil 'closed)
12419 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12420 org-deadline-time-regexp "\\)\\|\\("
12421 org-ts-regexp "\\)"))
12422 (while (re-search-forward
12423 re (save-excursion (outline-next-heading) (point)) t)
12424 (setq type (if (match-end 1) org-scheduled-string
12425 (if (match-end 3) org-deadline-string "Plain:"))
12426 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12427 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12428 (setq n (string-to-number (match-string 2 ts))
12429 what (match-string 3 ts))
12430 (if (equal what "w") (setq n (* n 7) what "d"))
12431 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12432 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12433 ;; Preparation, see if we need to modify the start date for the change
12434 (when (match-end 1)
12435 (setq time (save-match-data (org-time-string-to-time ts)))
12436 (cond
12437 ((equal (match-string 1 ts) ".")
12438 ;; Shift starting date to today
12439 (org-timestamp-change
12440 (- (org-today) (time-to-days time))
12441 'day))
12442 ((equal (match-string 1 ts) "+")
12443 (let ((nshiftmax 10) (nshift 0))
12444 (while (or (= nshift 0)
12445 (<= (time-to-days time)
12446 (time-to-days (current-time))))
12447 (when (= (incf nshift) nshiftmax)
12448 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12449 (error "Abort")))
12450 (org-timestamp-change n (cdr (assoc what whata)))
12451 (org-at-timestamp-p t)
12452 (setq ts (match-string 1))
12453 (setq time (save-match-data (org-time-string-to-time ts)))))
12454 (org-timestamp-change (- n) (cdr (assoc what whata)))
12455 ;; rematch, so that we have everything in place for the real shift
12456 (org-at-timestamp-p t)
12457 (setq ts (match-string 1))
12458 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12459 (org-timestamp-change n (cdr (assoc what whata)))
12460 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12461 (setq org-log-post-message msg)
12462 (message "%s" msg))))
12464 (defun org-show-todo-tree (arg)
12465 "Make a compact tree which shows all headlines marked with TODO.
12466 The tree will show the lines where the regexp matches, and all higher
12467 headlines above the match.
12468 With a \\[universal-argument] prefix, prompt for a regexp to match.
12469 With a numeric prefix N, construct a sparse tree for the Nth element
12470 of `org-todo-keywords-1'."
12471 (interactive "P")
12472 (let ((case-fold-search nil)
12473 (kwd-re
12474 (cond ((null arg) org-not-done-regexp)
12475 ((equal arg '(4))
12476 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12477 (mapcar 'list org-todo-keywords-1))))
12478 (concat "\\("
12479 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12480 "\\)\\>")))
12481 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12482 (regexp-quote (nth (1- (prefix-numeric-value arg))
12483 org-todo-keywords-1)))
12484 (t (error "Invalid prefix argument: %s" arg)))))
12485 (message "%d TODO entries found"
12486 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12488 (defun org-deadline (&optional remove time)
12489 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12490 With argument REMOVE, remove any deadline from the item.
12491 With argument TIME, set the deadline at the corresponding date. TIME
12492 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12493 (interactive "P")
12494 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12495 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12496 'region-start-level 'region))
12497 org-loop-over-headlines-in-active-region)
12498 (org-map-entries
12499 `(org-deadline ',remove ,time)
12500 org-loop-over-headlines-in-active-region
12501 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12502 (let* ((old-date (org-entry-get nil "DEADLINE"))
12503 (repeater (and old-date
12504 (string-match
12505 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12506 old-date)
12507 (match-string 1 old-date))))
12508 (if remove
12509 (progn
12510 (when (and old-date org-log-redeadline)
12511 (org-add-log-setup 'deldeadline nil old-date 'findpos
12512 org-log-redeadline))
12513 (org-remove-timestamp-with-keyword org-deadline-string)
12514 (message "Item no longer has a deadline."))
12515 (org-add-planning-info 'deadline time 'closed)
12516 (when (and old-date org-log-redeadline
12517 (not (equal old-date
12518 (substring org-last-inserted-timestamp 1 -1))))
12519 (org-add-log-setup 'redeadline nil old-date 'findpos
12520 org-log-redeadline))
12521 (when repeater
12522 (save-excursion
12523 (org-back-to-heading t)
12524 (when (re-search-forward (concat org-deadline-string " "
12525 org-last-inserted-timestamp)
12526 (save-excursion
12527 (outline-next-heading) (point)) t)
12528 (goto-char (1- (match-end 0)))
12529 (insert " " repeater)
12530 (setq org-last-inserted-timestamp
12531 (concat (substring org-last-inserted-timestamp 0 -1)
12532 " " repeater
12533 (substring org-last-inserted-timestamp -1))))))
12534 (message "Deadline on %s" org-last-inserted-timestamp)))))
12536 (defun org-schedule (&optional remove time)
12537 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12538 With argument REMOVE, remove any scheduling date from the item.
12539 With argument TIME, scheduled at the corresponding date. TIME can
12540 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12541 (interactive "P")
12542 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12543 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12544 'region-start-level 'region))
12545 org-loop-over-headlines-in-active-region)
12546 (org-map-entries
12547 `(org-schedule ',remove ,time)
12548 org-loop-over-headlines-in-active-region
12549 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12550 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12551 (repeater (and old-date
12552 (string-match
12553 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12554 old-date)
12555 (match-string 1 old-date))))
12556 (if remove
12557 (progn
12558 (when (and old-date org-log-reschedule)
12559 (org-add-log-setup 'delschedule nil old-date 'findpos
12560 org-log-reschedule))
12561 (org-remove-timestamp-with-keyword org-scheduled-string)
12562 (message "Item is no longer scheduled."))
12563 (org-add-planning-info 'scheduled time 'closed)
12564 (when (and old-date org-log-reschedule
12565 (not (equal old-date
12566 (substring org-last-inserted-timestamp 1 -1))))
12567 (org-add-log-setup 'reschedule nil old-date 'findpos
12568 org-log-reschedule))
12569 (when repeater
12570 (save-excursion
12571 (org-back-to-heading t)
12572 (when (re-search-forward (concat org-scheduled-string " "
12573 org-last-inserted-timestamp)
12574 (save-excursion
12575 (outline-next-heading) (point)) t)
12576 (goto-char (1- (match-end 0)))
12577 (insert " " repeater)
12578 (setq org-last-inserted-timestamp
12579 (concat (substring org-last-inserted-timestamp 0 -1)
12580 " " repeater
12581 (substring org-last-inserted-timestamp -1))))))
12582 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12584 (defun org-get-scheduled-time (pom &optional inherit)
12585 "Get the scheduled time as a time tuple, of a format suitable
12586 for calling org-schedule with, or if there is no scheduling,
12587 returns nil."
12588 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12589 (when time
12590 (apply 'encode-time (org-parse-time-string time)))))
12592 (defun org-get-deadline-time (pom &optional inherit)
12593 "Get the deadline as a time tuple, of a format suitable for
12594 calling org-deadline with, or if there is no scheduling, returns
12595 nil."
12596 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12597 (when time
12598 (apply 'encode-time (org-parse-time-string time)))))
12600 (defun org-remove-timestamp-with-keyword (keyword)
12601 "Remove all time stamps with KEYWORD in the current entry."
12602 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12603 beg)
12604 (save-excursion
12605 (org-back-to-heading t)
12606 (setq beg (point))
12607 (outline-next-heading)
12608 (while (re-search-backward re beg t)
12609 (replace-match "")
12610 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12611 (equal (char-before) ?\ ))
12612 (backward-delete-char 1)
12613 (if (string-match "^[ \t]*$" (buffer-substring
12614 (point-at-bol) (point-at-eol)))
12615 (delete-region (point-at-bol)
12616 (min (point-max) (1+ (point-at-eol))))))))))
12618 (defun org-add-planning-info (what &optional time &rest remove)
12619 "Insert new timestamp with keyword in the line directly after the headline.
12620 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12621 If non is given, the user is prompted for a date.
12622 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12623 be removed."
12624 (interactive)
12625 (let (org-time-was-given org-end-time-was-given ts
12626 end default-time default-input)
12628 (catch 'exit
12629 (when (and (memq what '(scheduled deadline))
12630 (or (not time)
12631 (and (stringp time)
12632 (string-match "^[-+]+[0-9]" time))))
12633 ;; Try to get a default date/time from existing timestamp
12634 (save-excursion
12635 (org-back-to-heading t)
12636 (setq end (save-excursion (outline-next-heading) (point)))
12637 (when (re-search-forward (if (eq what 'scheduled)
12638 org-scheduled-time-regexp
12639 org-deadline-time-regexp)
12640 end t)
12641 (setq ts (match-string 1)
12642 default-time
12643 (apply 'encode-time (org-parse-time-string ts))
12644 default-input (and ts (org-get-compact-tod ts))))))
12645 (when what
12646 (setq time
12647 (if (stringp time)
12648 ;; This is a string (relative or absolute), set proper date
12649 (apply 'encode-time
12650 (org-read-date-analyze
12651 time default-time (decode-time default-time)))
12652 ;; If necessary, get the time from the user
12653 (or time (org-read-date nil 'to-time nil nil
12654 default-time default-input)))))
12656 (when (and org-insert-labeled-timestamps-at-point
12657 (member what '(scheduled deadline)))
12658 (insert
12659 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12660 (org-insert-time-stamp time org-time-was-given
12661 nil nil nil (list org-end-time-was-given))
12662 (setq what nil))
12663 (save-excursion
12664 (save-restriction
12665 (let (col list elt ts buffer-invisibility-spec)
12666 (org-back-to-heading t)
12667 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12668 (goto-char (match-end 1))
12669 (setq col (current-column))
12670 (goto-char (match-end 0))
12671 (if (eobp) (insert "\n") (forward-char 1))
12672 (when (and (not what)
12673 (not (looking-at
12674 (concat "[ \t]*"
12675 org-keyword-time-not-clock-regexp))))
12676 ;; Nothing to add, nothing to remove...... :-)
12677 (throw 'exit nil))
12678 (if (and (not (looking-at org-outline-regexp))
12679 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12680 "[^\r\n]*"))
12681 (not (equal (match-string 1) org-clock-string)))
12682 (narrow-to-region (match-beginning 0) (match-end 0))
12683 (insert-before-markers "\n")
12684 (backward-char 1)
12685 (narrow-to-region (point) (point))
12686 (and org-adapt-indentation (org-indent-to-column col)))
12687 ;; Check if we have to remove something.
12688 (setq list (cons what remove))
12689 (while list
12690 (setq elt (pop list))
12691 (when (or (and (eq elt 'scheduled)
12692 (re-search-forward org-scheduled-time-regexp nil t))
12693 (and (eq elt 'deadline)
12694 (re-search-forward org-deadline-time-regexp nil t))
12695 (and (eq elt 'closed)
12696 (re-search-forward org-closed-time-regexp nil t)))
12697 (replace-match "")
12698 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12699 (and (looking-at "[ \t]+") (replace-match ""))
12700 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12701 (when what
12702 (insert
12703 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12704 (cond ((eq what 'scheduled) org-scheduled-string)
12705 ((eq what 'deadline) org-deadline-string)
12706 ((eq what 'closed) org-closed-string))
12707 " ")
12708 (setq ts (org-insert-time-stamp
12709 time
12710 (or org-time-was-given
12711 (and (eq what 'closed) org-log-done-with-time))
12712 (eq what 'closed)
12713 nil nil (list org-end-time-was-given)))
12714 (insert
12715 (if (not (or (bolp) (eq (char-before) ?\ )
12716 (memq (char-after) '(32 10))
12717 (eobp))) " " ""))
12718 (end-of-line 1))
12719 (goto-char (point-min))
12720 (widen)
12721 (if (and (looking-at "[ \t]*\n")
12722 (equal (char-before) ?\n))
12723 (delete-region (1- (point)) (point-at-eol)))
12724 ts))))))
12726 (defvar org-log-note-marker (make-marker))
12727 (defvar org-log-note-purpose nil)
12728 (defvar org-log-note-state nil)
12729 (defvar org-log-note-previous-state nil)
12730 (defvar org-log-note-how nil)
12731 (defvar org-log-note-extra nil)
12732 (defvar org-log-note-window-configuration nil)
12733 (defvar org-log-note-return-to (make-marker))
12734 (defvar org-log-note-effective-time nil
12735 "Remembered current time so that dynamically scoped
12736 `org-extend-today-until' affects tha timestamps in state change
12737 log")
12739 (defvar org-log-post-message nil
12740 "Message to be displayed after a log note has been stored.
12741 The auto-repeater uses this.")
12743 (defun org-add-note ()
12744 "Add a note to the current entry.
12745 This is done in the same way as adding a state change note."
12746 (interactive)
12747 (org-add-log-setup 'note nil nil 'findpos nil))
12749 (defvar org-property-end-re)
12750 (defun org-add-log-setup (&optional purpose state prev-state
12751 findpos how extra)
12752 "Set up the post command hook to take a note.
12753 If this is about to TODO state change, the new state is expected in STATE.
12754 When FINDPOS is non-nil, find the correct position for the note in
12755 the current entry. If not, assume that it can be inserted at point.
12756 HOW is an indicator what kind of note should be created.
12757 EXTRA is additional text that will be inserted into the notes buffer."
12758 (let* ((org-log-into-drawer (org-log-into-drawer))
12759 (drawer (cond ((stringp org-log-into-drawer)
12760 org-log-into-drawer)
12761 (org-log-into-drawer "LOGBOOK"))))
12762 (save-restriction
12763 (save-excursion
12764 (when findpos
12765 (org-back-to-heading t)
12766 (narrow-to-region (point) (save-excursion
12767 (outline-next-heading) (point)))
12768 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12769 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12770 "[^\r\n]*\\)?"))
12771 (goto-char (match-end 0))
12772 (cond
12773 (drawer
12774 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12775 nil t)
12776 (progn
12777 (goto-char (match-end 0))
12778 (or org-log-states-order-reversed
12779 (and (re-search-forward org-property-end-re nil t)
12780 (goto-char (1- (match-beginning 0))))))
12781 (insert "\n:" drawer ":\n:END:")
12782 (beginning-of-line 0)
12783 (org-indent-line)
12784 (beginning-of-line 2)
12785 (org-indent-line)
12786 (end-of-line 0)))
12787 ((and org-log-state-notes-insert-after-drawers
12788 (save-excursion
12789 (forward-line) (looking-at org-drawer-regexp)))
12790 (forward-line)
12791 (while (looking-at org-drawer-regexp)
12792 (goto-char (match-end 0))
12793 (re-search-forward org-property-end-re (point-max) t)
12794 (forward-line))
12795 (forward-line -1)))
12796 (unless org-log-states-order-reversed
12797 (and (= (char-after) ?\n) (forward-char 1))
12798 (org-skip-over-state-notes)
12799 (skip-chars-backward " \t\n\r")))
12800 (move-marker org-log-note-marker (point))
12801 (setq org-log-note-purpose purpose
12802 org-log-note-state state
12803 org-log-note-previous-state prev-state
12804 org-log-note-how how
12805 org-log-note-extra extra
12806 org-log-note-effective-time (org-current-effective-time))
12807 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12809 (defun org-skip-over-state-notes ()
12810 "Skip past the list of State notes in an entry."
12811 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12812 (when (ignore-errors (goto-char (org-in-item-p)))
12813 (let* ((struct (org-list-struct))
12814 (prevs (org-list-prevs-alist struct)))
12815 (while (looking-at "[ \t]*- State")
12816 (goto-char (or (org-list-get-next-item (point) struct prevs)
12817 (org-list-get-item-end (point) struct)))))))
12819 (defun org-add-log-note (&optional purpose)
12820 "Pop up a window for taking a note, and add this note later at point."
12821 (remove-hook 'post-command-hook 'org-add-log-note)
12822 (setq org-log-note-window-configuration (current-window-configuration))
12823 (delete-other-windows)
12824 (move-marker org-log-note-return-to (point))
12825 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12826 (goto-char org-log-note-marker)
12827 (org-switch-to-buffer-other-window "*Org Note*")
12828 (erase-buffer)
12829 (if (memq org-log-note-how '(time state))
12830 (let (current-prefix-arg) (org-store-log-note))
12831 (let ((org-inhibit-startup t)) (org-mode))
12832 (insert (format "# Insert note for %s.
12833 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12834 (cond
12835 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12836 ((eq org-log-note-purpose 'done) "closed todo item")
12837 ((eq org-log-note-purpose 'state)
12838 (format "state change from \"%s\" to \"%s\""
12839 (or org-log-note-previous-state "")
12840 (or org-log-note-state "")))
12841 ((eq org-log-note-purpose 'reschedule)
12842 "rescheduling")
12843 ((eq org-log-note-purpose 'delschedule)
12844 "no longer scheduled")
12845 ((eq org-log-note-purpose 'redeadline)
12846 "changing deadline")
12847 ((eq org-log-note-purpose 'deldeadline)
12848 "removing deadline")
12849 ((eq org-log-note-purpose 'refile)
12850 "refiling")
12851 ((eq org-log-note-purpose 'note)
12852 "this entry")
12853 (t (error "This should not happen")))))
12854 (if org-log-note-extra (insert org-log-note-extra))
12855 (org-set-local 'org-finish-function 'org-store-log-note)
12856 (run-hooks 'org-log-buffer-setup-hook)))
12858 (defvar org-note-abort nil) ; dynamically scoped
12859 (defun org-store-log-note ()
12860 "Finish taking a log note, and insert it to where it belongs."
12861 (let ((txt (buffer-string)))
12862 (kill-buffer (current-buffer))
12863 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12864 lines ind bul)
12865 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12866 (setq txt (replace-match "" t t txt)))
12867 (if (string-match "\\s-+\\'" txt)
12868 (setq txt (replace-match "" t t txt)))
12869 (setq lines (org-split-string txt "\n"))
12870 (when (and note (string-match "\\S-" note))
12871 (setq note
12872 (org-replace-escapes
12873 note
12874 (list (cons "%u" (user-login-name))
12875 (cons "%U" user-full-name)
12876 (cons "%t" (format-time-string
12877 (org-time-stamp-format 'long 'inactive)
12878 org-log-note-effective-time))
12879 (cons "%T" (format-time-string
12880 (org-time-stamp-format 'long nil)
12881 org-log-note-effective-time))
12882 (cons "%d" (format-time-string
12883 (org-time-stamp-format nil 'inactive)
12884 org-log-note-effective-time))
12885 (cons "%D" (format-time-string
12886 (org-time-stamp-format nil nil)
12887 org-log-note-effective-time))
12888 (cons "%s" (if org-log-note-state
12889 (concat "\"" org-log-note-state "\"")
12890 ""))
12891 (cons "%S" (if org-log-note-previous-state
12892 (concat "\"" org-log-note-previous-state "\"")
12893 "\"\"")))))
12894 (if lines (setq note (concat note " \\\\")))
12895 (push note lines))
12896 (when (or current-prefix-arg org-note-abort)
12897 (when org-log-into-drawer
12898 (org-remove-empty-drawer-at
12899 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12900 org-log-note-marker))
12901 (setq lines nil))
12902 (when lines
12903 (with-current-buffer (marker-buffer org-log-note-marker)
12904 (save-excursion
12905 (goto-char org-log-note-marker)
12906 (move-marker org-log-note-marker nil)
12907 (end-of-line 1)
12908 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12909 (setq ind (save-excursion
12910 (if (ignore-errors (goto-char (org-in-item-p)))
12911 (let ((struct (org-list-struct)))
12912 (org-list-get-ind
12913 (org-list-get-top-point struct) struct))
12914 (skip-chars-backward " \r\t\n")
12915 (cond
12916 ((and (org-at-heading-p)
12917 org-adapt-indentation)
12918 (1+ (org-current-level)))
12919 ((org-at-heading-p) 0)
12920 (t (org-get-indentation))))))
12921 (setq bul (org-list-bullet-string "-"))
12922 (org-indent-line-to ind)
12923 (insert bul (pop lines))
12924 (let ((ind-body (+ (length bul) ind)))
12925 (while lines
12926 (insert "\n")
12927 (org-indent-line-to ind-body)
12928 (insert (pop lines))))
12929 (message "Note stored")
12930 (org-back-to-heading t)
12931 (org-cycle-hide-drawers 'children))))))
12932 (set-window-configuration org-log-note-window-configuration)
12933 (with-current-buffer (marker-buffer org-log-note-return-to)
12934 (goto-char org-log-note-return-to))
12935 (move-marker org-log-note-return-to nil)
12936 (and org-log-post-message (message "%s" org-log-post-message)))
12938 (defun org-remove-empty-drawer-at (drawer pos)
12939 "Remove an empty drawer DRAWER at position POS.
12940 POS may also be a marker."
12941 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12942 (save-excursion
12943 (save-restriction
12944 (widen)
12945 (goto-char pos)
12946 (if (org-in-regexp
12947 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12948 (replace-match ""))))))
12950 (defvar org-ts-type nil)
12951 (defun org-sparse-tree (&optional arg type)
12952 "Create a sparse tree, prompt for the details.
12953 This command can create sparse trees. You first need to select the type
12954 of match used to create the tree:
12956 t Show all TODO entries.
12957 T Show entries with a specific TODO keyword.
12958 m Show entries selected by a tags/property match.
12959 p Enter a property name and its value (both with completion on existing
12960 names/values) and show entries with that property.
12961 r Show entries matching a regular expression (`/' can be used as well).
12962 b Show deadlines and scheduled items before a date.
12963 a Show deadlines and scheduled items after a date.
12964 d Show deadlines due within `org-deadline-warning-days'.
12965 D Show deadlines and scheduled items between a date range."
12966 (interactive "P")
12967 (let (ans kwd value ts-type)
12968 (setq type (or type org-sparse-tree-default-date-type))
12969 (setq org-ts-type type)
12970 (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"
12971 (cond ((eq type 'all) "all timestamps")
12972 ((eq type 'scheduled) "only scheduled")
12973 ((eq type 'deadline) "only deadline")
12974 ((eq type 'active) "only active timestamps")
12975 ((eq type 'inactive) "only inactive timestamps")
12976 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12977 (t "scheduled/deadline")))
12978 (setq ans (read-char-exclusive))
12979 (cond
12980 ((equal ans ?c)
12981 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12982 ((equal ans ?d)
12983 (call-interactively 'org-check-deadlines))
12984 ((equal ans ?b)
12985 (call-interactively 'org-check-before-date))
12986 ((equal ans ?a)
12987 (call-interactively 'org-check-after-date))
12988 ((equal ans ?D)
12989 (call-interactively 'org-check-dates-range))
12990 ((equal ans ?t)
12991 (call-interactively 'org-show-todo-tree))
12992 ((equal ans ?T)
12993 (org-show-todo-tree '(4)))
12994 ((member ans '(?T ?m))
12995 (call-interactively 'org-match-sparse-tree))
12996 ((member ans '(?p ?P))
12997 (setq kwd (org-icompleting-read "Property: "
12998 (mapcar 'list (org-buffer-property-keys))))
12999 (setq value (org-icompleting-read "Value: "
13000 (mapcar 'list (org-property-values kwd))))
13001 (unless (string-match "\\`{.*}\\'" value)
13002 (setq value (concat "\"" value "\"")))
13003 (org-match-sparse-tree arg (concat kwd "=" value)))
13004 ((member ans '(?r ?R ?/))
13005 (call-interactively 'org-occur))
13006 (t (error "No such sparse tree command \"%c\"" ans)))))
13008 (defvar org-occur-highlights nil
13009 "List of overlays used for occur matches.")
13010 (make-variable-buffer-local 'org-occur-highlights)
13011 (defvar org-occur-parameters nil
13012 "Parameters of the active org-occur calls.
13013 This is a list, each call to org-occur pushes as cons cell,
13014 containing the regular expression and the callback, onto the list.
13015 The list can contain several entries if `org-occur' has been called
13016 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13017 will only contain one set of parameters. When the highlights are
13018 removed (for example with `C-c C-c', or with the next edit (depending
13019 on `org-remove-highlights-with-change'), this variable is emptied
13020 as well.")
13021 (make-variable-buffer-local 'org-occur-parameters)
13023 (defun org-occur (regexp &optional keep-previous callback)
13024 "Make a compact tree which shows all matches of REGEXP.
13025 The tree will show the lines where the regexp matches, and all higher
13026 headlines above the match. It will also show the heading after the match,
13027 to make sure editing the matching entry is easy.
13028 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13029 call to `org-occur' will be kept, to allow stacking of calls to this
13030 command.
13031 If CALLBACK is non-nil, it is a function which is called to confirm
13032 that the match should indeed be shown."
13033 (interactive "sRegexp: \nP")
13034 (when (equal regexp "")
13035 (error "Regexp cannot be empty"))
13036 (unless keep-previous
13037 (org-remove-occur-highlights nil nil t))
13038 (push (cons regexp callback) org-occur-parameters)
13039 (let ((cnt 0))
13040 (save-excursion
13041 (goto-char (point-min))
13042 (if (or (not keep-previous) ; do not want to keep
13043 (not org-occur-highlights)) ; no previous matches
13044 ;; hide everything
13045 (org-overview))
13046 (while (re-search-forward regexp nil t)
13047 (when (or (not callback)
13048 (save-match-data (funcall callback)))
13049 (setq cnt (1+ cnt))
13050 (when org-highlight-sparse-tree-matches
13051 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13052 (org-show-context 'occur-tree))))
13053 (when org-remove-highlights-with-change
13054 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13055 nil 'local))
13056 (unless org-sparse-tree-open-archived-trees
13057 (org-hide-archived-subtrees (point-min) (point-max)))
13058 (run-hooks 'org-occur-hook)
13059 (if (org-called-interactively-p 'interactive)
13060 (message "%d match(es) for regexp %s" cnt regexp))
13061 cnt))
13063 (defun org-occur-next-match (&optional n reset)
13064 "Function for `next-error-function' to find sparse tree matches.
13065 N is the number of matches to move, when negative move backwards.
13066 RESET is entirely ignored - this function always goes back to the
13067 starting point when no match is found."
13068 (let* ((limit (if (< n 0) (point-min) (point-max)))
13069 (search-func (if (< n 0)
13070 'previous-single-char-property-change
13071 'next-single-char-property-change))
13072 (n (abs n))
13073 (pos (point))
13075 (catch 'exit
13076 (while (setq p1 (funcall search-func (point) 'org-type))
13077 (when (equal p1 limit)
13078 (goto-char pos)
13079 (error "No more matches"))
13080 (when (equal (get-char-property p1 'org-type) 'org-occur)
13081 (setq n (1- n))
13082 (when (= n 0)
13083 (goto-char p1)
13084 (throw 'exit (point))))
13085 (goto-char p1))
13086 (goto-char p1)
13087 (error "No more matches"))))
13089 (defun org-show-context (&optional key)
13090 "Make sure point and context are visible.
13091 How much context is shown depends upon the variables
13092 `org-show-hierarchy-above', `org-show-following-heading',
13093 `org-show-entry-below' and `org-show-siblings'."
13094 (let ((heading-p (org-at-heading-p t))
13095 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13096 (following-p (org-get-alist-option org-show-following-heading key))
13097 (entry-p (org-get-alist-option org-show-entry-below key))
13098 (siblings-p (org-get-alist-option org-show-siblings key)))
13099 (catch 'exit
13100 ;; Show heading or entry text
13101 (if (and heading-p (not entry-p))
13102 (org-flag-heading nil) ; only show the heading
13103 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13104 (org-show-hidden-entry))) ; show entire entry
13105 (when following-p
13106 ;; Show next sibling, or heading below text
13107 (save-excursion
13108 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13109 (org-flag-heading nil))))
13110 (when siblings-p (org-show-siblings))
13111 (when hierarchy-p
13112 ;; show all higher headings, possibly with siblings
13113 (save-excursion
13114 (while (and (condition-case nil
13115 (progn (org-up-heading-all 1) t)
13116 (error nil))
13117 (not (bobp)))
13118 (org-flag-heading nil)
13119 (when siblings-p (org-show-siblings))))))))
13121 (defvar org-reveal-start-hook nil
13122 "Hook run before revealing a location.")
13124 (defun org-reveal (&optional siblings)
13125 "Show current entry, hierarchy above it, and the following headline.
13126 This can be used to show a consistent set of context around locations
13127 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13128 not t for the search context.
13130 With optional argument SIBLINGS, on each level of the hierarchy all
13131 siblings are shown. This repairs the tree structure to what it would
13132 look like when opened with hierarchical calls to `org-cycle'.
13133 With double optional argument \\[universal-argument] \\[universal-argument], \
13134 go to the parent and show the
13135 entire tree."
13136 (interactive "P")
13137 (run-hooks 'org-reveal-start-hook)
13138 (let ((org-show-hierarchy-above t)
13139 (org-show-following-heading t)
13140 (org-show-siblings (if siblings t org-show-siblings)))
13141 (org-show-context nil))
13142 (when (equal siblings '(16))
13143 (save-excursion
13144 (when (org-up-heading-safe)
13145 (org-show-subtree)
13146 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13148 (defun org-highlight-new-match (beg end)
13149 "Highlight from BEG to END and mark the highlight is an occur headline."
13150 (let ((ov (make-overlay beg end)))
13151 (overlay-put ov 'face 'secondary-selection)
13152 (overlay-put ov 'org-type 'org-occur)
13153 (push ov org-occur-highlights)))
13155 (defun org-remove-occur-highlights (&optional beg end noremove)
13156 "Remove the occur highlights from the buffer.
13157 BEG and END are ignored. If NOREMOVE is nil, remove this function
13158 from the `before-change-functions' in the current buffer."
13159 (interactive)
13160 (unless org-inhibit-highlight-removal
13161 (mapc 'delete-overlay org-occur-highlights)
13162 (setq org-occur-highlights nil)
13163 (setq org-occur-parameters nil)
13164 (unless noremove
13165 (remove-hook 'before-change-functions
13166 'org-remove-occur-highlights 'local))))
13168 ;;;; Priorities
13170 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13171 "Regular expression matching the priority indicator.")
13173 (defvar org-remove-priority-next-time nil)
13175 (defun org-priority-up ()
13176 "Increase the priority of the current item."
13177 (interactive)
13178 (org-priority 'up))
13180 (defun org-priority-down ()
13181 "Decrease the priority of the current item."
13182 (interactive)
13183 (org-priority 'down))
13185 (defun org-priority (&optional action show)
13186 "Change the priority of an item.
13187 ACTION can be `set', `up', `down', or a character."
13188 (interactive "P")
13189 (if (equal action '(4))
13190 (org-show-priority)
13191 (unless org-enable-priority-commands
13192 (error "Priority commands are disabled"))
13193 (setq action (or action 'set))
13194 (let (current new news have remove)
13195 (save-excursion
13196 (org-back-to-heading t)
13197 (if (looking-at org-priority-regexp)
13198 (setq current (string-to-char (match-string 2))
13199 have t))
13200 (cond
13201 ((eq action 'remove)
13202 (setq remove t new ?\ ))
13203 ((or (eq action 'set)
13204 (if (featurep 'xemacs) (characterp action) (integerp action)))
13205 (if (not (eq action 'set))
13206 (setq new action)
13207 (message "Priority %c-%c, SPC to remove: "
13208 org-highest-priority org-lowest-priority)
13209 (save-match-data
13210 (setq new (read-char-exclusive))))
13211 (if (and (= (upcase org-highest-priority) org-highest-priority)
13212 (= (upcase org-lowest-priority) org-lowest-priority))
13213 (setq new (upcase new)))
13214 (cond ((equal new ?\ ) (setq remove t))
13215 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13216 (error "Priority must be between `%c' and `%c'"
13217 org-highest-priority org-lowest-priority))))
13218 ((eq action 'up)
13219 (setq new (if have
13220 (1- current) ; normal cycling
13221 ;; last priority was empty
13222 (if (eq last-command this-command)
13223 org-lowest-priority ; wrap around empty to lowest
13224 ;; default
13225 (if org-priority-start-cycle-with-default
13226 org-default-priority
13227 (1- org-default-priority))))))
13228 ((eq action 'down)
13229 (setq new (if have
13230 (1+ current) ; normal cycling
13231 ;; last priority was empty
13232 (if (eq last-command this-command)
13233 org-highest-priority ; wrap around empty to highest
13234 ;; default
13235 (if org-priority-start-cycle-with-default
13236 org-default-priority
13237 (1+ org-default-priority))))))
13238 (t (error "Invalid action")))
13239 (if (or (< (upcase new) org-highest-priority)
13240 (> (upcase new) org-lowest-priority))
13241 (if (and (memq action '(up down))
13242 (not have) (not (eq last-command this-command)))
13243 ;; `new' is from default priority
13244 (error
13245 "The default can not be set, see `org-default-priority' why")
13246 ;; normal cycling: `new' is beyond highest/lowest priority
13247 ;; and is wrapped around to the empty priority
13248 (setq remove t)))
13249 (setq news (format "%c" new))
13250 (if have
13251 (if remove
13252 (replace-match "" t t nil 1)
13253 (replace-match news t t nil 2))
13254 (if remove
13255 (error "No priority cookie found in line")
13256 (let ((case-fold-search nil))
13257 (looking-at org-todo-line-regexp))
13258 (if (match-end 2)
13259 (progn
13260 (goto-char (match-end 2))
13261 (insert " [#" news "]"))
13262 (goto-char (match-beginning 3))
13263 (insert "[#" news "] "))))
13264 (org-preserve-lc (org-set-tags nil 'align)))
13265 (if remove
13266 (message "Priority removed")
13267 (message "Priority of current item set to %s" news)))))
13269 (defun org-show-priority ()
13270 "Show the priority of the current item.
13271 This priority is composed of the main priority given with the [#A] cookies,
13272 and by additional input from the age of a schedules or deadline entry."
13273 (interactive)
13274 (let ((pri (if (eq major-mode 'org-agenda-mode)
13275 (org-get-at-bol 'priority)
13276 (save-excursion
13277 (save-match-data
13278 (beginning-of-line)
13279 (and (looking-at org-heading-regexp)
13280 (org-get-priority (match-string 0))))))))
13281 (message "Priority is %d" (if pri pri -1000))))
13283 (defun org-get-priority (s)
13284 "Find priority cookie and return priority."
13285 (save-match-data
13286 (if (functionp org-get-priority-function)
13287 (funcall org-get-priority-function)
13288 (if (not (string-match org-priority-regexp s))
13289 (* 1000 (- org-lowest-priority org-default-priority))
13290 (* 1000 (- org-lowest-priority
13291 (string-to-char (match-string 2 s))))))))
13293 ;;;; Tags
13295 (defvar org-agenda-archives-mode)
13296 (defvar org-map-continue-from nil
13297 "Position from where mapping should continue.
13298 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13300 (defvar org-scanner-tags nil
13301 "The current tag list while the tags scanner is running.")
13302 (defvar org-trust-scanner-tags nil
13303 "Should `org-get-tags-at' use the tags for the scanner.
13304 This is for internal dynamical scoping only.
13305 When this is non-nil, the function `org-get-tags-at' will return the value
13306 of `org-scanner-tags' instead of building the list by itself. This
13307 can lead to large speed-ups when the tags scanner is used in a file with
13308 many entries, and when the list of tags is retrieved, for example to
13309 obtain a list of properties. Building the tags list for each entry in such
13310 a file becomes an N^2 operation - but with this variable set, it scales
13311 as N.")
13313 (defun org-scan-tags (action matcher todo-only &optional start-level)
13314 "Scan headline tags with inheritance and produce output ACTION.
13316 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13317 or `agenda' to produce an entry list for an agenda view. It can also be
13318 a Lisp form or a function that should be called at each matched headline, in
13319 this case the return value is a list of all return values from these calls.
13321 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13322 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13323 only lines with a not-done TODO keyword are included in the output.
13324 This should be the same variable that was scoped into
13325 and set by `org-make-tags-matcher' when it constructed MATCHER.
13327 START-LEVEL can be a string with asterisks, reducing the scope to
13328 headlines matching this string."
13329 (require 'org-agenda)
13330 (let* ((re (concat "^"
13331 (if start-level
13332 ;; Get the correct level to match
13333 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13334 org-outline-regexp)
13335 " *\\(\\<\\("
13336 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13337 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13338 (props (list 'face 'default
13339 'done-face 'org-agenda-done
13340 'undone-face 'default
13341 'mouse-face 'highlight
13342 'org-not-done-regexp org-not-done-regexp
13343 'org-todo-regexp org-todo-regexp
13344 'org-complex-heading-regexp org-complex-heading-regexp
13345 'help-echo
13346 (format "mouse-2 or RET jump to org file %s"
13347 (abbreviate-file-name
13348 (or (buffer-file-name (buffer-base-buffer))
13349 (buffer-name (buffer-base-buffer)))))))
13350 (case-fold-search nil)
13351 (org-map-continue-from nil)
13352 lspos tags tags-list
13353 (tags-alist (list (cons 0 org-file-tags)))
13354 (llast 0) rtn rtn1 level category i txt
13355 todo marker entry priority)
13356 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13357 (setq action (list 'lambda nil action)))
13358 (save-excursion
13359 (goto-char (point-min))
13360 (when (eq action 'sparse-tree)
13361 (org-overview)
13362 (org-remove-occur-highlights))
13363 (while (re-search-forward re nil t)
13364 (setq org-map-continue-from nil)
13365 (catch :skip
13366 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13367 tags (if (match-end 4) (org-match-string-no-properties 4)))
13368 (goto-char (setq lspos (match-beginning 0)))
13369 (setq level (org-reduced-level (org-outline-level))
13370 category (org-get-category))
13371 (setq i llast llast level)
13372 ;; remove tag lists from same and sublevels
13373 (while (>= i level)
13374 (when (setq entry (assoc i tags-alist))
13375 (setq tags-alist (delete entry tags-alist)))
13376 (setq i (1- i)))
13377 ;; add the next tags
13378 (when tags
13379 (setq tags (org-split-string tags ":")
13380 tags-alist
13381 (cons (cons level tags) tags-alist)))
13382 ;; compile tags for current headline
13383 (setq tags-list
13384 (if org-use-tag-inheritance
13385 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13386 tags)
13387 org-scanner-tags tags-list)
13388 (when org-use-tag-inheritance
13389 (setcdr (car tags-alist)
13390 (mapcar (lambda (x)
13391 (setq x (copy-sequence x))
13392 (org-add-prop-inherited x))
13393 (cdar tags-alist))))
13394 (when (and tags org-use-tag-inheritance
13395 (or (not (eq t org-use-tag-inheritance))
13396 org-tags-exclude-from-inheritance))
13397 ;; selective inheritance, remove uninherited ones
13398 (setcdr (car tags-alist)
13399 (org-remove-uninherited-tags (cdar tags-alist))))
13400 (when (and
13402 ;; eval matcher only when the todo condition is OK
13403 (and (or (not todo-only) (member todo org-not-done-keywords))
13404 (let ((case-fold-search t) (org-trust-scanner-tags t))
13405 (eval matcher)))
13407 ;; Call the skipper, but return t if it does not skip,
13408 ;; so that the `and' form continues evaluating
13409 (progn
13410 (unless (eq action 'sparse-tree) (org-agenda-skip))
13413 ;; Check if timestamps are deselecting this entry
13414 (or (not todo-only)
13415 (and (member todo org-not-done-keywords)
13416 (or (not org-agenda-tags-todo-honor-ignore-options)
13417 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13419 ;; select this headline
13420 (cond
13421 ((eq action 'sparse-tree)
13422 (and org-highlight-sparse-tree-matches
13423 (org-get-heading) (match-end 0)
13424 (org-highlight-new-match
13425 (match-beginning 1) (match-end 1)))
13426 (org-show-context 'tags-tree))
13427 ((eq action 'agenda)
13428 (setq txt (org-agenda-format-item
13430 (concat
13431 (if (eq org-tags-match-list-sublevels 'indented)
13432 (make-string (1- level) ?.) "")
13433 (org-get-heading))
13434 level category
13435 tags-list)
13436 priority (org-get-priority txt))
13437 (goto-char lspos)
13438 (setq marker (org-agenda-new-marker))
13439 (org-add-props txt props
13440 'org-marker marker 'org-hd-marker marker 'org-category category
13441 'todo-state todo
13442 'priority priority 'type "tagsmatch")
13443 (push txt rtn))
13444 ((functionp action)
13445 (setq org-map-continue-from nil)
13446 (save-excursion
13447 (setq rtn1 (funcall action))
13448 (push rtn1 rtn)))
13449 (t (error "Invalid action")))
13451 ;; if we are to skip sublevels, jump to end of subtree
13452 (unless org-tags-match-list-sublevels
13453 (org-end-of-subtree t)
13454 (backward-char 1))))
13455 ;; Get the correct position from where to continue
13456 (if org-map-continue-from
13457 (goto-char org-map-continue-from)
13458 (and (= (point) lspos) (end-of-line 1)))))
13459 (when (and (eq action 'sparse-tree)
13460 (not org-sparse-tree-open-archived-trees))
13461 (org-hide-archived-subtrees (point-min) (point-max)))
13462 (nreverse rtn)))
13464 (defun org-remove-uninherited-tags (tags)
13465 "Remove all tags that are not inherited from the list TAGS."
13466 (cond
13467 ((eq org-use-tag-inheritance t)
13468 (if org-tags-exclude-from-inheritance
13469 (org-delete-all org-tags-exclude-from-inheritance tags)
13470 tags))
13471 ((not org-use-tag-inheritance) nil)
13472 ((stringp org-use-tag-inheritance)
13473 (delq nil (mapcar
13474 (lambda (x)
13475 (if (and (string-match org-use-tag-inheritance x)
13476 (not (member x org-tags-exclude-from-inheritance)))
13477 x nil))
13478 tags)))
13479 ((listp org-use-tag-inheritance)
13480 (delq nil (mapcar
13481 (lambda (x)
13482 (if (member x org-use-tag-inheritance) x nil))
13483 tags)))))
13485 (defun org-match-sparse-tree (&optional todo-only match)
13486 "Create a sparse tree according to tags string MATCH.
13487 MATCH can contain positive and negative selection of tags, like
13488 \"+WORK+URGENT-WITHBOSS\".
13489 If optional argument TODO-ONLY is non-nil, only select lines that are
13490 also TODO lines."
13491 (interactive "P")
13492 (org-agenda-prepare-buffers (list (current-buffer)))
13493 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13495 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13497 (defvar org-cached-props nil)
13498 (defun org-cached-entry-get (pom property)
13499 (if (or (eq t org-use-property-inheritance)
13500 (and (stringp org-use-property-inheritance)
13501 (string-match org-use-property-inheritance property))
13502 (and (listp org-use-property-inheritance)
13503 (member property org-use-property-inheritance)))
13504 ;; Caching is not possible, check it directly
13505 (org-entry-get pom property 'inherit)
13506 ;; Get all properties, so that we can do complicated checks easily
13507 (cdr (assoc property (or org-cached-props
13508 (setq org-cached-props
13509 (org-entry-properties pom)))))))
13511 (defun org-global-tags-completion-table (&optional files)
13512 "Return the list of all tags in all agenda buffer/files.
13513 Optional FILES argument is a list of files which can be used
13514 instead of the agenda files."
13515 (save-excursion
13516 (org-uniquify
13517 (delq nil
13518 (apply 'append
13519 (mapcar
13520 (lambda (file)
13521 (set-buffer (find-file-noselect file))
13522 (append (org-get-buffer-tags)
13523 (mapcar (lambda (x) (if (stringp (car-safe x))
13524 (list (car-safe x)) nil))
13525 org-tag-alist)))
13526 (if (and files (car files))
13527 files
13528 (org-agenda-files))))))))
13530 (defun org-make-tags-matcher (match)
13531 "Create the TAGS/TODO matcher form for the selection string MATCH.
13533 The variable `todo-only' is scoped dynamically into this function.
13534 It will be set to t if the matcher restricts matching to TODO entries,
13535 otherwise will not be touched.
13537 Returns a cons of the selection string MATCH and the constructed
13538 lisp form implementing the matcher. The matcher is to be evaluated
13539 at an Org entry, with point on the headline, and returns t if the
13540 entry matches the selection string MATCH. The returned lisp form
13541 references two variables with information about the entry, which
13542 must be bound around the form's evaluation: todo, the TODO keyword
13543 at the entry (or nil of none); and tags-list, the list of all tags
13544 at the entry including inherited ones. Additionally, the category
13545 of the entry (if any) must be specified as the text property
13546 'org-category on the headline.
13548 See also `org-scan-tags'.
13550 (declare (special todo-only))
13551 (unless (boundp 'todo-only)
13552 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13553 (unless match
13554 ;; Get a new match request, with completion
13555 (let ((org-last-tags-completion-table
13556 (org-global-tags-completion-table)))
13557 (setq match (org-completing-read-no-i
13558 "Match: " 'org-tags-completion-function nil nil nil
13559 'org-tags-history))))
13561 ;; Parse the string and create a lisp form
13562 (let ((match0 match)
13563 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13564 minus tag mm
13565 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13566 orterms term orlist re-p str-p level-p level-op time-p
13567 prop-p pn pv po gv rest)
13568 (if (string-match "/+" match)
13569 ;; match contains also a todo-matching request
13570 (progn
13571 (setq tagsmatch (substring match 0 (match-beginning 0))
13572 todomatch (substring match (match-end 0)))
13573 (if (string-match "^!" todomatch)
13574 (setq todo-only t todomatch (substring todomatch 1)))
13575 (if (string-match "^\\s-*$" todomatch)
13576 (setq todomatch nil)))
13577 ;; only matching tags
13578 (setq tagsmatch match todomatch nil))
13580 ;; Make the tags matcher
13581 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13582 (setq tagsmatcher t)
13583 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13584 (while (setq term (pop orterms))
13585 (while (and (equal (substring term -1) "\\") orterms)
13586 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13587 (while (string-match re term)
13588 (setq rest (substring term (match-end 0))
13589 minus (and (match-end 1)
13590 (equal (match-string 1 term) "-"))
13591 tag (save-match-data (replace-regexp-in-string
13592 "\\\\-" "-"
13593 (match-string 2 term)))
13594 re-p (equal (string-to-char tag) ?{)
13595 level-p (match-end 4)
13596 prop-p (match-end 5)
13597 mm (cond
13598 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13599 (level-p
13600 (setq level-op (org-op-to-function (match-string 3 term)))
13601 `(,level-op level ,(string-to-number
13602 (match-string 4 term))))
13603 (prop-p
13604 (setq pn (match-string 5 term)
13605 po (match-string 6 term)
13606 pv (match-string 7 term)
13607 re-p (equal (string-to-char pv) ?{)
13608 str-p (equal (string-to-char pv) ?\")
13609 time-p (save-match-data
13610 (string-match "^\"[[<].*[]>]\"$" pv))
13611 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13612 (if time-p (setq pv (org-matcher-time pv)))
13613 (setq po (org-op-to-function po (if time-p 'time str-p)))
13614 (cond
13615 ((equal pn "CATEGORY")
13616 (setq gv '(get-text-property (point) 'org-category)))
13617 ((equal pn "TODO")
13618 (setq gv 'todo))
13620 (setq gv `(org-cached-entry-get nil ,pn))))
13621 (if re-p
13622 (if (eq po 'org<>)
13623 `(not (string-match ,pv (or ,gv "")))
13624 `(string-match ,pv (or ,gv "")))
13625 (if str-p
13626 `(,po (or ,gv "") ,pv)
13627 `(,po (string-to-number (or ,gv ""))
13628 ,(string-to-number pv) ))))
13629 (t `(member ,tag tags-list)))
13630 mm (if minus (list 'not mm) mm)
13631 term rest)
13632 (push mm tagsmatcher))
13633 (push (if (> (length tagsmatcher) 1)
13634 (cons 'and tagsmatcher)
13635 (car tagsmatcher))
13636 orlist)
13637 (setq tagsmatcher nil))
13638 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13639 (setq tagsmatcher
13640 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13641 ;; Make the todo matcher
13642 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13643 (setq todomatcher t)
13644 (setq orterms (org-split-string todomatch "|") orlist nil)
13645 (while (setq term (pop orterms))
13646 (while (string-match re term)
13647 (setq minus (and (match-end 1)
13648 (equal (match-string 1 term) "-"))
13649 kwd (match-string 2 term)
13650 re-p (equal (string-to-char kwd) ?{)
13651 term (substring term (match-end 0))
13652 mm (if re-p
13653 `(string-match ,(substring kwd 1 -1) todo)
13654 (list 'equal 'todo kwd))
13655 mm (if minus (list 'not mm) mm))
13656 (push mm todomatcher))
13657 (push (if (> (length todomatcher) 1)
13658 (cons 'and todomatcher)
13659 (car todomatcher))
13660 orlist)
13661 (setq todomatcher nil))
13662 (setq todomatcher (if (> (length orlist) 1)
13663 (cons 'or orlist) (car orlist))))
13665 ;; Return the string and lisp forms of the matcher
13666 (setq matcher (if todomatcher
13667 (list 'and tagsmatcher todomatcher)
13668 tagsmatcher))
13669 (when todo-only
13670 (setq matcher (list 'and '(member todo org-not-done-keywords)
13671 matcher)))
13672 (cons match0 matcher)))
13674 (defun org-op-to-function (op &optional stringp)
13675 "Turn an operator into the appropriate function."
13676 (setq op
13677 (cond
13678 ((equal op "<" ) '(< string< org-time<))
13679 ((equal op ">" ) '(> org-string> org-time>))
13680 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13681 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13682 ((member op '("=" "==")) '(= string= org-time=))
13683 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13684 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13686 (defun org<> (a b) (not (= a b)))
13687 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13688 (defun org-string>= (a b) (not (string< a b)))
13689 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13690 (defun org-string<> (a b) (not (string= a b)))
13691 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13692 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13693 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13694 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13695 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13696 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13697 (defun org-2ft (s)
13698 "Convert S to a floating point time.
13699 If S is already a number, just return it. If it is a string, parse
13700 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13701 (cond
13702 ((numberp s) s)
13703 ((stringp s)
13704 (condition-case nil
13705 (float-time (apply 'encode-time (org-parse-time-string s)))
13706 (error 0.)))
13707 (t 0.)))
13709 (defun org-time-today ()
13710 "Time in seconds today at 0:00.
13711 Returns the float number of seconds since the beginning of the
13712 epoch to the beginning of today (00:00)."
13713 (float-time (apply 'encode-time
13714 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13716 (defun org-matcher-time (s)
13717 "Interpret a time comparison value."
13718 (save-match-data
13719 (cond
13720 ((string= s "<now>") (float-time))
13721 ((string= s "<today>") (org-time-today))
13722 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13723 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13724 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13725 (+ (org-time-today)
13726 (* (string-to-number (match-string 1 s))
13727 (cdr (assoc (match-string 2 s)
13728 '(("d" . 86400.0) ("w" . 604800.0)
13729 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13730 (t (org-2ft s)))))
13732 (defun org-match-any-p (re list)
13733 "Does re match any element of list?"
13734 (setq list (mapcar (lambda (x) (string-match re x)) list))
13735 (delq nil list))
13737 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13738 (defvar org-tags-overlay (make-overlay 1 1))
13739 (org-detach-overlay org-tags-overlay)
13741 (defun org-get-local-tags-at (&optional pos)
13742 "Get a list of tags defined in the current headline."
13743 (org-get-tags-at pos 'local))
13745 (defun org-get-local-tags ()
13746 "Get a list of tags defined in the current headline."
13747 (org-get-tags-at nil 'local))
13749 (defun org-get-tags-at (&optional pos local)
13750 "Get a list of all headline tags applicable at POS.
13751 POS defaults to point. If tags are inherited, the list contains
13752 the targets in the same sequence as the headlines appear, i.e.
13753 the tags of the current headline come last.
13754 When LOCAL is non-nil, only return tags from the current headline,
13755 ignore inherited ones."
13756 (interactive)
13757 (if (and org-trust-scanner-tags
13758 (or (not pos) (equal pos (point)))
13759 (not local))
13760 org-scanner-tags
13761 (let (tags ltags lastpos parent)
13762 (save-excursion
13763 (save-restriction
13764 (widen)
13765 (goto-char (or pos (point)))
13766 (save-match-data
13767 (catch 'done
13768 (condition-case nil
13769 (progn
13770 (org-back-to-heading t)
13771 (while (not (equal lastpos (point)))
13772 (setq lastpos (point))
13773 (when (looking-at
13774 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13775 (setq ltags (org-split-string
13776 (org-match-string-no-properties 1) ":"))
13777 (when parent
13778 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13779 (setq tags (append
13780 (if parent
13781 (org-remove-uninherited-tags ltags)
13782 ltags)
13783 tags)))
13784 (or org-use-tag-inheritance (throw 'done t))
13785 (if local (throw 'done t))
13786 (or (org-up-heading-safe) (error nil))
13787 (setq parent t)))
13788 (error nil)))))
13789 (if local
13790 tags
13791 (reverse (delete-dups
13792 (reverse (append
13793 (org-remove-uninherited-tags
13794 org-file-tags) tags)))))))))
13796 (defun org-add-prop-inherited (s)
13797 (add-text-properties 0 (length s) '(inherited t) s)
13800 (defun org-toggle-tag (tag &optional onoff)
13801 "Toggle the tag TAG for the current line.
13802 If ONOFF is `on' or `off', don't toggle but set to this state."
13803 (let (res current)
13804 (save-excursion
13805 (org-back-to-heading t)
13806 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13807 (point-at-eol) t)
13808 (progn
13809 (setq current (match-string 1))
13810 (replace-match ""))
13811 (setq current ""))
13812 (setq current (nreverse (org-split-string current ":")))
13813 (cond
13814 ((eq onoff 'on)
13815 (setq res t)
13816 (or (member tag current) (push tag current)))
13817 ((eq onoff 'off)
13818 (or (not (member tag current)) (setq current (delete tag current))))
13819 (t (if (member tag current)
13820 (setq current (delete tag current))
13821 (setq res t)
13822 (push tag current))))
13823 (end-of-line 1)
13824 (if current
13825 (progn
13826 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13827 (org-set-tags nil t))
13828 (delete-horizontal-space))
13829 (run-hooks 'org-after-tags-change-hook))
13830 res))
13832 (defun org-align-tags-here (to-col)
13833 ;; Assumes that this is a headline
13834 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13835 (beginning-of-line 1)
13836 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13837 (< pos (match-beginning 2)))
13838 (progn
13839 (setq tags-l (- (match-end 2) (match-beginning 2)))
13840 (goto-char (match-beginning 1))
13841 (insert " ")
13842 (delete-region (point) (1+ (match-beginning 2)))
13843 (setq ncol (max (current-column)
13844 (1+ col)
13845 (if (> to-col 0)
13846 to-col
13847 (- (abs to-col) tags-l))))
13848 (setq p (point))
13849 (insert (make-string (- ncol (current-column)) ?\ ))
13850 (setq ncol (current-column))
13851 (when indent-tabs-mode (tabify p (point-at-eol)))
13852 (org-move-to-column (min ncol col) t))
13853 (goto-char pos))))
13855 (defun org-set-tags-command (&optional arg just-align)
13856 "Call the set-tags command for the current entry."
13857 (interactive "P")
13858 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13859 (org-set-tags arg just-align)
13860 (save-excursion
13861 (org-back-to-heading t)
13862 (org-set-tags arg just-align))))
13864 (defun org-set-tags-to (data)
13865 "Set the tags of the current entry to DATA, replacing the current tags.
13866 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13867 If DATA is nil or the empty string, any tags will be removed."
13868 (interactive "sTags: ")
13869 (setq data
13870 (cond
13871 ((eq data nil) "")
13872 ((equal data "") "")
13873 ((stringp data)
13874 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13875 ":"))
13876 ((listp data)
13877 (concat ":" (mapconcat 'identity data ":") ":"))))
13878 (when data
13879 (save-excursion
13880 (org-back-to-heading t)
13881 (when (looking-at org-complex-heading-regexp)
13882 (if (match-end 5)
13883 (progn
13884 (goto-char (match-beginning 5))
13885 (insert data)
13886 (delete-region (point) (point-at-eol))
13887 (org-set-tags nil 'align))
13888 (goto-char (point-at-eol))
13889 (insert " " data)
13890 (org-set-tags nil 'align)))
13891 (beginning-of-line 1)
13892 (if (looking-at ".*?\\([ \t]+\\)$")
13893 (delete-region (match-beginning 1) (match-end 1))))))
13895 (defun org-align-all-tags ()
13896 "Align the tags i all headings."
13897 (interactive)
13898 (save-excursion
13899 (or (ignore-errors (org-back-to-heading t))
13900 (outline-next-heading))
13901 (if (org-at-heading-p)
13902 (org-set-tags t)
13903 (message "No headings"))))
13905 (defvar org-indent-indentation-per-level)
13906 (defun org-set-tags (&optional arg just-align)
13907 "Set the tags for the current headline.
13908 With prefix ARG, realign all tags in headings in the current buffer."
13909 (interactive "P")
13910 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13911 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13912 'region-start-level 'region))
13913 org-loop-over-headlines-in-active-region)
13914 (org-map-entries
13915 ;; We don't use ARG and JUST-ALIGN here these args are not
13916 ;; useful when looping over headlines
13917 `(org-set-tags)
13918 org-loop-over-headlines-in-active-region
13919 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13920 (let* ((re org-outline-regexp-bol)
13921 (current (unless arg (org-get-tags-string)))
13922 (col (current-column))
13923 (org-setting-tags t)
13924 table current-tags inherited-tags ; computed below when needed
13925 tags p0 c0 c1 rpl di tc level)
13926 (if arg
13927 (save-excursion
13928 (goto-char (point-min))
13929 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13930 (while (re-search-forward re nil t)
13931 (org-set-tags nil t)
13932 (end-of-line 1)))
13933 (message "All tags realigned to column %d" org-tags-column))
13934 (if just-align
13935 (setq tags current)
13936 ;; Get a new set of tags from the user
13937 (save-excursion
13938 (setq table (append org-tag-persistent-alist
13939 (or org-tag-alist (org-get-buffer-tags))
13940 (and
13941 org-complete-tags-always-offer-all-agenda-tags
13942 (org-global-tags-completion-table
13943 (org-agenda-files))))
13944 org-last-tags-completion-table table
13945 current-tags (org-split-string current ":")
13946 inherited-tags (nreverse
13947 (nthcdr (length current-tags)
13948 (nreverse (org-get-tags-at))))
13949 tags
13950 (if (or (eq t org-use-fast-tag-selection)
13951 (and org-use-fast-tag-selection
13952 (delq nil (mapcar 'cdr table))))
13953 (org-fast-tag-selection
13954 current-tags inherited-tags table
13955 (if org-fast-tag-selection-include-todo
13956 org-todo-key-alist))
13957 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13958 (org-trim
13959 (org-icompleting-read "Tags: "
13960 'org-tags-completion-function
13961 nil nil current 'org-tags-history))))))
13962 (while (string-match "[-+&]+" tags)
13963 ;; No boolean logic, just a list
13964 (setq tags (replace-match ":" t t tags))))
13966 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13968 (if org-tags-sort-function
13969 (setq tags (mapconcat 'identity
13970 (sort (org-split-string
13971 tags (org-re "[^[:alnum:]_@#%]+"))
13972 org-tags-sort-function) ":")))
13974 (if (string-match "\\`[\t ]*\\'" tags)
13975 (setq tags "")
13976 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13977 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13979 ;; Insert new tags at the correct column
13980 (beginning-of-line 1)
13981 (setq level (or (and (looking-at org-outline-regexp)
13982 (- (match-end 0) (point) 1))
13984 (cond
13985 ((and (equal current "") (equal tags "")))
13986 ((re-search-forward
13987 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13988 (point-at-eol) t)
13989 (if (equal tags "")
13990 (setq rpl "")
13991 (goto-char (match-beginning 0))
13992 (setq c0 (current-column)
13993 ;; compute offset for the case of org-indent-mode active
13994 di (if org-indent-mode
13995 (* (1- org-indent-indentation-per-level) (1- level))
13997 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13998 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13999 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14000 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14001 (replace-match rpl t t)
14002 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14003 tags)
14004 (t (error "Tags alignment failed")))
14005 (org-move-to-column col)
14006 (unless just-align
14007 (run-hooks 'org-after-tags-change-hook))))))
14009 (defun org-change-tag-in-region (beg end tag off)
14010 "Add or remove TAG for each entry in the region.
14011 This works in the agenda, and also in an org-mode buffer."
14012 (interactive
14013 (list (region-beginning) (region-end)
14014 (let ((org-last-tags-completion-table
14015 (if (derived-mode-p 'org-mode)
14016 (org-get-buffer-tags)
14017 (org-global-tags-completion-table))))
14018 (org-icompleting-read
14019 "Tag: " 'org-tags-completion-function nil nil nil
14020 'org-tags-history))
14021 (progn
14022 (message "[s]et or [r]emove? ")
14023 (equal (read-char-exclusive) ?r))))
14024 (if (fboundp 'deactivate-mark) (deactivate-mark))
14025 (let ((agendap (equal major-mode 'org-agenda-mode))
14026 l1 l2 m buf pos newhead (cnt 0))
14027 (goto-char end)
14028 (setq l2 (1- (org-current-line)))
14029 (goto-char beg)
14030 (setq l1 (org-current-line))
14031 (loop for l from l1 to l2 do
14032 (org-goto-line l)
14033 (setq m (get-text-property (point) 'org-hd-marker))
14034 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14035 (and agendap m))
14036 (setq buf (if agendap (marker-buffer m) (current-buffer))
14037 pos (if agendap m (point)))
14038 (with-current-buffer buf
14039 (save-excursion
14040 (save-restriction
14041 (goto-char pos)
14042 (setq cnt (1+ cnt))
14043 (org-toggle-tag tag (if off 'off 'on))
14044 (setq newhead (org-get-heading)))))
14045 (and agendap (org-agenda-change-all-lines newhead m))))
14046 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14048 (defun org-tags-completion-function (string predicate &optional flag)
14049 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14050 (confirm (lambda (x) (stringp (car x)))))
14051 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14052 (setq s1 (match-string 1 string)
14053 s2 (match-string 2 string))
14054 (setq s1 "" s2 string))
14055 (cond
14056 ((eq flag nil)
14057 ;; try completion
14058 (setq rtn (try-completion s2 ctable confirm))
14059 (if (stringp rtn)
14060 (setq rtn
14061 (concat s1 s2 (substring rtn (length s2))
14062 (if (and org-add-colon-after-tag-completion
14063 (assoc rtn ctable))
14064 ":" ""))))
14065 rtn)
14066 ((eq flag t)
14067 ;; all-completions
14068 (all-completions s2 ctable confirm)
14070 ((eq flag 'lambda)
14071 ;; exact match?
14072 (assoc s2 ctable)))
14075 (defun org-fast-tag-insert (kwd tags face &optional end)
14076 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14077 (insert (format "%-12s" (concat kwd ":"))
14078 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14079 (or end "")))
14081 (defun org-fast-tag-show-exit (flag)
14082 (save-excursion
14083 (org-goto-line 3)
14084 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14085 (replace-match ""))
14086 (when flag
14087 (end-of-line 1)
14088 (org-move-to-column (- (window-width) 19) t)
14089 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14091 (defun org-set-current-tags-overlay (current prefix)
14092 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14093 (if (featurep 'xemacs)
14094 (org-overlay-display org-tags-overlay (concat prefix s)
14095 'secondary-selection)
14096 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14097 (org-overlay-display org-tags-overlay (concat prefix s)))))
14099 (defvar org-last-tag-selection-key nil)
14100 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14101 "Fast tag selection with single keys.
14102 CURRENT is the current list of tags in the headline, INHERITED is the
14103 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14104 possibly with grouping information. TODO-TABLE is a similar table with
14105 TODO keywords, should these have keys assigned to them.
14106 If the keys are nil, a-z are automatically assigned.
14107 Returns the new tags string, or nil to not change the current settings."
14108 (let* ((fulltable (append table todo-table))
14109 (maxlen (apply 'max (mapcar
14110 (lambda (x)
14111 (if (stringp (car x)) (string-width (car x)) 0))
14112 fulltable)))
14113 (buf (current-buffer))
14114 (expert (eq org-fast-tag-selection-single-key 'expert))
14115 (buffer-tags nil)
14116 (fwidth (+ maxlen 3 1 3))
14117 (ncol (/ (- (window-width) 4) fwidth))
14118 (i-face 'org-done)
14119 (c-face 'org-todo)
14120 tg cnt e c char c1 c2 ntable tbl rtn
14121 ov-start ov-end ov-prefix
14122 (exit-after-next org-fast-tag-selection-single-key)
14123 (done-keywords org-done-keywords)
14124 groups ingroup)
14125 (save-excursion
14126 (beginning-of-line 1)
14127 (if (looking-at
14128 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14129 (setq ov-start (match-beginning 1)
14130 ov-end (match-end 1)
14131 ov-prefix "")
14132 (setq ov-start (1- (point-at-eol))
14133 ov-end (1+ ov-start))
14134 (skip-chars-forward "^\n\r")
14135 (setq ov-prefix
14136 (concat
14137 (buffer-substring (1- (point)) (point))
14138 (if (> (current-column) org-tags-column)
14140 (make-string (- org-tags-column (current-column)) ?\ ))))))
14141 (move-overlay org-tags-overlay ov-start ov-end)
14142 (save-window-excursion
14143 (if expert
14144 (set-buffer (get-buffer-create " *Org tags*"))
14145 (delete-other-windows)
14146 (split-window-vertically)
14147 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14148 (erase-buffer)
14149 (org-set-local 'org-done-keywords done-keywords)
14150 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14151 (org-fast-tag-insert "Current" current c-face "\n\n")
14152 (org-fast-tag-show-exit exit-after-next)
14153 (org-set-current-tags-overlay current ov-prefix)
14154 (setq tbl fulltable char ?a cnt 0)
14155 (while (setq e (pop tbl))
14156 (cond
14157 ((equal (car e) :startgroup)
14158 (push '() groups) (setq ingroup t)
14159 (when (not (= cnt 0))
14160 (setq cnt 0)
14161 (insert "\n"))
14162 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14163 ((equal (car e) :endgroup)
14164 (setq ingroup nil cnt 0)
14165 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14166 ((equal e '(:newline))
14167 (when (not (= cnt 0))
14168 (setq cnt 0)
14169 (insert "\n")
14170 (setq e (car tbl))
14171 (while (equal (car tbl) '(:newline))
14172 (insert "\n")
14173 (setq tbl (cdr tbl)))))
14175 (setq tg (copy-sequence (car e)) c2 nil)
14176 (if (cdr e)
14177 (setq c (cdr e))
14178 ;; automatically assign a character.
14179 (setq c1 (string-to-char
14180 (downcase (substring
14181 tg (if (= (string-to-char tg) ?@) 1 0)))))
14182 (if (or (rassoc c1 ntable) (rassoc c1 table))
14183 (while (or (rassoc char ntable) (rassoc char table))
14184 (setq char (1+ char)))
14185 (setq c2 c1))
14186 (setq c (or c2 char)))
14187 (if ingroup (push tg (car groups)))
14188 (setq tg (org-add-props tg nil 'face
14189 (cond
14190 ((not (assoc tg table))
14191 (org-get-todo-face tg))
14192 ((member tg current) c-face)
14193 ((member tg inherited) i-face))))
14194 (if (and (= cnt 0) (not ingroup)) (insert " "))
14195 (insert "[" c "] " tg (make-string
14196 (- fwidth 4 (length tg)) ?\ ))
14197 (push (cons tg c) ntable)
14198 (when (= (setq cnt (1+ cnt)) ncol)
14199 (insert "\n")
14200 (if ingroup (insert " "))
14201 (setq cnt 0)))))
14202 (setq ntable (nreverse ntable))
14203 (insert "\n")
14204 (goto-char (point-min))
14205 (if (not expert) (org-fit-window-to-buffer))
14206 (setq rtn
14207 (catch 'exit
14208 (while t
14209 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14210 (if (not groups) "no " "")
14211 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14212 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14213 (setq org-last-tag-selection-key c)
14214 (cond
14215 ((= c ?\r) (throw 'exit t))
14216 ((= c ?!)
14217 (setq groups (not groups))
14218 (goto-char (point-min))
14219 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14220 ((= c ?\C-c)
14221 (if (not expert)
14222 (org-fast-tag-show-exit
14223 (setq exit-after-next (not exit-after-next)))
14224 (setq expert nil)
14225 (delete-other-windows)
14226 (set-window-buffer (split-window-vertically) " *Org tags*")
14227 (org-switch-to-buffer-other-window " *Org tags*")
14228 (org-fit-window-to-buffer)))
14229 ((or (= c ?\C-g)
14230 (and (= c ?q) (not (rassoc c ntable))))
14231 (org-detach-overlay org-tags-overlay)
14232 (setq quit-flag t))
14233 ((= c ?\ )
14234 (setq current nil)
14235 (if exit-after-next (setq exit-after-next 'now)))
14236 ((= c ?\t)
14237 (condition-case nil
14238 (setq tg (org-icompleting-read
14239 "Tag: "
14240 (or buffer-tags
14241 (with-current-buffer buf
14242 (org-get-buffer-tags)))))
14243 (quit (setq tg "")))
14244 (when (string-match "\\S-" tg)
14245 (add-to-list 'buffer-tags (list tg))
14246 (if (member tg current)
14247 (setq current (delete tg current))
14248 (push tg current)))
14249 (if exit-after-next (setq exit-after-next 'now)))
14250 ((setq e (rassoc c todo-table) tg (car e))
14251 (with-current-buffer buf
14252 (save-excursion (org-todo tg)))
14253 (if exit-after-next (setq exit-after-next 'now)))
14254 ((setq e (rassoc c ntable) tg (car e))
14255 (if (member tg current)
14256 (setq current (delete tg current))
14257 (loop for g in groups do
14258 (if (member tg g)
14259 (mapc (lambda (x)
14260 (setq current (delete x current)))
14261 g)))
14262 (push tg current))
14263 (if exit-after-next (setq exit-after-next 'now))))
14265 ;; Create a sorted list
14266 (setq current
14267 (sort current
14268 (lambda (a b)
14269 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14270 (if (eq exit-after-next 'now) (throw 'exit t))
14271 (goto-char (point-min))
14272 (beginning-of-line 2)
14273 (delete-region (point) (point-at-eol))
14274 (org-fast-tag-insert "Current" current c-face)
14275 (org-set-current-tags-overlay current ov-prefix)
14276 (while (re-search-forward
14277 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14278 (setq tg (match-string 1))
14279 (add-text-properties
14280 (match-beginning 1) (match-end 1)
14281 (list 'face
14282 (cond
14283 ((member tg current) c-face)
14284 ((member tg inherited) i-face)
14285 (t (get-text-property (match-beginning 1) 'face))))))
14286 (goto-char (point-min)))))
14287 (org-detach-overlay org-tags-overlay)
14288 (if rtn
14289 (mapconcat 'identity current ":")
14290 nil))))
14292 (defun org-get-tags-string ()
14293 "Get the TAGS string in the current headline."
14294 (unless (org-at-heading-p t)
14295 (error "Not on a heading"))
14296 (save-excursion
14297 (beginning-of-line 1)
14298 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14299 (org-match-string-no-properties 1)
14300 "")))
14302 (defun org-get-tags ()
14303 "Get the list of tags specified in the current headline."
14304 (org-split-string (org-get-tags-string) ":"))
14306 (defun org-get-buffer-tags ()
14307 "Get a table of all tags used in the buffer, for completion."
14308 (let (tags)
14309 (save-excursion
14310 (goto-char (point-min))
14311 (while (re-search-forward
14312 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14313 (when (equal (char-after (point-at-bol 0)) ?*)
14314 (mapc (lambda (x) (add-to-list 'tags x))
14315 (org-split-string (org-match-string-no-properties 1) ":")))))
14316 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14317 (mapcar 'list tags)))
14319 ;;;; The mapping API
14321 (defun org-map-entries (func &optional match scope &rest skip)
14322 "Call FUNC at each headline selected by MATCH in SCOPE.
14324 FUNC is a function or a lisp form. The function will be called without
14325 arguments, with the cursor positioned at the beginning of the headline.
14326 The return values of all calls to the function will be collected and
14327 returned as a list.
14329 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14330 does not need to preserve point. After evaluation, the cursor will be
14331 moved to the end of the line (presumably of the headline of the
14332 processed entry) and search continues from there. Under some
14333 circumstances, this may not produce the wanted results. For example,
14334 if you have removed (e.g. archived) the current (sub)tree it could
14335 mean that the next entry will be skipped entirely. In such cases, you
14336 can specify the position from where search should continue by making
14337 FUNC set the variable `org-map-continue-from' to the desired buffer
14338 position.
14340 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14341 Only headlines that are matched by this query will be considered during
14342 the iteration. When MATCH is nil or t, all headlines will be
14343 visited by the iteration.
14345 SCOPE determines the scope of this command. It can be any of:
14347 nil The current buffer, respecting the restriction if any
14348 tree The subtree started with the entry at point
14349 region The entries within the active region, if any
14350 region-start-level
14351 The entries within the active region, but only those at
14352 the same level than the first one.
14353 file The current buffer, without restriction
14354 file-with-archives
14355 The current buffer, and any archives associated with it
14356 agenda All agenda files
14357 agenda-with-archives
14358 All agenda files with any archive files associated with them
14359 \(file1 file2 ...)
14360 If this is a list, all files in the list will be scanned
14362 The remaining args are treated as settings for the skipping facilities of
14363 the scanner. The following items can be given here:
14365 archive skip trees with the archive tag.
14366 comment skip trees with the COMMENT keyword
14367 function or Emacs Lisp form:
14368 will be used as value for `org-agenda-skip-function', so whenever
14369 the function returns t, FUNC will not be called for that
14370 entry and search will continue from the point where the
14371 function leaves it.
14373 If your function needs to retrieve the tags including inherited tags
14374 at the *current* entry, you can use the value of the variable
14375 `org-scanner-tags' which will be much faster than getting the value
14376 with `org-get-tags-at'. If your function gets properties with
14377 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14378 to t around the call to `org-entry-properties' to get the same speedup.
14379 Note that if your function moves around to retrieve tags and properties at
14380 a *different* entry, you cannot use these techniques."
14381 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14382 (not (org-region-active-p)))
14383 (let* ((org-agenda-archives-mode nil) ; just to make sure
14384 (org-agenda-skip-archived-trees (memq 'archive skip))
14385 (org-agenda-skip-comment-trees (memq 'comment skip))
14386 (org-agenda-skip-function
14387 (car (org-delete-all '(comment archive) skip)))
14388 (org-tags-match-list-sublevels t)
14389 (start-level (eq scope 'region-start-level))
14390 matcher file res
14391 org-todo-keywords-for-agenda
14392 org-done-keywords-for-agenda
14393 org-todo-keyword-alist-for-agenda
14394 org-drawers-for-agenda
14395 org-tag-alist-for-agenda
14396 todo-only)
14398 (cond
14399 ((eq match t) (setq matcher t))
14400 ((eq match nil) (setq matcher t))
14401 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14403 (save-excursion
14404 (save-restriction
14405 (cond ((eq scope 'tree)
14406 (org-back-to-heading t)
14407 (org-narrow-to-subtree)
14408 (setq scope nil))
14409 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14410 (org-region-active-p))
14411 ;; If needed, set start-level to a string like "2"
14412 (when start-level
14413 (save-excursion
14414 (goto-char (region-beginning))
14415 (unless (org-at-heading-p) (outline-next-heading))
14416 (setq start-level (org-current-level))))
14417 (narrow-to-region (region-beginning)
14418 (save-excursion
14419 (goto-char (region-end))
14420 (unless (and (bolp) (org-at-heading-p))
14421 (outline-next-heading))
14422 (point)))
14423 (setq scope nil)))
14425 (if (not scope)
14426 (progn
14427 (org-agenda-prepare-buffers
14428 (list (buffer-file-name (current-buffer))))
14429 (setq res (org-scan-tags func matcher todo-only start-level)))
14430 ;; Get the right scope
14431 (cond
14432 ((and scope (listp scope) (symbolp (car scope)))
14433 (setq scope (eval scope)))
14434 ((eq scope 'agenda)
14435 (setq scope (org-agenda-files t)))
14436 ((eq scope 'agenda-with-archives)
14437 (setq scope (org-agenda-files t))
14438 (setq scope (org-add-archive-files scope)))
14439 ((eq scope 'file)
14440 (setq scope (list (buffer-file-name))))
14441 ((eq scope 'file-with-archives)
14442 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14443 (org-agenda-prepare-buffers scope)
14444 (while (setq file (pop scope))
14445 (with-current-buffer (org-find-base-buffer-visiting file)
14446 (save-excursion
14447 (save-restriction
14448 (widen)
14449 (goto-char (point-min))
14450 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14451 res)))
14453 ;;;; Properties
14455 ;;; Setting and retrieving properties
14457 (defconst org-special-properties
14458 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14459 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14460 "The special properties valid in Org-mode.
14462 These are properties that are not defined in the property drawer,
14463 but in some other way.")
14465 (defconst org-default-properties
14466 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14467 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14468 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14469 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14470 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14471 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14472 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14473 "Some properties that are used by Org-mode for various purposes.
14474 Being in this list makes sure that they are offered for completion.")
14476 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14477 "Regular expression matching the first line of a property drawer.")
14479 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14480 "Regular expression matching the last line of a property drawer.")
14482 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14483 "Regular expression matching the first line of a property drawer.")
14485 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14486 "Regular expression matching the first line of a property drawer.")
14488 (defconst org-property-drawer-re
14489 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14490 org-property-end-re "\\)\n?")
14491 "Matches an entire property drawer.")
14493 (defconst org-clock-drawer-re
14494 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14495 org-property-end-re "\\)\n?")
14496 "Matches an entire clock drawer.")
14498 (defsubst org-re-property (property)
14499 "Return a regexp matching a PROPERTY line.
14500 Match group 1 will be set to the value."
14501 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14503 (defsubst org-re-property-keyword (property)
14504 "Return a regexp matching a PROPERTY line, possibly with no
14505 value for the property."
14506 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14508 (defun org-property-action ()
14509 "Do an action on properties."
14510 (interactive)
14511 (let (c)
14512 (org-at-property-p)
14513 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14514 (setq c (read-char-exclusive))
14515 (cond
14516 ((equal c ?s)
14517 (call-interactively 'org-set-property))
14518 ((equal c ?d)
14519 (call-interactively 'org-delete-property))
14520 ((equal c ?D)
14521 (call-interactively 'org-delete-property-globally))
14522 ((equal c ?c)
14523 (call-interactively 'org-compute-property-at-point))
14524 (t (error "No such property action %c" c)))))
14526 (defun org-inc-effort ()
14527 "Increment the value of the effort property in the current entry."
14528 (interactive)
14529 (org-set-effort nil t))
14531 (defun org-set-effort (&optional value increment)
14532 "Set the effort property of the current entry.
14533 With numerical prefix arg, use the nth allowed value, 0 stands for the
14534 10th allowed value.
14536 When INCREMENT is non-nil, set the property to the next allowed value."
14537 (interactive "P")
14538 (if (equal value 0) (setq value 10))
14539 (let* ((completion-ignore-case t)
14540 (prop org-effort-property)
14541 (cur (org-entry-get nil prop))
14542 (allowed (org-property-get-allowed-values nil prop 'table))
14543 (existing (mapcar 'list (org-property-values prop)))
14545 (val (cond
14546 ((stringp value) value)
14547 ((and allowed (integerp value))
14548 (or (car (nth (1- value) allowed))
14549 (car (org-last allowed))))
14550 ((and allowed increment)
14551 (or (caadr (member (list cur) allowed))
14552 (error "Allowed effort values are not set")))
14553 (allowed
14554 (message "Select 1-9,0, [RET%s]: %s"
14555 (if cur (concat "=" cur) "")
14556 (mapconcat 'car allowed " "))
14557 (setq rpl (read-char-exclusive))
14558 (if (equal rpl ?\r)
14560 (setq rpl (- rpl ?0))
14561 (if (equal rpl 0) (setq rpl 10))
14562 (if (and (> rpl 0) (<= rpl (length allowed)))
14563 (car (nth (1- rpl) allowed))
14564 (org-completing-read "Effort: " allowed nil))))
14566 (let (org-completion-use-ido org-completion-use-iswitchb)
14567 (org-completing-read
14568 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14569 (concat "[" cur "]") "")
14570 ": ")
14571 existing nil nil "" nil cur))))))
14572 (unless (equal (org-entry-get nil prop) val)
14573 (org-entry-put nil prop val))
14574 (save-excursion
14575 (org-back-to-heading t)
14576 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14577 (message "%s is now %s" prop val)))
14579 (defun org-at-property-p ()
14580 "Is cursor inside a property drawer?"
14581 (save-excursion
14582 (beginning-of-line 1)
14583 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14584 (save-match-data ;; Used by calling procedures
14585 (let ((p (point))
14586 (range (unless (org-before-first-heading-p)
14587 (org-get-property-block))))
14588 (and range (<= (car range) p) (< p (cdr range))))))))
14590 (defun org-get-property-block (&optional beg end force)
14591 "Return the (beg . end) range of the body of the property drawer.
14592 BEG and END are the beginning and end of the current subtree, or of
14593 the part before the first headline. If they are not given, they will
14594 be found. If the drawer does not exist and FORCE is non-nil, create
14595 the drawer."
14596 (catch 'exit
14597 (save-excursion
14598 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14599 (progn (org-back-to-heading t) (point))))
14600 (end (or end (and (not (outline-next-heading)) (point-max))
14601 (point))))
14602 (goto-char beg)
14603 (if (re-search-forward org-property-start-re end t)
14604 (setq beg (1+ (match-end 0)))
14605 (if force
14606 (save-excursion
14607 (org-insert-property-drawer)
14608 (setq end (progn (outline-next-heading) (point))))
14609 (throw 'exit nil))
14610 (goto-char beg)
14611 (if (re-search-forward org-property-start-re end t)
14612 (setq beg (1+ (match-end 0)))))
14613 (if (re-search-forward org-property-end-re end t)
14614 (setq end (match-beginning 0))
14615 (or force (throw 'exit nil))
14616 (goto-char beg)
14617 (setq end beg)
14618 (org-indent-line)
14619 (insert ":END:\n"))
14620 (cons beg end)))))
14622 (defun org-entry-properties (&optional pom which specific)
14623 "Get all properties of the entry at point-or-marker POM.
14624 This includes the TODO keyword, the tags, time strings for deadline,
14625 scheduled, and clocking, and any additional properties defined in the
14626 entry. The return value is an alist, keys may occur multiple times
14627 if the property key was used several times.
14628 POM may also be nil, in which case the current entry is used.
14629 If WHICH is nil or `all', get all properties. If WHICH is
14630 `special' or `standard', only get that subclass. If WHICH
14631 is a string only get exactly this property. SPECIFIC can be a string, the
14632 specific property we are interested in. Specifying it can speed
14633 things up because then unnecessary parsing is avoided."
14634 (setq which (or which 'all))
14635 (org-with-point-at pom
14636 (let ((clockstr (substring org-clock-string 0 -1))
14637 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14638 (case-fold-search nil)
14639 beg end range props sum-props key key1 value string clocksum clocksumt)
14640 (save-excursion
14641 (when (condition-case nil
14642 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14643 (error nil))
14644 (setq beg (point))
14645 (setq sum-props (get-text-property (point) 'org-summaries))
14646 (setq clocksum (get-text-property (point) :org-clock-minutes)
14647 clocksumt (get-text-property (point) :org-clock-minutes-today))
14648 (outline-next-heading)
14649 (setq end (point))
14650 (when (memq which '(all special))
14651 ;; Get the special properties, like TODO and tags
14652 (goto-char beg)
14653 (when (and (or (not specific) (string= specific "TODO"))
14654 (looking-at org-todo-line-regexp) (match-end 2))
14655 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14656 (when (and (or (not specific) (string= specific "PRIORITY"))
14657 (looking-at org-priority-regexp))
14658 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14659 (when (or (not specific) (string= specific "FILE"))
14660 (push (cons "FILE" buffer-file-name) props))
14661 (when (and (or (not specific) (string= specific "TAGS"))
14662 (setq value (org-get-tags-string))
14663 (string-match "\\S-" value))
14664 (push (cons "TAGS" value) props))
14665 (when (and (or (not specific) (string= specific "ALLTAGS"))
14666 (setq value (org-get-tags-at)))
14667 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14668 ":"))
14669 props))
14670 (when (or (not specific) (string= specific "BLOCKED"))
14671 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14672 (when (or (not specific)
14673 (member specific
14674 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14675 "TIMESTAMP" "TIMESTAMP_IA")))
14676 (catch 'match
14677 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14678 (setq key (if (match-end 1)
14679 (substring (org-match-string-no-properties 1)
14680 0 -1))
14681 string (if (equal key clockstr)
14682 (org-trim
14683 (buffer-substring-no-properties
14684 (match-beginning 3) (goto-char
14685 (point-at-eol))))
14686 (substring (org-match-string-no-properties 3)
14687 1 -1)))
14688 ;; Get the correct property name from the key. This is
14689 ;; necessary if the user has configured time keywords.
14690 (setq key1 (concat key ":"))
14691 (cond
14692 ((not key)
14693 (setq key
14694 (if (= (char-after (match-beginning 3)) ?\[)
14695 "TIMESTAMP_IA" "TIMESTAMP")))
14696 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14697 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14698 ((equal key1 org-closed-string) (setq key "CLOSED"))
14699 ((equal key1 org-clock-string) (setq key "CLOCK")))
14700 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14701 (progn
14702 (push (cons key string) props)
14703 ;; no need to search further if match is found
14704 (throw 'match t))
14705 (when (or (equal key "CLOCK") (not (assoc key props)))
14706 (push (cons key string) props)))))))
14708 (when (memq which '(all standard))
14709 ;; Get the standard properties, like :PROP: ...
14710 (setq range (org-get-property-block beg end))
14711 (when range
14712 (goto-char (car range))
14713 (while (re-search-forward
14714 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14715 (cdr range) t)
14716 (setq key (org-match-string-no-properties 1)
14717 value (org-trim (or (org-match-string-no-properties 2) "")))
14718 (unless (member key excluded)
14719 (push (cons key (or value "")) props)))))
14720 (if clocksum
14721 (push (cons "CLOCKSUM"
14722 (org-columns-number-to-string (/ (float clocksum) 60.)
14723 'add_times))
14724 props))
14725 (if clocksumt
14726 (push (cons "CLOCKSUM_T"
14727 (org-columns-number-to-string (/ (float clocksumt) 60.)
14728 'add_times))
14729 props))
14730 (unless (assoc "CATEGORY" props)
14731 (push (cons "CATEGORY" (org-get-category)) props))
14732 (append sum-props (nreverse props)))))))
14734 (defun org-entry-get (pom property &optional inherit literal-nil)
14735 "Get value of PROPERTY for entry or content at point-or-marker POM.
14736 If INHERIT is non-nil and the entry does not have the property,
14737 then also check higher levels of the hierarchy.
14738 If INHERIT is the symbol `selective', use inheritance only if the setting
14739 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14740 If the property is present but empty, the return value is the empty string.
14741 If the property is not present at all, nil is returned.
14743 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14744 do not interpret it as the list atom nil. This is used for inheritance
14745 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14746 (org-with-point-at pom
14747 (if (and inherit (if (eq inherit 'selective)
14748 (org-property-inherit-p property)
14750 (org-entry-get-with-inheritance property literal-nil)
14751 (if (member property org-special-properties)
14752 ;; We need a special property. Use `org-entry-properties' to
14753 ;; retrieve it, but specify the wanted property
14754 (cdr (assoc property (org-entry-properties nil 'special property)))
14755 (let ((range (org-get-property-block)))
14756 (when (and range (not (eq (car range) (cdr range))))
14757 (let* ((props (list (or (assoc property org-file-properties)
14758 (assoc property org-global-properties)
14759 (assoc property org-global-properties-fixed))))
14760 (ap (lambda (key)
14761 (when (re-search-forward
14762 (org-re-property key) (cdr range) t)
14763 (setq props
14764 (org-update-property-plist
14766 (if (match-end 1)
14767 (org-match-string-no-properties 1) "")
14768 props)))))
14769 val)
14770 (goto-char (car range))
14771 (funcall ap property)
14772 (goto-char (car range))
14773 (while (funcall ap (concat property "+")))
14774 (setq val (cdr (assoc property props)))
14775 (when val (if literal-nil val (org-not-nil val))))))))))
14777 (defun org-property-or-variable-value (var &optional inherit)
14778 "Check if there is a property fixing the value of VAR.
14779 If yes, return this value. If not, return the current value of the variable."
14780 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14781 (if (and prop (stringp prop) (string-match "\\S-" prop))
14782 (read prop)
14783 (symbol-value var))))
14785 (defun org-entry-delete (pom property)
14786 "Delete the property PROPERTY from entry at point-or-marker POM."
14787 (org-with-point-at pom
14788 (if (member property org-special-properties)
14789 nil ; cannot delete these properties.
14790 (let ((range (org-get-property-block)))
14791 (if (and range
14792 (goto-char (car range))
14793 (re-search-forward
14794 (org-re-property property)
14795 (cdr range) t))
14796 (progn
14797 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14799 nil)))))
14801 ;; Multi-values properties are properties that contain multiple values
14802 ;; These values are assumed to be single words, separated by whitespace.
14803 (defun org-entry-add-to-multivalued-property (pom property value)
14804 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14805 (let* ((old (org-entry-get pom property))
14806 (values (and old (org-split-string old "[ \t]"))))
14807 (setq value (org-entry-protect-space value))
14808 (unless (member value values)
14809 (setq values (cons value values))
14810 (org-entry-put pom property
14811 (mapconcat 'identity values " ")))))
14813 (defun org-entry-remove-from-multivalued-property (pom property value)
14814 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14815 (let* ((old (org-entry-get pom property))
14816 (values (and old (org-split-string old "[ \t]"))))
14817 (setq value (org-entry-protect-space value))
14818 (when (member value values)
14819 (setq values (delete value values))
14820 (org-entry-put pom property
14821 (mapconcat 'identity values " ")))))
14823 (defun org-entry-member-in-multivalued-property (pom property value)
14824 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14825 (let* ((old (org-entry-get pom property))
14826 (values (and old (org-split-string old "[ \t]"))))
14827 (setq value (org-entry-protect-space value))
14828 (member value values)))
14830 (defun org-entry-get-multivalued-property (pom property)
14831 "Return a list of values in a multivalued property."
14832 (let* ((value (org-entry-get pom property))
14833 (values (and value (org-split-string value "[ \t]"))))
14834 (mapcar 'org-entry-restore-space values)))
14836 (defun org-entry-put-multivalued-property (pom property &rest values)
14837 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14838 VALUES should be a list of strings. Spaces will be protected."
14839 (org-entry-put pom property
14840 (mapconcat 'org-entry-protect-space values " "))
14841 (let* ((value (org-entry-get pom property))
14842 (values (and value (org-split-string value "[ \t]"))))
14843 (mapcar 'org-entry-restore-space values)))
14845 (defun org-entry-protect-space (s)
14846 "Protect spaces and newline in string S."
14847 (while (string-match " " s)
14848 (setq s (replace-match "%20" t t s)))
14849 (while (string-match "\n" s)
14850 (setq s (replace-match "%0A" t t s)))
14853 (defun org-entry-restore-space (s)
14854 "Restore spaces and newline in string S."
14855 (while (string-match "%20" s)
14856 (setq s (replace-match " " t t s)))
14857 (while (string-match "%0A" s)
14858 (setq s (replace-match "\n" t t s)))
14861 (defvar org-entry-property-inherited-from (make-marker)
14862 "Marker pointing to the entry from where a property was inherited.
14863 Each call to `org-entry-get-with-inheritance' will set this marker to the
14864 location of the entry where the inheritance search matched. If there was
14865 no match, the marker will point nowhere.
14866 Note that also `org-entry-get' calls this function, if the INHERIT flag
14867 is set.")
14869 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14870 "Get PROPERTY of entry or content at point, search higher levels if needed.
14871 The search will stop at the first ancestor which has the property defined.
14872 If the value found is \"nil\", return nil to show that the property
14873 should be considered as undefined (this is the meaning of nil here).
14874 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14875 (move-marker org-entry-property-inherited-from nil)
14876 (let (tmp)
14877 (save-excursion
14878 (save-restriction
14879 (widen)
14880 (catch 'ex
14881 (while t
14882 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14883 (or (ignore-errors (org-back-to-heading t))
14884 (goto-char (point-min)))
14885 (move-marker org-entry-property-inherited-from (point))
14886 (throw 'ex tmp))
14887 (or (ignore-errors (org-up-heading-safe))
14888 (throw 'ex nil))))))
14889 (setq tmp (or tmp
14890 (cdr (assoc property org-file-properties))
14891 (cdr (assoc property org-global-properties))
14892 (cdr (assoc property org-global-properties-fixed))))
14893 (if literal-nil tmp (org-not-nil tmp))))
14895 (defvar org-property-changed-functions nil
14896 "Hook called when the value of a property has changed.
14897 Each hook function should accept two arguments, the name of the property
14898 and the new value.")
14900 (defun org-entry-put (pom property value)
14901 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14902 (org-with-point-at pom
14903 (org-back-to-heading t)
14904 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14905 range)
14906 (cond
14907 ((equal property "TODO")
14908 (when (and (stringp value) (string-match "\\S-" value)
14909 (not (member value org-todo-keywords-1)))
14910 (error "\"%s\" is not a valid TODO state" value))
14911 (if (or (not value)
14912 (not (string-match "\\S-" value)))
14913 (setq value 'none))
14914 (org-todo value)
14915 (org-set-tags nil 'align))
14916 ((equal property "PRIORITY")
14917 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14918 (string-to-char value) ?\ ))
14919 (org-set-tags nil 'align))
14920 ((equal property "CLOCKSUM")
14921 (if (not (re-search-forward
14922 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14923 (error "Cannot find a clock log")
14924 (goto-char (- (match-end 1) 2))
14925 (cond
14926 ((eq value 'earlier) (org-timestamp-down))
14927 ((eq value 'later) (org-timestamp-up)))
14928 (org-clock-sum-current-item)))
14929 ((equal property "SCHEDULED")
14930 (if (re-search-forward org-scheduled-time-regexp end t)
14931 (cond
14932 ((eq value 'earlier) (org-timestamp-change -1 'day))
14933 ((eq value 'later) (org-timestamp-change 1 'day))
14934 (t (call-interactively 'org-schedule)))
14935 (call-interactively 'org-schedule)))
14936 ((equal property "DEADLINE")
14937 (if (re-search-forward org-deadline-time-regexp end t)
14938 (cond
14939 ((eq value 'earlier) (org-timestamp-change -1 'day))
14940 ((eq value 'later) (org-timestamp-change 1 'day))
14941 (t (call-interactively 'org-deadline)))
14942 (call-interactively 'org-deadline)))
14943 ((member property org-special-properties)
14944 (error "The %s property can not yet be set with `org-entry-put'"
14945 property))
14946 (t ; a non-special property
14947 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14948 (setq range (org-get-property-block beg end 'force))
14949 (goto-char (car range))
14950 (if (re-search-forward
14951 (org-re-property-keyword property) (cdr range) t)
14952 (progn
14953 (delete-region (match-beginning 0) (match-end 0))
14954 (goto-char (match-beginning 0)))
14955 (goto-char (cdr range))
14956 (insert "\n")
14957 (backward-char 1)
14958 (org-indent-line))
14959 (insert ":" property ":")
14960 (and value (insert " " value))
14961 (org-indent-line)))))
14962 (run-hook-with-args 'org-property-changed-functions property value)))
14964 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14965 "Get all property keys in the current buffer.
14966 With INCLUDE-SPECIALS, also list the special properties that reflect things
14967 like tags and TODO state.
14968 With INCLUDE-DEFAULTS, also include properties that has special meaning
14969 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14970 and others.
14971 With INCLUDE-COLUMNS, also include property names given in COLUMN
14972 formats in the current buffer."
14973 (let (rtn range cfmt s p)
14974 (save-excursion
14975 (save-restriction
14976 (widen)
14977 (goto-char (point-min))
14978 (while (re-search-forward org-property-start-re nil t)
14979 (setq range (org-get-property-block))
14980 (goto-char (car range))
14981 (while (re-search-forward
14982 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14983 (cdr range) t)
14984 (add-to-list 'rtn (org-match-string-no-properties 1)))
14985 (outline-next-heading))))
14987 (when include-specials
14988 (setq rtn (append org-special-properties rtn)))
14990 (when include-defaults
14991 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14992 (add-to-list 'rtn org-effort-property))
14994 (when include-columns
14995 (save-excursion
14996 (save-restriction
14997 (widen)
14998 (goto-char (point-min))
14999 (while (re-search-forward
15000 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15001 nil t)
15002 (setq cfmt (match-string 2) s 0)
15003 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15004 cfmt s)
15005 (setq s (match-end 0)
15006 p (match-string 1 cfmt))
15007 (unless (or (equal p "ITEM")
15008 (member p org-special-properties))
15009 (add-to-list 'rtn (match-string 1 cfmt))))))))
15011 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15013 (defun org-property-values (key)
15014 "Return a list of all values of property KEY in the current buffer."
15015 (save-excursion
15016 (save-restriction
15017 (widen)
15018 (goto-char (point-min))
15019 (let ((re (org-re-property key))
15020 values)
15021 (while (re-search-forward re nil t)
15022 (add-to-list 'values (org-trim (match-string 1))))
15023 (delete "" values)))))
15025 (defun org-insert-property-drawer ()
15026 "Insert a property drawer into the current entry."
15027 (org-back-to-heading t)
15028 (looking-at org-outline-regexp)
15029 (let ((indent (if org-adapt-indentation
15030 (- (match-end 0) (match-beginning 0))
15032 (beg (point))
15033 (re (concat "^[ \t]*" org-keyword-time-regexp))
15034 end hiddenp)
15035 (outline-next-heading)
15036 (setq end (point))
15037 (goto-char beg)
15038 (while (re-search-forward re end t))
15039 (setq hiddenp (outline-invisible-p))
15040 (end-of-line 1)
15041 (and (equal (char-after) ?\n) (forward-char 1))
15042 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15043 (if (member (match-string 1) '("CLOCK:" ":END:"))
15044 ;; just skip this line
15045 (beginning-of-line 2)
15046 ;; Drawer start, find the end
15047 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15048 (beginning-of-line 1)))
15049 (org-skip-over-state-notes)
15050 (skip-chars-backward " \t\n\r")
15051 (if (eq (char-before) ?*) (forward-char 1))
15052 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15053 (beginning-of-line 0)
15054 (org-indent-to-column indent)
15055 (beginning-of-line 2)
15056 (org-indent-to-column indent)
15057 (beginning-of-line 0)
15058 (if hiddenp
15059 (save-excursion
15060 (org-back-to-heading t)
15061 (hide-entry))
15062 (org-flag-drawer t))))
15064 (defun org-insert-drawer (&optional arg drawer)
15065 "Insert a drawer at point.
15067 Optional argument DRAWER, when non-nil, is a string representing
15068 drawer's name. Otherwise, the user is prompted for a name.
15070 If a region is active, insert the drawer around that region
15071 instead.
15073 Point is left between drawer's boundaries."
15074 (interactive "P")
15075 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15076 "LOGBOOK"))
15077 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15078 ;; internally by Org. They are meant to be inserted
15079 ;; automatically.
15080 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15081 ;; Remove system drawers from list. Note: For some reason,
15082 ;; `org-completing-read' ignores the predicate while
15083 ;; `completing-read' handles it fine.
15084 (drawer (if arg "PROPERTIES"
15085 (or drawer
15086 (completing-read
15087 "Drawer: " org-drawers
15088 (lambda (d) (not (member d system-drawers))))))))
15089 (cond
15090 ;; With C-u, fall back on `org-insert-property-drawer'
15091 (arg (org-insert-property-drawer))
15092 ;; With an active region, insert a drawer at point.
15093 ((not (org-region-active-p))
15094 (progn
15095 (unless (bolp) (insert "\n"))
15096 (insert (format ":%s:\n\n:END:\n" drawer))
15097 (forward-line -2)))
15098 ;; Otherwise, insert the drawer at point
15100 (let ((rbeg (region-beginning))
15101 (rend (copy-marker (region-end))))
15102 (unwind-protect
15103 (progn
15104 (goto-char rbeg)
15105 (beginning-of-line)
15106 (when (save-excursion
15107 (re-search-forward org-outline-regexp-bol rend t))
15108 (error "Drawers cannot contain headlines"))
15109 ;; Position point at the beginning of the first
15110 ;; non-blank line in region. Insert drawer's opening
15111 ;; there, then indent it.
15112 (org-skip-whitespace)
15113 (beginning-of-line)
15114 (insert ":" drawer ":\n")
15115 (forward-line -1)
15116 (indent-for-tab-command)
15117 ;; Move point to the beginning of the first blank line
15118 ;; after the last non-blank line in region. Insert
15119 ;; drawer's closing, then indent it.
15120 (goto-char rend)
15121 (skip-chars-backward " \r\t\n")
15122 (insert "\n:END:")
15123 (deactivate-mark t)
15124 (indent-for-tab-command)
15125 (unless (eolp) (insert "\n")))
15126 ;; Clear marker, whatever the outcome of insertion is.
15127 (set-marker rend nil)))))))
15129 (defvar org-property-set-functions-alist nil
15130 "Property set function alist.
15131 Each entry should have the following format:
15133 (PROPERTY . READ-FUNCTION)
15135 The read function will be called with the same argument as
15136 `org-completing-read'.")
15138 (defun org-set-property-function (property)
15139 "Get the function that should be used to set PROPERTY.
15140 This is computed according to `org-property-set-functions-alist'."
15141 (or (cdr (assoc property org-property-set-functions-alist))
15142 'org-completing-read))
15144 (defun org-read-property-value (property)
15145 "Read PROPERTY value from user."
15146 (let* ((completion-ignore-case t)
15147 (allowed (org-property-get-allowed-values nil property 'table))
15148 (cur (org-entry-get nil property))
15149 (prompt (concat property " value"
15150 (if (and cur (string-match "\\S-" cur))
15151 (concat " [" cur "]") "") ": "))
15152 (set-function (org-set-property-function property))
15153 (val (if allowed
15154 (funcall set-function prompt allowed nil
15155 (not (get-text-property 0 'org-unrestricted
15156 (caar allowed))))
15157 (let (org-completion-use-ido org-completion-use-iswitchb)
15158 (funcall set-function prompt
15159 (mapcar 'list (org-property-values property))
15160 nil nil "" nil cur)))))
15161 (if (equal val "")
15163 val)))
15165 (defvar org-last-set-property nil)
15166 (defvar org-last-set-property-value nil)
15167 (defun org-read-property-name ()
15168 "Read a property name."
15169 (let* ((completion-ignore-case t)
15170 (keys (org-buffer-property-keys nil t t))
15171 (default-prop (or (save-excursion
15172 (save-match-data
15173 (beginning-of-line)
15174 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15175 (null (string= (match-string 1) "END"))
15176 (match-string 1))))
15177 org-last-set-property))
15178 (property (org-icompleting-read
15179 (concat "Property"
15180 (if default-prop (concat " [" default-prop "]") "")
15181 ": ")
15182 (mapcar 'list keys)
15183 nil nil nil nil
15184 default-prop)))
15185 (if (member property keys)
15186 property
15187 (or (cdr (assoc (downcase property)
15188 (mapcar (lambda (x) (cons (downcase x) x))
15189 keys)))
15190 property))))
15192 (defun org-set-property-and-value (use-last)
15193 "Allow to set [PROPERTY]: [value] direction from prompt.
15194 When use-default, don't even ask, just use the last
15195 \"[PROPERTY]: [value]\" string from the history."
15196 (interactive "P")
15197 (let* ((completion-ignore-case t)
15198 (pv (or (and use-last org-last-set-property-value)
15199 (org-completing-read
15200 "Enter a \"[Property]: [value]\" pair: "
15201 nil nil nil nil nil
15202 org-last-set-property-value)))
15203 prop val)
15204 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15205 (setq prop (match-string 1 pv)
15206 val (match-string 2 pv))
15207 (org-set-property prop val))))
15209 (defun org-set-property (property value)
15210 "In the current entry, set PROPERTY to VALUE.
15211 When called interactively, this will prompt for a property name, offering
15212 completion on existing and default properties. And then it will prompt
15213 for a value, offering completion either on allowed values (via an inherited
15214 xxx_ALL property) or on existing values in other instances of this property
15215 in the current file."
15216 (interactive (list nil nil))
15217 (let* ((property (or property (org-read-property-name)))
15218 (value (or value (org-read-property-value property)))
15219 (fn (cdr (assoc property org-properties-postprocess-alist))))
15220 (setq org-last-set-property property)
15221 (setq org-last-set-property-value (concat property ": " value))
15222 ;; Possibly postprocess the inserted value:
15223 (when fn (setq value (funcall fn value)))
15224 (unless (equal (org-entry-get nil property) value)
15225 (org-entry-put nil property value))))
15227 (defun org-delete-property (property)
15228 "In the current entry, delete PROPERTY."
15229 (interactive
15230 (let* ((completion-ignore-case t)
15231 (prop (org-icompleting-read "Property: "
15232 (org-entry-properties nil 'standard))))
15233 (list prop)))
15234 (message "Property %s %s" property
15235 (if (org-entry-delete nil property)
15236 "deleted"
15237 "was not present in the entry")))
15239 (defun org-delete-property-globally (property)
15240 "Remove PROPERTY globally, from all entries."
15241 (interactive
15242 (let* ((completion-ignore-case t)
15243 (prop (org-icompleting-read
15244 "Globally remove property: "
15245 (mapcar 'list (org-buffer-property-keys)))))
15246 (list prop)))
15247 (save-excursion
15248 (save-restriction
15249 (widen)
15250 (goto-char (point-min))
15251 (let ((cnt 0))
15252 (while (re-search-forward
15253 (org-re-property property)
15254 nil t)
15255 (setq cnt (1+ cnt))
15256 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15257 (message "Property \"%s\" removed from %d entries" property cnt)))))
15259 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15261 (defun org-compute-property-at-point ()
15262 "Compute the property at point.
15263 This looks for an enclosing column format, extracts the operator and
15264 then applies it to the property in the column format's scope."
15265 (interactive)
15266 (unless (org-at-property-p)
15267 (error "Not at a property"))
15268 (let ((prop (org-match-string-no-properties 2)))
15269 (org-columns-get-format-and-top-level)
15270 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15271 (error "No operator defined for property %s" prop))
15272 (org-columns-compute prop)))
15274 (defvar org-property-allowed-value-functions nil
15275 "Hook for functions supplying allowed values for a specific property.
15276 The functions must take a single argument, the name of the property, and
15277 return a flat list of allowed values. If \":ETC\" is one of
15278 the values, this means that these values are intended as defaults for
15279 completion, but that other values should be allowed too.
15280 The functions must return nil if they are not responsible for this
15281 property.")
15283 (defun org-property-get-allowed-values (pom property &optional table)
15284 "Get allowed values for the property PROPERTY.
15285 When TABLE is non-nil, return an alist that can directly be used for
15286 completion."
15287 (let (vals)
15288 (cond
15289 ((equal property "TODO")
15290 (setq vals (org-with-point-at pom
15291 (append org-todo-keywords-1 '("")))))
15292 ((equal property "PRIORITY")
15293 (let ((n org-lowest-priority))
15294 (while (>= n org-highest-priority)
15295 (push (char-to-string n) vals)
15296 (setq n (1- n)))))
15297 ((member property org-special-properties))
15298 ((setq vals (run-hook-with-args-until-success
15299 'org-property-allowed-value-functions property)))
15301 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15302 (when (and vals (string-match "\\S-" vals))
15303 (setq vals (car (read-from-string (concat "(" vals ")"))))
15304 (setq vals (mapcar (lambda (x)
15305 (cond ((stringp x) x)
15306 ((numberp x) (number-to-string x))
15307 ((symbolp x) (symbol-name x))
15308 (t "???")))
15309 vals)))))
15310 (when (member ":ETC" vals)
15311 (setq vals (remove ":ETC" vals))
15312 (org-add-props (car vals) '(org-unrestricted t)))
15313 (if table (mapcar 'list vals) vals)))
15315 (defun org-property-previous-allowed-value (&optional previous)
15316 "Switch to the next allowed value for this property."
15317 (interactive)
15318 (org-property-next-allowed-value t))
15320 (defun org-property-next-allowed-value (&optional previous)
15321 "Switch to the next allowed value for this property."
15322 (interactive)
15323 (unless (org-at-property-p)
15324 (error "Not at a property"))
15325 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15326 (key (match-string 2))
15327 (value (match-string 3))
15328 (allowed (or (org-property-get-allowed-values (point) key)
15329 (and (member value '("[ ]" "[-]" "[X]"))
15330 '("[ ]" "[X]"))))
15331 nval)
15332 (unless allowed
15333 (error "Allowed values for this property have not been defined"))
15334 (if previous (setq allowed (reverse allowed)))
15335 (if (member value allowed)
15336 (setq nval (car (cdr (member value allowed)))))
15337 (setq nval (or nval (car allowed)))
15338 (if (equal nval value)
15339 (error "Only one allowed value for this property"))
15340 (org-at-property-p)
15341 (replace-match (concat " :" key ": " nval) t t)
15342 (org-indent-line)
15343 (beginning-of-line 1)
15344 (skip-chars-forward " \t")
15345 (when (equal prop org-effort-property)
15346 (save-excursion
15347 (org-back-to-heading t)
15348 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15349 (run-hook-with-args 'org-property-changed-functions key nval)))
15351 (defun org-find-olp (path &optional this-buffer)
15352 "Return a marker pointing to the entry at outline path OLP.
15353 If anything goes wrong, throw an error.
15354 You can wrap this call to catch the error like this:
15356 (condition-case msg
15357 (org-mobile-locate-entry (match-string 4))
15358 (error (nth 1 msg)))
15360 The return value will then be either a string with the error message,
15361 or a marker if everything is OK.
15363 If THIS-BUFFER is set, the outline path does not contain a file,
15364 only headings."
15365 (let* ((file (if this-buffer buffer-file-name (pop path)))
15366 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15367 (level 1)
15368 (lmin 1)
15369 (lmax 1)
15370 limit re end found pos heading cnt flevel)
15371 (unless buffer (error "File not found :%s" file))
15372 (with-current-buffer buffer
15373 (save-excursion
15374 (save-restriction
15375 (widen)
15376 (setq limit (point-max))
15377 (goto-char (point-min))
15378 (while (setq heading (pop path))
15379 (setq re (format org-complex-heading-regexp-format
15380 (regexp-quote heading)))
15381 (setq cnt 0 pos (point))
15382 (while (re-search-forward re end t)
15383 (setq level (- (match-end 1) (match-beginning 1)))
15384 (if (and (>= level lmin) (<= level lmax))
15385 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15386 (when (= cnt 0) (error "Heading not found on level %d: %s"
15387 lmax heading))
15388 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15389 lmax heading))
15390 (goto-char found)
15391 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15392 (setq end (save-excursion (org-end-of-subtree t t))))
15393 (when (org-at-heading-p)
15394 (point-marker)))))))
15396 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15397 "Find node HEADING in BUFFER.
15398 Return a marker to the heading if it was found, or nil if not.
15399 If POS-ONLY is set, return just the position instead of a marker.
15401 The heading text must match exact, but it may have a TODO keyword,
15402 a priority cookie and tags in the standard locations."
15403 (with-current-buffer (or buffer (current-buffer))
15404 (save-excursion
15405 (save-restriction
15406 (widen)
15407 (goto-char (point-min))
15408 (let (case-fold-search)
15409 (if (re-search-forward
15410 (format org-complex-heading-regexp-format
15411 (regexp-quote heading)) nil t)
15412 (if pos-only
15413 (match-beginning 0)
15414 (move-marker (make-marker) (match-beginning 0)))))))))
15416 (defun org-find-exact-heading-in-directory (heading &optional dir)
15417 "Find Org node headline HEADING in all .org files in directory DIR.
15418 When the target headline is found, return a marker to this location."
15419 (let ((files (directory-files (or dir default-directory)
15420 nil "\\`[^.#].*\\.org\\'"))
15421 file visiting m buffer)
15422 (catch 'found
15423 (while (setq file (pop files))
15424 (message "trying %s" file)
15425 (setq visiting (org-find-base-buffer-visiting file))
15426 (setq buffer (or visiting (find-file-noselect file)))
15427 (setq m (org-find-exact-headline-in-buffer
15428 heading buffer))
15429 (when (and (not m) (not visiting)) (kill-buffer buffer))
15430 (and m (throw 'found m))))))
15432 (defun org-find-entry-with-id (ident)
15433 "Locate the entry that contains the ID property with exact value IDENT.
15434 IDENT can be a string, a symbol or a number, this function will search for
15435 the string representation of it.
15436 Return the position where this entry starts, or nil if there is no such entry."
15437 (interactive "sID: ")
15438 (let ((id (cond
15439 ((stringp ident) ident)
15440 ((symbol-name ident) (symbol-name ident))
15441 ((numberp ident) (number-to-string ident))
15442 (t (error "IDENT %s must be a string, symbol or number" ident))))
15443 (case-fold-search nil))
15444 (save-excursion
15445 (save-restriction
15446 (widen)
15447 (goto-char (point-min))
15448 (when (re-search-forward
15449 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15450 nil t)
15451 (org-back-to-heading t)
15452 (point))))))
15454 ;;;; Timestamps
15456 (defvar org-last-changed-timestamp nil)
15457 (defvar org-last-inserted-timestamp nil
15458 "The last time stamp inserted with `org-insert-time-stamp'.")
15459 (defvar org-time-was-given) ; dynamically scoped parameter
15460 (defvar org-end-time-was-given) ; dynamically scoped parameter
15461 (defvar org-ts-what) ; dynamically scoped parameter
15463 (defun org-time-stamp (arg &optional inactive)
15464 "Prompt for a date/time and insert a time stamp.
15465 If the user specifies a time like HH:MM or if this command is
15466 called with at least one prefix argument, the time stamp contains
15467 the date and the time. Otherwise, only the date is be included.
15469 All parts of a date not specified by the user is filled in from
15470 the current date/time. So if you just press return without
15471 typing anything, the time stamp will represent the current
15472 date/time.
15474 If there is already a timestamp at the cursor, it will be
15475 modified.
15477 With two universal prefix arguments, insert an active timestamp
15478 with the current time without prompting the user."
15479 (interactive "P")
15480 (let* ((ts nil)
15481 (default-time
15482 ;; Default time is either today, or, when entering a range,
15483 ;; the range start.
15484 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15485 (save-excursion
15486 (re-search-backward
15487 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15488 (- (point) 20) t)))
15489 (apply 'encode-time (org-parse-time-string (match-string 1)))
15490 (current-time)))
15491 (default-input (and ts (org-get-compact-tod ts)))
15492 (repeater (save-excursion
15493 (save-match-data
15494 (beginning-of-line)
15495 (when (re-search-forward
15496 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15497 (save-excursion (progn (end-of-line) (point))) t)
15498 (match-string 0)))))
15499 org-time-was-given org-end-time-was-given time)
15500 (cond
15501 ((and (org-at-timestamp-p t)
15502 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15503 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15504 (insert "--")
15505 (setq time (let ((this-command this-command))
15506 (org-read-date arg 'totime nil nil
15507 default-time default-input inactive)))
15508 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15509 ((org-at-timestamp-p t)
15510 (setq time (let ((this-command this-command))
15511 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15512 (when (org-at-timestamp-p t) ; just to get the match data
15513 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15514 (replace-match "")
15515 (setq org-last-changed-timestamp
15516 (org-insert-time-stamp
15517 time (or org-time-was-given arg)
15518 inactive nil nil (list org-end-time-was-given)))
15519 (when repeater (goto-char (1- (point))) (insert " " repeater)
15520 (setq org-last-changed-timestamp
15521 (concat (substring org-last-inserted-timestamp 0 -1)
15522 " " repeater ">"))))
15523 (message "Timestamp updated"))
15524 ((equal arg '(16))
15525 (org-insert-time-stamp (current-time) t))
15527 (setq time (let ((this-command this-command))
15528 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15529 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15530 nil nil (list org-end-time-was-given))))))
15532 ;; FIXME: can we use this for something else, like computing time differences?
15533 (defun org-get-compact-tod (s)
15534 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15535 (let* ((t1 (match-string 1 s))
15536 (h1 (string-to-number (match-string 2 s)))
15537 (m1 (string-to-number (match-string 3 s)))
15538 (t2 (and (match-end 4) (match-string 5 s)))
15539 (h2 (and t2 (string-to-number (match-string 6 s))))
15540 (m2 (and t2 (string-to-number (match-string 7 s))))
15541 dh dm)
15542 (if (not t2)
15544 (setq dh (- h2 h1) dm (- m2 m1))
15545 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15546 (concat t1 "+" (number-to-string dh)
15547 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15549 (defun org-time-stamp-inactive (&optional arg)
15550 "Insert an inactive time stamp.
15551 An inactive time stamp is enclosed in square brackets instead of angle
15552 brackets. It is inactive in the sense that it does not trigger agenda entries,
15553 does not link to the calendar and cannot be changed with the S-cursor keys.
15554 So these are more for recording a certain time/date."
15555 (interactive "P")
15556 (org-time-stamp arg 'inactive))
15558 (defvar org-date-ovl (make-overlay 1 1))
15559 (overlay-put org-date-ovl 'face 'org-date-selected)
15560 (org-detach-overlay org-date-ovl)
15562 (defvar org-ans1) ; dynamically scoped parameter
15563 (defvar org-ans2) ; dynamically scoped parameter
15565 (defvar org-plain-time-of-day-regexp) ; defined below
15567 (defvar org-overriding-default-time nil) ; dynamically scoped
15568 (defvar org-read-date-overlay nil)
15569 (defvar org-dcst nil) ; dynamically scoped
15570 (defvar org-read-date-history nil)
15571 (defvar org-read-date-final-answer nil)
15572 (defvar org-read-date-analyze-futurep nil)
15573 (defvar org-read-date-analyze-forced-year nil)
15574 (defvar org-read-date-inactive)
15576 (defvar org-read-date-minibuffer-local-map
15577 (let ((map (make-sparse-keymap)))
15578 (set-keymap-parent map minibuffer-local-map)
15579 (org-defkey map [(meta shift left)]
15580 (lambda () (interactive)
15581 (org-eval-in-calendar '(calendar-backward-month 1))))
15582 (org-defkey map [(meta shift right)]
15583 (lambda () (interactive)
15584 (org-eval-in-calendar '(calendar-forward-month 1))))
15585 (org-defkey map [(meta shift up)]
15586 (lambda () (interactive)
15587 (org-eval-in-calendar '(calendar-backward-year 1))))
15588 (org-defkey map [(meta shift down)]
15589 (lambda () (interactive)
15590 (org-eval-in-calendar '(calendar-forward-year 1))))
15591 (org-defkey map [?\e (shift left)]
15592 (lambda () (interactive)
15593 (org-eval-in-calendar '(calendar-backward-month 1))))
15594 (org-defkey map [?\e (shift right)]
15595 (lambda () (interactive)
15596 (org-eval-in-calendar '(calendar-forward-month 1))))
15597 (org-defkey map [?\e (shift up)]
15598 (lambda () (interactive)
15599 (org-eval-in-calendar '(calendar-backward-year 1))))
15600 (org-defkey map [?\e (shift down)]
15601 (lambda () (interactive)
15602 (org-eval-in-calendar '(calendar-forward-year 1))))
15603 (org-defkey map [(shift up)]
15604 (lambda () (interactive)
15605 (org-eval-in-calendar '(calendar-backward-week 1))))
15606 (org-defkey map [(shift down)]
15607 (lambda () (interactive)
15608 (org-eval-in-calendar '(calendar-forward-week 1))))
15609 (org-defkey map [(shift left)]
15610 (lambda () (interactive)
15611 (org-eval-in-calendar '(calendar-backward-day 1))))
15612 (org-defkey map [(shift right)]
15613 (lambda () (interactive)
15614 (org-eval-in-calendar '(calendar-forward-day 1))))
15615 (org-defkey map "?"
15616 (lambda () (interactive)
15617 (org-eval-in-calendar '(diary-view-entries))
15618 (message "")))
15619 (org-defkey map ">"
15620 (lambda () (interactive)
15621 (org-eval-in-calendar '(scroll-calendar-left 1))))
15622 (org-defkey map "<"
15623 (lambda () (interactive)
15624 (org-eval-in-calendar '(scroll-calendar-right 1))))
15625 (org-defkey map "\C-v"
15626 (lambda () (interactive)
15627 (org-eval-in-calendar
15628 '(calendar-scroll-left-three-months 1))))
15629 (org-defkey map "\M-v"
15630 (lambda () (interactive)
15631 (org-eval-in-calendar
15632 '(calendar-scroll-right-three-months 1))))
15633 map)
15634 "Keymap for minibuffer commands when using `org-read-date'.")
15636 (defun org-read-date (&optional org-with-time to-time from-string prompt
15637 default-time default-input inactive)
15638 "Read a date, possibly a time, and make things smooth for the user.
15639 The prompt will suggest to enter an ISO date, but you can also enter anything
15640 which will at least partially be understood by `parse-time-string'.
15641 Unrecognized parts of the date will default to the current day, month, year,
15642 hour and minute. If this command is called to replace a timestamp at point,
15643 or to enter the second timestamp of a range, the default time is taken
15644 from the existing stamp. Furthermore, the command prefers the future,
15645 so if you are giving a date where the year is not given, and the day-month
15646 combination is already past in the current year, it will assume you
15647 mean next year. For details, see the manual. A few examples:
15649 3-2-5 --> 2003-02-05
15650 feb 15 --> currentyear-02-15
15651 2/15 --> currentyear-02-15
15652 sep 12 9 --> 2009-09-12
15653 12:45 --> today 12:45
15654 22 sept 0:34 --> currentyear-09-22 0:34
15655 12 --> currentyear-currentmonth-12
15656 Fri --> nearest Friday (today or later)
15657 etc.
15659 Furthermore you can specify a relative date by giving, as the *first* thing
15660 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15661 change in days weeks, months, years.
15662 With a single plus or minus, the date is relative to today. With a double
15663 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15664 +4d --> four days from today
15665 +4 --> same as above
15666 +2w --> two weeks from today
15667 ++5 --> five days from default date
15669 The function understands only English month and weekday abbreviations.
15671 While prompting, a calendar is popped up - you can also select the
15672 date with the mouse (button 1). The calendar shows a period of three
15673 months. To scroll it to other months, use the keys `>' and `<'.
15674 If you don't like the calendar, turn it off with
15675 \(setq org-read-date-popup-calendar nil)
15677 With optional argument TO-TIME, the date will immediately be converted
15678 to an internal time.
15679 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15680 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15681 still enter a time, and this function will inform the calling routine
15682 about this change. The calling routine may then choose to change the
15683 format used to insert the time stamp into the buffer to include the time.
15684 With optional argument FROM-STRING, read from this string instead from
15685 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15686 the time/date that is used for everything that is not specified by the
15687 user."
15688 (require 'parse-time)
15689 (let* ((org-time-stamp-rounding-minutes
15690 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15691 (org-dcst org-display-custom-times)
15692 (ct (org-current-time))
15693 (org-def (or org-overriding-default-time default-time ct))
15694 (org-defdecode (decode-time org-def))
15695 (dummy (progn
15696 (when (< (nth 2 org-defdecode) org-extend-today-until)
15697 (setcar (nthcdr 2 org-defdecode) -1)
15698 (setcar (nthcdr 1 org-defdecode) 59)
15699 (setq org-def (apply 'encode-time org-defdecode)
15700 org-defdecode (decode-time org-def)))))
15701 (mouse-autoselect-window nil) ; Don't let the mouse jump
15702 (calendar-frame-setup nil)
15703 (calendar-setup nil)
15704 (calendar-move-hook nil)
15705 (calendar-view-diary-initially-flag nil)
15706 (calendar-view-holidays-initially-flag nil)
15707 (timestr (format-time-string
15708 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15709 (prompt (concat (if prompt (concat prompt " ") "")
15710 (format "Date+time [%s]: " timestr)))
15711 ans (org-ans0 "") org-ans1 org-ans2 final)
15713 (cond
15714 (from-string (setq ans from-string))
15715 (org-read-date-popup-calendar
15716 (save-excursion
15717 (save-window-excursion
15718 (calendar)
15719 (org-eval-in-calendar '(setq cursor-type nil) t)
15720 (unwind-protect
15721 (progn
15722 (calendar-forward-day (- (time-to-days org-def)
15723 (calendar-absolute-from-gregorian
15724 (calendar-current-date))))
15725 (org-eval-in-calendar nil t)
15726 (let* ((old-map (current-local-map))
15727 (map (copy-keymap calendar-mode-map))
15728 (minibuffer-local-map
15729 (copy-keymap org-read-date-minibuffer-local-map)))
15730 (org-defkey map (kbd "RET") 'org-calendar-select)
15731 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15732 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15733 (unwind-protect
15734 (progn
15735 (use-local-map map)
15736 (setq org-read-date-inactive inactive)
15737 (add-hook 'post-command-hook 'org-read-date-display)
15738 (setq org-ans0 (read-string prompt default-input
15739 'org-read-date-history nil))
15740 ;; org-ans0: from prompt
15741 ;; org-ans1: from mouse click
15742 ;; org-ans2: from calendar motion
15743 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15744 (remove-hook 'post-command-hook 'org-read-date-display)
15745 (use-local-map old-map)
15746 (when org-read-date-overlay
15747 (delete-overlay org-read-date-overlay)
15748 (setq org-read-date-overlay nil)))))
15749 (bury-buffer "*Calendar*")))))
15751 (t ; Naked prompt only
15752 (unwind-protect
15753 (setq ans (read-string prompt default-input
15754 'org-read-date-history timestr))
15755 (when org-read-date-overlay
15756 (delete-overlay org-read-date-overlay)
15757 (setq org-read-date-overlay nil)))))
15759 (setq final (org-read-date-analyze ans org-def org-defdecode))
15761 (when org-read-date-analyze-forced-year
15762 (message "Year was forced into %s"
15763 (if org-read-date-force-compatible-dates
15764 "compatible range (1970-2037)"
15765 "range representable on this machine"))
15766 (ding))
15768 ;; One round trip to get rid of 34th of August and stuff like that....
15769 (setq final (decode-time (apply 'encode-time final)))
15771 (setq org-read-date-final-answer ans)
15773 (if to-time
15774 (apply 'encode-time final)
15775 (if (and (boundp 'org-time-was-given) org-time-was-given)
15776 (format "%04d-%02d-%02d %02d:%02d"
15777 (nth 5 final) (nth 4 final) (nth 3 final)
15778 (nth 2 final) (nth 1 final))
15779 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15781 (defvar org-def)
15782 (defvar org-defdecode)
15783 (defvar org-with-time)
15784 (defun org-read-date-display ()
15785 "Display the current date prompt interpretation in the minibuffer."
15786 (when org-read-date-display-live
15787 (when org-read-date-overlay
15788 (delete-overlay org-read-date-overlay))
15789 (when (minibufferp (current-buffer))
15790 (save-excursion
15791 (end-of-line 1)
15792 (while (not (equal (buffer-substring
15793 (max (point-min) (- (point) 4)) (point))
15794 " "))
15795 (insert " ")))
15796 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15797 " " (or org-ans1 org-ans2)))
15798 (org-end-time-was-given nil)
15799 (f (org-read-date-analyze ans org-def org-defdecode))
15800 (fmts (if org-dcst
15801 org-time-stamp-custom-formats
15802 org-time-stamp-formats))
15803 (fmt (if (or org-with-time
15804 (and (boundp 'org-time-was-given) org-time-was-given))
15805 (cdr fmts)
15806 (car fmts)))
15807 (txt (format-time-string fmt (apply 'encode-time f)))
15808 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15809 (txt (concat "=> " txt)))
15810 (when (and org-end-time-was-given
15811 (string-match org-plain-time-of-day-regexp txt))
15812 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15813 org-end-time-was-given
15814 (substring txt (match-end 0)))))
15815 (when org-read-date-analyze-futurep
15816 (setq txt (concat txt " (=>F)")))
15817 (setq org-read-date-overlay
15818 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15819 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15821 (defun org-read-date-analyze (ans org-def org-defdecode)
15822 "Analyze the combined answer of the date prompt."
15823 ;; FIXME: cleanup and comment
15824 (let ((nowdecode (decode-time (current-time)))
15825 delta deltan deltaw deltadef year month day
15826 hour minute second wday pm h2 m2 tl wday1
15827 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15828 (setq org-read-date-analyze-futurep nil
15829 org-read-date-analyze-forced-year nil)
15830 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15831 (setq ans "+0"))
15833 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15834 (setq ans (replace-match "" t t ans)
15835 deltan (car delta)
15836 deltaw (nth 1 delta)
15837 deltadef (nth 2 delta)))
15839 ;; Check if there is an iso week date in there. If yes, store the
15840 ;; info and postpone interpreting it until the rest of the parsing
15841 ;; is done.
15842 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15843 (setq iso-year (if (match-end 1)
15844 (org-small-year-to-year
15845 (string-to-number (match-string 1 ans))))
15846 iso-weekday (if (match-end 3)
15847 (string-to-number (match-string 3 ans)))
15848 iso-week (string-to-number (match-string 2 ans)))
15849 (setq ans (replace-match "" t t ans)))
15851 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15852 (when (string-match
15853 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15854 (setq year (if (match-end 2)
15855 (string-to-number (match-string 2 ans))
15856 (progn (setq kill-year t)
15857 (string-to-number (format-time-string "%Y"))))
15858 month (string-to-number (match-string 3 ans))
15859 day (string-to-number (match-string 4 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)))
15864 ;; Help matching dotted european dates
15865 (when (string-match
15866 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15867 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15868 (setq kill-year t)
15869 (string-to-number (format-time-string "%Y")))
15870 day (string-to-number (match-string 1 ans))
15871 month (string-to-number (match-string 2 ans))
15872 ans (replace-match (format "%04d-%02d-%02d" year month day)
15873 t nil ans)))
15875 ;; Help matching american dates, like 5/30 or 5/30/7
15876 (when (string-match
15877 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15878 (setq year (if (match-end 4)
15879 (string-to-number (match-string 4 ans))
15880 (progn (setq kill-year t)
15881 (string-to-number (format-time-string "%Y"))))
15882 month (string-to-number (match-string 1 ans))
15883 day (string-to-number (match-string 2 ans)))
15884 (if (< year 100) (setq year (+ 2000 year)))
15885 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15886 t nil ans)))
15887 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15888 ;; If there is a time with am/pm, and *no* time without it, we convert
15889 ;; so that matching will be successful.
15890 (loop for i from 1 to 2 do ; twice, for end time as well
15891 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15892 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15893 (setq hour (string-to-number (match-string 1 ans))
15894 minute (if (match-end 3)
15895 (string-to-number (match-string 3 ans))
15897 pm (equal ?p
15898 (string-to-char (downcase (match-string 4 ans)))))
15899 (if (and (= hour 12) (not pm))
15900 (setq hour 0)
15901 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15902 (setq ans (replace-match (format "%02d:%02d" hour minute)
15903 t t ans))))
15905 ;; Check if a time range is given as a duration
15906 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15907 (setq hour (string-to-number (match-string 1 ans))
15908 h2 (+ hour (string-to-number (match-string 3 ans)))
15909 minute (string-to-number (match-string 2 ans))
15910 m2 (+ minute (if (match-end 5) (string-to-number
15911 (match-string 5 ans))0)))
15912 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15913 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15914 t t ans)))
15916 ;; Check if there is a time range
15917 (when (boundp 'org-end-time-was-given)
15918 (setq org-time-was-given nil)
15919 (when (and (string-match org-plain-time-of-day-regexp ans)
15920 (match-end 8))
15921 (setq org-end-time-was-given (match-string 8 ans))
15922 (setq ans (concat (substring ans 0 (match-beginning 7))
15923 (substring ans (match-end 7))))))
15925 (setq tl (parse-time-string ans)
15926 day (or (nth 3 tl) (nth 3 org-defdecode))
15927 month (or (nth 4 tl)
15928 (if (and org-read-date-prefer-future
15929 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15930 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15931 (nth 4 org-defdecode)))
15932 year (or (and (not kill-year) (nth 5 tl))
15933 (if (and org-read-date-prefer-future
15934 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15935 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15936 (nth 5 org-defdecode)))
15937 hour (or (nth 2 tl) (nth 2 org-defdecode))
15938 minute (or (nth 1 tl) (nth 1 org-defdecode))
15939 second (or (nth 0 tl) 0)
15940 wday (nth 6 tl))
15942 (when (and (eq org-read-date-prefer-future 'time)
15943 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15944 (equal day (nth 3 nowdecode))
15945 (equal month (nth 4 nowdecode))
15946 (equal year (nth 5 nowdecode))
15947 (nth 2 tl)
15948 (or (< (nth 2 tl) (nth 2 nowdecode))
15949 (and (= (nth 2 tl) (nth 2 nowdecode))
15950 (nth 1 tl)
15951 (< (nth 1 tl) (nth 1 nowdecode)))))
15952 (setq day (1+ day)
15953 futurep t))
15955 ;; Special date definitions below
15956 (cond
15957 (iso-week
15958 ;; There was an iso week
15959 (require 'cal-iso)
15960 (setq futurep nil)
15961 (setq year (or iso-year year)
15962 day (or iso-weekday wday 1)
15963 wday nil ; to make sure that the trigger below does not match
15964 iso-date (calendar-gregorian-from-absolute
15965 (calendar-absolute-from-iso
15966 (list iso-week day year))))
15967 ; FIXME: Should we also push ISO weeks into the future?
15968 ; (when (and org-read-date-prefer-future
15969 ; (not iso-year)
15970 ; (< (calendar-absolute-from-gregorian iso-date)
15971 ; (time-to-days (current-time))))
15972 ; (setq year (1+ year)
15973 ; iso-date (calendar-gregorian-from-absolute
15974 ; (calendar-absolute-from-iso
15975 ; (list iso-week day year)))))
15976 (setq month (car iso-date)
15977 year (nth 2 iso-date)
15978 day (nth 1 iso-date)))
15979 (deltan
15980 (setq futurep nil)
15981 (unless deltadef
15982 (let ((now (decode-time (current-time))))
15983 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15984 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15985 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15986 ((equal deltaw "m") (setq month (+ month deltan)))
15987 ((equal deltaw "y") (setq year (+ year deltan)))))
15988 ((and wday (not (nth 3 tl)))
15989 ;; Weekday was given, but no day, so pick that day in the week
15990 ;; on or after the derived date.
15991 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15992 (unless (equal wday wday1)
15993 (setq day (+ day (% (- wday wday1 -7) 7))))))
15994 (if (and (boundp 'org-time-was-given)
15995 (nth 2 tl))
15996 (setq org-time-was-given t))
15997 (if (< year 100) (setq year (+ 2000 year)))
15998 ;; Check of the date is representable
15999 (if org-read-date-force-compatible-dates
16000 (progn
16001 (if (< year 1970)
16002 (setq year 1970 org-read-date-analyze-forced-year t))
16003 (if (> year 2037)
16004 (setq year 2037 org-read-date-analyze-forced-year t)))
16005 (condition-case nil
16006 (ignore (encode-time second minute hour day month year))
16007 (error
16008 (setq year (nth 5 org-defdecode))
16009 (setq org-read-date-analyze-forced-year t))))
16010 (setq org-read-date-analyze-futurep futurep)
16011 (list second minute hour day month year)))
16013 (defvar parse-time-weekdays)
16014 (defun org-read-date-get-relative (s today default)
16015 "Check string S for special relative date string.
16016 TODAY and DEFAULT are internal times, for today and for a default.
16017 Return shift list (N what def-flag)
16018 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16019 N is the number of WHATs to shift.
16020 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16021 the DEFAULT date rather than TODAY."
16022 (require 'parse-time)
16023 (when (and
16024 (string-match
16025 (concat
16026 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16027 "\\([0-9]+\\)?"
16028 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16029 "\\([ \t]\\|$\\)") s)
16030 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16031 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16032 (string-to-char (substring (match-string 1 s) -1))
16033 ?+))
16034 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16035 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16036 (what (if (match-end 3) (match-string 3 s) "d"))
16037 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16038 (date (if rel default today))
16039 (wday (nth 6 (decode-time date)))
16040 delta)
16041 (if wday1
16042 (progn
16043 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16044 (if (= dir ?-) (setq delta (- delta 7)))
16045 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16046 (list delta "d" rel))
16047 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16049 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16050 "Turn a user-specified date into the internal representation.
16051 The internal representation needed by the calendar is (month day year).
16052 This is a wrapper to handle the brain-dead convention in calendar that
16053 user function argument order change dependent on argument order."
16054 (if (boundp 'calendar-date-style)
16055 (cond
16056 ((eq calendar-date-style 'american)
16057 (list arg1 arg2 arg3))
16058 ((eq calendar-date-style 'european)
16059 (list arg2 arg1 arg3))
16060 ((eq calendar-date-style 'iso)
16061 (list arg2 arg3 arg1)))
16062 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16063 (if (org-bound-and-true-p european-calendar-style)
16064 (list arg2 arg1 arg3)
16065 (list arg1 arg2 arg3)))))
16067 (defun org-eval-in-calendar (form &optional keepdate)
16068 "Eval FORM in the calendar window and return to current window.
16069 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16070 otherwise stick to the current value of `org-ans2'."
16071 (let ((sf (selected-frame))
16072 (sw (selected-window)))
16073 (select-window (get-buffer-window "*Calendar*" t))
16074 (eval form)
16075 (when (and (not keepdate) (calendar-cursor-to-date))
16076 (let* ((date (calendar-cursor-to-date))
16077 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16078 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16079 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16080 (select-window sw)
16081 (org-select-frame-set-input-focus sf)))
16083 (defun org-calendar-select ()
16084 "Return to `org-read-date' with the date currently selected.
16085 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16086 (interactive)
16087 (when (calendar-cursor-to-date)
16088 (let* ((date (calendar-cursor-to-date))
16089 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16090 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16091 (if (active-minibuffer-window) (exit-minibuffer))))
16093 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16094 "Insert a date stamp for the date given by the internal TIME.
16095 WITH-HM means use the stamp format that includes the time of the day.
16096 INACTIVE means use square brackets instead of angular ones, so that the
16097 stamp will not contribute to the agenda.
16098 PRE and POST are optional strings to be inserted before and after the
16099 stamp.
16100 The command returns the inserted time stamp."
16101 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16102 stamp)
16103 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16104 (insert-before-markers (or pre ""))
16105 (when (listp extra)
16106 (setq extra (car extra))
16107 (if (and (stringp extra)
16108 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16109 (setq extra (format "-%02d:%02d"
16110 (string-to-number (match-string 1 extra))
16111 (string-to-number (match-string 2 extra))))
16112 (setq extra nil)))
16113 (when extra
16114 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16115 (insert-before-markers (setq stamp (format-time-string fmt time)))
16116 (insert-before-markers (or post ""))
16117 (setq org-last-inserted-timestamp stamp)))
16119 (defun org-toggle-time-stamp-overlays ()
16120 "Toggle the use of custom time stamp formats."
16121 (interactive)
16122 (setq org-display-custom-times (not org-display-custom-times))
16123 (unless org-display-custom-times
16124 (let ((p (point-min)) (bmp (buffer-modified-p)))
16125 (while (setq p (next-single-property-change p 'display))
16126 (if (and (get-text-property p 'display)
16127 (eq (get-text-property p 'face) 'org-date))
16128 (remove-text-properties
16129 p (setq p (next-single-property-change p 'display))
16130 '(display t))))
16131 (set-buffer-modified-p bmp)))
16132 (if (featurep 'xemacs)
16133 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16134 (org-restart-font-lock)
16135 (setq org-table-may-need-update t)
16136 (if org-display-custom-times
16137 (message "Time stamps are overlaid with custom format")
16138 (message "Time stamp overlays removed")))
16140 (defun org-display-custom-time (beg end)
16141 "Overlay modified time stamp format over timestamp between BEG and END."
16142 (let* ((ts (buffer-substring beg end))
16143 t1 w1 with-hm tf time str w2 (off 0))
16144 (save-match-data
16145 (setq t1 (org-parse-time-string ts t))
16146 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16147 (setq off (- (match-end 0) (match-beginning 0)))))
16148 (setq end (- end off))
16149 (setq w1 (- end beg)
16150 with-hm (and (nth 1 t1) (nth 2 t1))
16151 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16152 time (org-fix-decoded-time t1)
16153 str (org-add-props
16154 (format-time-string
16155 (substring tf 1 -1) (apply 'encode-time time))
16156 nil 'mouse-face 'highlight)
16157 w2 (length str))
16158 (if (not (= w2 w1))
16159 (add-text-properties (1+ beg) (+ 2 beg)
16160 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16161 (if (featurep 'xemacs)
16162 (progn
16163 (put-text-property beg end 'invisible t)
16164 (put-text-property beg end 'end-glyph (make-glyph str)))
16165 (put-text-property beg end 'display str))))
16167 (defun org-translate-time (string)
16168 "Translate all timestamps in STRING to custom format.
16169 But do this only if the variable `org-display-custom-times' is set."
16170 (when org-display-custom-times
16171 (save-match-data
16172 (let* ((start 0)
16173 (re org-ts-regexp-both)
16174 t1 with-hm inactive tf time str beg end)
16175 (while (setq start (string-match re string start))
16176 (setq beg (match-beginning 0)
16177 end (match-end 0)
16178 t1 (save-match-data
16179 (org-parse-time-string (substring string beg end) t))
16180 with-hm (and (nth 1 t1) (nth 2 t1))
16181 inactive (equal (substring string beg (1+ beg)) "[")
16182 tf (funcall (if with-hm 'cdr 'car)
16183 org-time-stamp-custom-formats)
16184 time (org-fix-decoded-time t1)
16185 str (format-time-string
16186 (concat
16187 (if inactive "[" "<") (substring tf 1 -1)
16188 (if inactive "]" ">"))
16189 (apply 'encode-time time))
16190 string (replace-match str t t string)
16191 start (+ start (length str)))))))
16192 string)
16194 (defun org-fix-decoded-time (time)
16195 "Set 0 instead of nil for the first 6 elements of time.
16196 Don't touch the rest."
16197 (let ((n 0))
16198 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16200 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16202 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16203 "Difference between TIMESTAMP-STRING and now in days.
16204 If SECONDS is non-nil, return the difference in seconds."
16205 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16206 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16207 (funcall fdiff (current-time)))))
16209 (defun org-deadline-close (timestamp-string &optional ndays)
16210 "Is the time in TIMESTAMP-STRING close to the current date?"
16211 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16212 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16213 (not (org-entry-is-done-p))))
16215 (defun org-get-wdays (ts)
16216 "Get the deadline lead time appropriate for timestring TS."
16217 (cond
16218 ((<= org-deadline-warning-days 0)
16219 ;; 0 or negative, enforce this value no matter what
16220 (- org-deadline-warning-days))
16221 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16222 ;; lead time is specified.
16223 (floor (* (string-to-number (match-string 1 ts))
16224 (cdr (assoc (match-string 2 ts)
16225 '(("d" . 1) ("w" . 7)
16226 ("m" . 30.4) ("y" . 365.25)))))))
16227 ;; go for the default.
16228 (t org-deadline-warning-days)))
16230 (defun org-calendar-select-mouse (ev)
16231 "Return to `org-read-date' with the date currently selected.
16232 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16233 (interactive "e")
16234 (mouse-set-point ev)
16235 (when (calendar-cursor-to-date)
16236 (let* ((date (calendar-cursor-to-date))
16237 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16238 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16239 (if (active-minibuffer-window) (exit-minibuffer))))
16241 (defun org-check-deadlines (ndays)
16242 "Check if there are any deadlines due or past due.
16243 A deadline is considered due if it happens within `org-deadline-warning-days'
16244 days from today's date. If the deadline appears in an entry marked DONE,
16245 it is not shown. The prefix arg NDAYS can be used to test that many
16246 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16247 (interactive "P")
16248 (let* ((org-warn-days
16249 (cond
16250 ((equal ndays '(4)) 100000)
16251 (ndays (prefix-numeric-value ndays))
16252 (t (abs org-deadline-warning-days))))
16253 (case-fold-search nil)
16254 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16255 (callback
16256 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16258 (message "%d deadlines past-due or due within %d days"
16259 (org-occur regexp nil callback)
16260 org-warn-days)))
16262 (defsubst org-re-timestamp (type)
16263 "Return a regexp for timestamp TYPE.
16264 Allowed values for TYPE are:
16266 all: all timestamps
16267 active: only active timestamps (<...>)
16268 inactive: only inactive timestamps ([...])
16269 scheduled: only scheduled timestamps
16270 deadline: only deadline timestamps
16272 When TYPE is nil, fall back on returning a regexp that matches
16273 both scheduled and deadline timestamps."
16274 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16275 ((eq type 'active) org-ts-regexp)
16276 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16277 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16278 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16279 ((eq type 'scheduled-or-deadline)
16280 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16282 (defun org-check-before-date (date)
16283 "Check if there are deadlines or scheduled entries before DATE."
16284 (interactive (list (org-read-date)))
16285 (let ((case-fold-search nil)
16286 (regexp (org-re-timestamp org-ts-type))
16287 (callback
16288 (lambda () (time-less-p
16289 (org-time-string-to-time (match-string 1))
16290 (org-time-string-to-time date)))))
16291 (message "%d entries before %s"
16292 (org-occur regexp nil callback) date)))
16294 (defun org-check-after-date (date)
16295 "Check if there are deadlines or scheduled entries after DATE."
16296 (interactive (list (org-read-date)))
16297 (let ((case-fold-search nil)
16298 (regexp (org-re-timestamp org-ts-type))
16299 (callback
16300 (lambda () (not
16301 (time-less-p
16302 (org-time-string-to-time (match-string 1))
16303 (org-time-string-to-time date))))))
16304 (message "%d entries after %s"
16305 (org-occur regexp nil callback) date)))
16307 (defun org-check-dates-range (start-date end-date)
16308 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16309 (interactive (list (org-read-date nil nil nil "Range starts")
16310 (org-read-date nil nil nil "Range end")))
16311 (let ((case-fold-search nil)
16312 (regexp (org-re-timestamp org-ts-type))
16313 (callback
16314 (lambda ()
16315 (let ((match (match-string 1)))
16316 (and
16317 (not (time-less-p
16318 (org-time-string-to-time match)
16319 (org-time-string-to-time start-date)))
16320 (time-less-p
16321 (org-time-string-to-time match)
16322 (org-time-string-to-time end-date)))))))
16323 (message "%d entries between %s and %s"
16324 (org-occur regexp nil callback) start-date end-date)))
16326 (defun org-evaluate-time-range (&optional to-buffer)
16327 "Evaluate a time range by computing the difference between start and end.
16328 Normally the result is just printed in the echo area, but with prefix arg
16329 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16330 If the time range is actually in a table, the result is inserted into the
16331 next column.
16332 For time difference computation, a year is assumed to be exactly 365
16333 days in order to avoid rounding problems."
16334 (interactive "P")
16336 (org-clock-update-time-maybe)
16337 (save-excursion
16338 (unless (org-at-date-range-p t)
16339 (goto-char (point-at-bol))
16340 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16341 (if (not (org-at-date-range-p t))
16342 (error "Not at a time-stamp range, and none found in current line")))
16343 (let* ((ts1 (match-string 1))
16344 (ts2 (match-string 2))
16345 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16346 (match-end (match-end 0))
16347 (time1 (org-time-string-to-time ts1))
16348 (time2 (org-time-string-to-time ts2))
16349 (t1 (org-float-time time1))
16350 (t2 (org-float-time time2))
16351 (diff (abs (- t2 t1)))
16352 (negative (< (- t2 t1) 0))
16353 ;; (ys (floor (* 365 24 60 60)))
16354 (ds (* 24 60 60))
16355 (hs (* 60 60))
16356 (fy "%dy %dd %02d:%02d")
16357 (fy1 "%dy %dd")
16358 (fd "%dd %02d:%02d")
16359 (fd1 "%dd")
16360 (fh "%02d:%02d")
16361 y d h m align)
16362 (if havetime
16363 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16365 d (floor (/ diff ds)) diff (mod diff ds)
16366 h (floor (/ diff hs)) diff (mod diff hs)
16367 m (floor (/ diff 60)))
16368 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16370 d (floor (+ (/ diff ds) 0.5))
16371 h 0 m 0))
16372 (if (not to-buffer)
16373 (message "%s" (org-make-tdiff-string y d h m))
16374 (if (org-at-table-p)
16375 (progn
16376 (goto-char match-end)
16377 (setq align t)
16378 (and (looking-at " *|") (goto-char (match-end 0))))
16379 (goto-char match-end))
16380 (if (looking-at
16381 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16382 (replace-match ""))
16383 (if negative (insert " -"))
16384 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16385 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16386 (insert " " (format fh h m))))
16387 (if align (org-table-align))
16388 (message "Time difference inserted")))))
16390 (defun org-make-tdiff-string (y d h m)
16391 (let ((fmt "")
16392 (l nil))
16393 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16394 l (push y l)))
16395 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16396 l (push d l)))
16397 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16398 l (push h l)))
16399 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16400 l (push m l)))
16401 (apply 'format fmt (nreverse l))))
16403 (defun org-time-string-to-time (s &optional buffer pos)
16404 "Convert a timestamp string into internal time."
16405 (condition-case errdata
16406 (apply 'encode-time (org-parse-time-string s))
16407 (error (error "Bad timestamp `%s'%s\nError was: %s"
16408 s (if (not (and buffer pos))
16410 (format " at %d in buffer `%s'" pos buffer))
16411 (cdr errdata)))))
16413 (defun org-time-string-to-seconds (s)
16414 "Convert a timestamp string to a number of seconds."
16415 (org-float-time (org-time-string-to-time s)))
16417 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16418 "Convert a time stamp to an absolute day number.
16419 If there is a specifier for a cyclic time stamp, get the closest date to
16420 DAYNR.
16421 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16422 The variable date is bound by the calendar when this is called."
16423 (cond
16424 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16425 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16426 daynr
16427 (+ daynr 1000)))
16428 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16429 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16430 (time-to-days (current-time))) (match-string 0 s)
16431 prefer show-all))
16432 (t (time-to-days
16433 (condition-case errdata
16434 (apply 'encode-time (org-parse-time-string s))
16435 (error (error "Bad timestamp `%s'%s\nError was: %s"
16436 s (if (not (and buffer pos))
16438 (format " at %d in buffer `%s'" pos buffer))
16439 (cdr errdata))))))))
16441 (defun org-days-to-iso-week (days)
16442 "Return the iso week number."
16443 (require 'cal-iso)
16444 (car (calendar-iso-from-absolute days)))
16446 (defun org-small-year-to-year (year)
16447 "Convert 2-digit years into 4-digit years.
16448 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16449 The year 2000 cannot be abbreviated. Any year larger than 99
16450 is returned unchanged."
16451 (if (< year 38)
16452 (setq year (+ 2000 year))
16453 (if (< year 100)
16454 (setq year (+ 1900 year))))
16455 year)
16457 (defun org-time-from-absolute (d)
16458 "Return the time corresponding to date D.
16459 D may be an absolute day number, or a calendar-type list (month day year)."
16460 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16461 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16463 (defun org-calendar-holiday ()
16464 "List of holidays, for Diary display in Org-mode."
16465 (require 'holidays)
16466 (let ((hl (funcall
16467 (if (fboundp 'calendar-check-holidays)
16468 'calendar-check-holidays 'check-calendar-holidays) date)))
16469 (if hl (mapconcat 'identity hl "; "))))
16471 (defun org-diary-sexp-entry (sexp entry date)
16472 "Process a SEXP diary ENTRY for DATE."
16473 (require 'diary-lib)
16474 (let ((result (if calendar-debug-sexp
16475 (let ((stack-trace-on-error t))
16476 (eval (car (read-from-string sexp))))
16477 (condition-case nil
16478 (eval (car (read-from-string sexp)))
16479 (error
16480 (beep)
16481 (message "Bad sexp at line %d in %s: %s"
16482 (org-current-line)
16483 (buffer-file-name) sexp)
16484 (sleep-for 2))))))
16485 (cond ((stringp result) (split-string result "; "))
16486 ((and (consp result)
16487 (not (consp (cdr result)))
16488 (stringp (cdr result))) (cdr result))
16489 ((and (consp result)
16490 (stringp (car result))) result)
16491 (result entry))))
16493 (defun org-diary-to-ical-string (frombuf)
16494 "Get iCalendar entries from diary entries in buffer FROMBUF.
16495 This uses the icalendar.el library."
16496 (let* ((tmpdir (if (featurep 'xemacs)
16497 (temp-directory)
16498 temporary-file-directory))
16499 (tmpfile (make-temp-name
16500 (expand-file-name "orgics" tmpdir)))
16501 buf rtn b e)
16502 (with-current-buffer frombuf
16503 (icalendar-export-region (point-min) (point-max) tmpfile)
16504 (setq buf (find-buffer-visiting tmpfile))
16505 (set-buffer buf)
16506 (goto-char (point-min))
16507 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16508 (setq b (match-beginning 0)))
16509 (goto-char (point-max))
16510 (if (re-search-backward "^END:VEVENT" nil t)
16511 (setq e (match-end 0)))
16512 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16513 (kill-buffer buf)
16514 (delete-file tmpfile)
16515 rtn))
16517 (defun org-closest-date (start current change prefer show-all)
16518 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16519 When PREFER is `past', return a date that is either CURRENT or past.
16520 When PREFER is `future', return a date that is either CURRENT or future.
16521 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16522 ;; Make the proper lists from the dates
16523 (catch 'exit
16524 (let ((a1 '(("h" . hour)
16525 ("d" . day)
16526 ("w" . week)
16527 ("m" . month)
16528 ("y" . year)))
16529 (shour (nth 2 (org-parse-time-string start)))
16530 dn dw sday cday n1 n2 n0
16531 d m y y1 y2 date1 date2 nmonths nm ny m2)
16533 (setq start (org-date-to-gregorian start)
16534 current (org-date-to-gregorian
16535 (if show-all
16536 current
16537 (time-to-days (current-time))))
16538 sday (calendar-absolute-from-gregorian start)
16539 cday (calendar-absolute-from-gregorian current))
16541 (if (<= cday sday) (throw 'exit sday))
16543 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16544 (setq dn (string-to-number (match-string 1 change))
16545 dw (cdr (assoc (match-string 2 change) a1)))
16546 (error "Invalid change specifier: %s" change))
16547 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16548 (cond
16549 ((eq dw 'hour)
16550 (let ((missing-hours
16551 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16552 dn)))
16553 (setq n1 (if (zerop missing-hours) cday
16554 (- cday (1+ (floor (/ missing-hours 24)))))
16555 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16556 ((eq dw 'day)
16557 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16558 n2 (+ n1 dn)))
16559 ((eq dw 'year)
16560 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16561 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16562 (setq date1 (list m d y1)
16563 n1 (calendar-absolute-from-gregorian date1)
16564 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16565 n2 (calendar-absolute-from-gregorian date2)))
16566 ((eq dw 'month)
16567 ;; approx number of month between the two dates
16568 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16569 ;; How often does dn fit in there?
16570 (setq d (nth 1 start) m (car start) y (nth 2 start)
16571 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16572 m (+ m nm)
16573 ny (floor (/ m 12))
16574 y (+ y ny)
16575 m (- m (* ny 12)))
16576 (while (> m 12) (setq m (- m 12) y (1+ y)))
16577 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16578 (setq m2 (+ m dn) y2 y)
16579 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16580 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16581 (while (<= n2 cday)
16582 (setq n1 n2 m m2 y y2)
16583 (setq m2 (+ m dn) y2 y)
16584 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16585 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16586 ;; Make sure n1 is the earlier date
16587 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16588 (if show-all
16589 (cond
16590 ((eq prefer 'past) (if (= cday n2) n2 n1))
16591 ((eq prefer 'future) (if (= cday n1) n1 n2))
16592 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16593 (cond
16594 ((eq prefer 'past) (if (= cday n2) n2 n1))
16595 ((eq prefer 'future) (if (= cday n1) n1 n2))
16596 (t (if (= cday n1) n1 n2)))))))
16598 (defun org-date-to-gregorian (date)
16599 "Turn any specification of DATE into a Gregorian date for the calendar."
16600 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16601 ((and (listp date) (= (length date) 3)) date)
16602 ((stringp date)
16603 (setq date (org-parse-time-string date))
16604 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16605 ((listp date)
16606 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16608 (defun org-parse-time-string (s &optional nodefault)
16609 "Parse the standard Org-mode time string.
16610 This should be a lot faster than the normal `parse-time-string'.
16611 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16612 hour and minute fields will be nil if not given."
16613 (cond ((string-match org-ts-regexp0 s)
16614 (list 0
16615 (if (or (match-beginning 8) (not nodefault))
16616 (string-to-number (or (match-string 8 s) "0")))
16617 (if (or (match-beginning 7) (not nodefault))
16618 (string-to-number (or (match-string 7 s) "0")))
16619 (string-to-number (match-string 4 s))
16620 (string-to-number (match-string 3 s))
16621 (string-to-number (match-string 2 s))
16622 nil nil nil))
16623 ((string-match "^<[^>]+>$" s)
16624 (decode-time (seconds-to-time (org-matcher-time s))))
16625 (t (error "Not a standard Org-mode time string: %s" s))))
16627 (defun org-timestamp-up (&optional arg)
16628 "Increase the date item at the cursor by one.
16629 If the cursor is on the year, change the year. If it is on the month,
16630 the day or the time, change that.
16631 With prefix ARG, change by that many units."
16632 (interactive "p")
16633 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16635 (defun org-timestamp-down (&optional arg)
16636 "Decrease the date item at the cursor by one.
16637 If the cursor is on the year, change the year. If it is on the month,
16638 the day or the time, change that.
16639 With prefix ARG, change by that many units."
16640 (interactive "p")
16641 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16643 (defun org-timestamp-up-day (&optional arg)
16644 "Increase the date in the time stamp by one day.
16645 With prefix ARG, change that many days."
16646 (interactive "p")
16647 (if (and (not (org-at-timestamp-p t))
16648 (org-at-heading-p))
16649 (org-todo 'up)
16650 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16652 (defun org-timestamp-down-day (&optional arg)
16653 "Decrease the date in the time stamp by one day.
16654 With prefix ARG, change that many days."
16655 (interactive "p")
16656 (if (and (not (org-at-timestamp-p t))
16657 (org-at-heading-p))
16658 (org-todo 'down)
16659 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16661 (defun org-at-timestamp-p (&optional inactive-ok)
16662 "Determine if the cursor is in or at a timestamp."
16663 (interactive)
16664 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16665 (pos (point))
16666 (ans (or (looking-at tsr)
16667 (save-excursion
16668 (skip-chars-backward "^[<\n\r\t")
16669 (if (> (point) (point-min)) (backward-char 1))
16670 (and (looking-at tsr)
16671 (> (- (match-end 0) pos) -1))))))
16672 (and ans
16673 (boundp 'org-ts-what)
16674 (setq org-ts-what
16675 (cond
16676 ((= pos (match-beginning 0)) 'bracket)
16677 ;; Point is considered to be "on the bracket" whether
16678 ;; it's really on it or right after it.
16679 ((= pos (1- (match-end 0))) 'bracket)
16680 ((= pos (match-end 0)) 'after)
16681 ((org-pos-in-match-range pos 2) 'year)
16682 ((org-pos-in-match-range pos 3) 'month)
16683 ((org-pos-in-match-range pos 7) 'hour)
16684 ((org-pos-in-match-range pos 8) 'minute)
16685 ((or (org-pos-in-match-range pos 4)
16686 (org-pos-in-match-range pos 5)) 'day)
16687 ((and (> pos (or (match-end 8) (match-end 5)))
16688 (< pos (match-end 0)))
16689 (- pos (or (match-end 8) (match-end 5))))
16690 (t 'day))))
16691 ans))
16693 (defun org-toggle-timestamp-type ()
16694 "Toggle the type (<active> or [inactive]) of a time stamp."
16695 (interactive)
16696 (when (org-at-timestamp-p t)
16697 (let ((beg (match-beginning 0)) (end (match-end 0))
16698 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16699 (save-excursion
16700 (goto-char beg)
16701 (while (re-search-forward "[][<>]" end t)
16702 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16703 t t)))
16704 (message "Timestamp is now %sactive"
16705 (if (equal (char-after beg) ?<) "" "in")))))
16707 (defvar org-clock-history) ; defined in org-clock.el
16708 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16709 (defun org-timestamp-change (n &optional what updown)
16710 "Change the date in the time stamp at point.
16711 The date will be changed by N times WHAT. WHAT can be `day', `month',
16712 `year', `minute', `second'. If WHAT is not given, the cursor position
16713 in the timestamp determines what will be changed."
16714 (let ((origin (point)) origin-cat
16715 with-hm inactive
16716 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16717 org-ts-what
16718 extra rem
16719 ts time time0 fixnext clrgx)
16720 (if (not (org-at-timestamp-p t))
16721 (error "Not at a timestamp"))
16722 (if (and (not what) (eq org-ts-what 'bracket))
16723 (org-toggle-timestamp-type)
16724 ;; Point isn't on brackets. Remember the part of the time-stamp
16725 ;; the point was in. Indeed, size of time-stamps may change,
16726 ;; but point must be kept in the same category nonetheless.
16727 (setq origin-cat org-ts-what)
16728 (if (and (not what) (not (eq org-ts-what 'day))
16729 org-display-custom-times
16730 (get-text-property (point) 'display)
16731 (not (get-text-property (1- (point)) 'display)))
16732 (setq org-ts-what 'day))
16733 (setq org-ts-what (or what org-ts-what)
16734 inactive (= (char-after (match-beginning 0)) ?\[)
16735 ts (match-string 0))
16736 (replace-match "")
16737 (if (string-match
16738 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16740 (setq extra (match-string 1 ts)))
16741 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16742 (setq with-hm t))
16743 (setq time0 (org-parse-time-string ts))
16744 (when (and updown
16745 (eq org-ts-what 'minute)
16746 (not current-prefix-arg))
16747 ;; This looks like s-up and s-down. Change by one rounding step.
16748 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16749 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16750 (setcar (cdr time0) (+ (nth 1 time0)
16751 (if (> n 0) (- rem) (- dm rem))))))
16752 (setq time
16753 (encode-time (or (car time0) 0)
16754 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16755 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16756 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16757 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16758 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16759 (nthcdr 6 time0)))
16760 (when (and (member org-ts-what '(hour minute))
16761 extra
16762 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16763 (setq extra (org-modify-ts-extra
16764 extra
16765 (if (eq org-ts-what 'hour) 2 5)
16766 n dm)))
16767 (when (integerp org-ts-what)
16768 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16769 (if (eq what 'calendar)
16770 (let ((cal-date (org-get-date-from-calendar)))
16771 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16772 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16773 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16774 (setcar time0 (or (car time0) 0))
16775 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16776 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16777 (setq time (apply 'encode-time time0))))
16778 ;; Insert the new time-stamp, and ensure point stays in the same
16779 ;; category as before (i.e. not after the last position in that
16780 ;; category).
16781 (let ((pos (point)))
16782 ;; Stay before inserted string. `save-excursion' is of no use.
16783 (setq org-last-changed-timestamp
16784 (org-insert-time-stamp time with-hm inactive nil nil extra))
16785 (goto-char pos))
16786 (save-match-data
16787 (looking-at org-ts-regexp3)
16788 (goto-char (cond
16789 ;; `day' category ends before `hour' if any, or at
16790 ;; the end of the day name.
16791 ((eq origin-cat 'day)
16792 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16793 ((eq origin-cat 'hour) (min (match-end 7) origin))
16794 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16795 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16796 ;; `year' and `month' have both fixed size: point
16797 ;; couldn't have moved into another part.
16798 (t origin))))
16799 ;; Update clock if on a CLOCK line.
16800 (org-clock-update-time-maybe)
16801 ;; Maybe adjust the closest clock in `org-clock-history'
16802 (when org-clock-adjust-closest
16803 (if (not (and (org-at-clock-log-p)
16804 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16805 org-clock-history))))))
16806 (message "No clock to adjust")
16807 (cond ((save-excursion ; fix previous clock?
16808 (re-search-backward org-ts-regexp0 nil t)
16809 (org-looking-back (concat org-clock-string " \\[")))
16810 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16811 ((save-excursion ; fix next clock?
16812 (re-search-backward org-ts-regexp0 nil t)
16813 (looking-at (concat org-ts-regexp0 "\\] =>")))
16814 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16815 (save-window-excursion
16816 ;; Find closest clock to point, adjust the previous/next one in history
16817 (let* ((p (save-excursion (org-back-to-heading t)))
16818 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16819 (clfixnth
16820 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16821 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16822 (if (not clfixpos)
16823 (message "No clock to adjust")
16824 (save-excursion
16825 (org-goto-marker-or-bmk clfixpos)
16826 (org-show-subtree)
16827 (when (re-search-forward clrgx nil t)
16828 (goto-char (match-beginning 1))
16829 (let (org-clock-adjust-closest)
16830 (org-timestamp-change n org-ts-what updown))
16831 (message "Clock adjusted in %s for heading: %s"
16832 (file-name-nondirectory (buffer-file-name))
16833 (org-get-heading t t)))))))))
16834 ;; Try to recenter the calendar window, if any.
16835 (if (and org-calendar-follow-timestamp-change
16836 (get-buffer-window "*Calendar*" t)
16837 (memq org-ts-what '(day month year)))
16838 (org-recenter-calendar (time-to-days time))))))
16840 (defun org-modify-ts-extra (s pos n dm)
16841 "Change the different parts of the lead-time and repeat fields in timestamp."
16842 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16843 ng h m new rem)
16844 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16845 (cond
16846 ((or (org-pos-in-match-range pos 2)
16847 (org-pos-in-match-range pos 3))
16848 (setq m (string-to-number (match-string 3 s))
16849 h (string-to-number (match-string 2 s)))
16850 (if (org-pos-in-match-range pos 2)
16851 (setq h (+ h n))
16852 (setq n (* dm (org-no-warnings (signum n))))
16853 (when (not (= 0 (setq rem (% m dm))))
16854 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16855 (setq m (+ m n)))
16856 (if (< m 0) (setq m (+ m 60) h (1- h)))
16857 (if (> m 59) (setq m (- m 60) h (1+ h)))
16858 (setq h (min 24 (max 0 h)))
16859 (setq ng 1 new (format "-%02d:%02d" h m)))
16860 ((org-pos-in-match-range pos 6)
16861 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16862 ((org-pos-in-match-range pos 5)
16863 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16865 ((org-pos-in-match-range pos 9)
16866 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16867 ((org-pos-in-match-range pos 8)
16868 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16870 (when ng
16871 (setq s (concat
16872 (substring s 0 (match-beginning ng))
16874 (substring s (match-end ng))))))
16877 (defun org-recenter-calendar (date)
16878 "If the calendar is visible, recenter it to DATE."
16879 (let ((cwin (get-buffer-window "*Calendar*" t)))
16880 (when cwin
16881 (let ((calendar-move-hook nil))
16882 (with-selected-window cwin
16883 (calendar-goto-date (if (listp date) date
16884 (calendar-gregorian-from-absolute date))))))))
16886 (defun org-goto-calendar (&optional arg)
16887 "Go to the Emacs calendar at the current date.
16888 If there is a time stamp in the current line, go to that date.
16889 A prefix ARG can be used to force the current date."
16890 (interactive "P")
16891 (let ((tsr org-ts-regexp) diff
16892 (calendar-move-hook nil)
16893 (calendar-view-holidays-initially-flag nil)
16894 (calendar-view-diary-initially-flag nil))
16895 (if (or (org-at-timestamp-p)
16896 (save-excursion
16897 (beginning-of-line 1)
16898 (looking-at (concat ".*" tsr))))
16899 (let ((d1 (time-to-days (current-time)))
16900 (d2 (time-to-days
16901 (org-time-string-to-time (match-string 1)))))
16902 (setq diff (- d2 d1))))
16903 (calendar)
16904 (calendar-goto-today)
16905 (if (and diff (not arg)) (calendar-forward-day diff))))
16907 (defun org-get-date-from-calendar ()
16908 "Return a list (month day year) of date at point in calendar."
16909 (with-current-buffer "*Calendar*"
16910 (save-match-data
16911 (calendar-cursor-to-date))))
16913 (defun org-date-from-calendar ()
16914 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16915 If there is already a time stamp at the cursor position, update it."
16916 (interactive)
16917 (if (org-at-timestamp-p t)
16918 (org-timestamp-change 0 'calendar)
16919 (let ((cal-date (org-get-date-from-calendar)))
16920 (org-insert-time-stamp
16921 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16923 (defcustom org-effort-durations
16924 `(("h" . 60)
16925 ("d" . ,(* 60 8))
16926 ("w" . ,(* 60 8 5))
16927 ("m" . ,(* 60 8 5 4))
16928 ("y" . ,(* 60 8 5 40)))
16929 "Conversion factor to minutes for an effort modifier.
16931 Each entry has the form (MODIFIER . MINUTES).
16933 In an effort string, a number followed by MODIFIER is multiplied
16934 by the specified number of MINUTES to obtain an effort in
16935 minutes.
16937 For example, if the value of this variable is ((\"hours\" . 60)), then an
16938 effort string \"2hours\" is equivalent to 120 minutes."
16939 :group 'org-agenda
16940 :version "24.1"
16941 :type '(alist :key-type (string :tag "Modifier")
16942 :value-type (number :tag "Minutes")))
16944 (defun org-minutes-to-clocksum-string (m)
16945 "Format number of minutes as a clocksum string.
16946 The format is determined by `org-time-clocksum-format',
16947 `org-time-clocksum-use-fractional' and
16948 `org-time-clocksum-fractional-format' and
16949 `org-time-clocksum-use-effort-durations'."
16950 (let ((clocksum "") h d w mo y fmt n)
16951 (setq h (if org-time-clocksum-use-effort-durations
16952 (cdr (assoc "h" org-effort-durations)) 60)
16953 d (if org-time-clocksum-use-effort-durations
16954 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
16955 w (if org-time-clocksum-use-effort-durations
16956 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
16957 mo (if org-time-clocksum-use-effort-durations
16958 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
16959 y (if org-time-clocksum-use-effort-durations
16960 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
16961 ;; fractional format
16962 (if org-time-clocksum-use-fractional
16963 (cond
16964 ;; single format string
16965 ((stringp org-time-clocksum-fractional-format)
16966 (format org-time-clocksum-fractional-format (/ m (float h))))
16967 ;; choice of fractional formats for different time units
16968 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16969 (> (/ (truncate m) (* y d h)) 0))
16970 (format fmt (/ m (* y d (float h)))))
16971 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16972 (> (/ (truncate m) (* mo d h)) 0))
16973 (format fmt (/ m (* mo d (float h)))))
16974 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16975 (> (/ (truncate m) (* w d h)) 0))
16976 (format fmt (/ m (* w d (float h)))))
16977 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16978 (> (/ (truncate m) (* d h)) 0))
16979 (format fmt (/ m (* d (float h)))))
16980 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16981 (> (/ (truncate m) h) 0))
16982 (format fmt (/ m (float h))))
16983 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16984 (format fmt m))
16985 ;; fall back to smallest time unit with a format
16986 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16987 (format fmt (/ m (float h))))
16988 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16989 (format fmt (/ m (* d (float h)))))
16990 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16991 (format fmt (/ m (* w d (float h)))))
16992 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16993 (format fmt (/ m (* mo d (float h)))))
16994 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16995 (format fmt (/ m (* y d (float h))))))
16996 ;; standard (non-fractional) format, with single format string
16997 (if (stringp org-time-clocksum-format)
16998 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
16999 ;; separate formats components
17000 (and (setq fmt (plist-get org-time-clocksum-format :years))
17001 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17002 (plist-get org-time-clocksum-format :require-years))
17003 (setq clocksum (concat clocksum (format fmt n))
17004 m (- m (* n y d h))))
17005 (and (setq fmt (plist-get org-time-clocksum-format :months))
17006 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17007 (plist-get org-time-clocksum-format :require-months))
17008 (setq clocksum (concat clocksum (format fmt n))
17009 m (- m (* n mo d h))))
17010 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17011 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17012 (plist-get org-time-clocksum-format :require-weeks))
17013 (setq clocksum (concat clocksum (format fmt n))
17014 m (- m (* n w d h))))
17015 (and (setq fmt (plist-get org-time-clocksum-format :days))
17016 (or (> (setq n (/ (truncate m) (* d h))) 0)
17017 (plist-get org-time-clocksum-format :require-days))
17018 (setq clocksum (concat clocksum (format fmt n))
17019 m (- m (* n d h))))
17020 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17021 (or (> (setq n (/ (truncate m) h)) 0)
17022 (plist-get org-time-clocksum-format :require-hours))
17023 (setq clocksum (concat clocksum (format fmt n))
17024 m (- m (* n h))))
17025 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17026 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17027 (setq clocksum (concat clocksum (format fmt m))))
17028 ;; return formatted time duration
17029 clocksum))))
17031 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17032 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17033 "Org mode version 8.0")
17035 (defun org-hours-to-clocksum-string (n)
17036 (org-minutes-to-clocksum-string (* n 60)))
17038 (defun org-hh:mm-string-to-minutes (s)
17039 "Convert a string H:MM to a number of minutes.
17040 If the string is just a number, interpret it as minutes.
17041 In fact, the first hh:mm or number in the string will be taken,
17042 there can be extra stuff in the string.
17043 If no number is found, the return value is 0."
17044 (cond
17045 ((integerp s) s)
17046 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17047 (+ (* (string-to-number (match-string 1 s)) 60)
17048 (string-to-number (match-string 2 s))))
17049 ((string-match "\\([0-9]+\\)" s)
17050 (string-to-number (match-string 1 s)))
17051 (t 0)))
17053 (defcustom org-image-actual-width t
17054 "Should we use the actual width of images when inlining them?
17056 When set to `t', always use the image width.
17058 When set to a number, use imagemagick (when available) to set
17059 the image's width to this value.
17061 When set to a number in a list, try to get the width from the
17062 #+ATTR.* keyword if it matches a width specification like
17063 width=\"[0-9]+\", and fall back on that number if none is found.
17065 When set to nil, try to get the width from an #+ATTR.* keyword
17066 and fall back on the original width if none is found.
17068 This requires Emacs >= 24.1, build with imagemagick support."
17069 :group 'org-appearance
17070 :version "24.3"
17071 :type '(choice
17072 (const :tag "Use the image width" t)
17073 (integer :tag "Use a number of pixels")
17074 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17075 (const :tag "Use #+ATTR* or don't resize" nil)))
17077 (defcustom org-agenda-inhibit-startup t
17078 "Inhibit startup when preparing agenda buffers.
17079 When this variable is `t' (the default), the initialization of
17080 the Org agenda buffers is inhibited: e.g. the visibility state
17081 is not set, the tables are not re-aligned, etc."
17082 :type 'boolean
17083 :version "24.3"
17084 :group 'org-agenda)
17086 (defun org-duration-string-to-minutes (s &optional output-to-string)
17087 "Convert a duration string S to minutes.
17089 A bare number is interpreted as minutes, modifiers can be set by
17090 customizing `org-effort-durations' (which see).
17092 Entries containing a colon are interpreted as H:MM by
17093 `org-hh:mm-string-to-minutes'."
17094 (let ((result 0)
17095 (re (concat "\\([0-9.]+\\) *\\("
17096 (regexp-opt (mapcar 'car org-effort-durations))
17097 "\\)")))
17098 (while (string-match re s)
17099 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17100 (string-to-number (match-string 1 s))))
17101 (setq s (replace-match "" nil t s)))
17102 (setq result (floor result))
17103 (incf result (org-hh:mm-string-to-minutes s))
17104 (if output-to-string (number-to-string result) result)))
17106 ;;;; Files
17108 (defun org-save-all-org-buffers ()
17109 "Save all Org-mode buffers without user confirmation."
17110 (interactive)
17111 (message "Saving all Org-mode buffers...")
17112 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17113 (when (featurep 'org-id) (org-id-locations-save))
17114 (message "Saving all Org-mode buffers... done"))
17116 (defun org-revert-all-org-buffers ()
17117 "Revert all Org-mode buffers.
17118 Prompt for confirmation when there are unsaved changes.
17119 Be sure you know what you are doing before letting this function
17120 overwrite your changes.
17122 This function is useful in a setup where one tracks org files
17123 with a version control system, to revert on one machine after pulling
17124 changes from another. I believe the procedure must be like this:
17126 1. M-x org-save-all-org-buffers
17127 2. Pull changes from the other machine, resolve conflicts
17128 3. M-x org-revert-all-org-buffers"
17129 (interactive)
17130 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17131 (error "Abort"))
17132 (save-excursion
17133 (save-window-excursion
17134 (mapc
17135 (lambda (b)
17136 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17137 (with-current-buffer b buffer-file-name))
17138 (org-pop-to-buffer-same-window b)
17139 (revert-buffer t 'no-confirm)))
17140 (buffer-list))
17141 (when (and (featurep 'org-id) org-id-track-globally)
17142 (org-id-locations-load)))))
17144 ;;;; Agenda files
17146 ;;;###autoload
17147 (defun org-switchb (&optional arg)
17148 "Switch between Org buffers.
17149 With one prefix argument, restrict available buffers to files.
17150 With two prefix arguments, restrict available buffers to agenda files.
17152 Defaults to `iswitchb' for buffer name completion.
17153 Set `org-completion-use-ido' to make it use ido instead."
17154 (interactive "P")
17155 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17156 ((equal arg '(16)) (org-buffer-list 'agenda))
17157 (t (org-buffer-list))))
17158 (org-completion-use-iswitchb org-completion-use-iswitchb)
17159 (org-completion-use-ido org-completion-use-ido))
17160 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17161 (setq org-completion-use-iswitchb t))
17162 (org-pop-to-buffer-same-window
17163 (org-icompleting-read "Org buffer: "
17164 (mapcar 'list (mapcar 'buffer-name blist))
17165 nil t))))
17167 ;;; Define some older names previously used for this functionality
17168 ;;;###autoload
17169 (defalias 'org-ido-switchb 'org-switchb)
17170 ;;;###autoload
17171 (defalias 'org-iswitchb 'org-switchb)
17173 (defun org-buffer-list (&optional predicate exclude-tmp)
17174 "Return a list of Org buffers.
17175 PREDICATE can be `export', `files' or `agenda'.
17177 export restrict the list to Export buffers.
17178 files restrict the list to buffers visiting Org files.
17179 agenda restrict the list to buffers visiting agenda files.
17181 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17182 (let* ((bfn nil)
17183 (agenda-files (and (eq predicate 'agenda)
17184 (mapcar 'file-truename (org-agenda-files t))))
17185 (filter
17186 (cond
17187 ((eq predicate 'files)
17188 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17189 ((eq predicate 'export)
17190 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17191 ((eq predicate 'agenda)
17192 (lambda (b)
17193 (with-current-buffer b
17194 (and (derived-mode-p 'org-mode)
17195 (setq bfn (buffer-file-name b))
17196 (member (file-truename bfn) agenda-files)))))
17197 (t (lambda (b) (with-current-buffer b
17198 (or (derived-mode-p 'org-mode)
17199 (string-match "\*Org .*Export"
17200 (buffer-name b)))))))))
17201 (delq nil
17202 (mapcar
17203 (lambda(b)
17204 (if (and (funcall filter b)
17205 (or (not exclude-tmp)
17206 (not (string-match "tmp" (buffer-name b)))))
17208 nil))
17209 (buffer-list)))))
17211 (defun org-agenda-files (&optional unrestricted archives)
17212 "Get the list of agenda files.
17213 Optional UNRESTRICTED means return the full list even if a restriction
17214 is currently in place.
17215 When ARCHIVES is t, include all archive files that are really being
17216 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17217 `org-agenda-archives-mode' is t."
17218 (let ((files
17219 (cond
17220 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17221 ((stringp org-agenda-files) (org-read-agenda-file-list))
17222 ((listp org-agenda-files) org-agenda-files)
17223 (t (error "Invalid value of `org-agenda-files'")))))
17224 (setq files (apply 'append
17225 (mapcar (lambda (f)
17226 (if (file-directory-p f)
17227 (directory-files
17228 f t org-agenda-file-regexp)
17229 (list f)))
17230 files)))
17231 (when org-agenda-skip-unavailable-files
17232 (setq files (delq nil
17233 (mapcar (function
17234 (lambda (file)
17235 (and (file-readable-p file) file)))
17236 files))))
17237 (when (or (eq archives t)
17238 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17239 (setq files (org-add-archive-files files)))
17240 files))
17242 (defun org-agenda-file-p (&optional file)
17243 "Return non-nil, if FILE is an agenda file.
17244 If FILE is omitted, use the file associated with the current
17245 buffer."
17246 (member (or file (buffer-file-name))
17247 (org-agenda-files t)))
17249 (defun org-edit-agenda-file-list ()
17250 "Edit the list of agenda files.
17251 Depending on setup, this either uses customize to edit the variable
17252 `org-agenda-files', or it visits the file that is holding the list. In the
17253 latter case, the buffer is set up in a way that saving it automatically kills
17254 the buffer and restores the previous window configuration."
17255 (interactive)
17256 (if (stringp org-agenda-files)
17257 (let ((cw (current-window-configuration)))
17258 (find-file org-agenda-files)
17259 (org-set-local 'org-window-configuration cw)
17260 (org-add-hook 'after-save-hook
17261 (lambda ()
17262 (set-window-configuration
17263 (prog1 org-window-configuration
17264 (kill-buffer (current-buffer))))
17265 (org-install-agenda-files-menu)
17266 (message "New agenda file list installed"))
17267 nil 'local)
17268 (message "%s" (substitute-command-keys
17269 "Edit list and finish with \\[save-buffer]")))
17270 (customize-variable 'org-agenda-files)))
17272 (defun org-store-new-agenda-file-list (list)
17273 "Set new value for the agenda file list and save it correctly."
17274 (if (stringp org-agenda-files)
17275 (let ((fe (org-read-agenda-file-list t)) b u)
17276 (while (setq b (find-buffer-visiting org-agenda-files))
17277 (kill-buffer b))
17278 (with-temp-file org-agenda-files
17279 (insert
17280 (mapconcat
17281 (lambda (f) ;; Keep un-expanded entries.
17282 (if (setq u (assoc f fe))
17283 (cdr u)
17285 list "\n")
17286 "\n")))
17287 (let ((org-mode-hook nil) (org-inhibit-startup t)
17288 (org-insert-mode-line-in-empty-file nil))
17289 (setq org-agenda-files list)
17290 (customize-save-variable 'org-agenda-files org-agenda-files))))
17292 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17293 "Read the list of agenda files from a file.
17294 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17295 filenames, used by `org-store-new-agenda-file-list' to write back
17296 un-expanded file names."
17297 (when (file-directory-p org-agenda-files)
17298 (error "`org-agenda-files' cannot be a single directory"))
17299 (when (stringp org-agenda-files)
17300 (with-temp-buffer
17301 (insert-file-contents org-agenda-files)
17302 (mapcar
17303 (lambda (f)
17304 (let ((e (expand-file-name (substitute-in-file-name f)
17305 org-directory)))
17306 (if pair-with-expansion
17307 (cons e f)
17308 e)))
17309 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17311 ;;;###autoload
17312 (defun org-cycle-agenda-files ()
17313 "Cycle through the files in `org-agenda-files'.
17314 If the current buffer visits an agenda file, find the next one in the list.
17315 If the current buffer does not, find the first agenda file."
17316 (interactive)
17317 (let* ((fs (org-agenda-files t))
17318 (files (append fs (list (car fs))))
17319 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17320 file)
17321 (unless files (error "No agenda files"))
17322 (catch 'exit
17323 (while (setq file (pop files))
17324 (if (equal (file-truename file) tcf)
17325 (when (car files)
17326 (find-file (car files))
17327 (throw 'exit t))))
17328 (find-file (car fs)))
17329 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17331 (defun org-agenda-file-to-front (&optional to-end)
17332 "Move/add the current file to the top of the agenda file list.
17333 If the file is not present in the list, it is added to the front. If it is
17334 present, it is moved there. With optional argument TO-END, add/move to the
17335 end of the list."
17336 (interactive "P")
17337 (let ((org-agenda-skip-unavailable-files nil)
17338 (file-alist (mapcar (lambda (x)
17339 (cons (file-truename x) x))
17340 (org-agenda-files t)))
17341 (ctf (file-truename
17342 (or buffer-file-name
17343 (error "Please save the current buffer to a file"))))
17344 x had)
17345 (setq x (assoc ctf file-alist) had x)
17347 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17348 (if to-end
17349 (setq file-alist (append (delq x file-alist) (list x)))
17350 (setq file-alist (cons x (delq x file-alist))))
17351 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17352 (org-install-agenda-files-menu)
17353 (message "File %s to %s of agenda file list"
17354 (if had "moved" "added") (if to-end "end" "front"))))
17356 (defun org-remove-file (&optional file)
17357 "Remove current file from the list of files in variable `org-agenda-files'.
17358 These are the files which are being checked for agenda entries.
17359 Optional argument FILE means use this file instead of the current."
17360 (interactive)
17361 (let* ((org-agenda-skip-unavailable-files nil)
17362 (file (or file buffer-file-name
17363 (error "Current buffer does not visit a file")))
17364 (true-file (file-truename file))
17365 (afile (abbreviate-file-name file))
17366 (files (delq nil (mapcar
17367 (lambda (x)
17368 (if (equal true-file
17369 (file-truename x))
17370 nil x))
17371 (org-agenda-files t)))))
17372 (if (not (= (length files) (length (org-agenda-files t))))
17373 (progn
17374 (org-store-new-agenda-file-list files)
17375 (org-install-agenda-files-menu)
17376 (message "Removed file: %s" afile))
17377 (message "File was not in list: %s (not removed)" afile))))
17379 (defun org-file-menu-entry (file)
17380 (vector file (list 'find-file file) t))
17382 (defun org-check-agenda-file (file)
17383 "Make sure FILE exists. If not, ask user what to do."
17384 (when (not (file-exists-p file))
17385 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17386 (abbreviate-file-name file))
17387 (let ((r (downcase (read-char-exclusive))))
17388 (cond
17389 ((equal r ?r)
17390 (org-remove-file file)
17391 (throw 'nextfile t))
17392 (t (error "Abort"))))))
17394 (defun org-get-agenda-file-buffer (file)
17395 "Get a buffer visiting FILE. If the buffer needs to be created, add
17396 it to the list of buffers which might be released later."
17397 (let ((buf (org-find-base-buffer-visiting file)))
17398 (if buf
17399 buf ; just return it
17400 ;; Make a new buffer and remember it
17401 (setq buf (find-file-noselect file))
17402 (if buf (push buf org-agenda-new-buffers))
17403 buf)))
17405 (defun org-release-buffers (blist)
17406 "Release all buffers in list, asking the user for confirmation when needed.
17407 When a buffer is unmodified, it is just killed. When modified, it is saved
17408 \(if the user agrees) and then killed."
17409 (let (buf file)
17410 (while (setq buf (pop blist))
17411 (setq file (buffer-file-name buf))
17412 (when (and (buffer-modified-p buf)
17413 file
17414 (y-or-n-p (format "Save file %s? " file)))
17415 (with-current-buffer buf (save-buffer)))
17416 (kill-buffer buf))))
17418 (defun org-agenda-prepare-buffers (files)
17419 "Create buffers for all agenda files, protect archived trees and comments."
17420 (interactive)
17421 (let ((pa '(:org-archived t))
17422 (pc '(:org-comment t))
17423 (pall '(:org-archived t :org-comment t))
17424 (inhibit-read-only t)
17425 (org-inhibit-startup org-agenda-inhibit-startup)
17426 (rea (concat ":" org-archive-tag ":"))
17427 bmp file re)
17428 (save-excursion
17429 (save-restriction
17430 (while (setq file (pop files))
17431 (catch 'nextfile
17432 (if (bufferp file)
17433 (set-buffer file)
17434 (org-check-agenda-file file)
17435 (set-buffer (org-get-agenda-file-buffer file)))
17436 (widen)
17437 (setq bmp (buffer-modified-p))
17438 (org-refresh-category-properties)
17439 (org-refresh-properties org-effort-property 'org-effort)
17440 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17441 (setq org-todo-keywords-for-agenda
17442 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17443 (setq org-done-keywords-for-agenda
17444 (append org-done-keywords-for-agenda org-done-keywords))
17445 (setq org-todo-keyword-alist-for-agenda
17446 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17447 (setq org-drawers-for-agenda
17448 (append org-drawers-for-agenda org-drawers))
17449 (setq org-tag-alist-for-agenda
17450 (append org-tag-alist-for-agenda org-tag-alist))
17452 (save-excursion
17453 (remove-text-properties (point-min) (point-max) pall)
17454 (when org-agenda-skip-archived-trees
17455 (goto-char (point-min))
17456 (while (re-search-forward rea nil t)
17457 (if (org-at-heading-p t)
17458 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17459 (goto-char (point-min))
17460 (setq re (format org-heading-keyword-regexp-format
17461 org-comment-string))
17462 (while (re-search-forward re nil t)
17463 (add-text-properties
17464 (match-beginning 0) (org-end-of-subtree t) pc)))
17465 (set-buffer-modified-p bmp)))))
17466 (setq org-todo-keywords-for-agenda
17467 (org-uniquify org-todo-keywords-for-agenda))
17468 (setq org-todo-keyword-alist-for-agenda
17469 (org-uniquify org-todo-keyword-alist-for-agenda)
17470 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17472 ;;;; Embedded LaTeX
17474 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17475 "Keymap for the minor `org-cdlatex-mode'.")
17477 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17478 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17479 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17480 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17481 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17483 (defvar org-cdlatex-texmathp-advice-is-done nil
17484 "Flag remembering if we have applied the advice to texmathp already.")
17486 (define-minor-mode org-cdlatex-mode
17487 "Toggle the minor `org-cdlatex-mode'.
17488 This mode supports entering LaTeX environment and math in LaTeX fragments
17489 in Org-mode.
17490 \\{org-cdlatex-mode-map}"
17491 nil " OCDL" nil
17492 (when org-cdlatex-mode
17493 (require 'cdlatex)
17494 (run-hooks 'cdlatex-mode-hook)
17495 (cdlatex-compute-tables))
17496 (unless org-cdlatex-texmathp-advice-is-done
17497 (setq org-cdlatex-texmathp-advice-is-done t)
17498 (defadvice texmathp (around org-math-always-on activate)
17499 "Always return t in org-mode buffers.
17500 This is because we want to insert math symbols without dollars even outside
17501 the LaTeX math segments. If Orgmode thinks that point is actually inside
17502 an embedded LaTeX fragment, let texmathp do its job.
17503 \\[org-cdlatex-mode-map]"
17504 (interactive)
17505 (let (p)
17506 (cond
17507 ((not (derived-mode-p 'org-mode)) ad-do-it)
17508 ((eq this-command 'cdlatex-math-symbol)
17509 (setq ad-return-value t
17510 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17512 (let ((p (org-inside-LaTeX-fragment-p)))
17513 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17514 (setq ad-return-value t
17515 texmathp-why '("Org-mode embedded math" . 0))
17516 (if p ad-do-it)))))))))
17518 (defun turn-on-org-cdlatex ()
17519 "Unconditionally turn on `org-cdlatex-mode'."
17520 (org-cdlatex-mode 1))
17522 (defun org-inside-LaTeX-fragment-p ()
17523 "Test if point is inside a LaTeX fragment.
17524 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17525 sequence appearing also before point.
17526 Even though the matchers for math are configurable, this function assumes
17527 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17528 delimiters are skipped when they have been removed by customization.
17529 The return value is nil, or a cons cell with the delimiter and the
17530 position of this delimiter.
17532 This function does a reasonably good job, but can locally be fooled by
17533 for example currency specifications. For example it will assume being in
17534 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17535 fragments that are properly closed, but during editing, we have to live
17536 with the uncertainty caused by missing closing delimiters. This function
17537 looks only before point, not after."
17538 (catch 'exit
17539 (let ((pos (point))
17540 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17541 (lim (progn
17542 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17543 (point)))
17544 dd-on str (start 0) m re)
17545 (goto-char pos)
17546 (when dodollar
17547 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17548 re (nth 1 (assoc "$" org-latex-regexps)))
17549 (while (string-match re str start)
17550 (cond
17551 ((= (match-end 0) (length str))
17552 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17553 ((= (match-end 0) (- (length str) 5))
17554 (throw 'exit nil))
17555 (t (setq start (match-end 0))))))
17556 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17557 (goto-char pos)
17558 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17559 (and (match-beginning 2) (throw 'exit nil))
17560 ;; count $$
17561 (while (re-search-backward "\\$\\$" lim t)
17562 (setq dd-on (not dd-on)))
17563 (goto-char pos)
17564 (if dd-on (cons "$$" m))))))
17566 (defun org-inside-latex-macro-p ()
17567 "Is point inside a LaTeX macro or its arguments?"
17568 (save-match-data
17569 (org-in-regexp
17570 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17572 (defun org-try-cdlatex-tab ()
17573 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17574 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17575 - inside a LaTeX fragment, or
17576 - after the first word in a line, where an abbreviation expansion could
17577 insert a LaTeX environment."
17578 (when org-cdlatex-mode
17579 (cond
17580 ;; Before any word on the line: No expansion possible.
17581 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17582 ;; Just after first word on the line: Expand it. Make sure it
17583 ;; cannot happen on headlines, though.
17584 ((save-excursion
17585 (skip-chars-backward "a-zA-Z0-9*")
17586 (skip-chars-backward " \t")
17587 (and (bolp) (not (org-at-heading-p))))
17588 (cdlatex-tab) t)
17589 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17591 (defun org-cdlatex-underscore-caret (&optional arg)
17592 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17593 Revert to the normal definition outside of these fragments."
17594 (interactive "P")
17595 (if (org-inside-LaTeX-fragment-p)
17596 (call-interactively 'cdlatex-sub-superscript)
17597 (let (org-cdlatex-mode)
17598 (call-interactively (key-binding (vector last-input-event))))))
17600 (defun org-cdlatex-math-modify (&optional arg)
17601 "Execute `cdlatex-math-modify' in LaTeX fragments.
17602 Revert to the normal definition outside of these fragments."
17603 (interactive "P")
17604 (if (org-inside-LaTeX-fragment-p)
17605 (call-interactively 'cdlatex-math-modify)
17606 (let (org-cdlatex-mode)
17607 (call-interactively (key-binding (vector last-input-event))))))
17609 (defvar org-latex-fragment-image-overlays nil
17610 "List of overlays carrying the images of latex fragments.")
17611 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17613 (defun org-remove-latex-fragment-image-overlays ()
17614 "Remove all overlays with LaTeX fragment images in current buffer."
17615 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17616 (setq org-latex-fragment-image-overlays nil))
17618 (defun org-preview-latex-fragment (&optional subtree)
17619 "Preview the LaTeX fragment at point, or all locally or globally.
17620 If the cursor is in a LaTeX fragment, create the image and overlay
17621 it over the source code. If there is no fragment at point, display
17622 all fragments in the current text, from one headline to the next. With
17623 prefix SUBTREE, display all fragments in the current subtree. With a
17624 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17625 the cursor is before the first headline,
17626 display all fragments in the buffer.
17627 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17628 (interactive "P")
17629 (unless buffer-file-name
17630 (error "Can't preview LaTeX fragment in a non-file buffer"))
17631 (org-remove-latex-fragment-image-overlays)
17632 (save-excursion
17633 (save-restriction
17634 (let (beg end at msg)
17635 (cond
17636 ((or (equal subtree '(16))
17637 (not (save-excursion
17638 (re-search-backward org-outline-regexp-bol nil t))))
17639 (setq beg (point-min) end (point-max)
17640 msg "Creating images for buffer...%s"))
17641 ((equal subtree '(4))
17642 (org-back-to-heading)
17643 (setq beg (point) end (org-end-of-subtree t)
17644 msg "Creating images for subtree...%s"))
17646 (if (setq at (org-inside-LaTeX-fragment-p))
17647 (goto-char (max (point-min) (- (cdr at) 2)))
17648 (org-back-to-heading))
17649 (setq beg (point) end (progn (outline-next-heading) (point))
17650 msg (if at "Creating image...%s"
17651 "Creating images for entry...%s"))))
17652 (message msg "")
17653 (narrow-to-region beg end)
17654 (goto-char beg)
17655 (org-format-latex
17656 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17657 (file-name-nondirectory
17658 buffer-file-name)))
17659 default-directory 'overlays msg at 'forbuffer
17660 org-latex-create-formula-image-program)
17661 (message msg "done. Use `C-c C-c' to remove images.")))))
17663 (defvar org-latex-regexps
17664 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17665 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17666 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17667 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17668 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17669 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17670 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17671 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17672 "Regular expressions for matching embedded LaTeX.")
17674 (defvar org-export-have-math nil) ;; dynamic scoping
17675 (defun org-format-latex (prefix &optional dir overlays msg at
17676 forbuffer processing-type)
17677 "Replace LaTeX fragments with links to an image, and produce images.
17678 Some of the options can be changed using the variable
17679 `org-format-latex-options'."
17680 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17681 (let* ((prefixnodir (file-name-nondirectory prefix))
17682 (absprefix (expand-file-name prefix dir))
17683 (todir (file-name-directory absprefix))
17684 (opt org-format-latex-options)
17685 (optnew org-format-latex-options)
17686 (matchers (plist-get opt :matchers))
17687 (re-list org-latex-regexps)
17688 (org-format-latex-header-extra
17689 (plist-get (org-infile-export-plist) :latex-header-extra))
17690 (cnt 0) txt hash link beg end re e checkdir
17691 string
17692 m n block-type block linkfile movefile ov)
17693 ;; Check the different regular expressions
17694 (while (setq e (pop re-list))
17695 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17696 block (if block-type "\n\n" ""))
17697 (when (member m matchers)
17698 (goto-char (point-min))
17699 (while (re-search-forward re nil t)
17700 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17701 (not (get-text-property (match-beginning n)
17702 'org-protected))
17703 (or (not overlays)
17704 (not (eq (get-char-property (match-beginning n)
17705 'org-overlay-type)
17706 'org-latex-overlay))))
17707 (setq org-export-have-math t)
17708 (cond
17709 ((eq processing-type 'verbatim)
17710 ;; Leave the text verbatim, just protect it
17711 (add-text-properties (match-beginning n) (match-end n)
17712 '(org-protected t)))
17713 ((eq processing-type 'mathjax)
17714 ;; Prepare for MathJax processing
17715 (setq string (match-string n))
17716 (if (member m '("$" "$1"))
17717 (save-excursion
17718 (delete-region (match-beginning n) (match-end n))
17719 (goto-char (match-beginning n))
17720 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17721 "\\)")
17722 '(org-protected t))))
17723 (add-text-properties (match-beginning n) (match-end n)
17724 '(org-protected t))))
17725 ((or (eq processing-type 'dvipng)
17726 (eq processing-type 'imagemagick))
17727 ;; Process to an image
17728 (setq txt (match-string n)
17729 beg (match-beginning n) end (match-end n)
17730 cnt (1+ cnt))
17731 (let ((face (face-at-point))
17732 (fg (plist-get opt :foreground))
17733 (bg (plist-get opt :background))
17734 print-length print-level) ; make sure full list is printed
17735 (when forbuffer
17736 ; Get the colors from the face at point
17737 (goto-char beg)
17738 (when (eq fg 'auto)
17739 (setq fg (face-attribute face :foreground nil 'default)))
17740 (when (eq bg 'auto)
17741 (setq bg (face-attribute face :background nil 'default)))
17742 (setq optnew (copy-sequence opt))
17743 (plist-put optnew :foreground fg)
17744 (plist-put optnew :background bg))
17745 (setq hash (sha1 (prin1-to-string
17746 (list org-format-latex-header
17747 org-format-latex-header-extra
17748 org-export-latex-default-packages-alist
17749 org-export-latex-packages-alist
17750 org-format-latex-options
17751 forbuffer txt fg bg)))
17752 linkfile (format "%s_%s.png" prefix hash)
17753 movefile (format "%s_%s.png" absprefix hash)))
17754 (setq link (concat block "[[file:" linkfile "]]" block))
17755 (if msg (message msg cnt))
17756 (goto-char beg)
17757 (unless checkdir ; make sure the directory exists
17758 (setq checkdir t)
17759 (or (file-directory-p todir) (make-directory todir t)))
17760 (unless (file-exists-p movefile)
17761 (org-create-formula-image
17762 txt movefile optnew forbuffer processing-type))
17763 (if overlays
17764 (progn
17765 (mapc (lambda (o)
17766 (if (eq (overlay-get o 'org-overlay-type)
17767 'org-latex-overlay)
17768 (delete-overlay o)))
17769 (overlays-in beg end))
17770 (setq ov (make-overlay beg end))
17771 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17772 (if (featurep 'xemacs)
17773 (progn
17774 (overlay-put ov 'invisible t)
17775 (overlay-put
17776 ov 'end-glyph
17777 (make-glyph (vector 'png :file movefile))))
17778 (overlay-put
17779 ov 'display
17780 (list 'image :type 'png :file movefile :ascent 'center)))
17781 (push ov org-latex-fragment-image-overlays)
17782 (goto-char end))
17783 (delete-region beg end)
17784 (insert (org-add-props link
17785 (list 'org-latex-src
17786 (replace-regexp-in-string
17787 "\"" "" txt)
17788 'org-latex-src-embed-type
17789 (if block-type 'paragraph 'character))))))
17790 ((eq processing-type 'mathml)
17791 ;; Process to MathML
17792 (unless (save-match-data (org-format-latex-mathml-available-p))
17793 (error "LaTeX to MathML converter not configured"))
17794 (setq txt (match-string n)
17795 beg (match-beginning n) end (match-end n)
17796 cnt (1+ cnt))
17797 (if msg (message msg cnt))
17798 (goto-char beg)
17799 (delete-region beg end)
17800 (insert (org-format-latex-as-mathml
17801 txt block-type prefix dir)))
17803 (error "Unknown conversion type %s for latex fragments"
17804 processing-type)))))))))
17806 (defun org-create-math-formula (latex-frag &optional mathml-file)
17807 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17808 Use `org-latex-to-mathml-convert-command'. If the conversion is
17809 sucessful, return the portion between \"<math...> </math>\"
17810 elements otherwise return nil. When MATHML-FILE is specified,
17811 write the results in to that file. When invoked as an
17812 interactive command, prompt for LATEX-FRAG, with initial value
17813 set to the current active region and echo the results for user
17814 inspection."
17815 (interactive (list (let ((frag (when (org-region-active-p)
17816 (buffer-substring-no-properties
17817 (region-beginning) (region-end)))))
17818 (read-string "LaTeX Fragment: " frag nil frag))))
17819 (unless latex-frag (error "Invalid latex-frag"))
17820 (let* ((tmp-in-file (file-relative-name
17821 (make-temp-name (expand-file-name "ltxmathml-in"))))
17822 (ignore (write-region latex-frag nil tmp-in-file))
17823 (tmp-out-file (file-relative-name
17824 (make-temp-name (expand-file-name "ltxmathml-out"))))
17825 (cmd (format-spec
17826 org-latex-to-mathml-convert-command
17827 `((?j . ,(shell-quote-argument
17828 (expand-file-name org-latex-to-mathml-jar-file)))
17829 (?I . ,(shell-quote-argument tmp-in-file))
17830 (?o . ,(shell-quote-argument tmp-out-file)))))
17831 mathml shell-command-output)
17832 (when (org-called-interactively-p 'any)
17833 (unless (org-format-latex-mathml-available-p)
17834 (error "LaTeX to MathML converter not configured")))
17835 (message "Running %s" cmd)
17836 (setq shell-command-output (shell-command-to-string cmd))
17837 (setq mathml
17838 (when (file-readable-p tmp-out-file)
17839 (with-current-buffer (find-file-noselect tmp-out-file t)
17840 (goto-char (point-min))
17841 (when (re-search-forward
17842 (concat
17843 (regexp-quote
17844 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17845 "\\(.\\|\n\\)*"
17846 (regexp-quote "</math>")) nil t)
17847 (prog1 (match-string 0) (kill-buffer))))))
17848 (cond
17849 (mathml
17850 (setq mathml
17851 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17852 (when mathml-file
17853 (write-region mathml nil mathml-file))
17854 (when (org-called-interactively-p 'any)
17855 (message mathml)))
17856 ((message "LaTeX to MathML conversion failed")
17857 (message shell-command-output)))
17858 (delete-file tmp-in-file)
17859 (when (file-exists-p tmp-out-file)
17860 (delete-file tmp-out-file))
17861 mathml))
17863 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17864 prefix &optional dir)
17865 "Use `org-create-math-formula' but check local cache first."
17866 (let* ((absprefix (expand-file-name prefix dir))
17867 (print-length nil) (print-level nil)
17868 (formula-id (concat
17869 "formula-"
17870 (sha1
17871 (prin1-to-string
17872 (list latex-frag
17873 org-latex-to-mathml-convert-command)))))
17874 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17875 (formula-cache-dir (file-name-directory formula-cache)))
17877 (unless (file-directory-p formula-cache-dir)
17878 (make-directory formula-cache-dir t))
17880 (unless (file-exists-p formula-cache)
17881 (org-create-math-formula latex-frag formula-cache))
17883 (if (file-exists-p formula-cache)
17884 ;; Successful conversion. Return the link to MathML file.
17885 (org-add-props
17886 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17887 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17888 'org-latex-src-embed-type (if latex-frag-type
17889 'paragraph 'character)))
17890 ;; Failed conversion. Return the LaTeX fragment verbatim
17891 (add-text-properties
17892 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17893 latex-frag)))
17895 (defun org-create-formula-image (string tofile options buffer &optional type)
17896 "Create an image from LaTeX source using dvipng or convert.
17897 This function calls either `org-create-formula-image-with-dvipng'
17898 or `org-create-formula-image-with-imagemagick' depending on the
17899 value of `org-latex-create-formula-image-program' or on the value
17900 of the optional TYPE variable.
17902 Note: ultimately these two function should be combined as they
17903 share a good deal of logic."
17904 (org-check-external-command
17905 "latex" "needed to convert LaTeX fragments to images")
17906 (funcall
17907 (case (or type org-latex-create-formula-image-program)
17908 ('dvipng
17909 (org-check-external-command
17910 "dvipng" "needed to convert LaTeX fragments to images")
17911 #'org-create-formula-image-with-dvipng)
17912 ('imagemagick
17913 (org-check-external-command
17914 "convert" "you need to install imagemagick")
17915 #'org-create-formula-image-with-imagemagick)
17916 (t (error
17917 "invalid value of `org-latex-create-formula-image-program'")))
17918 string tofile options buffer))
17920 ;; This function borrows from Ganesh Swami's latex2png.el
17921 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17922 "This calls dvipng."
17923 (require 'org-latex)
17924 (let* ((tmpdir (if (featurep 'xemacs)
17925 (temp-directory)
17926 temporary-file-directory))
17927 (texfilebase (make-temp-name
17928 (expand-file-name "orgtex" tmpdir)))
17929 (texfile (concat texfilebase ".tex"))
17930 (dvifile (concat texfilebase ".dvi"))
17931 (pngfile (concat texfilebase ".png"))
17932 (fnh (if (featurep 'xemacs)
17933 (font-height (face-font 'default))
17934 (face-attribute 'default :height nil)))
17935 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17936 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17937 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17938 "Black"))
17939 (bg (or (plist-get options (if buffer :background :html-background))
17940 "Transparent")))
17941 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17942 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17943 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17944 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17945 (with-temp-file texfile
17946 (insert (org-splice-latex-header
17947 org-format-latex-header
17948 org-export-latex-default-packages-alist
17949 org-export-latex-packages-alist t
17950 org-format-latex-header-extra))
17951 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17952 (require 'org-latex)
17953 (org-export-latex-fix-inputenc))
17954 (let ((dir default-directory))
17955 (condition-case nil
17956 (progn
17957 (cd tmpdir)
17958 (call-process "latex" nil nil nil texfile))
17959 (error nil))
17960 (cd dir))
17961 (if (not (file-exists-p dvifile))
17962 (progn (message "Failed to create dvi file from %s" texfile) nil)
17963 (condition-case nil
17964 (if (featurep 'xemacs)
17965 (call-process "dvipng" nil nil nil
17966 "-fg" fg "-bg" bg
17967 "-T" "tight"
17968 "-o" pngfile
17969 dvifile)
17970 (call-process "dvipng" nil nil nil
17971 "-fg" fg "-bg" bg
17972 "-D" dpi
17973 ;;"-x" scale "-y" scale
17974 "-T" "tight"
17975 "-o" pngfile
17976 dvifile))
17977 (error nil))
17978 (if (not (file-exists-p pngfile))
17979 (if org-format-latex-signal-error
17980 (error "Failed to create png file from %s" texfile)
17981 (message "Failed to create png file from %s" texfile)
17982 nil)
17983 ;; Use the requested file name and clean up
17984 (copy-file pngfile tofile 'replace)
17985 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17986 (if (file-exists-p (concat texfilebase e))
17987 (delete-file (concat texfilebase e))))
17988 pngfile))))
17990 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17991 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17992 "This calls convert, which is included into imagemagick."
17993 (require 'org-latex)
17994 (let* ((tmpdir (if (featurep 'xemacs)
17995 (temp-directory)
17996 temporary-file-directory))
17997 (texfilebase (make-temp-name
17998 (expand-file-name "orgtex" tmpdir)))
17999 (texfile (concat texfilebase ".tex"))
18000 (pdffile (concat texfilebase ".pdf"))
18001 (pngfile (concat texfilebase ".png"))
18002 (fnh (if (featurep 'xemacs)
18003 (font-height (face-font 'default))
18004 (face-attribute 'default :height nil)))
18005 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18006 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18007 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18008 "black"))
18009 (bg (or (plist-get options (if buffer :background :html-background))
18010 "white")))
18011 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18012 (setq fg (org-latex-color-format fg)))
18013 (if (eq bg 'default) (setq bg (org-latex-color :background))
18014 (setq bg (org-latex-color-format
18015 (if (string= bg "Transparent") "white" bg))))
18016 (with-temp-file texfile
18017 (insert (org-splice-latex-header
18018 org-format-latex-header
18019 org-export-latex-default-packages-alist
18020 org-export-latex-packages-alist t
18021 org-format-latex-header-extra))
18022 (insert "\n\\begin{document}\n"
18023 "\\definecolor{fg}{rgb}{" fg "}\n"
18024 "\\definecolor{bg}{rgb}{" bg "}\n"
18025 "\n\\pagecolor{bg}\n"
18026 "\n{\\color{fg}\n"
18027 string
18028 "\n}\n"
18029 "\n\\end{document}\n" )
18030 (require 'org-latex)
18031 (org-export-latex-fix-inputenc))
18032 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18033 (condition-case nil
18034 (progn
18035 (cd tmpdir)
18036 (setq cmds org-latex-to-pdf-process)
18037 (while cmds
18038 (setq latex-frags-cmds (pop cmds))
18039 (if (listp latex-frags-cmds)
18040 (setq cmds nil)
18041 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
18042 (while latex-frags-cmds
18043 (setq cmd (pop latex-frags-cmds))
18044 (while (string-match "%b" cmd)
18045 (setq cmd (replace-match
18046 (save-match-data
18047 (shell-quote-argument texfile))
18048 t t cmd)))
18049 (while (string-match "%f" cmd)
18050 (setq cmd (replace-match
18051 (save-match-data
18052 (shell-quote-argument (file-name-nondirectory texfile)))
18053 t t cmd)))
18054 (while (string-match "%o" cmd)
18055 (setq cmd (replace-match
18056 (save-match-data
18057 (shell-quote-argument (file-name-directory texfile)))
18058 t t cmd)))
18059 (setq cmd (split-string cmd))
18060 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18061 (error nil))
18062 (cd dir))
18063 (if (not (file-exists-p pdffile))
18064 (progn (message "Failed to create pdf file from %s" texfile) nil)
18065 (condition-case nil
18066 (if (featurep 'xemacs)
18067 (call-process "convert" nil nil nil
18068 "-density" "96"
18069 "-trim"
18070 "-antialias"
18071 pdffile
18072 "-quality" "100"
18073 ;; "-sharpen" "0x1.0"
18074 pngfile)
18075 (call-process "convert" nil nil nil
18076 "-density" dpi
18077 "-trim"
18078 "-antialias"
18079 pdffile
18080 "-quality" "100"
18081 ; "-sharpen" "0x1.0"
18082 pngfile))
18083 (error nil))
18084 (if (not (file-exists-p pngfile))
18085 (if org-format-latex-signal-error
18086 (error "Failed to create png file from %s" texfile)
18087 (message "Failed to create png file from %s" texfile)
18088 nil)
18089 ;; Use the requested file name and clean up
18090 (copy-file pngfile tofile 'replace)
18091 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18092 (if (file-exists-p (concat texfilebase e))
18093 (delete-file (concat texfilebase e))))
18094 pngfile))))
18096 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18097 "Fill a LaTeX header template TPL.
18098 In the template, the following place holders will be recognized:
18100 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18101 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18102 [PACKAGES] \\usepackage statements for PKG
18103 [NO-PACKAGES] do not include PKG
18104 [EXTRA] the string EXTRA
18105 [NO-EXTRA] do not include EXTRA
18107 For backward compatibility, if both the positive and the negative place
18108 holder is missing, the positive one (without the \"NO-\") will be
18109 assumed to be present at the end of the template.
18110 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18111 EXTRA is a string.
18112 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18113 (let (rpl (end ""))
18114 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18115 (setq rpl (if (or (match-end 1) (not def-pkg))
18116 "" (org-latex-packages-to-string def-pkg snippets-p t))
18117 tpl (replace-match rpl t t tpl))
18118 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18120 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18121 (setq rpl (if (or (match-end 1) (not pkg))
18122 "" (org-latex-packages-to-string pkg snippets-p t))
18123 tpl (replace-match rpl t t tpl))
18124 (if pkg (setq end
18125 (concat end "\n"
18126 (org-latex-packages-to-string pkg snippets-p)))))
18128 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18129 (setq rpl (if (or (match-end 1) (not extra))
18130 "" (concat extra "\n"))
18131 tpl (replace-match rpl t t tpl))
18132 (if (and extra (string-match "\\S-" extra))
18133 (setq end (concat end "\n" extra))))
18135 (if (string-match "\\S-" end)
18136 (concat tpl "\n" end)
18137 tpl)))
18139 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18140 "Turn an alist of packages into a string with the \\usepackage macros."
18141 (setq pkg (mapconcat (lambda(p)
18142 (cond
18143 ((stringp p) p)
18144 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18145 (format "%% Package %s omitted" (cadr p)))
18146 ((equal "" (car p))
18147 (format "\\usepackage{%s}" (cadr p)))
18149 (format "\\usepackage[%s]{%s}"
18150 (car p) (cadr p)))))
18152 "\n"))
18153 (if newline (concat pkg "\n") pkg))
18155 (defun org-dvipng-color (attr)
18156 "Return a RGB color specification for dvipng."
18157 (apply 'format "rgb %s %s %s"
18158 (mapcar 'org-normalize-color
18159 (if (featurep 'xemacs)
18160 (color-rgb-components
18161 (face-property 'default
18162 (cond ((eq attr :foreground) 'foreground)
18163 ((eq attr :background) 'background))))
18164 (color-values (face-attribute 'default attr nil))))))
18166 (defun org-dvipng-color-format (color-name)
18167 "Convert COLOR-NAME to a RGB color value for dvipng."
18168 (apply 'format "rgb %s %s %s"
18169 (mapcar 'org-normalize-color
18170 (color-values color-name))))
18172 (defun org-latex-color (attr)
18173 "Return a RGB color for the LaTeX color package."
18174 (apply 'format "%s,%s,%s"
18175 (mapcar 'org-normalize-color
18176 (if (featurep 'xemacs)
18177 (color-rgb-components
18178 (face-property 'default
18179 (cond ((eq attr :foreground) 'foreground)
18180 ((eq attr :background) 'background))))
18181 (color-values (face-attribute 'default attr nil))))))
18183 (defun org-latex-color-format (color-name)
18184 "Convert COLOR-NAME to a RGB color value."
18185 (apply 'format "%s,%s,%s"
18186 (mapcar 'org-normalize-color
18187 (color-values color-name))))
18189 (defun org-normalize-color (value)
18190 "Return string to be used as color value for an RGB component."
18191 (format "%g" (/ value 65535.0)))
18193 ;; Image display
18196 (defvar org-inline-image-overlays nil)
18197 (make-variable-buffer-local 'org-inline-image-overlays)
18199 (defun org-toggle-inline-images (&optional include-linked)
18200 "Toggle the display of inline images.
18201 INCLUDE-LINKED is passed to `org-display-inline-images'."
18202 (interactive "P")
18203 (if org-inline-image-overlays
18204 (progn
18205 (org-remove-inline-images)
18206 (message "Inline image display turned off"))
18207 (org-display-inline-images include-linked)
18208 (if (and (org-called-interactively-p)
18209 org-inline-image-overlays)
18210 (message "%d images displayed inline"
18211 (length org-inline-image-overlays))
18212 (message "No images to display inline"))))
18214 (defun org-redisplay-inline-images ()
18215 "Refresh the display of inline images."
18216 (interactive)
18217 (if (not org-inline-image-overlays)
18218 (org-toggle-inline-images)
18219 (org-toggle-inline-images)
18220 (org-toggle-inline-images)))
18222 (defun org-display-inline-images (&optional include-linked refresh beg end)
18223 "Display inline images.
18224 Normally only links without a description part are inlined, because this
18225 is how it will work for export. When INCLUDE-LINKED is set, also links
18226 with a description part will be inlined. This can be nice for a quick
18227 look at those images, but it does not reflect what exported files will look
18228 like.
18229 When REFRESH is set, refresh existing images between BEG and END.
18230 This will create new image displays only if necessary.
18231 BEG and END default to the buffer boundaries."
18232 (interactive "P")
18233 (unless refresh
18234 (org-remove-inline-images)
18235 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18236 (save-excursion
18237 (save-restriction
18238 (widen)
18239 (setq beg (or beg (point-min)) end (or end (point-max)))
18240 (goto-char beg)
18241 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18242 (substring (org-image-file-name-regexp) 0 -2)
18243 "\\)\\]" (if include-linked "" "\\]")))
18244 old file ov img type attrwidth width)
18245 (while (re-search-forward re end t)
18246 (setq old (get-char-property-and-overlay (match-beginning 1)
18247 'org-image-overlay)
18248 file (expand-file-name
18249 (concat (or (match-string 3) "") (match-string 4))))
18250 (when (image-type-available-p 'imagemagick)
18251 (setq attrwidth (if (or (listp org-image-actual-width)
18252 (null org-image-actual-width))
18253 (save-excursion
18254 (save-match-data
18255 (when (re-search-backward
18256 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18257 (save-excursion
18258 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18259 (string-to-number (match-string 1))))))
18260 width (cond ((eq org-image-actual-width t) nil)
18261 ((null org-image-actual-width) attrwidth)
18262 ((numberp org-image-actual-width)
18263 org-image-actual-width)
18264 ((listp org-image-actual-width)
18265 (or attrwidth (car org-image-actual-width))))
18266 type (if width 'imagemagick)))
18267 (when (file-exists-p file)
18268 (if (and (car-safe old) refresh)
18269 (image-refresh (overlay-get (cdr old) 'display))
18270 (setq img (save-match-data (create-image file type nil :width width)))
18271 (when img
18272 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18273 (overlay-put ov 'display img)
18274 (overlay-put ov 'face 'default)
18275 (overlay-put ov 'org-image-overlay t)
18276 (overlay-put ov 'modification-hooks
18277 (list 'org-display-inline-remove-overlay))
18278 (push ov org-inline-image-overlays)))))))))
18280 (define-obsolete-function-alias
18281 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18283 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18284 "Remove inline-display overlay if a corresponding region is modified."
18285 (let ((inhibit-modification-hooks t))
18286 (when (and ov after)
18287 (delete ov org-inline-image-overlays)
18288 (delete-overlay ov))))
18290 (defun org-remove-inline-images ()
18291 "Remove inline display of images."
18292 (interactive)
18293 (mapc 'delete-overlay org-inline-image-overlays)
18294 (setq org-inline-image-overlays nil))
18296 ;;;; Key bindings
18298 ;; Outline functions from `outline-mode-prefix-map'
18299 ;; that can be remapped in Org:
18300 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18301 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18302 (define-key org-mode-map [remap outline-forward-same-level]
18303 'org-forward-heading-same-level)
18304 (define-key org-mode-map [remap outline-backward-same-level]
18305 'org-backward-heading-same-level)
18306 (define-key org-mode-map [remap show-branches]
18307 'org-kill-note-or-show-branches)
18308 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18309 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18310 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18312 ;; Outline functions from `outline-mode-prefix-map' that can not
18313 ;; be remapped in Org:
18315 ;; - the column "key binding" shows whether the Outline function is still
18316 ;; available in Org mode on the same key that it has been bound to in
18317 ;; Outline mode:
18318 ;; - "overridden": key used for a different functionality in Org mode
18319 ;; - else: key still bound to the same Outline function in Org mode
18321 ;; | Outline function | key binding | Org replacement |
18322 ;; |------------------------------------+-------------+-----------------------|
18323 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18324 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18325 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18326 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18327 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18328 ;; | `show-entry' | overridden | no replacement |
18329 ;; | `show-children' | `C-c C-i' | visibility cycling |
18330 ;; | `show-branches' | `C-c C-k' | still same function |
18331 ;; | `show-subtree' | overridden | visibility cycling |
18332 ;; | `show-all' | overridden | no replacement |
18333 ;; | `hide-subtree' | overridden | visibility cycling |
18334 ;; | `hide-body' | overridden | no replacement |
18335 ;; | `hide-entry' | overridden | visibility cycling |
18336 ;; | `hide-leaves' | overridden | no replacement |
18337 ;; | `hide-sublevels' | overridden | no replacement |
18338 ;; | `hide-other' | overridden | no replacement |
18340 ;; Make `C-c C-x' a prefix key
18341 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18343 ;; TAB key with modifiers
18344 (org-defkey org-mode-map "\C-i" 'org-cycle)
18345 (org-defkey org-mode-map [(tab)] 'org-cycle)
18346 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18347 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18348 ;; The following line is necessary under Suse GNU/Linux
18349 (unless (featurep 'xemacs)
18350 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18351 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18352 (define-key org-mode-map [backtab] 'org-shifttab)
18354 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18355 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18356 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18358 ;; Cursor keys with modifiers
18359 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18360 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18361 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18362 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18364 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18365 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18366 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18367 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18369 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18370 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18371 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18372 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18374 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18375 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18376 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18377 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18379 ;; Babel keys
18380 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18381 (mapc (lambda (pair)
18382 (define-key org-babel-map (car pair) (cdr pair)))
18383 org-babel-key-bindings)
18385 ;;; Extra keys for tty access.
18386 ;; We only set them when really needed because otherwise the
18387 ;; menus don't show the simple keys
18389 (when (or org-use-extra-keys
18390 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18391 (not window-system))
18392 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18393 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18394 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18395 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18396 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18397 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18398 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18399 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18400 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18401 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18402 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18403 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18404 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18405 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18406 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18407 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18408 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18409 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18410 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18411 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18412 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18413 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18414 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18415 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18416 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18417 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18418 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18419 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18421 ;; All the other keys
18423 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18424 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18425 (if (boundp 'narrow-map)
18426 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18427 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18428 (if (boundp 'narrow-map)
18429 (org-defkey narrow-map "b" 'org-narrow-to-block)
18430 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18431 (if (boundp 'narrow-map)
18432 (org-defkey narrow-map "e" 'org-narrow-to-element)
18433 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18434 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18435 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18436 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18437 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18438 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18439 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18440 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18441 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18442 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18443 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18444 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18445 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18446 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18447 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18448 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18449 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18450 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18451 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18452 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18453 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18454 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18455 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18456 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18457 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18458 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18459 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18460 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18461 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18462 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18463 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18464 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18465 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18466 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18467 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18468 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18469 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18470 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18471 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18472 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18473 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18474 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18475 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18476 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18477 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18478 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18479 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18480 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18481 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18482 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18483 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18484 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18485 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18486 (org-defkey org-mode-map "\C-c^" 'org-sort)
18487 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18488 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18489 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18490 (org-defkey org-mode-map "\C-m" 'org-return)
18491 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18492 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18493 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18494 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18495 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18496 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18497 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18498 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18499 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18500 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18501 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18502 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18503 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18504 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18505 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18506 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18507 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18508 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18509 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18510 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18511 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18512 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18513 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18515 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18516 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18517 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18519 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18520 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18521 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18522 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18523 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18524 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18525 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18526 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18527 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18528 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18529 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18530 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18531 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18532 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18533 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18534 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18535 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18536 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18537 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18538 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18539 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18540 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18541 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18543 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18544 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18545 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18546 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18547 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18549 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18551 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18553 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18554 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18556 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18559 (when (featurep 'xemacs)
18560 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18563 (defconst org-speed-commands-default
18565 ("Outline Navigation")
18566 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18567 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18568 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18569 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18570 ("u" . (org-speed-move-safe 'outline-up-heading))
18571 ("j" . org-goto)
18572 ("g" . (org-refile t))
18573 ("Outline Visibility")
18574 ("c" . org-cycle)
18575 ("C" . org-shifttab)
18576 (" " . org-display-outline-path)
18577 ("=" . org-columns)
18578 ("Outline Structure Editing")
18579 ("U" . org-shiftmetaup)
18580 ("D" . org-shiftmetadown)
18581 ("r" . org-metaright)
18582 ("l" . org-metaleft)
18583 ("R" . org-shiftmetaright)
18584 ("L" . org-shiftmetaleft)
18585 ("i" . (progn (forward-char 1) (call-interactively
18586 'org-insert-heading-respect-content)))
18587 ("^" . org-sort)
18588 ("w" . org-refile)
18589 ("a" . org-archive-subtree-default-with-confirmation)
18590 ("." . org-mark-subtree)
18591 ("#" . org-toggle-comment)
18592 ("Clock Commands")
18593 ("I" . org-clock-in)
18594 ("O" . org-clock-out)
18595 ("Meta Data Editing")
18596 ("t" . org-todo)
18597 ("," . (org-priority))
18598 ("0" . (org-priority ?\ ))
18599 ("1" . (org-priority ?A))
18600 ("2" . (org-priority ?B))
18601 ("3" . (org-priority ?C))
18602 (":" . org-set-tags-command)
18603 ("e" . org-set-effort)
18604 ("E" . org-inc-effort)
18605 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18606 (org-entry-put (point) "APPT_WARNTIME" m)))
18607 ("Agenda Views etc")
18608 ("v" . org-agenda)
18609 ("/" . org-sparse-tree)
18610 ("Misc")
18611 ("o" . org-open-at-point)
18612 ("?" . org-speed-command-help)
18613 ("<" . (org-agenda-set-restriction-lock 'subtree))
18614 (">" . (org-agenda-remove-restriction-lock))
18616 "The default speed commands.")
18618 (defun org-print-speed-command (e)
18619 (if (> (length (car e)) 1)
18620 (progn
18621 (princ "\n")
18622 (princ (car e))
18623 (princ "\n")
18624 (princ (make-string (length (car e)) ?-))
18625 (princ "\n"))
18626 (princ (car e))
18627 (princ " ")
18628 (if (symbolp (cdr e))
18629 (princ (symbol-name (cdr e)))
18630 (prin1 (cdr e)))
18631 (princ "\n")))
18633 (defun org-speed-command-help ()
18634 "Show the available speed commands."
18635 (interactive)
18636 (if (not org-use-speed-commands)
18637 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18638 (with-output-to-temp-buffer "*Help*"
18639 (princ "User-defined Speed commands\n===========================\n")
18640 (mapc 'org-print-speed-command org-speed-commands-user)
18641 (princ "\n")
18642 (princ "Built-in Speed commands\n=======================\n")
18643 (mapc 'org-print-speed-command org-speed-commands-default))
18644 (with-current-buffer "*Help*"
18645 (setq truncate-lines t))))
18647 (defun org-speed-move-safe (cmd)
18648 "Execute CMD, but make sure that the cursor always ends up in a headline.
18649 If not, return to the original position and throw an error."
18650 (interactive)
18651 (let ((pos (point)))
18652 (call-interactively cmd)
18653 (unless (and (bolp) (org-at-heading-p))
18654 (goto-char pos)
18655 (error "Boundary reached while executing %s" cmd))))
18657 (defvar org-self-insert-command-undo-counter 0)
18659 (defvar org-table-auto-blank-field) ; defined in org-table.el
18660 (defvar org-speed-command nil)
18662 (define-obsolete-function-alias
18663 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18665 (defun org-speed-command-activate (keys)
18666 "Hook for activating single-letter speed commands.
18667 `org-speed-commands-default' specifies a minimal command set.
18668 Use `org-speed-commands-user' for further customization."
18669 (when (or (and (bolp) (looking-at org-outline-regexp))
18670 (and (functionp org-use-speed-commands)
18671 (funcall org-use-speed-commands)))
18672 (cdr (assoc keys (append org-speed-commands-user
18673 org-speed-commands-default)))))
18675 (define-obsolete-function-alias
18676 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18678 (defun org-babel-speed-command-activate (keys)
18679 "Hook for activating single-letter code block commands."
18680 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18681 (cdr (assoc keys org-babel-key-bindings))))
18683 (defcustom org-speed-command-hook
18684 '(org-speed-command-default-hook org-babel-speed-command-hook)
18685 "Hook for activating speed commands at strategic locations.
18686 Hook functions are called in sequence until a valid handler is
18687 found.
18689 Each hook takes a single argument, a user-pressed command key
18690 which is also a `self-insert-command' from the global map.
18692 Within the hook, examine the cursor position and the command key
18693 and return nil or a valid handler as appropriate. Handler could
18694 be one of an interactive command, a function, or a form.
18696 Set `org-use-speed-commands' to non-nil value to enable this
18697 hook. The default setting is `org-speed-command-activate'."
18698 :group 'org-structure
18699 :version "24.1"
18700 :type 'hook)
18702 (defun org-self-insert-command (N)
18703 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18704 If the cursor is in a table looking at whitespace, the whitespace is
18705 overwritten, and the table is not marked as requiring realignment."
18706 (interactive "p")
18707 (org-check-before-invisible-edit 'insert)
18708 (cond
18709 ((and org-use-speed-commands
18710 (setq org-speed-command
18711 (run-hook-with-args-until-success
18712 'org-speed-command-hook (this-command-keys))))
18713 (cond
18714 ((commandp org-speed-command)
18715 (setq this-command org-speed-command)
18716 (call-interactively org-speed-command))
18717 ((functionp org-speed-command)
18718 (funcall org-speed-command))
18719 ((and org-speed-command (listp org-speed-command))
18720 (eval org-speed-command))
18721 (t (let (org-use-speed-commands)
18722 (call-interactively 'org-self-insert-command)))))
18723 ((and
18724 (org-table-p)
18725 (progn
18726 ;; check if we blank the field, and if that triggers align
18727 (and (featurep 'org-table) org-table-auto-blank-field
18728 (member last-command
18729 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18730 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18731 ;; got extra space, this field does not determine column width
18732 (let (org-table-may-need-update) (org-table-blank-field))
18733 ;; no extra space, this field may determine column width
18734 (org-table-blank-field)))
18736 (eq N 1)
18737 (looking-at "[^|\n]* |"))
18738 (let (org-table-may-need-update)
18739 (goto-char (1- (match-end 0)))
18740 (backward-delete-char 1)
18741 (goto-char (match-beginning 0))
18742 (self-insert-command N)))
18744 (setq org-table-may-need-update t)
18745 (self-insert-command N)
18746 (org-fix-tags-on-the-fly)
18747 (if org-self-insert-cluster-for-undo
18748 (if (not (eq last-command 'org-self-insert-command))
18749 (setq org-self-insert-command-undo-counter 1)
18750 (if (>= org-self-insert-command-undo-counter 20)
18751 (setq org-self-insert-command-undo-counter 1)
18752 (and (> org-self-insert-command-undo-counter 0)
18753 buffer-undo-list (listp buffer-undo-list)
18754 (not (cadr buffer-undo-list)) ; remove nil entry
18755 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18756 (setq org-self-insert-command-undo-counter
18757 (1+ org-self-insert-command-undo-counter))))))))
18759 (defun org-check-before-invisible-edit (kind)
18760 "Check is editing if kind KIND would be dangerous with invisible text around.
18761 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18762 ;; First, try to get out of here as quickly as possible, to reduce overhead
18763 (if (and org-catch-invisible-edits
18764 (or (not (boundp 'visible-mode)) (not visible-mode))
18765 (or (get-char-property (point) 'invisible)
18766 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18767 ;; OK, we need to take a closer look
18768 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18769 (invisible-before-point (if (bobp) nil (get-char-property
18770 (1- (point)) 'invisible)))
18771 (border-and-ok-direction
18773 ;; Check if we are acting predictably before invisible text
18774 (and invisible-at-point (not invisible-before-point)
18775 (memq kind '(insert delete-backward)))
18776 ;; Check if we are acting predictably after invisible text
18777 ;; This works not well, and I have turned it off. It seems
18778 ;; better to always show and stop after invisible text.
18779 ;; (and (not invisible-at-point) invisible-before-point
18780 ;; (memq kind '(insert delete)))
18782 (when (or (memq invisible-at-point '(outline org-hide-block t))
18783 (memq invisible-before-point '(outline org-hide-block t)))
18784 (if (eq org-catch-invisible-edits 'error)
18785 (error "Editing in invisible areas is prohibited - make visible first"))
18786 (if (and org-custom-properties-overlays
18787 (y-or-n-p "Display invisible properties in this buffer? "))
18788 (org-toggle-custom-properties-visibility)
18789 ;; Make the area visible
18790 (save-excursion
18791 (if invisible-before-point
18792 (goto-char (previous-single-char-property-change
18793 (point) 'invisible)))
18794 (org-cycle))
18795 (cond
18796 ((eq org-catch-invisible-edits 'show)
18797 ;; That's it, we do the edit after showing
18798 (message
18799 "Unfolding invisible region around point before editing")
18800 (sit-for 1))
18801 ((and (eq org-catch-invisible-edits 'smart)
18802 border-and-ok-direction)
18803 (message "Unfolding invisible region around point before editing"))
18805 ;; Don't do the edit, make the user repeat it in full visibility
18806 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18808 (defun org-fix-tags-on-the-fly ()
18809 (when (and (equal (char-after (point-at-bol)) ?*)
18810 (org-at-heading-p))
18811 (org-align-tags-here org-tags-column)))
18813 (defun org-delete-backward-char (N)
18814 "Like `delete-backward-char', insert whitespace at field end in tables.
18815 When deleting backwards, in tables this function will insert whitespace in
18816 front of the next \"|\" separator, to keep the table aligned. The table will
18817 still be marked for re-alignment if the field did fill the entire column,
18818 because, in this case the deletion might narrow the column."
18819 (interactive "p")
18820 (save-match-data
18821 (org-check-before-invisible-edit 'delete-backward)
18822 (if (and (org-table-p)
18823 (eq N 1)
18824 (string-match "|" (buffer-substring (point-at-bol) (point)))
18825 (looking-at ".*?|"))
18826 (let ((pos (point))
18827 (noalign (looking-at "[^|\n\r]* |"))
18828 (c org-table-may-need-update))
18829 (backward-delete-char N)
18830 (if (not overwrite-mode)
18831 (progn
18832 (skip-chars-forward "^|")
18833 (insert " ")
18834 (goto-char (1- pos))))
18835 ;; noalign: if there were two spaces at the end, this field
18836 ;; does not determine the width of the column.
18837 (if noalign (setq org-table-may-need-update c)))
18838 (backward-delete-char N)
18839 (org-fix-tags-on-the-fly))))
18841 (defun org-delete-char (N)
18842 "Like `delete-char', but insert whitespace at field end in tables.
18843 When deleting characters, in tables this function will insert whitespace in
18844 front of the next \"|\" separator, to keep the table aligned. The table will
18845 still be marked for re-alignment if the field did fill the entire column,
18846 because, in this case the deletion might narrow the column."
18847 (interactive "p")
18848 (save-match-data
18849 (org-check-before-invisible-edit 'delete)
18850 (if (and (org-table-p)
18851 (not (bolp))
18852 (not (= (char-after) ?|))
18853 (eq N 1))
18854 (if (looking-at ".*?|")
18855 (let ((pos (point))
18856 (noalign (looking-at "[^|\n\r]* |"))
18857 (c org-table-may-need-update))
18858 (replace-match (concat
18859 (substring (match-string 0) 1 -1)
18860 " |"))
18861 (goto-char pos)
18862 ;; noalign: if there were two spaces at the end, this field
18863 ;; does not determine the width of the column.
18864 (if noalign (setq org-table-may-need-update c)))
18865 (delete-char N))
18866 (delete-char N)
18867 (org-fix-tags-on-the-fly))))
18869 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18870 (put 'org-self-insert-command 'delete-selection t)
18871 (put 'orgtbl-self-insert-command 'delete-selection t)
18872 (put 'org-delete-char 'delete-selection 'supersede)
18873 (put 'org-delete-backward-char 'delete-selection 'supersede)
18874 (put 'org-yank 'delete-selection 'yank)
18876 ;; Make `flyspell-mode' delay after some commands
18877 (put 'org-self-insert-command 'flyspell-delayed t)
18878 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18879 (put 'org-delete-char 'flyspell-delayed t)
18880 (put 'org-delete-backward-char 'flyspell-delayed t)
18882 ;; Make pabbrev-mode expand after org-mode commands
18883 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18884 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18886 ;; How to do this: Measure non-white length of current string
18887 ;; If equal to column width, we should realign.
18889 (defun org-remap (map &rest commands)
18890 "In MAP, remap the functions given in COMMANDS.
18891 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18892 (let (new old)
18893 (while commands
18894 (setq old (pop commands) new (pop commands))
18895 (if (fboundp 'command-remapping)
18896 (org-defkey map (vector 'remap old) new)
18897 (substitute-key-definition old new map global-map)))))
18899 (when (eq org-enable-table-editor 'optimized)
18900 ;; If the user wants maximum table support, we need to hijack
18901 ;; some standard editing functions
18902 (org-remap org-mode-map
18903 'self-insert-command 'org-self-insert-command
18904 'delete-char 'org-delete-char
18905 'delete-backward-char 'org-delete-backward-char)
18906 (org-defkey org-mode-map "|" 'org-force-self-insert))
18908 (defvar org-ctrl-c-ctrl-c-hook nil
18909 "Hook for functions attaching themselves to `C-c C-c'.
18911 This can be used to add additional functionality to the C-c C-c
18912 key which executes context-dependent commands. This hook is run
18913 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18914 run after the last test.
18916 Each function will be called with no arguments. The function
18917 must check if the context is appropriate for it to act. If yes,
18918 it should do its thing and then return a non-nil value. If the
18919 context is wrong, just do nothing and return nil.")
18921 (defvar org-ctrl-c-ctrl-c-final-hook nil
18922 "Hook for functions attaching themselves to `C-c C-c'.
18924 This can be used to add additional functionality to the C-c C-c
18925 key which executes context-dependent commands. This hook is run
18926 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18927 before the first test.
18929 Each function will be called with no arguments. The function
18930 must check if the context is appropriate for it to act. If yes,
18931 it should do its thing and then return a non-nil value. If the
18932 context is wrong, just do nothing and return nil.")
18934 (defvar org-tab-first-hook nil
18935 "Hook for functions to attach themselves to TAB.
18936 See `org-ctrl-c-ctrl-c-hook' for more information.
18937 This hook runs as the first action when TAB is pressed, even before
18938 `org-cycle' messes around with the `outline-regexp' to cater for
18939 inline tasks and plain list item folding.
18940 If any function in this hook returns t, any other actions that
18941 would have been caused by TAB (such as table field motion or visibility
18942 cycling) will not occur.")
18944 (defvar org-tab-after-check-for-table-hook nil
18945 "Hook for functions to attach themselves to TAB.
18946 See `org-ctrl-c-ctrl-c-hook' for more information.
18947 This hook runs after it has been established that the cursor is not in a
18948 table, but before checking if the cursor is in a headline or if global cycling
18949 should be done.
18950 If any function in this hook returns t, not other actions like visibility
18951 cycling will be done.")
18953 (defvar org-tab-after-check-for-cycling-hook nil
18954 "Hook for functions to attach themselves to TAB.
18955 See `org-ctrl-c-ctrl-c-hook' for more information.
18956 This hook runs after it has been established that not table field motion and
18957 not visibility should be done because of current context. This is probably
18958 the place where a package like yasnippets can hook in.")
18960 (defvar org-tab-before-tab-emulation-hook nil
18961 "Hook for functions to attach themselves to TAB.
18962 See `org-ctrl-c-ctrl-c-hook' for more information.
18963 This hook runs after every other options for TAB have been exhausted, but
18964 before indentation and \t insertion takes place.")
18966 (defvar org-metaleft-hook nil
18967 "Hook for functions attaching themselves to `M-left'.
18968 See `org-ctrl-c-ctrl-c-hook' for more information.")
18969 (defvar org-metaright-hook nil
18970 "Hook for functions attaching themselves to `M-right'.
18971 See `org-ctrl-c-ctrl-c-hook' for more information.")
18972 (defvar org-metaup-hook nil
18973 "Hook for functions attaching themselves to `M-up'.
18974 See `org-ctrl-c-ctrl-c-hook' for more information.")
18975 (defvar org-metadown-hook nil
18976 "Hook for functions attaching themselves to `M-down'.
18977 See `org-ctrl-c-ctrl-c-hook' for more information.")
18978 (defvar org-shiftmetaleft-hook nil
18979 "Hook for functions attaching themselves to `M-S-left'.
18980 See `org-ctrl-c-ctrl-c-hook' for more information.")
18981 (defvar org-shiftmetaright-hook nil
18982 "Hook for functions attaching themselves to `M-S-right'.
18983 See `org-ctrl-c-ctrl-c-hook' for more information.")
18984 (defvar org-shiftmetaup-hook nil
18985 "Hook for functions attaching themselves to `M-S-up'.
18986 See `org-ctrl-c-ctrl-c-hook' for more information.")
18987 (defvar org-shiftmetadown-hook nil
18988 "Hook for functions attaching themselves to `M-S-down'.
18989 See `org-ctrl-c-ctrl-c-hook' for more information.")
18990 (defvar org-metareturn-hook nil
18991 "Hook for functions attaching themselves to `M-RET'.
18992 See `org-ctrl-c-ctrl-c-hook' for more information.")
18993 (defvar org-shiftup-hook nil
18994 "Hook for functions attaching themselves to `S-up'.
18995 See `org-ctrl-c-ctrl-c-hook' for more information.")
18996 (defvar org-shiftup-final-hook nil
18997 "Hook for functions attaching themselves to `S-up'.
18998 This one runs after all other options except shift-select have been excluded.
18999 See `org-ctrl-c-ctrl-c-hook' for more information.")
19000 (defvar org-shiftdown-hook nil
19001 "Hook for functions attaching themselves to `S-down'.
19002 See `org-ctrl-c-ctrl-c-hook' for more information.")
19003 (defvar org-shiftdown-final-hook nil
19004 "Hook for functions attaching themselves to `S-down'.
19005 This one runs after all other options except shift-select have been excluded.
19006 See `org-ctrl-c-ctrl-c-hook' for more information.")
19007 (defvar org-shiftleft-hook nil
19008 "Hook for functions attaching themselves to `S-left'.
19009 See `org-ctrl-c-ctrl-c-hook' for more information.")
19010 (defvar org-shiftleft-final-hook nil
19011 "Hook for functions attaching themselves to `S-left'.
19012 This one runs after all other options except shift-select have been excluded.
19013 See `org-ctrl-c-ctrl-c-hook' for more information.")
19014 (defvar org-shiftright-hook nil
19015 "Hook for functions attaching themselves to `S-right'.
19016 See `org-ctrl-c-ctrl-c-hook' for more information.")
19017 (defvar org-shiftright-final-hook nil
19018 "Hook for functions attaching themselves to `S-right'.
19019 This one runs after all other options except shift-select have been excluded.
19020 See `org-ctrl-c-ctrl-c-hook' for more information.")
19022 (defun org-modifier-cursor-error ()
19023 "Throw an error, a modified cursor command was applied in wrong context."
19024 (error "This command is active in special context like tables, headlines or items"))
19026 (defun org-shiftselect-error ()
19027 "Throw an error because Shift-Cursor command was applied in wrong context."
19028 (if (and (boundp 'shift-select-mode) shift-select-mode)
19029 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19030 (error "This command works only in special context like headlines or timestamps")))
19032 (defun org-call-for-shift-select (cmd)
19033 (let ((this-command-keys-shift-translated t))
19034 (call-interactively cmd)))
19036 (defun org-shifttab (&optional arg)
19037 "Global visibility cycling or move to previous table field.
19038 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19039 on context.
19040 See the individual commands for more information."
19041 (interactive "P")
19042 (cond
19043 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19044 ((integerp arg)
19045 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19046 (message "Content view to level: %d" arg)
19047 (org-content (prefix-numeric-value arg2))
19048 (setq org-cycle-global-status 'overview)))
19049 (t (call-interactively 'org-global-cycle))))
19051 (defun org-shiftmetaleft ()
19052 "Promote subtree or delete table column.
19053 Calls `org-promote-subtree', `org-outdent-item-tree', or
19054 `org-table-delete-column', depending on context. See the
19055 individual commands for more information."
19056 (interactive)
19057 (cond
19058 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19059 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19060 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19061 ((if (not (org-region-active-p)) (org-at-item-p)
19062 (save-excursion (goto-char (region-beginning))
19063 (org-at-item-p)))
19064 (call-interactively 'org-outdent-item-tree))
19065 (t (org-modifier-cursor-error))))
19067 (defun org-shiftmetaright ()
19068 "Demote subtree or insert table column.
19069 Calls `org-demote-subtree', `org-indent-item-tree', or
19070 `org-table-insert-column', depending on context. See the
19071 individual commands for more information."
19072 (interactive)
19073 (cond
19074 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19075 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19076 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19077 ((if (not (org-region-active-p)) (org-at-item-p)
19078 (save-excursion (goto-char (region-beginning))
19079 (org-at-item-p)))
19080 (call-interactively 'org-indent-item-tree))
19081 (t (org-modifier-cursor-error))))
19083 (defun org-shiftmetaup (&optional arg)
19084 "Move subtree up or kill table row.
19085 Calls `org-move-subtree-up' or `org-table-kill-row' or
19086 `org-move-item-up' or `org-timestamp-up', depending on context.
19087 See the individual commands for more information."
19088 (interactive "P")
19089 (cond
19090 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19091 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19092 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19093 ((org-at-item-p) (call-interactively 'org-move-item-up))
19094 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19095 (call-interactively 'org-timestamp-up)))
19096 (t (org-modifier-cursor-error))))
19098 (defun org-shiftmetadown (&optional arg)
19099 "Move subtree down or insert table row.
19100 Calls `org-move-subtree-down' or `org-table-insert-row' or
19101 `org-move-item-down' or `org-timestamp-up', depending on context.
19102 See the individual commands for more information."
19103 (interactive "P")
19104 (cond
19105 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19106 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19107 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19108 ((org-at-item-p) (call-interactively 'org-move-item-down))
19109 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19110 (call-interactively 'org-timestamp-down)))
19111 (t (org-modifier-cursor-error))))
19113 (defsubst org-hidden-tree-error ()
19114 (error
19115 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19117 (defun org-metaleft (&optional arg)
19118 "Promote heading or move table column to left.
19119 Calls `org-do-promote' or `org-table-move-column', depending on context.
19120 With no specific context, calls the Emacs default `backward-word'.
19121 See the individual commands for more information."
19122 (interactive "P")
19123 (cond
19124 ((run-hook-with-args-until-success 'org-metaleft-hook))
19125 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19126 ((org-with-limited-levels
19127 (or (org-at-heading-p)
19128 (and (org-region-active-p)
19129 (save-excursion
19130 (goto-char (region-beginning))
19131 (org-at-heading-p)))))
19132 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19133 (call-interactively 'org-do-promote))
19134 ;; At an inline task.
19135 ((org-at-heading-p)
19136 (call-interactively 'org-inlinetask-promote))
19137 ((or (org-at-item-p)
19138 (and (org-region-active-p)
19139 (save-excursion
19140 (goto-char (region-beginning))
19141 (org-at-item-p))))
19142 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19143 (call-interactively 'org-outdent-item))
19144 (t (call-interactively 'backward-word))))
19146 (defun org-metaright (&optional arg)
19147 "Demote a subtree, a list item or move table column to right.
19148 In front of a drawer or a block keyword, indent it correctly.
19149 With no specific context, calls the Emacs default `forward-word'.
19150 See the individual commands for more information."
19151 (interactive "P")
19152 (cond
19153 ((run-hook-with-args-until-success 'org-metaright-hook))
19154 ((org-at-table-p) (call-interactively 'org-table-move-column))
19155 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19156 ((org-at-block-p) (call-interactively 'org-indent-block))
19157 ((org-with-limited-levels
19158 (or (org-at-heading-p)
19159 (and (org-region-active-p)
19160 (save-excursion
19161 (goto-char (region-beginning))
19162 (org-at-heading-p)))))
19163 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19164 (call-interactively 'org-do-demote))
19165 ;; At an inline task.
19166 ((org-at-heading-p)
19167 (call-interactively 'org-inlinetask-demote))
19168 ((or (org-at-item-p)
19169 (and (org-region-active-p)
19170 (save-excursion
19171 (goto-char (region-beginning))
19172 (org-at-item-p))))
19173 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19174 (call-interactively 'org-indent-item))
19175 (t (call-interactively 'forward-word))))
19177 (defun org-check-for-hidden (what)
19178 "Check if there are hidden headlines/items in the current visual line.
19179 WHAT can be either `headlines' or `items'. If the current line is
19180 an outline or item heading and it has a folded subtree below it,
19181 this function returns t, nil otherwise."
19182 (let ((re (cond
19183 ((eq what 'headlines) org-outline-regexp-bol)
19184 ((eq what 'items) (org-item-beginning-re))
19185 (t (error "This should not happen"))))
19186 beg end)
19187 (save-excursion
19188 (catch 'exit
19189 (unless (org-region-active-p)
19190 (setq beg (point-at-bol))
19191 (beginning-of-line 2)
19192 (while (and (not (eobp)) ;; this is like `next-line'
19193 (get-char-property (1- (point)) 'invisible))
19194 (beginning-of-line 2))
19195 (setq end (point))
19196 (goto-char beg)
19197 (goto-char (point-at-eol))
19198 (setq end (max end (point)))
19199 (while (re-search-forward re end t)
19200 (if (get-char-property (match-beginning 0) 'invisible)
19201 (throw 'exit t))))
19202 nil))))
19204 (defun org-metaup (&optional arg)
19205 "Move subtree up or move table row up.
19206 Calls `org-move-subtree-up' or `org-table-move-row' or
19207 `org-move-item-up', depending on context. See the individual commands
19208 for more information."
19209 (interactive "P")
19210 (cond
19211 ((run-hook-with-args-until-success 'org-metaup-hook))
19212 ((org-region-active-p)
19213 (let* ((a (min (region-beginning) (region-end)))
19214 (b (1- (max (region-beginning) (region-end))))
19215 (c (save-excursion (goto-char a)
19216 (move-beginning-of-line 0)))
19217 (d (save-excursion (goto-char a)
19218 (move-end-of-line 0) (point))))
19219 (transpose-regions a b c d)
19220 (goto-char c)))
19221 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19222 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19223 ((org-at-item-p) (call-interactively 'org-move-item-up))
19224 (t (org-drag-element-backward))))
19226 (defun org-metadown (&optional arg)
19227 "Move subtree down or move table row down.
19228 Calls `org-move-subtree-down' or `org-table-move-row' or
19229 `org-move-item-down', depending on context. See the individual
19230 commands for more information."
19231 (interactive "P")
19232 (cond
19233 ((run-hook-with-args-until-success 'org-metadown-hook))
19234 ((org-region-active-p)
19235 (let* ((a (min (region-beginning) (region-end)))
19236 (b (max (region-beginning) (region-end)))
19237 (c (save-excursion (goto-char b)
19238 (move-beginning-of-line 1)))
19239 (d (save-excursion (goto-char b)
19240 (move-end-of-line 1) (1+ (point)))))
19241 (transpose-regions a b c d)
19242 (goto-char d)))
19243 ((org-at-table-p) (call-interactively 'org-table-move-row))
19244 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19245 ((org-at-item-p) (call-interactively 'org-move-item-down))
19246 (t (org-drag-element-forward))))
19248 (defun org-shiftup (&optional arg)
19249 "Increase item in timestamp or increase priority of current headline.
19250 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19251 depending on context. See the individual commands for more information."
19252 (interactive "P")
19253 (cond
19254 ((run-hook-with-args-until-success 'org-shiftup-hook))
19255 ((and org-support-shift-select (org-region-active-p))
19256 (org-call-for-shift-select 'previous-line))
19257 ((org-at-timestamp-p t)
19258 (call-interactively (if org-edit-timestamp-down-means-later
19259 'org-timestamp-down 'org-timestamp-up)))
19260 ((and (not (eq org-support-shift-select 'always))
19261 org-enable-priority-commands
19262 (org-at-heading-p))
19263 (call-interactively 'org-priority-up))
19264 ((and (not org-support-shift-select) (org-at-item-p))
19265 (call-interactively 'org-previous-item))
19266 ((org-clocktable-try-shift 'up arg))
19267 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19268 (org-support-shift-select
19269 (org-call-for-shift-select 'previous-line))
19270 (t (org-shiftselect-error))))
19272 (defun org-shiftdown (&optional arg)
19273 "Decrease item in timestamp or decrease priority of current headline.
19274 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19275 depending on context. See the individual commands for more information."
19276 (interactive "P")
19277 (cond
19278 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19279 ((and org-support-shift-select (org-region-active-p))
19280 (org-call-for-shift-select 'next-line))
19281 ((org-at-timestamp-p t)
19282 (call-interactively (if org-edit-timestamp-down-means-later
19283 'org-timestamp-up 'org-timestamp-down)))
19284 ((and (not (eq org-support-shift-select 'always))
19285 org-enable-priority-commands
19286 (org-at-heading-p))
19287 (call-interactively 'org-priority-down))
19288 ((and (not org-support-shift-select) (org-at-item-p))
19289 (call-interactively 'org-next-item))
19290 ((org-clocktable-try-shift 'down arg))
19291 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19292 (org-support-shift-select
19293 (org-call-for-shift-select 'next-line))
19294 (t (org-shiftselect-error))))
19296 (defun org-shiftright (&optional arg)
19297 "Cycle the thing at point or in the current line, depending on context.
19298 Depending on context, this does one of the following:
19300 - switch a timestamp at point one day into the future
19301 - on a headline, switch to the next TODO keyword.
19302 - on an item, switch entire list to the next bullet type
19303 - on a property line, switch to the next allowed value
19304 - on a clocktable definition line, move time block into the future"
19305 (interactive "P")
19306 (cond
19307 ((run-hook-with-args-until-success 'org-shiftright-hook))
19308 ((and org-support-shift-select (org-region-active-p))
19309 (org-call-for-shift-select 'forward-char))
19310 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19311 ((and (not (eq org-support-shift-select 'always))
19312 (org-at-heading-p))
19313 (let ((org-inhibit-logging
19314 (not org-treat-S-cursor-todo-selection-as-state-change))
19315 (org-inhibit-blocking
19316 (not org-treat-S-cursor-todo-selection-as-state-change)))
19317 (org-call-with-arg 'org-todo 'right)))
19318 ((or (and org-support-shift-select
19319 (not (eq org-support-shift-select 'always))
19320 (org-at-item-bullet-p))
19321 (and (not org-support-shift-select) (org-at-item-p)))
19322 (org-call-with-arg 'org-cycle-list-bullet nil))
19323 ((and (not (eq org-support-shift-select 'always))
19324 (org-at-property-p))
19325 (call-interactively 'org-property-next-allowed-value))
19326 ((org-clocktable-try-shift 'right arg))
19327 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19328 (org-support-shift-select
19329 (org-call-for-shift-select 'forward-char))
19330 (t (org-shiftselect-error))))
19332 (defun org-shiftleft (&optional arg)
19333 "Cycle the thing at point or in the current line, depending on context.
19334 Depending on context, this does one of the following:
19336 - switch a timestamp at point one day into the past
19337 - on a headline, switch to the previous TODO keyword.
19338 - on an item, switch entire list to the previous bullet type
19339 - on a property line, switch to the previous allowed value
19340 - on a clocktable definition line, move time block into the past"
19341 (interactive "P")
19342 (cond
19343 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19344 ((and org-support-shift-select (org-region-active-p))
19345 (org-call-for-shift-select 'backward-char))
19346 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19347 ((and (not (eq org-support-shift-select 'always))
19348 (org-at-heading-p))
19349 (let ((org-inhibit-logging
19350 (not org-treat-S-cursor-todo-selection-as-state-change))
19351 (org-inhibit-blocking
19352 (not org-treat-S-cursor-todo-selection-as-state-change)))
19353 (org-call-with-arg 'org-todo 'left)))
19354 ((or (and org-support-shift-select
19355 (not (eq org-support-shift-select 'always))
19356 (org-at-item-bullet-p))
19357 (and (not org-support-shift-select) (org-at-item-p)))
19358 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19359 ((and (not (eq org-support-shift-select 'always))
19360 (org-at-property-p))
19361 (call-interactively 'org-property-previous-allowed-value))
19362 ((org-clocktable-try-shift 'left arg))
19363 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19364 (org-support-shift-select
19365 (org-call-for-shift-select 'backward-char))
19366 (t (org-shiftselect-error))))
19368 (defun org-shiftcontrolright ()
19369 "Switch to next TODO set."
19370 (interactive)
19371 (cond
19372 ((and org-support-shift-select (org-region-active-p))
19373 (org-call-for-shift-select 'forward-word))
19374 ((and (not (eq org-support-shift-select 'always))
19375 (org-at-heading-p))
19376 (org-call-with-arg 'org-todo 'nextset))
19377 (org-support-shift-select
19378 (org-call-for-shift-select 'forward-word))
19379 (t (org-shiftselect-error))))
19381 (defun org-shiftcontrolleft ()
19382 "Switch to previous TODO set."
19383 (interactive)
19384 (cond
19385 ((and org-support-shift-select (org-region-active-p))
19386 (org-call-for-shift-select 'backward-word))
19387 ((and (not (eq org-support-shift-select 'always))
19388 (org-at-heading-p))
19389 (org-call-with-arg 'org-todo 'previousset))
19390 (org-support-shift-select
19391 (org-call-for-shift-select 'backward-word))
19392 (t (org-shiftselect-error))))
19394 (defun org-shiftcontrolup (&optional n)
19395 "Change timestamps synchronously up in CLOCK log lines.
19396 Optional argument N tells to change by that many units."
19397 (interactive "P")
19398 (cond ((and (not org-support-shift-select)
19399 (org-at-clock-log-p)
19400 (org-at-timestamp-p t))
19401 (org-clock-timestamps-up n))
19402 (t (org-shiftselect-error))))
19404 (defun org-shiftcontroldown (&optional n)
19405 "Change timestamps synchronously down in CLOCK log lines.
19406 Optional argument N tells to change by that many units."
19407 (interactive "P")
19408 (cond ((and (not org-support-shift-select)
19409 (org-at-clock-log-p)
19410 (org-at-timestamp-p t))
19411 (org-clock-timestamps-down n))
19412 (t (org-shiftselect-error))))
19414 (defun org-ctrl-c-ret ()
19415 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19416 (interactive)
19417 (cond
19418 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19419 (t (call-interactively 'org-insert-heading))))
19421 (defun org-find-visible ()
19422 (let ((s (point)))
19423 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19424 (get-char-property s 'invisible)))
19426 (defun org-find-invisible ()
19427 (let ((s (point)))
19428 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19429 (not (get-char-property s 'invisible))))
19432 (defun org-copy-visible (beg end)
19433 "Copy the visible parts of the region."
19434 (interactive "r")
19435 (let (snippets s)
19436 (save-excursion
19437 (save-restriction
19438 (narrow-to-region beg end)
19439 (setq s (goto-char (point-min)))
19440 (while (not (= (point) (point-max)))
19441 (goto-char (org-find-invisible))
19442 (push (buffer-substring s (point)) snippets)
19443 (setq s (goto-char (org-find-visible))))))
19444 (kill-new (apply 'concat (nreverse snippets)))))
19446 (defun org-copy-special ()
19447 "Copy region in table or copy current subtree.
19448 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19449 See the individual commands for more information."
19450 (interactive)
19451 (call-interactively
19452 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19454 (defun org-cut-special ()
19455 "Cut region in table or cut current subtree.
19456 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19457 See the individual commands for more information."
19458 (interactive)
19459 (call-interactively
19460 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19462 (defun org-paste-special (arg)
19463 "Paste rectangular region into table, or past subtree relative to level.
19464 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19465 See the individual commands for more information."
19466 (interactive "P")
19467 (if (org-at-table-p)
19468 (org-table-paste-rectangle)
19469 (org-paste-subtree arg)))
19471 (defsubst org-in-fixed-width-region-p ()
19472 "Is point in a fixed-width region?"
19473 (save-match-data
19474 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19476 (defun org-edit-special (&optional arg)
19477 "Call a special editor for the element at point.
19478 When at a table, call the formula editor with `org-table-edit-formulas'.
19479 When in a source code block, call `org-edit-src-code'.
19480 When in a fixed-width region, call `org-edit-fixed-width-region'.
19481 When at an #+INCLUDE keyword, visit the included file.
19482 On a link, call `ffap' to visit the link at point.
19483 Otherwise, return a user error."
19484 (interactive)
19485 (let ((element (org-element-at-point)))
19486 (case (org-element-type element)
19487 (src-block
19488 (if (not arg) (org-edit-src-code)
19489 (let* ((info (org-babel-get-src-block-info))
19490 (lang (nth 0 info))
19491 (params (nth 2 info))
19492 (session (cdr (assq :session params))))
19493 (if (not session) (org-edit-src-code)
19494 ;; At a src-block with a session and function called with
19495 ;; an ARG: switch to the buffer related to the inferior
19496 ;; process.
19497 (funcall (intern (concat "org-babel-prep-session:" lang))
19498 session params)))))
19499 (keyword
19500 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19501 (find-file
19502 (org-remove-double-quotes
19503 (car (org-split-string (org-element-property :value element)))))
19504 (user-error "No special environment to edit here")))
19505 (table
19506 (if (eq (org-element-property :type element) 'table.el)
19507 (org-edit-src-code)
19508 (call-interactively 'org-table-edit-formulas)))
19509 ;; Only Org tables contain `table-row' type elements.
19510 (table-row (call-interactively 'org-table-edit-formulas))
19511 ((example-block export-block) (org-edit-src-code))
19512 (fixed-width (org-edit-fixed-width-region))
19513 (otherwise
19514 ;; No notable element at point. Though, we may be at a link,
19515 ;; which is an object. Thus, scan deeper.
19516 (if (eq (org-element-type (org-element-context element)) 'link)
19517 (call-interactively 'ffap)
19518 (user-error "No special environment to edit here"))))))
19520 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19521 (defun org-ctrl-c-ctrl-c (&optional arg)
19522 "Set tags in headline, or update according to changed information at point.
19524 This command does many different things, depending on context:
19526 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19527 this is what we do.
19529 - If the cursor is on a statistics cookie, update it.
19531 - If the cursor is in a headline, prompt for tags and insert them
19532 into the current line, aligned to `org-tags-column'. When called
19533 with prefix arg, realign all tags in the current buffer.
19535 - If the cursor is in one of the special #+KEYWORD lines, this
19536 triggers scanning the buffer for these lines and updating the
19537 information.
19539 - If the cursor is inside a table, realign the table. This command
19540 works even if the automatic table editor has been turned off.
19542 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19543 the entire table.
19545 - If the cursor is at a footnote reference or definition, jump to
19546 the corresponding definition or references, respectively.
19548 - If the cursor is a the beginning of a dynamic block, update it.
19550 - If the current buffer is a capture buffer, close note and file it.
19552 - If the cursor is on a <<<target>>>, update radio targets and
19553 corresponding links in this buffer.
19555 - If the cursor is on a numbered item in a plain list, renumber the
19556 ordered list.
19558 - If the cursor is on a checkbox, toggle it.
19560 - If the cursor is on a code block, evaluate it. The variable
19561 `org-confirm-babel-evaluate' can be used to control prompting
19562 before code block evaluation, by default every code block
19563 evaluation requires confirmation. Code block evaluation can be
19564 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19565 (interactive "P")
19566 (cond
19567 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19568 org-occur-highlights
19569 org-latex-fragment-image-overlays)
19570 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19571 (org-remove-occur-highlights)
19572 (org-remove-latex-fragment-image-overlays)
19573 (message "Temporary highlights/overlays removed from current buffer"))
19574 ((and (local-variable-p 'org-finish-function (current-buffer))
19575 (fboundp org-finish-function))
19576 (funcall org-finish-function))
19577 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19579 (let* ((context (org-element-context)) (type (org-element-type context)))
19580 ;; Test if point is within blanks at the end of an element.
19581 (if (save-excursion
19582 (or (not context)
19583 (beginning-of-line)
19584 (and (looking-at "[ \t]*$")
19585 (skip-chars-forward " \r\t\n")
19586 (>= (point) (org-element-property :end context)))))
19587 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19588 (user-error "C-c C-c can do nothing useful at this location"))
19589 ;; For convenience: at the first line of a paragraph on the
19590 ;; same line as an item, apply function on that item instead.
19591 (when (eq type 'paragraph)
19592 (let ((parent (org-element-property :parent context)))
19593 (when (and (eq (org-element-type parent) 'item)
19594 (= (point-at-bol) (org-element-property :begin parent)))
19595 (setq context parent type 'item))))
19596 ;; Act according to type of element or object at point.
19597 (case type
19598 (clock (org-clock-update-time-maybe))
19599 (dynamic-block
19600 (save-excursion
19601 (goto-char (org-element-property :post-affiliated context))
19602 (org-update-dblock)))
19603 (footnote-definition
19604 (goto-char (org-element-property :post-affiliated context))
19605 (call-interactively 'org-footnote-action))
19606 (footnote-reference (call-interactively 'org-footnote-action))
19607 ((headline inlinetask)
19608 (save-excursion (goto-char (org-element-property :begin context))
19609 (call-interactively 'org-set-tags)))
19610 (item
19611 ;; At an item: a double C-u set checkbox to "[-]"
19612 ;; unconditionally, whereas a single one will toggle its
19613 ;; presence. Without an universal argument, if the item
19614 ;; has a checkbox, toggle it. Otherwise repair the list.
19615 (let* ((box (org-element-property :checkbox context))
19616 (struct (org-element-property :structure context))
19617 (old-struct (copy-tree struct))
19618 (parents (org-list-parents-alist struct))
19619 (prevs (org-list-prevs-alist struct))
19620 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19621 (org-list-set-checkbox
19622 (org-element-property :begin context) struct
19623 (cond ((equal arg '(16)) "[-]")
19624 ((and (not box) (equal arg '(4))) "[ ]")
19625 ((or (not box) (equal arg '(4))) nil)
19626 ((eq box 'on) "[ ]")
19627 (t "[X]")))
19628 ;; Mimic `org-list-write-struct' but with grabbing
19629 ;; a return value from `org-list-struct-fix-box'.
19630 (org-list-struct-fix-ind struct parents 2)
19631 (org-list-struct-fix-item-end struct)
19632 (org-list-struct-fix-bul struct prevs)
19633 (org-list-struct-fix-ind struct parents)
19634 (let ((block-item
19635 (org-list-struct-fix-box struct parents prevs orderedp)))
19636 (if (and box (equal struct old-struct))
19637 (if (equal arg '(16))
19638 (message "Checkboxes already reset")
19639 (user-error "Cannot toggle this checkbox: %s"
19640 (if (eq box 'on)
19641 "all subitems checked"
19642 "unchecked subitems")))
19643 (org-list-struct-apply-struct struct old-struct)
19644 (org-update-checkbox-count-maybe))
19645 (when block-item
19646 (message "Checkboxes were removed due to empty box at line %d"
19647 (org-current-line block-item))))))
19648 (keyword
19649 (let ((org-inhibit-startup-visibility-stuff t)
19650 (org-startup-align-all-tables nil))
19651 (when (boundp 'org-table-coordinate-overlays)
19652 (mapc 'delete-overlay org-table-coordinate-overlays)
19653 (setq org-table-coordinate-overlays nil))
19654 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19655 (message "Local setup has been refreshed"))
19656 (plain-list
19657 ;; At a plain list, with a double C-u argument, set
19658 ;; checkboxes of each item to "[-]", whereas a single one
19659 ;; will toggle their presence according to the state of the
19660 ;; first item in the list. Without an argument, repair the
19661 ;; list.
19662 (let* ((begin (org-element-property :contents-begin context))
19663 (struct (org-element-property :structure context))
19664 (old-struct (copy-tree struct))
19665 (first-box (save-excursion
19666 (goto-char begin)
19667 (looking-at org-list-full-item-re)
19668 (match-string-no-properties 3)))
19669 (new-box (cond ((equal arg '(16)) "[-]")
19670 ((equal arg '(4)) (unless first-box "[ ]"))
19671 ((equal first-box "[X]") "[ ]")
19672 (t "[X]"))))
19673 (cond
19674 (arg
19675 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19676 (org-list-get-all-items
19677 begin struct (org-list-prevs-alist struct))))
19678 ((and first-box (eq (point) begin))
19679 ;; For convenience, when point is at bol on the first
19680 ;; item of the list and no argument is provided, simply
19681 ;; toggle checkbox of that item, if any.
19682 (org-list-set-checkbox begin struct new-box)))
19683 (org-list-write-struct
19684 struct (org-list-parents-alist struct) old-struct)
19685 (org-update-checkbox-count-maybe)
19686 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19687 ((property-drawer node-property)
19688 (call-interactively 'org-property-action))
19689 ((radio-target target)
19690 (call-interactively 'org-update-radio-target-regexp))
19691 (statistics-cookie
19692 (call-interactively 'org-update-statistics-cookies))
19693 ((table table-cell table-row)
19694 ;; At a table, recalculate every field and align it. Also
19695 ;; send the table if necessary. If the table has
19696 ;; a `table.el' type, just give up. At a table row or
19697 ;; cell, maybe recalculate line but always align table.
19698 (if (eq (org-element-property :type context) 'table.el)
19699 (message "Use C-c ' to edit table.el tables")
19700 (let ((org-enable-table-editor t))
19701 (if (or (eq type 'table)
19702 ;; Check if point is at a TBLFM line.
19703 (and (eq type 'table-row)
19704 (= (point) (org-element-property :end context))))
19705 (save-excursion
19706 (goto-char (org-element-property :contents-begin context))
19707 (org-call-with-arg 'org-table-recalculate (or arg t))
19708 (orgtbl-send-table 'maybe))
19709 (org-table-maybe-eval-formula)
19710 (cond (arg (call-interactively 'org-table-recalculate))
19711 ((org-table-maybe-recalculate-line))
19712 (t (org-table-align)))))))
19713 (timestamp (org-timestamp-change 0 'day))
19714 (otherwise
19715 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19716 (user-error
19717 "C-c C-c can do nothing useful at this location")))))))))
19719 (defun org-mode-restart ()
19720 "Restart Org-mode, to scan again for special lines.
19721 Also updates the keyword regular expressions."
19722 (interactive)
19723 (org-mode)
19724 (message "Org-mode restarted"))
19726 (defun org-kill-note-or-show-branches ()
19727 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19728 (interactive)
19729 (if (not org-finish-function)
19730 (progn
19731 (hide-subtree)
19732 (call-interactively 'show-branches))
19733 (let ((org-note-abort t))
19734 (funcall org-finish-function))))
19736 (defun org-return (&optional indent)
19737 "Goto next table row or insert a newline.
19738 Calls `org-table-next-row' or `newline', depending on context.
19739 See the individual commands for more information."
19740 (interactive)
19741 (let (org-ts-what)
19742 (cond
19743 ((or (bobp) (org-in-src-block-p))
19744 (if indent (newline-and-indent) (newline)))
19745 ((org-at-table-p)
19746 (org-table-justify-field-maybe)
19747 (call-interactively 'org-table-next-row))
19748 ;; when `newline-and-indent' is called within a list, make sure
19749 ;; text moved stays inside the item.
19750 ((and (org-in-item-p) indent)
19751 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19752 (progn
19753 (save-match-data (newline))
19754 (org-indent-line-to (length (match-string 0))))
19755 (let ((ind (org-get-indentation)))
19756 (newline)
19757 (if (org-looking-back org-list-end-re)
19758 (org-indent-line)
19759 (org-indent-line-to ind)))))
19760 ((and org-return-follows-link
19761 (org-at-timestamp-p t)
19762 (not (eq org-ts-what 'after)))
19763 (org-follow-timestamp-link))
19764 ((and org-return-follows-link
19765 (let ((tprop (get-text-property (point) 'face)))
19766 (or (eq tprop 'org-link)
19767 (and (listp tprop) (memq 'org-link tprop)))))
19768 (call-interactively 'org-open-at-point))
19769 ((and (org-at-heading-p)
19770 (looking-at
19771 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19772 (org-show-entry)
19773 (end-of-line 1)
19774 (newline))
19775 (t (if indent (newline-and-indent) (newline))))))
19777 (defun org-return-indent ()
19778 "Goto next table row or insert a newline and indent.
19779 Calls `org-table-next-row' or `newline-and-indent', depending on
19780 context. See the individual commands for more information."
19781 (interactive)
19782 (org-return t))
19784 (defun org-ctrl-c-star ()
19785 "Compute table, or change heading status of lines.
19786 Calls `org-table-recalculate' or `org-toggle-heading',
19787 depending on context."
19788 (interactive)
19789 (cond
19790 ((org-at-table-p)
19791 (call-interactively 'org-table-recalculate))
19793 ;; Convert all lines in region to list items
19794 (call-interactively 'org-toggle-heading))))
19796 (defun org-ctrl-c-minus ()
19797 "Insert separator line in table or modify bullet status of line.
19798 Also turns a plain line or a region of lines into list items.
19799 Calls `org-table-insert-hline', `org-toggle-item', or
19800 `org-cycle-list-bullet', depending on context."
19801 (interactive)
19802 (cond
19803 ((org-at-table-p)
19804 (call-interactively 'org-table-insert-hline))
19805 ((org-region-active-p)
19806 (call-interactively 'org-toggle-item))
19807 ((org-in-item-p)
19808 (call-interactively 'org-cycle-list-bullet))
19810 (call-interactively 'org-toggle-item))))
19812 (defun org-toggle-item (arg)
19813 "Convert headings or normal lines to items, items to normal lines.
19814 If there is no active region, only the current line is considered.
19816 If the first non blank line in the region is an headline, convert
19817 all headlines to items, shifting text accordingly.
19819 If it is an item, convert all items to normal lines.
19821 If it is normal text, change region into an item. With a prefix
19822 argument ARG, change each line in region into an item."
19823 (interactive "P")
19824 (let ((shift-text
19825 (function
19826 ;; Shift text in current section to IND, from point to END.
19827 ;; The function leaves point to END line.
19828 (lambda (ind end)
19829 (let ((min-i 1000) (end (copy-marker end)))
19830 ;; First determine the minimum indentation (MIN-I) of
19831 ;; the text.
19832 (save-excursion
19833 (catch 'exit
19834 (while (< (point) end)
19835 (let ((i (org-get-indentation)))
19836 (cond
19837 ;; Skip blank lines and inline tasks.
19838 ((looking-at "^[ \t]*$"))
19839 ((looking-at org-outline-regexp-bol))
19840 ;; We can't find less than 0 indentation.
19841 ((zerop i) (throw 'exit (setq min-i 0)))
19842 ((< i min-i) (setq min-i i))))
19843 (forward-line))))
19844 ;; Then indent each line so that a line indented to
19845 ;; MIN-I becomes indented to IND. Ignore blank lines
19846 ;; and inline tasks in the process.
19847 (let ((delta (- ind min-i)))
19848 (while (< (point) end)
19849 (unless (or (looking-at "^[ \t]*$")
19850 (looking-at org-outline-regexp-bol))
19851 (org-indent-line-to (+ (org-get-indentation) delta)))
19852 (forward-line)))))))
19853 (skip-blanks
19854 (function
19855 ;; Return beginning of first non-blank line, starting from
19856 ;; line at POS.
19857 (lambda (pos)
19858 (save-excursion
19859 (goto-char pos)
19860 (skip-chars-forward " \r\t\n")
19861 (point-at-bol)))))
19862 beg end)
19863 ;; Determine boundaries of changes.
19864 (if (org-region-active-p)
19865 (setq beg (funcall skip-blanks (region-beginning))
19866 end (copy-marker (region-end)))
19867 (setq beg (funcall skip-blanks (point-at-bol))
19868 end (copy-marker (point-at-eol))))
19869 ;; Depending on the starting line, choose an action on the text
19870 ;; between BEG and END.
19871 (org-with-limited-levels
19872 (save-excursion
19873 (goto-char beg)
19874 (cond
19875 ;; Case 1. Start at an item: de-itemize. Note that it only
19876 ;; happens when a region is active: `org-ctrl-c-minus'
19877 ;; would call `org-cycle-list-bullet' otherwise.
19878 ((org-at-item-p)
19879 (while (< (point) end)
19880 (when (org-at-item-p)
19881 (skip-chars-forward " \t")
19882 (delete-region (point) (match-end 0)))
19883 (forward-line)))
19884 ;; Case 2. Start at an heading: convert to items.
19885 ((org-at-heading-p)
19886 (let* ((bul (org-list-bullet-string "-"))
19887 (bul-len (length bul))
19888 ;; Indentation of the first heading. It should be
19889 ;; relative to the indentation of its parent, if any.
19890 (start-ind (save-excursion
19891 (cond
19892 ((not org-adapt-indentation) 0)
19893 ((not (outline-previous-heading)) 0)
19894 (t (length (match-string 0))))))
19895 ;; Level of first heading. Further headings will be
19896 ;; compared to it to determine hierarchy in the list.
19897 (ref-level (org-reduced-level (org-outline-level))))
19898 (while (< (point) end)
19899 (let* ((level (org-reduced-level (org-outline-level)))
19900 (delta (max 0 (- level ref-level))))
19901 ;; If current headline is less indented than the first
19902 ;; one, set it as reference, in order to preserve
19903 ;; subtrees.
19904 (when (< level ref-level) (setq ref-level level))
19905 (replace-match bul t t)
19906 (org-indent-line-to (+ start-ind (* delta bul-len)))
19907 ;; Ensure all text down to END (or SECTION-END) belongs
19908 ;; to the newly created item.
19909 (let ((section-end (save-excursion
19910 (or (outline-next-heading) (point)))))
19911 (forward-line)
19912 (funcall shift-text
19913 (+ start-ind (* (1+ delta) bul-len))
19914 (min end section-end)))))))
19915 ;; Case 3. Normal line with ARG: turn each non-item line into
19916 ;; an item.
19917 (arg
19918 (while (< (point) end)
19919 (unless (or (org-at-heading-p) (org-at-item-p))
19920 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19921 (replace-match
19922 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19923 (forward-line)))
19924 ;; Case 4. Normal line without ARG: make the first line of
19925 ;; region an item, and shift indentation of others
19926 ;; lines to set them as item's body.
19927 (t (let* ((bul (org-list-bullet-string "-"))
19928 (bul-len (length bul))
19929 (ref-ind (org-get-indentation)))
19930 (skip-chars-forward " \t")
19931 (insert bul)
19932 (forward-line)
19933 (while (< (point) end)
19934 ;; Ensure that lines less indented than first one
19935 ;; still get included in item body.
19936 (funcall shift-text
19937 (+ ref-ind bul-len)
19938 (min end (save-excursion (or (outline-next-heading)
19939 (point)))))
19940 (forward-line)))))))))
19942 (defun org-toggle-heading (&optional nstars)
19943 "Convert headings to normal text, or items or text to headings.
19944 If there is no active region, only the current line is considered.
19946 With a \\[universal-argument] prefix, convert the whole list at
19947 point into heading.
19949 In a region:
19951 - If the first non blank line is an headline, remove the stars
19952 from all headlines in the region.
19954 - If it is a normal line turn each and every normal line (i.e. not an
19955 heading or an item) in the region into a heading.
19957 - If it is a plain list item, turn all plain list items into headings.
19959 When converting a line into a heading, the number of stars is chosen
19960 such that the lines become children of the current entry. However,
19961 when a prefix argument is given, its value determines the number of
19962 stars to add."
19963 (interactive "P")
19964 (let ((skip-blanks
19965 (function
19966 ;; Return beginning of first non-blank line, starting from
19967 ;; line at POS.
19968 (lambda (pos)
19969 (save-excursion
19970 (goto-char pos)
19971 (while (org-at-comment-p) (forward-line))
19972 (skip-chars-forward " \r\t\n")
19973 (point-at-bol)))))
19974 beg end toggled)
19975 ;; Determine boundaries of changes. If a universal prefix has
19976 ;; been given, put the list in a region. If region ends at a bol,
19977 ;; do not consider the last line to be in the region.
19979 (when (and current-prefix-arg (org-at-item-p))
19980 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19981 (org-mark-element))
19983 (if (org-region-active-p)
19984 (setq beg (funcall skip-blanks (region-beginning))
19985 end (copy-marker (save-excursion
19986 (goto-char (region-end))
19987 (if (bolp) (point) (point-at-eol)))))
19988 (setq beg (funcall skip-blanks (point-at-bol))
19989 end (copy-marker (point-at-eol))))
19990 ;; Ensure inline tasks don't count as headings.
19991 (org-with-limited-levels
19992 (save-excursion
19993 (goto-char beg)
19994 (cond
19995 ;; Case 1. Started at an heading: de-star headings.
19996 ((org-at-heading-p)
19997 (while (< (point) end)
19998 (when (org-at-heading-p t)
19999 (looking-at org-outline-regexp) (replace-match "")
20000 (setq toggled t))
20001 (forward-line)))
20002 ;; Case 2. Started at an item: change items into headlines.
20003 ;; One star will be added by `org-list-to-subtree'.
20004 ((org-at-item-p)
20005 (let* ((stars (make-string
20006 (if nstars
20007 ;; subtract the star that will be added again by
20008 ;; `org-list-to-subtree'
20009 (1- (prefix-numeric-value current-prefix-arg))
20010 (or (org-current-level) 0))
20011 ?*))
20012 (add-stars
20013 (cond (nstars "") ; stars from prefix only
20014 ((equal stars "") "") ; before first heading
20015 (org-odd-levels-only "*") ; inside heading, odd
20016 (t "")))) ; inside heading, oddeven
20017 (while (< (point) end)
20018 (when (org-at-item-p)
20019 ;; Pay attention to cases when region ends before list.
20020 (let* ((struct (org-list-struct))
20021 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20022 (save-restriction
20023 (narrow-to-region (point) list-end)
20024 (insert
20025 (org-list-to-subtree
20026 (org-list-parse-list t)
20027 '(:istart (concat stars add-stars (funcall get-stars depth))
20028 :icount (concat stars add-stars (funcall get-stars depth)))))))
20029 (setq toggled t))
20030 (forward-line))))
20031 ;; Case 3. Started at normal text: make every line an heading,
20032 ;; skipping headlines and items.
20033 (t (let* ((stars (make-string
20034 (if nstars
20035 (prefix-numeric-value current-prefix-arg)
20036 (or (org-current-level) 0))
20037 ?*))
20038 (add-stars
20039 (cond (nstars "") ; stars from prefix only
20040 ((equal stars "") "*") ; before first heading
20041 (org-odd-levels-only "**") ; inside heading, odd
20042 (t "*"))) ; inside heading, oddeven
20043 (rpl (concat stars add-stars " ")))
20044 (while (< (point) end)
20045 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20046 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20047 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20048 (forward-line)))))))
20049 (unless toggled (message "Cannot toggle heading from here"))))
20051 (defun org-meta-return (&optional arg)
20052 "Insert a new heading or wrap a region in a table.
20053 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20054 See the individual commands for more information."
20055 (interactive "P")
20056 (cond
20057 ((run-hook-with-args-until-success 'org-metareturn-hook))
20058 ((or (org-at-drawer-p) (org-at-property-p))
20059 (newline-and-indent))
20060 ((org-at-table-p)
20061 (call-interactively 'org-table-wrap-region))
20062 (t (call-interactively 'org-insert-heading))))
20064 ;;; Menu entries
20066 (defsubst org-in-subtree-not-table-p ()
20067 "Are we in a subtree and not in a table?"
20068 (and (not (org-before-first-heading-p))
20069 (not (org-at-table-p))))
20071 ;; Define the Org-mode menus
20072 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20073 '("Tbl"
20074 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20075 ["Next Field" org-cycle (org-at-table-p)]
20076 ["Previous Field" org-shifttab (org-at-table-p)]
20077 ["Next Row" org-return (org-at-table-p)]
20078 "--"
20079 ["Blank Field" org-table-blank-field (org-at-table-p)]
20080 ["Edit Field" org-table-edit-field (org-at-table-p)]
20081 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20082 "--"
20083 ("Column"
20084 ["Move Column Left" org-metaleft (org-at-table-p)]
20085 ["Move Column Right" org-metaright (org-at-table-p)]
20086 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20087 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20088 ("Row"
20089 ["Move Row Up" org-metaup (org-at-table-p)]
20090 ["Move Row Down" org-metadown (org-at-table-p)]
20091 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20092 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20093 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20094 "--"
20095 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20096 ("Rectangle"
20097 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20098 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20099 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20100 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20101 "--"
20102 ("Calculate"
20103 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20104 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20105 ["Edit Formulas" org-edit-special (org-at-table-p)]
20106 "--"
20107 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20108 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20109 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20110 "--"
20111 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20112 "--"
20113 ["Sum Column/Rectangle" org-table-sum
20114 (or (org-at-table-p) (org-region-active-p))]
20115 ["Which Column?" org-table-current-column (org-at-table-p)])
20116 ["Debug Formulas"
20117 org-table-toggle-formula-debugger
20118 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20119 ["Show Col/Row Numbers"
20120 org-table-toggle-coordinate-overlays
20121 :style toggle
20122 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20123 "--"
20124 ["Create" org-table-create (and (not (org-at-table-p))
20125 org-enable-table-editor)]
20126 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20127 ["Import from File" org-table-import (not (org-at-table-p))]
20128 ["Export to File" org-table-export (org-at-table-p)]
20129 "--"
20130 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20132 (easy-menu-define org-org-menu org-mode-map "Org menu"
20133 '("Org"
20134 ("Show/Hide"
20135 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20136 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20137 ["Sparse Tree..." org-sparse-tree t]
20138 ["Reveal Context" org-reveal t]
20139 ["Show All" show-all t]
20140 "--"
20141 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20142 "--"
20143 ["New Heading" org-insert-heading t]
20144 ("Navigate Headings"
20145 ["Up" outline-up-heading t]
20146 ["Next" outline-next-visible-heading t]
20147 ["Previous" outline-previous-visible-heading t]
20148 ["Next Same Level" outline-forward-same-level t]
20149 ["Previous Same Level" outline-backward-same-level t]
20150 "--"
20151 ["Jump" org-goto t])
20152 ("Edit Structure"
20153 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20154 "--"
20155 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20156 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20157 "--"
20158 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20159 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20160 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20161 "--"
20162 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20163 "--"
20164 ["Copy visible text" org-copy-visible t]
20165 "--"
20166 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20167 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20168 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20169 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20170 "--"
20171 ["Sort Region/Children" org-sort t]
20172 "--"
20173 ["Convert to odd levels" org-convert-to-odd-levels t]
20174 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20175 ("Editing"
20176 ["Emphasis..." org-emphasize t]
20177 ["Edit Source Example" org-edit-special t]
20178 "--"
20179 ["Footnote new/jump" org-footnote-action t]
20180 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20181 ("Archive"
20182 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20183 "--"
20184 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20185 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20186 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20188 "--"
20189 ("Hyperlinks"
20190 ["Store Link (Global)" org-store-link t]
20191 ["Find existing link to here" org-occur-link-in-agenda-files t]
20192 ["Insert Link" org-insert-link t]
20193 ["Follow Link" org-open-at-point t]
20194 "--"
20195 ["Next link" org-next-link t]
20196 ["Previous link" org-previous-link t]
20197 "--"
20198 ["Descriptive Links"
20199 org-toggle-link-display
20200 :style radio
20201 :selected org-descriptive-links
20203 ["Literal Links"
20204 org-toggle-link-display
20205 :style radio
20206 :selected (not org-descriptive-links)])
20207 "--"
20208 ("TODO Lists"
20209 ["TODO/DONE/-" org-todo t]
20210 ("Select keyword"
20211 ["Next keyword" org-shiftright (org-at-heading-p)]
20212 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20213 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20214 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20215 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20216 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20217 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20218 "--"
20219 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20220 :selected org-enforce-todo-dependencies :style toggle :active t]
20221 "Settings for tree at point"
20222 ["Do Children sequentially" org-toggle-ordered-property :style radio
20223 :selected (org-entry-get nil "ORDERED")
20224 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20225 ["Do Children parallel" org-toggle-ordered-property :style radio
20226 :selected (not (org-entry-get nil "ORDERED"))
20227 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20228 "--"
20229 ["Set Priority" org-priority t]
20230 ["Priority Up" org-shiftup t]
20231 ["Priority Down" org-shiftdown t]
20232 "--"
20233 ["Get news from all feeds" org-feed-update-all t]
20234 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20235 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20236 ("TAGS and Properties"
20237 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20238 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20239 "--"
20240 ["Set property" org-set-property (not (org-before-first-heading-p))]
20241 ["Column view of properties" org-columns t]
20242 ["Insert Column View DBlock" org-insert-columns-dblock t])
20243 ("Dates and Scheduling"
20244 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20245 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20246 ("Change Date"
20247 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20248 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20249 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20250 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20251 ["Compute Time Range" org-evaluate-time-range t]
20252 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20253 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20254 "--"
20255 ["Custom time format" org-toggle-time-stamp-overlays
20256 :style radio :selected org-display-custom-times]
20257 "--"
20258 ["Goto Calendar" org-goto-calendar t]
20259 ["Date from Calendar" org-date-from-calendar t]
20260 "--"
20261 ["Start/Restart Timer" org-timer-start t]
20262 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20263 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20264 ["Insert Timer String" org-timer t]
20265 ["Insert Timer Item" org-timer-item t])
20266 ("Logging work"
20267 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20268 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20269 ["Clock out" org-clock-out t]
20270 ["Clock cancel" org-clock-cancel t]
20271 "--"
20272 ["Mark as default task" org-clock-mark-default-task t]
20273 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20274 ["Goto running clock" org-clock-goto t]
20275 "--"
20276 ["Display times" org-clock-display t]
20277 ["Create clock table" org-clock-report t]
20278 "--"
20279 ["Record DONE time"
20280 (progn (setq org-log-done (not org-log-done))
20281 (message "Switching to %s will %s record a timestamp"
20282 (car org-done-keywords)
20283 (if org-log-done "automatically" "not")))
20284 :style toggle :selected org-log-done])
20285 "--"
20286 ["Agenda Command..." org-agenda t]
20287 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20288 ("File List for Agenda")
20289 ("Special views current file"
20290 ["TODO Tree" org-show-todo-tree t]
20291 ["Check Deadlines" org-check-deadlines t]
20292 ["Timeline" org-timeline t]
20293 ["Tags/Property tree" org-match-sparse-tree t])
20294 "--"
20295 ["Export/Publish..." org-export t]
20296 ("LaTeX"
20297 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20298 :selected org-cdlatex-mode]
20299 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20300 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20301 ["Modify math symbol" org-cdlatex-math-modify
20302 (org-inside-LaTeX-fragment-p)]
20303 ["Insert citation" org-reftex-citation t]
20304 "--"
20305 ["Template for BEAMER" (progn (require 'org-beamer)
20306 (org-insert-beamer-options-template)) t])
20307 "--"
20308 ("MobileOrg"
20309 ["Push Files and Views" org-mobile-push t]
20310 ["Get Captured and Flagged" org-mobile-pull t]
20311 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20312 "--"
20313 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20314 "--"
20315 ("Documentation"
20316 ["Show Version" org-version t]
20317 ["Info Documentation" org-info t])
20318 ("Customize"
20319 ["Browse Org Group" org-customize t]
20320 "--"
20321 ["Expand This Menu" org-create-customize-menu
20322 (fboundp 'customize-menu-create)])
20323 ["Send bug report" org-submit-bug-report t]
20324 "--"
20325 ("Refresh/Reload"
20326 ["Refresh setup current buffer" org-mode-restart t]
20327 ["Reload Org (after update)" org-reload t]
20328 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20331 (defun org-info (&optional node)
20332 "Read documentation for Org-mode in the info system.
20333 With optional NODE, go directly to that node."
20334 (interactive)
20335 (info (format "(org)%s" (or node ""))))
20337 ;;;###autoload
20338 (defun org-submit-bug-report ()
20339 "Submit a bug report on Org-mode via mail.
20341 Don't hesitate to report any problems or inaccurate documentation.
20343 If you don't have setup sending mail from (X)Emacs, please copy the
20344 output buffer into your mail program, as it gives us important
20345 information about your Org-mode version and configuration."
20346 (interactive)
20347 (require 'reporter)
20348 (org-load-modules-maybe)
20349 (org-require-autoloaded-modules)
20350 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20351 (reporter-submit-bug-report
20352 "emacs-orgmode@gnu.org"
20353 (org-version nil 'full)
20354 (let (list)
20355 (save-window-excursion
20356 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20357 (delete-other-windows)
20358 (erase-buffer)
20359 (insert "You are about to submit a bug report to the Org-mode mailing list.
20361 We would like to add your full Org-mode and Outline configuration to the
20362 bug report. This greatly simplifies the work of the maintainer and
20363 other experts on the mailing list.
20365 HOWEVER, some variables you have customized may contain private
20366 information. The names of customers, colleagues, or friends, might
20367 appear in the form of file names, tags, todo states, or search strings.
20368 If you answer yes to the prompt, you might want to check and remove
20369 such private information before sending the email.")
20370 (add-text-properties (point-min) (point-max) '(face org-warning))
20371 (when (yes-or-no-p "Include your Org-mode configuration ")
20372 (mapatoms
20373 (lambda (v)
20374 (and (boundp v)
20375 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20376 (or (and (symbol-value v)
20377 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20378 (and
20379 (get v 'custom-type) (get v 'standard-value)
20380 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20381 (push v list)))))
20382 (kill-buffer (get-buffer "*Warn about privacy*"))
20383 list))
20384 nil nil
20385 "Remember to cover the basics, that is, what you expected to happen and
20386 what in fact did happen. You don't know how to make a good report? See
20388 http://orgmode.org/manual/Feedback.html#Feedback
20390 Your bug report will be posted to the Org-mode mailing list.
20391 ------------------------------------------------------------------------")
20392 (save-excursion
20393 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20394 (replace-match "\\1Bug: \\3 [\\2]")))))
20397 (defun org-install-agenda-files-menu ()
20398 (let ((bl (buffer-list)))
20399 (save-excursion
20400 (while bl
20401 (set-buffer (pop bl))
20402 (if (derived-mode-p 'org-mode) (setq bl nil)))
20403 (when (derived-mode-p 'org-mode)
20404 (easy-menu-change
20405 '("Org") "File List for Agenda"
20406 (append
20407 (list
20408 ["Edit File List" (org-edit-agenda-file-list) t]
20409 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20410 ["Remove Current File from List" org-remove-file t]
20411 ["Cycle through agenda files" org-cycle-agenda-files t]
20412 ["Occur in all agenda files" org-occur-in-agenda-files t]
20413 "--")
20414 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20416 ;;;; Documentation
20418 (defun org-require-autoloaded-modules ()
20419 (interactive)
20420 (mapc 'require
20421 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20422 org-docbook org-exp org-html org-icalendar
20423 org-id org-latex
20424 org-publish org-remember org-table
20425 org-timer org-xoxo)))
20427 ;;;###autoload
20428 (defun org-reload (&optional uncompiled)
20429 "Reload all org lisp files.
20430 With prefix arg UNCOMPILED, load the uncompiled versions."
20431 (interactive "P")
20432 (require 'loadhist)
20433 (let* ((org-dir (org-find-library-dir "org"))
20434 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20435 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20436 (remove-re (mapconcat 'identity
20437 (mapcar (lambda (f) (concat "^" f "$"))
20438 (list (if (featurep 'xemacs)
20439 "org-colview"
20440 "org-colview-xemacs")
20441 "org" "org-loaddefs" "org-version"))
20442 "\\|"))
20443 (feats (delete-dups
20444 (mapcar 'file-name-sans-extension
20445 (mapcar 'file-name-nondirectory
20446 (delq nil
20447 (mapcar 'feature-file
20448 features))))))
20449 (lfeat (append
20450 (sort
20451 (setq feats
20452 (delq nil (mapcar
20453 (lambda (f)
20454 (if (and (string-match feature-re f)
20455 (not (string-match remove-re f)))
20456 f nil))
20457 feats)))
20458 'string-lessp)
20459 (list "org-version" "org")))
20460 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20461 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20462 load-uncore load-misses)
20463 (setq load-misses
20464 (delq 't
20465 (mapcar (lambda (f)
20466 (or (org-load-noerror-mustsuffix (concat org-dir f))
20467 (and (string= org-dir contrib-dir)
20468 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20469 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20470 (add-to-list 'load-uncore f 'append)
20473 lfeat)))
20474 (if load-uncore
20475 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20476 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20477 (if load-misses
20478 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20479 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20480 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20482 ;;;###autoload
20483 (defun org-customize ()
20484 "Call the customize function with org as argument."
20485 (interactive)
20486 (org-load-modules-maybe)
20487 (org-require-autoloaded-modules)
20488 (customize-browse 'org))
20490 (defun org-create-customize-menu ()
20491 "Create a full customization menu for Org-mode, insert it into the menu."
20492 (interactive)
20493 (org-load-modules-maybe)
20494 (org-require-autoloaded-modules)
20495 (if (fboundp 'customize-menu-create)
20496 (progn
20497 (easy-menu-change
20498 '("Org") "Customize"
20499 `(["Browse Org group" org-customize t]
20500 "--"
20501 ,(customize-menu-create 'org)
20502 ["Set" Custom-set t]
20503 ["Save" Custom-save t]
20504 ["Reset to Current" Custom-reset-current t]
20505 ["Reset to Saved" Custom-reset-saved t]
20506 ["Reset to Standard Settings" Custom-reset-standard t]))
20507 (message "\"Org\"-menu now contains full customization menu"))
20508 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20510 ;;;; Miscellaneous stuff
20512 ;;; Generally useful functions
20514 (defun org-get-at-bol (property)
20515 "Get text property PROPERTY at beginning of line."
20516 (get-text-property (point-at-bol) property))
20518 (defun org-find-text-property-in-string (prop s)
20519 "Return the first non-nil value of property PROP in string S."
20520 (or (get-text-property 0 prop s)
20521 (get-text-property (or (next-single-property-change 0 prop s) 0)
20522 prop s)))
20524 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20525 "Display the given MESSAGE as a warning."
20526 (if (fboundp 'display-warning)
20527 (display-warning 'org message
20528 (if (featurep 'xemacs) 'warning :warning))
20529 (let ((buf (get-buffer-create "*Org warnings*")))
20530 (with-current-buffer buf
20531 (goto-char (point-max))
20532 (insert "Warning (Org): " message)
20533 (unless (bolp)
20534 (newline)))
20535 (display-buffer buf)
20536 (sit-for 0))))
20538 (defun org-eval (form)
20539 "Eval FORM and return result."
20540 (condition-case error
20541 (eval form)
20542 (error (format "%%![Error: %s]" error))))
20544 (defun org-in-clocktable-p ()
20545 "Check if the cursor is in a clocktable."
20546 (let ((pos (point)) start)
20547 (save-excursion
20548 (end-of-line 1)
20549 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20550 (setq start (match-beginning 0))
20551 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20552 (>= (match-end 0) pos)
20553 start))))
20555 (defun org-in-commented-line ()
20556 "Is point in a line starting with `#'?"
20557 (equal (char-after (point-at-bol)) ?#))
20559 (defun org-in-indented-comment-line ()
20560 "Is point in a line starting with `#' after some white space?"
20561 (save-excursion
20562 (save-match-data
20563 (goto-char (point-at-bol))
20564 (looking-at "[ \t]*#"))))
20566 (defun org-in-verbatim-emphasis ()
20567 (save-match-data
20568 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20570 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20571 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20572 (if (and marker (marker-buffer marker)
20573 (buffer-live-p (marker-buffer marker)))
20574 (progn
20575 (org-pop-to-buffer-same-window (marker-buffer marker))
20576 (if (or (> marker (point-max)) (< marker (point-min)))
20577 (widen))
20578 (goto-char marker)
20579 (org-show-context 'org-goto))
20580 (if bookmark
20581 (bookmark-jump bookmark)
20582 (error "Cannot find location"))))
20584 (defun org-quote-csv-field (s)
20585 "Quote field for inclusion in CSV material."
20586 (if (string-match "[\",]" s)
20587 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20590 (defun org-force-self-insert (N)
20591 "Needed to enforce self-insert under remapping."
20592 (interactive "p")
20593 (self-insert-command N))
20595 (defun org-string-width (s)
20596 "Compute width of string, ignoring invisible characters.
20597 This ignores character with invisibility property `org-link', and also
20598 characters with property `org-cwidth', because these will become invisible
20599 upon the next fontification round."
20600 (let (b l)
20601 (when (or (eq t buffer-invisibility-spec)
20602 (assq 'org-link buffer-invisibility-spec))
20603 (while (setq b (text-property-any 0 (length s)
20604 'invisible 'org-link s))
20605 (setq s (concat (substring s 0 b)
20606 (substring s (or (next-single-property-change
20607 b 'invisible s) (length s)))))))
20608 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20609 (setq s (concat (substring s 0 b)
20610 (substring s (or (next-single-property-change
20611 b 'org-cwidth s) (length s))))))
20612 (setq l (string-width s) b -1)
20613 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20614 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20617 (defun org-shorten-string (s maxlength)
20618 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20619 If the string is shorter or has length MAXLENGTH, just return the
20620 original string. If it is longer, the functions finds a space in the
20621 string, breaks this string off at that locations and adds three dots
20622 as ellipsis. Including the ellipsis, the string will not be longer
20623 than MAXLENGTH. If finding a good breaking point in the string does
20624 not work, the string is just chopped off in the middle of a word
20625 if necessary."
20626 (if (<= (length s) maxlength)
20628 (let* ((n (max (- maxlength 4) 1))
20629 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20630 (if (string-match re s)
20631 (concat (match-string 1 s) "...")
20632 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20634 (defun org-get-indentation (&optional line)
20635 "Get the indentation of the current line, interpreting tabs.
20636 When LINE is given, assume it represents a line and compute its indentation."
20637 (if line
20638 (if (string-match "^ *" (org-remove-tabs line))
20639 (match-end 0))
20640 (save-excursion
20641 (beginning-of-line 1)
20642 (skip-chars-forward " \t")
20643 (current-column))))
20645 (defun org-get-string-indentation (s)
20646 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20647 (let ((n -1) (i 0) (w tab-width) c)
20648 (catch 'exit
20649 (while (< (setq n (1+ n)) (length s))
20650 (setq c (aref s n))
20651 (cond ((= c ?\ ) (setq i (1+ i)))
20652 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20653 (t (throw 'exit t)))))
20656 (defun org-remove-tabs (s &optional width)
20657 "Replace tabulators in S with spaces.
20658 Assumes that s is a single line, starting in column 0."
20659 (setq width (or width tab-width))
20660 (while (string-match "\t" s)
20661 (setq s (replace-match
20662 (make-string
20663 (- (* width (/ (+ (match-beginning 0) width) width))
20664 (match-beginning 0)) ?\ )
20665 t t s)))
20668 (defun org-fix-indentation (line ind)
20669 "Fix indentation in LINE.
20670 IND is a cons cell with target and minimum indentation.
20671 If the current indentation in LINE is smaller than the minimum,
20672 leave it alone. If it is larger than ind, set it to the target."
20673 (let* ((l (org-remove-tabs line))
20674 (i (org-get-indentation l))
20675 (i1 (car ind)) (i2 (cdr ind)))
20676 (if (>= i i2) (setq l (substring line i2)))
20677 (if (> i1 0)
20678 (concat (make-string i1 ?\ ) l)
20679 l)))
20681 (defun org-remove-indentation (code &optional n)
20682 "Remove the maximum common indentation from the lines in CODE.
20683 N may optionally be the number of spaces to remove."
20684 (with-temp-buffer
20685 (insert code)
20686 (org-do-remove-indentation n)
20687 (buffer-string)))
20689 (defun org-do-remove-indentation (&optional n)
20690 "Remove the maximum common indentation from the buffer."
20691 (untabify (point-min) (point-max))
20692 (let ((min 10000) re)
20693 (if n
20694 (setq min n)
20695 (goto-char (point-min))
20696 (while (re-search-forward "^ *[^ \n]" nil t)
20697 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20698 (unless (or (= min 0) (= min 10000))
20699 (setq re (format "^ \\{%d\\}" min))
20700 (goto-char (point-min))
20701 (while (re-search-forward re nil t)
20702 (replace-match "")
20703 (end-of-line 1))
20704 min)))
20706 (defun org-fill-template (template alist)
20707 "Find each %key of ALIST in TEMPLATE and replace it."
20708 (let ((case-fold-search nil)
20709 entry key value)
20710 (setq alist (sort (copy-sequence alist)
20711 (lambda (a b) (< (length (car a)) (length (car b))))))
20712 (while (setq entry (pop alist))
20713 (setq template
20714 (replace-regexp-in-string
20715 (concat "%" (regexp-quote (car entry)))
20716 (or (cdr entry) "") template t t)))
20717 template))
20719 (defun org-base-buffer (buffer)
20720 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20721 (if (not buffer)
20722 buffer
20723 (or (buffer-base-buffer buffer)
20724 buffer)))
20726 (defun org-trim (s)
20727 "Remove whitespace at beginning and end of string."
20728 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20729 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20732 (defun org-wrap (string &optional width lines)
20733 "Wrap string to either a number of lines, or a width in characters.
20734 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20735 that costs. If there is a word longer than WIDTH, the text is actually
20736 wrapped to the length of that word.
20737 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20738 many lines, whatever width that takes.
20739 The return value is a list of lines, without newlines at the end."
20740 (let* ((words (org-split-string string "[ \t\n]+"))
20741 (maxword (apply 'max (mapcar 'org-string-width words)))
20742 w ll)
20743 (cond (width
20744 (org-do-wrap words (max maxword width)))
20745 (lines
20746 (setq w maxword)
20747 (setq ll (org-do-wrap words maxword))
20748 (if (<= (length ll) lines)
20750 (setq ll words)
20751 (while (> (length ll) lines)
20752 (setq w (1+ w))
20753 (setq ll (org-do-wrap words w)))
20754 ll))
20755 (t (error "Cannot wrap this")))))
20757 (defun org-do-wrap (words width)
20758 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20759 (let (lines line)
20760 (while words
20761 (setq line (pop words))
20762 (while (and words (< (+ (length line) (length (car words))) width))
20763 (setq line (concat line " " (pop words))))
20764 (setq lines (push line lines)))
20765 (nreverse lines)))
20767 (defun org-split-string (string &optional separators)
20768 "Splits STRING into substrings at SEPARATORS.
20769 No empty strings are returned if there are matches at the beginning
20770 and end of string."
20771 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20772 (start 0)
20773 notfirst
20774 (list nil))
20775 (while (and (string-match rexp string
20776 (if (and notfirst
20777 (= start (match-beginning 0))
20778 (< start (length string)))
20779 (1+ start) start))
20780 (< (match-beginning 0) (length string)))
20781 (setq notfirst t)
20782 (or (eq (match-beginning 0) 0)
20783 (and (eq (match-beginning 0) (match-end 0))
20784 (eq (match-beginning 0) start))
20785 (setq list
20786 (cons (substring string start (match-beginning 0))
20787 list)))
20788 (setq start (match-end 0)))
20789 (or (eq start (length string))
20790 (setq list
20791 (cons (substring string start)
20792 list)))
20793 (nreverse list)))
20795 (defun org-quote-vert (s)
20796 "Replace \"|\" with \"\\vert\"."
20797 (while (string-match "|" s)
20798 (setq s (replace-match "\\vert" t t s)))
20801 (defun org-uuidgen-p (s)
20802 "Is S an ID created by UUIDGEN?"
20803 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20805 (defun org-in-src-block-p (&optional inside)
20806 "Whether point is in a code source block.
20807 When INSIDE is non-nil, don't consider we are within a src block
20808 when point is at #+BEGIN_SRC or #+END_SRC."
20809 (let ((case-fold-search t) ov)
20810 (or (and (setq ov (overlays-at (point)))
20811 (memq 'org-block-background
20812 (overlay-properties (car ov))))
20813 (and (not inside)
20814 (save-match-data
20815 (save-excursion
20816 (beginning-of-line)
20817 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20819 (defun org-context ()
20820 "Return a list of contexts of the current cursor position.
20821 If several contexts apply, all are returned.
20822 Each context entry is a list with a symbol naming the context, and
20823 two positions indicating start and end of the context. Possible
20824 contexts are:
20826 :headline anywhere in a headline
20827 :headline-stars on the leading stars in a headline
20828 :todo-keyword on a TODO keyword (including DONE) in a headline
20829 :tags on the TAGS in a headline
20830 :priority on the priority cookie in a headline
20831 :item on the first line of a plain list item
20832 :item-bullet on the bullet/number of a plain list item
20833 :checkbox on the checkbox in a plain list item
20834 :table in an org-mode table
20835 :table-special on a special filed in a table
20836 :table-table in a table.el table
20837 :clocktable in a clocktable
20838 :src-block in a source block
20839 :link on a hyperlink
20840 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20841 :target on a <<target>>
20842 :radio-target on a <<<radio-target>>>
20843 :latex-fragment on a LaTeX fragment
20844 :latex-preview on a LaTeX fragment with overlaid preview image
20846 This function expects the position to be visible because it uses font-lock
20847 faces as a help to recognize the following contexts: :table-special, :link,
20848 and :keyword."
20849 (let* ((f (get-text-property (point) 'face))
20850 (faces (if (listp f) f (list f)))
20851 (case-fold-search t)
20852 (p (point)) clist o)
20853 ;; First the large context
20854 (cond
20855 ((org-at-heading-p t)
20856 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20857 (when (progn
20858 (beginning-of-line 1)
20859 (looking-at org-todo-line-tags-regexp))
20860 (push (org-point-in-group p 1 :headline-stars) clist)
20861 (push (org-point-in-group p 2 :todo-keyword) clist)
20862 (push (org-point-in-group p 4 :tags) clist))
20863 (goto-char p)
20864 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20865 (if (looking-at "\\[#[A-Z0-9]\\]")
20866 (push (org-point-in-group p 0 :priority) clist)))
20868 ((org-at-item-p)
20869 (push (org-point-in-group p 2 :item-bullet) clist)
20870 (push (list :item (point-at-bol)
20871 (save-excursion (org-end-of-item) (point)))
20872 clist)
20873 (and (org-at-item-checkbox-p)
20874 (push (org-point-in-group p 0 :checkbox) clist)))
20876 ((org-at-table-p)
20877 (push (list :table (org-table-begin) (org-table-end)) clist)
20878 (if (memq 'org-formula faces)
20879 (push (list :table-special
20880 (previous-single-property-change p 'face)
20881 (next-single-property-change p 'face)) clist)))
20882 ((org-at-table-p 'any)
20883 (push (list :table-table) clist)))
20884 (goto-char p)
20886 (let ((case-fold-search t))
20887 ;; New the "medium" contexts: clocktables, source blocks
20888 (cond ((org-in-clocktable-p)
20889 (push (list :clocktable
20890 (and (or (looking-at "#\\+BEGIN: clocktable")
20891 (search-backward "#+BEGIN: clocktable" nil t))
20892 (match-beginning 0))
20893 (and (re-search-forward "#\\+END:?" nil t)
20894 (match-end 0))) clist))
20895 ((org-in-src-block-p)
20896 (push (list :src-block
20897 (and (or (looking-at "#\\+BEGIN_SRC")
20898 (search-backward "#+BEGIN_SRC" nil t))
20899 (match-beginning 0))
20900 (and (search-forward "#+END_SRC" nil t)
20901 (match-beginning 0))) clist))))
20902 (goto-char p)
20904 ;; Now the small context
20905 (cond
20906 ((org-at-timestamp-p)
20907 (push (org-point-in-group p 0 :timestamp) clist))
20908 ((memq 'org-link faces)
20909 (push (list :link
20910 (previous-single-property-change p 'face)
20911 (next-single-property-change p 'face)) clist))
20912 ((memq 'org-special-keyword faces)
20913 (push (list :keyword
20914 (previous-single-property-change p 'face)
20915 (next-single-property-change p 'face)) clist))
20916 ((org-at-target-p)
20917 (push (org-point-in-group p 0 :target) clist)
20918 (goto-char (1- (match-beginning 0)))
20919 (if (looking-at org-radio-target-regexp)
20920 (push (org-point-in-group p 0 :radio-target) clist))
20921 (goto-char p))
20922 ((setq o (car (delq nil
20923 (mapcar
20924 (lambda (x)
20925 (if (memq x org-latex-fragment-image-overlays) x))
20926 (overlays-at (point))))))
20927 (push (list :latex-fragment
20928 (overlay-start o) (overlay-end o)) clist)
20929 (push (list :latex-preview
20930 (overlay-start o) (overlay-end o)) clist))
20931 ((org-inside-LaTeX-fragment-p)
20932 ;; FIXME: positions wrong.
20933 (push (list :latex-fragment (point) (point)) clist)))
20935 (setq clist (nreverse (delq nil clist)))
20936 clist))
20938 ;; FIXME: Compare with at-regexp-p Do we need both?
20939 (defun org-in-regexp (re &optional nlines visually)
20940 "Check if point is inside a match of regexp.
20941 Normally only the current line is checked, but you can include NLINES extra
20942 lines both before and after point into the search.
20943 If VISUALLY is set, require that the cursor is not after the match but
20944 really on, so that the block visually is on the match."
20945 (catch 'exit
20946 (let ((pos (point))
20947 (eol (point-at-eol (+ 1 (or nlines 0))))
20948 (inc (if visually 1 0)))
20949 (save-excursion
20950 (beginning-of-line (- 1 (or nlines 0)))
20951 (while (re-search-forward re eol t)
20952 (if (and (<= (match-beginning 0) pos)
20953 (>= (+ inc (match-end 0)) pos))
20954 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20956 (defun org-at-regexp-p (regexp)
20957 "Is point inside a match of REGEXP in the current line?"
20958 (catch 'exit
20959 (save-excursion
20960 (let ((pos (point)) (end (point-at-eol)))
20961 (beginning-of-line 1)
20962 (while (re-search-forward regexp end t)
20963 (if (and (<= (match-beginning 0) pos)
20964 (>= (match-end 0) pos))
20965 (throw 'exit t)))
20966 nil))))
20968 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20969 "Non-nil when point is between matches of START-RE and END-RE.
20971 Also return a non-nil value when point is on one of the matches.
20973 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20974 buffer positions. Default values are the positions of headlines
20975 surrounding the point.
20977 The functions returns a cons cell whose car (resp. cdr) is the
20978 position before START-RE (resp. after END-RE)."
20979 (save-match-data
20980 (let ((pos (point))
20981 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20982 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20983 beg end)
20984 (save-excursion
20985 ;; Point is on a block when on START-RE or if START-RE can be
20986 ;; found before it...
20987 (and (or (org-at-regexp-p start-re)
20988 (re-search-backward start-re limit-up t))
20989 (setq beg (match-beginning 0))
20990 ;; ... and END-RE after it...
20991 (goto-char (match-end 0))
20992 (re-search-forward end-re limit-down t)
20993 (> (setq end (match-end 0)) pos)
20994 ;; ... without another START-RE in-between.
20995 (goto-char (match-beginning 0))
20996 (not (re-search-backward start-re (1+ beg) t))
20997 ;; Return value.
20998 (cons beg end))))))
21000 (defun org-in-block-p (names)
21001 "Non-nil when point belongs to a block whose name belongs to NAMES.
21003 NAMES is a list of strings containing names of blocks.
21005 Return first block name matched, or nil. Beware that in case of
21006 nested blocks, the returned name may not belong to the closest
21007 block from point."
21008 (save-match-data
21009 (catch 'exit
21010 (let ((case-fold-search t)
21011 (lim-up (save-excursion (outline-previous-heading)))
21012 (lim-down (save-excursion (outline-next-heading))))
21013 (mapc (lambda (name)
21014 (let ((n (regexp-quote name)))
21015 (when (org-between-regexps-p
21016 (concat "^[ \t]*#\\+begin_" n)
21017 (concat "^[ \t]*#\\+end_" n)
21018 lim-up lim-down)
21019 (throw 'exit n))))
21020 names))
21021 nil)))
21023 (defun org-occur-in-agenda-files (regexp &optional nlines)
21024 "Call `multi-occur' with buffers for all agenda files."
21025 (interactive "sOrg-files matching: \np")
21026 (let* ((files (org-agenda-files))
21027 (tnames (mapcar 'file-truename files))
21028 (extra org-agenda-text-search-extra-files)
21030 (when (eq (car extra) 'agenda-archives)
21031 (setq extra (cdr extra))
21032 (setq files (org-add-archive-files files)))
21033 (while (setq f (pop extra))
21034 (unless (member (file-truename f) tnames)
21035 (add-to-list 'files f 'append)
21036 (add-to-list 'tnames (file-truename f) 'append)))
21037 (multi-occur
21038 (mapcar (lambda (x)
21039 (with-current-buffer
21040 (or (get-file-buffer x) (find-file-noselect x))
21041 (widen)
21042 (current-buffer)))
21043 files)
21044 regexp)))
21046 (if (boundp 'occur-mode-find-occurrence-hook)
21047 ;; Emacs 23
21048 (add-hook 'occur-mode-find-occurrence-hook
21049 (lambda ()
21050 (when (derived-mode-p 'org-mode)
21051 (org-reveal))))
21052 ;; Emacs 22
21053 (defadvice occur-mode-goto-occurrence
21054 (after org-occur-reveal activate)
21055 (and (derived-mode-p 'org-mode) (org-reveal)))
21056 (defadvice occur-mode-goto-occurrence-other-window
21057 (after org-occur-reveal activate)
21058 (and (derived-mode-p 'org-mode) (org-reveal)))
21059 (defadvice occur-mode-display-occurrence
21060 (after org-occur-reveal activate)
21061 (when (derived-mode-p 'org-mode)
21062 (let ((pos (occur-mode-find-occurrence)))
21063 (with-current-buffer (marker-buffer pos)
21064 (save-excursion
21065 (goto-char pos)
21066 (org-reveal)))))))
21068 (defun org-occur-link-in-agenda-files ()
21069 "Create a link and search for it in the agendas.
21070 The link is not stored in `org-stored-links', it is just created
21071 for the search purpose."
21072 (interactive)
21073 (let ((link (condition-case nil
21074 (org-store-link nil)
21075 (error "Unable to create a link to here"))))
21076 (org-occur-in-agenda-files (regexp-quote link))))
21078 (defun org-uniquify (list)
21079 "Remove duplicate elements from LIST."
21080 (let (res)
21081 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21082 res))
21084 (defun org-delete-all (elts list)
21085 "Remove all elements in ELTS from LIST."
21086 (while elts
21087 (setq list (delete (pop elts) list)))
21088 list)
21090 (defun org-count (cl-item cl-seq)
21091 "Count the number of occurrences of ITEM in SEQ.
21092 Taken from `count' in cl-seq.el with all keyword arguments removed."
21093 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21094 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21095 (while (< cl-start cl-end)
21096 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21097 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21098 (setq cl-start (1+ cl-start)))
21099 cl-count))
21101 (defun org-remove-if (predicate seq)
21102 "Remove everything from SEQ that fulfills PREDICATE."
21103 (let (res e)
21104 (while seq
21105 (setq e (pop seq))
21106 (if (not (funcall predicate e)) (push e res)))
21107 (nreverse res)))
21109 (defun org-remove-if-not (predicate seq)
21110 "Remove everything from SEQ that does not fulfill PREDICATE."
21111 (let (res e)
21112 (while seq
21113 (setq e (pop seq))
21114 (if (funcall predicate e) (push e res)))
21115 (nreverse res)))
21117 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21118 "Reduce two-argument FUNCTION across SEQ.
21119 Taken from `reduce' in cl-seq.el with all keyword arguments but
21120 \":initial-value\" removed."
21121 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21122 (cadr (memq :initial-value cl-keys)))
21123 (cl-seq (pop cl-seq))
21124 (t (funcall cl-func)))))
21125 (while cl-seq
21126 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21127 cl-accum))
21129 (defun org-back-over-empty-lines ()
21130 "Move backwards over whitespace, to the beginning of the first empty line.
21131 Returns the number of empty lines passed."
21132 (let ((pos (point)))
21133 (if (cdr (assoc 'heading org-blank-before-new-entry))
21134 (skip-chars-backward " \t\n\r")
21135 (unless (eobp)
21136 (forward-line -1)))
21137 (beginning-of-line 2)
21138 (goto-char (min (point) pos))
21139 (count-lines (point) pos)))
21141 (defun org-skip-whitespace ()
21142 (skip-chars-forward " \t\n\r"))
21144 (defun org-point-in-group (point group &optional context)
21145 "Check if POINT is in match-group GROUP.
21146 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21147 match. If the match group does not exist or point is not inside it,
21148 return nil."
21149 (and (match-beginning group)
21150 (>= point (match-beginning group))
21151 (<= point (match-end group))
21152 (if context
21153 (list context (match-beginning group) (match-end group))
21154 t)))
21156 (defun org-switch-to-buffer-other-window (&rest args)
21157 "Switch to buffer in a second window on the current frame.
21158 In particular, do not allow pop-up frames.
21159 Returns the newly created buffer."
21160 (org-no-popups
21161 (apply 'switch-to-buffer-other-window args)))
21163 (defun org-combine-plists (&rest plists)
21164 "Create a single property list from all plists in PLISTS.
21165 The process starts by copying the first list, and then setting properties
21166 from the other lists. Settings in the last list are the most significant
21167 ones and overrule settings in the other lists."
21168 (let ((rtn (copy-sequence (pop plists)))
21169 p v ls)
21170 (while plists
21171 (setq ls (pop plists))
21172 (while ls
21173 (setq p (pop ls) v (pop ls))
21174 (setq rtn (plist-put rtn p v))))
21175 rtn))
21177 (defun org-replace-escapes (string table)
21178 "Replace %-escapes in STRING with values in TABLE.
21179 TABLE is an association list with keys like \"%a\" and string values.
21180 The sequences in STRING may contain normal field width and padding information,
21181 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21182 so values can contain further %-escapes if they are define later in TABLE."
21183 (let ((tbl (copy-alist table))
21184 (case-fold-search nil)
21185 (pchg 0)
21186 e re rpl)
21187 (while (setq e (pop tbl))
21188 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21189 (when (and (cdr e) (string-match re (cdr e)))
21190 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21191 (safe "SREF"))
21192 (add-text-properties 0 3 (list 'sref sref) safe)
21193 (setcdr e (replace-match safe t t (cdr e)))))
21194 (while (string-match re string)
21195 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21196 (cdr e)))
21197 (setq string (replace-match rpl t t string))))
21198 (while (setq pchg (next-property-change pchg string))
21199 (let ((sref (get-text-property pchg 'sref string)))
21200 (when (and sref (string-match "SREF" string pchg))
21201 (setq string (replace-match sref t t string)))))
21202 string))
21204 (defun org-sublist (list start end)
21205 "Return a section of LIST, from START to END.
21206 Counting starts at 1."
21207 (let (rtn (c start))
21208 (setq list (nthcdr (1- start) list))
21209 (while (and list (<= c end))
21210 (push (pop list) rtn)
21211 (setq c (1+ c)))
21212 (nreverse rtn)))
21214 (defun org-find-base-buffer-visiting (file)
21215 "Like `find-buffer-visiting' but always return the base buffer and
21216 not an indirect buffer."
21217 (let ((buf (or (get-file-buffer file)
21218 (find-buffer-visiting file))))
21219 (if buf
21220 (or (buffer-base-buffer buf) buf)
21221 nil)))
21223 (defun org-image-file-name-regexp (&optional extensions)
21224 "Return regexp matching the file names of images.
21225 If EXTENSIONS is given, only match these."
21226 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21227 (image-file-name-regexp)
21228 (let ((image-file-name-extensions
21229 (or extensions
21230 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21231 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21232 (concat "\\."
21233 (regexp-opt (nconc (mapcar 'upcase
21234 image-file-name-extensions)
21235 image-file-name-extensions)
21237 "\\'"))))
21239 (defun org-file-image-p (file &optional extensions)
21240 "Return non-nil if FILE is an image."
21241 (save-match-data
21242 (string-match (org-image-file-name-regexp extensions) file)))
21244 (defun org-get-cursor-date (&optional with-time)
21245 "Return the date at cursor in as a time.
21246 This works in the calendar and in the agenda, anywhere else it just
21247 returns the current time.
21248 If WITH-TIME is non-nil, returns the time of the event at point (in
21249 the agenda) or the current time of the day."
21250 (let (date day defd tp tm hod mod)
21251 (when with-time
21252 (setq tp (get-text-property (point) 'time))
21253 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21254 (setq hod (string-to-number (match-string 1 tp))
21255 mod (string-to-number (match-string 2 tp))))
21256 (or tp (setq hod (nth 2 (decode-time (current-time)))
21257 mod (nth 1 (decode-time (current-time))))))
21258 (cond
21259 ((eq major-mode 'calendar-mode)
21260 (setq date (calendar-cursor-to-date)
21261 defd (encode-time 0 (or mod 0) (or hod 0)
21262 (nth 1 date) (nth 0 date) (nth 2 date))))
21263 ((eq major-mode 'org-agenda-mode)
21264 (setq day (get-text-property (point) 'day))
21265 (if day
21266 (setq date (calendar-gregorian-from-absolute day)
21267 defd (encode-time 0 (or mod 0) (or hod 0)
21268 (nth 1 date) (nth 0 date) (nth 2 date))))))
21269 (or defd (current-time))))
21271 (defun org-mark-subtree (&optional up)
21272 "Mark the current subtree.
21273 This puts point at the start of the current subtree, and mark at
21274 the end. If a numeric prefix UP is given, move up into the
21275 hierarchy of headlines by UP levels before marking the subtree."
21276 (interactive "P")
21277 (org-with-limited-levels
21278 (cond ((org-at-heading-p) (beginning-of-line))
21279 ((org-before-first-heading-p) (error "Not in a subtree"))
21280 (t (outline-previous-visible-heading 1))))
21281 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21282 (if (org-called-interactively-p 'any)
21283 (call-interactively 'org-mark-element)
21284 (org-mark-element)))
21287 ;;; Macros
21289 ;; Macros are expanded with `org-macro-replace-all', which relies
21290 ;; internally on `org-macro-expand'.
21292 ;; Default templates for expansion are stored in the buffer-local
21293 ;; variable `org-macro-templates'. This variable is updated by
21294 ;; `org-macro-initialize-templates'.
21296 ;; Along with macros defined through #+MACRO: keyword, default
21297 ;; templates include the following hard-coded macros:
21298 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21299 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21301 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21302 ;; {{{title}}} will also be provided.
21305 (defvar org-macro-templates nil
21306 "Alist containing all macro templates in current buffer.
21307 Associations are in the shape of (NAME . TEMPLATE) where NAME
21308 stands for macro's name and template for its replacement value,
21309 both as strings. This is an internal variable. Do not set it
21310 directly, use instead:
21312 #+MACRO: name template")
21313 (make-variable-buffer-local 'org-macro-templates)
21315 (defun org-macro-expand (macro templates)
21316 "Return expanded MACRO, as a string.
21317 MACRO is an object, obtained, for example, with
21318 `org-element-context'. TEMPLATES is an alist of templates used
21319 for expansion. See `org-macro-templates' for a buffer-local
21320 default value. Return nil if no template was found."
21321 (let ((template
21322 ;; Macro names are case-insensitive.
21323 (cdr (assoc-string (org-element-property :key macro) templates t))))
21324 (when template
21325 (let ((value (replace-regexp-in-string
21326 "\\$[0-9]+"
21327 (lambda (arg)
21328 (or (nth (1- (string-to-number (substring arg 1)))
21329 (org-element-property :args macro))
21330 ;; No argument provided: remove
21331 ;; place-holder.
21332 ""))
21333 template)))
21334 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21335 (when (string-match "\\`(eval\\>" value)
21336 (setq value (eval (read value))))
21337 ;; Return string.
21338 (format "%s" (or value ""))))))
21340 (defun org-macro-replace-all (templates)
21341 "Replace all macros in current buffer by their expansion.
21342 TEMPLATES is an alist of templates used for expansion. See
21343 `org-macro-templates' for a buffer-local default value."
21344 (save-excursion
21345 (goto-char (point-min))
21346 (let (record)
21347 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21348 (let ((object (org-element-context)))
21349 (when (eq (org-element-type object) 'macro)
21350 (let* ((value (org-macro-expand object templates))
21351 (begin (org-element-property :begin object))
21352 (signature (list begin
21353 object
21354 (org-element-property :args object))))
21355 ;; Avoid circular dependencies by checking if the same
21356 ;; macro with the same arguments is expanded at the same
21357 ;; position twice.
21358 (if (member signature record)
21359 (error "Circular macro expansion: %s"
21360 (org-element-property :key object))
21361 (when value
21362 (push signature record)
21363 (delete-region
21364 begin
21365 ;; Preserve white spaces after the macro.
21366 (progn (goto-char (org-element-property :end object))
21367 (skip-chars-backward " \t")
21368 (point)))
21369 ;; Leave point before replacement in case of recursive
21370 ;; expansions.
21371 (save-excursion (insert value)))))))))))
21373 (defun org-macro-initialize-templates ()
21374 "Collect macro templates defined in current buffer.
21375 Templates are stored in buffer-local variable
21376 `org-macro-templates'. In addition to buffer-defined macros, the
21377 function installs the following ones: \"property\",
21378 \"time\". and, if the buffer is associated to a file,
21379 \"input-file\" and \"modification-time\"."
21380 (let ((case-fold-search t)
21381 (set-template
21382 (lambda (cell)
21383 ;; Add CELL to `org-macro-templates' if there's no
21384 ;; association matching its name already. Otherwise,
21385 ;; replace old association with the new one in that
21386 ;; variable.
21387 (let ((old-template (assoc (car cell) org-macro-templates)))
21388 (if old-template (setcdr old-template (cdr cell))
21389 (push cell org-macro-templates))))))
21390 ;; Install buffer-local macros.
21391 (org-with-wide-buffer
21392 (goto-char (point-min))
21393 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21394 (let ((element (org-element-at-point)))
21395 (when (eq (org-element-type element) 'keyword)
21396 (let ((value (org-element-property :value element)))
21397 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21398 (funcall set-template
21399 (cons (match-string 1 value)
21400 (or (match-string 2 value) "")))))))))
21401 ;; Install hard-coded macros.
21402 (mapc (lambda (cell) (funcall set-template cell))
21403 (list
21404 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21405 (cons "time" "(eval (format-time-string \"$1\"))")))
21406 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21407 (when (and visited-file (file-exists-p visited-file))
21408 (mapc (lambda (cell) (funcall set-template cell))
21409 (list
21410 (cons "input-file" (file-name-nondirectory visited-file))
21411 (cons "modification-time"
21412 (format "(eval (format-time-string \"$1\" '%s))"
21413 (prin1-to-string
21414 (nth 5 (file-attributes visited-file)))))))))))
21417 ;;; Indentation
21419 (defun org-indent-line ()
21420 "Indent line depending on context."
21421 (interactive)
21422 (let* ((pos (point))
21423 (itemp (org-at-item-p))
21424 (case-fold-search t)
21425 (org-drawer-regexp (or org-drawer-regexp "\000"))
21426 (inline-task-p (and (featurep 'org-inlinetask)
21427 (org-inlinetask-in-task-p)))
21428 (inline-re (and inline-task-p
21429 (org-inlinetask-outline-regexp)))
21430 column)
21431 (if (and orgstruct-is-++ (eq pos (point)))
21432 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21433 (indent-according-to-mode))
21434 (beginning-of-line 1)
21435 (cond
21436 ;; Headings
21437 ((looking-at org-outline-regexp) (setq column 0))
21438 ;; Included files
21439 ((looking-at "#\\+include:") (setq column 0))
21440 ;; Footnote definition
21441 ((looking-at org-footnote-definition-re) (setq column 0))
21442 ;; Literal examples
21443 ((looking-at "[ \t]*:\\( \\|$\\)")
21444 (setq column (org-get-indentation))) ; do nothing
21445 ;; Lists
21446 ((ignore-errors (goto-char (org-in-item-p)))
21447 (setq column (if itemp
21448 (org-get-indentation)
21449 (org-list-item-body-column (point))))
21450 (goto-char pos))
21451 ;; Drawers
21452 ((and (looking-at "[ \t]*:END:")
21453 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21454 (save-excursion
21455 (goto-char (1- (match-beginning 1)))
21456 (setq column (current-column))))
21457 ;; Special blocks
21458 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21459 (save-excursion
21460 (re-search-backward
21461 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21462 (setq column (org-get-indentation (match-string 0))))
21463 ((and (not (looking-at "[ \t]*#\\+begin_"))
21464 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21465 (save-excursion
21466 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21467 (setq column
21468 (cond ((equal (downcase (match-string 1)) "src")
21469 ;; src blocks: let `org-edit-src-exit' handle them
21470 (org-get-indentation))
21471 ((equal (downcase (match-string 1)) "example")
21472 (max (org-get-indentation)
21473 (org-get-indentation (match-string 0))))
21475 (org-get-indentation (match-string 0))))))
21476 ;; This line has nothing special, look at the previous relevant
21477 ;; line to compute indentation
21479 (beginning-of-line 0)
21480 (while (and (not (bobp))
21481 (not (looking-at org-table-line-regexp))
21482 (not (looking-at org-drawer-regexp))
21483 ;; When point started in an inline task, do not move
21484 ;; above task starting line.
21485 (not (and inline-task-p (looking-at inline-re)))
21486 ;; Skip drawers, blocks, empty lines, verbatim,
21487 ;; comments, tables, footnotes definitions, lists,
21488 ;; inline tasks.
21489 (or (and (looking-at "[ \t]*:END:")
21490 (re-search-backward org-drawer-regexp nil t))
21491 (and (looking-at "[ \t]*#\\+end_")
21492 (re-search-backward "[ \t]*#\\+begin_"nil t))
21493 (looking-at "[ \t]*[\n:#|]")
21494 (looking-at org-footnote-definition-re)
21495 (and (ignore-errors (goto-char (org-in-item-p)))
21496 (goto-char
21497 (org-list-get-top-point (org-list-struct))))
21498 (and (not inline-task-p)
21499 (featurep 'org-inlinetask)
21500 (org-inlinetask-in-task-p)
21501 (or (org-inlinetask-goto-beginning) t))))
21502 (beginning-of-line 0))
21503 (cond
21504 ;; There was an heading above.
21505 ((looking-at "\\*+[ \t]+")
21506 (if (not org-adapt-indentation)
21507 (setq column 0)
21508 (goto-char (match-end 0))
21509 (setq column (current-column))))
21510 ;; A drawer had started and is unfinished
21511 ((looking-at org-drawer-regexp)
21512 (goto-char (1- (match-beginning 1)))
21513 (setq column (current-column)))
21514 ;; Else, nothing noticeable found: get indentation and go on.
21515 (t (setq column (org-get-indentation))))))
21516 ;; Now apply indentation and move cursor accordingly
21517 (goto-char pos)
21518 (if (<= (current-column) (current-indentation))
21519 (org-indent-line-to column)
21520 (save-excursion (org-indent-line-to column)))
21521 ;; Special polishing for properties, see `org-property-format'
21522 (setq column (current-column))
21523 (beginning-of-line 1)
21524 (if (looking-at
21525 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21526 (replace-match (concat (match-string 1)
21527 (format org-property-format
21528 (match-string 2) (match-string 3)))
21529 t t))
21530 (org-move-to-column column))))
21532 (defun org-indent-drawer ()
21533 "Indent the drawer at point."
21534 (interactive)
21535 (let ((p (point))
21536 (e (and (save-excursion (re-search-forward ":END:" nil t))
21537 (match-end 0)))
21538 (folded
21539 (save-excursion
21540 (end-of-line)
21541 (when (overlays-at (point))
21542 (member 'invisible (overlay-properties
21543 (car (overlays-at (point)))))))))
21544 (when folded (org-cycle))
21545 (indent-for-tab-command)
21546 (while (and (move-beginning-of-line 2) (< (point) e))
21547 (indent-for-tab-command))
21548 (goto-char p)
21549 (when folded (org-cycle)))
21550 (message "Drawer at point indented"))
21552 (defun org-indent-block ()
21553 "Indent the block at point."
21554 (interactive)
21555 (let ((p (point))
21556 (case-fold-search t)
21557 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21558 (match-end 0)))
21559 (folded
21560 (save-excursion
21561 (end-of-line)
21562 (when (overlays-at (point))
21563 (member 'invisible (overlay-properties
21564 (car (overlays-at (point)))))))))
21565 (when folded (org-cycle))
21566 (indent-for-tab-command)
21567 (while (and (move-beginning-of-line 2) (< (point) e))
21568 (indent-for-tab-command))
21569 (goto-char p)
21570 (when folded (org-cycle)))
21571 (message "Block at point indented"))
21573 (defun org-indent-region (start end)
21574 "Indent region."
21575 (interactive "r")
21576 (save-excursion
21577 (let ((line-end (org-current-line end)))
21578 (goto-char start)
21579 (while (< (org-current-line) line-end)
21580 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21581 (t (call-interactively 'org-indent-line)))
21582 (move-beginning-of-line 2)))))
21585 ;;; Filling
21587 ;; We use our own fill-paragraph and auto-fill functions.
21589 ;; `org-fill-paragraph' relies on adaptive filling and context
21590 ;; checking. Appropriate `fill-prefix' is computed with
21591 ;; `org-adaptive-fill-function'.
21593 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21594 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21595 ;; `org-adaptive-fill-function' value. Internally,
21596 ;; `org-comment-line-break-function' breaks the line.
21598 ;; `org-setup-filling' installs filling and auto-filling related
21599 ;; variables during `org-mode' initialization.
21601 (defun org-setup-filling ()
21602 (interactive)
21603 ;; Prevent auto-fill from inserting unwanted new items.
21604 (when (boundp 'fill-nobreak-predicate)
21605 (org-set-local
21606 'fill-nobreak-predicate
21607 (org-uniquify
21608 (append fill-nobreak-predicate
21609 '(org-fill-paragraph-separate-nobreak-p
21610 org-fill-line-break-nobreak-p)))))
21611 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21612 (org-set-local 'auto-fill-inhibit-regexp nil)
21613 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21614 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21615 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21617 (defvar org-element-paragraph-separate) ; org-element.el
21618 (defun org-fill-paragraph-separate-nobreak-p ()
21619 "Non-nil when a line break at point would insert a new item."
21620 (looking-at (substring org-element-paragraph-separate 1)))
21622 (defun org-fill-line-break-nobreak-p ()
21623 "Non-nil when a line break at point would create an Org line break."
21624 (save-excursion
21625 (skip-chars-backward "[ \t]")
21626 (skip-chars-backward "\\\\")
21627 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21629 (declare-function message-in-body-p "message" ())
21630 (defvar orgtbl-line-start-regexp) ; From org-table.el
21631 (defun org-adaptive-fill-function ()
21632 "Compute a fill prefix for the current line.
21633 Return fill prefix, as a string, or nil if current line isn't
21634 meant to be filled."
21635 (let (prefix)
21636 (catch 'exit
21637 (when (derived-mode-p 'message-mode)
21638 (save-excursion
21639 (beginning-of-line)
21640 (cond ((or (not (message-in-body-p))
21641 (looking-at orgtbl-line-start-regexp))
21642 (throw 'exit nil))
21643 ((looking-at message-cite-prefix-regexp)
21644 (throw 'exit (match-string-no-properties 0)))
21645 ((looking-at org-outline-regexp)
21646 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21647 (org-with-wide-buffer
21648 (let* ((p (line-beginning-position))
21649 (element (save-excursion (beginning-of-line)
21650 (org-element-at-point)))
21651 (type (org-element-type element))
21652 (post-affiliated (org-element-property :post-affiliated element)))
21653 (unless (and post-affiliated (< p post-affiliated))
21654 (case type
21655 (comment (looking-at "[ \t]*# ?") (match-string 0))
21656 (footnote-definition "")
21657 ((item plain-list)
21658 (make-string (org-list-item-body-column
21659 (or post-affiliated
21660 (org-element-property :begin element)))
21661 ? ))
21662 (paragraph
21663 ;; Fill prefix is usually the same as the current line,
21664 ;; except if the paragraph is at the beginning of an item.
21665 (let ((parent (org-element-property :parent element)))
21666 (cond ((eq (org-element-type parent) 'item)
21667 (make-string (org-list-item-body-column
21668 (org-element-property :begin parent))
21669 ? ))
21670 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21671 (match-string 0))
21672 (t ""))))
21673 (comment-block
21674 ;; Only fill contents if P is within block boundaries.
21675 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21676 (forward-line)
21677 (point)))
21678 (cend (save-excursion
21679 (goto-char (org-element-property :end element))
21680 (skip-chars-backward " \r\t\n")
21681 (line-beginning-position))))
21682 (when (and (>= p cbeg) (< p cend))
21683 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21684 (match-string 0)
21685 "")))))))))))
21687 (declare-function message-goto-body "message" ())
21688 (defvar message-cite-prefix-regexp) ; From message.el
21689 (defvar org-element-all-objects) ; From org-element.el
21690 (defun org-fill-paragraph (&optional justify)
21691 "Fill element at point, when applicable.
21693 This function only applies to comment blocks, comments, example
21694 blocks and paragraphs. Also, as a special case, re-align table
21695 when point is at one.
21697 If JUSTIFY is non-nil (interactively, with prefix argument),
21698 justify as well. If `sentence-end-double-space' is non-nil, then
21699 period followed by one space does not end a sentence, so don't
21700 break a line there. The variable `fill-column' controls the
21701 width for filling.
21703 For convenience, when point is at a plain list, an item or
21704 a footnote definition, try to fill the first paragraph within."
21705 (interactive)
21706 (if (and (derived-mode-p 'message-mode)
21707 (or (not (message-in-body-p))
21708 (save-excursion (move-beginning-of-line 1)
21709 (looking-at message-cite-prefix-regexp))))
21710 ;; First ensure filling is correct in message-mode.
21711 (let ((fill-paragraph-function
21712 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21713 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21714 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21715 (paragraph-separate
21716 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21717 (fill-paragraph nil))
21718 (save-excursion
21719 ;; Move to end of line in order to get the first paragraph
21720 ;; within a plain list or a footnote definition.
21721 (end-of-line)
21722 (let ((element (org-element-at-point)))
21723 ;; First check if point is in a blank line at the beginning of
21724 ;; the buffer. In that case, ignore filling.
21725 (if (< (point) (org-element-property :begin element)) t
21726 (case (org-element-type element)
21727 ;; Use major mode filling function is src blocks.
21728 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21729 ;; Align Org tables, leave table.el tables as-is.
21730 (table-row (org-table-align) t)
21731 (table
21732 (when (eq (org-element-property :type element) 'org)
21733 (org-table-align))
21735 (paragraph
21736 ;; Paragraphs may contain `line-break' type objects.
21737 (let ((beg (max (point-min)
21738 (org-element-property :contents-begin element)))
21739 (end (min (point-max)
21740 (org-element-property :contents-end element))))
21741 ;; Do nothing if point is at an affiliated keyword.
21742 (if (< (point) beg) t
21743 (when (derived-mode-p 'message-mode)
21744 ;; In `message-mode', do not fill following
21745 ;; citation in current paragraph nor text before
21746 ;; message body.
21747 (let ((body-start (save-excursion (message-goto-body))))
21748 (when body-start (setq beg (max body-start beg))))
21749 (when (save-excursion
21750 (re-search-forward
21751 (concat "^" message-cite-prefix-regexp) end t))
21752 (setq end (match-beginning 0))))
21753 ;; Fill paragraph, taking line breaks into
21754 ;; consideration. For that, slice the paragraph
21755 ;; using line breaks as separators, and fill the
21756 ;; parts in reverse order to avoid messing with
21757 ;; markers.
21758 (save-excursion
21759 (goto-char end)
21760 (mapc
21761 (lambda (pos)
21762 (fill-region-as-paragraph pos (point) justify)
21763 (goto-char pos))
21764 ;; Find the list of ending positions for line
21765 ;; breaks in the current paragraph. Add paragraph
21766 ;; beginning to include first slice.
21767 (nreverse
21768 (cons
21770 (org-element-map
21771 (org-element--parse-objects
21772 beg end nil org-element-all-objects)
21773 'line-break
21774 (lambda (lb) (org-element-property :end lb)))))))
21775 t)))
21776 ;; Contents of `comment-block' type elements should be
21777 ;; filled as plain text, but only if point is within block
21778 ;; markers.
21779 (comment-block
21780 (let* ((case-fold-search t)
21781 (beg (save-excursion
21782 (goto-char (org-element-property :begin element))
21783 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21784 (forward-line)
21785 (point)))
21786 (end (save-excursion
21787 (goto-char (org-element-property :end element))
21788 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21789 (line-beginning-position))))
21790 (when (and (>= (point) beg) (< (point) end))
21791 (fill-region-as-paragraph
21792 (save-excursion
21793 (end-of-line)
21794 (re-search-backward "^[ \t]*$" beg 'move)
21795 (line-beginning-position))
21796 (save-excursion
21797 (beginning-of-line)
21798 (re-search-forward "^[ \t]*$" end 'move)
21799 (line-beginning-position))
21800 justify)))
21802 ;; Fill comments.
21803 (comment (fill-comment-paragraph justify))
21804 ;; Ignore every other element.
21805 (otherwise t)))))))
21807 (defun org-auto-fill-function ()
21808 "Auto-fill function."
21809 ;; Check if auto-filling is meaningful.
21810 (let ((fc (current-fill-column)))
21811 (when (and fc (> (current-column) fc))
21812 (let* ((fill-prefix (org-adaptive-fill-function))
21813 ;; Enforce empty fill prefix, if required. Otherwise, it
21814 ;; will be computed again.
21815 (adaptive-fill-mode (not (equal fill-prefix ""))))
21816 (when fill-prefix (do-auto-fill))))))
21818 (defun org-comment-line-break-function (&optional soft)
21819 "Break line at point and indent, continuing comment if within one.
21820 The inserted newline is marked hard if variable
21821 `use-hard-newlines' is true, unless optional argument SOFT is
21822 non-nil."
21823 (if soft (insert-and-inherit ?\n) (newline 1))
21824 (save-excursion (forward-char -1) (delete-horizontal-space))
21825 (delete-horizontal-space)
21826 (indent-to-left-margin)
21827 (insert-before-markers-and-inherit fill-prefix))
21830 ;;; Comments
21832 ;; Org comments syntax is quite complex. It requires the entire line
21833 ;; to be just a comment. Also, even with the right syntax at the
21834 ;; beginning of line, some some elements (i.e. verse-block or
21835 ;; example-block) don't accept comments. Usual Emacs comment commands
21836 ;; cannot cope with those requirements. Therefore, Org replaces them.
21838 ;; Org still relies on `comment-dwim', but cannot trust
21839 ;; `comment-only-p'. So, `comment-region-function' and
21840 ;; `uncomment-region-function' both point
21841 ;; to`org-comment-or-uncomment-region'. Eventually,
21842 ;; `org-insert-comment' takes care of insertion of comments at the
21843 ;; beginning of line.
21845 ;; `org-setup-comments-handling' install comments related variables
21846 ;; during `org-mode' initialization.
21848 (defun org-setup-comments-handling ()
21849 (interactive)
21850 (org-set-local 'comment-use-syntax nil)
21851 (org-set-local 'comment-start "# ")
21852 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21853 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21854 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21855 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21857 (defun org-insert-comment ()
21858 "Insert an empty comment above current line.
21859 If the line is empty, insert comment at its beginning."
21860 (beginning-of-line)
21861 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21862 (org-indent-line)
21863 (insert "# "))
21865 (defvar comment-empty-lines) ; From newcomment.el.
21866 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21867 "Comment or uncomment each non-blank line in the region.
21868 Uncomment each non-blank line between BEG and END if it only
21869 contains commented lines. Otherwise, comment them."
21870 (save-restriction
21871 ;; Restrict region
21872 (narrow-to-region (save-excursion (goto-char beg)
21873 (skip-chars-forward " \r\t\n" end)
21874 (line-beginning-position))
21875 (save-excursion (goto-char end)
21876 (skip-chars-backward " \r\t\n" beg)
21877 (line-end-position)))
21878 (let ((uncommentp
21879 ;; UNCOMMENTP is non-nil when every non blank line between
21880 ;; BEG and END is a comment.
21881 (save-excursion
21882 (goto-char (point-min))
21883 (while (and (not (eobp))
21884 (let ((element (org-element-at-point)))
21885 (and (eq (org-element-type element) 'comment)
21886 (goto-char (min (point-max)
21887 (org-element-property
21888 :end element)))))))
21889 (eobp))))
21890 (if uncommentp
21891 ;; Only blank lines and comments in region: uncomment it.
21892 (save-excursion
21893 (goto-char (point-min))
21894 (while (not (eobp))
21895 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21896 (replace-match "" nil nil nil 1))
21897 (forward-line)))
21898 ;; Comment each line in region.
21899 (let ((min-indent (point-max)))
21900 ;; First find the minimum indentation across all lines.
21901 (save-excursion
21902 (goto-char (point-min))
21903 (while (and (not (eobp)) (not (zerop min-indent)))
21904 (unless (looking-at "[ \t]*$")
21905 (setq min-indent (min min-indent (current-indentation))))
21906 (forward-line)))
21907 ;; Then loop over all lines.
21908 (save-excursion
21909 (goto-char (point-min))
21910 (while (not (eobp))
21911 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21912 (org-move-to-column min-indent t)
21913 (insert comment-start))
21914 (forward-line))))))))
21917 ;;; Planning
21919 ;; This section contains tools to operate on timestamp objects, as
21920 ;; returned by, e.g. `org-element-context'.
21922 (defun org-timestamp-has-time-p (timestamp)
21923 "Non-nil when TIMESTAMP has a time specified."
21924 (org-element-property :hour-start timestamp))
21926 (defun org-timestamp-format (timestamp format &optional end utc)
21927 "Format a TIMESTAMP element into a string.
21929 FORMAT is a format specifier to be passed to
21930 `format-time-string'.
21932 When optional argument END is non-nil, use end of date-range or
21933 time-range, if possible.
21935 When optional argument UTC is non-nil, time will be expressed as
21936 Universal Time."
21937 (format-time-string
21938 format
21939 (apply 'encode-time
21940 (cons 0
21941 (mapcar
21942 (lambda (prop) (or (org-element-property prop timestamp) 0))
21943 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21944 '(:minute-start :hour-start :day-start :month-start
21945 :year-start)))))
21946 utc))
21948 (defun org-timestamp-split-range (timestamp &optional end)
21949 "Extract a timestamp object from a date or time range.
21951 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21952 the end of the range. Otherwise, extract its start.
21954 Return a new timestamp object sharing the same parent as
21955 TIMESTAMP."
21956 (let ((type (org-element-property :type timestamp)))
21957 (if (memq type '(active inactive diary)) timestamp
21958 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21959 ;; Set new type.
21960 (org-element-put-property
21961 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21962 ;; Copy start properties over end properties if END is
21963 ;; non-nil. Otherwise, copy end properties over `start' ones.
21964 (let ((p-alist '((:minute-start . :minute-end)
21965 (:hour-start . :hour-end)
21966 (:day-start . :day-end)
21967 (:month-start . :month-end)
21968 (:year-start . :year-end))))
21969 (dolist (p-cell p-alist)
21970 (org-element-put-property
21971 split-ts
21972 (funcall (if end 'car 'cdr) p-cell)
21973 (org-element-property
21974 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21975 ;; Eventually refresh `:raw-value'.
21976 (org-element-put-property split-ts :raw-value nil)
21977 (org-element-put-property
21978 split-ts :raw-value (org-element-interpret-data split-ts)))))))
21980 (defun org-timestamp-translate (timestamp &optional boundary)
21981 "Apply `org-translate-time' on a TIMESTAMP object.
21982 When optional argument BOUNDARY is non-nil, it is either the
21983 symbol `start' or `end'. In this case, only translate the
21984 starting or ending part of TIMESTAMP if it is a date or time
21985 range. Otherwise, translate both parts."
21986 (if (and (not boundary)
21987 (memq (org-element-property :type timestamp)
21988 '(active-range inactive-range)))
21989 (concat
21990 (org-translate-time
21991 (org-element-property :raw-value
21992 (org-timestamp-split-range timestamp)))
21993 "--"
21994 (org-translate-time
21995 (org-element-property :raw-value
21996 (org-timestamp-split-range timestamp t))))
21997 (org-translate-time
21998 (org-element-property
21999 :raw-value
22000 (if (not boundary) timestamp
22001 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22005 ;;; Other stuff.
22007 (defun org-toggle-fixed-width-section (arg)
22008 "Toggle the fixed-width export.
22009 If there is no active region, the QUOTE keyword at the current headline is
22010 inserted or removed. When present, it causes the text between this headline
22011 and the next to be exported as fixed-width text, and unmodified.
22012 If there is an active region, this command adds or removes a colon as the
22013 first character of this line. If the first character of a line is a colon,
22014 this line is also exported in fixed-width font."
22015 (interactive "P")
22016 (let* ((cc 0)
22017 (regionp (org-region-active-p))
22018 (beg (if regionp (region-beginning) (point)))
22019 (end (if regionp (region-end)))
22020 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22021 (case-fold-search nil)
22022 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22023 off)
22024 (if regionp
22025 (save-excursion
22026 (goto-char beg)
22027 (setq cc (current-column))
22028 (beginning-of-line 1)
22029 (setq off (looking-at re))
22030 (while (> nlines 0)
22031 (setq nlines (1- nlines))
22032 (beginning-of-line 1)
22033 (cond
22034 (arg
22035 (org-move-to-column cc t)
22036 (insert ": \n")
22037 (forward-line -1))
22038 ((and off (looking-at re))
22039 (replace-match "" t t nil 1))
22040 ((not off) (org-move-to-column cc t) (insert ": ")))
22041 (forward-line 1)))
22042 (save-excursion
22043 (org-back-to-heading)
22044 (cond
22045 ((looking-at (format org-heading-keyword-regexp-format
22046 org-quote-string))
22047 (goto-char (match-end 1))
22048 (looking-at (concat " +" org-quote-string))
22049 (replace-match "" t t)
22050 (when (eolp) (insert " ")))
22051 ((looking-at org-outline-regexp)
22052 (goto-char (match-end 0))
22053 (insert org-quote-string " ")))))))
22055 (defun org-reftex-citation ()
22056 "Use reftex-citation to insert a citation into the buffer.
22057 This looks for a line like
22059 #+BIBLIOGRAPHY: foo plain option:-d
22061 and derives from it that foo.bib is the bibliography file relevant
22062 for this document. It then installs the necessary environment for RefTeX
22063 to work in this buffer and calls `reftex-citation' to insert a citation
22064 into the buffer.
22066 Export of such citations to both LaTeX and HTML is handled by the contributed
22067 package org-exp-bibtex by Taru Karttunen."
22068 (interactive)
22069 (let ((reftex-docstruct-symbol 'rds)
22070 (reftex-cite-format "\\cite{%l}")
22071 rds bib)
22072 (save-excursion
22073 (save-restriction
22074 (widen)
22075 (let ((case-fold-search t)
22076 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22077 (if (not (save-excursion
22078 (or (re-search-forward re nil t)
22079 (re-search-backward re nil t))))
22080 (error "No bibliography defined in file")
22081 (setq bib (concat (match-string 1) ".bib")
22082 rds (list (list 'bib bib)))))))
22083 (call-interactively 'reftex-citation)))
22085 ;;;; Functions extending outline functionality
22087 (defun org-beginning-of-line (&optional arg)
22088 "Go to the beginning of the current line. If that is invisible, continue
22089 to a visible line beginning. This makes the function of C-a more intuitive.
22090 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22091 first attempt, and only move to after the tags when the cursor is already
22092 beyond the end of the headline."
22093 (interactive "P")
22094 (let ((pos (point))
22095 (special (if (consp org-special-ctrl-a/e)
22096 (car org-special-ctrl-a/e)
22097 org-special-ctrl-a/e))
22098 refpos)
22099 (if (org-bound-and-true-p visual-line-mode)
22100 (beginning-of-visual-line 1)
22101 (beginning-of-line 1))
22102 (if (and arg (fboundp 'move-beginning-of-line))
22103 (call-interactively 'move-beginning-of-line)
22104 (if (bobp)
22106 (backward-char 1)
22107 (if (org-truely-invisible-p)
22108 (while (and (not (bobp)) (org-truely-invisible-p))
22109 (backward-char 1)
22110 (beginning-of-line 1))
22111 (forward-char 1))))
22112 (when special
22113 (cond
22114 ((and (looking-at org-complex-heading-regexp)
22115 (= (char-after (match-end 1)) ?\ ))
22116 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22117 (point-at-eol)))
22118 (goto-char
22119 (if (eq special t)
22120 (cond ((> pos refpos) refpos)
22121 ((= pos (point)) refpos)
22122 (t (point)))
22123 (cond ((> pos (point)) (point))
22124 ((not (eq last-command this-command)) (point))
22125 (t refpos)))))
22126 ((org-at-item-p)
22127 ;; Being at an item and not looking at an the item means point
22128 ;; was previously moved to beginning of a visual line, which
22129 ;; doesn't contain the item. Therefore, do nothing special,
22130 ;; just stay here.
22131 (when (looking-at org-list-full-item-re)
22132 ;; Set special position at first white space character after
22133 ;; bullet, and check-box, if any.
22134 (let ((after-bullet
22135 (let ((box (match-end 3)))
22136 (if (not box) (match-end 1)
22137 (let ((after (char-after box)))
22138 (if (and after (= after ? )) (1+ box) box))))))
22139 ;; Special case: Move point to special position when
22140 ;; currently after it or at beginning of line.
22141 (if (eq special t)
22142 (when (or (> pos after-bullet) (= (point) pos))
22143 (goto-char after-bullet))
22144 ;; Reversed case: Move point to special position when
22145 ;; point was already at beginning of line and command is
22146 ;; repeated.
22147 (when (and (= (point) pos) (eq last-command this-command))
22148 (goto-char after-bullet))))))))
22149 (org-no-warnings
22150 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22152 (defun org-end-of-line (&optional arg)
22153 "Go to the end of the line.
22154 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22155 tags on the first attempt, and only move to after the tags when
22156 the cursor is already beyond the end of the headline."
22157 (interactive "P")
22158 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22159 org-special-ctrl-a/e))
22160 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22161 'end-of-visual-line)
22162 ((fboundp 'move-end-of-line) 'move-end-of-line)
22163 (t 'end-of-line))))
22164 (if (or (not special) arg) (call-interactively move-fun)
22165 (let* ((element (save-excursion (beginning-of-line)
22166 (org-element-at-point)))
22167 (type (org-element-type element)))
22168 (cond
22169 ((memq type '(headline inlinetask))
22170 (let ((pos (point)))
22171 (beginning-of-line 1)
22172 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22173 (if (eq special t)
22174 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22175 (goto-char (match-beginning 1))
22176 (goto-char (match-end 0)))
22177 (if (or (< pos (match-end 0))
22178 (not (eq this-command last-command)))
22179 (goto-char (match-end 0))
22180 (goto-char (match-beginning 1))))
22181 (call-interactively move-fun))))
22182 ((org-element-property :hiddenp element)
22183 ;; If element is hidden, `move-end-of-line' would put point
22184 ;; after it. Use `end-of-line' to stay on current line.
22185 (call-interactively 'end-of-line))
22186 (t (call-interactively move-fun)))))
22187 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22189 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22190 (define-key org-mode-map "\C-e" 'org-end-of-line)
22192 (defun org-backward-sentence (&optional arg)
22193 "Go to beginning of sentence, or beginning of table field.
22194 This will call `backward-sentence' or `org-table-beginning-of-field',
22195 depending on context."
22196 (interactive "P")
22197 (cond
22198 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22199 (t (call-interactively 'backward-sentence))))
22201 (defun org-forward-sentence (&optional arg)
22202 "Go to end of sentence, or end of table field.
22203 This will call `forward-sentence' or `org-table-end-of-field',
22204 depending on context."
22205 (interactive "P")
22206 (cond
22207 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22208 (t (call-interactively 'forward-sentence))))
22210 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22211 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22213 (defun org-kill-line (&optional arg)
22214 "Kill line, to tags or end of line."
22215 (interactive "P")
22216 (cond
22217 ((or (not org-special-ctrl-k)
22218 (bolp)
22219 (not (org-at-heading-p)))
22220 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22221 org-ctrl-k-protect-subtree)
22222 (if (or (eq org-ctrl-k-protect-subtree 'error)
22223 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22224 (error "C-k aborted - would kill hidden subtree")))
22225 (call-interactively
22226 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22227 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22228 (kill-region (point) (match-beginning 1))
22229 (org-set-tags nil t))
22230 (t (kill-region (point) (point-at-eol)))))
22232 (define-key org-mode-map "\C-k" 'org-kill-line)
22234 (defun org-yank (&optional arg)
22235 "Yank. If the kill is a subtree, treat it specially.
22236 This command will look at the current kill and check if is a single
22237 subtree, or a series of subtrees[1]. If it passes the test, and if the
22238 cursor is at the beginning of a line or after the stars of a currently
22239 empty headline, then the yank is handled specially. How exactly depends
22240 on the value of the following variables, both set by default.
22242 org-yank-folded-subtrees
22243 When set, the subtree(s) will be folded after insertion, but only
22244 if doing so would now swallow text after the yanked text.
22246 org-yank-adjusted-subtrees
22247 When set, the subtree will be promoted or demoted in order to
22248 fit into the local outline tree structure, which means that the level
22249 will be adjusted so that it becomes the smaller one of the two
22250 *visible* surrounding headings.
22252 Any prefix to this command will cause `yank' to be called directly with
22253 no special treatment. In particular, a simple \\[universal-argument] prefix \
22254 will just
22255 plainly yank the text as it is.
22257 \[1] The test checks if the first non-white line is a heading
22258 and if there are no other headings with fewer stars."
22259 (interactive "P")
22260 (org-yank-generic 'yank arg))
22262 (defun org-yank-generic (command arg)
22263 "Perform some yank-like command.
22265 This function implements the behavior described in the `org-yank'
22266 documentation. However, it has been generalized to work for any
22267 interactive command with similar behavior."
22269 ;; pretend to be command COMMAND
22270 (setq this-command command)
22272 (if arg
22273 (call-interactively command)
22275 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22276 (and (org-kill-is-subtree-p)
22277 (or (bolp)
22278 (and (looking-at "[ \t]*$")
22279 (string-match
22280 "\\`\\*+\\'"
22281 (buffer-substring (point-at-bol) (point)))))))
22282 swallowp)
22283 (cond
22284 ((and subtreep org-yank-folded-subtrees)
22285 (let ((beg (point))
22286 end)
22287 (if (and subtreep org-yank-adjusted-subtrees)
22288 (org-paste-subtree nil nil 'for-yank)
22289 (call-interactively command))
22291 (setq end (point))
22292 (goto-char beg)
22293 (when (and (bolp) subtreep
22294 (not (setq swallowp
22295 (org-yank-folding-would-swallow-text beg end))))
22296 (org-with-limited-levels
22297 (or (looking-at org-outline-regexp)
22298 (re-search-forward org-outline-regexp-bol end t))
22299 (while (and (< (point) end) (looking-at org-outline-regexp))
22300 (hide-subtree)
22301 (org-cycle-show-empty-lines 'folded)
22302 (condition-case nil
22303 (outline-forward-same-level 1)
22304 (error (goto-char end))))))
22305 (when swallowp
22306 (message
22307 "Inserted text not folded because that would swallow text"))
22309 (goto-char end)
22310 (skip-chars-forward " \t\n\r")
22311 (beginning-of-line 1)
22312 (push-mark beg 'nomsg)))
22313 ((and subtreep org-yank-adjusted-subtrees)
22314 (let ((beg (point-at-bol)))
22315 (org-paste-subtree nil nil 'for-yank)
22316 (push-mark beg 'nomsg)))
22318 (call-interactively command))))))
22320 (defun org-yank-folding-would-swallow-text (beg end)
22321 "Would hide-subtree at BEG swallow any text after END?"
22322 (let (level)
22323 (org-with-limited-levels
22324 (save-excursion
22325 (goto-char beg)
22326 (when (or (looking-at org-outline-regexp)
22327 (re-search-forward org-outline-regexp-bol end t))
22328 (setq level (org-outline-level)))
22329 (goto-char end)
22330 (skip-chars-forward " \t\r\n\v\f")
22331 (if (or (eobp)
22332 (and (bolp) (looking-at org-outline-regexp)
22333 (<= (org-outline-level) level)))
22334 nil ; Nothing would be swallowed
22335 t))))) ; something would swallow
22337 (define-key org-mode-map "\C-y" 'org-yank)
22339 (defun org-truely-invisible-p ()
22340 "Check if point is at a character currently not visible.
22341 This version does not only check the character property, but also
22342 `visible-mode'."
22343 ;; Early versions of noutline don't have `outline-invisible-p'.
22344 (if (org-bound-and-true-p visible-mode)
22346 (outline-invisible-p)))
22348 (defun org-invisible-p2 ()
22349 "Check if point is at a character currently not visible."
22350 (save-excursion
22351 (if (and (eolp) (not (bobp))) (backward-char 1))
22352 ;; Early versions of noutline don't have `outline-invisible-p'.
22353 (outline-invisible-p)))
22355 (defun org-back-to-heading (&optional invisible-ok)
22356 "Call `outline-back-to-heading', but provide a better error message."
22357 (condition-case nil
22358 (outline-back-to-heading invisible-ok)
22359 (error (error "Before first headline at position %d in buffer %s"
22360 (point) (current-buffer)))))
22362 (defun org-before-first-heading-p ()
22363 "Before first heading?"
22364 (save-excursion
22365 (end-of-line)
22366 (null (re-search-backward org-outline-regexp-bol nil t))))
22368 (defun org-at-heading-p (&optional ignored)
22369 (outline-on-heading-p t))
22370 ;; Compatibility alias with Org versions < 7.8.03
22371 (defalias 'org-on-heading-p 'org-at-heading-p)
22373 (defun org-at-comment-p nil
22374 "Is cursor in a line starting with a # character?"
22375 (save-excursion
22376 (beginning-of-line)
22377 (looking-at "^#")))
22379 (defun org-at-drawer-p nil
22380 "Is cursor at a drawer keyword?"
22381 (save-excursion
22382 (move-beginning-of-line 1)
22383 (looking-at org-drawer-regexp)))
22385 (defun org-at-block-p nil
22386 "Is cursor at a block keyword?"
22387 (save-excursion
22388 (move-beginning-of-line 1)
22389 (looking-at org-block-regexp)))
22391 (defun org-point-at-end-of-empty-headline ()
22392 "If point is at the end of an empty headline, return t, else nil.
22393 If the heading only contains a TODO keyword, it is still still considered
22394 empty."
22395 (and (looking-at "[ \t]*$")
22396 (when org-todo-line-regexp
22397 (save-excursion
22398 (beginning-of-line 1)
22399 (let ((case-fold-search nil))
22400 (looking-at org-todo-line-regexp)
22401 (string= (match-string 3) ""))))))
22403 (defun org-at-heading-or-item-p ()
22404 (or (org-at-heading-p) (org-at-item-p)))
22406 (defun org-at-target-p ()
22407 (or (org-in-regexp org-radio-target-regexp)
22408 (org-in-regexp org-target-regexp)))
22409 ;; Compatibility alias with Org versions < 7.8.03
22410 (defalias 'org-on-target-p 'org-at-target-p)
22412 (defun org-up-heading-all (arg)
22413 "Move to the heading line of which the present line is a subheading.
22414 This function considers both visible and invisible heading lines.
22415 With argument, move up ARG levels."
22416 (if (fboundp 'outline-up-heading-all)
22417 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22418 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22420 (defun org-up-heading-safe ()
22421 "Move to the heading line of which the present line is a subheading.
22422 This version will not throw an error. It will return the level of the
22423 headline found, or nil if no higher level is found.
22425 Also, this function will be a lot faster than `outline-up-heading',
22426 because it relies on stars being the outline starters. This can really
22427 make a significant difference in outlines with very many siblings."
22428 (let (start-level re)
22429 (org-back-to-heading t)
22430 (setq start-level (funcall outline-level))
22431 (if (equal start-level 1)
22433 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22434 (if (re-search-backward re nil t)
22435 (funcall outline-level)))))
22437 (defun org-first-sibling-p ()
22438 "Is this heading the first child of its parents?"
22439 (interactive)
22440 (let ((re org-outline-regexp-bol)
22441 level l)
22442 (unless (org-at-heading-p t)
22443 (error "Not at a heading"))
22444 (setq level (funcall outline-level))
22445 (save-excursion
22446 (if (not (re-search-backward re nil t))
22448 (setq l (funcall outline-level))
22449 (< l level)))))
22451 (defun org-goto-sibling (&optional previous)
22452 "Goto the next sibling, even if it is invisible.
22453 When PREVIOUS is set, go to the previous sibling instead. Returns t
22454 when a sibling was found. When none is found, return nil and don't
22455 move point."
22456 (let ((fun (if previous 're-search-backward 're-search-forward))
22457 (pos (point))
22458 (re org-outline-regexp-bol)
22459 level l)
22460 (when (condition-case nil (org-back-to-heading t) (error nil))
22461 (setq level (funcall outline-level))
22462 (catch 'exit
22463 (or previous (forward-char 1))
22464 (while (funcall fun re nil t)
22465 (setq l (funcall outline-level))
22466 (when (< l level) (goto-char pos) (throw 'exit nil))
22467 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22468 (goto-char pos)
22469 nil))))
22471 (defun org-show-siblings ()
22472 "Show all siblings of the current headline."
22473 (save-excursion
22474 (while (org-goto-sibling) (org-flag-heading nil)))
22475 (save-excursion
22476 (while (org-goto-sibling 'previous)
22477 (org-flag-heading nil))))
22479 (defun org-goto-first-child ()
22480 "Goto the first child, even if it is invisible.
22481 Return t when a child was found. Otherwise don't move point and
22482 return nil."
22483 (let (level (pos (point)) (re org-outline-regexp-bol))
22484 (when (condition-case nil (org-back-to-heading t) (error nil))
22485 (setq level (outline-level))
22486 (forward-char 1)
22487 (if (and (re-search-forward re nil t) (> (outline-level) level))
22488 (progn (goto-char (match-beginning 0)) t)
22489 (goto-char pos) nil))))
22491 (defun org-show-hidden-entry ()
22492 "Show an entry where even the heading is hidden."
22493 (save-excursion
22494 (org-show-entry)))
22496 (defun org-flag-heading (flag &optional entry)
22497 "Flag the current heading. FLAG non-nil means make invisible.
22498 When ENTRY is non-nil, show the entire entry."
22499 (save-excursion
22500 (org-back-to-heading t)
22501 ;; Check if we should show the entire entry
22502 (if entry
22503 (progn
22504 (org-show-entry)
22505 (save-excursion
22506 (and (outline-next-heading)
22507 (org-flag-heading nil))))
22508 (outline-flag-region (max (point-min) (1- (point)))
22509 (save-excursion (outline-end-of-heading) (point))
22510 flag))))
22512 (defun org-get-next-sibling ()
22513 "Move to next heading of the same level, and return point.
22514 If there is no such heading, return nil.
22515 This is like outline-next-sibling, but invisible headings are ok."
22516 (let ((level (funcall outline-level)))
22517 (outline-next-heading)
22518 (while (and (not (eobp)) (> (funcall outline-level) level))
22519 (outline-next-heading))
22520 (if (or (eobp) (< (funcall outline-level) level))
22522 (point))))
22524 (defun org-get-last-sibling ()
22525 "Move to previous heading of the same level, and return point.
22526 If there is no such heading, return nil."
22527 (let ((opoint (point))
22528 (level (funcall outline-level)))
22529 (outline-previous-heading)
22530 (when (and (/= (point) opoint) (outline-on-heading-p t))
22531 (while (and (> (funcall outline-level) level)
22532 (not (bobp)))
22533 (outline-previous-heading))
22534 (if (< (funcall outline-level) level)
22536 (point)))))
22538 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22539 "Goto to the end of a subtree."
22540 ;; This contains an exact copy of the original function, but it uses
22541 ;; `org-back-to-heading', to make it work also in invisible
22542 ;; trees. And is uses an invisible-ok argument.
22543 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22544 ;; Furthermore, when used inside Org, finding the end of a large subtree
22545 ;; with many children and grandchildren etc, this can be much faster
22546 ;; than the outline version.
22547 (org-back-to-heading invisible-ok)
22548 (let ((first t)
22549 (level (funcall outline-level)))
22550 (if (and (derived-mode-p 'org-mode) (< level 1000))
22551 ;; A true heading (not a plain list item), in Org-mode
22552 ;; This means we can easily find the end by looking
22553 ;; only for the right number of stars. Using a regexp to do
22554 ;; this is so much faster than using a Lisp loop.
22555 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22556 (forward-char 1)
22557 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22558 ;; something else, do it the slow way
22559 (while (and (not (eobp))
22560 (or first (> (funcall outline-level) level)))
22561 (setq first nil)
22562 (outline-next-heading)))
22563 (unless to-heading
22564 (if (memq (preceding-char) '(?\n ?\^M))
22565 (progn
22566 ;; Go to end of line before heading
22567 (forward-char -1)
22568 (if (memq (preceding-char) '(?\n ?\^M))
22569 ;; leave blank line before heading
22570 (forward-char -1))))))
22571 (point))
22573 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22574 "Use Org version in org-mode, for dramatic speed-up."
22575 (if (derived-mode-p 'org-mode)
22576 (progn
22577 (org-end-of-subtree nil t)
22578 (unless (eobp) (backward-char 1)))
22579 ad-do-it))
22581 (defun org-end-of-meta-data-and-drawers ()
22582 "Jump to the first text after meta data and drawers in the current entry.
22583 This will move over empty lines, lines with planning time stamps,
22584 clocking lines, and drawers."
22585 (org-back-to-heading t)
22586 (let ((end (save-excursion (outline-next-heading) (point)))
22587 (re (concat "\\(" org-drawer-regexp "\\)"
22588 "\\|" "[ \t]*" org-keyword-time-regexp)))
22589 (forward-line 1)
22590 (while (re-search-forward re end t)
22591 (if (not (match-end 1))
22592 ;; empty or planning line
22593 (forward-line 1)
22594 ;; a drawer, find the end
22595 (re-search-forward "^[ \t]*:END:" end 'move)
22596 (forward-line 1)))
22597 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22598 (point)))
22600 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22601 "Move forward to the arg'th subheading at same level as this one.
22602 Stop at the first and last subheadings of a superior heading.
22603 Normally this only looks at visible headings, but when INVISIBLE-OK is
22604 non-nil it will also look at invisible ones."
22605 (interactive "p")
22606 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22607 (outline-next-heading)
22608 (org-at-heading-p)
22609 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22610 (re (format "^\\*\\{1,%d\\} " level))
22612 (forward-char 1)
22613 (while (> arg 0)
22614 (while (and (re-search-forward re nil 'move)
22615 (setq l (- (match-end 0) (match-beginning 0) 1))
22616 (= l level)
22617 (not invisible-ok)
22618 (progn (backward-char 1) (outline-invisible-p)))
22619 (if (< l level) (setq arg 1)))
22620 (setq arg (1- arg)))
22621 (beginning-of-line 1))))
22623 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22624 "Move backward to the arg'th subheading at same level as this one.
22625 Stop at the first and last subheadings of a superior heading."
22626 (interactive "p")
22627 (if (not (ignore-errors (org-back-to-heading)))
22628 (goto-char (point-min))
22629 (org-at-heading-p)
22630 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22631 (re (format "^\\*\\{1,%d\\} " level))
22633 (while (> arg 0)
22634 (while (and (re-search-backward re nil 'move)
22635 (setq l (- (match-end 0) (match-beginning 0) 1))
22636 (= l level)
22637 (not invisible-ok)
22638 (outline-invisible-p))
22639 (if (< l level) (setq arg 1)))
22640 (setq arg (1- arg))))))
22642 (defun org-forward-element ()
22643 "Move forward by one element.
22644 Move to the next element at the same level, when possible."
22645 (interactive)
22646 (cond ((eobp) (error "Cannot move further down"))
22647 ((org-with-limited-levels (org-at-heading-p))
22648 (let ((origin (point)))
22649 (org-forward-heading-same-level 1)
22650 (unless (org-with-limited-levels (org-at-heading-p))
22651 (goto-char origin)
22652 (error "Cannot move further down"))))
22654 (let* ((elem (org-element-at-point))
22655 (end (org-element-property :end elem))
22656 (parent (org-element-property :parent elem)))
22657 (if (and parent (= (org-element-property :contents-end parent) end))
22658 (goto-char (org-element-property :end parent))
22659 (goto-char end))))))
22661 (defun org-backward-element ()
22662 "Move backward by one element.
22663 Move to the previous element at the same level, when possible."
22664 (interactive)
22665 (cond ((bobp) (error "Cannot move further up"))
22666 ((org-with-limited-levels (org-at-heading-p))
22667 ;; At an headline, move to the previous one, if any, or stay
22668 ;; here.
22669 (let ((origin (point)))
22670 (org-backward-heading-same-level 1)
22671 (unless (org-with-limited-levels (org-at-heading-p))
22672 (goto-char origin)
22673 (error "Cannot move further up"))))
22675 (let* ((trail (org-element-at-point 'keep-trail))
22676 (elem (car trail))
22677 (prev-elem (nth 1 trail))
22678 (beg (org-element-property :begin elem)))
22679 (cond
22680 ;; Move to beginning of current element if point isn't
22681 ;; there already.
22682 ((/= (point) beg) (goto-char beg))
22683 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22684 ((org-before-first-heading-p) (goto-char (point-min)))
22685 (t (org-back-to-heading)))))))
22687 (defun org-up-element ()
22688 "Move to upper element."
22689 (interactive)
22690 (if (org-with-limited-levels (org-at-heading-p))
22691 (unless (org-up-heading-safe) (error "No surrounding element"))
22692 (let* ((elem (org-element-at-point))
22693 (parent (org-element-property :parent elem)))
22694 (if parent (goto-char (org-element-property :begin parent))
22695 (if (org-with-limited-levels (org-before-first-heading-p))
22696 (error "No surrounding element")
22697 (org-with-limited-levels (org-back-to-heading)))))))
22699 (defvar org-element-greater-elements)
22700 (defun org-down-element ()
22701 "Move to inner element."
22702 (interactive)
22703 (let ((element (org-element-at-point)))
22704 (cond
22705 ((memq (org-element-type element) '(plain-list table))
22706 (goto-char (org-element-property :contents-begin element))
22707 (forward-char))
22708 ((memq (org-element-type element) org-element-greater-elements)
22709 ;; If contents are hidden, first disclose them.
22710 (when (org-element-property :hiddenp element) (org-cycle))
22711 (goto-char (or (org-element-property :contents-begin element)
22712 (error "No content for this element"))))
22713 (t (error "No inner element")))))
22715 (defun org-drag-element-backward ()
22716 "Move backward element at point."
22717 (interactive)
22718 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22719 (let* ((trail (org-element-at-point 'keep-trail))
22720 (elem (car trail))
22721 (prev-elem (nth 1 trail)))
22722 ;; Error out if no previous element or previous element is
22723 ;; a parent of the current one.
22724 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22725 (error "Cannot drag element backward")
22726 (let ((pos (point)))
22727 (org-element-swap-A-B prev-elem elem)
22728 (goto-char (+ (org-element-property :begin prev-elem)
22729 (- pos (org-element-property :begin elem)))))))))
22731 (defun org-drag-element-forward ()
22732 "Move forward element at point."
22733 (interactive)
22734 (let* ((pos (point))
22735 (elem (org-element-at-point)))
22736 (when (= (point-max) (org-element-property :end elem))
22737 (error "Cannot drag element forward"))
22738 (goto-char (org-element-property :end elem))
22739 (let ((next-elem (org-element-at-point)))
22740 (when (or (org-element-nested-p elem next-elem)
22741 (and (eq (org-element-type next-elem) 'headline)
22742 (not (eq (org-element-type elem) 'headline))))
22743 (goto-char pos)
22744 (error "Cannot drag element forward"))
22745 ;; Compute new position of point: it's shifted by NEXT-ELEM
22746 ;; body's length (without final blanks) and by the length of
22747 ;; blanks between ELEM and NEXT-ELEM.
22748 (let ((size-next (- (save-excursion
22749 (goto-char (org-element-property :end next-elem))
22750 (skip-chars-backward " \r\t\n")
22751 (forward-line)
22752 ;; Small correction if buffer doesn't end
22753 ;; with a newline character.
22754 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22755 (org-element-property :begin next-elem)))
22756 (size-blank (- (org-element-property :end elem)
22757 (save-excursion
22758 (goto-char (org-element-property :end elem))
22759 (skip-chars-backward " \r\t\n")
22760 (forward-line)
22761 (point)))))
22762 (org-element-swap-A-B elem next-elem)
22763 (goto-char (+ pos size-next size-blank))))))
22765 (defun org-mark-element ()
22766 "Put point at beginning of this element, mark at end.
22768 Interactively, if this command is repeated or (in Transient Mark
22769 mode) if the mark is active, it marks the next element after the
22770 ones already marked."
22771 (interactive)
22772 (let (deactivate-mark)
22773 (if (and (org-called-interactively-p 'any)
22774 (or (and (eq last-command this-command) (mark t))
22775 (and transient-mark-mode mark-active)))
22776 (set-mark
22777 (save-excursion
22778 (goto-char (mark))
22779 (goto-char (org-element-property :end (org-element-at-point)))))
22780 (let ((element (org-element-at-point)))
22781 (end-of-line)
22782 (push-mark (org-element-property :end element) t t)
22783 (goto-char (org-element-property :begin element))))))
22785 (defun org-narrow-to-element ()
22786 "Narrow buffer to current element."
22787 (interactive)
22788 (let ((elem (org-element-at-point)))
22789 (cond
22790 ((eq (car elem) 'headline)
22791 (narrow-to-region
22792 (org-element-property :begin elem)
22793 (org-element-property :end elem)))
22794 ((memq (car elem) org-element-greater-elements)
22795 (narrow-to-region
22796 (org-element-property :contents-begin elem)
22797 (org-element-property :contents-end elem)))
22799 (narrow-to-region
22800 (org-element-property :begin elem)
22801 (org-element-property :end elem))))))
22803 (defun org-transpose-words ()
22804 "Transpose words, using `org-mode' syntax table."
22805 (interactive)
22806 (with-syntax-table org-syntax-table
22807 (call-interactively 'transpose-words)))
22808 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22810 (defun org-transpose-element ()
22811 "Transpose current and previous elements, keeping blank lines between.
22812 Point is moved after both elements."
22813 (interactive)
22814 (org-skip-whitespace)
22815 (let ((end (org-element-property :end (org-element-at-point))))
22816 (org-drag-element-backward)
22817 (goto-char end)))
22819 (defun org-unindent-buffer ()
22820 "Un-indent the visible part of the buffer.
22821 Relative indentation (between items, inside blocks, etc.) isn't
22822 modified."
22823 (interactive)
22824 (unless (eq major-mode 'org-mode)
22825 (error "Cannot un-indent a buffer not in Org mode"))
22826 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22827 unindent-tree ; For byte-compiler.
22828 (unindent-tree
22829 (function
22830 (lambda (contents)
22831 (mapc
22832 (lambda (element)
22833 (if (memq (org-element-type element) '(headline section))
22834 (funcall unindent-tree (org-element-contents element))
22835 (save-excursion
22836 (save-restriction
22837 (narrow-to-region
22838 (org-element-property :begin element)
22839 (org-element-property :end element))
22840 (org-do-remove-indentation)))))
22841 (reverse contents))))))
22842 (funcall unindent-tree (org-element-contents parse-tree))))
22844 (defun org-show-subtree ()
22845 "Show everything after this heading at deeper levels."
22846 (interactive)
22847 (outline-flag-region
22848 (point)
22849 (save-excursion
22850 (org-end-of-subtree t t))
22851 nil))
22853 (defun org-show-entry ()
22854 "Show the body directly following this heading.
22855 Show the heading too, if it is currently invisible."
22856 (interactive)
22857 (save-excursion
22858 (condition-case nil
22859 (progn
22860 (org-back-to-heading t)
22861 (outline-flag-region
22862 (max (point-min) (1- (point)))
22863 (save-excursion
22864 (if (re-search-forward
22865 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22866 (match-beginning 1)
22867 (point-max)))
22868 nil)
22869 (org-cycle-hide-drawers 'children))
22870 (error nil))))
22872 (defun org-make-options-regexp (kwds &optional extra)
22873 "Make a regular expression for keyword lines."
22874 (concat
22875 "^#\\+\\("
22876 (mapconcat 'regexp-quote kwds "\\|")
22877 (if extra (concat "\\|" extra))
22878 "\\):[ \t]*\\(.*\\)"))
22880 ;; Make isearch reveal the necessary context
22881 (defun org-isearch-end ()
22882 "Reveal context after isearch exits."
22883 (when isearch-success ; only if search was successful
22884 (if (featurep 'xemacs)
22885 ;; Under XEmacs, the hook is run in the correct place,
22886 ;; we directly show the context.
22887 (org-show-context 'isearch)
22888 ;; In Emacs the hook runs *before* restoring the overlays.
22889 ;; So we have to use a one-time post-command-hook to do this.
22890 ;; (Emacs 22 has a special variable, see function `org-mode')
22891 (unless (and (boundp 'isearch-mode-end-hook-quit)
22892 isearch-mode-end-hook-quit)
22893 ;; Only when the isearch was not quitted.
22894 (org-add-hook 'post-command-hook 'org-isearch-post-command
22895 'append 'local)))))
22897 (defun org-isearch-post-command ()
22898 "Remove self from hook, and show context."
22899 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22900 (org-show-context 'isearch))
22903 ;;;; Integration with and fixes for other packages
22905 ;;; Imenu support
22907 (defvar org-imenu-markers nil
22908 "All markers currently used by Imenu.")
22909 (make-variable-buffer-local 'org-imenu-markers)
22911 (defun org-imenu-new-marker (&optional pos)
22912 "Return a new marker for use by Imenu, and remember the marker."
22913 (let ((m (make-marker)))
22914 (move-marker m (or pos (point)))
22915 (push m org-imenu-markers)
22918 (defun org-imenu-get-tree ()
22919 "Produce the index for Imenu."
22920 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22921 (setq org-imenu-markers nil)
22922 (let* ((n org-imenu-depth)
22923 (re (concat "^" (org-get-limited-outline-regexp)))
22924 (subs (make-vector (1+ n) nil))
22925 (last-level 0)
22926 m level head)
22927 (save-excursion
22928 (save-restriction
22929 (widen)
22930 (goto-char (point-max))
22931 (while (re-search-backward re nil t)
22932 (setq level (org-reduced-level (funcall outline-level)))
22933 (when (and (<= level n)
22934 (looking-at org-complex-heading-regexp))
22935 (setq head (org-link-display-format
22936 (org-match-string-no-properties 4))
22937 m (org-imenu-new-marker))
22938 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22939 (if (>= level last-level)
22940 (push (cons head m) (aref subs level))
22941 (push (cons head (aref subs (1+ level))) (aref subs level))
22942 (loop for i from (1+ level) to n do (aset subs i nil)))
22943 (setq last-level level)))))
22944 (aref subs 1)))
22946 (eval-after-load "imenu"
22947 '(progn
22948 (add-hook 'imenu-after-jump-hook
22949 (lambda ()
22950 (if (derived-mode-p 'org-mode)
22951 (org-show-context 'org-goto))))))
22953 (defun org-link-display-format (link)
22954 "Replace a link with either the description, or the link target
22955 if no description is present"
22956 (save-match-data
22957 (if (string-match org-bracket-link-analytic-regexp link)
22958 (replace-match (if (match-end 5)
22959 (match-string 5 link)
22960 (concat (match-string 1 link)
22961 (match-string 3 link)))
22962 nil t link)
22963 link)))
22965 (defun org-toggle-link-display ()
22966 "Toggle the literal or descriptive display of links."
22967 (interactive)
22968 (if org-descriptive-links
22969 (progn (org-remove-from-invisibility-spec '(org-link))
22970 (org-restart-font-lock)
22971 (setq org-descriptive-links nil))
22972 (progn (add-to-invisibility-spec '(org-link))
22973 (org-restart-font-lock)
22974 (setq org-descriptive-links t))))
22976 ;; Speedbar support
22978 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22979 "Overlay marking the agenda restriction line in speedbar.")
22980 (overlay-put org-speedbar-restriction-lock-overlay
22981 'face 'org-agenda-restriction-lock)
22982 (overlay-put org-speedbar-restriction-lock-overlay
22983 'help-echo "Agendas are currently limited to this item.")
22984 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22986 (defun org-speedbar-set-agenda-restriction ()
22987 "Restrict future agenda commands to the location at point in speedbar.
22988 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22989 (interactive)
22990 (require 'org-agenda)
22991 (let (p m tp np dir txt)
22992 (cond
22993 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22994 'org-imenu t))
22995 (setq m (get-text-property p 'org-imenu-marker))
22996 (with-current-buffer (marker-buffer m)
22997 (goto-char m)
22998 (org-agenda-set-restriction-lock 'subtree)))
22999 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23000 'speedbar-function 'speedbar-find-file))
23001 (setq tp (previous-single-property-change
23002 (1+ p) 'speedbar-function)
23003 np (next-single-property-change
23004 tp 'speedbar-function)
23005 dir (speedbar-line-directory)
23006 txt (buffer-substring-no-properties (or tp (point-min))
23007 (or np (point-max))))
23008 (with-current-buffer (find-file-noselect
23009 (let ((default-directory dir))
23010 (expand-file-name txt)))
23011 (unless (derived-mode-p 'org-mode)
23012 (error "Cannot restrict to non-Org-mode file"))
23013 (org-agenda-set-restriction-lock 'file)))
23014 (t (error "Don't know how to restrict Org-mode's agenda")))
23015 (move-overlay org-speedbar-restriction-lock-overlay
23016 (point-at-bol) (point-at-eol))
23017 (setq current-prefix-arg nil)
23018 (org-agenda-maybe-redo)))
23020 (eval-after-load "speedbar"
23021 '(progn
23022 (speedbar-add-supported-extension ".org")
23023 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23024 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23025 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23026 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23027 (add-hook 'speedbar-visiting-tag-hook
23028 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23030 ;;; Fixes and Hacks for problems with other packages
23032 ;; Make flyspell not check words in links, to not mess up our keymap
23033 (defun org-mode-flyspell-verify ()
23034 "Don't let flyspell put overlays at active buttons, or on
23035 {todo,all-time,additional-option-like}-keywords."
23036 (let ((pos (max (1- (point)) (point-min)))
23037 (word (thing-at-point 'word)))
23038 (and (not (get-text-property pos 'keymap))
23039 (not (get-text-property pos 'org-no-flyspell))
23040 (not (member word org-todo-keywords-1))
23041 (not (member word org-all-time-keywords))
23042 (not (member word org-options-keywords))
23043 (not (member word (mapcar 'car org-startup-options)))
23044 (not (member word org-additional-option-like-keywords-for-flyspell)))))
23046 (defun org-remove-flyspell-overlays-in (beg end)
23047 "Remove flyspell overlays in region."
23048 (and (org-bound-and-true-p flyspell-mode)
23049 (fboundp 'flyspell-delete-region-overlays)
23050 (flyspell-delete-region-overlays beg end))
23051 (add-text-properties beg end '(org-no-flyspell t)))
23053 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23054 (eval-after-load "bookmark"
23055 '(if (boundp 'bookmark-after-jump-hook)
23056 ;; We can use the hook
23057 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23058 ;; Hook not available, use advice
23059 (defadvice bookmark-jump (after org-make-visible activate)
23060 "Make the position visible."
23061 (org-bookmark-jump-unhide))))
23063 ;; Make sure saveplace shows the location if it was hidden
23064 (eval-after-load "saveplace"
23065 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23066 "Make the position visible."
23067 (org-bookmark-jump-unhide)))
23069 ;; Make sure ecb shows the location if it was hidden
23070 (eval-after-load "ecb"
23071 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23072 "Make hierarchy visible when jumping into location from ECB tree buffer."
23073 (if (derived-mode-p 'org-mode)
23074 (org-show-context))))
23076 (defun org-bookmark-jump-unhide ()
23077 "Unhide the current position, to show the bookmark location."
23078 (and (derived-mode-p 'org-mode)
23079 (or (outline-invisible-p)
23080 (save-excursion (goto-char (max (point-min) (1- (point))))
23081 (outline-invisible-p)))
23082 (org-show-context 'bookmark-jump)))
23084 ;; Make session.el ignore our circular variable
23085 (eval-after-load "session"
23086 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23088 ;;;; Experimental code
23090 (defun org-closed-in-range ()
23091 "Sparse tree of items closed in a certain time range.
23092 Still experimental, may disappear in the future."
23093 (interactive)
23094 ;; Get the time interval from the user.
23095 (let* ((time1 (org-float-time
23096 (org-read-date nil 'to-time nil "Starting date: ")))
23097 (time2 (org-float-time
23098 (org-read-date nil 'to-time nil "End date:")))
23099 ;; callback function
23100 (callback (lambda ()
23101 (let ((time
23102 (org-float-time
23103 (apply 'encode-time
23104 (org-parse-time-string
23105 (match-string 1))))))
23106 ;; check if time in interval
23107 (and (>= time time1) (<= time time2))))))
23108 ;; make tree, check each match with the callback
23109 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23111 ;;;; Finish up
23113 (provide 'org)
23115 (run-hooks 'org-load-hook)
23117 ;;; org.el ends here