org-export: Fix smart quotes with isolated quotes
[org-mode.git] / lisp / org.el
blob63c4323803b1c31b63823f342d349150cd495ced
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (let ((load-suffixes (list ".el")))
82 (load "org-loaddefs" 'noerror nil nil 'mustsuffix))
84 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
85 ;; some places -- e.g. see the macro org-with-limited-levels.
87 ;; In Org buffers, the value of `outline-regexp' is that of
88 ;; `org-outline-regexp'. The only function still directly relying on
89 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
90 ;; job when `orgstruct-mode' is active.
91 (defvar org-outline-regexp "\\*+ "
92 "Regexp to match Org headlines.")
94 (defvar org-outline-regexp-bol "^\\*+ "
95 "Regexp to match Org headlines.
96 This is similar to `org-outline-regexp' but additionally makes
97 sure that we are at the beginning of the line.")
99 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
100 "Matches an headline, putting stars and text into groups.
101 Stars are put in group 1 and the trimmed body in group 2.")
103 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
104 (when (fboundp 'defvaralias)
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-at-clock-log-p "org-clock" ())
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" ())
121 (declare-function org-clock-timestamps-down "org-clock" ())
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "org-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (autoload 'org-element-at-point "org-element")
139 (autoload 'org-element-type "org-element")
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-type "org-element" (element))
143 (declare-function org-element-context "org-element" ())
144 (declare-function org-element-contents "org-element" (element))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
150 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
152 ;; load languages based on value of `org-babel-load-languages'
153 (defvar org-babel-load-languages)
155 ;;;###autoload
156 (defun org-babel-do-load-languages (sym value)
157 "Load the languages defined in `org-babel-load-languages'."
158 (set-default sym value)
159 (mapc (lambda (pair)
160 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
161 (if active
162 (progn
163 (require (intern (concat "ob-" lang))))
164 (progn
165 (funcall 'fmakunbound
166 (intern (concat "org-babel-execute:" lang)))
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-expand-body:" lang)))))))
169 org-babel-load-languages))
171 (defcustom org-babel-load-languages '((emacs-lisp . t))
172 "Languages which can be evaluated in Org-mode buffers.
173 This list can be used to load support for any of the languages
174 below, note that each language will depend on a different set of
175 system executables and/or Emacs modes. When a language is
176 \"loaded\", then code blocks in that language can be evaluated
177 with `org-babel-execute-src-block' bound by default to C-c
178 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
179 be set to remove code block evaluation from the C-c C-c
180 keybinding. By default only Emacs Lisp (which has no
181 requirements) is loaded."
182 :group 'org-babel
183 :set 'org-babel-do-load-languages
184 :version "24.1"
185 :type '(alist :tag "Babel Languages"
186 :key-type
187 (choice
188 (const :tag "Awk" awk)
189 (const :tag "C" C)
190 (const :tag "R" R)
191 (const :tag "Asymptote" asymptote)
192 (const :tag "Calc" calc)
193 (const :tag "Clojure" clojure)
194 (const :tag "CSS" css)
195 (const :tag "Ditaa" ditaa)
196 (const :tag "Dot" dot)
197 (const :tag "Emacs Lisp" emacs-lisp)
198 (const :tag "Fortran" fortran)
199 (const :tag "Gnuplot" gnuplot)
200 (const :tag "Haskell" haskell)
201 (const :tag "IO" io)
202 (const :tag "Java" java)
203 (const :tag "Javascript" js)
204 (const :tag "LaTeX" latex)
205 (const :tag "Ledger" ledger)
206 (const :tag "Lilypond" lilypond)
207 (const :tag "Lisp" lisp)
208 (const :tag "Makefile" makefile)
209 (const :tag "Maxima" maxima)
210 (const :tag "Matlab" matlab)
211 (const :tag "Mscgen" mscgen)
212 (const :tag "Ocaml" ocaml)
213 (const :tag "Octave" octave)
214 (const :tag "Org" org)
215 (const :tag "Perl" perl)
216 (const :tag "Pico Lisp" picolisp)
217 (const :tag "PlantUML" plantuml)
218 (const :tag "Python" python)
219 (const :tag "Ruby" ruby)
220 (const :tag "Sass" sass)
221 (const :tag "Scala" scala)
222 (const :tag "Scheme" scheme)
223 (const :tag "Screen" screen)
224 (const :tag "Shell Script" sh)
225 (const :tag "Shen" shen)
226 (const :tag "Sql" sql)
227 (const :tag "Sqlite" sqlite))
228 :value-type (boolean :tag "Activate" :value t)))
230 ;;;; Customization variables
231 (defcustom org-clone-delete-id nil
232 "Remove ID property of clones of a subtree.
233 When non-nil, clones of a subtree don't inherit the ID property.
234 Otherwise they inherit the ID property with a new unique
235 identifier."
236 :type 'boolean
237 :version "24.1"
238 :group 'org-id)
240 ;;; Version
241 (require 'org-compat)
242 (org-check-version)
244 ;;;###autoload
245 (defun org-version (&optional here full message)
246 "Show the org-mode version in the echo area.
247 With prefix argument HERE, insert it at point.
248 When FULL is non-nil, use a verbose version string.
249 When MESSAGE is non-nil, display a message with the version."
250 (interactive "P")
251 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
252 (save-load-suffixes load-suffixes)
253 (load-suffixes (list ".el"))
254 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
255 (org-trash (or
256 (and (fboundp 'org-release) (fboundp 'org-git-version))
257 (load (concat org-dir "org-version")
258 'noerror 'nomessage nil 'mustsuffix)))
259 (load-suffixes save-load-suffixes)
260 (org-version (org-release))
261 (git-version (org-git-version))
262 (version (format "Org-mode version %s (%s @ %s)"
263 org-version
264 git-version
265 (if org-install-dir
266 (if (string= org-dir org-install-dir)
267 org-install-dir
268 (concat "mixed installation! " org-install-dir " and " org-dir))
269 "org-loaddefs.el can not be found!")))
270 (_version (if full version org-version)))
271 (if (org-called-interactively-p 'interactive)
272 (if here
273 (insert version)
274 (message version))
275 (if message (message _version))
276 _version)))
278 (defconst org-version (org-version))
280 ;;; Compatibility constants
282 ;;; The custom variables
284 (defgroup org nil
285 "Outline-based notes management and organizer."
286 :tag "Org"
287 :group 'outlines
288 :group 'calendar)
290 (defcustom org-mode-hook nil
291 "Mode hook for Org-mode, run after the mode was turned on."
292 :group 'org
293 :type 'hook)
295 (defcustom org-load-hook nil
296 "Hook that is run after org.el has been loaded."
297 :group 'org
298 :type 'hook)
300 (defcustom org-log-buffer-setup-hook nil
301 "Hook that is run after an Org log buffer is created."
302 :group 'org
303 :version "24.1"
304 :type 'hook)
306 (defvar org-modules) ; defined below
307 (defvar org-modules-loaded nil
308 "Have the modules been loaded already?")
310 (defun org-load-modules-maybe (&optional force)
311 "Load all extensions listed in `org-modules'."
312 (when (or force (not org-modules-loaded))
313 (mapc (lambda (ext)
314 (condition-case nil (require ext)
315 (error (message "Problems while trying to load feature `%s'" ext))))
316 org-modules)
317 (setq org-modules-loaded t)))
319 (defun org-set-modules (var value)
320 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
321 (set var value)
322 (when (featurep 'org)
323 (org-load-modules-maybe 'force)))
325 (when (org-bound-and-true-p org-modules)
326 (let ((a (member 'org-infojs org-modules)))
327 (and a (setcar a 'org-jsinfo))))
329 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
330 "Modules that should always be loaded together with org.el.
331 If a description starts with <C>, the file is not part of Emacs
332 and loading it will require that you have downloaded and properly installed
333 the org-mode distribution.
335 You can also use this system to load external packages (i.e. neither Org
336 core modules, nor modules from the CONTRIB directory). Just add symbols
337 to the end of the list. If the package is called org-xyz.el, then you need
338 to add the symbol `xyz', and the package must have a call to
340 (provide 'org-xyz)"
341 :group 'org
342 :set 'org-set-modules
343 :type
344 '(set :greedy t
345 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
346 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
347 (const :tag " crypt: Encryption of subtrees" org-crypt)
348 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
349 (const :tag " docview: Links to doc-view buffers" org-docview)
350 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
351 (const :tag " id: Global IDs for identifying entries" org-id)
352 (const :tag " info: Links to Info nodes" org-info)
353 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
354 (const :tag " habit: Track your consistency with habits" org-habit)
355 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
356 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
357 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
358 (const :tag " mew Links to Mew folders/messages" org-mew)
359 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
360 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
361 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
362 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
363 (const :tag " vm: Links to VM folders/messages" org-vm)
364 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
365 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
366 (const :tag " mouse: Additional mouse support" org-mouse)
367 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
369 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
370 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
371 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
372 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
373 (const :tag "C collector: Collect properties into tables" org-collector)
374 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
375 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
376 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
377 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
378 (const :tag "C eval: Include command output as text" org-eval)
379 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
380 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
381 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
382 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
383 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
385 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
387 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
388 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
389 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
390 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
391 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
392 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
393 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
394 (const :tag "C mtags: Support for muse-like tags" org-mtags)
395 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
396 (const :tag "C registry: A registry for Org-mode links" org-registry)
397 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
398 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
399 (const :tag "C secretary: Team management with org-mode" org-secretary)
400 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
401 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
402 (const :tag "C track: Keep up with Org-mode development" org-track)
403 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
404 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
405 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
407 (defcustom org-support-shift-select nil
408 "Non-nil means make shift-cursor commands select text when possible.
410 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
411 start selecting a region, or enlarge regions started in this way.
412 In Org-mode, in special contexts, these same keys are used for
413 other purposes, important enough to compete with shift selection.
414 Org tries to balance these needs by supporting `shift-select-mode'
415 outside these special contexts, under control of this variable.
417 The default of this variable is nil, to avoid confusing behavior. Shifted
418 cursor keys will then execute Org commands in the following contexts:
419 - on a headline, changing TODO state (left/right) and priority (up/down)
420 - on a time stamp, changing the time
421 - in a plain list item, changing the bullet type
422 - in a property definition line, switching between allowed values
423 - in the BEGIN line of a clock table (changing the time block).
424 Outside these contexts, the commands will throw an error.
426 When this variable is t and the cursor is not in a special
427 context, Org-mode will support shift-selection for making and
428 enlarging regions. To make this more effective, the bullet
429 cycling will no longer happen anywhere in an item line, but only
430 if the cursor is exactly on the bullet.
432 If you set this variable to the symbol `always', then the keys
433 will not be special in headlines, property lines, and item lines,
434 to make shift selection work there as well. If this is what you
435 want, you can use the following alternative commands: `C-c C-t'
436 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
437 can be used to switch TODO sets, `C-c -' to cycle item bullet
438 types, and properties can be edited by hand or in column view.
440 However, when the cursor is on a timestamp, shift-cursor commands
441 will still edit the time stamp - this is just too good to give up.
443 XEmacs user should have this variable set to nil, because
444 `shift-select-mode' is in Emacs 23 or later only."
445 :group 'org
446 :type '(choice
447 (const :tag "Never" nil)
448 (const :tag "When outside special context" t)
449 (const :tag "Everywhere except timestamps" always)))
451 (defcustom org-loop-over-headlines-in-active-region nil
452 "Shall some commands act upon headlines in the active region?
454 When set to `t', some commands will be performed in all headlines
455 within the active region.
457 When set to `start-level', some commands will be performed in all
458 headlines within the active region, provided that these headlines
459 are of the same level than the first one.
461 When set to a string, those commands will be performed on the
462 matching headlines within the active region. Such string must be
463 a tags/property/todo match as it is used in the agenda tags view.
465 The list of commands is: `org-schedule', `org-deadline',
466 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
467 `org-archive-to-archive-sibling'. The archiving commands skip
468 already archived entries."
469 :type '(choice (const :tag "Don't loop" nil)
470 (const :tag "All headlines in active region" t)
471 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
472 (string :tag "Tags/Property/Todo matcher"))
473 :version "24.1"
474 :group 'org-todo
475 :group 'org-archive)
477 (defgroup org-startup nil
478 "Options concerning startup of Org-mode."
479 :tag "Org Startup"
480 :group 'org)
482 (defcustom org-startup-folded t
483 "Non-nil means entering Org-mode will switch to OVERVIEW.
484 This can also be configured on a per-file basis by adding one of
485 the following lines anywhere in the buffer:
487 #+STARTUP: fold (or `overview', this is equivalent)
488 #+STARTUP: nofold (or `showall', this is equivalent)
489 #+STARTUP: content
490 #+STARTUP: showeverything"
491 :group 'org-startup
492 :type '(choice
493 (const :tag "nofold: show all" nil)
494 (const :tag "fold: overview" t)
495 (const :tag "content: all headlines" content)
496 (const :tag "show everything, even drawers" showeverything)))
498 (defcustom org-startup-truncated t
499 "Non-nil means entering Org-mode will set `truncate-lines'.
500 This is useful since some lines containing links can be very long and
501 uninteresting. Also tables look terrible when wrapped."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-startup-indented nil
506 "Non-nil means turn on `org-indent-mode' on startup.
507 This can also be configured on a per-file basis by adding one of
508 the following lines anywhere in the buffer:
510 #+STARTUP: indent
511 #+STARTUP: noindent"
512 :group 'org-structure
513 :type '(choice
514 (const :tag "Not" nil)
515 (const :tag "Globally (slow on startup in large files)" t)))
517 (defcustom org-use-sub-superscripts t
518 "Non-nil means interpret \"_\" and \"^\" for export.
519 When this option is turned on, you can use TeX-like syntax for sub- and
520 superscripts. Several characters after \"_\" or \"^\" will be
521 considered as a single item - so grouping with {} is normally not
522 needed. For example, the following things will be parsed as single
523 sub- or superscripts.
525 10^24 or 10^tau several digits will be considered 1 item.
526 10^-12 or 10^-tau a leading sign with digits or a word
527 x^2-y^3 will be read as x^2 - y^3, because items are
528 terminated by almost any nonword/nondigit char.
529 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
531 Still, ambiguity is possible - so when in doubt use {} to enclose the
532 sub/superscript. If you set this variable to the symbol `{}',
533 the braces are *required* in order to trigger interpretations as
534 sub/superscript. This can be helpful in documents that need \"_\"
535 frequently in plain text.
537 Not all export backends support this, but HTML does.
539 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
540 :group 'org-startup
541 :group 'org-export-translation
542 :version "24.1"
543 :type '(choice
544 (const :tag "Always interpret" t)
545 (const :tag "Only with braces" {})
546 (const :tag "Never interpret" nil)))
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
552 (defcustom org-startup-with-beamer-mode nil
553 "Non-nil means turn on `org-beamer-mode' on startup.
554 This can also be configured on a per-file basis by adding one of
555 the following lines anywhere in the buffer:
557 #+STARTUP: beamer"
558 :group 'org-startup
559 :version "24.1"
560 :type 'boolean)
562 (defcustom org-startup-align-all-tables nil
563 "Non-nil means align all tables when visiting a file.
564 This is useful when the column width in tables is forced with <N> cookies
565 in table fields. Such tables will look correct only after the first re-align.
566 This can also be configured on a per-file basis by adding one of
567 the following lines anywhere in the buffer:
568 #+STARTUP: align
569 #+STARTUP: noalign"
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-startup-with-inline-images nil
574 "Non-nil means show inline images when loading a new Org file.
575 This can also be configured on a per-file basis by adding one of
576 the following lines anywhere in the buffer:
577 #+STARTUP: inlineimages
578 #+STARTUP: noinlineimages"
579 :group 'org-startup
580 :version "24.1"
581 :type 'boolean)
583 (defcustom org-insert-mode-line-in-empty-file nil
584 "Non-nil means insert the first line setting Org-mode in empty files.
585 When the function `org-mode' is called interactively in an empty file, this
586 normally means that the file name does not automatically trigger Org-mode.
587 To ensure that the file will always be in Org-mode in the future, a
588 line enforcing Org-mode will be inserted into the buffer, if this option
589 has been set."
590 :group 'org-startup
591 :type 'boolean)
593 (defcustom org-replace-disputed-keys nil
594 "Non-nil means use alternative key bindings for some keys.
595 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
596 These keys are also used by other packages like shift-selection-mode'
597 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
598 If you want to use Org-mode together with one of these other modes,
599 or more generally if you would like to move some Org-mode commands to
600 other keys, set this variable and configure the keys with the variable
601 `org-disputed-keys'.
603 This option is only relevant at load-time of Org-mode, and must be set
604 *before* org.el is loaded. Changing it requires a restart of Emacs to
605 become effective."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-use-extra-keys nil
610 "Non-nil means use extra key sequence definitions for certain commands.
611 This happens automatically if you run XEmacs or if `window-system'
612 is nil. This variable lets you do the same manually. You must
613 set it before loading org.
615 Example: on Carbon Emacs 22 running graphically, with an external
616 keyboard on a Powerbook, the default way of setting M-left might
617 not work for either Alt or ESC. Setting this variable will make
618 it work for ESC."
619 :group 'org-startup
620 :type 'boolean)
622 (if (fboundp 'defvaralias)
623 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
625 (defcustom org-disputed-keys
626 '(([(shift up)] . [(meta p)])
627 ([(shift down)] . [(meta n)])
628 ([(shift left)] . [(meta -)])
629 ([(shift right)] . [(meta +)])
630 ([(control shift right)] . [(meta shift +)])
631 ([(control shift left)] . [(meta shift -)]))
632 "Keys for which Org-mode and other modes compete.
633 This is an alist, cars are the default keys, second element specifies
634 the alternative to use when `org-replace-disputed-keys' is t.
636 Keys can be specified in any syntax supported by `define-key'.
637 The value of this option takes effect only at Org-mode's startup,
638 therefore you'll have to restart Emacs to apply it after changing."
639 :group 'org-startup
640 :type 'alist)
642 (defun org-key (key)
643 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
644 Or return the original if not disputed.
645 Also apply the translations defined in `org-xemacs-key-equivalents'."
646 (when org-replace-disputed-keys
647 (let* ((nkey (key-description key))
648 (x (org-find-if (lambda (x)
649 (equal (key-description (car x)) nkey))
650 org-disputed-keys)))
651 (setq key (if x (cdr x) key))))
652 (when (featurep 'xemacs)
653 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
654 key)
656 (defun org-find-if (predicate seq)
657 (catch 'exit
658 (while seq
659 (if (funcall predicate (car seq))
660 (throw 'exit (car seq))
661 (pop seq)))))
663 (defun org-defkey (keymap key def)
664 "Define a key, possibly translated, as returned by `org-key'."
665 (define-key keymap (org-key key) def))
667 (defcustom org-ellipsis nil
668 "The ellipsis to use in the Org-mode outline.
669 When nil, just use the standard three dots. When a string, use that instead,
670 When a face, use the standard 3 dots, but with the specified face.
671 The change affects only Org-mode (which will then use its own display table).
672 Changing this requires executing `M-x org-mode' in a buffer to become
673 effective."
674 :group 'org-startup
675 :type '(choice (const :tag "Default" nil)
676 (face :tag "Face" :value org-warning)
677 (string :tag "String" :value "...#")))
679 (defvar org-display-table nil
680 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
682 (defgroup org-keywords nil
683 "Keywords in Org-mode."
684 :tag "Org Keywords"
685 :group 'org)
687 (defcustom org-deadline-string "DEADLINE:"
688 "String to mark deadline entries.
689 A deadline is this string, followed by a time stamp. Should be a word,
690 terminated by a colon. You can insert a schedule keyword and
691 a timestamp with \\[org-deadline].
692 Changes become only effective after restarting Emacs."
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-scheduled-string "SCHEDULED:"
697 "String to mark scheduled TODO entries.
698 A schedule is this string, followed by a time stamp. Should be a word,
699 terminated by a colon. You can insert a schedule keyword and
700 a timestamp with \\[org-schedule].
701 Changes become only effective after restarting Emacs."
702 :group 'org-keywords
703 :type 'string)
705 (defcustom org-closed-string "CLOSED:"
706 "String used as the prefix for timestamps logging closing a TODO entry."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-clock-string "CLOCK:"
711 "String used as prefix for timestamps clocking work hours on an item."
712 :group 'org-keywords
713 :type 'string)
715 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
716 org-scheduled-string "\\|"
717 org-deadline-string "\\|"
718 org-closed-string "\\|"
719 org-clock-string "\\)")
720 "Matches a line with planning or clock info.")
722 (defcustom org-comment-string "COMMENT"
723 "Entries starting with this keyword will never be exported.
724 An entry can be toggled between COMMENT and normal with
725 \\[org-toggle-comment].
726 Changes become only effective after restarting Emacs."
727 :group 'org-keywords
728 :type 'string)
730 (defcustom org-quote-string "QUOTE"
731 "Entries starting with this keyword will be exported in fixed-width font.
732 Quoting applies only to the text in the entry following the headline, and does
733 not extend beyond the next headline, even if that is lower level.
734 An entry can be toggled between QUOTE and normal with
735 \\[org-toggle-fixed-width-section]."
736 :group 'org-keywords
737 :type 'string)
739 (defconst org-repeat-re
740 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
741 "Regular expression for specifying repeated events.
742 After a match, group 1 contains the repeat expression.")
744 (defgroup org-structure nil
745 "Options concerning the general structure of Org-mode files."
746 :tag "Org Structure"
747 :group 'org)
749 (defgroup org-reveal-location nil
750 "Options about how to make context of a location visible."
751 :tag "Org Reveal Location"
752 :group 'org-structure)
754 (defconst org-context-choice
755 '(choice
756 (const :tag "Always" t)
757 (const :tag "Never" nil)
758 (repeat :greedy t :tag "Individual contexts"
759 (cons
760 (choice :tag "Context"
761 (const agenda)
762 (const org-goto)
763 (const occur-tree)
764 (const tags-tree)
765 (const link-search)
766 (const mark-goto)
767 (const bookmark-jump)
768 (const isearch)
769 (const default))
770 (boolean))))
771 "Contexts for the reveal options.")
773 (defcustom org-show-hierarchy-above '((default . t))
774 "Non-nil means show full hierarchy when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the hierarchy of headings
777 above the exposed location is shown.
778 Turning this off for example for sparse trees makes them very compact.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. Valid contexts are
781 agenda when exposing an entry from the agenda
782 org-goto when using the command `org-goto' on key C-c C-j
783 occur-tree when using the command `org-occur' on key C-c /
784 tags-tree when constructing a sparse tree based on tags matches
785 link-search when exposing search matches associated with a link
786 mark-goto when exposing the jump goal of a mark
787 bookmark-jump when exposing a bookmark location
788 isearch when exiting from an incremental search
789 default default for all contexts not set explicitly"
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-show-following-heading '((default . nil))
794 "Non-nil means show following heading when revealing a location.
795 Org-mode often shows locations in an org-mode file which might have
796 been invisible before. When this is set, the heading following the
797 match is shown.
798 Turning this off for example for sparse trees makes them very compact,
799 but makes it harder to edit the location of the match. In such a case,
800 use the command \\[org-reveal] to show more context.
801 Instead of t, this can also be an alist specifying this option for different
802 contexts. See `org-show-hierarchy-above' for valid contexts."
803 :group 'org-reveal-location
804 :type org-context-choice)
806 (defcustom org-show-siblings '((default . nil) (isearch t))
807 "Non-nil means show all sibling heading when revealing a location.
808 Org-mode often shows locations in an org-mode file which might have
809 been invisible before. When this is set, the sibling of the current entry
810 heading are all made visible. If `org-show-hierarchy-above' is t,
811 the same happens on each level of the hierarchy above the current entry.
813 By default this is on for the isearch context, off for all other contexts.
814 Turning this off for example for sparse trees makes them very compact,
815 but makes it harder to edit the location of the match. In such a case,
816 use the command \\[org-reveal] to show more context.
817 Instead of t, this can also be an alist specifying this option for different
818 contexts. See `org-show-hierarchy-above' for valid contexts."
819 :group 'org-reveal-location
820 :type org-context-choice)
822 (defcustom org-show-entry-below '((default . nil))
823 "Non-nil means show the entry below a headline when revealing a location.
824 Org-mode often shows locations in an org-mode file which might have
825 been invisible before. When this is set, the text below the headline that is
826 exposed is also shown.
828 By default this is off for all contexts.
829 Instead of t, this can also be an alist specifying this option for different
830 contexts. See `org-show-hierarchy-above' for valid contexts."
831 :group 'org-reveal-location
832 :type org-context-choice)
834 (defcustom org-indirect-buffer-display 'other-window
835 "How should indirect tree buffers be displayed?
836 This applies to indirect buffers created with the commands
837 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
838 Valid values are:
839 current-window Display in the current window
840 other-window Just display in another window.
841 dedicated-frame Create one new frame, and re-use it each time.
842 new-frame Make a new frame each time. Note that in this case
843 previously-made indirect buffers are kept, and you need to
844 kill these buffers yourself."
845 :group 'org-structure
846 :group 'org-agenda-windows
847 :type '(choice
848 (const :tag "In current window" current-window)
849 (const :tag "In current frame, other window" other-window)
850 (const :tag "Each time a new frame" new-frame)
851 (const :tag "One dedicated frame" dedicated-frame)))
853 (defcustom org-use-speed-commands nil
854 "Non-nil means activate single letter commands at beginning of a headline.
855 This may also be a function to test for appropriate locations where speed
856 commands should be active."
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Never" nil)
860 (const :tag "At beginning of headline stars" t)
861 (function)))
863 (defcustom org-speed-commands-user nil
864 "Alist of additional speed commands.
865 This list will be checked before `org-speed-commands-default'
866 when the variable `org-use-speed-commands' is non-nil
867 and when the cursor is at the beginning of a headline.
868 The car if each entry is a string with a single letter, which must
869 be assigned to `self-insert-command' in the global map.
870 The cdr is either a command to be called interactively, a function
871 to be called, or a form to be evaluated.
872 An entry that is just a list with a single string will be interpreted
873 as a descriptive headline that will be added when listing the speed
874 commands in the Help buffer using the `?' speed command."
875 :group 'org-structure
876 :type '(repeat :value ("k" . ignore)
877 (choice :value ("k" . ignore)
878 (list :tag "Descriptive Headline" (string :tag "Headline"))
879 (cons :tag "Letter and Command"
880 (string :tag "Command letter")
881 (choice
882 (function)
883 (sexp))))))
885 (defgroup org-cycle nil
886 "Options concerning visibility cycling in Org-mode."
887 :tag "Org Cycle"
888 :group 'org-structure)
890 (defcustom org-cycle-skip-children-state-if-no-children t
891 "Non-nil means skip CHILDREN state in entries that don't have any."
892 :group 'org-cycle
893 :type 'boolean)
895 (defcustom org-cycle-max-level nil
896 "Maximum level which should still be subject to visibility cycling.
897 Levels higher than this will, for cycling, be treated as text, not a headline.
898 When `org-odd-levels-only' is set, a value of N in this variable actually
899 means 2N-1 stars as the limiting headline.
900 When nil, cycle all levels.
901 Note that the limiting level of cycling is also influenced by
902 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
903 `org-inlinetask-min-level' is, cycling will be limited to levels one less
904 than its value."
905 :group 'org-cycle
906 :type '(choice
907 (const :tag "No limit" nil)
908 (integer :tag "Maximum level")))
910 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
911 "Names of drawers. Drawers are not opened by cycling on the headline above.
912 Drawers only open with a TAB on the drawer line itself. A drawer looks like
913 this:
914 :DRAWERNAME:
915 .....
916 :END:
917 The drawer \"PROPERTIES\" is special for capturing properties through
918 the property API.
920 Drawers can be defined on the per-file basis with a line like:
922 #+DRAWERS: HIDDEN STATE PROPERTIES"
923 :group 'org-structure
924 :group 'org-cycle
925 :type '(repeat (string :tag "Drawer Name")))
927 (defcustom org-hide-block-startup nil
928 "Non-nil means entering Org-mode will fold all blocks.
929 This can also be set in on a per-file basis with
931 #+STARTUP: hideblocks
932 #+STARTUP: showblocks"
933 :group 'org-startup
934 :group 'org-cycle
935 :type 'boolean)
937 (defcustom org-cycle-global-at-bob nil
938 "Cycle globally if cursor is at beginning of buffer and not at a headline.
939 This makes it possible to do global cycling without having to use S-TAB or
940 \\[universal-argument] TAB. For this special case to work, the first line
941 of the buffer must not be a headline -- it may be empty or some other text.
942 When used in this way, `org-cycle-hook' is disabled temporarily to make
943 sure the cursor stays at the beginning of the buffer. When this option is
944 nil, don't do anything special at the beginning of the buffer."
945 :group 'org-cycle
946 :type 'boolean)
948 (defcustom org-cycle-level-after-item/entry-creation t
949 "Non-nil means cycle entry level or item indentation in new empty entries.
951 When the cursor is at the end of an empty headline, i.e with only stars
952 and maybe a TODO keyword, TAB will then switch the entry to become a child,
953 and then all possible ancestor states, before returning to the original state.
954 This makes data entry extremely fast: M-RET to create a new headline,
955 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
957 When the cursor is at the end of an empty plain list item, one TAB will
958 make it a subitem, two or more tabs will back up to make this an item
959 higher up in the item hierarchy."
960 :group 'org-cycle
961 :type 'boolean)
963 (defcustom org-cycle-emulate-tab t
964 "Where should `org-cycle' emulate TAB.
965 nil Never
966 white Only in completely white lines
967 whitestart Only at the beginning of lines, before the first non-white char
968 t Everywhere except in headlines
969 exc-hl-bol Everywhere except at the start of a headline
970 If TAB is used in a place where it does not emulate TAB, the current subtree
971 visibility is cycled."
972 :group 'org-cycle
973 :type '(choice (const :tag "Never" nil)
974 (const :tag "Only in completely white lines" white)
975 (const :tag "Before first char in a line" whitestart)
976 (const :tag "Everywhere except in headlines" t)
977 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
980 (defcustom org-cycle-separator-lines 2
981 "Number of empty lines needed to keep an empty line between collapsed trees.
982 If you leave an empty line between the end of a subtree and the following
983 headline, this empty line is hidden when the subtree is folded.
984 Org-mode will leave (exactly) one empty line visible if the number of
985 empty lines is equal or larger to the number given in this variable.
986 So the default 2 means at least 2 empty lines after the end of a subtree
987 are needed to produce free space between a collapsed subtree and the
988 following headline.
990 If the number is negative, and the number of empty lines is at least -N,
991 all empty lines are shown.
993 Special case: when 0, never leave empty lines in collapsed view."
994 :group 'org-cycle
995 :type 'integer)
996 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
998 (defcustom org-pre-cycle-hook nil
999 "Hook that is run before visibility cycling is happening.
1000 The function(s) in this hook must accept a single argument which indicates
1001 the new state that will be set right after running this hook. The
1002 argument is a symbol. Before a global state change, it can have the values
1003 `overview', `content', or `all'. Before a local state change, it can have
1004 the values `folded', `children', or `subtree'."
1005 :group 'org-cycle
1006 :type 'hook)
1008 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1009 org-cycle-hide-drawers
1010 org-cycle-hide-inline-tasks
1011 org-cycle-show-empty-lines
1012 org-optimize-window-after-visibility-change)
1013 "Hook that is run after `org-cycle' has changed the buffer visibility.
1014 The function(s) in this hook must accept a single argument which indicates
1015 the new state that was set by the most recent `org-cycle' command. The
1016 argument is a symbol. After a global state change, it can have the values
1017 `overview', `contents', or `all'. After a local state change, it can have
1018 the values `folded', `children', or `subtree'."
1019 :group 'org-cycle
1020 :type 'hook)
1022 (defgroup org-edit-structure nil
1023 "Options concerning structure editing in Org-mode."
1024 :tag "Org Edit Structure"
1025 :group 'org-structure)
1027 (defcustom org-odd-levels-only nil
1028 "Non-nil means skip even levels and only use odd levels for the outline.
1029 This has the effect that two stars are being added/taken away in
1030 promotion/demotion commands. It also influences how levels are
1031 handled by the exporters.
1032 Changing it requires restart of `font-lock-mode' to become effective
1033 for fontification also in regions already fontified.
1034 You may also set this on a per-file basis by adding one of the following
1035 lines to the buffer:
1037 #+STARTUP: odd
1038 #+STARTUP: oddeven"
1039 :group 'org-edit-structure
1040 :group 'org-appearance
1041 :type 'boolean)
1043 (defcustom org-adapt-indentation t
1044 "Non-nil means adapt indentation to outline node level.
1046 When this variable is set, Org assumes that you write outlines by
1047 indenting text in each node to align with the headline (after the stars).
1048 The following issues are influenced by this variable:
1050 - When this is set and the *entire* text in an entry is indented, the
1051 indentation is increased by one space in a demotion command, and
1052 decreased by one in a promotion command. If any line in the entry
1053 body starts with text at column 0, indentation is not changed at all.
1055 - Property drawers and planning information is inserted indented when
1056 this variable s set. When nil, they will not be indented.
1058 - TAB indents a line relative to context. The lines below a headline
1059 will be indented when this variable is set.
1061 Note that this is all about true indentation, by adding and removing
1062 space characters. See also `org-indent.el' which does level-dependent
1063 indentation in a virtual way, i.e. at display time in Emacs."
1064 :group 'org-edit-structure
1065 :type 'boolean)
1067 (defcustom org-special-ctrl-a/e nil
1068 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1070 When t, `C-a' will bring back the cursor to the beginning of the
1071 headline text, i.e. after the stars and after a possible TODO
1072 keyword. In an item, this will be the position after bullet and
1073 check-box, if any. When the cursor is already at that position,
1074 another `C-a' will bring it to the beginning of the line.
1076 `C-e' will jump to the end of the headline, ignoring the presence
1077 of tags in the headline. A second `C-e' will then jump to the
1078 true end of the line, after any tags. This also means that, when
1079 this variable is non-nil, `C-e' also will never jump beyond the
1080 end of the heading of a folded section, i.e. not after the
1081 ellipses.
1083 When set to the symbol `reversed', the first `C-a' or `C-e' works
1084 normally, going to the true line boundary first. Only a directly
1085 following, identical keypress will bring the cursor to the
1086 special positions.
1088 This may also be a cons cell where the behavior for `C-a' and
1089 `C-e' is set separately."
1090 :group 'org-edit-structure
1091 :type '(choice
1092 (const :tag "off" nil)
1093 (const :tag "on: after stars/bullet and before tags first" t)
1094 (const :tag "reversed: true line boundary first" reversed)
1095 (cons :tag "Set C-a and C-e separately"
1096 (choice :tag "Special C-a"
1097 (const :tag "off" nil)
1098 (const :tag "on: after stars/bullet first" t)
1099 (const :tag "reversed: before stars/bullet first" reversed))
1100 (choice :tag "Special C-e"
1101 (const :tag "off" nil)
1102 (const :tag "on: before tags first" t)
1103 (const :tag "reversed: after tags first" reversed)))))
1104 (if (fboundp 'defvaralias)
1105 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1107 (defcustom org-special-ctrl-k nil
1108 "Non-nil means `C-k' will behave specially in headlines.
1109 When nil, `C-k' will call the default `kill-line' command.
1110 When t, the following will happen while the cursor is in the headline:
1112 - When the cursor is at the beginning of a headline, kill the entire
1113 line and possible the folded subtree below the line.
1114 - When in the middle of the headline text, kill the headline up to the tags.
1115 - When after the headline text, kill the tags."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-ctrl-k-protect-subtree nil
1120 "Non-nil means, do not delete a hidden subtree with C-k.
1121 When set to the symbol `error', simply throw an error when C-k is
1122 used to kill (part-of) a headline that has hidden text behind it.
1123 Any other non-nil value will result in a query to the user, if it is
1124 OK to kill that hidden subtree. When nil, kill without remorse."
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not protect hidden subtrees" nil)
1129 (const :tag "Protect hidden subtrees with a security query" t)
1130 (const :tag "Never kill a hidden subtree with C-k" error)))
1132 (defcustom org-catch-invisible-edits nil
1133 "Check if in invisible region before inserting or deleting a character.
1134 Valid values are:
1136 nil Do not check, so just do invisible edits.
1137 error Throw an error and do nothing.
1138 show Make point visible, and do the requested edit.
1139 show-and-error Make point visible, then throw an error and abort the edit.
1140 smart Make point visible, and do insertion/deletion if it is
1141 adjacent to visible text and the change feels predictable.
1142 Never delete a previously invisible character or add in the
1143 middle or right after an invisible region. Basically, this
1144 allows insertion and backward-delete right before ellipses.
1145 FIXME: maybe in this case we should not even show?"
1146 :group 'org-edit-structure
1147 :version "24.1"
1148 :type '(choice
1149 (const :tag "Do not check" nil)
1150 (const :tag "Throw error when trying to edit" error)
1151 (const :tag "Unhide, but do not do the edit" show-and-error)
1152 (const :tag "Show invisible part and do the edit" show)
1153 (const :tag "Be smart and do the right thing" smart)))
1155 (defcustom org-yank-folded-subtrees t
1156 "Non-nil means when yanking subtrees, fold them.
1157 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1158 it starts with a heading and all other headings in it are either children
1159 or siblings, then fold all the subtrees. However, do this only if no
1160 text after the yank would be swallowed into a folded tree by this action."
1161 :group 'org-edit-structure
1162 :type 'boolean)
1164 (defcustom org-yank-adjusted-subtrees nil
1165 "Non-nil means when yanking subtrees, adjust the level.
1166 With this setting, `org-paste-subtree' is used to insert the subtree, see
1167 this function for details."
1168 :group 'org-edit-structure
1169 :type 'boolean)
1171 (defcustom org-M-RET-may-split-line '((default . t))
1172 "Non-nil means M-RET will split the line at the cursor position.
1173 When nil, it will go to the end of the line before making a
1174 new line.
1175 You may also set this option in a different way for different
1176 contexts. Valid contexts are:
1178 headline when creating a new headline
1179 item when creating a new item
1180 table in a table field
1181 default the value to be used for all contexts not explicitly
1182 customized"
1183 :group 'org-structure
1184 :group 'org-table
1185 :type '(choice
1186 (const :tag "Always" t)
1187 (const :tag "Never" nil)
1188 (repeat :greedy t :tag "Individual contexts"
1189 (cons
1190 (choice :tag "Context"
1191 (const headline)
1192 (const item)
1193 (const table)
1194 (const default))
1195 (boolean)))))
1198 (defcustom org-insert-heading-respect-content nil
1199 "Non-nil means insert new headings after the current subtree.
1200 When nil, the new heading is created directly after the current line.
1201 The commands \\[org-insert-heading-respect-content] and
1202 \\[org-insert-todo-heading-respect-content] turn this variable on
1203 for the duration of the command."
1204 :group 'org-structure
1205 :type 'boolean)
1207 (defcustom org-blank-before-new-entry '((heading . auto)
1208 (plain-list-item . auto))
1209 "Should `org-insert-heading' leave a blank line before new heading/item?
1210 The value is an alist, with `heading' and `plain-list-item' as CAR,
1211 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1212 which case Org will look at the surrounding headings/items and try to
1213 make an intelligent decision whether to insert a blank line or not.
1215 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1216 set, the setting here is ignored and no empty line is inserted, to avoid
1217 breaking the list structure."
1218 :group 'org-edit-structure
1219 :type '(list
1220 (cons (const heading)
1221 (choice (const :tag "Never" nil)
1222 (const :tag "Always" t)
1223 (const :tag "Auto" auto)))
1224 (cons (const plain-list-item)
1225 (choice (const :tag "Never" nil)
1226 (const :tag "Always" t)
1227 (const :tag "Auto" auto)))))
1229 (defcustom org-insert-heading-hook nil
1230 "Hook being run after inserting a new heading."
1231 :group 'org-edit-structure
1232 :type 'hook)
1234 (defcustom org-enable-fixed-width-editor t
1235 "Non-nil means lines starting with \":\" are treated as fixed-width.
1236 This currently only means they are never auto-wrapped.
1237 When nil, such lines will be treated like ordinary lines.
1238 See also the QUOTE keyword."
1239 :group 'org-edit-structure
1240 :type 'boolean)
1242 (defcustom org-goto-auto-isearch t
1243 "Non-nil means typing characters in `org-goto' starts incremental search."
1244 :group 'org-edit-structure
1245 :type 'boolean)
1247 (defgroup org-sparse-trees nil
1248 "Options concerning sparse trees in Org-mode."
1249 :tag "Org Sparse Trees"
1250 :group 'org-structure)
1252 (defcustom org-highlight-sparse-tree-matches t
1253 "Non-nil means highlight all matches that define a sparse tree.
1254 The highlights will automatically disappear the next time the buffer is
1255 changed by an edit command."
1256 :group 'org-sparse-trees
1257 :type 'boolean)
1259 (defcustom org-remove-highlights-with-change t
1260 "Non-nil means any change to the buffer will remove temporary highlights.
1261 Such highlights are created by `org-occur' and `org-clock-display'.
1262 When nil, `C-c C-c needs to be used to get rid of the highlights.
1263 The highlights created by `org-preview-latex-fragment' always need
1264 `C-c C-c' to be removed."
1265 :group 'org-sparse-trees
1266 :group 'org-time
1267 :type 'boolean)
1270 (defcustom org-occur-hook '(org-first-headline-recenter)
1271 "Hook that is run after `org-occur' has constructed a sparse tree.
1272 This can be used to recenter the window to show as much of the structure
1273 as possible."
1274 :group 'org-sparse-trees
1275 :type 'hook)
1277 (defgroup org-imenu-and-speedbar nil
1278 "Options concerning imenu and speedbar in Org-mode."
1279 :tag "Org Imenu and Speedbar"
1280 :group 'org-structure)
1282 (defcustom org-imenu-depth 2
1283 "The maximum level for Imenu access to Org-mode headlines.
1284 This also applied for speedbar access."
1285 :group 'org-imenu-and-speedbar
1286 :type 'integer)
1288 (defgroup org-table nil
1289 "Options concerning tables in Org-mode."
1290 :tag "Org Table"
1291 :group 'org)
1293 (defcustom org-enable-table-editor 'optimized
1294 "Non-nil means lines starting with \"|\" are handled by the table editor.
1295 When nil, such lines will be treated like ordinary lines.
1297 When equal to the symbol `optimized', the table editor will be optimized to
1298 do the following:
1299 - Automatic overwrite mode in front of whitespace in table fields.
1300 This makes the structure of the table stay in tact as long as the edited
1301 field does not exceed the column width.
1302 - Minimize the number of realigns. Normally, the table is aligned each time
1303 TAB or RET are pressed to move to another field. With optimization this
1304 happens only if changes to a field might have changed the column width.
1305 Optimization requires replacing the functions `self-insert-command',
1306 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1307 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1308 very good at guessing when a re-align will be necessary, but you can always
1309 force one with \\[org-ctrl-c-ctrl-c].
1311 If you would like to use the optimized version in Org-mode, but the
1312 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1314 This variable can be used to turn on and off the table editor during a session,
1315 but in order to toggle optimization, a restart is required.
1317 See also the variable `org-table-auto-blank-field'."
1318 :group 'org-table
1319 :type '(choice
1320 (const :tag "off" nil)
1321 (const :tag "on" t)
1322 (const :tag "on, optimized" optimized)))
1324 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1325 (version<= emacs-version "24.1"))
1326 "Non-nil means cluster self-insert commands for undo when possible.
1327 If this is set, then, like in the Emacs command loop, 20 consecutive
1328 characters will be undone together.
1329 This is configurable, because there is some impact on typing performance."
1330 :group 'org-table
1331 :type 'boolean)
1333 (defcustom org-table-tab-recognizes-table.el t
1334 "Non-nil means TAB will automatically notice a table.el table.
1335 When it sees such a table, it moves point into it and - if necessary -
1336 calls `table-recognize-table'."
1337 :group 'org-table-editing
1338 :type 'boolean)
1340 (defgroup org-link nil
1341 "Options concerning links in Org-mode."
1342 :tag "Org Link"
1343 :group 'org)
1345 (defvar org-link-abbrev-alist-local nil
1346 "Buffer-local version of `org-link-abbrev-alist', which see.
1347 The value of this is taken from the #+LINK lines.")
1348 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1350 (defcustom org-link-abbrev-alist nil
1351 "Alist of link abbreviations.
1352 The car of each element is a string, to be replaced at the start of a link.
1353 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1354 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1356 [[linkkey:tag][description]]
1358 The 'linkkey' must be a word word, starting with a letter, followed
1359 by letters, numbers, '-' or '_'.
1361 If REPLACE is a string, the tag will simply be appended to create the link.
1362 If the string contains \"%s\", the tag will be inserted there. If the string
1363 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1364 at that point (see the function `url-hexify-string'). If the string contains
1365 the specifier \"%(my-function)\", then the custom function `my-function' will
1366 be invoked: this function takes the tag as its only argument and must return
1367 a string.
1369 REPLACE may also be a function that will be called with the tag as the
1370 only argument to create the link, which should be returned as a string.
1372 See the manual for examples."
1373 :group 'org-link
1374 :type '(repeat
1375 (cons
1376 (string :tag "Protocol")
1377 (choice
1378 (string :tag "Format")
1379 (function)))))
1381 (defcustom org-descriptive-links t
1382 "Non-nil means Org will display descriptive links.
1383 E.g. [[http://orgmode.org][Org website]] will be displayed as
1384 \"Org Website\", hiding the link itself and just displaying its
1385 description. When set to `nil', Org will display the full links
1386 literally.
1388 You can interactively set the value of this variable by calling
1389 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1390 :group 'org-link
1391 :type 'boolean)
1393 (defcustom org-link-file-path-type 'adaptive
1394 "How the path name in file links should be stored.
1395 Valid values are:
1397 relative Relative to the current directory, i.e. the directory of the file
1398 into which the link is being inserted.
1399 absolute Absolute path, if possible with ~ for home directory.
1400 noabbrev Absolute path, no abbreviation of home directory.
1401 adaptive Use relative path for files in the current directory and sub-
1402 directories of it. For other files, use an absolute path."
1403 :group 'org-link
1404 :type '(choice
1405 (const relative)
1406 (const absolute)
1407 (const noabbrev)
1408 (const adaptive)))
1410 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1411 "Types of links that should be activated in Org-mode files.
1412 This is a list of symbols, each leading to the activation of a certain link
1413 type. In principle, it does not hurt to turn on most link types - there may
1414 be a small gain when turning off unused link types. The types are:
1416 bracket The recommended [[link][description]] or [[link]] links with hiding.
1417 angle Links in angular brackets that may contain whitespace like
1418 <bbdb:Carsten Dominik>.
1419 plain Plain links in normal text, no whitespace, like http://google.com.
1420 radio Text that is matched by a radio target, see manual for details.
1421 tag Tag settings in a headline (link to tag search).
1422 date Time stamps (link to calendar).
1423 footnote Footnote labels.
1425 Changing this variable requires a restart of Emacs to become effective."
1426 :group 'org-link
1427 :type '(set :greedy t
1428 (const :tag "Double bracket links" bracket)
1429 (const :tag "Angular bracket links" angle)
1430 (const :tag "Plain text links" plain)
1431 (const :tag "Radio target matches" radio)
1432 (const :tag "Tags" tag)
1433 (const :tag "Timestamps" date)
1434 (const :tag "Footnotes" footnote)))
1436 (defcustom org-make-link-description-function nil
1437 "Function to use for generating link descriptions from links.
1438 When nil, the link location will be used. This function must take
1439 two parameters: the first one is the link, the second one is the
1440 description generated by `org-insert-link'. The function should
1441 return the description to use."
1442 :group 'org-link
1443 :type 'function)
1445 (defgroup org-link-store nil
1446 "Options concerning storing links in Org-mode."
1447 :tag "Org Store Link"
1448 :group 'org-link)
1450 (defcustom org-url-hexify-p t
1451 "When non-nil, hexify URL when creating a link."
1452 :type 'boolean
1453 :version "24.3"
1454 :group 'org-link-store)
1456 (defcustom org-email-link-description-format "Email %c: %.30s"
1457 "Format of the description part of a link to an email or usenet message.
1458 The following %-escapes will be replaced by corresponding information:
1460 %F full \"From\" field
1461 %f name, taken from \"From\" field, address if no name
1462 %T full \"To\" field
1463 %t first name in \"To\" field, address if no name
1464 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1465 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1466 %s subject
1467 %d date
1468 %m message-id.
1470 You may use normal field width specification between the % and the letter.
1471 This is for example useful to limit the length of the subject.
1473 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1474 :group 'org-link-store
1475 :type 'string)
1477 (defcustom org-from-is-user-regexp
1478 (let (r1 r2)
1479 (when (and user-mail-address (not (string= user-mail-address "")))
1480 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1481 (when (and user-full-name (not (string= user-full-name "")))
1482 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1483 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1484 "Regexp matched against the \"From:\" header of an email or usenet message.
1485 It should match if the message is from the user him/herself."
1486 :group 'org-link-store
1487 :type 'regexp)
1489 (defcustom org-context-in-file-links t
1490 "Non-nil means file links from `org-store-link' contain context.
1491 A search string will be added to the file name with :: as separator and
1492 used to find the context when the link is activated by the command
1493 `org-open-at-point'. When this option is t, the entire active region
1494 will be placed in the search string of the file link. If set to a
1495 positive integer, only the first n lines of context will be stored.
1497 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1498 negates this setting for the duration of the command."
1499 :group 'org-link-store
1500 :type '(choice boolean integer))
1502 (defcustom org-keep-stored-link-after-insertion nil
1503 "Non-nil means keep link in list for entire session.
1505 The command `org-store-link' adds a link pointing to the current
1506 location to an internal list. These links accumulate during a session.
1507 The command `org-insert-link' can be used to insert links into any
1508 Org-mode file (offering completion for all stored links). When this
1509 option is nil, every link which has been inserted once using \\[org-insert-link]
1510 will be removed from the list, to make completing the unused links
1511 more efficient."
1512 :group 'org-link-store
1513 :type 'boolean)
1515 (defgroup org-link-follow nil
1516 "Options concerning following links in Org-mode."
1517 :tag "Org Follow Link"
1518 :group 'org-link)
1520 (defcustom org-link-translation-function nil
1521 "Function to translate links with different syntax to Org syntax.
1522 This can be used to translate links created for example by the Planner
1523 or emacs-wiki packages to Org syntax.
1524 The function must accept two parameters, a TYPE containing the link
1525 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1526 which is everything after the link protocol. It should return a cons
1527 with possibly modified values of type and path.
1528 Org contains a function for this, so if you set this variable to
1529 `org-translate-link-from-planner', you should be able follow many
1530 links created by planner."
1531 :group 'org-link-follow
1532 :type 'function)
1534 (defcustom org-follow-link-hook nil
1535 "Hook that is run after a link has been followed."
1536 :group 'org-link-follow
1537 :type 'hook)
1539 (defcustom org-tab-follows-link nil
1540 "Non-nil means on links TAB will follow the link.
1541 Needs to be set before org.el is loaded.
1542 This really should not be used, it does not make sense, and the
1543 implementation is bad."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-return-follows-link nil
1548 "Non-nil means on links RET will follow the link."
1549 :group 'org-link-follow
1550 :type 'boolean)
1552 (defcustom org-mouse-1-follows-link
1553 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1554 "Non-nil means mouse-1 on a link will follow the link.
1555 A longer mouse click will still set point. Does not work on XEmacs.
1556 Needs to be set before org.el is loaded."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mark-ring-length 4
1561 "Number of different positions to be recorded in the ring.
1562 Changing this requires a restart of Emacs to work correctly."
1563 :group 'org-link-follow
1564 :type 'integer)
1566 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1567 "Non-nil means internal links in Org files must exactly match a headline.
1568 When nil, the link search tries to match a phrase with all words
1569 in the search text."
1570 :group 'org-link-follow
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Use fuzzy text search" nil)
1574 (const :tag "Match only exact headline" t)
1575 (const :tag "Match exact headline or query to create it"
1576 query-to-create)))
1578 (defcustom org-link-frame-setup
1579 '((vm . vm-visit-folder-other-frame)
1580 (vm-imap . vm-visit-imap-folder-other-frame)
1581 (gnus . org-gnus-no-new-news)
1582 (file . find-file-other-window)
1583 (wl . wl-other-frame))
1584 "Setup the frame configuration for following links.
1585 When following a link with Emacs, it may often be useful to display
1586 this link in another window or frame. This variable can be used to
1587 set this up for the different types of links.
1588 For VM, use any of
1589 `vm-visit-folder'
1590 `vm-visit-folder-other-window'
1591 `vm-visit-folder-other-frame'
1592 For Gnus, use any of
1593 `gnus'
1594 `gnus-other-frame'
1595 `org-gnus-no-new-news'
1596 For FILE, use any of
1597 `find-file'
1598 `find-file-other-window'
1599 `find-file-other-frame'
1600 For Wanderlust use any of
1601 `wl'
1602 `wl-other-frame'
1603 For the calendar, use the variable `calendar-setup'.
1604 For BBDB, it is currently only possible to display the matches in
1605 another window."
1606 :group 'org-link-follow
1607 :type '(list
1608 (cons (const vm)
1609 (choice
1610 (const vm-visit-folder)
1611 (const vm-visit-folder-other-window)
1612 (const vm-visit-folder-other-frame)))
1613 (cons (const gnus)
1614 (choice
1615 (const gnus)
1616 (const gnus-other-frame)
1617 (const org-gnus-no-new-news)))
1618 (cons (const file)
1619 (choice
1620 (const find-file)
1621 (const find-file-other-window)
1622 (const find-file-other-frame)))
1623 (cons (const wl)
1624 (choice
1625 (const wl)
1626 (const wl-other-frame)))))
1628 (defcustom org-display-internal-link-with-indirect-buffer nil
1629 "Non-nil means use indirect buffer to display infile links.
1630 Activating internal links (from one location in a file to another location
1631 in the same file) normally just jumps to the location. When the link is
1632 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 is displayed in
1634 another window. When this option is set, the other window actually displays
1635 an indirect buffer clone of the current buffer, to avoid any visibility
1636 changes to the current buffer."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-non-existing-files nil
1641 "Non-nil means `org-open-file' will open non-existing files.
1642 When nil, an error will be generated.
1643 This variable applies only to external applications because they
1644 might choke on non-existing files. If the link is to a file that
1645 will be opened in Emacs, the variable is ignored."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-directory-means-index-dot-org nil
1650 "Non-nil means a link to a directory really means to index.org.
1651 When nil, following a directory link will run dired or open a finder/explorer
1652 window on that directory."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1657 "Function and arguments to call for following mailto links.
1658 This is a list with the first element being a Lisp function, and the
1659 remaining elements being arguments to the function. In string arguments,
1660 %a will be replaced by the address, and %s will be replaced by the subject
1661 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1665 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1666 (const :tag "message-mail" (message-mail "%a" "%s"))
1667 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1669 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1670 "Non-nil means ask for confirmation before executing shell links.
1671 Shell links can be dangerous: just think about a link
1673 [[shell:rm -rf ~/*][Google Search]]
1675 This link would show up in your Org-mode document as \"Google Search\",
1676 but really it would remove your entire home directory.
1677 Therefore we advise against setting this variable to nil.
1678 Just change it to `y-or-n-p' if you want to confirm with a
1679 single keystroke rather than having to type \"yes\"."
1680 :group 'org-link-follow
1681 :type '(choice
1682 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1683 (const :tag "with y-or-n (faster)" y-or-n-p)
1684 (const :tag "no confirmation (dangerous)" nil)))
1685 (put 'org-confirm-shell-link-function
1686 'safe-local-variable
1687 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1689 (defcustom org-confirm-shell-link-not-regexp ""
1690 "A regexp to skip confirmation for shell links."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type 'regexp)
1695 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1696 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1697 Elisp links can be dangerous: just think about a link
1699 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1701 This link would show up in your Org-mode document as \"Google Search\",
1702 but really it would remove your entire home directory.
1703 Therefore we advise against setting this variable to nil.
1704 Just change it to `y-or-n-p' if you want to confirm with a
1705 single keystroke rather than having to type \"yes\"."
1706 :group 'org-link-follow
1707 :type '(choice
1708 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1709 (const :tag "with y-or-n (faster)" y-or-n-p)
1710 (const :tag "no confirmation (dangerous)" nil)))
1711 (put 'org-confirm-shell-link-function
1712 'safe-local-variable
1713 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1715 (defcustom org-confirm-elisp-link-not-regexp ""
1716 "A regexp to skip confirmation for Elisp links."
1717 :group 'org-link-follow
1718 :version "24.1"
1719 :type 'regexp)
1721 (defconst org-file-apps-defaults-gnu
1722 '((remote . emacs)
1723 (system . mailcap)
1724 (t . mailcap))
1725 "Default file applications on a UNIX or GNU/Linux system.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-macosx
1729 '((remote . emacs)
1730 (t . "open %s")
1731 (system . "open %s")
1732 ("ps.gz" . "gv %s")
1733 ("eps.gz" . "gv %s")
1734 ("dvi" . "xdvi %s")
1735 ("fig" . "xfig %s"))
1736 "Default file applications on a MacOS X system.
1737 The system \"open\" is known as a default, but we use X11 applications
1738 for some files for which the OS does not have a good default.
1739 See `org-file-apps'.")
1741 (defconst org-file-apps-defaults-windowsnt
1742 (list
1743 '(remote . emacs)
1744 (cons t
1745 (list (if (featurep 'xemacs)
1746 'mswindows-shell-execute
1747 'w32-shell-execute)
1748 "open" 'file))
1749 (cons 'system
1750 (list (if (featurep 'xemacs)
1751 'mswindows-shell-execute
1752 'w32-shell-execute)
1753 "open" 'file)))
1754 "Default file applications on a Windows NT system.
1755 The system \"open\" is used for most files.
1756 See `org-file-apps'.")
1758 (defcustom org-file-apps
1760 (auto-mode . emacs)
1761 ("\\.mm\\'" . default)
1762 ("\\.x?html?\\'" . default)
1763 ("\\.pdf\\'" . default)
1765 "External applications for opening `file:path' items in a document.
1766 Org-mode uses system defaults for different file types, but
1767 you can use this variable to set the application for a given file
1768 extension. The entries in this list are cons cells where the car identifies
1769 files and the cdr the corresponding command. Possible values for the
1770 file identifier are
1771 \"string\" A string as a file identifier can be interpreted in different
1772 ways, depending on its contents:
1774 - Alphanumeric characters only:
1775 Match links with this file extension.
1776 Example: (\"pdf\" . \"evince %s\")
1777 to open PDFs with evince.
1779 - Regular expression: Match links where the
1780 filename matches the regexp. If you want to
1781 use groups here, use shy groups.
1783 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1784 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1785 to open *.html and *.xhtml with firefox.
1787 - Regular expression which contains (non-shy) groups:
1788 Match links where the whole link, including \"::\", and
1789 anything after that, matches the regexp.
1790 In a custom command string, %1, %2, etc. are replaced with
1791 the parts of the link that were matched by the groups.
1792 For backwards compatibility, if a command string is given
1793 that does not use any of the group matches, this case is
1794 handled identically to the second one (i.e. match against
1795 file name only).
1796 In a custom lisp form, you can access the group matches with
1797 (match-string n link).
1799 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1800 to open [[file:document.pdf::5]] with evince at page 5.
1802 `directory' Matches a directory
1803 `remote' Matches a remote file, accessible through tramp or efs.
1804 Remote files most likely should be visited through Emacs
1805 because external applications cannot handle such paths.
1806 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1807 so all files Emacs knows how to handle. Using this with
1808 command `emacs' will open most files in Emacs. Beware that this
1809 will also open html files inside Emacs, unless you add
1810 (\"html\" . default) to the list as well.
1811 t Default for files not matched by any of the other options.
1812 `system' The system command to open files, like `open' on Windows
1813 and Mac OS X, and mailcap under GNU/Linux. This is the command
1814 that will be selected if you call `C-c C-o' with a double
1815 \\[universal-argument] \\[universal-argument] prefix.
1817 Possible values for the command are:
1818 `emacs' The file will be visited by the current Emacs process.
1819 `default' Use the default application for this file type, which is the
1820 association for t in the list, most likely in the system-specific
1821 part.
1822 This can be used to overrule an unwanted setting in the
1823 system-specific variable.
1824 `system' Use the system command for opening files, like \"open\".
1825 This command is specified by the entry whose car is `system'.
1826 Most likely, the system-specific version of this variable
1827 does define this command, but you can overrule/replace it
1828 here.
1829 string A command to be executed by a shell; %s will be replaced
1830 by the path to the file.
1831 sexp A Lisp form which will be evaluated. The file path will
1832 be available in the Lisp variable `file'.
1833 For more examples, see the system specific constants
1834 `org-file-apps-defaults-macosx'
1835 `org-file-apps-defaults-windowsnt'
1836 `org-file-apps-defaults-gnu'."
1837 :group 'org-link-follow
1838 :type '(repeat
1839 (cons (choice :value ""
1840 (string :tag "Extension")
1841 (const :tag "System command to open files" system)
1842 (const :tag "Default for unrecognized files" t)
1843 (const :tag "Remote file" remote)
1844 (const :tag "Links to a directory" directory)
1845 (const :tag "Any files that have Emacs modes"
1846 auto-mode))
1847 (choice :value ""
1848 (const :tag "Visit with Emacs" emacs)
1849 (const :tag "Use default" default)
1850 (const :tag "Use the system command" system)
1851 (string :tag "Command")
1852 (sexp :tag "Lisp form")))))
1854 (defcustom org-doi-server-url "http://dx.doi.org/"
1855 "The URL of the DOI server."
1856 :type 'string
1857 :version "24.3"
1858 :group 'org-link-follow)
1860 (defgroup org-refile nil
1861 "Options concerning refiling entries in Org-mode."
1862 :tag "Org Refile"
1863 :group 'org)
1865 (defcustom org-directory "~/org"
1866 "Directory with org files.
1867 This is just a default location to look for Org files. There is no need
1868 at all to put your files into this directory. It is only used in the
1869 following situations:
1871 1. When a capture template specifies a target file that is not an
1872 absolute path. The path will then be interpreted relative to
1873 `org-directory'
1874 2. When a capture note is filed away in an interactive way (when exiting the
1875 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1876 with `org-directory' as the default path."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :group 'org-capture
1880 :type 'directory)
1882 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1883 "Default target for storing notes.
1884 Used as a fall back file for org-remember.el and org-capture.el, for
1885 templates that do not specify a target file."
1886 :group 'org-refile
1887 :group 'org-remember
1888 :group 'org-capture
1889 :type '(choice
1890 (const :tag "Default from remember-data-file" nil)
1891 file))
1893 (defcustom org-goto-interface 'outline
1894 "The default interface to be used for `org-goto'.
1895 Allowed values are:
1896 outline The interface shows an outline of the relevant file
1897 and the correct heading is found by moving through
1898 the outline or by searching with incremental search.
1899 outline-path-completion Headlines in the current buffer are offered via
1900 completion. This is the interface also used by
1901 the refile command."
1902 :group 'org-refile
1903 :type '(choice
1904 (const :tag "Outline" outline)
1905 (const :tag "Outline-path-completion" outline-path-completion)))
1907 (defcustom org-goto-max-level 5
1908 "Maximum target level when running `org-goto' with refile interface."
1909 :group 'org-refile
1910 :type 'integer)
1912 (defcustom org-reverse-note-order nil
1913 "Non-nil means store new notes at the beginning of a file or entry.
1914 When nil, new notes will be filed to the end of a file or entry.
1915 This can also be a list with cons cells of regular expressions that
1916 are matched against file names, and values."
1917 :group 'org-remember
1918 :group 'org-capture
1919 :group 'org-refile
1920 :type '(choice
1921 (const :tag "Reverse always" t)
1922 (const :tag "Reverse never" nil)
1923 (repeat :tag "By file name regexp"
1924 (cons regexp boolean))))
1926 (defcustom org-log-refile nil
1927 "Information to record when a task is refiled.
1929 Possible values are:
1931 nil Don't add anything
1932 time Add a time stamp to the task
1933 note Prompt for a note and add it with template `org-log-note-headings'
1935 This option can also be set with on a per-file-basis with
1937 #+STARTUP: nologrefile
1938 #+STARTUP: logrefile
1939 #+STARTUP: lognoterefile
1941 You can have local logging settings for a subtree by setting the LOGGING
1942 property to one or more of these keywords.
1944 When bulk-refiling from the agenda, the value `note' is forbidden and
1945 will temporarily be changed to `time'."
1946 :group 'org-refile
1947 :group 'org-progress
1948 :version "24.1"
1949 :type '(choice
1950 (const :tag "No logging" nil)
1951 (const :tag "Record timestamp" time)
1952 (const :tag "Record timestamp with note." note)))
1954 (defcustom org-refile-targets nil
1955 "Targets for refiling entries with \\[org-refile].
1956 This is a list of cons cells. Each cell contains:
1957 - a specification of the files to be considered, either a list of files,
1958 or a symbol whose function or variable value will be used to retrieve
1959 a file name or a list of file names. If you use `org-agenda-files' for
1960 that, all agenda files will be scanned for targets. Nil means consider
1961 headings in the current buffer.
1962 - A specification of how to find candidate refile targets. This may be
1963 any of:
1964 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1965 This tag has to be present in all target headlines, inheritance will
1966 not be considered.
1967 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1968 todo keyword.
1969 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1970 headlines that are refiling targets.
1971 - a cons cell (:level . N). Any headline of level N is considered a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1974 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1975 Note that, when `org-odd-levels-only' is set, level corresponds to
1976 order in hierarchy, not to the number of stars.
1978 Each element of this list generates a set of possible targets.
1979 The union of these sets is presented (with completion) to
1980 the user by `org-refile'.
1982 You can set the variable `org-refile-target-verify-function' to a function
1983 to verify each headline found by the simple criteria above.
1985 When this variable is nil, all top-level headlines in the current buffer
1986 are used, equivalent to the value `((nil . (:level . 1))'."
1987 :group 'org-refile
1988 :type '(repeat
1989 (cons
1990 (choice :value org-agenda-files
1991 (const :tag "All agenda files" org-agenda-files)
1992 (const :tag "Current buffer" nil)
1993 (function) (variable) (file))
1994 (choice :tag "Identify target headline by"
1995 (cons :tag "Specific tag" (const :value :tag) (string))
1996 (cons :tag "TODO keyword" (const :value :todo) (string))
1997 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1998 (cons :tag "Level number" (const :value :level) (integer))
1999 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2001 (defcustom org-refile-target-verify-function nil
2002 "Function to verify if the headline at point should be a refile target.
2003 The function will be called without arguments, with point at the
2004 beginning of the headline. It should return t and leave point
2005 where it is if the headline is a valid target for refiling.
2007 If the target should not be selected, the function must return nil.
2008 In addition to this, it may move point to a place from where the search
2009 should be continued. For example, the function may decide that the entire
2010 subtree of the current entry should be excluded and move point to the end
2011 of the subtree."
2012 :group 'org-refile
2013 :type 'function)
2015 (defcustom org-refile-use-cache nil
2016 "Non-nil means cache refile targets to speed up the process.
2017 The cache for a particular file will be updated automatically when
2018 the buffer has been killed, or when any of the marker used for flagging
2019 refile targets no longer points at a live buffer.
2020 If you have added new entries to a buffer that might themselves be targets,
2021 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2022 find that easier, `C-u C-u C-u C-c C-w'."
2023 :group 'org-refile
2024 :version "24.1"
2025 :type 'boolean)
2027 (defcustom org-refile-use-outline-path nil
2028 "Non-nil means provide refile targets as paths.
2029 So a level 3 headline will be available as level1/level2/level3.
2031 When the value is `file', also include the file name (without directory)
2032 into the path. In this case, you can also stop the completion after
2033 the file name, to get entries inserted as top level in the file.
2035 When `full-file-path', include the full file path."
2036 :group 'org-refile
2037 :type '(choice
2038 (const :tag "Not" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Start with file name" file)
2041 (const :tag "Start with full file path" full-file-path)))
2043 (defcustom org-outline-path-complete-in-steps t
2044 "Non-nil means complete the outline path in hierarchical steps.
2045 When Org-mode uses the refile interface to select an outline path
2046 \(see variable `org-refile-use-outline-path'), the completion of
2047 the path can be done is a single go, or if can be done in steps down
2048 the headline hierarchy. Going in steps is probably the best if you
2049 do not use a special completion package like `ido' or `icicles'.
2050 However, when using these packages, going in one step can be very
2051 fast, while still showing the whole path to the entry."
2052 :group 'org-refile
2053 :type 'boolean)
2055 (defcustom org-refile-allow-creating-parent-nodes nil
2056 "Non-nil means allow to create new nodes as refile targets.
2057 New nodes are then created by adding \"/new node name\" to the completion
2058 of an existing node. When the value of this variable is `confirm',
2059 new node creation must be confirmed by the user (recommended)
2060 When nil, the completion must match an existing entry.
2062 Note that, if the new heading is not seen by the criteria
2063 listed in `org-refile-targets', multiple instances of the same
2064 heading would be created by trying again to file under the new
2065 heading."
2066 :group 'org-refile
2067 :type '(choice
2068 (const :tag "Never" nil)
2069 (const :tag "Always" t)
2070 (const :tag "Prompt for confirmation" confirm)))
2072 (defcustom org-refile-active-region-within-subtree nil
2073 "Non-nil means also refile active region within a subtree.
2075 By default `org-refile' doesn't allow refiling regions if they
2076 don't contain a set of subtrees, but it might be convenient to
2077 do so sometimes: in that case, the first line of the region is
2078 converted to a headline before refiling."
2079 :group 'org-refile
2080 :version "24.1"
2081 :type 'boolean)
2083 (defgroup org-todo nil
2084 "Options concerning TODO items in Org-mode."
2085 :tag "Org TODO"
2086 :group 'org)
2088 (defgroup org-progress nil
2089 "Options concerning Progress logging in Org-mode."
2090 :tag "Org Progress"
2091 :group 'org-time)
2093 (defvar org-todo-interpretation-widgets
2094 '((:tag "Sequence (cycling hits every state)" sequence)
2095 (:tag "Type (cycling directly to DONE)" type))
2096 "The available interpretation symbols for customizing `org-todo-keywords'.
2097 Interested libraries should add to this list.")
2099 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2100 "List of TODO entry keyword sequences and their interpretation.
2101 \\<org-mode-map>This is a list of sequences.
2103 Each sequence starts with a symbol, either `sequence' or `type',
2104 indicating if the keywords should be interpreted as a sequence of
2105 action steps, or as different types of TODO items. The first
2106 keywords are states requiring action - these states will select a headline
2107 for inclusion into the global TODO list Org-mode produces. If one of
2108 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2109 signify that no further action is necessary. If \"|\" is not found,
2110 the last keyword is treated as the only DONE state of the sequence.
2112 The command \\[org-todo] cycles an entry through these states, and one
2113 additional state where no keyword is present. For details about this
2114 cycling, see the manual.
2116 TODO keywords and interpretation can also be set on a per-file basis with
2117 the special #+SEQ_TODO and #+TYP_TODO lines.
2119 Each keyword can optionally specify a character for fast state selection
2120 \(in combination with the variable `org-use-fast-todo-selection')
2121 and specifiers for state change logging, using the same syntax that
2122 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2123 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2124 indicates to record a time stamp each time this state is selected.
2126 Each keyword may also specify if a timestamp or a note should be
2127 recorded when entering or leaving the state, by adding additional
2128 characters in the parenthesis after the keyword. This looks like this:
2129 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2130 record only the time of the state change. With X and Y being either
2131 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2132 Y when leaving the state if and only if the *target* state does not
2133 define X. You may omit any of the fast-selection key or X or /Y,
2134 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2136 For backward compatibility, this variable may also be just a list
2137 of keywords. In this case the interpretation (sequence or type) will be
2138 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2139 :group 'org-todo
2140 :group 'org-keywords
2141 :type '(choice
2142 (repeat :tag "Old syntax, just keywords"
2143 (string :tag "Keyword"))
2144 (repeat :tag "New syntax"
2145 (cons
2146 (choice
2147 :tag "Interpretation"
2148 ;;Quick and dirty way to see
2149 ;;`org-todo-interpretations'. This takes the
2150 ;;place of item arguments
2151 :convert-widget
2152 (lambda (widget)
2153 (widget-put widget
2154 :args (mapcar
2155 #'(lambda (x)
2156 (widget-convert
2157 (cons 'const x)))
2158 org-todo-interpretation-widgets))
2159 widget))
2160 (repeat
2161 (string :tag "Keyword"))))))
2163 (defvar org-todo-keywords-1 nil
2164 "All TODO and DONE keywords active in a buffer.")
2165 (make-variable-buffer-local 'org-todo-keywords-1)
2166 (defvar org-todo-keywords-for-agenda nil)
2167 (defvar org-done-keywords-for-agenda nil)
2168 (defvar org-drawers-for-agenda nil)
2169 (defvar org-todo-keyword-alist-for-agenda nil)
2170 (defvar org-tag-alist-for-agenda nil)
2171 (defvar org-agenda-contributing-files nil)
2172 (defvar org-not-done-keywords nil)
2173 (make-variable-buffer-local 'org-not-done-keywords)
2174 (defvar org-done-keywords nil)
2175 (make-variable-buffer-local 'org-done-keywords)
2176 (defvar org-todo-heads nil)
2177 (make-variable-buffer-local 'org-todo-heads)
2178 (defvar org-todo-sets nil)
2179 (make-variable-buffer-local 'org-todo-sets)
2180 (defvar org-todo-log-states nil)
2181 (make-variable-buffer-local 'org-todo-log-states)
2182 (defvar org-todo-kwd-alist nil)
2183 (make-variable-buffer-local 'org-todo-kwd-alist)
2184 (defvar org-todo-key-alist nil)
2185 (make-variable-buffer-local 'org-todo-key-alist)
2186 (defvar org-todo-key-trigger nil)
2187 (make-variable-buffer-local 'org-todo-key-trigger)
2189 (defcustom org-todo-interpretation 'sequence
2190 "Controls how TODO keywords are interpreted.
2191 This variable is in principle obsolete and is only used for
2192 backward compatibility, if the interpretation of todo keywords is
2193 not given already in `org-todo-keywords'. See that variable for
2194 more information."
2195 :group 'org-todo
2196 :group 'org-keywords
2197 :type '(choice (const sequence)
2198 (const type)))
2200 (defcustom org-use-fast-todo-selection t
2201 "Non-nil means use the fast todo selection scheme with C-c C-t.
2202 This variable describes if and under what circumstances the cycling
2203 mechanism for TODO keywords will be replaced by a single-key, direct
2204 selection scheme.
2206 When nil, fast selection is never used.
2208 When the symbol `prefix', it will be used when `org-todo' is called
2209 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2210 `C-u t' in an agenda buffer.
2212 When t, fast selection is used by default. In this case, the prefix
2213 argument forces cycling instead.
2215 In all cases, the special interface is only used if access keys have
2216 actually been assigned by the user, i.e. if keywords in the configuration
2217 are followed by a letter in parenthesis, like TODO(t)."
2218 :group 'org-todo
2219 :type '(choice
2220 (const :tag "Never" nil)
2221 (const :tag "By default" t)
2222 (const :tag "Only with C-u C-c C-t" prefix)))
2224 (defcustom org-provide-todo-statistics t
2225 "Non-nil means update todo statistics after insert and toggle.
2226 ALL-HEADLINES means update todo statistics by including headlines
2227 with no TODO keyword as well, counting them as not done.
2228 A list of TODO keywords means the same, but skip keywords that are
2229 not in this list.
2231 When this is set, todo statistics is updated in the parent of the
2232 current entry each time a todo state is changed."
2233 :group 'org-todo
2234 :type '(choice
2235 (const :tag "Yes, only for TODO entries" t)
2236 (const :tag "Yes, including all entries" 'all-headlines)
2237 (repeat :tag "Yes, for TODOs in this list"
2238 (string :tag "TODO keyword"))
2239 (other :tag "No TODO statistics" nil)))
2241 (defcustom org-hierarchical-todo-statistics t
2242 "Non-nil means TODO statistics covers just direct children.
2243 When nil, all entries in the subtree are considered.
2244 This has only an effect if `org-provide-todo-statistics' is set.
2245 To set this to nil for only a single subtree, use a COOKIE_DATA
2246 property and include the word \"recursive\" into the value."
2247 :group 'org-todo
2248 :type 'boolean)
2250 (defcustom org-after-todo-state-change-hook nil
2251 "Hook which is run after the state of a TODO item was changed.
2252 The new state (a string with a TODO keyword, or nil) is available in the
2253 Lisp variable `org-state'."
2254 :group 'org-todo
2255 :type 'hook)
2257 (defvar org-blocker-hook nil
2258 "Hook for functions that are allowed to block a state change.
2260 Each function gets as its single argument a property list, see
2261 `org-trigger-hook' for more information about this list.
2263 If any of the functions in this hook returns nil, the state change
2264 is blocked.")
2266 (defvar org-trigger-hook nil
2267 "Hook for functions that are triggered by a state change.
2269 Each function gets as its single argument a property list with at least
2270 the following elements:
2272 (:type type-of-change :position pos-at-entry-start
2273 :from old-state :to new-state)
2275 Depending on the type, more properties may be present.
2277 This mechanism is currently implemented for:
2279 TODO state changes
2280 ------------------
2281 :type todo-state-change
2282 :from previous state (keyword as a string), or nil, or a symbol
2283 'todo' or 'done', to indicate the general type of state.
2284 :to new state, like in :from")
2286 (defcustom org-enforce-todo-dependencies nil
2287 "Non-nil means undone TODO entries will block switching the parent to DONE.
2288 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2289 be blocked if any prior sibling is not yet done.
2290 Finally, if the parent is blocked because of ordered siblings of its own,
2291 the child will also be blocked."
2292 :set (lambda (var val)
2293 (set var val)
2294 (if val
2295 (add-hook 'org-blocker-hook
2296 'org-block-todo-from-children-or-siblings-or-parent)
2297 (remove-hook 'org-blocker-hook
2298 'org-block-todo-from-children-or-siblings-or-parent)))
2299 :group 'org-todo
2300 :type 'boolean)
2302 (defcustom org-enforce-todo-checkbox-dependencies nil
2303 "Non-nil means unchecked boxes will block switching the parent to DONE.
2304 When this is nil, checkboxes have no influence on switching TODO states.
2305 When non-nil, you first need to check off all check boxes before the TODO
2306 entry can be switched to DONE.
2307 This variable needs to be set before org.el is loaded, and you need to
2308 restart Emacs after a change to make the change effective. The only way
2309 to change is while Emacs is running is through the customize interface."
2310 :set (lambda (var val)
2311 (set var val)
2312 (if val
2313 (add-hook 'org-blocker-hook
2314 'org-block-todo-from-checkboxes)
2315 (remove-hook 'org-blocker-hook
2316 'org-block-todo-from-checkboxes)))
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-treat-insert-todo-heading-as-state-change nil
2321 "Non-nil means inserting a TODO heading is treated as state change.
2322 So when the command \\[org-insert-todo-heading] is used, state change
2323 logging will apply if appropriate. When nil, the new TODO item will
2324 be inserted directly, and no logging will take place."
2325 :group 'org-todo
2326 :type 'boolean)
2328 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2329 "Non-nil means switching TODO states with S-cursor counts as state change.
2330 This is the default behavior. However, setting this to nil allows a
2331 convenient way to select a TODO state and bypass any logging associated
2332 with that."
2333 :group 'org-todo
2334 :type 'boolean)
2336 (defcustom org-todo-state-tags-triggers nil
2337 "Tag changes that should be triggered by TODO state changes.
2338 This is a list. Each entry is
2340 (state-change (tag . flag) .......)
2342 State-change can be a string with a state, and empty string to indicate the
2343 state that has no TODO keyword, or it can be one of the symbols `todo'
2344 or `done', meaning any not-done or done state, respectively."
2345 :group 'org-todo
2346 :group 'org-tags
2347 :type '(repeat
2348 (cons (choice :tag "When changing to"
2349 (const :tag "Not-done state" todo)
2350 (const :tag "Done state" done)
2351 (string :tag "State"))
2352 (repeat
2353 (cons :tag "Tag action"
2354 (string :tag "Tag")
2355 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2357 (defcustom org-log-done nil
2358 "Information to record when a task moves to the DONE state.
2360 Possible values are:
2362 nil Don't add anything, just change the keyword
2363 time Add a time stamp to the task
2364 note Prompt for a note and add it with template `org-log-note-headings'
2366 This option can also be set with on a per-file-basis with
2368 #+STARTUP: nologdone
2369 #+STARTUP: logdone
2370 #+STARTUP: lognotedone
2372 You can have local logging settings for a subtree by setting the LOGGING
2373 property to one or more of these keywords."
2374 :group 'org-todo
2375 :group 'org-progress
2376 :type '(choice
2377 (const :tag "No logging" nil)
2378 (const :tag "Record CLOSED timestamp" time)
2379 (const :tag "Record CLOSED timestamp with note." note)))
2381 ;; Normalize old uses of org-log-done.
2382 (cond
2383 ((eq org-log-done t) (setq org-log-done 'time))
2384 ((and (listp org-log-done) (memq 'done org-log-done))
2385 (setq org-log-done 'note)))
2387 (defcustom org-log-reschedule nil
2388 "Information to record when the scheduling date of a tasks is modified.
2390 Possible values are:
2392 nil Don't add anything, just change the date
2393 time Add a time stamp to the task
2394 note Prompt for a note and add it with template `org-log-note-headings'
2396 This option can also be set with on a per-file-basis with
2398 #+STARTUP: nologreschedule
2399 #+STARTUP: logreschedule
2400 #+STARTUP: lognotereschedule"
2401 :group 'org-todo
2402 :group 'org-progress
2403 :type '(choice
2404 (const :tag "No logging" nil)
2405 (const :tag "Record timestamp" time)
2406 (const :tag "Record timestamp with note." note)))
2408 (defcustom org-log-redeadline nil
2409 "Information to record when the deadline date of a tasks is modified.
2411 Possible values are:
2413 nil Don't add anything, just change the date
2414 time Add a time stamp to the task
2415 note Prompt for a note and add it with template `org-log-note-headings'
2417 This option can also be set with on a per-file-basis with
2419 #+STARTUP: nologredeadline
2420 #+STARTUP: logredeadline
2421 #+STARTUP: lognoteredeadline
2423 You can have local logging settings for a subtree by setting the LOGGING
2424 property to one or more of these keywords."
2425 :group 'org-todo
2426 :group 'org-progress
2427 :type '(choice
2428 (const :tag "No logging" nil)
2429 (const :tag "Record timestamp" time)
2430 (const :tag "Record timestamp with note." note)))
2432 (defcustom org-log-note-clock-out nil
2433 "Non-nil means record a note when clocking out of an item.
2434 This can also be configured on a per-file basis by adding one of
2435 the following lines anywhere in the buffer:
2437 #+STARTUP: lognoteclock-out
2438 #+STARTUP: nolognoteclock-out"
2439 :group 'org-todo
2440 :group 'org-progress
2441 :type 'boolean)
2443 (defcustom org-log-done-with-time t
2444 "Non-nil means the CLOSED time stamp will contain date and time.
2445 When nil, only the date will be recorded."
2446 :group 'org-progress
2447 :type 'boolean)
2449 (defcustom org-log-note-headings
2450 '((done . "CLOSING NOTE %t")
2451 (state . "State %-12s from %-12S %t")
2452 (note . "Note taken on %t")
2453 (reschedule . "Rescheduled from %S on %t")
2454 (delschedule . "Not scheduled, was %S on %t")
2455 (redeadline . "New deadline from %S on %t")
2456 (deldeadline . "Removed deadline, was %S on %t")
2457 (refile . "Refiled on %t")
2458 (clock-out . ""))
2459 "Headings for notes added to entries.
2460 The value is an alist, with the car being a symbol indicating the note
2461 context, and the cdr is the heading to be used. The heading may also be the
2462 empty string.
2463 %t in the heading will be replaced by a time stamp.
2464 %T will be an active time stamp instead the default inactive one
2465 %d will be replaced by a short-format time stamp.
2466 %D will be replaced by an active short-format time stamp.
2467 %s will be replaced by the new TODO state, in double quotes.
2468 %S will be replaced by the old TODO state, in double quotes.
2469 %u will be replaced by the user name.
2470 %U will be replaced by the full user name.
2472 In fact, it is not a good idea to change the `state' entry, because
2473 agenda log mode depends on the format of these entries."
2474 :group 'org-todo
2475 :group 'org-progress
2476 :type '(list :greedy t
2477 (cons (const :tag "Heading when closing an item" done) string)
2478 (cons (const :tag
2479 "Heading when changing todo state (todo sequence only)"
2480 state) string)
2481 (cons (const :tag "Heading when just taking a note" note) string)
2482 (cons (const :tag "Heading when clocking out" clock-out) string)
2483 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2484 (cons (const :tag "Heading when rescheduling" reschedule) string)
2485 (cons (const :tag "Heading when changing deadline" redeadline) string)
2486 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2487 (cons (const :tag "Heading when refiling" refile) string)))
2489 (unless (assq 'note org-log-note-headings)
2490 (push '(note . "%t") org-log-note-headings))
2492 (defcustom org-log-into-drawer nil
2493 "Non-nil means insert state change notes and time stamps into a drawer.
2494 When nil, state changes notes will be inserted after the headline and
2495 any scheduling and clock lines, but not inside a drawer.
2497 The value of this variable should be the name of the drawer to use.
2498 LOGBOOK is proposed as the default drawer for this purpose, you can
2499 also set this to a string to define the drawer of your choice.
2501 A value of t is also allowed, representing \"LOGBOOK\".
2503 If this variable is set, `org-log-state-notes-insert-after-drawers'
2504 will be ignored.
2506 You can set the property LOG_INTO_DRAWER to overrule this setting for
2507 a subtree."
2508 :group 'org-todo
2509 :group 'org-progress
2510 :type '(choice
2511 (const :tag "Not into a drawer" nil)
2512 (const :tag "LOGBOOK" t)
2513 (string :tag "Other")))
2515 (if (fboundp 'defvaralias)
2516 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2518 (defun org-log-into-drawer ()
2519 "Return the value of `org-log-into-drawer', but let properties overrule.
2520 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2521 used instead of the default value."
2522 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2523 (cond
2524 ((not p) org-log-into-drawer)
2525 ((equal p "nil") nil)
2526 ((equal p "t") "LOGBOOK")
2527 (t p))))
2529 (defcustom org-log-state-notes-insert-after-drawers nil
2530 "Non-nil means insert state change notes after any drawers in entry.
2531 Only the drawers that *immediately* follow the headline and the
2532 deadline/scheduled line are skipped.
2533 When nil, insert notes right after the heading and perhaps the line
2534 with deadline/scheduling if present.
2536 This variable will have no effect if `org-log-into-drawer' is
2537 set."
2538 :group 'org-todo
2539 :group 'org-progress
2540 :type 'boolean)
2542 (defcustom org-log-states-order-reversed t
2543 "Non-nil means the latest state note will be directly after heading.
2544 When nil, the state change notes will be ordered according to time."
2545 :group 'org-todo
2546 :group 'org-progress
2547 :type 'boolean)
2549 (defcustom org-todo-repeat-to-state nil
2550 "The TODO state to which a repeater should return the repeating task.
2551 By default this is the first task in a TODO sequence, or the previous state
2552 in a TODO_TYP set. But you can specify another task here.
2553 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2554 :group 'org-todo
2555 :version "24.1"
2556 :type '(choice (const :tag "Head of sequence" nil)
2557 (string :tag "Specific state")))
2559 (defcustom org-log-repeat 'time
2560 "Non-nil means record moving through the DONE state when triggering repeat.
2561 An auto-repeating task is immediately switched back to TODO when
2562 marked DONE. If you are not logging state changes (by adding \"@\"
2563 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2564 record a closing note, there will be no record of the task moving
2565 through DONE. This variable forces taking a note anyway.
2567 nil Don't force a record
2568 time Record a time stamp
2569 note Prompt for a note and add it with template `org-log-note-headings'
2571 This option can also be set with on a per-file-basis with
2573 #+STARTUP: nologrepeat
2574 #+STARTUP: logrepeat
2575 #+STARTUP: lognoterepeat
2577 You can have local logging settings for a subtree by setting the LOGGING
2578 property to one or more of these keywords."
2579 :group 'org-todo
2580 :group 'org-progress
2581 :type '(choice
2582 (const :tag "Don't force a record" nil)
2583 (const :tag "Force recording the DONE state" time)
2584 (const :tag "Force recording a note with the DONE state" note)))
2587 (defgroup org-priorities nil
2588 "Priorities in Org-mode."
2589 :tag "Org Priorities"
2590 :group 'org-todo)
2592 (defcustom org-enable-priority-commands t
2593 "Non-nil means priority commands are active.
2594 When nil, these commands will be disabled, so that you never accidentally
2595 set a priority."
2596 :group 'org-priorities
2597 :type 'boolean)
2599 (defcustom org-highest-priority ?A
2600 "The highest priority of TODO items. A character like ?A, ?B etc.
2601 Must have a smaller ASCII number than `org-lowest-priority'."
2602 :group 'org-priorities
2603 :type 'character)
2605 (defcustom org-lowest-priority ?C
2606 "The lowest priority of TODO items. A character like ?A, ?B etc.
2607 Must have a larger ASCII number than `org-highest-priority'."
2608 :group 'org-priorities
2609 :type 'character)
2611 (defcustom org-default-priority ?B
2612 "The default priority of TODO items.
2613 This is the priority an item gets if no explicit priority is given.
2614 When starting to cycle on an empty priority the first step in the cycle
2615 depends on `org-priority-start-cycle-with-default'. The resulting first
2616 step priority must not exceed the range from `org-highest-priority' to
2617 `org-lowest-priority' which means that `org-default-priority' has to be
2618 in this range exclusive or inclusive the range boundaries. Else the
2619 first step refuses to set the default and the second will fall back
2620 to (depending on the command used) the highest or lowest priority."
2621 :group 'org-priorities
2622 :type 'character)
2624 (defcustom org-priority-start-cycle-with-default t
2625 "Non-nil means start with default priority when starting to cycle.
2626 When this is nil, the first step in the cycle will be (depending on the
2627 command used) one higher or lower than the default priority.
2628 See also `org-default-priority'."
2629 :group 'org-priorities
2630 :type 'boolean)
2632 (defcustom org-get-priority-function nil
2633 "Function to extract the priority from a string.
2634 The string is normally the headline. If this is nil Org computes the
2635 priority from the priority cookie like [#A] in the headline. It returns
2636 an integer, increasing by 1000 for each priority level.
2637 The user can set a different function here, which should take a string
2638 as an argument and return the numeric priority."
2639 :group 'org-priorities
2640 :version "24.1"
2641 :type 'function)
2643 (defgroup org-time nil
2644 "Options concerning time stamps and deadlines in Org-mode."
2645 :tag "Org Time"
2646 :group 'org)
2648 (defcustom org-insert-labeled-timestamps-at-point nil
2649 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2650 When nil, these labeled time stamps are forces into the second line of an
2651 entry, just after the headline. When scheduling from the global TODO list,
2652 the time stamp will always be forced into the second line."
2653 :group 'org-time
2654 :type 'boolean)
2656 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2657 "Formats for `format-time-string' which are used for time stamps.
2658 It is not recommended to change this constant.")
2660 (defcustom org-time-stamp-rounding-minutes '(0 5)
2661 "Number of minutes to round time stamps to.
2662 These are two values, the first applies when first creating a time stamp.
2663 The second applies when changing it with the commands `S-up' and `S-down'.
2664 When changing the time stamp, this means that it will change in steps
2665 of N minutes, as given by the second value.
2667 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2668 numbers should be factors of 60, so for example 5, 10, 15.
2670 When this is larger than 1, you can still force an exact time stamp by using
2671 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2672 and by using a prefix arg to `S-up/down' to specify the exact number
2673 of minutes to shift."
2674 :group 'org-time
2675 :get #'(lambda (var) ; Make sure both elements are there
2676 (if (integerp (default-value var))
2677 (list (default-value var) 5)
2678 (default-value var)))
2679 :type '(list
2680 (integer :tag "when inserting times")
2681 (integer :tag "when modifying times")))
2683 ;; Normalize old customizations of this variable.
2684 (when (integerp org-time-stamp-rounding-minutes)
2685 (setq org-time-stamp-rounding-minutes
2686 (list org-time-stamp-rounding-minutes
2687 org-time-stamp-rounding-minutes)))
2689 (defcustom org-display-custom-times nil
2690 "Non-nil means overlay custom formats over all time stamps.
2691 The formats are defined through the variable `org-time-stamp-custom-formats'.
2692 To turn this on on a per-file basis, insert anywhere in the file:
2693 #+STARTUP: customtime"
2694 :group 'org-time
2695 :set 'set-default
2696 :type 'sexp)
2697 (make-variable-buffer-local 'org-display-custom-times)
2699 (defcustom org-time-stamp-custom-formats
2700 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2701 "Custom formats for time stamps. See `format-time-string' for the syntax.
2702 These are overlaid over the default ISO format if the variable
2703 `org-display-custom-times' is set. Time like %H:%M should be at the
2704 end of the second format. The custom formats are also honored by export
2705 commands, if custom time display is turned on at the time of export."
2706 :group 'org-time
2707 :type 'sexp)
2709 (defun org-time-stamp-format (&optional long inactive)
2710 "Get the right format for a time string."
2711 (let ((f (if long (cdr org-time-stamp-formats)
2712 (car org-time-stamp-formats))))
2713 (if inactive
2714 (concat "[" (substring f 1 -1) "]")
2715 f)))
2717 (defcustom org-time-clocksum-format "%d:%02d"
2718 "The format string used when creating CLOCKSUM lines.
2719 This is also used when org-mode generates a time duration."
2720 :group 'org-time
2721 :type 'string)
2723 (defcustom org-time-clocksum-use-fractional nil
2724 "If non-nil, \\[org-clock-display] uses fractional times.
2725 org-mode generates a time duration."
2726 :group 'org-time
2727 :type 'boolean)
2729 (defcustom org-time-clocksum-fractional-format "%.2f"
2730 "The format string used when creating CLOCKSUM lines, or when
2731 org-mode generates a time duration."
2732 :group 'org-time
2733 :type 'string)
2735 (defcustom org-deadline-warning-days 14
2736 "No. of days before expiration during which a deadline becomes active.
2737 This variable governs the display in sparse trees and in the agenda.
2738 When 0 or negative, it means use this number (the absolute value of it)
2739 even if a deadline has a different individual lead time specified.
2741 Custom commands can set this variable in the options section."
2742 :group 'org-time
2743 :group 'org-agenda-daily/weekly
2744 :type 'integer)
2746 (defcustom org-read-date-prefer-future t
2747 "Non-nil means assume future for incomplete date input from user.
2748 This affects the following situations:
2749 1. The user gives a month but not a year.
2750 For example, if it is April and you enter \"feb 2\", this will be read
2751 as Feb 2, *next* year. \"May 5\", however, will be this year.
2752 2. The user gives a day, but no month.
2753 For example, if today is the 15th, and you enter \"3\", Org-mode will
2754 read this as the third of *next* month. However, if you enter \"17\",
2755 it will be considered as *this* month.
2757 If you set this variable to the symbol `time', then also the following
2758 will work:
2760 3. If the user gives a time.
2761 If the time is before now, it will be interpreted as tomorrow.
2763 Currently none of this works for ISO week specifications.
2765 When this option is nil, the current day, month and year will always be
2766 used as defaults.
2768 See also `org-agenda-jump-prefer-future'."
2769 :group 'org-time
2770 :type '(choice
2771 (const :tag "Never" nil)
2772 (const :tag "Check month and day" t)
2773 (const :tag "Check month, day, and time" time)))
2775 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2776 "Should the agenda jump command prefer the future for incomplete dates?
2777 The default is to do the same as configured in `org-read-date-prefer-future'.
2778 But you can also set a deviating value here.
2779 This may t or nil, or the symbol `org-read-date-prefer-future'."
2780 :group 'org-agenda
2781 :group 'org-time
2782 :version "24.1"
2783 :type '(choice
2784 (const :tag "Use org-read-date-prefer-future"
2785 org-read-date-prefer-future)
2786 (const :tag "Never" nil)
2787 (const :tag "Always" t)))
2789 (defcustom org-read-date-force-compatible-dates t
2790 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2792 Depending on the system Emacs is running on, certain dates cannot
2793 be represented with the type used internally to represent time.
2794 Dates between 1970-1-1 and 2038-1-1 can always be represented
2795 correctly. Some systems allow for earlier dates, some for later,
2796 some for both. One way to find out it to insert any date into an
2797 Org buffer, putting the cursor on the year and hitting S-up and
2798 S-down to test the range.
2800 When this variable is set to t, the date/time prompt will not let
2801 you specify dates outside the 1970-2037 range, so it is certain that
2802 these dates will work in whatever version of Emacs you are
2803 running, and also that you can move a file from one Emacs implementation
2804 to another. WHenever Org is forcing the year for you, it will display
2805 a message and beep.
2807 When this variable is nil, Org will check if the date is
2808 representable in the specific Emacs implementation you are using.
2809 If not, it will force a year, usually the current year, and beep
2810 to remind you. Currently this setting is not recommended because
2811 the likelihood that you will open your Org files in an Emacs that
2812 has limited date range is not negligible.
2814 A workaround for this problem is to use diary sexp dates for time
2815 stamps outside of this range."
2816 :group 'org-time
2817 :version "24.1"
2818 :type 'boolean)
2820 (defcustom org-read-date-display-live t
2821 "Non-nil means display current interpretation of date prompt live.
2822 This display will be in an overlay, in the minibuffer."
2823 :group 'org-time
2824 :type 'boolean)
2826 (defcustom org-read-date-popup-calendar t
2827 "Non-nil means pop up a calendar when prompting for a date.
2828 In the calendar, the date can be selected with mouse-1. However, the
2829 minibuffer will also be active, and you can simply enter the date as well.
2830 When nil, only the minibuffer will be available."
2831 :group 'org-time
2832 :type 'boolean)
2833 (if (fboundp 'defvaralias)
2834 (defvaralias 'org-popup-calendar-for-date-prompt
2835 'org-read-date-popup-calendar))
2837 (defcustom org-read-date-minibuffer-setup-hook nil
2838 "Hook to be used to set up keys for the date/time interface.
2839 Add key definitions to `minibuffer-local-map', which will be a temporary
2840 copy."
2841 :group 'org-time
2842 :type 'hook)
2844 (defcustom org-extend-today-until 0
2845 "The hour when your day really ends. Must be an integer.
2846 This has influence for the following applications:
2847 - When switching the agenda to \"today\". It it is still earlier than
2848 the time given here, the day recognized as TODAY is actually yesterday.
2849 - When a date is read from the user and it is still before the time given
2850 here, the current date and time will be assumed to be yesterday, 23:59.
2851 Also, timestamps inserted in capture templates follow this rule.
2853 IMPORTANT: This is a feature whose implementation is and likely will
2854 remain incomplete. Really, it is only here because past midnight seems to
2855 be the favorite working time of John Wiegley :-)"
2856 :group 'org-time
2857 :type 'integer)
2859 (defcustom org-use-effective-time nil
2860 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2861 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2862 \"effective time\" of any timestamps between midnight and 8am will be
2863 23:59 of the previous day."
2864 :group 'org-time
2865 :version "24.1"
2866 :type 'boolean)
2868 (defcustom org-use-last-clock-out-time-as-effective-time nil
2869 "When non-nil, use the last clock out time for `org-todo'.
2870 Note that this option has precedence over the combined use of
2871 `org-use-effective-time' and `org-extend-today-until'."
2872 :group 'org-time
2873 ;; :version "24.3"
2874 :type 'boolean)
2876 (defcustom org-edit-timestamp-down-means-later nil
2877 "Non-nil means S-down will increase the time in a time stamp.
2878 When nil, S-up will increase."
2879 :group 'org-time
2880 :type 'boolean)
2882 (defcustom org-calendar-follow-timestamp-change t
2883 "Non-nil means make the calendar window follow timestamp changes.
2884 When a timestamp is modified and the calendar window is visible, it will be
2885 moved to the new date."
2886 :group 'org-time
2887 :type 'boolean)
2889 (defgroup org-tags nil
2890 "Options concerning tags in Org-mode."
2891 :tag "Org Tags"
2892 :group 'org)
2894 (defcustom org-tag-alist nil
2895 "List of tags allowed in Org-mode files.
2896 When this list is nil, Org-mode will base TAG input on what is already in the
2897 buffer.
2898 The value of this variable is an alist, the car of each entry must be a
2899 keyword as a string, the cdr may be a character that is used to select
2900 that tag through the fast-tag-selection interface.
2901 See the manual for details."
2902 :group 'org-tags
2903 :type '(repeat
2904 (choice
2905 (cons (string :tag "Tag name")
2906 (character :tag "Access char"))
2907 (list :tag "Start radio group"
2908 (const :startgroup)
2909 (option (string :tag "Group description")))
2910 (list :tag "End radio group"
2911 (const :endgroup)
2912 (option (string :tag "Group description")))
2913 (const :tag "New line" (:newline)))))
2915 (defcustom org-tag-persistent-alist nil
2916 "List of tags that will always appear in all Org-mode files.
2917 This is in addition to any in buffer settings or customizations
2918 of `org-tag-alist'.
2919 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2920 The value of this variable is an alist, the car of each entry must be a
2921 keyword as a string, the cdr may be a character that is used to select
2922 that tag through the fast-tag-selection interface.
2923 See the manual for details.
2924 To disable these tags on a per-file basis, insert anywhere in the file:
2925 #+STARTUP: noptag"
2926 :group 'org-tags
2927 :type '(repeat
2928 (choice
2929 (cons (string :tag "Tag name")
2930 (character :tag "Access char"))
2931 (const :tag "Start radio group" (:startgroup))
2932 (const :tag "End radio group" (:endgroup))
2933 (const :tag "New line" (:newline)))))
2935 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2936 "If non-nil, always offer completion for all tags of all agenda files.
2937 Instead of customizing this variable directly, you might want to
2938 set it locally for capture buffers, because there no list of
2939 tags in that file can be created dynamically (there are none).
2941 (add-hook 'org-capture-mode-hook
2942 (lambda ()
2943 (set (make-local-variable
2944 'org-complete-tags-always-offer-all-agenda-tags)
2945 t)))"
2946 :group 'org-tags
2947 :version "24.1"
2948 :type 'boolean)
2950 (defvar org-file-tags nil
2951 "List of tags that can be inherited by all entries in the file.
2952 The tags will be inherited if the variable `org-use-tag-inheritance'
2953 says they should be.
2954 This variable is populated from #+FILETAGS lines.")
2956 (defcustom org-use-fast-tag-selection 'auto
2957 "Non-nil means use fast tag selection scheme.
2958 This is a special interface to select and deselect tags with single keys.
2959 When nil, fast selection is never used.
2960 When the symbol `auto', fast selection is used if and only if selection
2961 characters for tags have been configured, either through the variable
2962 `org-tag-alist' or through a #+TAGS line in the buffer.
2963 When t, fast selection is always used and selection keys are assigned
2964 automatically if necessary."
2965 :group 'org-tags
2966 :type '(choice
2967 (const :tag "Always" t)
2968 (const :tag "Never" nil)
2969 (const :tag "When selection characters are configured" 'auto)))
2971 (defcustom org-fast-tag-selection-single-key nil
2972 "Non-nil means fast tag selection exits after first change.
2973 When nil, you have to press RET to exit it.
2974 During fast tag selection, you can toggle this flag with `C-c'.
2975 This variable can also have the value `expert'. In this case, the window
2976 displaying the tags menu is not even shown, until you press C-c again."
2977 :group 'org-tags
2978 :type '(choice
2979 (const :tag "No" nil)
2980 (const :tag "Yes" t)
2981 (const :tag "Expert" expert)))
2983 (defvar org-fast-tag-selection-include-todo nil
2984 "Non-nil means fast tags selection interface will also offer TODO states.
2985 This is an undocumented feature, you should not rely on it.")
2987 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2988 "The column to which tags should be indented in a headline.
2989 If this number is positive, it specifies the column. If it is negative,
2990 it means that the tags should be flushright to that column. For example,
2991 -80 works well for a normal 80 character screen.
2992 When 0, place tags directly after headline text, with only one space in
2993 between."
2994 :group 'org-tags
2995 :type 'integer)
2997 (defcustom org-auto-align-tags t
2998 "Non-nil keeps tags aligned when modifying headlines.
2999 Some operations (i.e. demoting) change the length of a headline and
3000 therefore shift the tags around. With this option turned on, after
3001 each such operation the tags are again aligned to `org-tags-column'."
3002 :group 'org-tags
3003 :type 'boolean)
3005 (defcustom org-use-tag-inheritance t
3006 "Non-nil means tags in levels apply also for sublevels.
3007 When nil, only the tags directly given in a specific line apply there.
3008 This may also be a list of tags that should be inherited, or a regexp that
3009 matches tags that should be inherited. Additional control is possible
3010 with the variable `org-tags-exclude-from-inheritance' which gives an
3011 explicit list of tags to be excluded from inheritance., even if the value of
3012 `org-use-tag-inheritance' would select it for inheritance.
3014 If this option is t, a match early-on in a tree can lead to a large
3015 number of matches in the subtree when constructing the agenda or creating
3016 a sparse tree. If you only want to see the first match in a tree during
3017 a search, check out the variable `org-tags-match-list-sublevels'."
3018 :group 'org-tags
3019 :type '(choice
3020 (const :tag "Not" nil)
3021 (const :tag "Always" t)
3022 (repeat :tag "Specific tags" (string :tag "Tag"))
3023 (regexp :tag "Tags matched by regexp")))
3025 (defcustom org-tags-exclude-from-inheritance nil
3026 "List of tags that should never be inherited.
3027 This is a way to exclude a few tags from inheritance. For way to do
3028 the opposite, to actively allow inheritance for selected tags,
3029 see the variable `org-use-tag-inheritance'."
3030 :group 'org-tags
3031 :type '(repeat (string :tag "Tag")))
3033 (defun org-tag-inherit-p (tag)
3034 "Check if TAG is one that should be inherited."
3035 (cond
3036 ((member tag org-tags-exclude-from-inheritance) nil)
3037 ((eq org-use-tag-inheritance t) t)
3038 ((not org-use-tag-inheritance) nil)
3039 ((stringp org-use-tag-inheritance)
3040 (string-match org-use-tag-inheritance tag))
3041 ((listp org-use-tag-inheritance)
3042 (member tag org-use-tag-inheritance))
3043 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3045 (defcustom org-tags-match-list-sublevels t
3046 "Non-nil means list also sublevels of headlines matching a search.
3047 This variable applies to tags/property searches, and also to stuck
3048 projects because this search is based on a tags match as well.
3050 When set to the symbol `indented', sublevels are indented with
3051 leading dots.
3053 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3054 the sublevels of a headline matching a tag search often also match
3055 the same search. Listing all of them can create very long lists.
3056 Setting this variable to nil causes subtrees of a match to be skipped.
3058 This variable is semi-obsolete and probably should always be true. It
3059 is better to limit inheritance to certain tags using the variables
3060 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3061 :group 'org-tags
3062 :type '(choice
3063 (const :tag "No, don't list them" nil)
3064 (const :tag "Yes, do list them" t)
3065 (const :tag "List them, indented with leading dots" indented)))
3067 (defcustom org-tags-sort-function nil
3068 "When set, tags are sorted using this function as a comparator."
3069 :group 'org-tags
3070 :type '(choice
3071 (const :tag "No sorting" nil)
3072 (const :tag "Alphabetical" string<)
3073 (const :tag "Reverse alphabetical" string>)
3074 (function :tag "Custom function" nil)))
3076 (defvar org-tags-history nil
3077 "History of minibuffer reads for tags.")
3078 (defvar org-last-tags-completion-table nil
3079 "The last used completion table for tags.")
3080 (defvar org-after-tags-change-hook nil
3081 "Hook that is run after the tags in a line have changed.")
3083 (defgroup org-properties nil
3084 "Options concerning properties in Org-mode."
3085 :tag "Org Properties"
3086 :group 'org)
3088 (defcustom org-property-format "%-10s %s"
3089 "How property key/value pairs should be formatted by `indent-line'.
3090 When `indent-line' hits a property definition, it will format the line
3091 according to this format, mainly to make sure that the values are
3092 lined-up with respect to each other."
3093 :group 'org-properties
3094 :type 'string)
3096 (defcustom org-properties-postprocess-alist nil
3097 "Alist of properties and functions to adjust inserted values.
3098 Elements of this alist must be of the form
3100 ([string] [function])
3102 where [string] must be a property name and [function] must be a
3103 lambda expression: this lambda expression must take one argument,
3104 the value to adjust, and return the new value as a string.
3106 For example, this element will allow the property \"Remaining\"
3107 to be updated wrt the relation between the \"Effort\" property
3108 and the clock summary:
3110 ((\"Remaining\" (lambda(value)
3111 (let ((clocksum (org-clock-sum-current-item))
3112 (effort (org-duration-string-to-minutes
3113 (org-entry-get (point) \"Effort\"))))
3114 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3115 :group 'org-properties
3116 :version "24.1"
3117 :type '(alist :key-type (string :tag "Property")
3118 :value-type (function :tag "Function")))
3120 (defcustom org-use-property-inheritance nil
3121 "Non-nil means properties apply also for sublevels.
3123 This setting is chiefly used during property searches. Turning it on can
3124 cause significant overhead when doing a search, which is why it is not
3125 on by default.
3127 When nil, only the properties directly given in the current entry count.
3128 When t, every property is inherited. The value may also be a list of
3129 properties that should have inheritance, or a regular expression matching
3130 properties that should be inherited.
3132 However, note that some special properties use inheritance under special
3133 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3134 and the properties ending in \"_ALL\" when they are used as descriptor
3135 for valid values of a property.
3137 Note for programmers:
3138 When querying an entry with `org-entry-get', you can control if inheritance
3139 should be used. By default, `org-entry-get' looks only at the local
3140 properties. You can request inheritance by setting the inherit argument
3141 to t (to force inheritance) or to `selective' (to respect the setting
3142 in this variable)."
3143 :group 'org-properties
3144 :type '(choice
3145 (const :tag "Not" nil)
3146 (const :tag "Always" t)
3147 (repeat :tag "Specific properties" (string :tag "Property"))
3148 (regexp :tag "Properties matched by regexp")))
3150 (defun org-property-inherit-p (property)
3151 "Check if PROPERTY is one that should be inherited."
3152 (cond
3153 ((eq org-use-property-inheritance t) t)
3154 ((not org-use-property-inheritance) nil)
3155 ((stringp org-use-property-inheritance)
3156 (string-match org-use-property-inheritance property))
3157 ((listp org-use-property-inheritance)
3158 (member property org-use-property-inheritance))
3159 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3161 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3162 "The default column format, if no other format has been defined.
3163 This variable can be set on the per-file basis by inserting a line
3165 #+COLUMNS: %25ITEM ....."
3166 :group 'org-properties
3167 :type 'string)
3169 (defcustom org-columns-ellipses ".."
3170 "The ellipses to be used when a field in column view is truncated.
3171 When this is the empty string, as many characters as possible are shown,
3172 but then there will be no visual indication that the field has been truncated.
3173 When this is a string of length N, the last N characters of a truncated
3174 field are replaced by this string. If the column is narrower than the
3175 ellipses string, only part of the ellipses string will be shown."
3176 :group 'org-properties
3177 :type 'string)
3179 (defcustom org-columns-modify-value-for-display-function nil
3180 "Function that modifies values for display in column view.
3181 For example, it can be used to cut out a certain part from a time stamp.
3182 The function must take 2 arguments:
3184 column-title The title of the column (*not* the property name)
3185 value The value that should be modified.
3187 The function should return the value that should be displayed,
3188 or nil if the normal value should be used."
3189 :group 'org-properties
3190 :type 'function)
3192 (defcustom org-effort-property "Effort"
3193 "The property that is being used to keep track of effort estimates.
3194 Effort estimates given in this property need to have the format H:MM."
3195 :group 'org-properties
3196 :group 'org-progress
3197 :type '(string :tag "Property"))
3199 (defconst org-global-properties-fixed
3200 '(("VISIBILITY_ALL" . "folded children content all")
3201 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3202 "List of property/value pairs that can be inherited by any entry.
3204 These are fixed values, for the preset properties. The user variable
3205 that can be used to add to this list is `org-global-properties'.
3207 The entries in this list are cons cells where the car is a property
3208 name and cdr is a string with the value. If the value represents
3209 multiple items like an \"_ALL\" property, separate the items by
3210 spaces.")
3212 (defcustom org-global-properties nil
3213 "List of property/value pairs that can be inherited by any entry.
3215 This list will be combined with the constant `org-global-properties-fixed'.
3217 The entries in this list are cons cells where the car is a property
3218 name and cdr is a string with the value.
3220 You can set buffer-local values for the same purpose in the variable
3221 `org-file-properties' this by adding lines like
3223 #+PROPERTY: NAME VALUE"
3224 :group 'org-properties
3225 :type '(repeat
3226 (cons (string :tag "Property")
3227 (string :tag "Value"))))
3229 (defvar org-file-properties nil
3230 "List of property/value pairs that can be inherited by any entry.
3231 Valid for the current buffer.
3232 This variable is populated from #+PROPERTY lines.")
3233 (make-variable-buffer-local 'org-file-properties)
3235 (defgroup org-agenda nil
3236 "Options concerning agenda views in Org-mode."
3237 :tag "Org Agenda"
3238 :group 'org)
3240 (defvar org-category nil
3241 "Variable used by org files to set a category for agenda display.
3242 Such files should use a file variable to set it, for example
3244 # -*- mode: org; org-category: \"ELisp\"
3246 or contain a special line
3248 #+CATEGORY: ELisp
3250 If the file does not specify a category, then file's base name
3251 is used instead.")
3252 (make-variable-buffer-local 'org-category)
3253 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3255 (defcustom org-agenda-files nil
3256 "The files to be used for agenda display.
3257 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3258 \\[org-remove-file]. You can also use customize to edit the list.
3260 If an entry is a directory, all files in that directory that are matched by
3261 `org-agenda-file-regexp' will be part of the file list.
3263 If the value of the variable is not a list but a single file name, then
3264 the list of agenda files is actually stored and maintained in that file, one
3265 agenda file per line. In this file paths can be given relative to
3266 `org-directory'. Tilde expansion and environment variable substitution
3267 are also made."
3268 :group 'org-agenda
3269 :type '(choice
3270 (repeat :tag "List of files and directories" file)
3271 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3273 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3274 "Regular expression to match files for `org-agenda-files'.
3275 If any element in the list in that variable contains a directory instead
3276 of a normal file, all files in that directory that are matched by this
3277 regular expression will be included."
3278 :group 'org-agenda
3279 :type 'regexp)
3281 (defcustom org-agenda-text-search-extra-files nil
3282 "List of extra files to be searched by text search commands.
3283 These files will be search in addition to the agenda files by the
3284 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3285 Note that these files will only be searched for text search commands,
3286 not for the other agenda views like todo lists, tag searches or the weekly
3287 agenda. This variable is intended to list notes and possibly archive files
3288 that should also be searched by these two commands.
3289 In fact, if the first element in the list is the symbol `agenda-archives',
3290 than all archive files of all agenda files will be added to the search
3291 scope."
3292 :group 'org-agenda
3293 :type '(set :greedy t
3294 (const :tag "Agenda Archives" agenda-archives)
3295 (repeat :inline t (file))))
3297 (if (fboundp 'defvaralias)
3298 (defvaralias 'org-agenda-multi-occur-extra-files
3299 'org-agenda-text-search-extra-files))
3301 (defcustom org-agenda-skip-unavailable-files nil
3302 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3303 A nil value means to remove them, after a query, from the list."
3304 :group 'org-agenda
3305 :type 'boolean)
3307 (defcustom org-calendar-to-agenda-key [?c]
3308 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3309 The command `org-calendar-goto-agenda' will be bound to this key. The
3310 default is the character `c' because then `c' can be used to switch back and
3311 forth between agenda and calendar."
3312 :group 'org-agenda
3313 :type 'sexp)
3315 (defcustom org-calendar-insert-diary-entry-key [?i]
3316 "The key to be installed in `calendar-mode-map' for adding diary entries.
3317 This option is irrelevant until `org-agenda-diary-file' has been configured
3318 to point to an Org-mode file. When that is the case, the command
3319 `org-agenda-diary-entry' will be bound to the key given here, by default
3320 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3321 if you want to continue doing this, you need to change this to a different
3322 key."
3323 :group 'org-agenda
3324 :type 'sexp)
3326 (defcustom org-agenda-diary-file 'diary-file
3327 "File to which to add new entries with the `i' key in agenda and calendar.
3328 When this is the symbol `diary-file', the functionality in the Emacs
3329 calendar will be used to add entries to the `diary-file'. But when this
3330 points to a file, `org-agenda-diary-entry' will be used instead."
3331 :group 'org-agenda
3332 :type '(choice
3333 (const :tag "The standard Emacs diary file" diary-file)
3334 (file :tag "Special Org file diary entries")))
3336 (eval-after-load "calendar"
3337 '(progn
3338 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3339 'org-calendar-goto-agenda)
3340 (add-hook 'calendar-mode-hook
3341 (lambda ()
3342 (unless (eq org-agenda-diary-file 'diary-file)
3343 (define-key calendar-mode-map
3344 org-calendar-insert-diary-entry-key
3345 'org-agenda-diary-entry))))))
3347 (defgroup org-latex nil
3348 "Options for embedding LaTeX code into Org-mode."
3349 :tag "Org LaTeX"
3350 :group 'org)
3352 (defcustom org-format-latex-options
3353 '(:foreground default :background default :scale 1.0
3354 :html-foreground "Black" :html-background "Transparent"
3355 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3356 "Options for creating images from LaTeX fragments.
3357 This is a property list with the following properties:
3358 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3359 `default' means use the foreground of the default face.
3360 `auto' means use the foreground from the text face.
3361 :background the background color, or \"Transparent\".
3362 `default' means use the background of the default face.
3363 `auto' means use the background from the text face.
3364 :scale a scaling factor for the size of the images, to get more pixels
3365 :html-foreground, :html-background, :html-scale
3366 the same numbers for HTML export.
3367 :matchers a list indicating which matchers should be used to
3368 find LaTeX fragments. Valid members of this list are:
3369 \"begin\" find environments
3370 \"$1\" find single characters surrounded by $.$
3371 \"$\" find math expressions surrounded by $...$
3372 \"$$\" find math expressions surrounded by $$....$$
3373 \"\\(\" find math expressions surrounded by \\(...\\)
3374 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3375 :group 'org-latex
3376 :type 'plist)
3378 (defcustom org-format-latex-signal-error t
3379 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3380 When nil, just push out a message."
3381 :group 'org-latex
3382 :version "24.1"
3383 :type 'boolean)
3385 (defcustom org-latex-to-mathml-jar-file nil
3386 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3387 Use this to specify additional executable file say a jar file.
3389 When using MathToWeb as the converter, specify the full-path to
3390 your mathtoweb.jar file."
3391 :group 'org-latex
3392 :version "24.1"
3393 :type '(choice
3394 (const :tag "None" nil)
3395 (file :tag "JAR file" :must-match t)))
3397 (defcustom org-latex-to-mathml-convert-command nil
3398 "Command to convert LaTeX fragments to MathML.
3399 Replace format-specifiers in the command as noted below and use
3400 `shell-command' to convert LaTeX to MathML.
3401 %j: Executable file in fully expanded form as specified by
3402 `org-latex-to-mathml-jar-file'.
3403 %I: Input LaTeX file in fully expanded form
3404 %o: Output MathML file
3405 This command is used by `org-create-math-formula'.
3407 When using MathToWeb as the converter, set this to
3408 \"java -jar %j -unicode -force -df %o %I\"."
3409 :group 'org-latex
3410 :version "24.1"
3411 :type '(choice
3412 (const :tag "None" nil)
3413 (string :tag "\nShell command")))
3415 (defcustom org-latex-create-formula-image-program 'dvipng
3416 "Program to convert LaTeX fragments with.
3418 dvipng Process the LaTeX fragments to dvi file, then convert
3419 dvi files to png files using dvipng.
3420 This will also include processing of non-math environments.
3421 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3422 to convert pdf files to png files"
3423 :group 'org-latex
3424 :version "24.1"
3425 :type '(choice
3426 (const :tag "dvipng" dvipng)
3427 (const :tag "imagemagick" imagemagick)))
3429 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3430 "Path to store latex preview images. A relative path here creates many
3431 directories relative to the processed org files paths. An absolute path
3432 puts all preview images at the same place."
3433 :group 'org-latex
3434 :version "24.3"
3435 :type 'string)
3437 (defun org-format-latex-mathml-available-p ()
3438 "Return t if `org-latex-to-mathml-convert-command' is usable."
3439 (save-match-data
3440 (when (and (boundp 'org-latex-to-mathml-convert-command)
3441 org-latex-to-mathml-convert-command)
3442 (let ((executable (car (split-string
3443 org-latex-to-mathml-convert-command))))
3444 (when (executable-find executable)
3445 (if (string-match
3446 "%j" org-latex-to-mathml-convert-command)
3447 (file-readable-p org-latex-to-mathml-jar-file)
3448 t))))))
3450 (defcustom org-format-latex-header "\\documentclass{article}
3451 \\usepackage[usenames]{color}
3452 \\usepackage{amsmath}
3453 \\usepackage[mathscr]{eucal}
3454 \\pagestyle{empty} % do not remove
3455 \[PACKAGES]
3456 \[DEFAULT-PACKAGES]
3457 % The settings below are copied from fullpage.sty
3458 \\setlength{\\textwidth}{\\paperwidth}
3459 \\addtolength{\\textwidth}{-3cm}
3460 \\setlength{\\oddsidemargin}{1.5cm}
3461 \\addtolength{\\oddsidemargin}{-2.54cm}
3462 \\setlength{\\evensidemargin}{\\oddsidemargin}
3463 \\setlength{\\textheight}{\\paperheight}
3464 \\addtolength{\\textheight}{-\\headheight}
3465 \\addtolength{\\textheight}{-\\headsep}
3466 \\addtolength{\\textheight}{-\\footskip}
3467 \\addtolength{\\textheight}{-3cm}
3468 \\setlength{\\topmargin}{1.5cm}
3469 \\addtolength{\\topmargin}{-2.54cm}"
3470 "The document header used for processing LaTeX fragments.
3471 It is imperative that this header make sure that no page number
3472 appears on the page. The package defined in the variables
3473 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3474 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3475 will be appended."
3476 :group 'org-latex
3477 :type 'string)
3479 (defvar org-format-latex-header-extra nil)
3481 (defun org-set-packages-alist (var val)
3482 "Set the packages alist and make sure it has 3 elements per entry."
3483 (set var (mapcar (lambda (x)
3484 (if (and (consp x) (= (length x) 2))
3485 (list (car x) (nth 1 x) t)
3487 val)))
3489 (defun org-get-packages-alist (var)
3491 "Get the packages alist and make sure it has 3 elements per entry."
3492 (mapcar (lambda (x)
3493 (if (and (consp x) (= (length x) 2))
3494 (list (car x) (nth 1 x) t)
3496 (default-value var)))
3498 ;; The following variables are defined here because is it also used
3499 ;; when formatting latex fragments. Originally it was part of the
3500 ;; LaTeX exporter, which is why the name includes "export".
3501 (defcustom org-export-latex-default-packages-alist
3502 '(("AUTO" "inputenc" t)
3503 ("T1" "fontenc" t)
3504 ("" "fixltx2e" nil)
3505 ("" "graphicx" t)
3506 ("" "longtable" nil)
3507 ("" "float" nil)
3508 ("" "wrapfig" nil)
3509 ("" "soul" t)
3510 ("" "textcomp" t)
3511 ("" "marvosym" t)
3512 ("" "wasysym" t)
3513 ("" "latexsym" t)
3514 ("" "amssymb" t)
3515 ("" "hyperref" nil)
3516 "\\tolerance=1000"
3518 "Alist of default packages to be inserted in the header.
3519 Change this only if one of the packages here causes an incompatibility
3520 with another package you are using.
3521 The packages in this list are needed by one part or another of Org-mode
3522 to function properly.
3524 - inputenc, fontenc: for basic font and character selection
3525 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3526 for interpreting the entities in `org-entities'. You can skip some of these
3527 packages if you don't use any of the symbols in it.
3528 - graphicx: for including images
3529 - float, wrapfig: for figure placement
3530 - longtable: for long tables
3531 - hyperref: for cross references
3533 Therefore you should not modify this variable unless you know what you
3534 are doing. The one reason to change it anyway is that you might be loading
3535 some other package that conflicts with one of the default packages.
3536 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3537 If SNIPPET-FLAG is t, the package also needs to be included when
3538 compiling LaTeX snippets into images for inclusion into HTML."
3539 :group 'org-export-latex
3540 :set 'org-set-packages-alist
3541 :get 'org-get-packages-alist
3542 :version "24.1"
3543 :type '(repeat
3544 (choice
3545 (list :tag "options/package pair"
3546 (string :tag "options")
3547 (string :tag "package")
3548 (boolean :tag "Snippet"))
3549 (string :tag "A line of LaTeX"))))
3551 (defcustom org-export-latex-packages-alist nil
3552 "Alist of packages to be inserted in every LaTeX header.
3553 These will be inserted after `org-export-latex-default-packages-alist'.
3554 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3555 SNIPPET-FLAG, when t, indicates that this package is also needed when
3556 turning LaTeX snippets into images for inclusion into HTML.
3557 Make sure that you only list packages here which:
3558 - you want in every file
3559 - do not conflict with the default packages in
3560 `org-export-latex-default-packages-alist'
3561 - do not conflict with the setup in `org-format-latex-header'."
3562 :group 'org-export-latex
3563 :set 'org-set-packages-alist
3564 :get 'org-get-packages-alist
3565 :type '(repeat
3566 (choice
3567 (list :tag "options/package pair"
3568 (string :tag "options")
3569 (string :tag "package")
3570 (boolean :tag "Snippet"))
3571 (string :tag "A line of LaTeX"))))
3574 (defgroup org-appearance nil
3575 "Settings for Org-mode appearance."
3576 :tag "Org Appearance"
3577 :group 'org)
3579 (defcustom org-level-color-stars-only nil
3580 "Non-nil means fontify only the stars in each headline.
3581 When nil, the entire headline is fontified.
3582 Changing it requires restart of `font-lock-mode' to become effective
3583 also in regions already fontified."
3584 :group 'org-appearance
3585 :type 'boolean)
3587 (defcustom org-hide-leading-stars nil
3588 "Non-nil means hide the first N-1 stars in a headline.
3589 This works by using the face `org-hide' for these stars. This
3590 face is white for a light background, and black for a dark
3591 background. You may have to customize the face `org-hide' to
3592 make this work.
3593 Changing it requires restart of `font-lock-mode' to become effective
3594 also in regions already fontified.
3595 You may also set this on a per-file basis by adding one of the following
3596 lines to the buffer:
3598 #+STARTUP: hidestars
3599 #+STARTUP: showstars"
3600 :group 'org-appearance
3601 :type 'boolean)
3603 (defcustom org-hidden-keywords nil
3604 "List of symbols corresponding to keywords to be hidden the org buffer.
3605 For example, a value '(title) for this list will make the document's title
3606 appear in the buffer without the initial #+TITLE: keyword."
3607 :group 'org-appearance
3608 :version "24.1"
3609 :type '(set (const :tag "#+AUTHOR" author)
3610 (const :tag "#+DATE" date)
3611 (const :tag "#+EMAIL" email)
3612 (const :tag "#+TITLE" title)))
3614 (defcustom org-custom-properties nil
3615 "List of properties (as strings) with a special meaning.
3616 The default use of these custom properties is to let the user
3617 hide them with `org-toggle-custom-properties-visibility'."
3618 :group 'org-properties
3619 :group 'org-appearance
3620 :version "24.3"
3621 :type '(repeat (string :tag "Property Name")))
3623 (defcustom org-fontify-done-headline nil
3624 "Non-nil means change the face of a headline if it is marked DONE.
3625 Normally, only the TODO/DONE keyword indicates the state of a headline.
3626 When this is non-nil, the headline after the keyword is set to the
3627 `org-headline-done' as an additional indication."
3628 :group 'org-appearance
3629 :type 'boolean)
3631 (defcustom org-fontify-emphasized-text t
3632 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3633 Changing this variable requires a restart of Emacs to take effect."
3634 :group 'org-appearance
3635 :type 'boolean)
3637 (defcustom org-fontify-whole-heading-line nil
3638 "Non-nil means fontify the whole line for headings.
3639 This is useful when setting a background color for the
3640 org-level-* faces."
3641 :group 'org-appearance
3642 :type 'boolean)
3644 (defcustom org-highlight-latex-fragments-and-specials nil
3645 "Non-nil means fontify what is treated specially by the exporters."
3646 :group 'org-appearance
3647 :type 'boolean)
3649 (defcustom org-hide-emphasis-markers nil
3650 "Non-nil mean font-lock should hide the emphasis marker characters."
3651 :group 'org-appearance
3652 :type 'boolean)
3654 (defcustom org-pretty-entities nil
3655 "Non-nil means show entities as UTF8 characters.
3656 When nil, the \\name form remains in the buffer."
3657 :group 'org-appearance
3658 :version "24.1"
3659 :type 'boolean)
3661 (defcustom org-pretty-entities-include-sub-superscripts t
3662 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3663 :group 'org-appearance
3664 :version "24.1"
3665 :type 'boolean)
3667 (defvar org-emph-re nil
3668 "Regular expression for matching emphasis.
3669 After a match, the match groups contain these elements:
3670 0 The match of the full regular expression, including the characters
3671 before and after the proper match
3672 1 The character before the proper match, or empty at beginning of line
3673 2 The proper match, including the leading and trailing markers
3674 3 The leading marker like * or /, indicating the type of highlighting
3675 4 The text between the emphasis markers, not including the markers
3676 5 The character after the match, empty at the end of a line")
3677 (defvar org-verbatim-re nil
3678 "Regular expression for matching verbatim text.")
3679 (defvar org-emphasis-regexp-components) ; defined just below
3680 (defvar org-emphasis-alist) ; defined just below
3681 (defun org-set-emph-re (var val)
3682 "Set variable and compute the emphasis regular expression."
3683 (set var val)
3684 (when (and (boundp 'org-emphasis-alist)
3685 (boundp 'org-emphasis-regexp-components)
3686 org-emphasis-alist org-emphasis-regexp-components)
3687 (let* ((e org-emphasis-regexp-components)
3688 (pre (car e))
3689 (post (nth 1 e))
3690 (border (nth 2 e))
3691 (body (nth 3 e))
3692 (nl (nth 4 e))
3693 (body1 (concat body "*?"))
3694 (markers (mapconcat 'car org-emphasis-alist ""))
3695 (vmarkers (mapconcat
3696 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3697 org-emphasis-alist "")))
3698 ;; make sure special characters appear at the right position in the class
3699 (if (string-match "\\^" markers)
3700 (setq markers (concat (replace-match "" t t markers) "^")))
3701 (if (string-match "-" markers)
3702 (setq markers (concat (replace-match "" t t markers) "-")))
3703 (if (string-match "\\^" vmarkers)
3704 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3705 (if (string-match "-" vmarkers)
3706 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3707 (if (> nl 0)
3708 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3709 (int-to-string nl) "\\}")))
3710 ;; Make the regexp
3711 (setq org-emph-re
3712 (concat "\\([" pre "]\\|^\\)"
3713 "\\("
3714 "\\([" markers "]\\)"
3715 "\\("
3716 "[^" border "]\\|"
3717 "[^" border "]"
3718 body1
3719 "[^" border "]"
3720 "\\)"
3721 "\\3\\)"
3722 "\\([" post "]\\|$\\)"))
3723 (setq org-verbatim-re
3724 (concat "\\([" pre "]\\|^\\)"
3725 "\\("
3726 "\\([" vmarkers "]\\)"
3727 "\\("
3728 "[^" border "]\\|"
3729 "[^" border "]"
3730 body1
3731 "[^" border "]"
3732 "\\)"
3733 "\\3\\)"
3734 "\\([" post "]\\|$\\)")))))
3736 (defcustom org-emphasis-regexp-components
3737 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3738 "Components used to build the regular expression for emphasis.
3739 This is a list with five entries. Terminology: In an emphasis string
3740 like \" *strong word* \", we call the initial space PREMATCH, the final
3741 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3742 and \"trong wor\" is the body. The different components in this variable
3743 specify what is allowed/forbidden in each part:
3745 pre Chars allowed as prematch. Beginning of line will be allowed too.
3746 post Chars allowed as postmatch. End of line will be allowed too.
3747 border The chars *forbidden* as border characters.
3748 body-regexp A regexp like \".\" to match a body character. Don't use
3749 non-shy groups here, and don't allow newline here.
3750 newline The maximum number of newlines allowed in an emphasis exp.
3752 Use customize to modify this, or restart Emacs after changing it."
3753 :group 'org-appearance
3754 :set 'org-set-emph-re
3755 :type '(list
3756 (sexp :tag "Allowed chars in pre ")
3757 (sexp :tag "Allowed chars in post ")
3758 (sexp :tag "Forbidden chars in border ")
3759 (sexp :tag "Regexp for body ")
3760 (integer :tag "number of newlines allowed")
3761 (option (boolean :tag "Please ignore this button"))))
3763 (defcustom org-emphasis-alist
3764 `(("*" bold "<b>" "</b>")
3765 ("/" italic "<i>" "</i>")
3766 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3767 ("=" org-code "<code>" "</code>" verbatim)
3768 ("~" org-verbatim "<code>" "</code>" verbatim)
3769 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3770 "<del>" "</del>")
3772 "Special syntax for emphasized text.
3773 Text starting and ending with a special character will be emphasized, for
3774 example *bold*, _underlined_ and /italic/. This variable sets the marker
3775 characters, the face to be used by font-lock for highlighting in Org-mode
3776 Emacs buffers, and the HTML tags to be used for this.
3777 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3778 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3779 Use customize to modify this, or restart Emacs after changing it."
3780 :group 'org-appearance
3781 :set 'org-set-emph-re
3782 :type '(repeat
3783 (list
3784 (string :tag "Marker character")
3785 (choice
3786 (face :tag "Font-lock-face")
3787 (plist :tag "Face property list"))
3788 (string :tag "HTML start tag")
3789 (string :tag "HTML end tag")
3790 (option (const verbatim)))))
3792 (defvar org-protecting-blocks
3793 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3794 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3795 This is needed for font-lock setup.")
3797 ;;; Miscellaneous options
3799 (defgroup org-completion nil
3800 "Completion in Org-mode."
3801 :tag "Org Completion"
3802 :group 'org)
3804 (defcustom org-completion-use-ido nil
3805 "Non-nil means use ido completion wherever possible.
3806 Note that `ido-mode' must be active for this variable to be relevant.
3807 If you decide to turn this variable on, you might well want to turn off
3808 `org-outline-path-complete-in-steps'.
3809 See also `org-completion-use-iswitchb'."
3810 :group 'org-completion
3811 :type 'boolean)
3813 (defcustom org-completion-use-iswitchb nil
3814 "Non-nil means use iswitchb completion wherever possible.
3815 Note that `iswitchb-mode' must be active for this variable to be relevant.
3816 If you decide to turn this variable on, you might well want to turn off
3817 `org-outline-path-complete-in-steps'.
3818 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3819 :group 'org-completion
3820 :type 'boolean)
3822 (defcustom org-completion-fallback-command 'hippie-expand
3823 "The expansion command called by \\[pcomplete] in normal context.
3824 Normal means, no org-mode-specific context."
3825 :group 'org-completion
3826 :type 'function)
3828 ;;; Functions and variables from their packages
3829 ;; Declared here to avoid compiler warnings
3831 ;; XEmacs only
3832 (defvar outline-mode-menu-heading)
3833 (defvar outline-mode-menu-show)
3834 (defvar outline-mode-menu-hide)
3835 (defvar zmacs-regions) ; XEmacs regions
3837 ;; Emacs only
3838 (defvar mark-active)
3840 ;; Various packages
3841 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3842 (declare-function calendar-forward-day "cal-move" (arg))
3843 (declare-function calendar-goto-date "cal-move" (date))
3844 (declare-function calendar-goto-today "cal-move" ())
3845 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3846 (defvar calc-embedded-close-formula)
3847 (defvar calc-embedded-open-formula)
3848 (declare-function cdlatex-tab "ext:cdlatex" ())
3849 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3850 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3851 (defvar font-lock-unfontify-region-function)
3852 (declare-function iswitchb-read-buffer "iswitchb"
3853 (prompt &optional default require-match start matches-set))
3854 (defvar iswitchb-temp-buflist)
3855 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3856 (defvar org-agenda-tags-todo-honor-ignore-options)
3857 (declare-function org-agenda-skip "org-agenda" ())
3858 (declare-function
3859 org-agenda-format-item "org-agenda"
3860 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3861 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3862 (declare-function org-agenda-change-all-lines "org-agenda"
3863 (newhead hdmarker &optional fixface just-this))
3864 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3865 (declare-function org-agenda-maybe-redo "org-agenda" ())
3866 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3867 (beg end))
3868 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3869 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3870 "org-agenda" (&optional end))
3871 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3872 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3873 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3874 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3875 (declare-function org-indent-mode "org-indent" (&optional arg))
3876 (declare-function parse-time-string "parse-time" (string))
3877 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3878 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3879 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3880 (defvar remember-data-file)
3881 (defvar texmathp-why)
3882 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3883 (declare-function table--at-cell-p "table" (position &optional object at-column))
3885 (defvar w3m-current-url)
3886 (defvar w3m-current-title)
3888 (defvar org-latex-regexps)
3890 ;;; Autoload and prepare some org modules
3892 ;; Some table stuff that needs to be defined here, because it is used
3893 ;; by the functions setting up org-mode or checking for table context.
3895 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3896 "Detect an org-type or table-type table.")
3897 (defconst org-table-line-regexp "^[ \t]*|"
3898 "Detect an org-type table line.")
3899 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3900 "Detect an org-type table line.")
3901 (defconst org-table-hline-regexp "^[ \t]*|-"
3902 "Detect an org-type table hline.")
3903 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3904 "Detect a table-type table hline.")
3905 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3906 "Detect the first line outside a table when searching from within it.
3907 This works for both table types.")
3909 ;; Autoload the functions in org-table.el that are needed by functions here.
3911 (eval-and-compile
3912 (org-autoload "org-table"
3913 '(org-table-begin org-table-blank-field org-table-end)))
3915 ;;;###autoload
3916 (defun turn-on-orgtbl ()
3917 "Unconditionally turn on `orgtbl-mode'."
3918 (require 'org-table)
3919 (orgtbl-mode 1))
3921 (defun org-at-table-p (&optional table-type)
3922 "Return t if the cursor is inside an org-type table.
3923 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3924 (if org-enable-table-editor
3925 (save-excursion
3926 (beginning-of-line 1)
3927 (looking-at (if table-type org-table-any-line-regexp
3928 org-table-line-regexp)))
3929 nil))
3930 (defsubst org-table-p () (org-at-table-p))
3932 (defun org-at-table.el-p ()
3933 "Return t if and only if we are at a table.el table."
3934 (and (org-at-table-p 'any)
3935 (save-excursion
3936 (goto-char (org-table-begin 'any))
3937 (looking-at org-table1-hline-regexp))))
3938 (defun org-table-recognize-table.el ()
3939 "If there is a table.el table nearby, recognize it and move into it."
3940 (if org-table-tab-recognizes-table.el
3941 (if (org-at-table.el-p)
3942 (progn
3943 (beginning-of-line 1)
3944 (if (looking-at org-table-dataline-regexp)
3946 (if (looking-at org-table1-hline-regexp)
3947 (progn
3948 (beginning-of-line 2)
3949 (if (looking-at org-table-any-border-regexp)
3950 (beginning-of-line -1)))))
3951 (if (re-search-forward "|" (org-table-end t) t)
3952 (progn
3953 (require 'table)
3954 (if (table--at-cell-p (point))
3956 (message "recognizing table.el table...")
3957 (table-recognize-table)
3958 (message "recognizing table.el table...done")))
3959 (error "This should not happen"))
3961 nil)
3962 nil))
3964 (defun org-at-table-hline-p ()
3965 "Return t if the cursor is inside a hline in a table."
3966 (if org-enable-table-editor
3967 (save-excursion
3968 (beginning-of-line 1)
3969 (looking-at org-table-hline-regexp))
3970 nil))
3972 (defvar org-table-clean-did-remove-column nil)
3974 (defun org-table-map-tables (function &optional quietly)
3975 "Apply FUNCTION to the start of all tables in the buffer."
3976 (save-excursion
3977 (save-restriction
3978 (widen)
3979 (goto-char (point-min))
3980 (while (re-search-forward org-table-any-line-regexp nil t)
3981 (unless quietly
3982 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3983 (beginning-of-line 1)
3984 (when (and (looking-at org-table-line-regexp)
3985 ;; Exclude tables in src/example/verbatim/clocktable blocks
3986 (not (org-in-block-p '("src" "example"))))
3987 (save-excursion (funcall function))
3988 (or (looking-at org-table-line-regexp)
3989 (forward-char 1)))
3990 (re-search-forward org-table-any-border-regexp nil 1))))
3991 (unless quietly (message "Mapping tables: done")))
3993 ;; Declare and autoload functions from org-exp.el & Co
3995 (declare-function org-default-export-plist "org-exp")
3996 (declare-function org-infile-export-plist "org-exp")
3997 (declare-function org-get-current-options "org-exp")
3999 ;; Declare and autoload functions from org-agenda.el
4001 (eval-and-compile
4002 (org-autoload "org-agenda"
4003 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4005 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4006 (declare-function org-clock-update-mode-line "org-clock" ())
4007 (declare-function org-resolve-clocks "org-clock"
4008 (&optional also-non-dangling-p prompt last-valid))
4009 (defvar org-clock-start-time)
4010 (defvar org-clock-marker (make-marker)
4011 "Marker recording the last clock-in.")
4012 (defvar org-clock-hd-marker (make-marker)
4013 "Marker recording the last clock-in, but the headline position.")
4014 (defvar org-clock-heading ""
4015 "The heading of the current clock entry.")
4016 (defun org-clock-is-active ()
4017 "Return non-nil if clock is currently running.
4018 The return value is actually the clock marker."
4019 (marker-buffer org-clock-marker))
4021 (eval-and-compile
4022 (org-autoload "org-clock" '(org-clock-remove-overlays
4023 org-clock-update-time-maybe
4024 org-clocktable-shift)))
4026 (defun org-check-running-clock ()
4027 "Check if the current buffer contains the running clock.
4028 If yes, offer to stop it and to save the buffer with the changes."
4029 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4030 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4031 (buffer-name))))
4032 (org-clock-out)
4033 (when (y-or-n-p "Save changed buffer?")
4034 (save-buffer))))
4036 (defun org-clocktable-try-shift (dir n)
4037 "Check if this line starts a clock table, if yes, shift the time block."
4038 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4039 (org-clocktable-shift dir n)))
4041 ;;;###autoload
4042 (defun org-clock-persistence-insinuate ()
4043 "Set up hooks for clock persistence."
4044 (require 'org-clock)
4045 (add-hook 'org-mode-hook 'org-clock-load)
4046 (add-hook 'kill-emacs-hook 'org-clock-save))
4048 ;; Define the variable already here, to make sure we have it.
4049 (defvar org-indent-mode nil
4050 "Non-nil if Org-Indent mode is enabled.
4051 Use the command `org-indent-mode' to change this variable.")
4053 ;; Autoload archiving code
4054 ;; The stuff that is needed for cycling and tags has to be defined here.
4056 (defgroup org-archive nil
4057 "Options concerning archiving in Org-mode."
4058 :tag "Org Archive"
4059 :group 'org-structure)
4061 (defcustom org-archive-location "%s_archive::"
4062 "The location where subtrees should be archived.
4064 The value of this variable is a string, consisting of two parts,
4065 separated by a double-colon. The first part is a filename and
4066 the second part is a headline.
4068 When the filename is omitted, archiving happens in the same file.
4069 %s in the filename will be replaced by the current file
4070 name (without the directory part). Archiving to a different file
4071 is useful to keep archived entries from contributing to the
4072 Org-mode Agenda.
4074 The archived entries will be filed as subtrees of the specified
4075 headline. When the headline is omitted, the subtrees are simply
4076 filed away at the end of the file, as top-level entries. Also in
4077 the heading you can use %s to represent the file name, this can be
4078 useful when using the same archive for a number of different files.
4080 Here are a few examples:
4081 \"%s_archive::\"
4082 If the current file is Projects.org, archive in file
4083 Projects.org_archive, as top-level trees. This is the default.
4085 \"::* Archived Tasks\"
4086 Archive in the current file, under the top-level headline
4087 \"* Archived Tasks\".
4089 \"~/org/archive.org::\"
4090 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4092 \"~/org/archive.org::* From %s\"
4093 Archive in file ~/org/archive.org (absolute path), under headlines
4094 \"From FILENAME\" where file name is the current file name.
4096 \"~/org/datetree.org::datetree/* Finished Tasks\"
4097 The \"datetree/\" string is special, signifying to archive
4098 items to the datetree. Items are placed in either the CLOSED
4099 date of the item, or the current date if there is no CLOSED date.
4100 The heading will be a subentry to the current date. There doesn't
4101 need to be a heading, but there always needs to be a slash after
4102 datetree. For example, to store archived items directly in the
4103 datetree, use \"~/org/datetree.org::datetree/\".
4105 \"basement::** Finished Tasks\"
4106 Archive in file ./basement (relative path), as level 3 trees
4107 below the level 2 heading \"** Finished Tasks\".
4109 You may set this option on a per-file basis by adding to the buffer a
4110 line like
4112 #+ARCHIVE: basement::** Finished Tasks
4114 You may also define it locally for a subtree by setting an ARCHIVE property
4115 in the entry. If such a property is found in an entry, or anywhere up
4116 the hierarchy, it will be used."
4117 :group 'org-archive
4118 :type 'string)
4120 (defcustom org-archive-tag "ARCHIVE"
4121 "The tag that marks a subtree as archived.
4122 An archived subtree does not open during visibility cycling, and does
4123 not contribute to the agenda listings.
4124 After changing this, font-lock must be restarted in the relevant buffers to
4125 get the proper fontification."
4126 :group 'org-archive
4127 :group 'org-keywords
4128 :type 'string)
4130 (defcustom org-agenda-skip-archived-trees t
4131 "Non-nil means the agenda will skip any items located in archived trees.
4132 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4133 variable is no longer recommended, you should leave it at the value t.
4134 Instead, use the key `v' to cycle the archives-mode in the agenda."
4135 :group 'org-archive
4136 :group 'org-agenda-skip
4137 :type 'boolean)
4139 (defcustom org-columns-skip-archived-trees t
4140 "Non-nil means ignore archived trees when creating column view."
4141 :group 'org-archive
4142 :group 'org-properties
4143 :type 'boolean)
4145 (defcustom org-cycle-open-archived-trees nil
4146 "Non-nil means `org-cycle' will open archived trees.
4147 An archived tree is a tree marked with the tag ARCHIVE.
4148 When nil, archived trees will stay folded. You can still open them with
4149 normal outline commands like `show-all', but not with the cycling commands."
4150 :group 'org-archive
4151 :group 'org-cycle
4152 :type 'boolean)
4154 (defcustom org-sparse-tree-open-archived-trees nil
4155 "Non-nil means sparse tree construction shows matches in archived trees.
4156 When nil, matches in these trees are highlighted, but the trees are kept in
4157 collapsed state."
4158 :group 'org-archive
4159 :group 'org-sparse-trees
4160 :type 'boolean)
4162 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4163 "The default date type when building a sparse tree.
4164 When this is nil, a date is a scheduled or a deadline timestamp.
4165 Otherwise, these types are allowed:
4167 all: all timestamps
4168 active: only active timestamps (<...>)
4169 inactive: only inactive timestamps (<...)
4170 scheduled: only scheduled timestamps
4171 deadline: only deadline timestamps"
4172 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4173 (const :tag "All timestamps" all)
4174 (const :tag "Only active timestamps" active)
4175 (const :tag "Only inactive timestamps" inactive)
4176 (const :tag "Only scheduled timestamps" scheduled)
4177 (const :tag "Only deadline timestamps" deadline))
4178 :version "24.3"
4179 :group 'org-sparse-trees)
4181 (defun org-cycle-hide-archived-subtrees (state)
4182 "Re-hide all archived subtrees after a visibility state change."
4183 (when (and (not org-cycle-open-archived-trees)
4184 (not (memq state '(overview folded))))
4185 (save-excursion
4186 (let* ((globalp (memq state '(contents all)))
4187 (beg (if globalp (point-min) (point)))
4188 (end (if globalp (point-max) (org-end-of-subtree t))))
4189 (org-hide-archived-subtrees beg end)
4190 (goto-char beg)
4191 (if (looking-at (concat ".*:" org-archive-tag ":"))
4192 (message "%s" (substitute-command-keys
4193 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4195 (defun org-force-cycle-archived ()
4196 "Cycle subtree even if it is archived."
4197 (interactive)
4198 (setq this-command 'org-cycle)
4199 (let ((org-cycle-open-archived-trees t))
4200 (call-interactively 'org-cycle)))
4202 (defun org-hide-archived-subtrees (beg end)
4203 "Re-hide all archived subtrees after a visibility state change."
4204 (save-excursion
4205 (let* ((re (concat ":" org-archive-tag ":")))
4206 (goto-char beg)
4207 (while (re-search-forward re end t)
4208 (when (org-at-heading-p)
4209 (org-flag-subtree t)
4210 (org-end-of-subtree t))))))
4212 (declare-function outline-end-of-heading "outline" ())
4213 (declare-function outline-flag-region "outline" (from to flag))
4214 (defun org-flag-subtree (flag)
4215 (save-excursion
4216 (org-back-to-heading t)
4217 (outline-end-of-heading)
4218 (outline-flag-region (point)
4219 (progn (org-end-of-subtree t) (point))
4220 flag)))
4222 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4224 (eval-and-compile
4225 (org-autoload "org-archive"
4226 '(org-add-archive-files)))
4228 ;; Autoload Column View Code
4230 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4231 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4232 (declare-function org-columns-compute "org-colview" (property))
4234 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4235 '(org-columns-number-to-string
4236 org-columns-get-format-and-top-level
4237 org-columns-compute
4238 org-columns-remove-overlays))
4240 ;; Autoload ID code
4242 (declare-function org-id-store-link "org-id")
4243 (declare-function org-id-locations-load "org-id")
4244 (declare-function org-id-locations-save "org-id")
4245 (defvar org-id-track-globally)
4246 (org-autoload "org-id"
4247 '(org-id-new
4248 org-id-copy
4249 org-id-get-with-outline-path-completion
4250 org-id-get-with-outline-drilling))
4252 ;;; Variables for pre-computed regular expressions, all buffer local
4254 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4255 "Matches first line of a hidden block.")
4256 (make-variable-buffer-local 'org-drawer-regexp)
4257 (defvar org-todo-regexp nil
4258 "Matches any of the TODO state keywords.")
4259 (make-variable-buffer-local 'org-todo-regexp)
4260 (defvar org-not-done-regexp nil
4261 "Matches any of the TODO state keywords except the last one.")
4262 (make-variable-buffer-local 'org-not-done-regexp)
4263 (defvar org-not-done-heading-regexp nil
4264 "Matches a TODO headline that is not done.")
4265 (make-variable-buffer-local 'org-not-done-regexp)
4266 (defvar org-todo-line-regexp nil
4267 "Matches a headline and puts TODO state into group 2 if present.")
4268 (make-variable-buffer-local 'org-todo-line-regexp)
4269 (defvar org-complex-heading-regexp nil
4270 "Matches a headline and puts everything into groups:
4271 group 1: the stars
4272 group 2: The todo keyword, maybe
4273 group 3: Priority cookie
4274 group 4: True headline
4275 group 5: Tags")
4276 (make-variable-buffer-local 'org-complex-heading-regexp)
4277 (defvar org-complex-heading-regexp-format nil
4278 "Printf format to make regexp to match an exact headline.
4279 This regexp will match the headline of any node which has the
4280 exact headline text that is put into the format, but may have any
4281 TODO state, priority and tags.")
4282 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4283 (defvar org-todo-line-tags-regexp nil
4284 "Matches a headline and puts TODO state into group 2 if present.
4285 Also put tags into group 4 if tags are present.")
4286 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4287 (defvar org-ds-keyword-length 12
4288 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4289 (make-variable-buffer-local 'org-ds-keyword-length)
4290 (defvar org-deadline-regexp nil
4291 "Matches the DEADLINE keyword.")
4292 (make-variable-buffer-local 'org-deadline-regexp)
4293 (defvar org-deadline-time-regexp nil
4294 "Matches the DEADLINE keyword together with a time stamp.")
4295 (make-variable-buffer-local 'org-deadline-time-regexp)
4296 (defvar org-deadline-line-regexp nil
4297 "Matches the DEADLINE keyword and the rest of the line.")
4298 (make-variable-buffer-local 'org-deadline-line-regexp)
4299 (defvar org-scheduled-regexp nil
4300 "Matches the SCHEDULED keyword.")
4301 (make-variable-buffer-local 'org-scheduled-regexp)
4302 (defvar org-scheduled-time-regexp nil
4303 "Matches the SCHEDULED keyword together with a time stamp.")
4304 (make-variable-buffer-local 'org-scheduled-time-regexp)
4305 (defvar org-closed-time-regexp nil
4306 "Matches the CLOSED keyword together with a time stamp.")
4307 (make-variable-buffer-local 'org-closed-time-regexp)
4309 (defvar org-keyword-time-regexp nil
4310 "Matches any of the 4 keywords, together with the time stamp.")
4311 (make-variable-buffer-local 'org-keyword-time-regexp)
4312 (defvar org-keyword-time-not-clock-regexp nil
4313 "Matches any of the 3 keywords, together with the time stamp.")
4314 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4315 (defvar org-maybe-keyword-time-regexp nil
4316 "Matches a timestamp, possibly preceded by a keyword.")
4317 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4318 (defvar org-all-time-keywords nil
4319 "List of time keywords.")
4320 (make-variable-buffer-local 'org-all-time-keywords)
4322 (defconst org-plain-time-of-day-regexp
4323 (concat
4324 "\\(\\<[012]?[0-9]"
4325 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4326 "\\(--?"
4327 "\\(\\<[012]?[0-9]"
4328 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4329 "\\)?")
4330 "Regular expression to match a plain time or time range.
4331 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4332 groups carry important information:
4333 0 the full match
4334 1 the first time, range or not
4335 8 the second time, if it is a range.")
4337 (defconst org-plain-time-extension-regexp
4338 (concat
4339 "\\(\\<[012]?[0-9]"
4340 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4341 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4342 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4343 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4344 groups carry important information:
4345 0 the full match
4346 7 hours of duration
4347 9 minutes of duration")
4349 (defconst org-stamp-time-of-day-regexp
4350 (concat
4351 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4352 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4353 "\\(--?"
4354 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4355 "Regular expression to match a timestamp time or time range.
4356 After a match, the following groups carry important information:
4357 0 the full match
4358 1 date plus weekday, for back referencing to make sure both times are on the same day
4359 2 the first time, range or not
4360 4 the second time, if it is a range.")
4362 (defconst org-startup-options
4363 '(("fold" org-startup-folded t)
4364 ("overview" org-startup-folded t)
4365 ("nofold" org-startup-folded nil)
4366 ("showall" org-startup-folded nil)
4367 ("showeverything" org-startup-folded showeverything)
4368 ("content" org-startup-folded content)
4369 ("indent" org-startup-indented t)
4370 ("noindent" org-startup-indented nil)
4371 ("hidestars" org-hide-leading-stars t)
4372 ("showstars" org-hide-leading-stars nil)
4373 ("odd" org-odd-levels-only t)
4374 ("oddeven" org-odd-levels-only nil)
4375 ("align" org-startup-align-all-tables t)
4376 ("noalign" org-startup-align-all-tables nil)
4377 ("inlineimages" org-startup-with-inline-images t)
4378 ("noinlineimages" org-startup-with-inline-images nil)
4379 ("customtime" org-display-custom-times t)
4380 ("logdone" org-log-done time)
4381 ("lognotedone" org-log-done note)
4382 ("nologdone" org-log-done nil)
4383 ("lognoteclock-out" org-log-note-clock-out t)
4384 ("nolognoteclock-out" org-log-note-clock-out nil)
4385 ("logrepeat" org-log-repeat state)
4386 ("lognoterepeat" org-log-repeat note)
4387 ("nologrepeat" org-log-repeat nil)
4388 ("logreschedule" org-log-reschedule time)
4389 ("lognotereschedule" org-log-reschedule note)
4390 ("nologreschedule" org-log-reschedule nil)
4391 ("logredeadline" org-log-redeadline time)
4392 ("lognoteredeadline" org-log-redeadline note)
4393 ("nologredeadline" org-log-redeadline nil)
4394 ("logrefile" org-log-refile time)
4395 ("lognoterefile" org-log-refile note)
4396 ("nologrefile" org-log-refile nil)
4397 ("fninline" org-footnote-define-inline t)
4398 ("nofninline" org-footnote-define-inline nil)
4399 ("fnlocal" org-footnote-section nil)
4400 ("fnauto" org-footnote-auto-label t)
4401 ("fnprompt" org-footnote-auto-label nil)
4402 ("fnconfirm" org-footnote-auto-label confirm)
4403 ("fnplain" org-footnote-auto-label plain)
4404 ("fnadjust" org-footnote-auto-adjust t)
4405 ("nofnadjust" org-footnote-auto-adjust nil)
4406 ("constcgs" constants-unit-system cgs)
4407 ("constSI" constants-unit-system SI)
4408 ("noptag" org-tag-persistent-alist nil)
4409 ("hideblocks" org-hide-block-startup t)
4410 ("nohideblocks" org-hide-block-startup nil)
4411 ("beamer" org-startup-with-beamer-mode t)
4412 ("entitiespretty" org-pretty-entities t)
4413 ("entitiesplain" org-pretty-entities nil))
4414 "Variable associated with STARTUP options for org-mode.
4415 Each element is a list of three items: the startup options (as written
4416 in the #+STARTUP line), the corresponding variable, and the value to set
4417 this variable to if the option is found. An optional forth element PUSH
4418 means to push this value onto the list in the variable.")
4420 (defun org-update-property-plist (key val props)
4421 "Update PROPS with KEY and VAL."
4422 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4423 (key (if appending (substring key 0 (- (length key) 1)) key))
4424 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4425 (previous (cdr (assoc key props))))
4426 (if appending
4427 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4428 (cons (cons key val) remainder))))
4430 (defconst org-block-regexp
4431 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4432 "Regular expression for hiding blocks.")
4433 (defconst org-heading-keyword-regexp-format
4434 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4435 "Printf format for a regexp matching an headline with some keyword.
4436 This regexp will match the headline of any node which has the
4437 exact keyword that is put into the format. The keyword isn't in
4438 any group by default, but the stars and the body are.")
4439 (defconst org-heading-keyword-maybe-regexp-format
4440 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4441 "Printf format for a regexp matching an headline, possibly with some keyword.
4442 This regexp can match any headline with the specified keyword, or
4443 without a keyword. The keyword isn't in any group by default,
4444 but the stars and the body are.")
4446 (defun org-set-regexps-and-options ()
4447 "Precompute regular expressions for current buffer."
4448 (when (derived-mode-p 'org-mode)
4449 (org-set-local 'org-todo-kwd-alist nil)
4450 (org-set-local 'org-todo-key-alist nil)
4451 (org-set-local 'org-todo-key-trigger nil)
4452 (org-set-local 'org-todo-keywords-1 nil)
4453 (org-set-local 'org-done-keywords nil)
4454 (org-set-local 'org-todo-heads nil)
4455 (org-set-local 'org-todo-sets nil)
4456 (org-set-local 'org-todo-log-states nil)
4457 (org-set-local 'org-file-properties nil)
4458 (org-set-local 'org-file-tags nil)
4459 (let ((re (org-make-options-regexp
4460 '("CATEGORY" "TODO" "COLUMNS"
4461 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4462 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4463 "OPTIONS")
4464 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4465 (splitre "[ \t]+")
4466 (scripts org-use-sub-superscripts)
4467 kwds kws0 kwsa key log value cat arch tags const links hw dws
4468 tail sep kws1 prio props ftags drawers beamer-p
4469 ext-setup-or-nil setup-contents (start 0))
4470 (save-excursion
4471 (save-restriction
4472 (widen)
4473 (goto-char (point-min))
4474 (while (or (and ext-setup-or-nil
4475 (string-match re ext-setup-or-nil start)
4476 (setq start (match-end 0)))
4477 (and (setq ext-setup-or-nil nil start 0)
4478 (re-search-forward re nil t)))
4479 (setq key (upcase (match-string 1 ext-setup-or-nil))
4480 value (org-match-string-no-properties 2 ext-setup-or-nil))
4481 (if (stringp value) (setq value (org-trim value)))
4482 (cond
4483 ((equal key "CATEGORY")
4484 (setq cat value))
4485 ((member key '("SEQ_TODO" "TODO"))
4486 (push (cons 'sequence (org-split-string value splitre)) kwds))
4487 ((equal key "TYP_TODO")
4488 (push (cons 'type (org-split-string value splitre)) kwds))
4489 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4490 ;; general TODO-like setup
4491 (push (cons (intern (downcase (match-string 1 key)))
4492 (org-split-string value splitre)) kwds))
4493 ((equal key "TAGS")
4494 (setq tags (append tags (if tags '("\\n") nil)
4495 (org-split-string value splitre))))
4496 ((equal key "COLUMNS")
4497 (org-set-local 'org-columns-default-format value))
4498 ((equal key "LINK")
4499 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4500 (push (cons (match-string 1 value)
4501 (org-trim (match-string 2 value)))
4502 links)))
4503 ((equal key "PRIORITIES")
4504 (setq prio (org-split-string value " +")))
4505 ((equal key "PROPERTY")
4506 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4507 (setq props (org-update-property-plist (match-string 1 value)
4508 (match-string 2 value)
4509 props))))
4510 ((equal key "FILETAGS")
4511 (when (string-match "\\S-" value)
4512 (setq ftags
4513 (append
4514 ftags
4515 (apply 'append
4516 (mapcar (lambda (x) (org-split-string x ":"))
4517 (org-split-string value)))))))
4518 ((equal key "DRAWERS")
4519 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4520 ((equal key "CONSTANTS")
4521 (setq const (append const (org-split-string value splitre))))
4522 ((equal key "STARTUP")
4523 (let ((opts (org-split-string value splitre))
4524 l var val)
4525 (while (setq l (pop opts))
4526 (when (setq l (assoc l org-startup-options))
4527 (setq var (nth 1 l) val (nth 2 l))
4528 (if (not (nth 3 l))
4529 (set (make-local-variable var) val)
4530 (if (not (listp (symbol-value var)))
4531 (set (make-local-variable var) nil))
4532 (set (make-local-variable var) (symbol-value var))
4533 (add-to-list var val))))))
4534 ((equal key "ARCHIVE")
4535 (setq arch value)
4536 (remove-text-properties 0 (length arch)
4537 '(face t fontified t) arch))
4538 ((equal key "LATEX_CLASS")
4539 (setq beamer-p (equal value "beamer")))
4540 ((equal key "OPTIONS")
4541 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4542 (setq scripts (read (match-string 2 value)))))
4543 ((equal key "SETUPFILE")
4544 (setq setup-contents (org-file-contents
4545 (expand-file-name
4546 (org-remove-double-quotes value))
4547 'noerror))
4548 (if (not ext-setup-or-nil)
4549 (setq ext-setup-or-nil setup-contents start 0)
4550 (setq ext-setup-or-nil
4551 (concat (substring ext-setup-or-nil 0 start)
4552 "\n" setup-contents "\n"
4553 (substring ext-setup-or-nil start)))))))
4554 ;; search for property blocks
4555 (goto-char (point-min))
4556 (while (re-search-forward org-block-regexp nil t)
4557 (when (equal "PROPERTY" (upcase (match-string 1)))
4558 (setq value (replace-regexp-in-string
4559 "[\n\r]" " " (match-string 4)))
4560 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4561 (setq props (org-update-property-plist (match-string 1 value)
4562 (match-string 2 value)
4563 props)))))))
4564 (org-set-local 'org-use-sub-superscripts scripts)
4565 (when cat
4566 (org-set-local 'org-category (intern cat))
4567 (push (cons "CATEGORY" cat) props))
4568 (when prio
4569 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4570 (setq prio (mapcar 'string-to-char prio))
4571 (org-set-local 'org-highest-priority (nth 0 prio))
4572 (org-set-local 'org-lowest-priority (nth 1 prio))
4573 (org-set-local 'org-default-priority (nth 2 prio)))
4574 (and props (org-set-local 'org-file-properties (nreverse props)))
4575 (and ftags (org-set-local 'org-file-tags
4576 (mapcar 'org-add-prop-inherited ftags)))
4577 (and drawers (org-set-local 'org-drawers drawers))
4578 (and arch (org-set-local 'org-archive-location arch))
4579 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4580 ;; Process the TODO keywords
4581 (unless kwds
4582 ;; Use the global values as if they had been given locally.
4583 (setq kwds (default-value 'org-todo-keywords))
4584 (if (stringp (car kwds))
4585 (setq kwds (list (cons org-todo-interpretation
4586 (default-value 'org-todo-keywords)))))
4587 (setq kwds (reverse kwds)))
4588 (setq kwds (nreverse kwds))
4589 (let (inter kws kw)
4590 (while (setq kws (pop kwds))
4591 (let ((kws (or
4592 (run-hook-with-args-until-success
4593 'org-todo-setup-filter-hook kws)
4594 kws)))
4595 (setq inter (pop kws) sep (member "|" kws)
4596 kws0 (delete "|" (copy-sequence kws))
4597 kwsa nil
4598 kws1 (mapcar
4599 (lambda (x)
4600 ;; 1 2
4601 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4602 (progn
4603 (setq kw (match-string 1 x)
4604 key (and (match-end 2) (match-string 2 x))
4605 log (org-extract-log-state-settings x))
4606 (push (cons kw (and key (string-to-char key))) kwsa)
4607 (and log (push log org-todo-log-states))
4609 (error "Invalid TODO keyword %s" x)))
4610 kws0)
4611 kwsa (if kwsa (append '((:startgroup))
4612 (nreverse kwsa)
4613 '((:endgroup))))
4614 hw (car kws1)
4615 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4616 tail (list inter hw (car dws) (org-last dws))))
4617 (add-to-list 'org-todo-heads hw 'append)
4618 (push kws1 org-todo-sets)
4619 (setq org-done-keywords (append org-done-keywords dws nil))
4620 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4621 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4622 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4623 (setq org-todo-sets (nreverse org-todo-sets)
4624 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4625 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4626 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4627 ;; Process the constants
4628 (when const
4629 (let (e cst)
4630 (while (setq e (pop const))
4631 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4632 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4633 (setq org-table-formula-constants-local cst)))
4635 ;; Process the tags.
4636 (when tags
4637 (let (e tgs)
4638 (while (setq e (pop tags))
4639 (cond
4640 ((equal e "{") (push '(:startgroup) tgs))
4641 ((equal e "}") (push '(:endgroup) tgs))
4642 ((equal e "\\n") (push '(:newline) tgs))
4643 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4644 (push (cons (match-string 1 e)
4645 (string-to-char (match-string 2 e)))
4646 tgs))
4647 (t (push (list e) tgs))))
4648 (org-set-local 'org-tag-alist nil)
4649 (while (setq e (pop tgs))
4650 (or (and (stringp (car e))
4651 (assoc (car e) org-tag-alist))
4652 (push e org-tag-alist)))))
4654 ;; Compute the regular expressions and other local variables.
4655 ;; Using `org-outline-regexp-bol' would complicate them much,
4656 ;; because of the fixed white space at the end of that string.
4657 (if (not org-done-keywords)
4658 (setq org-done-keywords (and org-todo-keywords-1
4659 (list (org-last org-todo-keywords-1)))))
4660 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4661 (length org-scheduled-string)
4662 (length org-clock-string)
4663 (length org-closed-string)))
4664 org-drawer-regexp
4665 (concat "^[ \t]*:\\("
4666 (mapconcat 'regexp-quote org-drawers "\\|")
4667 "\\):[ \t]*$")
4668 org-not-done-keywords
4669 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4670 org-todo-regexp
4671 (concat "\\("
4672 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4673 "\\)")
4674 org-not-done-regexp
4675 (concat "\\("
4676 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4677 "\\)")
4678 org-not-done-heading-regexp
4679 (format org-heading-keyword-regexp-format org-not-done-regexp)
4680 org-todo-line-regexp
4681 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4682 org-complex-heading-regexp
4683 (concat "^\\(\\*+\\)"
4684 "\\(?: +" org-todo-regexp "\\)?"
4685 "\\(?: +\\(\\[#.\\]\\)\\)?"
4686 "\\(?: +\\(.*?\\)\\)??"
4687 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4688 "[ \t]*$")
4689 org-complex-heading-regexp-format
4690 (concat "^\\(\\*+\\)"
4691 "\\(?: +" org-todo-regexp "\\)?"
4692 "\\(?: +\\(\\[#.\\]\\)\\)?"
4693 "\\(?: +"
4694 ;; Stats cookies can be stuck to body.
4695 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4696 "\\(%s\\)"
4697 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4698 "\\)"
4699 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4700 "[ \t]*$")
4701 org-todo-line-tags-regexp
4702 (concat "^\\(\\*+\\)"
4703 "\\(?: +" org-todo-regexp "\\)?"
4704 "\\(?: +\\(.*?\\)\\)??"
4705 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4706 "[ \t]*$")
4707 org-deadline-regexp (concat "\\<" org-deadline-string)
4708 org-deadline-time-regexp
4709 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4710 org-deadline-line-regexp
4711 (concat "\\<\\(" org-deadline-string "\\).*")
4712 org-scheduled-regexp
4713 (concat "\\<" org-scheduled-string)
4714 org-scheduled-time-regexp
4715 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4716 org-closed-time-regexp
4717 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4718 org-keyword-time-regexp
4719 (concat "\\<\\(" org-scheduled-string
4720 "\\|" org-deadline-string
4721 "\\|" org-closed-string
4722 "\\|" org-clock-string "\\)"
4723 " *[[<]\\([^]>]+\\)[]>]")
4724 org-keyword-time-not-clock-regexp
4725 (concat "\\<\\(" org-scheduled-string
4726 "\\|" org-deadline-string
4727 "\\|" org-closed-string
4728 "\\)"
4729 " *[[<]\\([^]>]+\\)[]>]")
4730 org-maybe-keyword-time-regexp
4731 (concat "\\(\\<\\(" org-scheduled-string
4732 "\\|" org-deadline-string
4733 "\\|" org-closed-string
4734 "\\|" org-clock-string "\\)\\)?"
4735 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4736 org-all-time-keywords
4737 (mapcar (lambda (w) (substring w 0 -1))
4738 (list org-scheduled-string org-deadline-string
4739 org-clock-string org-closed-string))
4741 (org-compute-latex-and-specials-regexp)
4742 (org-set-font-lock-defaults))))
4744 (defun org-file-contents (file &optional noerror)
4745 "Return the contents of FILE, as a string."
4746 (if (or (not file)
4747 (not (file-readable-p file)))
4748 (if noerror
4749 (progn
4750 (message "Cannot read file \"%s\"" file)
4751 (ding) (sit-for 2)
4753 (error "Cannot read file \"%s\"" file))
4754 (with-temp-buffer
4755 (insert-file-contents file)
4756 (buffer-string))))
4758 (defun org-extract-log-state-settings (x)
4759 "Extract the log state setting from a TODO keyword string.
4760 This will extract info from a string like \"WAIT(w@/!)\"."
4761 (let (kw key log1 log2)
4762 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4763 (setq kw (match-string 1 x)
4764 key (and (match-end 2) (match-string 2 x))
4765 log1 (and (match-end 3) (match-string 3 x))
4766 log2 (and (match-end 4) (match-string 4 x)))
4767 (and (or log1 log2)
4768 (list kw
4769 (and log1 (if (equal log1 "!") 'time 'note))
4770 (and log2 (if (equal log2 "!") 'time 'note)))))))
4772 (defun org-remove-keyword-keys (list)
4773 "Remove a pair of parenthesis at the end of each string in LIST."
4774 (mapcar (lambda (x)
4775 (if (string-match "(.*)$" x)
4776 (substring x 0 (match-beginning 0))
4778 list))
4780 (defun org-assign-fast-keys (alist)
4781 "Assign fast keys to a keyword-key alist.
4782 Respect keys that are already there."
4783 (let (new e (alt ?0))
4784 (while (setq e (pop alist))
4785 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4786 (cdr e)) ;; Key already assigned.
4787 (push e new)
4788 (let ((clist (string-to-list (downcase (car e))))
4789 (used (append new alist)))
4790 (when (= (car clist) ?@)
4791 (pop clist))
4792 (while (and clist (rassoc (car clist) used))
4793 (pop clist))
4794 (unless clist
4795 (while (rassoc alt used)
4796 (incf alt)))
4797 (push (cons (car e) (or (car clist) alt)) new))))
4798 (nreverse new)))
4800 ;;; Some variables used in various places
4802 (defvar org-window-configuration nil
4803 "Used in various places to store a window configuration.")
4804 (defvar org-selected-window nil
4805 "Used in various places to store a window configuration.")
4806 (defvar org-finish-function nil
4807 "Function to be called when `C-c C-c' is used.
4808 This is for getting out of special buffers like capture.")
4811 ;; FIXME: Occasionally check by commenting these, to make sure
4812 ;; no other functions uses these, forgetting to let-bind them.
4813 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4814 (defvar org-last-state)
4815 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4817 ;; Defined somewhere in this file, but used before definition.
4818 (defvar org-entities) ;; defined in org-entities.el
4819 (defvar org-struct-menu)
4820 (defvar org-org-menu)
4821 (defvar org-tbl-menu)
4823 ;;;; Define the Org-mode
4825 ;; We use a before-change function to check if a table might need
4826 ;; an update.
4827 (defvar org-table-may-need-update t
4828 "Indicates that a table might need an update.
4829 This variable is set by `org-before-change-function'.
4830 `org-table-align' sets it back to nil.")
4831 (defun org-before-change-function (beg end)
4832 "Every change indicates that a table might need an update."
4833 (setq org-table-may-need-update t))
4834 (defvar org-mode-map)
4835 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4836 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4837 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4838 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4839 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4840 (defvar org-table-buffer-is-an nil)
4842 (defvar bidi-paragraph-direction)
4843 (defvar buffer-face-mode-face)
4845 (require 'outline)
4846 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4847 (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"))
4848 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4850 ;; Other stuff we need.
4851 (require 'time-date)
4852 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4853 (require 'easymenu)
4854 (require 'overlay)
4856 (require 'org-macs)
4857 (require 'org-entities)
4858 ;; (require 'org-compat) moved higher up in the file before it is first used
4859 (require 'org-faces)
4860 (require 'org-list)
4861 (require 'org-pcomplete)
4862 (require 'org-src)
4863 (require 'org-footnote)
4865 ;; babel
4866 (require 'ob)
4867 (require 'ob-table)
4868 (require 'ob-lob)
4869 (require 'ob-ref)
4870 (require 'ob-tangle)
4871 (require 'ob-comint)
4872 (require 'ob-keys)
4874 ;;;###autoload
4875 (define-derived-mode org-mode outline-mode "Org"
4876 "Outline-based notes management and organizer, alias
4877 \"Carsten's outline-mode for keeping track of everything.\"
4879 Org-mode develops organizational tasks around a NOTES file which
4880 contains information about projects as plain text. Org-mode is
4881 implemented on top of outline-mode, which is ideal to keep the content
4882 of large files well structured. It supports ToDo items, deadlines and
4883 time stamps, which magically appear in the diary listing of the Emacs
4884 calendar. Tables are easily created with a built-in table editor.
4885 Plain text URL-like links connect to websites, emails (VM), Usenet
4886 messages (Gnus), BBDB entries, and any files related to the project.
4887 For printing and sharing of notes, an Org-mode file (or a part of it)
4888 can be exported as a structured ASCII or HTML file.
4890 The following commands are available:
4892 \\{org-mode-map}"
4894 ;; Get rid of Outline menus, they are not needed
4895 ;; Need to do this here because define-derived-mode sets up
4896 ;; the keymap so late. Still, it is a waste to call this each time
4897 ;; we switch another buffer into org-mode.
4898 (if (featurep 'xemacs)
4899 (when (boundp 'outline-mode-menu-heading)
4900 ;; Assume this is Greg's port, it uses easymenu
4901 (easy-menu-remove outline-mode-menu-heading)
4902 (easy-menu-remove outline-mode-menu-show)
4903 (easy-menu-remove outline-mode-menu-hide))
4904 (define-key org-mode-map [menu-bar headings] 'undefined)
4905 (define-key org-mode-map [menu-bar hide] 'undefined)
4906 (define-key org-mode-map [menu-bar show] 'undefined))
4908 (org-load-modules-maybe)
4909 (easy-menu-add org-org-menu)
4910 (easy-menu-add org-tbl-menu)
4911 (org-install-agenda-files-menu)
4912 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4913 (add-to-invisibility-spec '(org-cwidth))
4914 (add-to-invisibility-spec '(org-hide-block . t))
4915 (when (featurep 'xemacs)
4916 (org-set-local 'line-move-ignore-invisible t))
4917 (org-set-local 'outline-regexp org-outline-regexp)
4918 (org-set-local 'outline-level 'org-outline-level)
4919 (setq bidi-paragraph-direction 'left-to-right)
4920 (when (and org-ellipsis
4921 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4922 (fboundp 'make-glyph-code))
4923 (unless org-display-table
4924 (setq org-display-table (make-display-table)))
4925 (set-display-table-slot
4926 org-display-table 4
4927 (vconcat (mapcar
4928 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4929 org-ellipsis)))
4930 (if (stringp org-ellipsis) org-ellipsis "..."))))
4931 (setq buffer-display-table org-display-table))
4932 (org-set-regexps-and-options)
4933 (when (and org-tag-faces (not org-tags-special-faces-re))
4934 ;; tag faces set outside customize.... force initialization.
4935 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4936 ;; Calc embedded
4937 (org-set-local 'calc-embedded-open-mode "# ")
4938 (modify-syntax-entry ?@ "w")
4939 (modify-syntax-entry ?\" "\"")
4940 (if org-startup-truncated (setq truncate-lines t))
4941 (org-set-local 'font-lock-unfontify-region-function
4942 'org-unfontify-region)
4943 ;; Activate before-change-function
4944 (org-set-local 'org-table-may-need-update t)
4945 (org-add-hook 'before-change-functions 'org-before-change-function nil
4946 'local)
4947 ;; Check for running clock before killing a buffer
4948 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4949 ;; Initialize macros templates.
4950 (org-macro-initialize-templates)
4951 ;; Initialize radio targets.
4952 (org-update-radio-target-regexp)
4953 ;; Indentation.
4954 (org-set-local 'indent-line-function 'org-indent-line)
4955 (org-set-local 'indent-region-function 'org-indent-region)
4956 ;; Filling and auto-filling.
4957 (org-setup-filling)
4958 ;; Comments.
4959 (org-setup-comments-handling)
4960 ;; Beginning/end of defun
4961 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4962 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4963 ;; Next error for sparse trees
4964 (org-set-local 'next-error-function 'org-occur-next-match)
4965 ;; Make sure dependence stuff works reliably, even for users who set it
4966 ;; too late :-(
4967 (if org-enforce-todo-dependencies
4968 (add-hook 'org-blocker-hook
4969 'org-block-todo-from-children-or-siblings-or-parent)
4970 (remove-hook 'org-blocker-hook
4971 'org-block-todo-from-children-or-siblings-or-parent))
4972 (if org-enforce-todo-checkbox-dependencies
4973 (add-hook 'org-blocker-hook
4974 'org-block-todo-from-checkboxes)
4975 (remove-hook 'org-blocker-hook
4976 'org-block-todo-from-checkboxes))
4978 ;; Align options lines
4979 (org-set-local
4980 'align-mode-rules-list
4981 '((org-in-buffer-settings
4982 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4983 (modes . '(org-mode)))))
4985 ;; Imenu
4986 (org-set-local 'imenu-create-index-function
4987 'org-imenu-get-tree)
4989 ;; Make isearch reveal context
4990 (if (or (featurep 'xemacs)
4991 (not (boundp 'outline-isearch-open-invisible-function)))
4992 ;; Emacs 21 and XEmacs make use of the hook
4993 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4994 ;; Emacs 22 deals with this through a special variable
4995 (org-set-local 'outline-isearch-open-invisible-function
4996 (lambda (&rest ignore) (org-show-context 'isearch))))
4998 ;; Turn on org-beamer-mode?
4999 (and org-startup-with-beamer-mode (org-beamer-mode))
5001 ;; Setup the pcomplete hooks
5002 (set (make-local-variable 'pcomplete-command-completion-function)
5003 'org-pcomplete-initial)
5004 (set (make-local-variable 'pcomplete-command-name-function)
5005 'org-command-at-point)
5006 (set (make-local-variable 'pcomplete-default-completion-function)
5007 'ignore)
5008 (set (make-local-variable 'pcomplete-parse-arguments-function)
5009 'org-parse-arguments)
5010 (set (make-local-variable 'pcomplete-termination-string) "")
5011 (when (>= emacs-major-version 23)
5012 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5014 ;; If empty file that did not turn on org-mode automatically, make it to.
5015 (if (and org-insert-mode-line-in-empty-file
5016 (org-called-interactively-p 'any)
5017 (= (point-min) (point-max)))
5018 (insert "# -*- mode: org -*-\n\n"))
5019 (unless org-inhibit-startup
5020 (when org-startup-align-all-tables
5021 (let ((bmp (buffer-modified-p)))
5022 (org-table-map-tables 'org-table-align 'quietly)
5023 (set-buffer-modified-p bmp)))
5024 (when org-startup-with-inline-images
5025 (org-display-inline-images))
5026 (when org-startup-indented
5027 (require 'org-indent)
5028 (org-indent-mode 1))
5029 (unless org-inhibit-startup-visibility-stuff
5030 (org-set-startup-visibility)))
5031 ;; Try to set org-hide correctly
5032 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5034 (when (fboundp 'abbrev-table-put)
5035 (abbrev-table-put org-mode-abbrev-table
5036 :parents (list text-mode-abbrev-table)))
5038 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5041 (defun org-find-invisible-foreground ()
5042 (let ((candidates (remove
5043 "unspecified-bg"
5044 (list
5045 (face-background 'default)
5046 (face-background 'org-default)
5047 (cdr (assoc 'background-color default-frame-alist))
5048 (cdr (assoc 'background-color initial-frame-alist))
5049 (cdr (assoc 'background-color window-system-default-frame-alist))
5050 (face-foreground 'org-hide)))))
5051 (car (remove nil candidates))))
5053 (defun org-current-time ()
5054 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5055 (if (> (car org-time-stamp-rounding-minutes) 1)
5056 (let ((r (car org-time-stamp-rounding-minutes))
5057 (time (decode-time)))
5058 (apply 'encode-time
5059 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5060 (nthcdr 2 time))))
5061 (current-time)))
5063 (defun org-today ()
5064 "Return today date, considering `org-extend-today-until'."
5065 (time-to-days
5066 (time-subtract (current-time)
5067 (list 0 (* 3600 org-extend-today-until) 0))))
5069 ;;;; Font-Lock stuff, including the activators
5071 (defvar org-mouse-map (make-sparse-keymap))
5072 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5073 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5074 (when org-mouse-1-follows-link
5075 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5076 (when org-tab-follows-link
5077 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5078 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5080 (require 'font-lock)
5082 (defconst org-non-link-chars "]\t\n\r<>")
5083 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5084 "shell" "elisp" "doi" "message"))
5085 (defvar org-link-types-re nil
5086 "Matches a link that has a url-like prefix like \"http:\"")
5087 (defvar org-link-re-with-space nil
5088 "Matches a link with spaces, optional angular brackets around it.")
5089 (defvar org-link-re-with-space2 nil
5090 "Matches a link with spaces, optional angular brackets around it.")
5091 (defvar org-link-re-with-space3 nil
5092 "Matches a link with spaces, only for internal part in bracket links.")
5093 (defvar org-angle-link-re nil
5094 "Matches link with angular brackets, spaces are allowed.")
5095 (defvar org-plain-link-re nil
5096 "Matches plain link, without spaces.")
5097 (defvar org-bracket-link-regexp nil
5098 "Matches a link in double brackets.")
5099 (defvar org-bracket-link-analytic-regexp nil
5100 "Regular expression used to analyze links.
5101 Here is what the match groups contain after a match:
5102 1: http:
5103 2: http
5104 3: path
5105 4: [desc]
5106 5: desc")
5107 (defvar org-bracket-link-analytic-regexp++ nil
5108 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5109 (defvar org-any-link-re nil
5110 "Regular expression matching any link.")
5112 (defcustom org-match-sexp-depth 3
5113 "Number of stacked braces for sub/superscript matching.
5114 This has to be set before loading org.el to be effective."
5115 :group 'org-export-translation ; ??????????????????????????/
5116 :type 'integer)
5118 (defun org-create-multibrace-regexp (left right n)
5119 "Create a regular expression which will match a balanced sexp.
5120 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5121 as single character strings.
5122 The regexp returned will match the entire expression including the
5123 delimiters. It will also define a single group which contains the
5124 match except for the outermost delimiters. The maximum depth of
5125 stacked delimiters is N. Escaping delimiters is not possible."
5126 (let* ((nothing (concat "[^" left right "]*?"))
5127 (or "\\|")
5128 (re nothing)
5129 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5130 (while (> n 1)
5131 (setq n (1- n)
5132 re (concat re or next)
5133 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5134 (concat left "\\(" re "\\)" right)))
5136 (defvar org-match-substring-regexp
5137 (concat
5138 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5139 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5140 "\\|"
5141 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5142 "\\|"
5143 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5144 "The regular expression matching a sub- or superscript.")
5146 (defvar org-match-substring-with-braces-regexp
5147 (concat
5148 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5149 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5150 "\\)")
5151 "The regular expression matching a sub- or superscript, forcing braces.")
5153 (defun org-make-link-regexps ()
5154 "Update the link regular expressions.
5155 This should be called after the variable `org-link-types' has changed."
5156 (setq org-link-types-re
5157 (concat
5158 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5159 org-link-re-with-space
5160 (concat
5161 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5162 "\\([^" org-non-link-chars " ]"
5163 "[^" org-non-link-chars "]*"
5164 "[^" org-non-link-chars " ]\\)>?")
5165 org-link-re-with-space2
5166 (concat
5167 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5168 "\\([^" org-non-link-chars " ]"
5169 "[^\t\n\r]*"
5170 "[^" org-non-link-chars " ]\\)>?")
5171 org-link-re-with-space3
5172 (concat
5173 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5174 "\\([^" org-non-link-chars " ]"
5175 "[^\t\n\r]*\\)")
5176 org-angle-link-re
5177 (concat
5178 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5179 "\\([^" org-non-link-chars " ]"
5180 "[^" org-non-link-chars "]*"
5181 "\\)>")
5182 org-plain-link-re
5183 (concat
5184 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5185 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5186 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5187 org-bracket-link-regexp
5188 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5189 org-bracket-link-analytic-regexp
5190 (concat
5191 "\\[\\["
5192 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5193 "\\([^]]+\\)"
5194 "\\]"
5195 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5196 "\\]")
5197 org-bracket-link-analytic-regexp++
5198 (concat
5199 "\\[\\["
5200 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5201 "\\([^]]+\\)"
5202 "\\]"
5203 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5204 "\\]")
5205 org-any-link-re
5206 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5207 org-angle-link-re "\\)\\|\\("
5208 org-plain-link-re "\\)")))
5210 (org-make-link-regexps)
5212 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5213 "Regular expression for fast time stamp matching.")
5214 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5215 "Regular expression for fast time stamp matching.")
5216 (defconst org-ts-regexp0
5217 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5218 "Regular expression matching time strings for analysis.
5219 This one does not require the space after the date, so it can be used
5220 on a string that terminates immediately after the date.")
5221 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5222 "Regular expression matching time strings for analysis.")
5223 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5224 "Regular expression matching time stamps, with groups.")
5225 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5226 "Regular expression matching time stamps (also [..]), with groups.")
5227 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5228 "Regular expression matching a time stamp range.")
5229 (defconst org-tr-regexp-both
5230 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5231 "Regular expression matching a time stamp range.")
5232 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5233 org-ts-regexp "\\)?")
5234 "Regular expression matching a time stamp or time stamp range.")
5235 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5236 org-ts-regexp-both "\\)?")
5237 "Regular expression matching a time stamp or time stamp range.
5238 The time stamps may be either active or inactive.")
5240 (defvar org-emph-face nil)
5242 (defun org-do-emphasis-faces (limit)
5243 "Run through the buffer and add overlays to emphasized strings."
5244 (let (rtn a)
5245 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5246 (if (not (= (char-after (match-beginning 3))
5247 (char-after (match-beginning 4))))
5248 (progn
5249 (setq rtn t)
5250 (setq a (assoc (match-string 3) org-emphasis-alist))
5251 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5252 'face
5253 (nth 1 a))
5254 (and (nth 4 a)
5255 (org-remove-flyspell-overlays-in
5256 (match-beginning 0) (match-end 0)))
5257 (add-text-properties (match-beginning 2) (match-end 2)
5258 '(font-lock-multiline t org-emphasis t))
5259 (when org-hide-emphasis-markers
5260 (add-text-properties (match-end 4) (match-beginning 5)
5261 '(invisible org-link))
5262 (add-text-properties (match-beginning 3) (match-end 3)
5263 '(invisible org-link)))))
5264 (backward-char 1))
5265 rtn))
5267 (defun org-emphasize (&optional char)
5268 "Insert or change an emphasis, i.e. a font like bold or italic.
5269 If there is an active region, change that region to a new emphasis.
5270 If there is no region, just insert the marker characters and position
5271 the cursor between them.
5272 CHAR should be either the marker character, or the first character of the
5273 HTML tag associated with that emphasis. If CHAR is a space, the means
5274 to remove the emphasis of the selected region.
5275 If char is not given (for example in an interactive call) it
5276 will be prompted for."
5277 (interactive)
5278 (let ((eal org-emphasis-alist) e det
5279 (erc org-emphasis-regexp-components)
5280 (prompt "")
5281 (string "") beg end move tag c s)
5282 (if (org-region-active-p)
5283 (setq beg (region-beginning) end (region-end)
5284 string (buffer-substring beg end))
5285 (setq move t))
5287 (while (setq e (pop eal))
5288 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5289 c (aref tag 0))
5290 (push (cons c (string-to-char (car e))) det)
5291 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5292 (substring tag 1)))))
5293 (setq det (nreverse det))
5294 (unless char
5295 (message "%s" (concat "Emphasis marker or tag:" prompt))
5296 (setq char (read-char-exclusive)))
5297 (setq char (or (cdr (assoc char det)) char))
5298 (if (equal char ?\ )
5299 (setq s "" move nil)
5300 (unless (assoc (char-to-string char) org-emphasis-alist)
5301 (error "No such emphasis marker: \"%c\"" char))
5302 (setq s (char-to-string char)))
5303 (while (and (> (length string) 1)
5304 (equal (substring string 0 1) (substring string -1))
5305 (assoc (substring string 0 1) org-emphasis-alist))
5306 (setq string (substring string 1 -1)))
5307 (setq string (concat s string s))
5308 (if beg (delete-region beg end))
5309 (unless (or (bolp)
5310 (string-match (concat "[" (nth 0 erc) "\n]")
5311 (char-to-string (char-before (point)))))
5312 (insert " "))
5313 (unless (or (eobp)
5314 (string-match (concat "[" (nth 1 erc) "\n]")
5315 (char-to-string (char-after (point)))))
5316 (insert " ") (backward-char 1))
5317 (insert string)
5318 (and move (backward-char 1))))
5320 (defconst org-nonsticky-props
5321 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5323 (defsubst org-rear-nonsticky-at (pos)
5324 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5326 (defun org-activate-plain-links (limit)
5327 "Run through the buffer and add overlays to links."
5328 (catch 'exit
5329 (let (f hl)
5330 (when (re-search-forward (concat org-plain-link-re) limit t)
5331 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5332 (setq f (get-text-property (match-beginning 0) 'face))
5333 (setq hl (org-match-string-no-properties 0))
5334 (if (or (eq f 'org-tag)
5335 (and (listp f) (memq 'org-tag f)))
5337 (add-text-properties (match-beginning 0) (match-end 0)
5338 (list 'mouse-face 'highlight
5339 'face 'org-link
5340 'htmlize-link `(:uri ,hl)
5341 'keymap org-mouse-map))
5342 (org-rear-nonsticky-at (match-end 0)))
5343 t))))
5345 (defun org-activate-code (limit)
5346 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5347 (progn
5348 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5349 (remove-text-properties (match-beginning 0) (match-end 0)
5350 '(display t invisible t intangible t))
5351 t)))
5353 (defcustom org-src-fontify-natively nil
5354 "When non-nil, fontify code in code blocks."
5355 :type 'boolean
5356 :version "24.1"
5357 :group 'org-appearance
5358 :group 'org-babel)
5360 (defcustom org-allow-promoting-top-level-subtree nil
5361 "When non-nil, allow promoting a top level subtree.
5362 The leading star of the top level headline will be replaced
5363 by a #."
5364 :type 'boolean
5365 :version "24.1"
5366 :group 'org-appearance)
5368 (defun org-fontify-meta-lines-and-blocks (limit)
5369 (condition-case nil
5370 (org-fontify-meta-lines-and-blocks-1 limit)
5371 (error (message "org-mode fontification error"))))
5373 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5374 "Fontify #+ lines and blocks, in the correct ways."
5375 (let ((case-fold-search t))
5376 (if (re-search-forward
5377 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5378 limit t)
5379 (let ((beg (match-beginning 0))
5380 (block-start (match-end 0))
5381 (block-end nil)
5382 (lang (match-string 7))
5383 (beg1 (line-beginning-position 2))
5384 (dc1 (downcase (match-string 2)))
5385 (dc3 (downcase (match-string 3)))
5386 end end1 quoting block-type ovl)
5387 (cond
5388 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5389 ;; a single line of backend-specific content
5390 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5391 (remove-text-properties (match-beginning 0) (match-end 0)
5392 '(display t invisible t intangible t))
5393 (add-text-properties (match-beginning 1) (match-end 3)
5394 '(font-lock-fontified t face org-meta-line))
5395 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5396 '(font-lock-fontified t face org-block))
5397 ; for backend-specific code
5399 ((and (match-end 4) (equal dc3 "+begin"))
5400 ;; Truly a block
5401 (setq block-type (downcase (match-string 5))
5402 quoting (member block-type org-protecting-blocks))
5403 (when (re-search-forward
5404 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5405 nil t) ;; on purpose, we look further than LIMIT
5406 (setq end (min (point-max) (match-end 0))
5407 end1 (min (point-max) (1- (match-beginning 0))))
5408 (setq block-end (match-beginning 0))
5409 (when quoting
5410 (remove-text-properties beg end
5411 '(display t invisible t intangible t)))
5412 (add-text-properties
5413 beg end
5414 '(font-lock-fontified t font-lock-multiline t))
5415 (add-text-properties beg beg1 '(face org-meta-line))
5416 (add-text-properties end1 (min (point-max) (1+ end))
5417 '(face org-meta-line)) ; for end_src
5418 (cond
5419 ((and lang (not (string= lang "")) org-src-fontify-natively)
5420 (org-src-font-lock-fontify-block lang block-start block-end)
5421 ;; remove old background overlays
5422 (mapc (lambda (ov)
5423 (if (eq (overlay-get ov 'face) 'org-block-background)
5424 (delete-overlay ov)))
5425 (overlays-at (/ (+ beg1 block-end) 2)))
5426 ;; add a background overlay
5427 (setq ovl (make-overlay beg1 block-end))
5428 (overlay-put ovl 'face 'org-block-background)
5429 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5430 (quoting
5431 (add-text-properties beg1 (min (point-max) (1+ end1))
5432 '(face org-block))) ; end of source block
5433 ((not org-fontify-quote-and-verse-blocks))
5434 ((string= block-type "quote")
5435 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5436 ((string= block-type "verse")
5437 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5438 (add-text-properties beg beg1 '(face org-block-begin-line))
5439 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5440 '(face org-block-end-line))
5442 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5443 (add-text-properties
5444 beg (match-end 3)
5445 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5446 '(font-lock-fontified t invisible t)
5447 '(font-lock-fontified t face org-document-info-keyword)))
5448 (add-text-properties
5449 (match-beginning 6) (match-end 6)
5450 (if (string-equal dc1 "+title:")
5451 '(font-lock-fontified t face org-document-title)
5452 '(font-lock-fontified t face org-document-info))))
5453 ((or (equal dc1 "+results")
5454 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5455 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5456 "+call:" "+header:" "+headers:" "+name:"))
5457 (and (match-end 4) (equal dc3 "+attr")))
5458 (add-text-properties
5459 beg (match-end 0)
5460 '(font-lock-fontified t face org-meta-line))
5462 ((member dc3 '(" " ""))
5463 (add-text-properties
5464 beg (match-end 0)
5465 '(font-lock-fontified t face font-lock-comment-face)))
5466 ((not (member (char-after beg) '(?\ ?\t)))
5467 ;; just any other in-buffer setting, but not indented
5468 (add-text-properties
5469 beg (match-end 0)
5470 '(font-lock-fontified t face org-meta-line))
5472 (t nil))))))
5474 (defun org-activate-angle-links (limit)
5475 "Run through the buffer and add overlays to links."
5476 (if (re-search-forward org-angle-link-re limit t)
5477 (progn
5478 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5479 (add-text-properties (match-beginning 0) (match-end 0)
5480 (list 'mouse-face 'highlight
5481 'keymap org-mouse-map))
5482 (org-rear-nonsticky-at (match-end 0))
5483 t)))
5485 (defun org-activate-footnote-links (limit)
5486 "Run through the buffer and add overlays to footnotes."
5487 (let ((fn (org-footnote-next-reference-or-definition limit)))
5488 (when fn
5489 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5490 (org-remove-flyspell-overlays-in beg end)
5491 (add-text-properties beg end
5492 (list 'mouse-face 'highlight
5493 'keymap org-mouse-map
5494 'help-echo
5495 (if (= (point-at-bol) beg)
5496 "Footnote definition"
5497 "Footnote reference")
5498 'font-lock-fontified t
5499 'font-lock-multiline t
5500 'face 'org-footnote))))))
5502 (defun org-activate-bracket-links (limit)
5503 "Run through the buffer and add overlays to bracketed links."
5504 (if (re-search-forward org-bracket-link-regexp limit t)
5505 (let* ((hl (org-match-string-no-properties 1))
5506 (help (concat "LINK: " hl))
5507 ;; FIXME: Above we should remove the escapes. But that
5508 ;; requires another match, protecting match data, a lot
5509 ;; of overhead for font-lock.
5510 (ip (org-maybe-intangible
5511 (list 'invisible 'org-link
5512 'keymap org-mouse-map 'mouse-face 'highlight
5513 'font-lock-multiline t 'help-echo help
5514 'htmlize-link `(:uri ,hl))))
5515 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5516 'font-lock-multiline t 'help-echo help
5517 'htmlize-link `(:uri ,hl))))
5518 ;; We need to remove the invisible property here. Table narrowing
5519 ;; may have made some of this invisible.
5520 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5521 (remove-text-properties (match-beginning 0) (match-end 0)
5522 '(invisible nil))
5523 (if (match-end 3)
5524 (progn
5525 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5526 (org-rear-nonsticky-at (match-beginning 3))
5527 (add-text-properties (match-beginning 3) (match-end 3) vp)
5528 (org-rear-nonsticky-at (match-end 3))
5529 (add-text-properties (match-end 3) (match-end 0) ip)
5530 (org-rear-nonsticky-at (match-end 0)))
5531 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5532 (org-rear-nonsticky-at (match-beginning 1))
5533 (add-text-properties (match-beginning 1) (match-end 1) vp)
5534 (org-rear-nonsticky-at (match-end 1))
5535 (add-text-properties (match-end 1) (match-end 0) ip)
5536 (org-rear-nonsticky-at (match-end 0)))
5537 t)))
5539 (defun org-activate-dates (limit)
5540 "Run through the buffer and add overlays to dates."
5541 (if (re-search-forward org-tsr-regexp-both limit t)
5542 (progn
5543 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5544 (add-text-properties (match-beginning 0) (match-end 0)
5545 (list 'mouse-face 'highlight
5546 'keymap org-mouse-map))
5547 (org-rear-nonsticky-at (match-end 0))
5548 (when org-display-custom-times
5549 (if (match-end 3)
5550 (org-display-custom-time (match-beginning 3) (match-end 3)))
5551 (org-display-custom-time (match-beginning 1) (match-end 1)))
5552 t)))
5554 (defvar org-target-link-regexp nil
5555 "Regular expression matching radio targets in plain text.")
5556 (make-variable-buffer-local 'org-target-link-regexp)
5557 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5558 "Regular expression matching a link target.")
5559 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5560 "Regular expression matching a radio target.")
5561 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5562 "Regular expression matching any target.")
5564 (defun org-activate-target-links (limit)
5565 "Run through the buffer and add overlays to target matches."
5566 (when org-target-link-regexp
5567 (let ((case-fold-search t))
5568 (if (re-search-forward org-target-link-regexp limit t)
5569 (progn
5570 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5571 (add-text-properties (match-beginning 0) (match-end 0)
5572 (list 'mouse-face 'highlight
5573 'keymap org-mouse-map
5574 'help-echo "Radio target link"
5575 'org-linked-text t))
5576 (org-rear-nonsticky-at (match-end 0))
5577 t)))))
5579 (defun org-update-radio-target-regexp ()
5580 "Find all radio targets in this file and update the regular expression."
5581 (interactive)
5582 (when (memq 'radio org-activate-links)
5583 (setq org-target-link-regexp
5584 (org-make-target-link-regexp (org-all-targets 'radio)))
5585 (org-restart-font-lock)))
5587 (defun org-hide-wide-columns (limit)
5588 (let (s e)
5589 (setq s (text-property-any (point) (or limit (point-max))
5590 'org-cwidth t))
5591 (when s
5592 (setq e (next-single-property-change s 'org-cwidth))
5593 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5594 (goto-char e)
5595 t)))
5597 (defvar org-latex-and-specials-regexp nil
5598 "Regular expression for highlighting export special stuff.")
5599 (defvar org-match-substring-regexp)
5600 (defvar org-match-substring-with-braces-regexp)
5602 ;; This should be with the exporter code, but we also use if for font-locking
5603 (defconst org-export-html-special-string-regexps
5604 '(("\\\\-" . "&shy;")
5605 ("---\\([^-]\\)" . "&mdash;\\1")
5606 ("--\\([^-]\\)" . "&ndash;\\1")
5607 ("\\.\\.\\." . "&hellip;"))
5608 "Regular expressions for special string conversion.")
5611 (defun org-compute-latex-and-specials-regexp ()
5612 "Compute regular expression for stuff treated specially by exporters."
5613 (if (not org-highlight-latex-fragments-and-specials)
5614 (org-set-local 'org-latex-and-specials-regexp nil)
5615 (require 'org-exp)
5616 (let*
5617 ((matchers (plist-get org-format-latex-options :matchers))
5618 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5619 org-latex-regexps)))
5620 (org-export-allow-BIND nil)
5621 (options (org-combine-plists (org-default-export-plist)
5622 (org-infile-export-plist)))
5623 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5624 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5625 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5626 (org-export-html-expand (plist-get options :expand-quoted-html))
5627 (org-export-with-special-strings (plist-get options :special-strings))
5628 (re-sub
5629 (cond
5630 ((equal org-export-with-sub-superscripts '{})
5631 (list org-match-substring-with-braces-regexp))
5632 (org-export-with-sub-superscripts
5633 (list org-match-substring-regexp))))
5634 (re-latex
5635 (if org-export-with-LaTeX-fragments
5636 (mapcar (lambda (x) (nth 1 x)) latexs)))
5637 (re-macros
5638 (if org-export-with-TeX-macros
5639 (list (concat "\\\\"
5640 (regexp-opt
5641 (append
5643 (delq nil
5644 (mapcar 'car-safe
5645 (append org-entities-user
5646 org-entities)))
5647 (if (boundp 'org-latex-entities)
5648 (mapcar (lambda (x)
5649 (or (car-safe x) x))
5650 org-latex-entities)
5651 nil))
5652 'words))) ; FIXME
5654 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5655 (re-special (if org-export-with-special-strings
5656 (mapcar (lambda (x) (car x))
5657 org-export-html-special-string-regexps)))
5658 (re-rest
5659 (delq nil
5660 (list
5661 (if org-export-html-expand "@<[^>\n]+>")
5662 ))))
5663 (org-set-local
5664 'org-latex-and-specials-regexp
5665 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5666 re-rest) "\\|")))))
5668 (defun org-do-latex-and-special-faces (limit)
5669 "Run through the buffer and add overlays to links."
5670 (when org-latex-and-specials-regexp
5671 (let (rtn d)
5672 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5673 limit t))
5674 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5675 'face))
5676 '(org-code org-verbatim underline)))
5677 (progn
5678 (setq rtn t
5679 d (cond ((member (char-after (1+ (match-beginning 0)))
5680 '(?_ ?^)) 1)
5681 (t 0)))
5682 (font-lock-prepend-text-property
5683 (+ d (match-beginning 0)) (match-end 0)
5684 'face 'org-latex-and-export-specials)
5685 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5686 '(font-lock-multiline t)))))
5687 rtn)))
5689 (defun org-restart-font-lock ()
5690 "Restart `font-lock-mode', to force refontification."
5691 (when (and (boundp 'font-lock-mode) font-lock-mode)
5692 (font-lock-mode -1)
5693 (font-lock-mode 1)))
5695 (defun org-all-targets (&optional radio)
5696 "Return a list of all targets in this file.
5697 When optional argument RADIO is non-nil, only find radio
5698 targets."
5699 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5700 (save-excursion
5701 (goto-char (point-min))
5702 (while (re-search-forward re nil t)
5703 (let ((obj (org-element-context)))
5704 (when (memq (org-element-type obj) '(radio-target target))
5705 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5706 rtn)))
5708 (defun org-make-target-link-regexp (targets)
5709 "Make regular expression matching all strings in TARGETS.
5710 The regular expression finds the targets also if there is a line break
5711 between words."
5712 (and targets
5713 (concat
5714 "\\<\\("
5715 (mapconcat
5716 (lambda (x)
5717 (setq x (regexp-quote x))
5718 (while (string-match " +" x)
5719 (setq x (replace-match "\\s-+" t t x)))
5721 targets
5722 "\\|")
5723 "\\)\\>")))
5725 (defun org-activate-tags (limit)
5726 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5727 (progn
5728 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5729 (add-text-properties (match-beginning 1) (match-end 1)
5730 (list 'mouse-face 'highlight
5731 'keymap org-mouse-map))
5732 (org-rear-nonsticky-at (match-end 1))
5733 t)))
5735 (defun org-outline-level ()
5736 "Compute the outline level of the heading at point.
5737 If this is called at a normal headline, the level is the number of stars.
5738 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5739 (save-excursion
5740 (if (not (condition-case nil
5741 (org-back-to-heading t)
5742 (error nil)))
5744 (looking-at org-outline-regexp)
5745 (1- (- (match-end 0) (match-beginning 0))))))
5747 (defvar org-font-lock-keywords nil)
5749 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5750 "Regular expression matching a property line.")
5752 (defvar org-font-lock-hook nil
5753 "Functions to be called for special font lock stuff.")
5755 (defvar org-font-lock-set-keywords-hook nil
5756 "Functions that can manipulate `org-font-lock-extra-keywords'.
5757 This is called after `org-font-lock-extra-keywords' is defined, but before
5758 it is installed to be used by font lock. This can be useful if something
5759 needs to be inserted at a specific position in the font-lock sequence.")
5761 (defun org-font-lock-hook (limit)
5762 "Run `org-font-lock-hook' within LIMIT."
5763 (run-hook-with-args 'org-font-lock-hook limit))
5765 (defun org-set-font-lock-defaults ()
5766 "Set font lock defaults for the current buffer."
5767 (let* ((em org-fontify-emphasized-text)
5768 (lk org-activate-links)
5769 (org-font-lock-extra-keywords
5770 (list
5771 ;; Call the hook
5772 '(org-font-lock-hook)
5773 ;; Headlines
5774 `(,(if org-fontify-whole-heading-line
5775 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5776 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5777 (1 (org-get-level-face 1))
5778 (2 (org-get-level-face 2))
5779 (3 (org-get-level-face 3)))
5780 ;; Table lines
5781 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5782 (1 'org-table t))
5783 ;; Table internals
5784 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5785 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5786 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5787 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5788 ;; Drawers
5789 (list org-drawer-regexp '(0 'org-special-keyword t))
5790 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5791 ;; Properties
5792 (list org-property-re
5793 '(1 'org-special-keyword t)
5794 '(3 'org-property-value t))
5795 ;; Links
5796 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5797 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5798 (if (memq 'plain lk) '(org-activate-plain-links))
5799 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5800 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5801 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5802 (if (memq 'footnote lk) '(org-activate-footnote-links))
5803 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5804 '(org-hide-wide-columns (0 nil append))
5805 ;; TODO keyword
5806 (list (format org-heading-keyword-regexp-format
5807 org-todo-regexp)
5808 '(2 (org-get-todo-face 2) t))
5809 ;; DONE
5810 (if org-fontify-done-headline
5811 (list (format org-heading-keyword-regexp-format
5812 (concat
5813 "\\(?:"
5814 (mapconcat 'regexp-quote org-done-keywords "\\|")
5815 "\\)"))
5816 '(2 'org-headline-done t))
5817 nil)
5818 ;; Priorities
5819 '(org-font-lock-add-priority-faces)
5820 ;; Tags
5821 '(org-font-lock-add-tag-faces)
5822 ;; Special keywords
5823 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5824 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5825 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5826 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5827 ;; Emphasis
5828 (if em
5829 (if (featurep 'xemacs)
5830 '(org-do-emphasis-faces (0 nil append))
5831 '(org-do-emphasis-faces)))
5832 ;; Checkboxes
5833 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5834 1 'org-checkbox prepend)
5835 (if (cdr (assq 'checkbox org-list-automatic-rules))
5836 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5837 (0 (org-get-checkbox-statistics-face) t)))
5838 ;; Description list items
5839 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5840 1 'org-list-dt prepend)
5841 ;; ARCHIVEd headings
5842 (list (concat
5843 org-outline-regexp-bol
5844 "\\(.*:" org-archive-tag ":.*\\)")
5845 '(1 'org-archived prepend))
5846 ;; Specials
5847 '(org-do-latex-and-special-faces)
5848 '(org-fontify-entities)
5849 '(org-raise-scripts)
5850 ;; Code
5851 '(org-activate-code (1 'org-code t))
5852 ;; COMMENT
5853 (list (format org-heading-keyword-regexp-format
5854 (concat "\\("
5855 org-comment-string "\\|" org-quote-string
5856 "\\)"))
5857 '(2 'org-special-keyword t))
5858 ;; Blocks and meta lines
5859 '(org-fontify-meta-lines-and-blocks)
5861 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5862 (run-hooks 'org-font-lock-set-keywords-hook)
5863 ;; Now set the full font-lock-keywords
5864 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5865 (org-set-local 'font-lock-defaults
5866 '(org-font-lock-keywords t nil nil backward-paragraph))
5867 (kill-local-variable 'font-lock-keywords) nil))
5869 (defun org-toggle-pretty-entities ()
5870 "Toggle the composition display of entities as UTF8 characters."
5871 (interactive)
5872 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5873 (org-restart-font-lock)
5874 (if org-pretty-entities
5875 (message "Entities are displayed as UTF8 characters")
5876 (save-restriction
5877 (widen)
5878 (org-decompose-region (point-min) (point-max))
5879 (message "Entities are displayed plain"))))
5881 (defvar org-custom-properties-overlays nil
5882 "List of overlays used for custom properties.")
5883 (make-variable-buffer-local 'org-custom-properties-overlays)
5885 (defun org-toggle-custom-properties-visibility ()
5886 "Display or hide properties in `org-custom-properties'."
5887 (interactive)
5888 (if org-custom-properties-overlays
5889 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5890 (setq org-custom-properties-overlays nil))
5891 (unless (not org-custom-properties)
5892 (save-excursion
5893 (save-restriction
5894 (widen)
5895 (goto-char (point-min))
5896 (while (re-search-forward org-property-re nil t)
5897 (mapc (lambda(p)
5898 (when (equal p (substring (match-string 1) 1 -1))
5899 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5900 (overlay-put o 'invisible t)
5901 (overlay-put o 'org-custom-property t)
5902 (push o org-custom-properties-overlays))))
5903 org-custom-properties)))))))
5905 (defun org-fontify-entities (limit)
5906 "Find an entity to fontify."
5907 (let (ee)
5908 (when org-pretty-entities
5909 (catch 'match
5910 (while (re-search-forward
5911 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5912 limit t)
5913 (if (and (not (org-in-indented-comment-line))
5914 (setq ee (org-entity-get (match-string 1)))
5915 (= (length (nth 6 ee)) 1))
5916 (let*
5917 ((end (if (equal (match-string 2) "{}")
5918 (match-end 2)
5919 (match-end 1))))
5920 (add-text-properties
5921 (match-beginning 0) end
5922 (list 'font-lock-fontified t))
5923 (compose-region (match-beginning 0) end
5924 (nth 6 ee) nil)
5925 (backward-char 1)
5926 (throw 'match t))))
5927 nil))))
5929 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5930 "Fontify string S like in Org-mode."
5931 (with-temp-buffer
5932 (insert s)
5933 (let ((org-odd-levels-only odd-levels))
5934 (org-mode)
5935 (font-lock-fontify-buffer)
5936 (buffer-string))))
5938 (defvar org-m nil)
5939 (defvar org-l nil)
5940 (defvar org-f nil)
5941 (defun org-get-level-face (n)
5942 "Get the right face for match N in font-lock matching of headlines."
5943 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5944 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5945 (if org-cycle-level-faces
5946 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5947 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5948 (cond
5949 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5950 ((eq n 2) org-f)
5951 (t (if org-level-color-stars-only nil org-f))))
5954 (defun org-get-todo-face (kwd)
5955 "Get the right face for a TODO keyword KWD.
5956 If KWD is a number, get the corresponding match group."
5957 (if (numberp kwd) (setq kwd (match-string kwd)))
5958 (or (org-face-from-face-or-color
5959 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5960 (and (member kwd org-done-keywords) 'org-done)
5961 'org-todo))
5963 (defun org-face-from-face-or-color (context inherit face-or-color)
5964 "Create a face list that inherits INHERIT, but sets the foreground color.
5965 When FACE-OR-COLOR is not a string, just return it."
5966 (if (stringp face-or-color)
5967 (list :inherit inherit
5968 (cdr (assoc context org-faces-easy-properties))
5969 face-or-color)
5970 face-or-color))
5972 (defun org-font-lock-add-tag-faces (limit)
5973 "Add the special tag faces."
5974 (when (and org-tag-faces org-tags-special-faces-re)
5975 (while (re-search-forward org-tags-special-faces-re limit t)
5976 (add-text-properties (match-beginning 1) (match-end 1)
5977 (list 'face (org-get-tag-face 1)
5978 'font-lock-fontified t))
5979 (backward-char 1))))
5981 (defun org-font-lock-add-priority-faces (limit)
5982 "Add the special priority faces."
5983 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5984 (when (save-match-data (org-at-heading-p))
5985 (add-text-properties
5986 (match-beginning 0) (match-end 0)
5987 (list 'face (or (org-face-from-face-or-color
5988 'priority 'org-special-keyword
5989 (cdr (assoc (char-after (match-beginning 1))
5990 org-priority-faces)))
5991 'org-special-keyword)
5992 'font-lock-fontified t)))))
5994 (defun org-get-tag-face (kwd)
5995 "Get the right face for a TODO keyword KWD.
5996 If KWD is a number, get the corresponding match group."
5997 (if (numberp kwd) (setq kwd (match-string kwd)))
5998 (or (org-face-from-face-or-color
5999 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6000 'org-tag))
6002 (defun org-unfontify-region (beg end &optional maybe_loudly)
6003 "Remove fontification and activation overlays from links."
6004 (font-lock-default-unfontify-region beg end)
6005 (let* ((buffer-undo-list t)
6006 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6007 (inhibit-modification-hooks t)
6008 deactivate-mark buffer-file-name buffer-file-truename)
6009 (org-decompose-region beg end)
6010 (remove-text-properties beg end
6011 '(mouse-face t keymap t org-linked-text t
6012 invisible t intangible t
6013 org-no-flyspell t org-emphasis t))
6014 (org-remove-font-lock-display-properties beg end)))
6016 (defconst org-script-display '(((raise -0.3) (height 0.7))
6017 ((raise 0.3) (height 0.7))
6018 ((raise -0.5))
6019 ((raise 0.5)))
6020 "Display properties for showing superscripts and subscripts.")
6022 (defun org-remove-font-lock-display-properties (beg end)
6023 "Remove specific display properties that have been added by font lock.
6024 The will remove the raise properties that are used to show superscripts
6025 and subscripts."
6026 (let (next prop)
6027 (while (< beg end)
6028 (setq next (next-single-property-change beg 'display nil end)
6029 prop (get-text-property beg 'display))
6030 (if (member prop org-script-display)
6031 (put-text-property beg next 'display nil))
6032 (setq beg next))))
6034 (defun org-raise-scripts (limit)
6035 "Add raise properties to sub/superscripts."
6036 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6037 (if (re-search-forward
6038 (if (eq org-use-sub-superscripts t)
6039 org-match-substring-regexp
6040 org-match-substring-with-braces-regexp)
6041 limit t)
6042 (let* ((pos (point)) table-p comment-p
6043 (mpos (match-beginning 3))
6044 (emph-p (get-text-property mpos 'org-emphasis))
6045 (link-p (get-text-property mpos 'mouse-face))
6046 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6047 (goto-char (point-at-bol))
6048 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6049 comment-p (org-looking-at-p "[ \t]*#"))
6050 (goto-char pos)
6051 ;; FIXME: Should we go back one character here, for a_b^c
6052 ;; (goto-char (1- pos)) ;????????????????????
6053 (if (or comment-p emph-p link-p keyw-p)
6055 (put-text-property (match-beginning 3) (match-end 0)
6056 'display
6057 (if (equal (char-after (match-beginning 2)) ?^)
6058 (nth (if table-p 3 1) org-script-display)
6059 (nth (if table-p 2 0) org-script-display)))
6060 (add-text-properties (match-beginning 2) (match-end 2)
6061 (list 'invisible t
6062 'org-dwidth t 'org-dwidth-n 1))
6063 (if (and (eq (char-after (match-beginning 3)) ?{)
6064 (eq (char-before (match-end 3)) ?}))
6065 (progn
6066 (add-text-properties
6067 (match-beginning 3) (1+ (match-beginning 3))
6068 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6069 (add-text-properties
6070 (1- (match-end 3)) (match-end 3)
6071 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6072 t)))))
6074 ;;;; Visibility cycling, including org-goto and indirect buffer
6076 ;;; Cycling
6078 (defvar org-cycle-global-status nil)
6079 (make-variable-buffer-local 'org-cycle-global-status)
6080 (defvar org-cycle-subtree-status nil)
6081 (make-variable-buffer-local 'org-cycle-subtree-status)
6083 (defvar org-inlinetask-min-level)
6085 ;;;###autoload
6086 (defun org-cycle (&optional arg)
6087 "TAB-action and visibility cycling for Org-mode.
6089 This is the command invoked in Org-mode by the TAB key. Its main purpose
6090 is outline visibility cycling, but it also invokes other actions
6091 in special contexts.
6093 - When this function is called with a prefix argument, rotate the entire
6094 buffer through 3 states (global cycling)
6095 1. OVERVIEW: Show only top-level headlines.
6096 2. CONTENTS: Show all headlines of all levels, but no body text.
6097 3. SHOW ALL: Show everything.
6098 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6099 determined by the variable `org-startup-folded', and by any VISIBILITY
6100 properties in the buffer.
6101 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6102 including any drawers.
6104 - When inside a table, re-align the table and move to the next field.
6106 - When point is at the beginning of a headline, rotate the subtree started
6107 by this line through 3 different states (local cycling)
6108 1. FOLDED: Only the main headline is shown.
6109 2. CHILDREN: The main headline and the direct children are shown.
6110 From this state, you can move to one of the children
6111 and zoom in further.
6112 3. SUBTREE: Show the entire subtree, including body text.
6113 If there is no subtree, switch directly from CHILDREN to FOLDED.
6115 - When point is at the beginning of an empty headline and the variable
6116 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6117 of the headline by demoting and promoting it to likely levels. This
6118 speeds up creation document structure by pressing TAB once or several
6119 times right after creating a new headline.
6121 - When there is a numeric prefix, go up to a heading with level ARG, do
6122 a `show-subtree' and return to the previous cursor position. If ARG
6123 is negative, go up that many levels.
6125 - When point is not at the beginning of a headline, execute the global
6126 binding for TAB, which is re-indenting the line. See the option
6127 `org-cycle-emulate-tab' for details.
6129 - Special case: if point is at the beginning of the buffer and there is
6130 no headline in line 1, this function will act as if called with prefix arg
6131 (C-u TAB, same as S-TAB) also when called without prefix arg.
6132 But only if also the variable `org-cycle-global-at-bob' is t."
6133 (interactive "P")
6134 (org-load-modules-maybe)
6135 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6136 (and org-cycle-level-after-item/entry-creation
6137 (or (org-cycle-level)
6138 (org-cycle-item-indentation))))
6139 (let* ((limit-level
6140 (or org-cycle-max-level
6141 (and (boundp 'org-inlinetask-min-level)
6142 org-inlinetask-min-level
6143 (1- org-inlinetask-min-level))))
6144 (nstars (and limit-level
6145 (if org-odd-levels-only
6146 (and limit-level (1- (* limit-level 2)))
6147 limit-level)))
6148 (org-outline-regexp
6149 (if (not (derived-mode-p 'org-mode))
6150 outline-regexp
6151 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6152 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6153 (not (looking-at org-outline-regexp))))
6154 (org-cycle-hook
6155 (if bob-special
6156 (delq 'org-optimize-window-after-visibility-change
6157 (copy-sequence org-cycle-hook))
6158 org-cycle-hook))
6159 (pos (point)))
6161 (if (or bob-special (equal arg '(4)))
6162 ;; special case: use global cycling
6163 (setq arg t))
6165 (cond
6167 ((equal arg '(16))
6168 (setq last-command 'dummy)
6169 (org-set-startup-visibility)
6170 (message "Startup visibility, plus VISIBILITY properties"))
6172 ((equal arg '(64))
6173 (show-all)
6174 (message "Entire buffer visible, including drawers"))
6176 ;; Table: enter it or move to the next field.
6177 ((org-at-table-p 'any)
6178 (if (org-at-table.el-p)
6179 (message "Use C-c ' to edit table.el tables")
6180 (if arg (org-table-edit-field t)
6181 (org-table-justify-field-maybe)
6182 (call-interactively 'org-table-next-field))))
6184 ((run-hook-with-args-until-success
6185 'org-tab-after-check-for-table-hook))
6187 ;; Global cycling: delegate to `org-cycle-internal-global'.
6188 ((eq arg t) (org-cycle-internal-global))
6190 ;; Drawers: delegate to `org-flag-drawer'.
6191 ((and org-drawers org-drawer-regexp
6192 (save-excursion
6193 (beginning-of-line 1)
6194 (looking-at org-drawer-regexp)))
6195 (org-flag-drawer ; toggle block visibility
6196 (not (get-char-property (match-end 0) 'invisible))))
6198 ;; Show-subtree, ARG levels up from here.
6199 ((integerp arg)
6200 (save-excursion
6201 (org-back-to-heading)
6202 (outline-up-heading (if (< arg 0) (- arg)
6203 (- (funcall outline-level) arg)))
6204 (org-show-subtree)))
6206 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6207 ((and (featurep 'org-inlinetask)
6208 (org-inlinetask-at-task-p)
6209 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6210 (org-inlinetask-toggle-visibility))
6212 ((org-try-cdlatex-tab))
6214 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6215 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6216 (save-excursion (beginning-of-line 1)
6217 (looking-at org-outline-regexp)))
6218 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6219 (org-cycle-internal-local))
6221 ;; From there: TAB emulation and template completion.
6222 (buffer-read-only (org-back-to-heading))
6224 ((run-hook-with-args-until-success
6225 'org-tab-after-check-for-cycling-hook))
6227 ((org-try-structure-completion))
6229 ((run-hook-with-args-until-success
6230 'org-tab-before-tab-emulation-hook))
6232 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6233 (or (not (bolp))
6234 (not (looking-at org-outline-regexp))))
6235 (call-interactively (global-key-binding "\t")))
6237 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6238 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6239 (or (and (eq org-cycle-emulate-tab 'white)
6240 (= (match-end 0) (point-at-eol)))
6241 (and (eq org-cycle-emulate-tab 'whitestart)
6242 (>= (match-end 0) pos))))
6244 (eq org-cycle-emulate-tab t))
6245 (call-interactively (global-key-binding "\t")))
6247 (t (save-excursion
6248 (org-back-to-heading)
6249 (org-cycle)))))))
6251 (defun org-cycle-internal-global ()
6252 "Do the global cycling action."
6253 ;; Hack to avoid display of messages for .org attachments in Gnus
6254 (let ((ga (string-match "\\*fontification" (buffer-name))))
6255 (cond
6256 ((and (eq last-command this-command)
6257 (eq org-cycle-global-status 'overview))
6258 ;; We just created the overview - now do table of contents
6259 ;; This can be slow in very large buffers, so indicate action
6260 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6261 (unless ga (message "CONTENTS..."))
6262 (org-content)
6263 (unless ga (message "CONTENTS...done"))
6264 (setq org-cycle-global-status 'contents)
6265 (run-hook-with-args 'org-cycle-hook 'contents))
6267 ((and (eq last-command this-command)
6268 (eq org-cycle-global-status 'contents))
6269 ;; We just showed the table of contents - now show everything
6270 (run-hook-with-args 'org-pre-cycle-hook 'all)
6271 (show-all)
6272 (unless ga (message "SHOW ALL"))
6273 (setq org-cycle-global-status 'all)
6274 (run-hook-with-args 'org-cycle-hook 'all))
6277 ;; Default action: go to overview
6278 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6279 (org-overview)
6280 (unless ga (message "OVERVIEW"))
6281 (setq org-cycle-global-status 'overview)
6282 (run-hook-with-args 'org-cycle-hook 'overview)))))
6284 (defun org-cycle-internal-local ()
6285 "Do the local cycling action."
6286 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6287 ;; First, determine end of headline (EOH), end of subtree or item
6288 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6289 (save-excursion
6290 (if (org-at-item-p)
6291 (progn
6292 (beginning-of-line)
6293 (setq struct (org-list-struct))
6294 (setq eoh (point-at-eol))
6295 (setq eos (org-list-get-item-end-before-blank (point) struct))
6296 (setq has-children (org-list-has-child-p (point) struct)))
6297 (org-back-to-heading)
6298 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6299 (setq eos (save-excursion
6300 (org-end-of-subtree t)
6301 (unless (eobp)
6302 (skip-chars-forward " \t\n"))
6303 (if (eobp) (point) (1- (point)))))
6304 (setq has-children
6305 (or (save-excursion
6306 (let ((level (funcall outline-level)))
6307 (outline-next-heading)
6308 (and (org-at-heading-p t)
6309 (> (funcall outline-level) level))))
6310 (save-excursion
6311 (org-list-search-forward (org-item-beginning-re) eos t)))))
6312 ;; Determine end invisible part of buffer (EOL)
6313 (beginning-of-line 2)
6314 ;; XEmacs doesn't have `next-single-char-property-change'
6315 (if (featurep 'xemacs)
6316 (while (and (not (eobp)) ;; this is like `next-line'
6317 (get-char-property (1- (point)) 'invisible))
6318 (beginning-of-line 2))
6319 (while (and (not (eobp)) ;; this is like `next-line'
6320 (get-char-property (1- (point)) 'invisible))
6321 (goto-char (next-single-char-property-change (point) 'invisible))
6322 (and (eolp) (beginning-of-line 2))))
6323 (setq eol (point)))
6324 ;; Find out what to do next and set `this-command'
6325 (cond
6326 ((= eos eoh)
6327 ;; Nothing is hidden behind this heading
6328 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6329 (message "EMPTY ENTRY")
6330 (setq org-cycle-subtree-status nil)
6331 (save-excursion
6332 (goto-char eos)
6333 (outline-next-heading)
6334 (if (outline-invisible-p) (org-flag-heading nil))))
6335 ((and (or (>= eol eos)
6336 (not (string-match "\\S-" (buffer-substring eol eos))))
6337 (or has-children
6338 (not (setq children-skipped
6339 org-cycle-skip-children-state-if-no-children))))
6340 ;; Entire subtree is hidden in one line: children view
6341 (run-hook-with-args 'org-pre-cycle-hook 'children)
6342 (if (org-at-item-p)
6343 (org-list-set-item-visibility (point-at-bol) struct 'children)
6344 (org-show-entry)
6345 (org-with-limited-levels (show-children))
6346 ;; FIXME: This slows down the func way too much.
6347 ;; How keep drawers hidden in subtree anyway?
6348 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6349 ;; (org-cycle-hide-drawers 'subtree))
6351 ;; Fold every list in subtree to top-level items.
6352 (when (eq org-cycle-include-plain-lists 'integrate)
6353 (save-excursion
6354 (org-back-to-heading)
6355 (while (org-list-search-forward (org-item-beginning-re) eos t)
6356 (beginning-of-line 1)
6357 (let* ((struct (org-list-struct))
6358 (prevs (org-list-prevs-alist struct))
6359 (end (org-list-get-bottom-point struct)))
6360 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6361 (org-list-get-all-items (point) struct prevs))
6362 (goto-char end))))))
6363 (message "CHILDREN")
6364 (save-excursion
6365 (goto-char eos)
6366 (outline-next-heading)
6367 (if (outline-invisible-p) (org-flag-heading nil)))
6368 (setq org-cycle-subtree-status 'children)
6369 (run-hook-with-args 'org-cycle-hook 'children))
6370 ((or children-skipped
6371 (and (eq last-command this-command)
6372 (eq org-cycle-subtree-status 'children)))
6373 ;; We just showed the children, or no children are there,
6374 ;; now show everything.
6375 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6376 (outline-flag-region eoh eos nil)
6377 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6378 (setq org-cycle-subtree-status 'subtree)
6379 (run-hook-with-args 'org-cycle-hook 'subtree))
6381 ;; Default action: hide the subtree.
6382 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6383 (outline-flag-region eoh eos t)
6384 (message "FOLDED")
6385 (setq org-cycle-subtree-status 'folded)
6386 (run-hook-with-args 'org-cycle-hook 'folded)))))
6388 ;;;###autoload
6389 (defun org-global-cycle (&optional arg)
6390 "Cycle the global visibility. For details see `org-cycle'.
6391 With \\[universal-argument] prefix arg, switch to startup visibility.
6392 With a numeric prefix, show all headlines up to that level."
6393 (interactive "P")
6394 (let ((org-cycle-include-plain-lists
6395 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6396 (cond
6397 ((integerp arg)
6398 (show-all)
6399 (hide-sublevels arg)
6400 (setq org-cycle-global-status 'contents))
6401 ((equal arg '(4))
6402 (org-set-startup-visibility)
6403 (message "Startup visibility, plus VISIBILITY properties."))
6405 (org-cycle '(4))))))
6407 (defun org-set-startup-visibility ()
6408 "Set the visibility required by startup options and properties."
6409 (cond
6410 ((eq org-startup-folded t)
6411 (org-cycle '(4)))
6412 ((eq org-startup-folded 'content)
6413 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6414 (org-cycle '(4)) (org-cycle '(4)))))
6415 (unless (eq org-startup-folded 'showeverything)
6416 (if org-hide-block-startup (org-hide-block-all))
6417 (org-set-visibility-according-to-property 'no-cleanup)
6418 (org-cycle-hide-archived-subtrees 'all)
6419 (org-cycle-hide-drawers 'all)
6420 (org-cycle-show-empty-lines t)))
6422 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6423 "Switch subtree visibilities according to :VISIBILITY: property."
6424 (interactive)
6425 (let (org-show-entry-below state)
6426 (save-excursion
6427 (goto-char (point-min))
6428 (while (re-search-forward
6429 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6430 nil t)
6431 (setq state (match-string 1))
6432 (save-excursion
6433 (org-back-to-heading t)
6434 (hide-subtree)
6435 (org-reveal)
6436 (cond
6437 ((equal state '("fold" "folded"))
6438 (hide-subtree))
6439 ((equal state "children")
6440 (org-show-hidden-entry)
6441 (show-children))
6442 ((equal state "content")
6443 (save-excursion
6444 (save-restriction
6445 (org-narrow-to-subtree)
6446 (org-content))))
6447 ((member state '("all" "showall"))
6448 (show-subtree)))))
6449 (unless no-cleanup
6450 (org-cycle-hide-archived-subtrees 'all)
6451 (org-cycle-hide-drawers 'all)
6452 (org-cycle-show-empty-lines 'all)))))
6454 ;; This function uses outline-regexp instead of the more fundamental
6455 ;; org-outline-regexp so that org-cycle-global works outside of Org
6456 ;; buffers, where outline-regexp is needed.
6457 (defun org-overview ()
6458 "Switch to overview mode, showing only top-level headlines.
6459 Really, this shows all headlines with level equal or greater than the level
6460 of the first headline in the buffer. This is important, because if the
6461 first headline is not level one, then (hide-sublevels 1) gives confusing
6462 results."
6463 (interactive)
6464 (let ((level (save-excursion
6465 (goto-char (point-min))
6466 (if (re-search-forward (concat "^" outline-regexp) nil t)
6467 (progn
6468 (goto-char (match-beginning 0))
6469 (funcall outline-level))))))
6470 (and level (hide-sublevels level))))
6472 (defun org-content (&optional arg)
6473 "Show all headlines in the buffer, like a table of contents.
6474 With numerical argument N, show content up to level N."
6475 (interactive "P")
6476 (save-excursion
6477 ;; Visit all headings and show their offspring
6478 (and (integerp arg) (org-overview))
6479 (goto-char (point-max))
6480 (catch 'exit
6481 (while (and (progn (condition-case nil
6482 (outline-previous-visible-heading 1)
6483 (error (goto-char (point-min))))
6485 (looking-at org-outline-regexp))
6486 (if (integerp arg)
6487 (show-children (1- arg))
6488 (show-branches))
6489 (if (bobp) (throw 'exit nil))))))
6492 (defun org-optimize-window-after-visibility-change (state)
6493 "Adjust the window after a change in outline visibility.
6494 This function is the default value of the hook `org-cycle-hook'."
6495 (when (get-buffer-window (current-buffer))
6496 (cond
6497 ((eq state 'content) nil)
6498 ((eq state 'all) nil)
6499 ((eq state 'folded) nil)
6500 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6501 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6503 (defun org-remove-empty-overlays-at (pos)
6504 "Remove outline overlays that do not contain non-white stuff."
6505 (mapc
6506 (lambda (o)
6507 (and (eq 'outline (overlay-get o 'invisible))
6508 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6509 (overlay-end o))))
6510 (delete-overlay o)))
6511 (overlays-at pos)))
6513 (defun org-clean-visibility-after-subtree-move ()
6514 "Fix visibility issues after moving a subtree."
6515 ;; First, find a reasonable region to look at:
6516 ;; Start two siblings above, end three below
6517 (let* ((beg (save-excursion
6518 (and (org-get-last-sibling)
6519 (org-get-last-sibling))
6520 (point)))
6521 (end (save-excursion
6522 (and (org-get-next-sibling)
6523 (org-get-next-sibling)
6524 (org-get-next-sibling))
6525 (if (org-at-heading-p)
6526 (point-at-eol)
6527 (point))))
6528 (level (looking-at "\\*+"))
6529 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6530 (save-excursion
6531 (save-restriction
6532 (narrow-to-region beg end)
6533 (when re
6534 ;; Properly fold already folded siblings
6535 (goto-char (point-min))
6536 (while (re-search-forward re nil t)
6537 (if (and (not (outline-invisible-p))
6538 (save-excursion
6539 (goto-char (point-at-eol)) (outline-invisible-p)))
6540 (hide-entry))))
6541 (org-cycle-show-empty-lines 'overview)
6542 (org-cycle-hide-drawers 'overview)))))
6544 (defun org-cycle-show-empty-lines (state)
6545 "Show empty lines above all visible headlines.
6546 The region to be covered depends on STATE when called through
6547 `org-cycle-hook'. Lisp program can use t for STATE to get the
6548 entire buffer covered. Note that an empty line is only shown if there
6549 are at least `org-cycle-separator-lines' empty lines before the headline."
6550 (when (not (= org-cycle-separator-lines 0))
6551 (save-excursion
6552 (let* ((n (abs org-cycle-separator-lines))
6553 (re (cond
6554 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6555 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6556 (t (let ((ns (number-to-string (- n 2))))
6557 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6558 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6559 beg end b e)
6560 (cond
6561 ((memq state '(overview contents t))
6562 (setq beg (point-min) end (point-max)))
6563 ((memq state '(children folded))
6564 (setq beg (point) end (progn (org-end-of-subtree t t)
6565 (beginning-of-line 2)
6566 (point)))))
6567 (when beg
6568 (goto-char beg)
6569 (while (re-search-forward re end t)
6570 (unless (get-char-property (match-end 1) 'invisible)
6571 (setq e (match-end 1))
6572 (if (< org-cycle-separator-lines 0)
6573 (setq b (save-excursion
6574 (goto-char (match-beginning 0))
6575 (org-back-over-empty-lines)
6576 (if (save-excursion
6577 (goto-char (max (point-min) (1- (point))))
6578 (org-at-heading-p))
6579 (1- (point))
6580 (point))))
6581 (setq b (match-beginning 1)))
6582 (outline-flag-region b e nil)))))))
6583 ;; Never hide empty lines at the end of the file.
6584 (save-excursion
6585 (goto-char (point-max))
6586 (outline-previous-heading)
6587 (outline-end-of-heading)
6588 (if (and (looking-at "[ \t\n]+")
6589 (= (match-end 0) (point-max)))
6590 (outline-flag-region (point) (match-end 0) nil))))
6592 (defun org-show-empty-lines-in-parent ()
6593 "Move to the parent and re-show empty lines before visible headlines."
6594 (save-excursion
6595 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6596 (org-cycle-show-empty-lines context))))
6598 (defun org-files-list ()
6599 "Return `org-agenda-files' list, plus all open org-mode files.
6600 This is useful for operations that need to scan all of a user's
6601 open and agenda-wise Org files."
6602 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6603 (dolist (buf (buffer-list))
6604 (with-current-buffer buf
6605 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6606 (let ((file (expand-file-name (buffer-file-name))))
6607 (unless (member file files)
6608 (push file files))))))
6609 files))
6611 (defsubst org-entry-beginning-position ()
6612 "Return the beginning position of the current entry."
6613 (save-excursion (outline-back-to-heading t) (point)))
6615 (defsubst org-entry-end-position ()
6616 "Return the end position of the current entry."
6617 (save-excursion (outline-next-heading) (point)))
6619 (defun org-cycle-hide-drawers (state)
6620 "Re-hide all drawers after a visibility state change."
6621 (when (and (derived-mode-p 'org-mode)
6622 (not (memq state '(overview folded contents))))
6623 (save-excursion
6624 (let* ((globalp (memq state '(contents all)))
6625 (beg (if globalp (point-min) (point)))
6626 (end (if globalp (point-max)
6627 (if (eq state 'children)
6628 (save-excursion (outline-next-heading) (point))
6629 (org-end-of-subtree t)))))
6630 (goto-char beg)
6631 (while (re-search-forward org-drawer-regexp end t)
6632 (org-flag-drawer t))))))
6634 (defun org-cycle-hide-inline-tasks (state)
6635 "Re-hide inline task when switching to 'contents visibility state."
6636 (when (and (eq state 'contents)
6637 (boundp 'org-inlinetask-min-level)
6638 org-inlinetask-min-level)
6639 (hide-sublevels (1- org-inlinetask-min-level))))
6641 (defun org-flag-drawer (flag)
6642 "When FLAG is non-nil, hide the drawer we are within.
6643 Otherwise make it visible."
6644 (save-excursion
6645 (beginning-of-line 1)
6646 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6647 (let ((b (match-end 0)))
6648 (if (re-search-forward
6649 "^[ \t]*:END:"
6650 (save-excursion (outline-next-heading) (point)) t)
6651 (outline-flag-region b (point-at-eol) flag)
6652 (error ":END: line missing at position %s" b))))))
6654 (defun org-subtree-end-visible-p ()
6655 "Is the end of the current subtree visible?"
6656 (pos-visible-in-window-p
6657 (save-excursion (org-end-of-subtree t) (point))))
6659 (defun org-first-headline-recenter (&optional N)
6660 "Move cursor to the first headline and recenter the headline.
6661 Optional argument N means put the headline into the Nth line of the window."
6662 (goto-char (point-min))
6663 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6664 (beginning-of-line)
6665 (recenter (prefix-numeric-value N))))
6667 ;;; Saving and restoring visibility
6669 (defun org-outline-overlay-data (&optional use-markers)
6670 "Return a list of the locations of all outline overlays.
6671 These are overlays with the `invisible' property value `outline'.
6672 The return value is a list of cons cells, with start and stop
6673 positions for each overlay.
6674 If USE-MARKERS is set, return the positions as markers."
6675 (let (beg end)
6676 (save-excursion
6677 (save-restriction
6678 (widen)
6679 (delq nil
6680 (mapcar (lambda (o)
6681 (when (eq (overlay-get o 'invisible) 'outline)
6682 (setq beg (overlay-start o)
6683 end (overlay-end o))
6684 (and beg end (> end beg)
6685 (if use-markers
6686 (cons (move-marker (make-marker) beg)
6687 (move-marker (make-marker) end))
6688 (cons beg end)))))
6689 (overlays-in (point-min) (point-max))))))))
6691 (defun org-set-outline-overlay-data (data)
6692 "Create visibility overlays for all positions in DATA.
6693 DATA should have been made by `org-outline-overlay-data'."
6694 (let (o)
6695 (save-excursion
6696 (save-restriction
6697 (widen)
6698 (show-all)
6699 (mapc (lambda (c)
6700 (outline-flag-region (car c) (cdr c) t))
6701 data)))))
6703 ;;; Folding of blocks
6705 (defvar org-hide-block-overlays nil
6706 "Overlays hiding blocks.")
6707 (make-variable-buffer-local 'org-hide-block-overlays)
6709 (defun org-block-map (function &optional start end)
6710 "Call FUNCTION at the head of all source blocks in the current buffer.
6711 Optional arguments START and END can be used to limit the range."
6712 (let ((start (or start (point-min)))
6713 (end (or end (point-max))))
6714 (save-excursion
6715 (goto-char start)
6716 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6717 (save-excursion
6718 (save-match-data
6719 (goto-char (match-beginning 0))
6720 (funcall function)))))))
6722 (defun org-hide-block-toggle-all ()
6723 "Toggle the visibility of all blocks in the current buffer."
6724 (org-block-map #'org-hide-block-toggle))
6726 (defun org-hide-block-all ()
6727 "Fold all blocks in the current buffer."
6728 (interactive)
6729 (org-show-block-all)
6730 (org-block-map #'org-hide-block-toggle-maybe))
6732 (defun org-show-block-all ()
6733 "Unfold all blocks in the current buffer."
6734 (interactive)
6735 (mapc 'delete-overlay org-hide-block-overlays)
6736 (setq org-hide-block-overlays nil))
6738 (defun org-hide-block-toggle-maybe ()
6739 "Toggle visibility of block at point."
6740 (interactive)
6741 (let ((case-fold-search t))
6742 (if (save-excursion
6743 (beginning-of-line 1)
6744 (looking-at org-block-regexp))
6745 (progn (org-hide-block-toggle)
6746 t) ;; to signal that we took action
6747 nil))) ;; to signal that we did not
6749 (defun org-hide-block-toggle (&optional force)
6750 "Toggle the visibility of the current block."
6751 (interactive)
6752 (save-excursion
6753 (beginning-of-line)
6754 (if (re-search-forward org-block-regexp nil t)
6755 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6756 (end (match-end 0)) ;; end of entire body
6758 (if (memq t (mapcar (lambda (overlay)
6759 (eq (overlay-get overlay 'invisible)
6760 'org-hide-block))
6761 (overlays-at start)))
6762 (if (or (not force) (eq force 'off))
6763 (mapc (lambda (ov)
6764 (when (member ov org-hide-block-overlays)
6765 (setq org-hide-block-overlays
6766 (delq ov org-hide-block-overlays)))
6767 (when (eq (overlay-get ov 'invisible)
6768 'org-hide-block)
6769 (delete-overlay ov)))
6770 (overlays-at start)))
6771 (setq ov (make-overlay start end))
6772 (overlay-put ov 'invisible 'org-hide-block)
6773 ;; make the block accessible to isearch
6774 (overlay-put
6775 ov 'isearch-open-invisible
6776 (lambda (ov)
6777 (when (member ov org-hide-block-overlays)
6778 (setq org-hide-block-overlays
6779 (delq ov org-hide-block-overlays)))
6780 (when (eq (overlay-get ov 'invisible)
6781 'org-hide-block)
6782 (delete-overlay ov))))
6783 (push ov org-hide-block-overlays)))
6784 (error "Not looking at a source block"))))
6786 ;; org-tab-after-check-for-cycling-hook
6787 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6788 ;; Remove overlays when changing major mode
6789 (add-hook 'org-mode-hook
6790 (lambda () (org-add-hook 'change-major-mode-hook
6791 'org-show-block-all 'append 'local)))
6793 ;;; Org-goto
6795 (defvar org-goto-window-configuration nil)
6796 (defvar org-goto-marker nil)
6797 (defvar org-goto-map
6798 (let ((map (make-sparse-keymap)))
6799 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6800 (while (setq cmd (pop cmds))
6801 (substitute-key-definition cmd cmd map global-map)))
6802 (suppress-keymap map)
6803 (org-defkey map "\C-m" 'org-goto-ret)
6804 (org-defkey map [(return)] 'org-goto-ret)
6805 (org-defkey map [(left)] 'org-goto-left)
6806 (org-defkey map [(right)] 'org-goto-right)
6807 (org-defkey map [(control ?g)] 'org-goto-quit)
6808 (org-defkey map "\C-i" 'org-cycle)
6809 (org-defkey map [(tab)] 'org-cycle)
6810 (org-defkey map [(down)] 'outline-next-visible-heading)
6811 (org-defkey map [(up)] 'outline-previous-visible-heading)
6812 (if org-goto-auto-isearch
6813 (if (fboundp 'define-key-after)
6814 (define-key-after map [t] 'org-goto-local-auto-isearch)
6815 nil)
6816 (org-defkey map "q" 'org-goto-quit)
6817 (org-defkey map "n" 'outline-next-visible-heading)
6818 (org-defkey map "p" 'outline-previous-visible-heading)
6819 (org-defkey map "f" 'outline-forward-same-level)
6820 (org-defkey map "b" 'outline-backward-same-level)
6821 (org-defkey map "u" 'outline-up-heading))
6822 (org-defkey map "/" 'org-occur)
6823 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6824 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6825 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6826 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6827 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6828 map))
6830 (defconst org-goto-help
6831 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6832 RET=jump to location [Q]uit and return to previous location
6833 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6835 (defvar org-goto-start-pos) ; dynamically scoped parameter
6837 ;; FIXME: Docstring does not mention both interfaces
6838 (defun org-goto (&optional alternative-interface)
6839 "Look up a different location in the current file, keeping current visibility.
6841 When you want look-up or go to a different location in a
6842 document, the fastest way is often to fold the entire buffer and
6843 then dive into the tree. This method has the disadvantage, that
6844 the previous location will be folded, which may not be what you
6845 want.
6847 This command works around this by showing a copy of the current
6848 buffer in an indirect buffer, in overview mode. You can dive
6849 into the tree in that copy, use org-occur and incremental search
6850 to find a location. When pressing RET or `Q', the command
6851 returns to the original buffer in which the visibility is still
6852 unchanged. After RET it will also jump to the location selected
6853 in the indirect buffer and expose the headline hierarchy above.
6855 With a prefix argument, use the alternative interface: e.g. if
6856 `org-goto-interface' is 'outline use 'outline-path-completion."
6857 (interactive "P")
6858 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6859 (org-refile-use-outline-path t)
6860 (org-refile-target-verify-function nil)
6861 (interface
6862 (if (not alternative-interface)
6863 org-goto-interface
6864 (if (eq org-goto-interface 'outline)
6865 'outline-path-completion
6866 'outline)))
6867 (org-goto-start-pos (point))
6868 (selected-point
6869 (if (eq interface 'outline)
6870 (car (org-get-location (current-buffer) org-goto-help))
6871 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6872 (org-refile-check-position pa)
6873 (nth 3 pa)))))
6874 (if selected-point
6875 (progn
6876 (org-mark-ring-push org-goto-start-pos)
6877 (goto-char selected-point)
6878 (if (or (outline-invisible-p) (org-invisible-p2))
6879 (org-show-context 'org-goto)))
6880 (message "Quit"))))
6882 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6883 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6884 (defvar org-goto-local-auto-isearch-map) ; defined below
6886 (defun org-get-location (buf help)
6887 "Let the user select a location in the Org-mode buffer BUF.
6888 This function uses a recursive edit. It returns the selected position
6889 or nil."
6890 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6891 (isearch-hide-immediately nil)
6892 (isearch-search-fun-function
6893 (lambda () 'org-goto-local-search-headings))
6894 (org-goto-selected-point org-goto-exit-command)
6895 (pop-up-frames nil)
6896 (special-display-buffer-names nil)
6897 (special-display-regexps nil)
6898 (special-display-function nil))
6899 (save-excursion
6900 (save-window-excursion
6901 (delete-other-windows)
6902 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6903 (org-pop-to-buffer-same-window
6904 (condition-case nil
6905 (make-indirect-buffer (current-buffer) "*org-goto*")
6906 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6907 (with-output-to-temp-buffer "*Help*"
6908 (princ help))
6909 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6910 (setq buffer-read-only nil)
6911 (let ((org-startup-truncated t)
6912 (org-startup-folded nil)
6913 (org-startup-align-all-tables nil))
6914 (org-mode)
6915 (org-overview))
6916 (setq buffer-read-only t)
6917 (if (and (boundp 'org-goto-start-pos)
6918 (integer-or-marker-p org-goto-start-pos))
6919 (let ((org-show-hierarchy-above t)
6920 (org-show-siblings t)
6921 (org-show-following-heading t))
6922 (goto-char org-goto-start-pos)
6923 (and (outline-invisible-p) (org-show-context)))
6924 (goto-char (point-min)))
6925 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6926 (message "Select location and press RET")
6927 (use-local-map org-goto-map)
6928 (recursive-edit)
6930 (kill-buffer "*org-goto*")
6931 (cons org-goto-selected-point org-goto-exit-command)))
6933 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6934 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6935 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6936 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6938 (defun org-goto-local-search-headings (string bound noerror)
6939 "Search and make sure that any matches are in headlines."
6940 (catch 'return
6941 (while (if isearch-forward
6942 (search-forward string bound noerror)
6943 (search-backward string bound noerror))
6944 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6945 (and (member :headline context)
6946 (not (member :tags context))))
6947 (throw 'return (point))))))
6949 (defun org-goto-local-auto-isearch ()
6950 "Start isearch."
6951 (interactive)
6952 (goto-char (point-min))
6953 (let ((keys (this-command-keys)))
6954 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6955 (isearch-mode t)
6956 (isearch-process-search-char (string-to-char keys)))))
6958 (defun org-goto-ret (&optional arg)
6959 "Finish `org-goto' by going to the new location."
6960 (interactive "P")
6961 (setq org-goto-selected-point (point)
6962 org-goto-exit-command 'return)
6963 (throw 'exit nil))
6965 (defun org-goto-left ()
6966 "Finish `org-goto' by going to the new location."
6967 (interactive)
6968 (if (org-at-heading-p)
6969 (progn
6970 (beginning-of-line 1)
6971 (setq org-goto-selected-point (point)
6972 org-goto-exit-command 'left)
6973 (throw 'exit nil))
6974 (error "Not on a heading")))
6976 (defun org-goto-right ()
6977 "Finish `org-goto' by going to the new location."
6978 (interactive)
6979 (if (org-at-heading-p)
6980 (progn
6981 (setq org-goto-selected-point (point)
6982 org-goto-exit-command 'right)
6983 (throw 'exit nil))
6984 (error "Not on a heading")))
6986 (defun org-goto-quit ()
6987 "Finish `org-goto' without cursor motion."
6988 (interactive)
6989 (setq org-goto-selected-point nil)
6990 (setq org-goto-exit-command 'quit)
6991 (throw 'exit nil))
6993 ;;; Indirect buffer display of subtrees
6995 (defvar org-indirect-dedicated-frame nil
6996 "This is the frame being used for indirect tree display.")
6997 (defvar org-last-indirect-buffer nil)
6999 (defun org-tree-to-indirect-buffer (&optional arg)
7000 "Create indirect buffer and narrow it to current subtree.
7001 With a numerical prefix ARG, go up to this level and then take that tree.
7002 If ARG is negative, go up that many levels.
7004 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7005 indirect buffer previously made with this command, to avoid proliferation of
7006 indirect buffers. However, when you call the command with a \
7007 \\[universal-argument] prefix, or
7008 when `org-indirect-buffer-display' is `new-frame', the last buffer
7009 is kept so that you can work with several indirect buffers at the same time.
7010 If `org-indirect-buffer-display' is `dedicated-frame', the \
7011 \\[universal-argument] prefix also
7012 requests that a new frame be made for the new buffer, so that the dedicated
7013 frame is not changed."
7014 (interactive "P")
7015 (let ((cbuf (current-buffer))
7016 (cwin (selected-window))
7017 (pos (point))
7018 beg end level heading ibuf)
7019 (save-excursion
7020 (org-back-to-heading t)
7021 (when (numberp arg)
7022 (setq level (org-outline-level))
7023 (if (< arg 0) (setq arg (+ level arg)))
7024 (while (> (setq level (org-outline-level)) arg)
7025 (org-up-heading-safe)))
7026 (setq beg (point)
7027 heading (org-get-heading))
7028 (org-end-of-subtree t t)
7029 (if (org-at-heading-p) (backward-char 1))
7030 (setq end (point)))
7031 (if (and (buffer-live-p org-last-indirect-buffer)
7032 (not (eq org-indirect-buffer-display 'new-frame))
7033 (not arg))
7034 (kill-buffer org-last-indirect-buffer))
7035 (setq ibuf (org-get-indirect-buffer cbuf)
7036 org-last-indirect-buffer ibuf)
7037 (cond
7038 ((or (eq org-indirect-buffer-display 'new-frame)
7039 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7040 (select-frame (make-frame))
7041 (delete-other-windows)
7042 (org-pop-to-buffer-same-window ibuf)
7043 (org-set-frame-title heading))
7044 ((eq org-indirect-buffer-display 'dedicated-frame)
7045 (raise-frame
7046 (select-frame (or (and org-indirect-dedicated-frame
7047 (frame-live-p org-indirect-dedicated-frame)
7048 org-indirect-dedicated-frame)
7049 (setq org-indirect-dedicated-frame (make-frame)))))
7050 (delete-other-windows)
7051 (org-pop-to-buffer-same-window ibuf)
7052 (org-set-frame-title (concat "Indirect: " heading)))
7053 ((eq org-indirect-buffer-display 'current-window)
7054 (org-pop-to-buffer-same-window ibuf))
7055 ((eq org-indirect-buffer-display 'other-window)
7056 (pop-to-buffer ibuf))
7057 (t (error "Invalid value")))
7058 (if (featurep 'xemacs)
7059 (save-excursion (org-mode) (turn-on-font-lock)))
7060 (narrow-to-region beg end)
7061 (show-all)
7062 (goto-char pos)
7063 (run-hook-with-args 'org-cycle-hook 'all)
7064 (and (window-live-p cwin) (select-window cwin))))
7066 (defun org-get-indirect-buffer (&optional buffer)
7067 (setq buffer (or buffer (current-buffer)))
7068 (let ((n 1) (base (buffer-name buffer)) bname)
7069 (while (buffer-live-p
7070 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7071 (setq n (1+ n)))
7072 (condition-case nil
7073 (make-indirect-buffer buffer bname 'clone)
7074 (error (make-indirect-buffer buffer bname)))))
7076 (defun org-set-frame-title (title)
7077 "Set the title of the current frame to the string TITLE."
7078 ;; FIXME: how to name a single frame in XEmacs???
7079 (unless (featurep 'xemacs)
7080 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7082 ;;;; Structure editing
7084 ;;; Inserting headlines
7086 (defun org-previous-line-empty-p ()
7087 (save-excursion
7088 (and (not (bobp))
7089 (or (beginning-of-line 0) t)
7090 (save-match-data
7091 (looking-at "[ \t]*$")))))
7093 (defun org-insert-heading (&optional force-heading invisible-ok)
7094 "Insert a new heading or item with same depth at point.
7095 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7096 If point is at the beginning of a headline, insert a sibling before the
7097 current headline. If point is not at the beginning, split the line,
7098 create the new headline with the text in the current line after point
7099 \(but see also the variable `org-M-RET-may-split-line').
7101 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7102 This is important for non-interactive uses of the command."
7103 (interactive "P")
7104 (if (or (= (buffer-size) 0)
7105 (and (not (save-excursion
7106 (and (ignore-errors (org-back-to-heading invisible-ok))
7107 (org-at-heading-p))))
7108 (or force-heading (not (org-in-item-p)))))
7109 (progn
7110 (insert "\n* ")
7111 (run-hooks 'org-insert-heading-hook))
7112 (when (or force-heading (not (org-insert-item)))
7113 (let* ((empty-line-p nil)
7114 (level nil)
7115 (on-heading (org-at-heading-p))
7116 (head (save-excursion
7117 (condition-case nil
7118 (progn
7119 (org-back-to-heading invisible-ok)
7120 (when (and (not on-heading)
7121 (featurep 'org-inlinetask)
7122 (integerp org-inlinetask-min-level)
7123 (>= (length (match-string 0))
7124 org-inlinetask-min-level))
7125 ;; Find a heading level before the inline task
7126 (while (and (setq level (org-up-heading-safe))
7127 (>= level org-inlinetask-min-level)))
7128 (if (org-at-heading-p)
7129 (org-back-to-heading invisible-ok)
7130 (error "This should not happen")))
7131 (setq empty-line-p (org-previous-line-empty-p))
7132 (match-string 0))
7133 (error "*"))))
7134 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7135 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7136 pos hide-previous previous-pos)
7137 (cond
7138 ((and (org-at-heading-p) (bolp)
7139 (or (bobp)
7140 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7141 ;; insert before the current line
7142 (open-line (if blank 2 1)))
7143 ((and (bolp)
7144 (not org-insert-heading-respect-content)
7145 (or (bobp)
7146 (save-excursion
7147 (backward-char 1) (not (outline-invisible-p)))))
7148 ;; insert right here
7149 nil)
7151 ;; somewhere in the line
7152 (save-excursion
7153 (setq previous-pos (point-at-bol))
7154 (end-of-line)
7155 (setq hide-previous (outline-invisible-p)))
7156 (and org-insert-heading-respect-content (org-show-subtree))
7157 (let ((split
7158 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7159 (save-excursion
7160 (let ((p (point)))
7161 (goto-char (point-at-bol))
7162 (and (looking-at org-complex-heading-regexp)
7163 (match-beginning 4)
7164 (> p (match-beginning 4)))))))
7165 tags pos)
7166 (cond
7167 (org-insert-heading-respect-content
7168 (org-end-of-subtree nil t)
7169 (when (featurep 'org-inlinetask)
7170 (while (and (not (eobp))
7171 (looking-at "\\(\\*+\\)[ \t]+")
7172 (>= (length (match-string 1))
7173 org-inlinetask-min-level))
7174 (org-end-of-subtree nil t)))
7175 (or (bolp) (newline))
7176 (or (org-previous-line-empty-p)
7177 (and blank (newline)))
7178 (open-line 1))
7179 ((org-at-heading-p)
7180 (when hide-previous
7181 (show-children)
7182 (org-show-entry))
7183 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7184 (setq tags (and (match-end 2) (match-string 2)))
7185 (and (match-end 1)
7186 (delete-region (match-beginning 1) (match-end 1)))
7187 (setq pos (point-at-bol))
7188 (or split (end-of-line 1))
7189 (delete-horizontal-space)
7190 (if (string-match "\\`\\*+\\'"
7191 (buffer-substring (point-at-bol) (point)))
7192 (insert " "))
7193 (newline (if blank 2 1))
7194 (when tags
7195 (save-excursion
7196 (goto-char pos)
7197 (end-of-line 1)
7198 (insert " " tags)
7199 (org-set-tags nil 'align))))
7201 (or split (end-of-line 1))
7202 (newline (if blank 2 1)))))))
7203 (insert head) (just-one-space)
7204 (setq pos (point))
7205 (end-of-line 1)
7206 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7207 (when (and org-insert-heading-respect-content hide-previous)
7208 (save-excursion
7209 (goto-char previous-pos)
7210 (hide-subtree)))
7211 (run-hooks 'org-insert-heading-hook)))))
7213 (defun org-get-heading (&optional no-tags no-todo)
7214 "Return the heading of the current entry, without the stars.
7215 When NO-TAGS is non-nil, don't include tags.
7216 When NO-TODO is non-nil, don't include TODO keywords."
7217 (save-excursion
7218 (org-back-to-heading t)
7219 (cond
7220 ((and no-tags no-todo)
7221 (looking-at org-complex-heading-regexp)
7222 (match-string 4))
7223 (no-tags
7224 (looking-at (concat org-outline-regexp
7225 "\\(.*?\\)"
7226 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7227 (match-string 1))
7228 (no-todo
7229 (looking-at org-todo-line-regexp)
7230 (match-string 3))
7231 (t (looking-at org-heading-regexp)
7232 (match-string 2)))))
7234 (defun org-heading-components ()
7235 "Return the components of the current heading.
7236 This is a list with the following elements:
7237 - the level as an integer
7238 - the reduced level, different if `org-odd-levels-only' is set.
7239 - the TODO keyword, or nil
7240 - the priority character, like ?A, or nil if no priority is given
7241 - the headline text itself, or the tags string if no headline text
7242 - the tags string, or nil."
7243 (save-excursion
7244 (org-back-to-heading t)
7245 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7246 (list (length (match-string 1))
7247 (org-reduced-level (length (match-string 1)))
7248 (org-match-string-no-properties 2)
7249 (and (match-end 3) (aref (match-string 3) 2))
7250 (org-match-string-no-properties 4)
7251 (org-match-string-no-properties 5)))))
7253 (defun org-get-entry ()
7254 "Get the entry text, after heading, entire subtree."
7255 (save-excursion
7256 (org-back-to-heading t)
7257 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7259 (defun org-insert-heading-after-current ()
7260 "Insert a new heading with same level as current, after current subtree."
7261 (interactive)
7262 (org-back-to-heading)
7263 (org-insert-heading)
7264 (org-move-subtree-down)
7265 (end-of-line 1))
7267 (defun org-insert-heading-respect-content ()
7268 (interactive)
7269 (let ((org-insert-heading-respect-content t))
7270 (org-insert-heading t)))
7272 (defun org-insert-todo-heading-respect-content (&optional force-state)
7273 (interactive "P")
7274 (let ((org-insert-heading-respect-content t))
7275 (org-insert-todo-heading force-state t)))
7277 (defun org-insert-todo-heading (arg &optional force-heading)
7278 "Insert a new heading with the same level and TODO state as current heading.
7279 If the heading has no TODO state, or if the state is DONE, use the first
7280 state (TODO by default). Also with prefix arg, force first state."
7281 (interactive "P")
7282 (when (or force-heading (not (org-insert-item 'checkbox)))
7283 (org-insert-heading force-heading)
7284 (save-excursion
7285 (org-back-to-heading)
7286 (outline-previous-heading)
7287 (looking-at org-todo-line-regexp))
7288 (let*
7289 ((new-mark-x
7290 (if (or arg
7291 (not (match-beginning 2))
7292 (member (match-string 2) org-done-keywords))
7293 (car org-todo-keywords-1)
7294 (match-string 2)))
7295 (new-mark
7297 (run-hook-with-args-until-success
7298 'org-todo-get-default-hook new-mark-x nil)
7299 new-mark-x)))
7300 (beginning-of-line 1)
7301 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7302 (if org-treat-insert-todo-heading-as-state-change
7303 (org-todo new-mark)
7304 (insert new-mark " "))))
7305 (when org-provide-todo-statistics
7306 (org-update-parent-todo-statistics))))
7308 (defun org-insert-subheading (arg)
7309 "Insert a new subheading and demote it.
7310 Works for outline headings and for plain lists alike."
7311 (interactive "P")
7312 (org-insert-heading arg)
7313 (cond
7314 ((org-at-heading-p) (org-do-demote))
7315 ((org-at-item-p) (org-indent-item))))
7317 (defun org-insert-todo-subheading (arg)
7318 "Insert a new subheading with TODO keyword or checkbox and demote it.
7319 Works for outline headings and for plain lists alike."
7320 (interactive "P")
7321 (org-insert-todo-heading arg)
7322 (cond
7323 ((org-at-heading-p) (org-do-demote))
7324 ((org-at-item-p) (org-indent-item))))
7326 ;;; Promotion and Demotion
7328 (defvar org-after-demote-entry-hook nil
7329 "Hook run after an entry has been demoted.
7330 The cursor will be at the beginning of the entry.
7331 When a subtree is being demoted, the hook will be called for each node.")
7333 (defvar org-after-promote-entry-hook nil
7334 "Hook run after an entry has been promoted.
7335 The cursor will be at the beginning of the entry.
7336 When a subtree is being promoted, the hook will be called for each node.")
7338 (defun org-promote-subtree ()
7339 "Promote the entire subtree.
7340 See also `org-promote'."
7341 (interactive)
7342 (save-excursion
7343 (org-with-limited-levels (org-map-tree 'org-promote)))
7344 (org-fix-position-after-promote))
7346 (defun org-demote-subtree ()
7347 "Demote the entire subtree. See `org-demote'.
7348 See also `org-promote'."
7349 (interactive)
7350 (save-excursion
7351 (org-with-limited-levels (org-map-tree 'org-demote)))
7352 (org-fix-position-after-promote))
7355 (defun org-do-promote ()
7356 "Promote the current heading higher up the tree.
7357 If the region is active in `transient-mark-mode', promote all headings
7358 in the region."
7359 (interactive)
7360 (save-excursion
7361 (if (org-region-active-p)
7362 (org-map-region 'org-promote (region-beginning) (region-end))
7363 (org-promote)))
7364 (org-fix-position-after-promote))
7366 (defun org-do-demote ()
7367 "Demote the current heading lower down the tree.
7368 If the region is active in `transient-mark-mode', demote all headings
7369 in the region."
7370 (interactive)
7371 (save-excursion
7372 (if (org-region-active-p)
7373 (org-map-region 'org-demote (region-beginning) (region-end))
7374 (org-demote)))
7375 (org-fix-position-after-promote))
7377 (defun org-fix-position-after-promote ()
7378 "Make sure that after pro/demotion cursor position is right."
7379 (let ((pos (point)))
7380 (when (save-excursion
7381 (beginning-of-line 1)
7382 (looking-at org-todo-line-regexp)
7383 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7384 (cond ((eobp) (insert " "))
7385 ((eolp) (insert " "))
7386 ((equal (char-after) ?\ ) (forward-char 1))))))
7388 (defun org-current-level ()
7389 "Return the level of the current entry, or nil if before the first headline.
7390 The level is the number of stars at the beginning of the headline."
7391 (save-excursion
7392 (org-with-limited-levels
7393 (if (ignore-errors (org-back-to-heading t))
7394 (funcall outline-level)))))
7396 (defun org-get-previous-line-level ()
7397 "Return the outline depth of the last headline before the current line.
7398 Returns 0 for the first headline in the buffer, and nil if before the
7399 first headline."
7400 (let ((current-level (org-current-level))
7401 (prev-level (when (> (line-number-at-pos) 1)
7402 (save-excursion
7403 (beginning-of-line 0)
7404 (org-current-level)))))
7405 (cond ((null current-level) nil) ; Before first headline
7406 ((null prev-level) 0) ; At first headline
7407 (prev-level))))
7409 (defun org-reduced-level (l)
7410 "Compute the effective level of a heading.
7411 This takes into account the setting of `org-odd-levels-only'."
7412 (cond
7413 ((zerop l) 0)
7414 (org-odd-levels-only (1+ (floor (/ l 2))))
7415 (t l)))
7417 (defun org-level-increment ()
7418 "Return the number of stars that will be added or removed at a
7419 time to headlines when structure editing, based on the value of
7420 `org-odd-levels-only'."
7421 (if org-odd-levels-only 2 1))
7423 (defun org-get-valid-level (level &optional change)
7424 "Rectify a level change under the influence of `org-odd-levels-only'
7425 LEVEL is a current level, CHANGE is by how much the level should be
7426 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7427 even level numbers will become the next higher odd number."
7428 (if org-odd-levels-only
7429 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7430 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7431 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7432 (max 1 (+ level (or change 0)))))
7434 (if (boundp 'define-obsolete-function-alias)
7435 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7436 (define-obsolete-function-alias 'org-get-legal-level
7437 'org-get-valid-level)
7438 (define-obsolete-function-alias 'org-get-legal-level
7439 'org-get-valid-level "23.1")))
7441 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7442 ;; ̀org-with-limited-levels'
7443 (defun org-promote ()
7444 "Promote the current heading higher up the tree.
7445 If the region is active in `transient-mark-mode', promote all headings
7446 in the region."
7447 (org-back-to-heading t)
7448 (let* ((level (save-match-data (funcall outline-level)))
7449 (after-change-functions (remove 'flyspell-after-change-function
7450 after-change-functions))
7451 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7452 (diff (abs (- level (length up-head) -1))))
7453 (cond ((and (= level 1) org-called-with-limited-levels
7454 org-allow-promoting-top-level-subtree)
7455 (replace-match "# " nil t))
7456 ((= level 1)
7457 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7458 (t (replace-match up-head nil t)))
7459 ;; Fixup tag positioning
7460 (unless (= level 1)
7461 (and org-auto-align-tags (org-set-tags nil t))
7462 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7463 (run-hooks 'org-after-promote-entry-hook)))
7465 (defun org-demote ()
7466 "Demote the current heading lower down the tree.
7467 If the region is active in `transient-mark-mode', demote all headings
7468 in the region."
7469 (org-back-to-heading t)
7470 (let* ((level (save-match-data (funcall outline-level)))
7471 (after-change-functions (remove 'flyspell-after-change-function
7472 after-change-functions))
7473 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7474 (diff (abs (- level (length down-head) -1))))
7475 (replace-match down-head nil t)
7476 ;; Fixup tag positioning
7477 (and org-auto-align-tags (org-set-tags nil t))
7478 (if org-adapt-indentation (org-fixup-indentation diff))
7479 (run-hooks 'org-after-demote-entry-hook)))
7481 (defun org-cycle-level ()
7482 "Cycle the level of an empty headline through possible states.
7483 This goes first to child, then to parent, level, then up the hierarchy.
7484 After top level, it switches back to sibling level."
7485 (interactive)
7486 (let ((org-adapt-indentation nil))
7487 (when (org-point-at-end-of-empty-headline)
7488 (setq this-command 'org-cycle-level) ; Only needed for caching
7489 (let ((cur-level (org-current-level))
7490 (prev-level (org-get-previous-line-level)))
7491 (cond
7492 ;; If first headline in file, promote to top-level.
7493 ((= prev-level 0)
7494 (loop repeat (/ (- cur-level 1) (org-level-increment))
7495 do (org-do-promote)))
7496 ;; If same level as prev, demote one.
7497 ((= prev-level cur-level)
7498 (org-do-demote))
7499 ;; If parent is top-level, promote to top level if not already.
7500 ((= prev-level 1)
7501 (loop repeat (/ (- cur-level 1) (org-level-increment))
7502 do (org-do-promote)))
7503 ;; If top-level, return to prev-level.
7504 ((= cur-level 1)
7505 (loop repeat (/ (- prev-level 1) (org-level-increment))
7506 do (org-do-demote)))
7507 ;; If less than prev-level, promote one.
7508 ((< cur-level prev-level)
7509 (org-do-promote))
7510 ;; If deeper than prev-level, promote until higher than
7511 ;; prev-level.
7512 ((> cur-level prev-level)
7513 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7514 do (org-do-promote))))
7515 t))))
7517 (defun org-map-tree (fun)
7518 "Call FUN for every heading underneath the current one."
7519 (org-back-to-heading)
7520 (let ((level (funcall outline-level)))
7521 (save-excursion
7522 (funcall fun)
7523 (while (and (progn
7524 (outline-next-heading)
7525 (> (funcall outline-level) level))
7526 (not (eobp)))
7527 (funcall fun)))))
7529 (defun org-map-region (fun beg end)
7530 "Call FUN for every heading between BEG and END."
7531 (let ((org-ignore-region t))
7532 (save-excursion
7533 (setq end (copy-marker end))
7534 (goto-char beg)
7535 (if (and (re-search-forward org-outline-regexp-bol nil t)
7536 (< (point) end))
7537 (funcall fun))
7538 (while (and (progn
7539 (outline-next-heading)
7540 (< (point) end))
7541 (not (eobp)))
7542 (funcall fun)))))
7544 (defvar org-property-end-re) ; silence byte-compiler
7545 (defun org-fixup-indentation (diff)
7546 "Change the indentation in the current entry by DIFF.
7547 However, if any line in the current entry has no indentation, or if it
7548 would end up with no indentation after the change, nothing at all is done."
7549 (save-excursion
7550 (let ((end (save-excursion (outline-next-heading)
7551 (point-marker)))
7552 (prohibit (if (> diff 0)
7553 "^\\S-"
7554 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7555 col)
7556 (unless (save-excursion (end-of-line 1)
7557 (re-search-forward prohibit end t))
7558 (while (and (< (point) end)
7559 (re-search-forward "^[ \t]+" end t))
7560 (goto-char (match-end 0))
7561 (setq col (current-column))
7562 (if (< diff 0) (replace-match ""))
7563 (org-indent-to-column (+ diff col))))
7564 (move-marker end nil))))
7566 (defun org-convert-to-odd-levels ()
7567 "Convert an org-mode file with all levels allowed to one with odd levels.
7568 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7569 level 5 etc."
7570 (interactive)
7571 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7572 (let ((outline-level 'org-outline-level)
7573 (org-odd-levels-only nil) n)
7574 (save-excursion
7575 (goto-char (point-min))
7576 (while (re-search-forward "^\\*\\*+ " nil t)
7577 (setq n (- (length (match-string 0)) 2))
7578 (while (>= (setq n (1- n)) 0)
7579 (org-demote))
7580 (end-of-line 1))))))
7582 (defun org-convert-to-oddeven-levels ()
7583 "Convert an org-mode file with only odd levels to one with odd/even levels.
7584 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7585 file contains a section with an even level, conversion would
7586 destroy the structure of the file. An error is signaled in this
7587 case."
7588 (interactive)
7589 (goto-char (point-min))
7590 ;; First check if there are no even levels
7591 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7592 (org-show-context t)
7593 (error "Not all levels are odd in this file. Conversion not possible"))
7594 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7595 (let ((outline-regexp org-outline-regexp)
7596 (outline-level 'org-outline-level)
7597 (org-odd-levels-only nil) n)
7598 (save-excursion
7599 (goto-char (point-min))
7600 (while (re-search-forward "^\\*\\*+ " nil t)
7601 (setq n (/ (1- (length (match-string 0))) 2))
7602 (while (>= (setq n (1- n)) 0)
7603 (org-promote))
7604 (end-of-line 1))))))
7606 (defun org-tr-level (n)
7607 "Make N odd if required."
7608 (if org-odd-levels-only (1+ (/ n 2)) n))
7610 ;;; Vertical tree motion, cutting and pasting of subtrees
7612 (defun org-move-subtree-up (&optional arg)
7613 "Move the current subtree up past ARG headlines of the same level."
7614 (interactive "p")
7615 (org-move-subtree-down (- (prefix-numeric-value arg))))
7617 (defun org-move-subtree-down (&optional arg)
7618 "Move the current subtree down past ARG headlines of the same level."
7619 (interactive "p")
7620 (setq arg (prefix-numeric-value arg))
7621 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7622 'org-get-last-sibling))
7623 (ins-point (make-marker))
7624 (cnt (abs arg))
7625 (col (current-column))
7626 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7627 ;; Select the tree
7628 (org-back-to-heading)
7629 (setq beg0 (point))
7630 (save-excursion
7631 (setq ne-beg (org-back-over-empty-lines))
7632 (setq beg (point)))
7633 (save-match-data
7634 (save-excursion (outline-end-of-heading)
7635 (setq folded (outline-invisible-p)))
7636 (outline-end-of-subtree))
7637 (outline-next-heading)
7638 (setq ne-end (org-back-over-empty-lines))
7639 (setq end (point))
7640 (goto-char beg0)
7641 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7642 ;; include less whitespace
7643 (save-excursion
7644 (goto-char beg)
7645 (forward-line (- ne-beg ne-end))
7646 (setq beg (point))))
7647 ;; Find insertion point, with error handling
7648 (while (> cnt 0)
7649 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7650 (progn (goto-char beg0)
7651 (error "Cannot move past superior level or buffer limit")))
7652 (setq cnt (1- cnt)))
7653 (if (> arg 0)
7654 ;; Moving forward - still need to move over subtree
7655 (progn (org-end-of-subtree t t)
7656 (save-excursion
7657 (org-back-over-empty-lines)
7658 (or (bolp) (newline)))))
7659 (setq ne-ins (org-back-over-empty-lines))
7660 (move-marker ins-point (point))
7661 (setq txt (buffer-substring beg end))
7662 (org-save-markers-in-region beg end)
7663 (delete-region beg end)
7664 (org-remove-empty-overlays-at beg)
7665 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7666 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7667 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7668 (let ((bbb (point)))
7669 (insert-before-markers txt)
7670 (org-reinstall-markers-in-region bbb)
7671 (move-marker ins-point bbb))
7672 (or (bolp) (insert "\n"))
7673 (setq ins-end (point))
7674 (goto-char ins-point)
7675 (org-skip-whitespace)
7676 (when (and (< arg 0)
7677 (org-first-sibling-p)
7678 (> ne-ins ne-beg))
7679 ;; Move whitespace back to beginning
7680 (save-excursion
7681 (goto-char ins-end)
7682 (let ((kill-whole-line t))
7683 (kill-line (- ne-ins ne-beg)) (point)))
7684 (insert (make-string (- ne-ins ne-beg) ?\n)))
7685 (move-marker ins-point nil)
7686 (if folded
7687 (hide-subtree)
7688 (org-show-entry)
7689 (show-children)
7690 (org-cycle-hide-drawers 'children))
7691 (org-clean-visibility-after-subtree-move)
7692 ;; move back to the initial column we were at
7693 (move-to-column col)))
7695 (defvar org-subtree-clip ""
7696 "Clipboard for cut and paste of subtrees.
7697 This is actually only a copy of the kill, because we use the normal kill
7698 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7700 (defvar org-subtree-clip-folded nil
7701 "Was the last copied subtree folded?
7702 This is used to fold the tree back after pasting.")
7704 (defun org-cut-subtree (&optional n)
7705 "Cut the current subtree into the clipboard.
7706 With prefix arg N, cut this many sequential subtrees.
7707 This is a short-hand for marking the subtree and then cutting it."
7708 (interactive "p")
7709 (org-copy-subtree n 'cut))
7711 (defun org-copy-subtree (&optional n cut force-store-markers)
7712 "Cut the current subtree into the clipboard.
7713 With prefix arg N, cut this many sequential subtrees.
7714 This is a short-hand for marking the subtree and then copying it.
7715 If CUT is non-nil, actually cut the subtree.
7716 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7717 of some markers in the region, even if CUT is non-nil. This is
7718 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7719 (interactive "p")
7720 (let (beg end folded (beg0 (point)))
7721 (if (org-called-interactively-p 'any)
7722 (org-back-to-heading nil) ; take what looks like a subtree
7723 (org-back-to-heading t)) ; take what is really there
7724 (org-back-over-empty-lines)
7725 (setq beg (point))
7726 (skip-chars-forward " \t\r\n")
7727 (save-match-data
7728 (save-excursion (outline-end-of-heading)
7729 (setq folded (outline-invisible-p)))
7730 (condition-case nil
7731 (org-forward-heading-same-level (1- n) t)
7732 (error nil))
7733 (org-end-of-subtree t t))
7734 (org-back-over-empty-lines)
7735 (setq end (point))
7736 (goto-char beg0)
7737 (when (> end beg)
7738 (setq org-subtree-clip-folded folded)
7739 (when (or cut force-store-markers)
7740 (org-save-markers-in-region beg end))
7741 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7742 (setq org-subtree-clip (current-kill 0))
7743 (message "%s: Subtree(s) with %d characters"
7744 (if cut "Cut" "Copied")
7745 (length org-subtree-clip)))))
7747 (defun org-paste-subtree (&optional level tree for-yank)
7748 "Paste the clipboard as a subtree, with modification of headline level.
7749 The entire subtree is promoted or demoted in order to match a new headline
7750 level.
7752 If the cursor is at the beginning of a headline, the same level as
7753 that headline is used to paste the tree
7755 If not, the new level is derived from the *visible* headings
7756 before and after the insertion point, and taken to be the inferior headline
7757 level of the two. So if the previous visible heading is level 3 and the
7758 next is level 4 (or vice versa), level 4 will be used for insertion.
7759 This makes sure that the subtree remains an independent subtree and does
7760 not swallow low level entries.
7762 You can also force a different level, either by using a numeric prefix
7763 argument, or by inserting the heading marker by hand. For example, if the
7764 cursor is after \"*****\", then the tree will be shifted to level 5.
7766 If optional TREE is given, use this text instead of the kill ring.
7768 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7769 move back over whitespace before inserting, and move point to the end of
7770 the inserted text when done."
7771 (interactive "P")
7772 (setq tree (or tree (and kill-ring (current-kill 0))))
7773 (unless (org-kill-is-subtree-p tree)
7774 (error "%s"
7775 (substitute-command-keys
7776 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7777 (org-with-limited-levels
7778 (let* ((visp (not (outline-invisible-p)))
7779 (txt tree)
7780 (^re_ "\\(\\*+\\)[ \t]*")
7781 (old-level (if (string-match org-outline-regexp-bol txt)
7782 (- (match-end 0) (match-beginning 0) 1)
7783 -1))
7784 (force-level (cond (level (prefix-numeric-value level))
7785 ((and (looking-at "[ \t]*$")
7786 (string-match
7787 "^\\*+$" (buffer-substring
7788 (point-at-bol) (point))))
7789 (- (match-end 1) (match-beginning 1)))
7790 ((and (bolp)
7791 (looking-at org-outline-regexp))
7792 (- (match-end 0) (point) 1))))
7793 (previous-level (save-excursion
7794 (condition-case nil
7795 (progn
7796 (outline-previous-visible-heading 1)
7797 (if (looking-at ^re_)
7798 (- (match-end 0) (match-beginning 0) 1)
7800 (error 1))))
7801 (next-level (save-excursion
7802 (condition-case nil
7803 (progn
7804 (or (looking-at org-outline-regexp)
7805 (outline-next-visible-heading 1))
7806 (if (looking-at ^re_)
7807 (- (match-end 0) (match-beginning 0) 1)
7809 (error 1))))
7810 (new-level (or force-level (max previous-level next-level)))
7811 (shift (if (or (= old-level -1)
7812 (= new-level -1)
7813 (= old-level new-level))
7815 (- new-level old-level)))
7816 (delta (if (> shift 0) -1 1))
7817 (func (if (> shift 0) 'org-demote 'org-promote))
7818 (org-odd-levels-only nil)
7819 beg end newend)
7820 ;; Remove the forced level indicator
7821 (if force-level
7822 (delete-region (point-at-bol) (point)))
7823 ;; Paste
7824 (beginning-of-line (if (bolp) 1 2))
7825 (unless for-yank (org-back-over-empty-lines))
7826 (setq beg (point))
7827 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7828 (insert-before-markers txt)
7829 (unless (string-match "\n\\'" txt) (insert "\n"))
7830 (setq newend (point))
7831 (org-reinstall-markers-in-region beg)
7832 (setq end (point))
7833 (goto-char beg)
7834 (skip-chars-forward " \t\n\r")
7835 (setq beg (point))
7836 (if (and (outline-invisible-p) visp)
7837 (save-excursion (outline-show-heading)))
7838 ;; Shift if necessary
7839 (unless (= shift 0)
7840 (save-restriction
7841 (narrow-to-region beg end)
7842 (while (not (= shift 0))
7843 (org-map-region func (point-min) (point-max))
7844 (setq shift (+ delta shift)))
7845 (goto-char (point-min))
7846 (setq newend (point-max))))
7847 (when (or (org-called-interactively-p 'interactive) for-yank)
7848 (message "Clipboard pasted as level %d subtree" new-level))
7849 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7850 kill-ring
7851 (eq org-subtree-clip (current-kill 0))
7852 org-subtree-clip-folded)
7853 ;; The tree was folded before it was killed/copied
7854 (hide-subtree))
7855 (and for-yank (goto-char newend)))))
7857 (defun org-kill-is-subtree-p (&optional txt)
7858 "Check if the current kill is an outline subtree, or a set of trees.
7859 Returns nil if kill does not start with a headline, or if the first
7860 headline level is not the largest headline level in the tree.
7861 So this will actually accept several entries of equal levels as well,
7862 which is OK for `org-paste-subtree'.
7863 If optional TXT is given, check this string instead of the current kill."
7864 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7865 (re (org-get-limited-outline-regexp))
7866 (^re (concat "^" re))
7867 (start-level (and kill
7868 (string-match
7869 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7870 kill)
7871 (- (match-end 2) (match-beginning 2) 1)))
7872 (start (1+ (or (match-beginning 2) -1))))
7873 (if (not start-level)
7874 (progn
7875 nil) ;; does not even start with a heading
7876 (catch 'exit
7877 (while (setq start (string-match ^re kill (1+ start)))
7878 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7879 (throw 'exit nil)))
7880 t))))
7882 (defvar org-markers-to-move nil
7883 "Markers that should be moved with a cut-and-paste operation.
7884 Those markers are stored together with their positions relative to
7885 the start of the region.")
7887 (defun org-save-markers-in-region (beg end)
7888 "Check markers in region.
7889 If these markers are between BEG and END, record their position relative
7890 to BEG, so that after moving the block of text, we can put the markers back
7891 into place.
7892 This function gets called just before an entry or tree gets cut from the
7893 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7894 called immediately, to move the markers with the entries."
7895 (setq org-markers-to-move nil)
7896 (when (featurep 'org-clock)
7897 (org-clock-save-markers-for-cut-and-paste beg end))
7898 (when (featurep 'org-agenda)
7899 (org-agenda-save-markers-for-cut-and-paste beg end)))
7901 (defun org-check-and-save-marker (marker beg end)
7902 "Check if MARKER is between BEG and END.
7903 If yes, remember the marker and the distance to BEG."
7904 (when (and (marker-buffer marker)
7905 (equal (marker-buffer marker) (current-buffer)))
7906 (if (and (>= marker beg) (< marker end))
7907 (push (cons marker (- marker beg)) org-markers-to-move))))
7909 (defun org-reinstall-markers-in-region (beg)
7910 "Move all remembered markers to their position relative to BEG."
7911 (mapc (lambda (x)
7912 (move-marker (car x) (+ beg (cdr x))))
7913 org-markers-to-move)
7914 (setq org-markers-to-move nil))
7916 (defun org-narrow-to-subtree ()
7917 "Narrow buffer to the current subtree."
7918 (interactive)
7919 (save-excursion
7920 (save-match-data
7921 (org-with-limited-levels
7922 (narrow-to-region
7923 (progn (org-back-to-heading t) (point))
7924 (progn (org-end-of-subtree t t)
7925 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7926 (point)))))))
7928 (defun org-narrow-to-block ()
7929 "Narrow buffer to the current block."
7930 (interactive)
7931 (let* ((case-fold-search t)
7932 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7933 "^[ \t]*#\\+end_.*")))
7934 (if blockp
7935 (narrow-to-region (car blockp) (cdr blockp))
7936 (error "Not in a block"))))
7938 (eval-when-compile
7939 (defvar org-property-drawer-re))
7941 (defvar org-property-start-re) ;; defined below
7942 (defun org-clone-subtree-with-time-shift (n &optional shift)
7943 "Clone the task (subtree) at point N times.
7944 The clones will be inserted as siblings.
7946 In interactive use, the user will be prompted for the number of
7947 clones to be produced, and for a time SHIFT, which may be a
7948 repeater as used in time stamps, for example `+3d'.
7950 When a valid repeater is given and the entry contains any time
7951 stamps, the clones will become a sequence in time, with time
7952 stamps in the subtree shifted for each clone produced. If SHIFT
7953 is nil or the empty string, time stamps will be left alone. The
7954 ID property of the original subtree is removed.
7956 If the original subtree did contain time stamps with a repeater,
7957 the following will happen:
7958 - the repeater will be removed in each clone
7959 - an additional clone will be produced, with the current, unshifted
7960 date(s) in the entry.
7961 - the original entry will be placed *after* all the clones, with
7962 repeater intact.
7963 - the start days in the repeater in the original entry will be shifted
7964 to past the last clone.
7965 In this way you can spell out a number of instances of a repeating task,
7966 and still retain the repeater to cover future instances of the task."
7967 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7968 (let (beg end template task idprop
7969 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7970 (drawer-re org-drawer-regexp))
7971 (if (not (and (integerp n) (> n 0)))
7972 (error "Invalid number of replications %s" n))
7973 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7974 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7975 shift)))
7976 (error "Invalid shift specification %s" shift))
7977 (when doshift
7978 (setq shift-n (string-to-number (match-string 1 shift))
7979 shift-what (cdr (assoc (match-string 2 shift)
7980 '(("d" . day) ("w" . week)
7981 ("m" . month) ("y" . year))))))
7982 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7983 (setq nmin 1 nmax n)
7984 (org-back-to-heading t)
7985 (setq beg (point))
7986 (setq idprop (org-entry-get nil "ID"))
7987 (org-end-of-subtree t t)
7988 (or (bolp) (insert "\n"))
7989 (setq end (point))
7990 (setq template (buffer-substring beg end))
7991 (when (and doshift
7992 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7993 (delete-region beg end)
7994 (setq end beg)
7995 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7996 (goto-char end)
7997 (loop for n from nmin to nmax do
7998 ;; prepare clone
7999 (with-temp-buffer
8000 (insert template)
8001 (org-mode)
8002 (goto-char (point-min))
8003 (org-show-subtree)
8004 (and idprop (if org-clone-delete-id
8005 (org-entry-delete nil "ID")
8006 (org-id-get-create t)))
8007 (unless (= n 0)
8008 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8009 (kill-whole-line))
8010 (goto-char (point-min))
8011 (while (re-search-forward drawer-re nil t)
8012 (mapc (lambda (d)
8013 (org-remove-empty-drawer-at d (point))) org-drawers)))
8014 (goto-char (point-min))
8015 (when doshift
8016 (while (re-search-forward org-ts-regexp-both nil t)
8017 (org-timestamp-change (* n shift-n) shift-what))
8018 (unless (= n n-no-remove)
8019 (goto-char (point-min))
8020 (while (re-search-forward org-ts-regexp nil t)
8021 (save-excursion
8022 (goto-char (match-beginning 0))
8023 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8024 (delete-region (match-beginning 1) (match-end 1)))))))
8025 (setq task (buffer-string)))
8026 (insert task))
8027 (goto-char beg)))
8029 ;;; Outline Sorting
8031 (defun org-sort (with-case)
8032 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8033 Optional argument WITH-CASE means sort case-sensitively."
8034 (interactive "P")
8035 (cond
8036 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8037 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8039 (org-call-with-arg 'org-sort-entries with-case))))
8041 (defun org-sort-remove-invisible (s)
8042 (remove-text-properties 0 (length s) org-rm-props s)
8043 (while (string-match org-bracket-link-regexp s)
8044 (setq s (replace-match (if (match-end 2)
8045 (match-string 3 s)
8046 (match-string 1 s)) t t s)))
8049 (defvar org-priority-regexp) ; defined later in the file
8051 (defvar org-after-sorting-entries-or-items-hook nil
8052 "Hook that is run after a bunch of entries or items have been sorted.
8053 When children are sorted, the cursor is in the parent line when this
8054 hook gets called. When a region or a plain list is sorted, the cursor
8055 will be in the first entry of the sorted region/list.")
8057 (defun org-sort-entries
8058 (&optional with-case sorting-type getkey-func compare-func property)
8059 "Sort entries on a certain level of an outline tree.
8060 If there is an active region, the entries in the region are sorted.
8061 Else, if the cursor is before the first entry, sort the top-level items.
8062 Else, the children of the entry at point are sorted.
8064 Sorting can be alphabetically, numerically, by date/time as given by
8065 a time stamp, by a property or by priority.
8067 The command prompts for the sorting type unless it has been given to the
8068 function through the SORTING-TYPE argument, which needs to be a character,
8069 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8070 precise meaning of each character:
8072 n Numerically, by converting the beginning of the entry/item to a number.
8073 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8074 t By date/time, either the first active time stamp in the entry, or, if
8075 none exist, by the first inactive one.
8076 s By the scheduled date/time.
8077 d By deadline date/time.
8078 c By creation time, which is assumed to be the first inactive time stamp
8079 at the beginning of a line.
8080 p By priority according to the cookie.
8081 r By the value of a property.
8083 Capital letters will reverse the sort order.
8085 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8086 called with point at the beginning of the record. It must return either
8087 a string or a number that should serve as the sorting key for that record.
8089 Comparing entries ignores case by default. However, with an optional argument
8090 WITH-CASE, the sorting considers case as well."
8091 (interactive "P")
8092 (let ((case-func (if with-case 'identity 'downcase))
8093 start beg end stars re re2
8094 txt what tmp)
8095 ;; Find beginning and end of region to sort
8096 (cond
8097 ((org-region-active-p)
8098 ;; we will sort the region
8099 (setq end (region-end)
8100 what "region")
8101 (goto-char (region-beginning))
8102 (if (not (org-at-heading-p)) (outline-next-heading))
8103 (setq start (point)))
8104 ((or (org-at-heading-p)
8105 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8106 ;; we will sort the children of the current headline
8107 (org-back-to-heading)
8108 (setq start (point)
8109 end (progn (org-end-of-subtree t t)
8110 (or (bolp) (insert "\n"))
8111 (org-back-over-empty-lines)
8112 (point))
8113 what "children")
8114 (goto-char start)
8115 (show-subtree)
8116 (outline-next-heading))
8118 ;; we will sort the top-level entries in this file
8119 (goto-char (point-min))
8120 (or (org-at-heading-p) (outline-next-heading))
8121 (setq start (point))
8122 (goto-char (point-max))
8123 (beginning-of-line 1)
8124 (when (looking-at ".*?\\S-")
8125 ;; File ends in a non-white line
8126 (end-of-line 1)
8127 (insert "\n"))
8128 (setq end (point-max))
8129 (setq what "top-level")
8130 (goto-char start)
8131 (show-all)))
8133 (setq beg (point))
8134 (if (>= beg end) (error "Nothing to sort"))
8136 (looking-at "\\(\\*+\\)")
8137 (setq stars (match-string 1)
8138 re (concat "^" (regexp-quote stars) " +")
8139 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8140 txt (buffer-substring beg end))
8141 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8142 (if (and (not (equal stars "*")) (string-match re2 txt))
8143 (error "Region to sort contains a level above the first entry"))
8145 (unless sorting-type
8146 (message
8147 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8148 [t]ime [s]cheduled [d]eadline [c]reated
8149 A/N/T/S/D/C/P/O/F means reversed:"
8150 what)
8151 (setq sorting-type (read-char-exclusive))
8153 (unless getkey-func
8154 (and (= (downcase sorting-type) ?f)
8155 (setq getkey-func
8156 (org-icompleting-read "Sort using function: "
8157 obarray 'fboundp t nil nil))
8158 (setq getkey-func (intern getkey-func))))
8160 (and (= (downcase sorting-type) ?r)
8161 (not property)
8162 (setq property
8163 (org-icompleting-read "Property: "
8164 (mapcar 'list (org-buffer-property-keys t))
8165 nil t))))
8167 (message "Sorting entries...")
8169 (save-restriction
8170 (narrow-to-region start end)
8171 (let ((dcst (downcase sorting-type))
8172 (case-fold-search nil)
8173 (now (current-time)))
8174 (sort-subr
8175 (/= dcst sorting-type)
8176 ;; This function moves to the beginning character of the "record" to
8177 ;; be sorted.
8178 (lambda nil
8179 (if (re-search-forward re nil t)
8180 (goto-char (match-beginning 0))
8181 (goto-char (point-max))))
8182 ;; This function moves to the last character of the "record" being
8183 ;; sorted.
8184 (lambda nil
8185 (save-match-data
8186 (condition-case nil
8187 (outline-forward-same-level 1)
8188 (error
8189 (goto-char (point-max))))))
8190 ;; This function returns the value that gets sorted against.
8191 (lambda nil
8192 (cond
8193 ((= dcst ?n)
8194 (if (looking-at org-complex-heading-regexp)
8195 (string-to-number (match-string 4))
8196 nil))
8197 ((= dcst ?a)
8198 (if (looking-at org-complex-heading-regexp)
8199 (funcall case-func (match-string 4))
8200 nil))
8201 ((= dcst ?t)
8202 (let ((end (save-excursion (outline-next-heading) (point))))
8203 (if (or (re-search-forward org-ts-regexp end t)
8204 (re-search-forward org-ts-regexp-both end t))
8205 (org-time-string-to-seconds (match-string 0))
8206 (org-float-time now))))
8207 ((= dcst ?c)
8208 (let ((end (save-excursion (outline-next-heading) (point))))
8209 (if (re-search-forward
8210 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8211 end t)
8212 (org-time-string-to-seconds (match-string 0))
8213 (org-float-time now))))
8214 ((= dcst ?s)
8215 (let ((end (save-excursion (outline-next-heading) (point))))
8216 (if (re-search-forward org-scheduled-time-regexp end t)
8217 (org-time-string-to-seconds (match-string 1))
8218 (org-float-time now))))
8219 ((= dcst ?d)
8220 (let ((end (save-excursion (outline-next-heading) (point))))
8221 (if (re-search-forward org-deadline-time-regexp end t)
8222 (org-time-string-to-seconds (match-string 1))
8223 (org-float-time now))))
8224 ((= dcst ?p)
8225 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8226 (string-to-char (match-string 2))
8227 org-default-priority))
8228 ((= dcst ?r)
8229 (or (org-entry-get nil property) ""))
8230 ((= dcst ?o)
8231 (if (looking-at org-complex-heading-regexp)
8232 (- 9999 (length (member (match-string 2)
8233 org-todo-keywords-1)))))
8234 ((= dcst ?f)
8235 (if getkey-func
8236 (progn
8237 (setq tmp (funcall getkey-func))
8238 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8239 tmp)
8240 (error "Invalid key function `%s'" getkey-func)))
8241 (t (error "Invalid sorting type `%c'" sorting-type))))
8243 (cond
8244 ((= dcst ?a) 'string<)
8245 ((= dcst ?f) compare-func)
8246 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8247 (run-hooks 'org-after-sorting-entries-or-items-hook)
8248 (message "Sorting entries...done")))
8250 (defun org-do-sort (table what &optional with-case sorting-type)
8251 "Sort TABLE of WHAT according to SORTING-TYPE.
8252 The user will be prompted for the SORTING-TYPE if the call to this
8253 function does not specify it. WHAT is only for the prompt, to indicate
8254 what is being sorted. The sorting key will be extracted from
8255 the car of the elements of the table.
8256 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8257 (unless sorting-type
8258 (message
8259 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8260 what)
8261 (setq sorting-type (read-char-exclusive)))
8262 (let ((dcst (downcase sorting-type))
8263 extractfun comparefun)
8264 ;; Define the appropriate functions
8265 (cond
8266 ((= dcst ?n)
8267 (setq extractfun 'string-to-number
8268 comparefun (if (= dcst sorting-type) '< '>)))
8269 ((= dcst ?a)
8270 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8271 (lambda(x) (downcase (org-sort-remove-invisible x))))
8272 comparefun (if (= dcst sorting-type)
8273 'string<
8274 (lambda (a b) (and (not (string< a b))
8275 (not (string= a b)))))))
8276 ((= dcst ?t)
8277 (setq extractfun
8278 (lambda (x)
8279 (if (or (string-match org-ts-regexp x)
8280 (string-match org-ts-regexp-both x))
8281 (org-float-time
8282 (org-time-string-to-time (match-string 0 x)))
8284 comparefun (if (= dcst sorting-type) '< '>)))
8285 (t (error "Invalid sorting type `%c'" sorting-type)))
8287 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8288 table)
8289 (lambda (a b) (funcall comparefun (car a) (car b))))))
8292 ;;; The orgstruct minor mode
8294 ;; Define a minor mode which can be used in other modes in order to
8295 ;; integrate the org-mode structure editing commands.
8297 ;; This is really a hack, because the org-mode structure commands use
8298 ;; keys which normally belong to the major mode. Here is how it
8299 ;; works: The minor mode defines all the keys necessary to operate the
8300 ;; structure commands, but wraps the commands into a function which
8301 ;; tests if the cursor is currently at a headline or a plain list
8302 ;; item. If that is the case, the structure command is used,
8303 ;; temporarily setting many Org-mode variables like regular
8304 ;; expressions for filling etc. However, when any of those keys is
8305 ;; used at a different location, function uses `key-binding' to look
8306 ;; up if the key has an associated command in another currently active
8307 ;; keymap (minor modes, major mode, global), and executes that
8308 ;; command. There might be problems if any of the keys is otherwise
8309 ;; used as a prefix key.
8311 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8312 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8313 ;; addresses this by checking explicitly for both bindings.
8315 (defvar orgstruct-mode-map (make-sparse-keymap)
8316 "Keymap for the minor `orgstruct-mode'.")
8318 (defvar org-local-vars nil
8319 "List of local variables, for use by `orgstruct-mode'.")
8321 ;;;###autoload
8322 (define-minor-mode orgstruct-mode
8323 "Toggle the minor mode `orgstruct-mode'.
8324 This mode is for using Org-mode structure commands in other
8325 modes. The following keys behave as if Org-mode were active, if
8326 the cursor is on a headline, or on a plain list item (both as
8327 defined by Org-mode).
8329 M-up Move entry/item up
8330 M-down Move entry/item down
8331 M-left Promote
8332 M-right Demote
8333 M-S-up Move entry/item up
8334 M-S-down Move entry/item down
8335 M-S-left Promote subtree
8336 M-S-right Demote subtree
8337 M-q Fill paragraph and items like in Org-mode
8338 C-c ^ Sort entries
8339 C-c - Cycle list bullet
8340 TAB Cycle item visibility
8341 M-RET Insert new heading/item
8342 S-M-RET Insert new TODO heading / Checkbox item
8343 C-c C-c Set tags / toggle checkbox"
8344 nil " OrgStruct" nil
8345 (org-load-modules-maybe)
8346 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8348 ;;;###autoload
8349 (defun turn-on-orgstruct ()
8350 "Unconditionally turn on `orgstruct-mode'."
8351 (orgstruct-mode 1))
8353 (defvar org-fb-vars nil)
8354 (make-variable-buffer-local 'org-fb-vars)
8355 (defun orgstruct++-mode (&optional arg)
8356 "Toggle `orgstruct-mode', the enhanced version of it.
8357 In addition to setting orgstruct-mode, this also exports all
8358 indentation and autofilling variables from org-mode into the
8359 buffer. It will also recognize item context in multiline items."
8360 (interactive "P")
8361 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8362 (if (< arg 1)
8363 (progn (orgstruct-mode -1)
8364 (mapc (lambda(v)
8365 (org-set-local (car v)
8366 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8367 org-fb-vars))
8368 (orgstruct-mode 1)
8369 (setq org-fb-vars nil)
8370 (let (var val)
8371 (mapc
8372 (lambda (x)
8373 (when (string-match
8374 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8375 (symbol-name (car x)))
8376 (setq var (car x) val (nth 1 x))
8377 (push (list var `(quote ,(eval var))) org-fb-vars)
8378 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8379 org-local-vars)
8380 (org-set-local 'orgstruct-is-++ t))))
8382 (defvar orgstruct-is-++ nil
8383 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8384 (make-variable-buffer-local 'orgstruct-is-++)
8386 ;;;###autoload
8387 (defun turn-on-orgstruct++ ()
8388 "Unconditionally turn on `orgstruct++-mode'."
8389 (orgstruct++-mode 1))
8391 (defun orgstruct-error ()
8392 "Error when there is no default binding for a structure key."
8393 (interactive)
8394 (error "This key has no function outside structure elements"))
8396 (defun orgstruct-setup ()
8397 "Setup orgstruct keymaps."
8398 (let ((nfunc 0)
8399 (bindings
8400 (list
8401 '([(meta up)] org-metaup)
8402 '([(meta down)] org-metadown)
8403 '([(meta left)] org-metaleft)
8404 '([(meta right)] org-metaright)
8405 '([(meta shift up)] org-shiftmetaup)
8406 '([(meta shift down)] org-shiftmetadown)
8407 '([(meta shift left)] org-shiftmetaleft)
8408 '([(meta shift right)] org-shiftmetaright)
8409 '([?\e (up)] org-metaup)
8410 '([?\e (down)] org-metadown)
8411 '([?\e (left)] org-metaleft)
8412 '([?\e (right)] org-metaright)
8413 '([?\e (shift up)] org-shiftmetaup)
8414 '([?\e (shift down)] org-shiftmetadown)
8415 '([?\e (shift left)] org-shiftmetaleft)
8416 '([?\e (shift right)] org-shiftmetaright)
8417 '([(shift up)] org-shiftup)
8418 '([(shift down)] org-shiftdown)
8419 '([(shift left)] org-shiftleft)
8420 '([(shift right)] org-shiftright)
8421 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8422 '("\M-q" fill-paragraph)
8423 '("\C-c^" org-sort)
8424 '("\C-c-" org-cycle-list-bullet)))
8425 elt key fun cmd)
8426 (while (setq elt (pop bindings))
8427 (setq nfunc (1+ nfunc))
8428 (setq key (org-key (car elt))
8429 fun (nth 1 elt)
8430 cmd (orgstruct-make-binding fun nfunc key))
8431 (org-defkey orgstruct-mode-map key cmd))
8433 ;; Prevent an error for users who forgot to make autoloads
8434 (require 'org-element)
8436 ;; Special treatment needed for TAB and RET
8437 (org-defkey orgstruct-mode-map [(tab)]
8438 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8439 (org-defkey orgstruct-mode-map "\C-i"
8440 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8442 (org-defkey orgstruct-mode-map "\M-\C-m"
8443 (orgstruct-make-binding 'org-insert-heading 105
8444 "\M-\C-m" [(meta return)]))
8445 (org-defkey orgstruct-mode-map [(meta return)]
8446 (orgstruct-make-binding 'org-insert-heading 106
8447 [(meta return)] "\M-\C-m"))
8449 (org-defkey orgstruct-mode-map [(shift meta return)]
8450 (orgstruct-make-binding 'org-insert-todo-heading 107
8451 [(meta return)] "\M-\C-m"))
8453 (org-defkey orgstruct-mode-map "\e\C-m"
8454 (orgstruct-make-binding 'org-insert-heading 108
8455 "\e\C-m" [?\e (return)]))
8456 (org-defkey orgstruct-mode-map [?\e (return)]
8457 (orgstruct-make-binding 'org-insert-heading 109
8458 [?\e (return)] "\e\C-m"))
8459 (org-defkey orgstruct-mode-map [?\e (shift return)]
8460 (orgstruct-make-binding 'org-insert-todo-heading 110
8461 [?\e (return)] "\e\C-m"))
8463 (unless org-local-vars
8464 (setq org-local-vars (org-get-local-variables)))
8468 (defun orgstruct-make-binding (fun n &rest keys)
8469 "Create a function for binding in the structure minor mode.
8470 FUN is the command to call inside a table. N is used to create a unique
8471 command name. KEYS are keys that should be checked in for a command
8472 to execute outside of tables."
8473 (eval
8474 (list 'defun
8475 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8476 '(arg)
8477 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8478 "Outside of structure, run the binding of `"
8479 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8480 "'.")
8481 '(interactive "p")
8482 (list 'if
8483 `(org-context-p 'headline 'item
8484 (and orgstruct-is-++
8485 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8486 'item-body))
8487 (list 'org-run-like-in-org-mode (list 'quote fun))
8488 (list 'let '(orgstruct-mode)
8489 (list 'call-interactively
8490 (append '(or)
8491 (mapcar (lambda (k)
8492 (list 'key-binding k))
8493 keys)
8494 '('orgstruct-error))))))))
8496 (defun org-contextualize-keys (alist contexts)
8497 "Return valid elements in ALIST depending on CONTEXTS.
8499 `org-agenda-custom-commands' or `org-capture-templates' are the
8500 values used for ALIST, and `org-agenda-custom-commands-contexts'
8501 or `org-capture-templates-contexts' are the associated contexts
8502 definitions."
8503 (let ((contexts
8504 ;; normalize contexts
8505 (mapcar
8506 (lambda(c) (cond ((listp (cadr c))
8507 (list (car c) (car c) (cadr c)))
8508 ((string= "" (cadr c))
8509 (list (car c) (car c) (caddr c)))
8510 (t c))) contexts))
8511 (a alist) c r s)
8512 ;; loop over all commands or templates
8513 (while (setq c (pop a))
8514 (let (vrules repl)
8515 (cond
8516 ((not (assoc (car c) contexts))
8517 (push c r))
8518 ((and (assoc (car c) contexts)
8519 (setq vrules (org-contextualize-validate-key
8520 (car c) contexts)))
8521 (mapc (lambda (vr)
8522 (when (not (equal (car vr) (cadr vr)))
8523 (setq repl vr))) vrules)
8524 (if (not repl) (push c r)
8525 (push (cadr repl) s)
8526 (push
8527 (cons (car c)
8528 (cdr (or (assoc (cadr repl) alist)
8529 (error "Undefined key `%s' as contextual replacement for `%s'"
8530 (cadr repl) (car c)))))
8531 r))))))
8532 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8533 (delq
8535 (delete-dups
8536 (mapcar (lambda (x)
8537 (let ((tpl (car x)))
8538 (when (not (delq
8540 (mapcar (lambda(y)
8541 (equal y tpl)) s))) x)))
8542 (reverse r))))))
8544 (defun org-contextualize-validate-key (key contexts)
8545 "Check CONTEXTS for agenda or capture KEY."
8546 (let (r rr res)
8547 (while (setq r (pop contexts))
8548 (mapc
8549 (lambda (rr)
8550 (when
8551 (and (equal key (car r))
8552 (if (functionp rr) (funcall rr)
8553 (or (and (eq (car rr) 'in-file)
8554 (buffer-file-name)
8555 (string-match (cdr rr) (buffer-file-name)))
8556 (and (eq (car rr) 'in-mode)
8557 (string-match (cdr rr) (symbol-name major-mode)))
8558 (when (and (eq (car rr) 'not-in-file)
8559 (buffer-file-name))
8560 (not (string-match (cdr rr) (buffer-file-name))))
8561 (when (eq (car rr) 'not-in-mode)
8562 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8563 (push r res)))
8564 (car (last r))))
8565 (delete-dups (delq nil res))))
8567 (defun org-context-p (&rest contexts)
8568 "Check if local context is any of CONTEXTS.
8569 Possible values in the list of contexts are `table', `headline', and `item'."
8570 (let ((pos (point)))
8571 (goto-char (point-at-bol))
8572 (prog1 (or (and (memq 'table contexts)
8573 (looking-at "[ \t]*|"))
8574 (and (memq 'headline contexts)
8575 (looking-at org-outline-regexp))
8576 (and (memq 'item contexts)
8577 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8578 (and (memq 'item-body contexts)
8579 (org-in-item-p)))
8580 (goto-char pos))))
8582 (defun org-get-local-variables ()
8583 "Return a list of all local variables in an Org mode buffer."
8584 (let (varlist)
8585 (with-current-buffer (get-buffer-create "*Org tmp*")
8586 (erase-buffer)
8587 (org-mode)
8588 (setq varlist (buffer-local-variables)))
8589 (kill-buffer "*Org tmp*")
8590 (delq nil
8591 (mapcar
8592 (lambda (x)
8593 (setq x
8594 (if (symbolp x)
8595 (list x)
8596 (list (car x) (list 'quote (cdr x)))))
8597 (if (string-match
8598 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8599 (symbol-name (car x)))
8600 x nil))
8601 varlist))))
8603 (defun org-clone-local-variables (from-buffer &optional regexp)
8604 "Clone local variables from FROM-BUFFER.
8605 Optional argument REGEXP selects variables to clone."
8606 (mapc
8607 (lambda (pair)
8608 (and (symbolp (car pair))
8609 (or (null regexp)
8610 (string-match regexp (symbol-name (car pair))))
8611 (set (make-local-variable (car pair))
8612 (cdr pair))))
8613 (buffer-local-variables from-buffer)))
8615 ;;;###autoload
8616 (defun org-run-like-in-org-mode (cmd)
8617 "Run a command, pretending that the current buffer is in Org-mode.
8618 This will temporarily bind local variables that are typically bound in
8619 Org-mode to the values they have in Org-mode, and then interactively
8620 call CMD."
8621 (org-load-modules-maybe)
8622 (unless org-local-vars
8623 (setq org-local-vars (org-get-local-variables)))
8624 (eval (list 'let org-local-vars
8625 (list 'call-interactively (list 'quote cmd)))))
8627 ;;;; Archiving
8629 (defun org-get-category (&optional pos force-refresh)
8630 "Get the category applying to position POS."
8631 (save-match-data
8632 (if force-refresh (org-refresh-category-properties))
8633 (let ((pos (or pos (point))))
8634 (or (get-text-property pos 'org-category)
8635 (progn (org-refresh-category-properties)
8636 (get-text-property pos 'org-category))))))
8638 (defun org-refresh-category-properties ()
8639 "Refresh category text properties in the buffer."
8640 (let ((case-fold-search t)
8641 (inhibit-read-only t)
8642 (def-cat (cond
8643 ((null org-category)
8644 (if buffer-file-name
8645 (file-name-sans-extension
8646 (file-name-nondirectory buffer-file-name))
8647 "???"))
8648 ((symbolp org-category) (symbol-name org-category))
8649 (t org-category)))
8650 beg end cat pos optionp)
8651 (org-unmodified
8652 (save-excursion
8653 (save-restriction
8654 (widen)
8655 (goto-char (point-min))
8656 (put-text-property (point) (point-max) 'org-category def-cat)
8657 (while (re-search-forward
8658 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8659 (setq pos (match-end 0)
8660 optionp (equal (char-after (match-beginning 0)) ?#)
8661 cat (org-trim (match-string 2)))
8662 (if optionp
8663 (setq beg (point-at-bol) end (point-max))
8664 (org-back-to-heading t)
8665 (setq beg (point) end (org-end-of-subtree t t)))
8666 (put-text-property beg end 'org-category cat)
8667 (put-text-property beg end 'org-category-position beg)
8668 (goto-char pos)))))))
8671 ;;;; Link Stuff
8673 ;;; Link abbreviations
8675 (defun org-link-expand-abbrev (link)
8676 "Apply replacements as defined in `org-link-abbrev-alist'."
8677 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8678 (let* ((key (match-string 1 link))
8679 (as (or (assoc key org-link-abbrev-alist-local)
8680 (assoc key org-link-abbrev-alist)))
8681 (tag (and (match-end 2) (match-string 3 link)))
8682 rpl)
8683 (if (not as)
8684 link
8685 (setq rpl (cdr as))
8686 (cond
8687 ((symbolp rpl) (funcall rpl tag))
8688 ((string-match "%(\\([^)]+\\))" rpl)
8689 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8690 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8691 ((string-match "%h" rpl)
8692 (replace-match (url-hexify-string (or tag "")) t t rpl))
8693 (t (concat rpl tag)))))
8694 link))
8696 ;;; Storing and inserting links
8698 (defvar org-insert-link-history nil
8699 "Minibuffer history for links inserted with `org-insert-link'.")
8701 (defvar org-stored-links nil
8702 "Contains the links stored with `org-store-link'.")
8704 (defvar org-store-link-plist nil
8705 "Plist with info about the most recently link created with `org-store-link'.")
8707 (defvar org-link-protocols nil
8708 "Link protocols added to Org-mode using `org-add-link-type'.")
8710 (defvar org-store-link-functions nil
8711 "List of functions that are called to create and store a link.
8712 Each function will be called in turn until one returns a non-nil
8713 value. Each function should check if it is responsible for creating
8714 this link (for example by looking at the major mode).
8715 If not, it must exit and return nil.
8716 If yes, it should return a non-nil value after a calling
8717 `org-store-link-props' with a list of properties and values.
8718 Special properties are:
8720 :type The link prefix, like \"http\". This must be given.
8721 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8722 This is obligatory as well.
8723 :description Optional default description for the second pair
8724 of brackets in an Org-mode link. The user can still change
8725 this when inserting this link into an Org-mode buffer.
8727 In addition to these, any additional properties can be specified
8728 and then used in capture templates.")
8730 (defun org-add-link-type (type &optional follow export)
8731 "Add TYPE to the list of `org-link-types'.
8732 Re-compute all regular expressions depending on `org-link-types'
8734 FOLLOW and EXPORT are two functions.
8736 FOLLOW should take the link path as the single argument and do whatever
8737 is necessary to follow the link, for example find a file or display
8738 a mail message.
8740 EXPORT should format the link path for export to one of the export formats.
8741 It should be a function accepting three arguments:
8743 path the path of the link, the text after the prefix (like \"http:\")
8744 desc the description of the link, if any, or a description added by
8745 org-export-normalize-links if there is none
8746 format the export format, a symbol like `html' or `latex' or `ascii'..
8748 The function may use the FORMAT information to return different values
8749 depending on the format. The return value will be put literally into
8750 the exported file. If the return value is nil, this means Org should
8751 do what it normally does with links which do not have EXPORT defined.
8753 Org-mode has a built-in default for exporting links. If you are happy with
8754 this default, there is no need to define an export function for the link
8755 type. For a simple example of an export function, see `org-bbdb.el'."
8756 (add-to-list 'org-link-types type t)
8757 (org-make-link-regexps)
8758 (if (assoc type org-link-protocols)
8759 (setcdr (assoc type org-link-protocols) (list follow export))
8760 (push (list type follow export) org-link-protocols)))
8762 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8763 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8765 ;;;###autoload
8766 (defun org-store-link (arg)
8767 "\\<org-mode-map>Store an org-link to the current location.
8768 This link is added to `org-stored-links' and can later be inserted
8769 into an org-buffer with \\[org-insert-link].
8771 For some link types, a prefix arg is interpreted:
8772 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8773 For file links, arg negates `org-context-in-file-links'."
8774 (interactive "P")
8775 (org-load-modules-maybe)
8776 (setq org-store-link-plist nil) ; reset
8777 (org-with-limited-levels
8778 (let (link cpltxt desc description search txt custom-id agenda-link)
8779 (cond
8781 ((run-hook-with-args-until-success 'org-store-link-functions)
8782 (setq link (plist-get org-store-link-plist :link)
8783 desc (or (plist-get org-store-link-plist :description) link)))
8785 ((org-src-edit-buffer-p)
8786 (let (label gc)
8787 (while (or (not label)
8788 (save-excursion
8789 (save-restriction
8790 (widen)
8791 (goto-char (point-min))
8792 (re-search-forward
8793 (regexp-quote (format org-coderef-label-format label))
8794 nil t))))
8795 (when label (message "Label exists already") (sit-for 2))
8796 (setq label (read-string "Code line label: " label)))
8797 (end-of-line 1)
8798 (setq link (format org-coderef-label-format label))
8799 (setq gc (- 79 (length link)))
8800 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8801 (insert link)
8802 (setq link (concat "(" label ")") desc nil)))
8804 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8805 ;; We are in the agenda, link to referenced location
8806 (let ((m (or (get-text-property (point) 'org-hd-marker)
8807 (get-text-property (point) 'org-marker))))
8808 (when m
8809 (org-with-point-at m
8810 (setq agenda-link
8811 (if (org-called-interactively-p 'any)
8812 (call-interactively 'org-store-link)
8813 (org-store-link nil)))))))
8815 ((eq major-mode 'calendar-mode)
8816 (let ((cd (calendar-cursor-to-date)))
8817 (setq link
8818 (format-time-string
8819 (car org-time-stamp-formats)
8820 (apply 'encode-time
8821 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8822 nil nil nil))))
8823 (org-store-link-props :type "calendar" :date cd)))
8825 ((eq major-mode 'help-mode)
8826 (setq link (concat "help:" (save-excursion
8827 (goto-char (point-min))
8828 (looking-at "^[^ ]+")
8829 (match-string 0))))
8830 (org-store-link-props :type "help"))
8832 ((eq major-mode 'w3-mode)
8833 (setq cpltxt (if (and (buffer-name)
8834 (not (string-match "Untitled" (buffer-name))))
8835 (buffer-name)
8836 (url-view-url t))
8837 link (url-view-url t))
8838 (org-store-link-props :type "w3" :url (url-view-url t)))
8840 ((eq major-mode 'w3m-mode)
8841 (setq cpltxt (or w3m-current-title w3m-current-url)
8842 link w3m-current-url)
8843 (org-store-link-props :type "w3m" :url (url-view-url t)))
8845 ((setq search (run-hook-with-args-until-success
8846 'org-create-file-search-functions))
8847 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8848 "::" search))
8849 (setq cpltxt (or description link)))
8851 ((eq major-mode 'image-mode)
8852 (setq cpltxt (concat "file:"
8853 (abbreviate-file-name buffer-file-name))
8854 link cpltxt)
8855 (org-store-link-props :type "image" :file buffer-file-name))
8857 ((eq major-mode 'dired-mode)
8858 ;; link to the file in the current line
8859 (let ((file (dired-get-filename nil t)))
8860 (setq file (if file
8861 (abbreviate-file-name
8862 (expand-file-name (dired-get-filename nil t)))
8863 ;; otherwise, no file so use current directory.
8864 default-directory))
8865 (setq cpltxt (concat "file:" file)
8866 link cpltxt)))
8868 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8869 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8870 (cond
8871 ((org-in-regexp "<<\\(.*?\\)>>")
8872 (setq cpltxt
8873 (concat "file:"
8874 (abbreviate-file-name
8875 (buffer-file-name (buffer-base-buffer)))
8876 "::" (match-string 1))
8877 link cpltxt))
8878 ((and (featurep 'org-id)
8879 (or (eq org-link-to-org-use-id t)
8880 (and (org-called-interactively-p 'any)
8881 (or (eq org-link-to-org-use-id 'create-if-interactive)
8882 (and (eq org-link-to-org-use-id
8883 'create-if-interactive-and-no-custom-id)
8884 (not custom-id))))
8885 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8886 ;; We can make a link using the ID.
8887 (setq link (condition-case nil
8888 (prog1 (org-id-store-link)
8889 (setq desc (plist-get org-store-link-plist :description)))
8890 (error
8891 ;; probably before first headline, link to file only
8892 (concat "file:"
8893 (abbreviate-file-name
8894 (buffer-file-name (buffer-base-buffer))))))))
8896 ;; Just link to current headline
8897 (setq cpltxt (concat "file:"
8898 (abbreviate-file-name
8899 (buffer-file-name (buffer-base-buffer)))))
8900 ;; Add a context search string
8901 (when (org-xor org-context-in-file-links arg)
8902 (setq txt (cond
8903 ((org-at-heading-p) nil)
8904 ((org-region-active-p)
8905 (buffer-substring (region-beginning) (region-end)))))
8906 (when (or (null txt) (string-match "\\S-" txt))
8907 (setq cpltxt
8908 (concat cpltxt "::"
8909 (condition-case nil
8910 (org-make-org-heading-search-string txt)
8911 (error "")))
8912 desc (or (nth 4 (ignore-errors
8913 (org-heading-components))) "NONE"))))
8914 (if (string-match "::\\'" cpltxt)
8915 (setq cpltxt (substring cpltxt 0 -2)))
8916 (setq link cpltxt))))
8918 ((buffer-file-name (buffer-base-buffer))
8919 ;; Just link to this file here.
8920 (setq cpltxt (concat "file:"
8921 (abbreviate-file-name
8922 (buffer-file-name (buffer-base-buffer)))))
8923 ;; Add a context string
8924 (when (org-xor org-context-in-file-links arg)
8925 (setq txt (if (org-region-active-p)
8926 (buffer-substring (region-beginning) (region-end))
8927 (buffer-substring (point-at-bol) (point-at-eol))))
8928 ;; Only use search option if there is some text.
8929 (when (string-match "\\S-" txt)
8930 (setq cpltxt
8931 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8932 desc "NONE")))
8933 (setq link cpltxt))
8935 ((org-called-interactively-p 'interactive)
8936 (error "Cannot link to a buffer which is not visiting a file"))
8938 (t (setq link nil)))
8940 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8941 (setq link (or link cpltxt)
8942 desc (or desc cpltxt))
8943 (if (equal desc "NONE") (setq desc nil))
8945 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8946 (progn
8947 (setq org-stored-links
8948 (cons (list link desc) org-stored-links))
8949 (message "Stored: %s" (or desc link))
8950 (when custom-id
8951 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8952 "::#" custom-id))
8953 (setq org-stored-links
8954 (cons (list link desc) org-stored-links))))
8955 (or agenda-link (and link (org-make-link-string link desc)))))))
8957 (defun org-store-link-props (&rest plist)
8958 "Store link properties, extract names and addresses."
8959 (let (x adr)
8960 (when (setq x (plist-get plist :from))
8961 (setq adr (mail-extract-address-components x))
8962 (setq plist (plist-put plist :fromname (car adr)))
8963 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8964 (when (setq x (plist-get plist :to))
8965 (setq adr (mail-extract-address-components x))
8966 (setq plist (plist-put plist :toname (car adr)))
8967 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8968 (let ((from (plist-get plist :from))
8969 (to (plist-get plist :to)))
8970 (when (and from to org-from-is-user-regexp)
8971 (setq plist
8972 (plist-put plist :fromto
8973 (if (string-match org-from-is-user-regexp from)
8974 (concat "to %t")
8975 (concat "from %f"))))))
8976 (setq org-store-link-plist plist))
8978 (defun org-add-link-props (&rest plist)
8979 "Add these properties to the link property list."
8980 (let (key value)
8981 (while plist
8982 (setq key (pop plist) value (pop plist))
8983 (setq org-store-link-plist
8984 (plist-put org-store-link-plist key value)))))
8986 (defun org-email-link-description (&optional fmt)
8987 "Return the description part of an email link.
8988 This takes information from `org-store-link-plist' and formats it
8989 according to FMT (default from `org-email-link-description-format')."
8990 (setq fmt (or fmt org-email-link-description-format))
8991 (let* ((p org-store-link-plist)
8992 (to (plist-get p :toaddress))
8993 (from (plist-get p :fromaddress))
8994 (table
8995 (list
8996 (cons "%c" (plist-get p :fromto))
8997 (cons "%F" (plist-get p :from))
8998 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8999 (cons "%T" (plist-get p :to))
9000 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9001 (cons "%s" (plist-get p :subject))
9002 (cons "%d" (plist-get p :date))
9003 (cons "%m" (plist-get p :message-id)))))
9004 (when (string-match "%c" fmt)
9005 ;; Check if the user wrote this message
9006 (if (and org-from-is-user-regexp from to
9007 (save-match-data (string-match org-from-is-user-regexp from)))
9008 (setq fmt (replace-match "to %t" t t fmt))
9009 (setq fmt (replace-match "from %f" t t fmt))))
9010 (org-replace-escapes fmt table)))
9012 (defun org-make-org-heading-search-string (&optional string heading)
9013 "Make search string for STRING or current headline."
9014 (interactive)
9015 (let ((s (or string (org-get-heading)))
9016 (lines org-context-in-file-links))
9017 (unless (and string (not heading))
9018 ;; We are using a headline, clean up garbage in there.
9019 (if (string-match org-todo-regexp s)
9020 (setq s (replace-match "" t t s)))
9021 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9022 (setq s (replace-match "" t t s)))
9023 (setq s (org-trim s))
9024 (if (string-match (concat "^\\(" org-quote-string "\\|"
9025 org-comment-string "\\)") s)
9026 (setq s (replace-match "" t t s)))
9027 (while (string-match org-ts-regexp s)
9028 (setq s (replace-match "" t t s))))
9029 (or string (setq s (concat "*" s))) ; Add * for headlines
9030 (when (and string (integerp lines) (> lines 0))
9031 (let ((slines (org-split-string s "\n")))
9032 (when (< lines (length slines))
9033 (setq s (mapconcat
9034 'identity
9035 (reverse (nthcdr (- (length slines) lines)
9036 (reverse slines))) "\n")))))
9037 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9039 (defun org-make-link-string (link &optional description)
9040 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9041 (unless (string-match "\\S-" link)
9042 (error "Empty link"))
9043 (when (and description
9044 (stringp description)
9045 (not (string-match "\\S-" description)))
9046 (setq description nil))
9047 (when (stringp description)
9048 ;; Remove brackets from the description, they are fatal.
9049 (while (string-match "\\[" description)
9050 (setq description (replace-match "{" t t description)))
9051 (while (string-match "\\]" description)
9052 (setq description (replace-match "}" t t description))))
9053 (when (equal link description)
9054 ;; No description needed, it is identical
9055 (setq description nil))
9056 (when (and (not description)
9057 (not (string-match (org-image-file-name-regexp) link))
9058 (not (equal link (org-link-escape link))))
9059 (setq description (org-extract-attributes link)))
9060 (setq link
9061 (cond ((string-match (org-image-file-name-regexp) link) link)
9062 ((string-match org-link-types-re link)
9063 (concat (match-string 1 link)
9064 (org-link-escape (substring link (match-end 1)))))
9065 (t (org-link-escape link))))
9066 (concat "[[" link "]"
9067 (if description (concat "[" description "]") "")
9068 "]"))
9070 (defconst org-link-escape-chars
9071 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9072 "List of characters that should be escaped in link.
9073 This is the list that is used for internal purposes.")
9075 (defconst org-link-escape-chars-browser
9076 '(?\ )
9077 "List of escapes for characters that are problematic in links.
9078 This is the list that is used before handing over to the browser.")
9080 (defun org-link-escape (text &optional table merge)
9081 "Return percent escaped representation of TEXT.
9082 TEXT is a string with the text to escape.
9083 Optional argument TABLE is a list with characters that should be
9084 escaped. When nil, `org-link-escape-chars' is used.
9085 If optional argument MERGE is set, merge TABLE into
9086 `org-link-escape-chars'."
9087 (cond
9088 ((and table merge)
9089 (mapc (lambda (defchr)
9090 (unless (member defchr table)
9091 (setq table (cons defchr table)))) org-link-escape-chars))
9092 ((null table)
9093 (setq table org-link-escape-chars)))
9094 (mapconcat
9095 (lambda (char)
9096 (if (or (member char table)
9097 (and (or (< char 32) (= char 37) (> char 126))
9098 org-url-hexify-p))
9099 (mapconcat (lambda (sequence-element)
9100 (format "%%%.2X" sequence-element))
9101 (or (encode-coding-char char 'utf-8)
9102 (error "Unable to percent escape character: %s"
9103 (char-to-string char))) "")
9104 (char-to-string char))) text ""))
9106 (defun org-link-unescape (str)
9107 "Unhex hexified Unicode strings as returned from the JavaScript function
9108 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9109 (unless (and (null str) (string= "" str))
9110 (let ((pos 0) (case-fold-search t) unhexed)
9111 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9112 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9113 (setq str (replace-match unhexed t t str))
9114 (setq pos (+ pos (length unhexed))))))
9115 str)
9117 (defun org-link-unescape-compound (hex)
9118 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9119 Note: this function also decodes single byte encodings like
9120 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9121 (save-match-data
9122 (let* ((bytes (cdr (split-string hex "%")))
9123 (ret "")
9124 (eat 0)
9125 (sum 0))
9126 (while bytes
9127 (let* ((val (string-to-number (pop bytes) 16))
9128 (shift-xor
9129 (if (= 0 eat)
9130 (cond
9131 ((>= val 252) (cons 6 252))
9132 ((>= val 248) (cons 5 248))
9133 ((>= val 240) (cons 4 240))
9134 ((>= val 224) (cons 3 224))
9135 ((>= val 192) (cons 2 192))
9136 (t (cons 0 0)))
9137 (cons 6 128))))
9138 (if (>= val 192) (setq eat (car shift-xor)))
9139 (setq val (logxor val (cdr shift-xor)))
9140 (setq sum (+ (lsh sum (car shift-xor)) val))
9141 (if (> eat 0) (setq eat (- eat 1)))
9142 (cond
9143 ((= 0 eat) ;multi byte
9144 (setq ret (concat ret (org-char-to-string sum)))
9145 (setq sum 0))
9146 ((not bytes) ; single byte(s)
9147 (setq ret (org-link-unescape-single-byte-sequence hex))))
9148 )) ;; end (while bytes
9149 ret )))
9151 (defun org-link-unescape-single-byte-sequence (hex)
9152 "Unhexify hex-encoded single byte character sequences."
9153 (mapconcat (lambda (byte)
9154 (char-to-string (string-to-number byte 16)))
9155 (cdr (split-string hex "%")) ""))
9157 (defun org-xor (a b)
9158 "Exclusive or."
9159 (if a (not b) b))
9161 (defun org-fixup-message-id-for-http (s)
9162 "Replace special characters in a message id, so it can be used in an http query."
9163 (when (string-match "%" s)
9164 (setq s (mapconcat (lambda (c)
9165 (if (eq c ?%)
9166 "%25"
9167 (char-to-string c)))
9168 s "")))
9169 (while (string-match "<" s)
9170 (setq s (replace-match "%3C" t t s)))
9171 (while (string-match ">" s)
9172 (setq s (replace-match "%3E" t t s)))
9173 (while (string-match "@" s)
9174 (setq s (replace-match "%40" t t s)))
9177 (defun org-link-prettify (link)
9178 "Return a human-readable representation of LINK.
9179 The car of LINK must be a raw link the cdr of LINK must be either
9180 a link description or nil."
9181 (let ((desc (or (cadr link) "<no description>")))
9182 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9183 "<" (car link) ">")))
9185 ;;;###autoload
9186 (defun org-insert-link-global ()
9187 "Insert a link like Org-mode does.
9188 This command can be called in any mode to insert a link in Org-mode syntax."
9189 (interactive)
9190 (org-load-modules-maybe)
9191 (org-run-like-in-org-mode 'org-insert-link))
9193 (defun org-insert-all-links (&optional keep)
9194 "Insert all links in `org-stored-links'."
9195 (interactive "P")
9196 (let ((links (copy-sequence org-stored-links)) l)
9197 (while (setq l (if keep (pop links) (pop org-stored-links)))
9198 (insert "- ")
9199 (org-insert-link nil (car l) (cadr l))
9200 (insert "\n"))))
9202 (defun org-link-fontify-links-to-this-file ()
9203 "Fontify links to the current file in `org-stored-links'."
9204 (let ((f (buffer-file-name)) a b)
9205 (setq a (mapcar (lambda(l)
9206 (let ((ll (car l)))
9207 (when (and (string-match "^file:\\(.+\\)::" ll)
9208 (equal f (expand-file-name (match-string 1 ll))))
9209 ll)))
9210 org-stored-links))
9211 (when (featurep 'org-id)
9212 (setq b (mapcar (lambda(l)
9213 (let ((ll (car l)))
9214 (when (and (string-match "^id:\\(.+\\)$" ll)
9215 (equal f (expand-file-name
9216 (or (org-id-find-id-file
9217 (match-string 1 ll)) ""))))
9218 ll)))
9219 org-stored-links)))
9220 (mapcar (lambda(l)
9221 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9222 (delq nil (append a b)))))
9224 (defvar org-link-links-in-this-file nil)
9225 (defun org-insert-link (&optional complete-file link-location default-description)
9226 "Insert a link. At the prompt, enter the link.
9228 Completion can be used to insert any of the link protocol prefixes like
9229 http or ftp in use.
9231 The history can be used to select a link previously stored with
9232 `org-store-link'. When the empty string is entered (i.e. if you just
9233 press RET at the prompt), the link defaults to the most recently
9234 stored link. As SPC triggers completion in the minibuffer, you need to
9235 use M-SPC or C-q SPC to force the insertion of a space character.
9237 You will also be prompted for a description, and if one is given, it will
9238 be displayed in the buffer instead of the link.
9240 If there is already a link at point, this command will allow you to edit link
9241 and description parts.
9243 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9244 be selected using completion. The path to the file will be relative to the
9245 current directory if the file is in the current directory or a subdirectory.
9246 Otherwise, the link will be the absolute path as completed in the minibuffer
9247 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9248 option `org-link-file-path-type'.
9250 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9251 the current directory or below.
9253 With three \\[universal-argument] prefixes, negate the meaning of
9254 `org-keep-stored-link-after-insertion'.
9256 If `org-make-link-description-function' is non-nil, this function will be
9257 called with the link target, and the result will be the default
9258 link description.
9260 If the LINK-LOCATION parameter is non-nil, this value will be
9261 used as the link location instead of reading one interactively.
9263 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9264 be used as the default description."
9265 (interactive "P")
9266 (let* ((wcf (current-window-configuration))
9267 (origbuf (current-buffer))
9268 (region (if (org-region-active-p)
9269 (buffer-substring (region-beginning) (region-end))))
9270 (remove (and region (list (region-beginning) (region-end))))
9271 (desc region)
9272 tmphist ; byte-compile incorrectly complains about this
9273 (link link-location)
9274 (abbrevs org-link-abbrev-alist-local)
9275 entry file all-prefixes auto-desc)
9276 (cond
9277 (link-location) ; specified by arg, just use it.
9278 ((org-in-regexp org-bracket-link-regexp 1)
9279 ;; We do have a link at point, and we are going to edit it.
9280 (setq remove (list (match-beginning 0) (match-end 0)))
9281 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9282 (setq link (read-string "Link: "
9283 (org-link-unescape
9284 (org-match-string-no-properties 1)))))
9285 ((or (org-in-regexp org-angle-link-re)
9286 (org-in-regexp org-plain-link-re))
9287 ;; Convert to bracket link
9288 (setq remove (list (match-beginning 0) (match-end 0))
9289 link (read-string "Link: "
9290 (org-remove-angle-brackets (match-string 0)))))
9291 ((member complete-file '((4) (16)))
9292 ;; Completing read for file names.
9293 (setq link (org-file-complete-link complete-file)))
9295 ;; Read link, with completion for stored links.
9296 (org-link-fontify-links-to-this-file)
9297 (org-switch-to-buffer-other-window "*Org Links*")
9298 (with-current-buffer "*Org Links*"
9299 (erase-buffer)
9300 (insert "Insert a link.
9301 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9302 (when org-stored-links
9303 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9304 (insert (mapconcat 'org-link-prettify
9305 (reverse org-stored-links) "\n")))
9306 (goto-char (point-min)))
9307 (let ((cw (selected-window)))
9308 (select-window (get-buffer-window "*Org Links*" 'visible))
9309 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9310 (unless (pos-visible-in-window-p (point-max))
9311 (org-fit-window-to-buffer))
9312 (and (window-live-p cw) (select-window cw)))
9313 ;; Fake a link history, containing the stored links.
9314 (setq tmphist (append (mapcar 'car org-stored-links)
9315 org-insert-link-history))
9316 (setq all-prefixes (append (mapcar 'car abbrevs)
9317 (mapcar 'car org-link-abbrev-alist)
9318 org-link-types))
9319 (unwind-protect
9320 (progn
9321 (setq link
9322 (org-completing-read
9323 "Link: "
9324 (append
9325 (mapcar (lambda (x) (concat x ":"))
9326 all-prefixes)
9327 (mapcar 'car org-stored-links))
9328 nil nil nil
9329 'tmphist
9330 (caar org-stored-links)))
9331 (if (not (string-match "\\S-" link))
9332 (error "No link selected"))
9333 (mapc (lambda(l)
9334 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9335 org-stored-links)
9336 (if (or (member link all-prefixes)
9337 (and (equal ":" (substring link -1))
9338 (member (substring link 0 -1) all-prefixes)
9339 (setq link (substring link 0 -1))))
9340 (setq link (with-current-buffer origbuf
9341 (org-link-try-special-completion link)))))
9342 (set-window-configuration wcf)
9343 (kill-buffer "*Org Links*"))
9344 (setq entry (assoc link org-stored-links))
9345 (or entry (push link org-insert-link-history))
9346 (setq desc (or desc (nth 1 entry)))))
9348 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9349 (not org-keep-stored-link-after-insertion))
9350 (setq org-stored-links (delq (assoc link org-stored-links)
9351 org-stored-links)))
9353 (if (string-match org-plain-link-re link)
9354 ;; URL-like link, normalize the use of angular brackets.
9355 (setq link (org-remove-angle-brackets link)))
9357 ;; Check if we are linking to the current file with a search option
9358 ;; If yes, simplify the link by using only the search option.
9359 (when (and buffer-file-name
9360 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9361 (let* ((path (match-string 1 link))
9362 (case-fold-search nil)
9363 (search (match-string 2 link)))
9364 (save-match-data
9365 (if (equal (file-truename buffer-file-name) (file-truename path))
9366 ;; We are linking to this same file, with a search option
9367 (setq link search)))))
9369 ;; Check if we can/should use a relative path. If yes, simplify the link
9370 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9371 (let* ((type (match-string 1 link))
9372 (path (match-string 2 link))
9373 (origpath path)
9374 (case-fold-search nil))
9375 (cond
9376 ((or (eq org-link-file-path-type 'absolute)
9377 (equal complete-file '(16)))
9378 (setq path (abbreviate-file-name (expand-file-name path))))
9379 ((eq org-link-file-path-type 'noabbrev)
9380 (setq path (expand-file-name path)))
9381 ((eq org-link-file-path-type 'relative)
9382 (setq path (file-relative-name path)))
9384 (save-match-data
9385 (if (string-match (concat "^" (regexp-quote
9386 (expand-file-name
9387 (file-name-as-directory
9388 default-directory))))
9389 (expand-file-name path))
9390 ;; We are linking a file with relative path name.
9391 (setq path (substring (expand-file-name path)
9392 (match-end 0)))
9393 (setq path (abbreviate-file-name (expand-file-name path)))))))
9394 (setq link (concat type path))
9395 (if (equal desc origpath)
9396 (setq desc path))))
9398 (if org-make-link-description-function
9399 (setq desc
9400 (or (condition-case nil
9401 (funcall org-make-link-description-function link desc)
9402 (error (progn (message "Can't get link description from `%s'"
9403 (symbol-name org-make-link-description-function))
9404 (sit-for 2) nil)))
9405 (read-string "Description: " default-description)))
9406 (if default-description (setq desc default-description)
9407 (setq desc (or (and auto-desc desc)
9408 (read-string "Description: " desc)))))
9410 (unless (string-match "\\S-" desc) (setq desc nil))
9411 (if remove (apply 'delete-region remove))
9412 (insert (org-make-link-string link desc))))
9414 (defun org-link-try-special-completion (type)
9415 "If there is completion support for link type TYPE, offer it."
9416 (let ((fun (intern (concat "org-" type "-complete-link"))))
9417 (if (functionp fun)
9418 (funcall fun)
9419 (read-string "Link (no completion support): " (concat type ":")))))
9421 (defun org-file-complete-link (&optional arg)
9422 "Create a file link using completion."
9423 (let (file link)
9424 (setq file (org-iread-file-name "File: "))
9425 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9426 (pwd1 (file-name-as-directory (abbreviate-file-name
9427 (expand-file-name ".")))))
9428 (cond
9429 ((equal arg '(16))
9430 (setq link (concat
9431 "file:"
9432 (abbreviate-file-name (expand-file-name file)))))
9433 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9434 (setq link (concat "file:" (match-string 1 file))))
9435 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9436 (expand-file-name file))
9437 (setq link (concat
9438 "file:" (match-string 1 (expand-file-name file)))))
9439 (t (setq link (concat "file:" file)))))
9440 link))
9442 (defun org-iread-file-name (&rest args)
9443 "Read-file-name using `ido-mode' speedup if available.
9444 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9445 See `read-file-name' for a description of parameters."
9446 (org-without-partial-completion
9447 (if (and org-completion-use-ido
9448 (fboundp 'ido-read-file-name)
9449 (boundp 'ido-mode) ido-mode
9450 (listp (second args)))
9451 (let ((ido-enter-matching-directory nil))
9452 (apply 'ido-read-file-name args))
9453 (apply 'read-file-name args))))
9455 (defun org-completing-read (&rest args)
9456 "Completing-read with SPACE being a normal character."
9457 (let ((enable-recursive-minibuffers t)
9458 (minibuffer-local-completion-map
9459 (copy-keymap minibuffer-local-completion-map)))
9460 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9461 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9462 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9463 (apply 'org-icompleting-read args)))
9465 (defun org-completing-read-no-i (&rest args)
9466 (let (org-completion-use-ido org-completion-use-iswitchb)
9467 (apply 'org-completing-read args)))
9469 (defun org-iswitchb-completing-read (prompt choices &rest args)
9470 "Use iswitch as a completing-read replacement to choose from choices.
9471 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9472 from."
9473 (let* ((iswitchb-use-virtual-buffers nil)
9474 (iswitchb-make-buflist-hook
9475 (lambda ()
9476 (setq iswitchb-temp-buflist choices))))
9477 (iswitchb-read-buffer prompt)))
9479 (defun org-icompleting-read (&rest args)
9480 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9481 (org-without-partial-completion
9482 (if (and org-completion-use-ido
9483 (fboundp 'ido-completing-read)
9484 (boundp 'ido-mode) ido-mode
9485 (listp (second args)))
9486 (let ((ido-enter-matching-directory nil))
9487 (apply 'ido-completing-read (concat (car args))
9488 (if (consp (car (nth 1 args)))
9489 (mapcar 'car (nth 1 args))
9490 (nth 1 args))
9491 (cddr args)))
9492 (if (and org-completion-use-iswitchb
9493 (boundp 'iswitchb-mode) iswitchb-mode
9494 (listp (second args)))
9495 (apply 'org-iswitchb-completing-read (concat (car args))
9496 (if (consp (car (nth 1 args)))
9497 (mapcar 'car (nth 1 args))
9498 (nth 1 args))
9499 (cddr args))
9500 (apply 'completing-read args)))))
9502 (defun org-extract-attributes (s)
9503 "Extract the attributes cookie from a string and set as text property."
9504 (let (a attr (start 0) key value)
9505 (save-match-data
9506 (when (string-match "{{\\([^}]+\\)}}$" s)
9507 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9508 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9509 (setq key (match-string 1 a) value (match-string 2 a)
9510 start (match-end 0)
9511 attr (plist-put attr (intern key) value))))
9512 (org-add-props s nil 'org-attr attr))
9515 (defun org-extract-attributes-from-string (tag)
9516 (let (key value attr)
9517 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9518 (setq key (match-string 1 tag) value (match-string 2 tag)
9519 tag (replace-match "" t t tag)
9520 attr (plist-put attr (intern key) value)))
9521 (cons tag attr)))
9523 (defun org-attributes-to-string (plist)
9524 "Format a property list into an HTML attribute list."
9525 (let ((s "") key value)
9526 (while plist
9527 (setq key (pop plist) value (pop plist))
9528 (and value
9529 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9532 ;;; Opening/following a link
9534 (defvar org-link-search-failed nil)
9536 (defvar org-open-link-functions nil
9537 "Hook for functions finding a plain text link.
9538 These functions must take a single argument, the link content.
9539 They will be called for links that look like [[link text][description]]
9540 when LINK TEXT does not have a protocol like \"http:\" and does not look
9541 like a filename (e.g. \"./blue.png\").
9543 These functions will be called *before* Org attempts to resolve the
9544 link by doing text searches in the current buffer - so if you want a
9545 link \"[[target]]\" to still find \"<<target>>\", your function should
9546 handle this as a special case.
9548 When the function does handle the link, it must return a non-nil value.
9549 If it decides that it is not responsible for this link, it must return
9550 nil to indicate that that Org-mode can continue with other options
9551 like exact and fuzzy text search.")
9553 (defun org-next-link ()
9554 "Move forward to the next link.
9555 If the link is in hidden text, expose it."
9556 (interactive)
9557 (when (and org-link-search-failed (eq this-command last-command))
9558 (goto-char (point-min))
9559 (message "Link search wrapped back to beginning of buffer"))
9560 (setq org-link-search-failed nil)
9561 (let* ((pos (point))
9562 (ct (org-context))
9563 (a (assoc :link ct)))
9564 (if a (goto-char (nth 2 a)))
9565 (if (re-search-forward org-any-link-re nil t)
9566 (progn
9567 (goto-char (match-beginning 0))
9568 (if (outline-invisible-p) (org-show-context)))
9569 (goto-char pos)
9570 (setq org-link-search-failed t)
9571 (error "No further link found"))))
9573 (defun org-previous-link ()
9574 "Move backward to the previous link.
9575 If the link is in hidden text, expose it."
9576 (interactive)
9577 (when (and org-link-search-failed (eq this-command last-command))
9578 (goto-char (point-max))
9579 (message "Link search wrapped back to end of buffer"))
9580 (setq org-link-search-failed nil)
9581 (let* ((pos (point))
9582 (ct (org-context))
9583 (a (assoc :link ct)))
9584 (if a (goto-char (nth 1 a)))
9585 (if (re-search-backward org-any-link-re nil t)
9586 (progn
9587 (goto-char (match-beginning 0))
9588 (if (outline-invisible-p) (org-show-context)))
9589 (goto-char pos)
9590 (setq org-link-search-failed t)
9591 (error "No further link found"))))
9593 (defun org-translate-link (s)
9594 "Translate a link string if a translation function has been defined."
9595 (if (and org-link-translation-function
9596 (fboundp org-link-translation-function)
9597 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9598 (progn
9599 (setq s (funcall org-link-translation-function
9600 (match-string 1 s) (match-string 2 s)))
9601 (concat (car s) ":" (cdr s)))
9604 (defun org-translate-link-from-planner (type path)
9605 "Translate a link from Emacs Planner syntax so that Org can follow it.
9606 This is still an experimental function, your mileage may vary."
9607 (cond
9608 ((member type '("http" "https" "news" "ftp"))
9609 ;; standard Internet links are the same.
9610 nil)
9611 ((and (equal type "irc") (string-match "^//" path))
9612 ;; Planner has two / at the beginning of an irc link, we have 1.
9613 ;; We should have zero, actually....
9614 (setq path (substring path 1)))
9615 ((and (equal type "lisp") (string-match "^/" path))
9616 ;; Planner has a slash, we do not.
9617 (setq type "elisp" path (substring path 1)))
9618 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9619 ;; A typical message link. Planner has the id after the final slash,
9620 ;; we separate it with a hash mark
9621 (setq path (concat (match-string 1 path) "#"
9622 (org-remove-angle-brackets (match-string 2 path)))))
9624 (cons type path))
9626 (defun org-find-file-at-mouse (ev)
9627 "Open file link or URL at mouse."
9628 (interactive "e")
9629 (mouse-set-point ev)
9630 (org-open-at-point 'in-emacs))
9632 (defun org-open-at-mouse (ev)
9633 "Open file link or URL at mouse.
9634 See the docstring of `org-open-file' for details."
9635 (interactive "e")
9636 (mouse-set-point ev)
9637 (if (eq major-mode 'org-agenda-mode)
9638 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9639 (org-open-at-point))
9641 (defvar org-window-config-before-follow-link nil
9642 "The window configuration before following a link.
9643 This is saved in case the need arises to restore it.")
9645 (defvar org-open-link-marker (make-marker)
9646 "Marker pointing to the location where `org-open-at-point; was called.")
9648 ;;;###autoload
9649 (defun org-open-at-point-global ()
9650 "Follow a link like Org-mode does.
9651 This command can be called in any mode to follow a link that has
9652 Org-mode syntax."
9653 (interactive)
9654 (org-run-like-in-org-mode 'org-open-at-point))
9656 ;;;###autoload
9657 (defun org-open-link-from-string (s &optional arg reference-buffer)
9658 "Open a link in the string S, as if it was in Org-mode."
9659 (interactive "sLink: \nP")
9660 (let ((reference-buffer (or reference-buffer (current-buffer))))
9661 (with-temp-buffer
9662 (let ((org-inhibit-startup (not reference-buffer)))
9663 (org-mode)
9664 (insert s)
9665 (goto-char (point-min))
9666 (when reference-buffer
9667 (setq org-link-abbrev-alist-local
9668 (with-current-buffer reference-buffer
9669 org-link-abbrev-alist-local)))
9670 (org-open-at-point arg reference-buffer)))))
9672 (defvar org-open-at-point-functions nil
9673 "Hook that is run when following a link at point.
9675 Functions in this hook must return t if they identify and follow
9676 a link at point. If they don't find anything interesting at point,
9677 they must return nil.")
9679 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9680 (defun org-open-at-point (&optional arg reference-buffer)
9681 "Open link at or after point.
9682 If there is no link at point, this function will search forward up to
9683 the end of the current line.
9684 Normally, files will be opened by an appropriate application. If the
9685 optional prefix argument ARG is non-nil, Emacs will visit the file.
9686 With a double prefix argument, try to open outside of Emacs, in the
9687 application the system uses for this file type."
9688 (interactive "P")
9689 ;; if in a code block, then open the block's results
9690 (unless (call-interactively #'org-babel-open-src-block-result)
9691 (org-load-modules-maybe)
9692 (move-marker org-open-link-marker (point))
9693 (setq org-window-config-before-follow-link (current-window-configuration))
9694 (org-remove-occur-highlights nil nil t)
9695 (cond
9696 ((and (org-at-heading-p)
9697 (not (org-at-timestamp-p t))
9698 (not (org-in-regexp
9699 (concat org-plain-link-re "\\|"
9700 org-bracket-link-regexp "\\|"
9701 org-angle-link-re "\\|"
9702 "[ \t]:[^ \t\n]+:[ \t]*$")))
9703 (not (get-text-property (point) 'org-linked-text)))
9704 (or (org-offer-links-in-entry arg)
9705 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9706 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9707 ((and (org-at-timestamp-p t)
9708 (not (org-in-regexp org-bracket-link-regexp)))
9709 (org-follow-timestamp-link))
9710 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9711 (not (org-in-regexp org-bracket-link-regexp)))
9712 (org-footnote-action))
9714 (let (type path link line search (pos (point)))
9715 (catch 'match
9716 (save-excursion
9717 (skip-chars-forward "^]\n\r")
9718 (when (org-in-regexp org-bracket-link-regexp 1)
9719 (setq link (org-extract-attributes
9720 (org-link-unescape (org-match-string-no-properties 1))))
9721 (while (string-match " *\n *" link)
9722 (setq link (replace-match " " t t link)))
9723 (setq link (org-link-expand-abbrev link))
9724 (cond
9725 ((or (file-name-absolute-p link)
9726 (string-match "^\\.\\.?/" link))
9727 (setq type "file" path link))
9728 ((string-match org-link-re-with-space3 link)
9729 (setq type (match-string 1 link) path (match-string 2 link)))
9730 ((string-match "^help:+\\(.+\\)" link)
9731 (setq type "help" path (match-string 1 link)))
9732 (t (setq type "thisfile" path link)))
9733 (throw 'match t)))
9735 (when (get-text-property (point) 'org-linked-text)
9736 (setq type "thisfile"
9737 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9738 (1+ (point)) (point))
9739 path (buffer-substring
9740 (or (previous-single-property-change pos 'org-linked-text)
9741 (point-min))
9742 (or (next-single-property-change pos 'org-linked-text)
9743 (point-max))))
9744 (throw 'match t))
9746 (save-excursion
9747 (when (or (org-in-regexp org-angle-link-re)
9748 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9749 (save-match-data (not (looking-back "\\[\\[")))))
9750 (setq type (match-string 1)
9751 path (org-link-unescape (match-string 2)))
9752 (throw 'match t)))
9753 (save-excursion
9754 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9755 (setq type "tags"
9756 path (match-string 1))
9757 (while (string-match ":" path)
9758 (setq path (replace-match "+" t t path)))
9759 (throw 'match t)))
9760 (when (org-in-regexp "<\\([^><\n]+\\)>")
9761 (setq type "tree-match"
9762 path (match-string 1))
9763 (throw 'match t)))
9764 (unless path
9765 (error "No link found"))
9767 ;; switch back to reference buffer
9768 ;; needed when if called in a temporary buffer through
9769 ;; org-open-link-from-string
9770 (with-current-buffer (or reference-buffer (current-buffer))
9772 ;; Remove any trailing spaces in path
9773 (if (string-match " +\\'" path)
9774 (setq path (replace-match "" t t path)))
9775 (if (and org-link-translation-function
9776 (fboundp org-link-translation-function))
9777 ;; Check if we need to translate the link
9778 (let ((tmp (funcall org-link-translation-function type path)))
9779 (setq type (car tmp) path (cdr tmp))))
9781 (cond
9783 ((assoc type org-link-protocols)
9784 (funcall (nth 1 (assoc type org-link-protocols)) path))
9786 ((equal type "help")
9787 (let ((f-or-v (intern path)))
9788 (cond ((fboundp f-or-v)
9789 (describe-function f-or-v))
9790 ((boundp f-or-v)
9791 (describe-variable f-or-v))
9792 (t (error "Not a known function or variable")))))
9794 ((equal type "mailto")
9795 (let ((cmd (car org-link-mailto-program))
9796 (args (cdr org-link-mailto-program)) args1
9797 (address path) (subject "") a)
9798 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9799 (setq address (match-string 1 path)
9800 subject (org-link-escape (match-string 2 path))))
9801 (while args
9802 (cond
9803 ((not (stringp (car args))) (push (pop args) args1))
9804 (t (setq a (pop args))
9805 (if (string-match "%a" a)
9806 (setq a (replace-match address t t a)))
9807 (if (string-match "%s" a)
9808 (setq a (replace-match subject t t a)))
9809 (push a args1))))
9810 (apply cmd (nreverse args1))))
9812 ((member type '("http" "https" "ftp" "news"))
9813 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9814 (org-link-escape
9815 path org-link-escape-chars-browser)
9816 path))))
9818 ((string= type "doi")
9819 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9820 (org-link-escape
9821 path org-link-escape-chars-browser)
9822 path))))
9824 ((member type '("message"))
9825 (browse-url (concat type ":" path)))
9827 ((string= type "tags")
9828 (org-tags-view arg path))
9830 ((string= type "tree-match")
9831 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9833 ((string= type "file")
9834 (if (string-match "::\\([0-9]+\\)\\'" path)
9835 (setq line (string-to-number (match-string 1 path))
9836 path (substring path 0 (match-beginning 0)))
9837 (if (string-match "::\\(.+\\)\\'" path)
9838 (setq search (match-string 1 path)
9839 path (substring path 0 (match-beginning 0)))))
9840 (if (string-match "[*?{]" (file-name-nondirectory path))
9841 (dired path)
9842 (org-open-file path arg line search)))
9844 ((string= type "shell")
9845 (let ((buf (generate-new-buffer "*Org Shell Output"))
9846 (cmd path))
9847 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9848 (string-match org-confirm-shell-link-not-regexp cmd))
9849 (not org-confirm-shell-link-function)
9850 (funcall org-confirm-shell-link-function
9851 (format "Execute \"%s\" in shell? "
9852 (org-add-props cmd nil
9853 'face 'org-warning))))
9854 (progn
9855 (message "Executing %s" cmd)
9856 (shell-command cmd buf)
9857 (if (featurep 'midnight)
9858 (setq clean-buffer-list-kill-buffer-names
9859 (cons buf clean-buffer-list-kill-buffer-names))))
9860 (error "Abort"))))
9862 ((string= type "elisp")
9863 (let ((cmd path))
9864 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9865 (string-match org-confirm-elisp-link-not-regexp cmd))
9866 (not org-confirm-elisp-link-function)
9867 (funcall org-confirm-elisp-link-function
9868 (format "Execute \"%s\" as elisp? "
9869 (org-add-props cmd nil
9870 'face 'org-warning))))
9871 (message "%s => %s" cmd
9872 (if (equal (string-to-char cmd) ?\()
9873 (eval (read cmd))
9874 (call-interactively (read cmd))))
9875 (error "Abort"))))
9877 ((and (string= type "thisfile")
9878 (run-hook-with-args-until-success
9879 'org-open-link-functions path)))
9881 ((string= type "thisfile")
9882 (if arg
9883 (switch-to-buffer-other-window
9884 (org-get-buffer-for-internal-link (current-buffer)))
9885 (org-mark-ring-push))
9886 (let ((cmd `(org-link-search
9887 ,path
9888 ,(cond ((equal arg '(4)) ''occur)
9889 ((equal arg '(16)) ''org-occur))
9890 ,pos)))
9891 (condition-case nil (let ((org-link-search-inhibit-query t))
9892 (eval cmd))
9893 (error (progn (widen) (eval cmd))))))
9895 (t (browse-url-at-point)))))))
9896 (move-marker org-open-link-marker nil)
9897 (run-hook-with-args 'org-follow-link-hook)))
9899 (defun org-offer-links-in-entry (&optional nth zero)
9900 "Offer links in the current entry and follow the selected link.
9901 If there is only one link, follow it immediately as well.
9902 If NTH is an integer, immediately pick the NTH link found.
9903 If ZERO is a string, check also this string for a link, and if
9904 there is one, offer it as link number zero."
9905 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9906 "\\(" org-angle-link-re "\\)\\|"
9907 "\\(" org-plain-link-re "\\)"))
9908 (cnt ?0)
9909 (in-emacs (if (integerp nth) nil nth))
9910 have-zero end links link c)
9911 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9912 (push (match-string 0 zero) links)
9913 (setq cnt (1- cnt) have-zero t))
9914 (save-excursion
9915 (org-back-to-heading t)
9916 (setq end (save-excursion (outline-next-heading) (point)))
9917 (while (re-search-forward re end t)
9918 (push (match-string 0) links))
9919 (setq links (org-uniquify (reverse links))))
9921 (cond
9922 ((null links)
9923 (message "No links"))
9924 ((equal (length links) 1)
9925 (setq link (list (car links))))
9926 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9927 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9928 (t ; we have to select a link
9929 (save-excursion
9930 (save-window-excursion
9931 (delete-other-windows)
9932 (with-output-to-temp-buffer "*Select Link*"
9933 (mapc (lambda (l)
9934 (if (not (string-match org-bracket-link-regexp l))
9935 (princ (format "[%c] %s\n" (incf cnt)
9936 (org-remove-angle-brackets l)))
9937 (if (match-end 3)
9938 (princ (format "[%c] %s (%s)\n" (incf cnt)
9939 (match-string 3 l) (match-string 1 l)))
9940 (princ (format "[%c] %s\n" (incf cnt)
9941 (match-string 1 l))))))
9942 links))
9943 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9944 (message "Select link to open, RET to open all:")
9945 (setq c (read-char-exclusive))
9946 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9947 (when (equal c ?q) (error "Abort"))
9948 (if (equal c ?\C-m)
9949 (setq link links)
9950 (setq nth (- c ?0))
9951 (if have-zero (setq nth (1+ nth)))
9952 (unless (and (integerp nth) (>= (length links) nth))
9953 (error "Invalid link selection"))
9954 (setq link (list (nth (1- nth) links))))))
9955 (if link
9956 (let ((buf (current-buffer)))
9957 (dolist (l link)
9958 (org-open-link-from-string l in-emacs buf))
9960 nil)))
9962 ;; Add special file links that specify the way of opening
9964 (org-add-link-type "file+sys" 'org-open-file-with-system)
9965 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9966 (defun org-open-file-with-system (path)
9967 "Open file at PATH using the system way of opening it."
9968 (org-open-file path 'system))
9969 (defun org-open-file-with-emacs (path)
9970 "Open file at PATH in Emacs."
9971 (org-open-file path 'emacs))
9972 (defun org-remove-file-link-modifiers ()
9973 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9974 (goto-char (point-min))
9975 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9976 (org-if-unprotected
9977 (replace-match "file:" t t))))
9978 (eval-after-load "org-exp"
9979 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9980 'org-remove-file-link-modifiers))
9982 ;;;; Time estimates
9984 (defun org-get-effort (&optional pom)
9985 "Get the effort estimate for the current entry."
9986 (org-entry-get pom org-effort-property))
9988 ;;; File search
9990 (defvar org-create-file-search-functions nil
9991 "List of functions to construct the right search string for a file link.
9992 These functions are called in turn with point at the location to
9993 which the link should point.
9995 A function in the hook should first test if it would like to
9996 handle this file type, for example by checking the `major-mode'
9997 or the file extension. If it decides not to handle this file, it
9998 should just return nil to give other functions a chance. If it
9999 does handle the file, it must return the search string to be used
10000 when following the link. The search string will be part of the
10001 file link, given after a double colon, and `org-open-at-point'
10002 will automatically search for it. If special measures must be
10003 taken to make the search successful, another function should be
10004 added to the companion hook `org-execute-file-search-functions',
10005 which see.
10007 A function in this hook may also use `setq' to set the variable
10008 `description' to provide a suggestion for the descriptive text to
10009 be used for this link when it gets inserted into an Org-mode
10010 buffer with \\[org-insert-link].")
10012 (defvar org-execute-file-search-functions nil
10013 "List of functions to execute a file search triggered by a link.
10015 Functions added to this hook must accept a single argument, the
10016 search string that was part of the file link, the part after the
10017 double colon. The function must first check if it would like to
10018 handle this search, for example by checking the `major-mode' or
10019 the file extension. If it decides not to handle this search, it
10020 should just return nil to give other functions a chance. If it
10021 does handle the search, it must return a non-nil value to keep
10022 other functions from trying.
10024 Each function can access the current prefix argument through the
10025 variable `current-prefix-argument'. Note that a single prefix is
10026 used to force opening a link in Emacs, so it may be good to only
10027 use a numeric or double prefix to guide the search function.
10029 In case this is needed, a function in this hook can also restore
10030 the window configuration before `org-open-at-point' was called using:
10032 (set-window-configuration org-window-config-before-follow-link)")
10034 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10035 (defun org-link-search (s &optional type avoid-pos stealth)
10036 "Search for a link search option.
10037 If S is surrounded by forward slashes, it is interpreted as a
10038 regular expression. In org-mode files, this will create an `org-occur'
10039 sparse tree. In ordinary files, `occur' will be used to list matches.
10040 If the current buffer is in `dired-mode', grep will be used to search
10041 in all files. If AVOID-POS is given, ignore matches near that position.
10043 When optional argument STEALTH is non-nil, do not modify
10044 visibility around point, thus ignoring
10045 `org-show-hierarchy-above', `org-show-following-heading' and
10046 `org-show-siblings' variables."
10047 (let ((case-fold-search t)
10048 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10049 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10050 (append '(("") (" ") ("\t") ("\n"))
10051 org-emphasis-alist)
10052 "\\|") "\\)"))
10053 (pos (point))
10054 (pre nil) (post nil)
10055 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10056 (cond
10057 ;; First check if there are any special search functions
10058 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10059 ;; Now try the builtin stuff
10060 ((and (equal (string-to-char s0) ?#)
10061 (> (length s0) 1)
10062 (save-excursion
10063 (goto-char (point-min))
10064 (and
10065 (re-search-forward
10066 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10067 (setq type 'dedicated
10068 pos (match-beginning 0))))
10069 ;; There is an exact target for this
10070 (goto-char pos)
10071 (org-back-to-heading t)))
10072 ((save-excursion
10073 (goto-char (point-min))
10074 (and
10075 (re-search-forward
10076 (concat "<<" (regexp-quote s0) ">>") nil t)
10077 (setq type 'dedicated
10078 pos (match-beginning 0))))
10079 ;; There is an exact target for this
10080 (goto-char pos))
10081 ((save-excursion
10082 (goto-char (point-min))
10083 (and
10084 (re-search-forward
10085 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10086 (setq type 'dedicated pos (match-beginning 0))))
10087 ;; Found an invisible target.
10088 (goto-char pos))
10089 ((save-excursion
10090 (goto-char (point-min))
10091 (and
10092 (re-search-forward
10093 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10094 (setq type 'dedicated pos (match-beginning 0))))
10095 ;; Found an element with a matching #+name affiliated keyword.
10096 (goto-char pos))
10097 ((and (string-match "^(\\(.*\\))$" s0)
10098 (save-excursion
10099 (goto-char (point-min))
10100 (and
10101 (re-search-forward
10102 (concat "[^[]" (regexp-quote
10103 (format org-coderef-label-format
10104 (match-string 1 s0))))
10105 nil t)
10106 (setq type 'dedicated
10107 pos (1+ (match-beginning 0))))))
10108 ;; There is a coderef target for this
10109 (goto-char pos))
10110 ((string-match "^/\\(.*\\)/$" s)
10111 ;; A regular expression
10112 (cond
10113 ((derived-mode-p 'org-mode)
10114 (org-occur (match-string 1 s)))
10115 ;;((eq major-mode 'dired-mode)
10116 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10117 (t (org-do-occur (match-string 1 s)))))
10118 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10119 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10120 (goto-char (point-min))
10121 (cond
10122 ((let (case-fold-search)
10123 (re-search-forward (format org-complex-heading-regexp-format
10124 (regexp-quote s))
10125 nil t))
10126 ;; OK, found a match
10127 (setq type 'dedicated)
10128 (goto-char (match-beginning 0)))
10129 ((and (not org-link-search-inhibit-query)
10130 (eq org-link-search-must-match-exact-headline 'query-to-create)
10131 (y-or-n-p "No match - create this as a new heading? "))
10132 (goto-char (point-max))
10133 (or (bolp) (newline))
10134 (insert "* " s "\n")
10135 (beginning-of-line 0))
10137 (goto-char pos)
10138 (error "No match"))))
10140 ;; A normal search string
10141 (when (equal (string-to-char s) ?*)
10142 ;; Anchor on headlines, post may include tags.
10143 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10144 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10145 s (substring s 1)))
10146 (remove-text-properties
10147 0 (length s)
10148 '(face nil mouse-face nil keymap nil fontified nil) s)
10149 ;; Make a series of regular expressions to find a match
10150 (setq words (org-split-string s "[ \n\r\t]+")
10152 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10153 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10154 "\\)" markers)
10155 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10156 re2a (concat "[ \t\r\n]" re2a_)
10157 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10158 re4 (concat "[^a-zA-Z_]" re4_)
10160 re1 (concat pre re2 post)
10161 re3 (concat pre (if pre re4_ re4) post)
10162 re5 (concat pre ".*" re4)
10163 re2 (concat pre re2)
10164 re2a (concat pre (if pre re2a_ re2a))
10165 re4 (concat pre (if pre re4_ re4))
10166 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10167 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10168 re5 "\\)"
10170 (cond
10171 ((eq type 'org-occur) (org-occur reall))
10172 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10173 (t (goto-char (point-min))
10174 (setq type 'fuzzy)
10175 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10176 (org-search-not-self 1 re1 nil t)
10177 (org-search-not-self 1 re2 nil t)
10178 (org-search-not-self 1 re2a nil t)
10179 (org-search-not-self 1 re3 nil t)
10180 (org-search-not-self 1 re4 nil t)
10181 (org-search-not-self 1 re5 nil t)
10183 (goto-char (match-beginning 1))
10184 (goto-char pos)
10185 (error "No match"))))))
10186 (and (derived-mode-p 'org-mode)
10187 (not stealth)
10188 (org-show-context 'link-search))
10189 type))
10191 (defun org-search-not-self (group &rest args)
10192 "Execute `re-search-forward', but only accept matches that do not
10193 enclose the position of `org-open-link-marker'."
10194 (let ((m org-open-link-marker))
10195 (catch 'exit
10196 (while (apply 're-search-forward args)
10197 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10198 (goto-char (match-end group))
10199 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10200 (> (match-beginning 0) (marker-position m))
10201 (< (match-end 0) (marker-position m)))
10202 (save-match-data
10203 (or (not (org-in-regexp
10204 org-bracket-link-analytic-regexp 1))
10205 (not (match-end 4)) ; no description
10206 (and (<= (match-beginning 4) (point))
10207 (>= (match-end 4) (point))))))
10208 (throw 'exit (point))))))))
10210 (defun org-get-buffer-for-internal-link (buffer)
10211 "Return a buffer to be used for displaying the link target of internal links."
10212 (cond
10213 ((not org-display-internal-link-with-indirect-buffer)
10214 buffer)
10215 ((string-match "(Clone)$" (buffer-name buffer))
10216 (message "Buffer is already a clone, not making another one")
10217 ;; we also do not modify visibility in this case
10218 buffer)
10219 (t ; make a new indirect buffer for displaying the link
10220 (let* ((bn (buffer-name buffer))
10221 (ibn (concat bn "(Clone)"))
10222 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10223 (with-current-buffer ib (org-overview))
10224 ib))))
10226 (defun org-do-occur (regexp &optional cleanup)
10227 "Call the Emacs command `occur'.
10228 If CLEANUP is non-nil, remove the printout of the regular expression
10229 in the *Occur* buffer. This is useful if the regex is long and not useful
10230 to read."
10231 (occur regexp)
10232 (when cleanup
10233 (let ((cwin (selected-window)) win beg end)
10234 (when (setq win (get-buffer-window "*Occur*"))
10235 (select-window win))
10236 (goto-char (point-min))
10237 (when (re-search-forward "match[a-z]+" nil t)
10238 (setq beg (match-end 0))
10239 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10240 (setq end (1- (match-beginning 0)))))
10241 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10242 (goto-char (point-min))
10243 (select-window cwin))))
10245 ;;; The mark ring for links jumps
10247 (defvar org-mark-ring nil
10248 "Mark ring for positions before jumps in Org-mode.")
10249 (defvar org-mark-ring-last-goto nil
10250 "Last position in the mark ring used to go back.")
10251 ;; Fill and close the ring
10252 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10253 (loop for i from 1 to org-mark-ring-length do
10254 (push (make-marker) org-mark-ring))
10255 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10256 org-mark-ring)
10258 (defun org-mark-ring-push (&optional pos buffer)
10259 "Put the current position or POS into the mark ring and rotate it."
10260 (interactive)
10261 (setq pos (or pos (point)))
10262 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10263 (move-marker (car org-mark-ring)
10264 (or pos (point))
10265 (or buffer (current-buffer)))
10266 (message "%s"
10267 (substitute-command-keys
10268 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10270 (defun org-mark-ring-goto (&optional n)
10271 "Jump to the previous position in the mark ring.
10272 With prefix arg N, jump back that many stored positions. When
10273 called several times in succession, walk through the entire ring.
10274 Org-mode commands jumping to a different position in the current file,
10275 or to another Org-mode file, automatically push the old position
10276 onto the ring."
10277 (interactive "p")
10278 (let (p m)
10279 (if (eq last-command this-command)
10280 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10281 (setq p org-mark-ring))
10282 (setq org-mark-ring-last-goto p)
10283 (setq m (car p))
10284 (org-pop-to-buffer-same-window (marker-buffer m))
10285 (goto-char m)
10286 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10288 (defun org-remove-angle-brackets (s)
10289 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10290 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10292 (defun org-add-angle-brackets (s)
10293 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10294 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10296 (defun org-remove-double-quotes (s)
10297 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10298 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10301 ;;; Following specific links
10303 (defun org-follow-timestamp-link ()
10304 "Open an agenda view for the time-stamp date/range at point."
10305 (cond
10306 ((org-at-date-range-p t)
10307 (let ((org-agenda-start-on-weekday)
10308 (t1 (match-string 1))
10309 (t2 (match-string 2)) tt1 tt2)
10310 (setq tt1 (time-to-days (org-time-string-to-time t1))
10311 tt2 (time-to-days (org-time-string-to-time t2)))
10312 (let ((org-agenda-buffer-tmp-name
10313 (format "*Org Agenda(a:%s)"
10314 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10315 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10316 ((org-at-timestamp-p t)
10317 (let ((org-agenda-buffer-tmp-name
10318 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10319 (org-agenda-list nil (time-to-days (org-time-string-to-time
10320 (substring (match-string 1) 0 10)))
10321 1)))
10322 (t (error "This should not happen"))))
10325 ;;; Following file links
10326 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10327 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10328 (declare-function mailcap-mime-info
10329 "mailcap" (string &optional request no-decode))
10330 (defvar org-wait nil)
10331 (defun org-open-file (path &optional in-emacs line search)
10332 "Open the file at PATH.
10333 First, this expands any special file name abbreviations. Then the
10334 configuration variable `org-file-apps' is checked if it contains an
10335 entry for this file type, and if yes, the corresponding command is launched.
10337 If no application is found, Emacs simply visits the file.
10339 With optional prefix argument IN-EMACS, Emacs will visit the file.
10340 With a double \\[universal-argument] \\[universal-argument] \
10341 prefix arg, Org tries to avoid opening in Emacs
10342 and to use an external application to visit the file.
10344 Optional LINE specifies a line to go to, optional SEARCH a string
10345 to search for. If LINE or SEARCH is given, the file will be
10346 opened in Emacs, unless an entry from org-file-apps that makes
10347 use of groups in a regexp matches.
10349 If you want to change the way frames are used when following a
10350 link, please customize `org-link-frame-setup'.
10352 If the file does not exist, an error is thrown."
10353 (let* ((file (if (equal path "")
10354 buffer-file-name
10355 (substitute-in-file-name (expand-file-name path))))
10356 (file-apps (append org-file-apps (org-default-apps)))
10357 (apps (org-remove-if
10358 'org-file-apps-entry-match-against-dlink-p file-apps))
10359 (apps-dlink (org-remove-if-not
10360 'org-file-apps-entry-match-against-dlink-p file-apps))
10361 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10362 (dirp (if remp nil (file-directory-p file)))
10363 (file (if (and dirp org-open-directory-means-index-dot-org)
10364 (concat (file-name-as-directory file) "index.org")
10365 file))
10366 (a-m-a-p (assq 'auto-mode apps))
10367 (dfile (downcase file))
10368 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10369 (link (cond ((and (eq line nil)
10370 (eq search nil))
10371 file)
10372 (line
10373 (concat file "::" (number-to-string line)))
10374 (search
10375 (concat file "::" search))))
10376 (dlink (downcase link))
10377 (old-buffer (current-buffer))
10378 (old-pos (point))
10379 (old-mode major-mode)
10380 ext cmd link-match-data)
10381 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10382 (setq ext (match-string 1 dfile))
10383 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10384 (setq ext (match-string 1 dfile))))
10385 (cond
10386 ((member in-emacs '((16) system))
10387 (setq cmd (cdr (assoc 'system apps))))
10388 (in-emacs (setq cmd 'emacs))
10390 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10391 (and dirp (cdr (assoc 'directory apps)))
10392 ; first, try matching against apps-dlink
10393 ; if we get a match here, store the match data for later
10394 (let ((match (assoc-default dlink apps-dlink
10395 'string-match)))
10396 (if match
10397 (progn (setq link-match-data (match-data))
10398 match)
10399 (progn (setq in-emacs (or in-emacs line search))
10400 nil))) ; if we have no match in apps-dlink,
10401 ; always open the file in emacs if line or search
10402 ; is given (for backwards compatibility)
10403 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10404 'string-match)
10405 (cdr (assoc ext apps))
10406 (cdr (assoc t apps))))))
10407 (when (eq cmd 'system)
10408 (setq cmd (cdr (assoc 'system apps))))
10409 (when (eq cmd 'default)
10410 (setq cmd (cdr (assoc t apps))))
10411 (when (eq cmd 'mailcap)
10412 (require 'mailcap)
10413 (mailcap-parse-mailcaps)
10414 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10415 (command (mailcap-mime-info mime-type)))
10416 (if (stringp command)
10417 (setq cmd command)
10418 (setq cmd 'emacs))))
10419 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10420 (not (file-exists-p file))
10421 (not org-open-non-existing-files))
10422 (error "No such file: %s" file))
10423 (cond
10424 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10425 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10426 (while (string-match "['\"]%s['\"]" cmd)
10427 (setq cmd (replace-match "%s" t t cmd)))
10428 (while (string-match "%s" cmd)
10429 (setq cmd (replace-match
10430 (save-match-data
10431 (shell-quote-argument
10432 (convert-standard-filename file)))
10433 t t cmd)))
10435 ;; Replace "%1", "%2" etc. in command with group matches from regex
10436 (save-match-data
10437 (let ((match-index 1)
10438 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10439 (set-match-data link-match-data)
10440 (while (<= match-index number-of-groups)
10441 (let ((regex (concat "%" (number-to-string match-index)))
10442 (replace-with (match-string match-index dlink)))
10443 (while (string-match regex cmd)
10444 (setq cmd (replace-match replace-with t t cmd))))
10445 (setq match-index (+ match-index 1)))))
10447 (save-window-excursion
10448 (message "Running %s...done" cmd)
10449 (start-process-shell-command cmd nil cmd)
10450 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10451 ((or (stringp cmd)
10452 (eq cmd 'emacs))
10453 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10454 (widen)
10455 (if line (org-goto-line line)
10456 (if search (org-link-search search))))
10457 ((consp cmd)
10458 (let ((file (convert-standard-filename file)))
10459 (save-match-data
10460 (set-match-data link-match-data)
10461 (eval cmd))))
10462 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10463 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10464 (or (not (equal old-buffer (current-buffer)))
10465 (not (equal old-pos (point))))
10466 (org-mark-ring-push old-pos old-buffer))))
10468 (defun org-file-apps-entry-match-against-dlink-p (entry)
10469 "This function returns non-nil if `entry' uses a regular
10470 expression which should be matched against the whole link by
10471 org-open-file.
10473 It assumes that is the case when the entry uses a regular
10474 expression which has at least one grouping construct and the
10475 action is either a lisp form or a command string containing
10476 '%1', i.e. using at least one subexpression match as a
10477 parameter."
10478 (let ((selector (car entry))
10479 (action (cdr entry)))
10480 (if (stringp selector)
10481 (and (> (regexp-opt-depth selector) 0)
10482 (or (and (stringp action)
10483 (string-match "%[0-9]" action))
10484 (consp action)))
10485 nil)))
10487 (defun org-default-apps ()
10488 "Return the default applications for this operating system."
10489 (cond
10490 ((eq system-type 'darwin)
10491 org-file-apps-defaults-macosx)
10492 ((eq system-type 'windows-nt)
10493 org-file-apps-defaults-windowsnt)
10494 (t org-file-apps-defaults-gnu)))
10496 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10497 "Convert extensions to regular expressions in the cars of LIST.
10498 Also, weed out any non-string entries, because the return value is used
10499 only for regexp matching.
10500 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10501 point to the symbol `emacs', indicating that the file should
10502 be opened in Emacs."
10503 (append
10504 (delq nil
10505 (mapcar (lambda (x)
10506 (if (not (stringp (car x)))
10508 (if (string-match "\\W" (car x))
10510 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10511 list))
10512 (if add-auto-mode
10513 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10515 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10516 (defun org-file-remote-p (file)
10517 "Test whether FILE specifies a location on a remote system.
10518 Return non-nil if the location is indeed remote.
10520 For example, the filename \"/user@host:/foo\" specifies a location
10521 on the system \"/user@host:\"."
10522 (cond ((fboundp 'file-remote-p)
10523 (file-remote-p file))
10524 ((fboundp 'tramp-handle-file-remote-p)
10525 (tramp-handle-file-remote-p file))
10526 ((and (boundp 'ange-ftp-name-format)
10527 (string-match (car ange-ftp-name-format) file))
10528 t)))
10531 ;;;; Refiling
10533 (defun org-get-org-file ()
10534 "Read a filename, with default directory `org-directory'."
10535 (let ((default (or org-default-notes-file remember-data-file)))
10536 (read-file-name (format "File name [%s]: " default)
10537 (file-name-as-directory org-directory)
10538 default)))
10540 (defun org-notes-order-reversed-p ()
10541 "Check if the current file should receive notes in reversed order."
10542 (cond
10543 ((not org-reverse-note-order) nil)
10544 ((eq t org-reverse-note-order) t)
10545 ((not (listp org-reverse-note-order)) nil)
10546 (t (catch 'exit
10547 (let ((all org-reverse-note-order)
10548 entry)
10549 (while (setq entry (pop all))
10550 (if (string-match (car entry) buffer-file-name)
10551 (throw 'exit (cdr entry))))
10552 nil)))))
10554 (defvar org-refile-target-table nil
10555 "The list of refile targets, created by `org-refile'.")
10557 (defvar org-agenda-new-buffers nil
10558 "Buffers created to visit agenda files.")
10560 (defvar org-refile-cache nil
10561 "Cache for refile targets.")
10563 (defvar org-refile-markers nil
10564 "All the markers used for caching refile locations.")
10566 (defun org-refile-marker (pos)
10567 "Get a new refile marker, but only if caching is in use."
10568 (if (not org-refile-use-cache)
10570 (let ((m (make-marker)))
10571 (move-marker m pos)
10572 (push m org-refile-markers)
10573 m)))
10575 (defun org-refile-cache-clear ()
10576 "Clear the refile cache and disable all the markers."
10577 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10578 (setq org-refile-markers nil)
10579 (setq org-refile-cache nil)
10580 (message "Refile cache has been cleared"))
10582 (defun org-refile-cache-check-set (set)
10583 "Check if all the markers in the cache still have live buffers."
10584 (let (marker)
10585 (catch 'exit
10586 (while (and set (setq marker (nth 3 (pop set))))
10587 ;; if org-refile-use-outline-path is 'file, marker may be nil
10588 (when (and marker (null (marker-buffer marker)))
10589 (message "not found") (sit-for 3)
10590 (throw 'exit nil)))
10591 t)))
10593 (defun org-refile-cache-put (set &rest identifiers)
10594 "Push the refile targets SET into the cache, under IDENTIFIERS."
10595 (let* ((key (sha1 (prin1-to-string identifiers)))
10596 (entry (assoc key org-refile-cache)))
10597 (if entry
10598 (setcdr entry set)
10599 (push (cons key set) org-refile-cache))))
10601 (defun org-refile-cache-get (&rest identifiers)
10602 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10603 (cond
10604 ((not org-refile-cache) nil)
10605 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10607 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10608 org-refile-cache))))
10609 (and set (org-refile-cache-check-set set) set)))))
10611 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10612 "Produce a table with refile targets."
10613 (let ((case-fold-search nil)
10614 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10615 (entries (or org-refile-targets '((nil . (:level . 1)))))
10616 targets tgs txt re files f desc descre fast-path-p level pos0)
10617 (message "Getting targets...")
10618 (with-current-buffer (or default-buffer (current-buffer))
10619 (while (setq entry (pop entries))
10620 (setq files (car entry) desc (cdr entry))
10621 (setq fast-path-p nil)
10622 (cond
10623 ((null files) (setq files (list (current-buffer))))
10624 ((eq files 'org-agenda-files)
10625 (setq files (org-agenda-files 'unrestricted)))
10626 ((and (symbolp files) (fboundp files))
10627 (setq files (funcall files)))
10628 ((and (symbolp files) (boundp files))
10629 (setq files (symbol-value files))))
10630 (if (stringp files) (setq files (list files)))
10631 (cond
10632 ((eq (car desc) :tag)
10633 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10634 ((eq (car desc) :todo)
10635 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10636 ((eq (car desc) :regexp)
10637 (setq descre (cdr desc)))
10638 ((eq (car desc) :level)
10639 (setq descre (concat "^\\*\\{" (number-to-string
10640 (if org-odd-levels-only
10641 (1- (* 2 (cdr desc)))
10642 (cdr desc)))
10643 "\\}[ \t]")))
10644 ((eq (car desc) :maxlevel)
10645 (setq fast-path-p t)
10646 (setq descre (concat "^\\*\\{1," (number-to-string
10647 (if org-odd-levels-only
10648 (1- (* 2 (cdr desc)))
10649 (cdr desc)))
10650 "\\}[ \t]")))
10651 (t (error "Bad refiling target description %s" desc)))
10652 (while (setq f (pop files))
10653 (with-current-buffer
10654 (if (bufferp f) f (org-get-agenda-file-buffer f))
10656 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10657 (progn
10658 (if (bufferp f) (setq f (buffer-file-name
10659 (buffer-base-buffer f))))
10660 (setq f (and f (expand-file-name f)))
10661 (if (eq org-refile-use-outline-path 'file)
10662 (push (list (file-name-nondirectory f) f nil nil) tgs))
10663 (save-excursion
10664 (save-restriction
10665 (widen)
10666 (goto-char (point-min))
10667 (while (re-search-forward descre nil t)
10668 (goto-char (setq pos0 (point-at-bol)))
10669 (catch 'next
10670 (when org-refile-target-verify-function
10671 (save-match-data
10672 (or (funcall org-refile-target-verify-function)
10673 (throw 'next t))))
10674 (when (and (looking-at org-complex-heading-regexp)
10675 (not (member (match-string 4) excluded-entries))
10676 (match-string 4))
10677 (setq level (org-reduced-level
10678 (- (match-end 1) (match-beginning 1)))
10679 txt (org-link-display-format (match-string 4))
10680 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10681 re (format org-complex-heading-regexp-format
10682 (regexp-quote (match-string 4))))
10683 (when org-refile-use-outline-path
10684 (setq txt (mapconcat
10685 'org-protect-slash
10686 (append
10687 (if (eq org-refile-use-outline-path
10688 'file)
10689 (list (file-name-nondirectory
10690 (buffer-file-name
10691 (buffer-base-buffer))))
10692 (if (eq org-refile-use-outline-path
10693 'full-file-path)
10694 (list (buffer-file-name
10695 (buffer-base-buffer)))))
10696 (org-get-outline-path fast-path-p
10697 level txt)
10698 (list txt))
10699 "/")))
10700 (push (list txt f re (org-refile-marker (point)))
10701 tgs)))
10702 (when (= (point) pos0)
10703 ;; verification function has not moved point
10704 (goto-char (point-at-eol))))))))
10705 (when org-refile-use-cache
10706 (org-refile-cache-put tgs (buffer-file-name) descre))
10707 (setq targets (append tgs targets))
10708 ))))
10709 (message "Getting targets...done")
10710 (nreverse targets)))
10712 (defun org-protect-slash (s)
10713 (while (string-match "/" s)
10714 (setq s (replace-match "\\" t t s)))
10717 (defvar org-olpa (make-vector 20 nil))
10719 (defun org-get-outline-path (&optional fastp level heading)
10720 "Return the outline path to the current entry, as a list.
10722 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10723 routine which makes outline path derivations for an entire file,
10724 avoiding backtracing. Refile target collection makes use of that."
10725 (if fastp
10726 (progn
10727 (if (> level 19)
10728 (error "Outline path failure, more than 19 levels"))
10729 (loop for i from level upto 19 do
10730 (aset org-olpa i nil))
10731 (prog1
10732 (delq nil (append org-olpa nil))
10733 (aset org-olpa level heading)))
10734 (let (rtn case-fold-search)
10735 (save-excursion
10736 (save-restriction
10737 (widen)
10738 (while (org-up-heading-safe)
10739 (when (looking-at org-complex-heading-regexp)
10740 (push (org-match-string-no-properties 4) rtn)))
10741 rtn)))))
10743 (defun org-format-outline-path (path &optional width prefix separator)
10744 "Format the outline path PATH for display.
10745 WIDTH is the maximum number of characters that is available.
10746 PREFIX is a prefix to be included in the returned string,
10747 such as the file name.
10748 SEPARATOR is inserted between the different parts of the path,
10749 the default is \"/\"."
10750 (setq width (or width 79))
10751 (if prefix (setq width (- width (length prefix))))
10752 (if (not path)
10753 (or prefix "")
10754 (let* ((nsteps (length path))
10755 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10756 (maxwidth (if (<= total-width width)
10757 10000 ;; everything fits
10758 ;; we need to shorten the level headings
10759 (/ (- width nsteps) nsteps)))
10760 (org-odd-levels-only nil)
10761 (n 0)
10762 (total (1+ (length prefix))))
10763 (setq maxwidth (max maxwidth 10))
10764 (concat prefix
10765 (if prefix (or separator "/"))
10766 (mapconcat
10767 (lambda (h)
10768 (setq n (1+ n))
10769 (if (and (= n nsteps) (< maxwidth 10000))
10770 (setq maxwidth (- total-width total)))
10771 (if (< (length h) maxwidth)
10772 (progn (setq total (+ total (length h) 1)) h)
10773 (setq h (substring h 0 (- maxwidth 2))
10774 total (+ total maxwidth 1))
10775 (if (string-match "[ \t]+\\'" h)
10776 (setq h (substring h 0 (match-beginning 0))))
10777 (setq h (concat h "..")))
10778 (org-add-props h nil 'face
10779 (nth (% (1- n) org-n-level-faces)
10780 org-level-faces))
10782 path (or separator "/"))))))
10784 (defun org-display-outline-path (&optional file current separator just-return-string)
10785 "Display the current outline path in the echo area.
10787 If FILE is non-nil, prepend the output with the file name.
10788 If CURRENT is non-nil, append the current heading to the output.
10789 SEPARATOR is passed through to `org-format-outline-path'. It separates
10790 the different parts of the path and defaults to \"/\".
10791 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10792 (interactive "P")
10793 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10794 (case-fold-search nil)
10795 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10796 res)
10797 (if current (setq path (append path
10798 (save-excursion
10799 (org-back-to-heading t)
10800 (if (looking-at org-complex-heading-regexp)
10801 (list (match-string 4)))))))
10802 (setq res
10803 (org-format-outline-path
10804 path
10805 (1- (frame-width))
10806 (and file bfn (concat (file-name-nondirectory bfn) separator))
10807 separator))
10808 (if just-return-string
10809 (org-no-properties res)
10810 (message "%s" res))))
10812 (defvar org-refile-history nil
10813 "History for refiling operations.")
10815 (defvar org-after-refile-insert-hook nil
10816 "Hook run after `org-refile' has inserted its stuff at the new location.
10817 Note that this is still *before* the stuff will be removed from
10818 the *old* location.")
10820 (defvar org-capture-last-stored-marker)
10821 (defvar org-refile-keep nil
10822 "Non-nil means `org-refile' will copy instead of refile.")
10824 (defun org-copy ()
10825 "Like `org-refile', but copy."
10826 (interactive)
10827 (let ((org-refile-keep t))
10828 (funcall 'org-refile nil nil nil "Copy")))
10830 (defun org-refile (&optional goto default-buffer rfloc msg)
10831 "Move the entry or entries at point to another heading.
10832 The list of target headings is compiled using the information in
10833 `org-refile-targets', which see.
10835 At the target location, the entry is filed as a subitem of the target
10836 heading. Depending on `org-reverse-note-order', the new subitem will
10837 either be the first or the last subitem.
10839 If there is an active region, all entries in that region will be moved.
10840 However, the region must fulfill the requirement that the first heading
10841 is the first one sets the top-level of the moved text - at most siblings
10842 below it are allowed.
10844 With prefix arg GOTO, the command will only visit the target location
10845 and not actually move anything.
10847 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10848 go to the location where the last refiling operation has put the subtree.
10849 With a prefix argument of `2', refile to the running clock.
10851 RFLOC can be a refile location obtained in a different way.
10853 MSG is a string to replace \"Refile\" in the default prompt with
10854 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10856 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10858 If you are using target caching (see `org-refile-use-cache'),
10859 you have to clear the target cache in order to find new targets.
10860 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10861 prefix argument (`C-u C-u C-u C-c C-w')."
10863 (interactive "P")
10864 (if (member goto '(0 (64)))
10865 (org-refile-cache-clear)
10866 (let* ((actionmsg (or msg "Refile"))
10867 (cbuf (current-buffer))
10868 (regionp (org-region-active-p))
10869 (region-start (and regionp (region-beginning)))
10870 (region-end (and regionp (region-end)))
10871 (region-length (and regionp (- region-end region-start)))
10872 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10873 pos it nbuf file re level reversed)
10874 (setq last-command nil)
10875 (when regionp
10876 (goto-char region-start)
10877 (or (bolp) (goto-char (point-at-bol)))
10878 (setq region-start (point))
10879 (unless (or (org-kill-is-subtree-p
10880 (buffer-substring region-start region-end))
10881 (prog1 org-refile-active-region-within-subtree
10882 (org-toggle-heading)))
10883 (error "The region is not a (sequence of) subtree(s)")))
10884 (if (equal goto '(16))
10885 (org-refile-goto-last-stored)
10886 (when (or
10887 (and (equal goto 2)
10888 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10889 (prog1
10890 (setq it (list (or org-clock-heading "running clock")
10891 (buffer-file-name
10892 (marker-buffer org-clock-hd-marker))
10894 (marker-position org-clock-hd-marker)))
10895 (setq goto nil)))
10896 (setq it (or rfloc
10897 (let (heading-text)
10898 (save-excursion
10899 (unless goto
10900 (org-back-to-heading t)
10901 (setq heading-text
10902 (nth 4 (org-heading-components))))
10904 (org-refile-get-location
10905 (cond (goto "Goto")
10906 (regionp (concat actionmsg " region to"))
10907 (t (concat actionmsg " subtree \""
10908 heading-text "\" to")))
10909 default-buffer
10910 (and (not (equal '(4) goto))
10911 org-refile-allow-creating-parent-nodes)
10912 goto))))))
10913 (setq file (nth 1 it)
10914 re (nth 2 it)
10915 pos (nth 3 it))
10916 (if (and (not goto)
10918 (equal (buffer-file-name) file)
10919 (if regionp
10920 (and (>= pos region-start)
10921 (<= pos region-end))
10922 (and (>= pos (point))
10923 (< pos (save-excursion
10924 (org-end-of-subtree t t))))))
10925 (error "Cannot refile to position inside the tree or region"))
10927 (setq nbuf (or (find-buffer-visiting file)
10928 (find-file-noselect file)))
10929 (if goto
10930 (progn
10931 (org-pop-to-buffer-same-window nbuf)
10932 (goto-char pos)
10933 (org-show-context 'org-goto))
10934 (if regionp
10935 (progn
10936 (org-kill-new (buffer-substring region-start region-end))
10937 (org-save-markers-in-region region-start region-end))
10938 (org-copy-subtree 1 nil t))
10939 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10940 (find-file-noselect file)))
10941 (setq reversed (org-notes-order-reversed-p))
10942 (save-excursion
10943 (save-restriction
10944 (widen)
10945 (if pos
10946 (progn
10947 (goto-char pos)
10948 (looking-at org-outline-regexp)
10949 (setq level (org-get-valid-level (funcall outline-level) 1))
10950 (goto-char
10951 (if reversed
10952 (or (outline-next-heading) (point-max))
10953 (or (save-excursion (org-get-next-sibling))
10954 (org-end-of-subtree t t)
10955 (point-max)))))
10956 (setq level 1)
10957 (if (not reversed)
10958 (goto-char (point-max))
10959 (goto-char (point-min))
10960 (or (outline-next-heading) (goto-char (point-max)))))
10961 (if (not (bolp)) (newline))
10962 (org-paste-subtree level)
10963 (when org-log-refile
10964 (org-add-log-setup 'refile nil nil 'findpos
10965 org-log-refile)
10966 (unless (eq org-log-refile 'note)
10967 (save-excursion (org-add-log-note))))
10968 (and org-auto-align-tags
10969 (let ((org-loop-over-headlines-in-active-region nil))
10970 (org-set-tags nil t)))
10971 (with-demoted-errors
10972 (bookmark-set "org-refile-last-stored"))
10973 ;; If we are refiling for capture, make sure that the
10974 ;; last-capture pointers point here
10975 (when (org-bound-and-true-p org-refile-for-capture)
10976 (with-demoted-errors
10977 (bookmark-set "org-capture-last-stored-marker"))
10978 (move-marker org-capture-last-stored-marker (point)))
10979 (if (fboundp 'deactivate-mark) (deactivate-mark))
10980 (run-hooks 'org-after-refile-insert-hook))))
10981 (unless org-refile-keep
10982 (if regionp
10983 (delete-region (point) (+ (point) region-length))
10984 (org-cut-subtree)))
10985 (when (featurep 'org-inlinetask)
10986 (org-inlinetask-remove-END-maybe))
10987 (setq org-markers-to-move nil)
10988 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
10990 (defun org-refile-goto-last-stored ()
10991 "Go to the location where the last refile was stored."
10992 (interactive)
10993 (bookmark-jump "org-refile-last-stored")
10994 (message "This is the location of the last refile"))
10996 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10997 no-exclude)
10998 "Prompt the user for a refile location, using PROMPT.
10999 PROMPT should not be suffixed with a colon and a space, because
11000 this function appends the default value from
11001 `org-refile-history' automatically, if that is not empty.
11002 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11003 this is used for the GOTO interface."
11004 (let ((org-refile-targets org-refile-targets)
11005 (org-refile-use-outline-path org-refile-use-outline-path)
11006 excluded-entries)
11007 (when (and (derived-mode-p 'org-mode)
11008 (not org-refile-use-cache)
11009 (not no-exclude))
11010 (org-map-tree
11011 (lambda()
11012 (setq excluded-entries
11013 (append excluded-entries (list (org-get-heading t t)))))))
11014 (setq org-refile-target-table
11015 (org-refile-get-targets default-buffer excluded-entries)))
11016 (unless org-refile-target-table
11017 (error "No refile targets"))
11018 (let* ((cbuf (current-buffer))
11019 (partial-completion-mode nil)
11020 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11021 (cfunc (if (and org-refile-use-outline-path
11022 org-outline-path-complete-in-steps)
11023 'org-olpath-completing-read
11024 'org-icompleting-read))
11025 (extra (if org-refile-use-outline-path "/" ""))
11026 (cbnex (concat (buffer-name) extra))
11027 (filename (and cfn (expand-file-name cfn)))
11028 (tbl (mapcar
11029 (lambda (x)
11030 (if (and (not (member org-refile-use-outline-path
11031 '(file full-file-path)))
11032 (not (equal filename (nth 1 x))))
11033 (cons (concat (car x) extra " ("
11034 (file-name-nondirectory (nth 1 x)) ")")
11035 (cdr x))
11036 (cons (concat (car x) extra) (cdr x))))
11037 org-refile-target-table))
11038 (completion-ignore-case t)
11039 cdef
11040 (prompt (concat prompt
11041 (or (and (car org-refile-history)
11042 (concat " (default " (car org-refile-history) ")"))
11043 (and (assoc cbnex tbl) (setq cdef cbnex)
11044 (concat " (default " cbnex ")"))) ": "))
11045 pa answ parent-target child parent old-hist)
11046 (setq old-hist org-refile-history)
11047 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11048 nil 'org-refile-history (or cdef (car org-refile-history))))
11049 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11050 (org-refile-check-position pa)
11051 (if pa
11052 (progn
11053 (when (or (not org-refile-history)
11054 (not (eq old-hist org-refile-history))
11055 (not (equal (car pa) (car org-refile-history))))
11056 (setq org-refile-history
11057 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11058 org-refile-history
11059 (cdr org-refile-history))))
11060 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11061 (pop org-refile-history)))
11063 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11064 (progn
11065 (setq parent (match-string 1 answ)
11066 child (match-string 2 answ))
11067 (setq parent-target (or (assoc parent tbl)
11068 (assoc (concat parent "/") tbl)))
11069 (when (and parent-target
11070 (or (eq new-nodes t)
11071 (and (eq new-nodes 'confirm)
11072 (y-or-n-p (format "Create new node \"%s\"? "
11073 child)))))
11074 (org-refile-new-child parent-target child)))
11075 (error "Invalid target location")))))
11077 (declare-function org-string-nw-p "org-macs" (s))
11078 (defun org-refile-check-position (refile-pointer)
11079 "Check if the refile pointer matches the headline to which it points."
11080 (let* ((file (nth 1 refile-pointer))
11081 (re (nth 2 refile-pointer))
11082 (pos (nth 3 refile-pointer))
11083 buffer)
11084 (if (and (not (markerp pos)) (not file))
11085 (error "Please save the buffer to a file before refiling")
11086 (when (org-string-nw-p re)
11087 (setq buffer (if (markerp pos)
11088 (marker-buffer pos)
11089 (or (find-buffer-visiting file)
11090 (find-file-noselect file))))
11091 (with-current-buffer buffer
11092 (save-excursion
11093 (save-restriction
11094 (widen)
11095 (goto-char pos)
11096 (beginning-of-line 1)
11097 (unless (org-looking-at-p re)
11098 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11100 (defun org-refile-new-child (parent-target child)
11101 "Use refile target PARENT-TARGET to add new CHILD below it."
11102 (unless parent-target
11103 (error "Cannot find parent for new node"))
11104 (let ((file (nth 1 parent-target))
11105 (pos (nth 3 parent-target))
11106 level)
11107 (with-current-buffer (or (find-buffer-visiting file)
11108 (find-file-noselect file))
11109 (save-excursion
11110 (save-restriction
11111 (widen)
11112 (if pos
11113 (goto-char pos)
11114 (goto-char (point-max))
11115 (if (not (bolp)) (newline)))
11116 (when (looking-at org-outline-regexp)
11117 (setq level (funcall outline-level))
11118 (org-end-of-subtree t t))
11119 (org-back-over-empty-lines)
11120 (insert "\n" (make-string
11121 (if pos (org-get-valid-level level 1) 1) ?*)
11122 " " child "\n")
11123 (beginning-of-line 0)
11124 (list (concat (car parent-target) "/" child) file "" (point)))))))
11126 (defun org-olpath-completing-read (prompt collection &rest args)
11127 "Read an outline path like a file name."
11128 (let ((thetable collection)
11129 (org-completion-use-ido nil) ; does not work with ido.
11130 (org-completion-use-iswitchb nil)) ; or iswitchb
11131 (apply
11132 'org-icompleting-read prompt
11133 (lambda (string predicate &optional flag)
11134 (let (rtn r f (l (length string)))
11135 (cond
11136 ((eq flag nil)
11137 ;; try completion
11138 (try-completion string thetable))
11139 ((eq flag t)
11140 ;; all-completions
11141 (setq rtn (all-completions string thetable predicate))
11142 (mapcar
11143 (lambda (x)
11144 (setq r (substring x l))
11145 (if (string-match " ([^)]*)$" x)
11146 (setq f (match-string 0 x))
11147 (setq f ""))
11148 (if (string-match "/" r)
11149 (concat string (substring r 0 (match-end 0)) f)
11151 rtn))
11152 ((eq flag 'lambda)
11153 ;; exact match?
11154 (assoc string thetable)))))
11155 args)))
11157 ;;;; Dynamic blocks
11159 (defun org-find-dblock (name)
11160 "Find the first dynamic block with name NAME in the buffer.
11161 If not found, stay at current position and return nil."
11162 (let ((case-fold-search t) pos)
11163 (save-excursion
11164 (goto-char (point-min))
11165 (setq pos (and (re-search-forward
11166 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11167 (match-beginning 0))))
11168 (if pos (goto-char pos))
11169 pos))
11171 (defconst org-dblock-start-re
11172 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11173 "Matches the start line of a dynamic block, with parameters.")
11175 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11176 "Matches the end of a dynamic block.")
11178 (defun org-create-dblock (plist)
11179 "Create a dynamic block section, with parameters taken from PLIST.
11180 PLIST must contain a :name entry which is used as name of the block."
11181 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11182 (end-of-line 1)
11183 (newline))
11184 (let ((col (current-column))
11185 (name (plist-get plist :name)))
11186 (insert "#+BEGIN: " name)
11187 (while plist
11188 (if (eq (car plist) :name)
11189 (setq plist (cddr plist))
11190 (insert " " (prin1-to-string (pop plist)))))
11191 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11192 (beginning-of-line -2)))
11194 (defun org-prepare-dblock ()
11195 "Prepare dynamic block for refresh.
11196 This empties the block, puts the cursor at the insert position and returns
11197 the property list including an extra property :name with the block name."
11198 (unless (looking-at org-dblock-start-re)
11199 (error "Not at a dynamic block"))
11200 (let* ((begdel (1+ (match-end 0)))
11201 (name (org-no-properties (match-string 1)))
11202 (params (append (list :name name)
11203 (read (concat "(" (match-string 3) ")")))))
11204 (save-excursion
11205 (beginning-of-line 1)
11206 (skip-chars-forward " \t")
11207 (setq params (plist-put params :indentation-column (current-column))))
11208 (unless (re-search-forward org-dblock-end-re nil t)
11209 (error "Dynamic block not terminated"))
11210 (setq params
11211 (append params
11212 (list :content (buffer-substring
11213 begdel (match-beginning 0)))))
11214 (delete-region begdel (match-beginning 0))
11215 (goto-char begdel)
11216 (open-line 1)
11217 params))
11219 (defun org-map-dblocks (&optional command)
11220 "Apply COMMAND to all dynamic blocks in the current buffer.
11221 If COMMAND is not given, use `org-update-dblock'."
11222 (let ((cmd (or command 'org-update-dblock)))
11223 (save-excursion
11224 (goto-char (point-min))
11225 (while (re-search-forward org-dblock-start-re nil t)
11226 (goto-char (match-beginning 0))
11227 (save-excursion
11228 (condition-case nil
11229 (funcall cmd)
11230 (error (message "Error during update of dynamic block"))))
11231 (unless (re-search-forward org-dblock-end-re nil t)
11232 (error "Dynamic block not terminated"))))))
11234 (defun org-dblock-update (&optional arg)
11235 "User command for updating dynamic blocks.
11236 Update the dynamic block at point. With prefix ARG, update all dynamic
11237 blocks in the buffer."
11238 (interactive "P")
11239 (if arg
11240 (org-update-all-dblocks)
11241 (or (looking-at org-dblock-start-re)
11242 (org-beginning-of-dblock))
11243 (org-update-dblock)))
11245 (defun org-update-dblock ()
11246 "Update the dynamic block at point.
11247 This means to empty the block, parse for parameters and then call
11248 the correct writing function."
11249 (interactive)
11250 (save-window-excursion
11251 (let* ((pos (point))
11252 (line (org-current-line))
11253 (params (org-prepare-dblock))
11254 (name (plist-get params :name))
11255 (indent (plist-get params :indentation-column))
11256 (cmd (intern (concat "org-dblock-write:" name))))
11257 (message "Updating dynamic block `%s' at line %d..." name line)
11258 (funcall cmd params)
11259 (message "Updating dynamic block `%s' at line %d...done" name line)
11260 (goto-char pos)
11261 (when (and indent (> indent 0))
11262 (setq indent (make-string indent ?\ ))
11263 (save-excursion
11264 (org-beginning-of-dblock)
11265 (forward-line 1)
11266 (while (not (looking-at org-dblock-end-re))
11267 (insert indent)
11268 (beginning-of-line 2))
11269 (when (looking-at org-dblock-end-re)
11270 (and (looking-at "[ \t]+")
11271 (replace-match ""))
11272 (insert indent)))))))
11274 (defun org-beginning-of-dblock ()
11275 "Find the beginning of the dynamic block at point.
11276 Error if there is no such block at point."
11277 (let ((pos (point))
11278 beg)
11279 (end-of-line 1)
11280 (if (and (re-search-backward org-dblock-start-re nil t)
11281 (setq beg (match-beginning 0))
11282 (re-search-forward org-dblock-end-re nil t)
11283 (> (match-end 0) pos))
11284 (goto-char beg)
11285 (goto-char pos)
11286 (error "Not in a dynamic block"))))
11288 (defun org-update-all-dblocks ()
11289 "Update all dynamic blocks in the buffer.
11290 This function can be used in a hook."
11291 (interactive)
11292 (when (derived-mode-p 'org-mode)
11293 (org-map-dblocks 'org-update-dblock)))
11296 ;;;; Completion
11298 (defconst org-additional-option-like-keywords
11299 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11300 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11301 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11302 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11303 "BEGIN:" "END:"
11304 "ORGTBL" "TBLFM:" "TBLNAME:"
11305 "BEGIN_EXAMPLE" "END_EXAMPLE"
11306 "BEGIN_VERBATIM" "END_VERBATIM"
11307 "BEGIN_QUOTE" "END_QUOTE"
11308 "BEGIN_VERSE" "END_VERSE"
11309 "BEGIN_CENTER" "END_CENTER"
11310 "BEGIN_SRC" "END_SRC"
11311 "BEGIN_RESULT" "END_RESULT"
11312 "BEGIN_lstlisting" "END_lstlisting"
11313 "NAME:" "RESULTS:"
11314 "HEADER:" "HEADERS:"
11315 "COLUMNS:" "PROPERTY:"
11316 "CAPTION:" "LABEL:"
11317 "SETUPFILE:"
11318 "INCLUDE:" "INDEX:"
11319 "BIND:"
11320 "MACRO:"))
11322 (defconst org-options-keywords
11323 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11324 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11325 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11326 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11327 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11328 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11329 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11331 (defconst org-additional-option-like-keywords-for-flyspell
11332 (delete-dups
11333 (split-string
11334 (mapconcat (lambda(k)
11335 (replace-regexp-in-string
11336 "_\\|:" " "
11337 (concat k " " (downcase k) " " (upcase k))))
11338 (append org-options-keywords org-additional-option-like-keywords)
11339 " ")
11340 " +" t)))
11342 (defcustom org-structure-template-alist
11344 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11345 "<src lang=\"?\">\n\n</src>")
11346 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11347 "<example>\n?\n</example>")
11348 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11349 "<quote>\n?\n</quote>")
11350 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11351 "<verse>\n?\n</verse>")
11352 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11353 "<center>\n?\n</center>")
11354 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11355 "<literal style=\"latex\">\n?\n</literal>")
11356 ("L" "#+LaTeX: "
11357 "<literal style=\"latex\">?</literal>")
11358 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11359 "<literal style=\"html\">\n?\n</literal>")
11360 ("H" "#+HTML: "
11361 "<literal style=\"html\">?</literal>")
11362 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11363 ("A" "#+ASCII: ")
11364 ("i" "#+INDEX: ?"
11365 "#+INDEX: ?")
11366 ("I" "#+INCLUDE: %file ?"
11367 "<include file=%file markup=\"?\">")
11369 "Structure completion elements.
11370 This is a list of abbreviation keys and values. The value gets inserted
11371 if you type `<' followed by the key and then press the completion key,
11372 usually `M-TAB'. %file will be replaced by a file name after prompting
11373 for the file using completion. The cursor will be placed at the position
11374 of the `?` in the template.
11375 There are two templates for each key, the first uses the original Org syntax,
11376 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11377 the default when the /org-mtags.el/ module has been loaded. See also the
11378 variable `org-mtags-prefer-muse-templates'."
11379 :group 'org-completion
11380 :type '(repeat
11381 (string :tag "Key")
11382 (string :tag "Template")
11383 (string :tag "Muse Template")))
11385 (defun org-try-structure-completion ()
11386 "Try to complete a structure template before point.
11387 This looks for strings like \"<e\" on an otherwise empty line and
11388 expands them."
11389 (let ((l (buffer-substring (point-at-bol) (point)))
11391 (when (and (looking-at "[ \t]*$")
11392 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11393 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11394 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11395 (match-beginning 1)) a)
11396 t)))
11398 (defun org-complete-expand-structure-template (start cell)
11399 "Expand a structure template."
11400 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11401 (rpl (nth (if musep 2 1) cell))
11402 (ind ""))
11403 (delete-region start (point))
11404 (when (string-match "\\`#\\+" rpl)
11405 (cond
11406 ((bolp))
11407 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11408 (setq ind (buffer-substring (point-at-bol) (point))))
11409 (t (newline))))
11410 (setq start (point))
11411 (if (string-match "%file" rpl)
11412 (setq rpl (replace-match
11413 (concat
11414 "\""
11415 (save-match-data
11416 (abbreviate-file-name (read-file-name "Include file: ")))
11417 "\"")
11418 t t rpl)))
11419 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11420 (concat "\n" ind)))
11421 (insert rpl)
11422 (if (re-search-backward "\\?" start t) (delete-char 1))))
11424 ;;;; TODO, DEADLINE, Comments
11426 (defun org-toggle-comment ()
11427 "Change the COMMENT state of an entry."
11428 (interactive)
11429 (save-excursion
11430 (org-back-to-heading)
11431 (let (case-fold-search)
11432 (cond
11433 ((looking-at (format org-heading-keyword-regexp-format
11434 org-comment-string))
11435 (goto-char (match-end 1))
11436 (looking-at (concat " +" org-comment-string))
11437 (replace-match "" t t)
11438 (when (eolp) (insert " ")))
11439 ((looking-at org-outline-regexp)
11440 (goto-char (match-end 0))
11441 (insert org-comment-string " "))))))
11443 (defvar org-last-todo-state-is-todo nil
11444 "This is non-nil when the last TODO state change led to a TODO state.
11445 If the last change removed the TODO tag or switched to DONE, then
11446 this is nil.")
11448 (defvar org-setting-tags nil) ; dynamically skipped
11450 (defvar org-todo-setup-filter-hook nil
11451 "Hook for functions that pre-filter todo specs.
11452 Each function takes a todo spec and returns either nil or the spec
11453 transformed into canonical form." )
11455 (defvar org-todo-get-default-hook nil
11456 "Hook for functions that get a default item for todo.
11457 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11458 nil or a string to be used for the todo mark." )
11460 (defvar org-agenda-headline-snapshot-before-repeat)
11462 (defun org-current-effective-time ()
11463 "Return current time adjusted for `org-extend-today-until' variable."
11464 (let* ((ct (org-current-time))
11465 (dct (decode-time ct))
11466 (ct1
11467 (cond
11468 (org-use-last-clock-out-time-as-effective-time
11469 (or (org-clock-get-last-clock-out-time) ct))
11470 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11471 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11472 (t ct))))
11473 ct1))
11475 (defun org-todo-yesterday (&optional arg)
11476 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11477 (interactive "P")
11478 (if (eq major-mode 'org-agenda-mode)
11479 (apply 'org-agenda-todo-yesterday arg)
11480 (let* ((hour (third (decode-time
11481 (org-current-time))))
11482 (org-extend-today-until (1+ hour)))
11483 (org-todo arg))))
11485 (defun org-todo (&optional arg)
11486 "Change the TODO state of an item.
11487 The state of an item is given by a keyword at the start of the heading,
11488 like
11489 *** TODO Write paper
11490 *** DONE Call mom
11492 The different keywords are specified in the variable `org-todo-keywords'.
11493 By default the available states are \"TODO\" and \"DONE\".
11494 So for this example: when the item starts with TODO, it is changed to DONE.
11495 When it starts with DONE, the DONE is removed. And when neither TODO nor
11496 DONE are present, add TODO at the beginning of the heading.
11498 With \\[universal-argument] prefix arg, use completion to determine the new \
11499 state.
11500 With numeric prefix arg, switch to that state.
11501 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11502 keywords (nextset).
11503 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11504 With a numeric prefix arg of 0, inhibit note taking for the change.
11506 For calling through lisp, arg is also interpreted in the following way:
11507 'none -> empty state
11508 \"\"(empty string) -> switch to empty state
11509 'done -> switch to DONE
11510 'nextset -> switch to the next set of keywords
11511 'previousset -> switch to the previous set of keywords
11512 \"WAITING\" -> switch to the specified keyword, but only if it
11513 really is a member of `org-todo-keywords'."
11514 (interactive "P")
11515 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11516 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11517 'region-start-level 'region))
11518 org-loop-over-headlines-in-active-region)
11519 (org-map-entries
11520 `(org-todo ,arg)
11521 org-loop-over-headlines-in-active-region
11522 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11523 (if (equal arg '(16)) (setq arg 'nextset))
11524 (let ((org-blocker-hook org-blocker-hook)
11525 (case-fold-search nil))
11526 (when (equal arg '(64))
11527 (setq arg nil org-blocker-hook nil))
11528 (when (and org-blocker-hook
11529 (or org-inhibit-blocking
11530 (org-entry-get nil "NOBLOCKING")))
11531 (setq org-blocker-hook nil))
11532 (save-excursion
11533 (catch 'exit
11534 (org-back-to-heading t)
11535 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11536 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11537 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11538 (let* ((match-data (match-data))
11539 (startpos (point-at-bol))
11540 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11541 (org-log-done org-log-done)
11542 (org-log-repeat org-log-repeat)
11543 (org-todo-log-states org-todo-log-states)
11544 (org-inhibit-logging
11545 (if (equal arg 0)
11546 (progn (setq arg nil) 'note) org-inhibit-logging))
11547 (this (match-string 1))
11548 (hl-pos (match-beginning 0))
11549 (head (org-get-todo-sequence-head this))
11550 (ass (assoc head org-todo-kwd-alist))
11551 (interpret (nth 1 ass))
11552 (done-word (nth 3 ass))
11553 (final-done-word (nth 4 ass))
11554 (org-last-state (or this ""))
11555 (completion-ignore-case t)
11556 (member (member this org-todo-keywords-1))
11557 (tail (cdr member))
11558 (org-state (cond
11559 ((and org-todo-key-trigger
11560 (or (and (equal arg '(4))
11561 (eq org-use-fast-todo-selection 'prefix))
11562 (and (not arg) org-use-fast-todo-selection
11563 (not (eq org-use-fast-todo-selection
11564 'prefix)))))
11565 ;; Use fast selection
11566 (org-fast-todo-selection))
11567 ((and (equal arg '(4))
11568 (or (not org-use-fast-todo-selection)
11569 (not org-todo-key-trigger)))
11570 ;; Read a state with completion
11571 (org-icompleting-read
11572 "State: " (mapcar (lambda(x) (list x))
11573 org-todo-keywords-1)
11574 nil t))
11575 ((eq arg 'right)
11576 (if this
11577 (if tail (car tail) nil)
11578 (car org-todo-keywords-1)))
11579 ((eq arg 'left)
11580 (if (equal member org-todo-keywords-1)
11582 (if this
11583 (nth (- (length org-todo-keywords-1)
11584 (length tail) 2)
11585 org-todo-keywords-1)
11586 (org-last org-todo-keywords-1))))
11587 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11588 (setq arg nil))) ; hack to fall back to cycling
11589 (arg
11590 ;; user or caller requests a specific state
11591 (cond
11592 ((equal arg "") nil)
11593 ((eq arg 'none) nil)
11594 ((eq arg 'done) (or done-word (car org-done-keywords)))
11595 ((eq arg 'nextset)
11596 (or (car (cdr (member head org-todo-heads)))
11597 (car org-todo-heads)))
11598 ((eq arg 'previousset)
11599 (let ((org-todo-heads (reverse org-todo-heads)))
11600 (or (car (cdr (member head org-todo-heads)))
11601 (car org-todo-heads))))
11602 ((car (member arg org-todo-keywords-1)))
11603 ((stringp arg)
11604 (error "State `%s' not valid in this file" arg))
11605 ((nth (1- (prefix-numeric-value arg))
11606 org-todo-keywords-1))))
11607 ((null member) (or head (car org-todo-keywords-1)))
11608 ((equal this final-done-word) nil) ;; -> make empty
11609 ((null tail) nil) ;; -> first entry
11610 ((memq interpret '(type priority))
11611 (if (eq this-command last-command)
11612 (car tail)
11613 (if (> (length tail) 0)
11614 (or done-word (car org-done-keywords))
11615 nil)))
11617 (car tail))))
11618 (org-state (or
11619 (run-hook-with-args-until-success
11620 'org-todo-get-default-hook org-state org-last-state)
11621 org-state))
11622 (next (if org-state (concat " " org-state " ") " "))
11623 (change-plist (list :type 'todo-state-change :from this :to org-state
11624 :position startpos))
11625 dolog now-done-p)
11626 (when org-blocker-hook
11627 (setq org-last-todo-state-is-todo
11628 (not (member this org-done-keywords)))
11629 (unless (save-excursion
11630 (save-match-data
11631 (org-with-wide-buffer
11632 (run-hook-with-args-until-failure
11633 'org-blocker-hook change-plist))))
11634 (if (org-called-interactively-p 'interactive)
11635 (error "TODO state change from %s to %s blocked" this org-state)
11636 ;; fail silently
11637 (message "TODO state change from %s to %s blocked" this org-state)
11638 (throw 'exit nil))))
11639 (store-match-data match-data)
11640 (replace-match next t t)
11641 (unless (pos-visible-in-window-p hl-pos)
11642 (message "TODO state changed to %s" (org-trim next)))
11643 (unless head
11644 (setq head (org-get-todo-sequence-head org-state)
11645 ass (assoc head org-todo-kwd-alist)
11646 interpret (nth 1 ass)
11647 done-word (nth 3 ass)
11648 final-done-word (nth 4 ass)))
11649 (when (memq arg '(nextset previousset))
11650 (message "Keyword-Set %d/%d: %s"
11651 (- (length org-todo-sets) -1
11652 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11653 (length org-todo-sets)
11654 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11655 (setq org-last-todo-state-is-todo
11656 (not (member org-state org-done-keywords)))
11657 (setq now-done-p (and (member org-state org-done-keywords)
11658 (not (member this org-done-keywords))))
11659 (and logging (org-local-logging logging))
11660 (when (and (or org-todo-log-states org-log-done)
11661 (not (eq org-inhibit-logging t))
11662 (not (memq arg '(nextset previousset))))
11663 ;; we need to look at recording a time and note
11664 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11665 (nth 2 (assoc this org-todo-log-states))))
11666 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11667 (setq dolog 'time))
11668 (when (and org-state
11669 (member org-state org-not-done-keywords)
11670 (not (member this org-not-done-keywords)))
11671 ;; This is now a todo state and was not one before
11672 ;; If there was a CLOSED time stamp, get rid of it.
11673 (org-add-planning-info nil nil 'closed))
11674 (when (and now-done-p org-log-done)
11675 ;; It is now done, and it was not done before
11676 (org-add-planning-info 'closed (org-current-effective-time))
11677 (if (and (not dolog) (eq 'note org-log-done))
11678 (org-add-log-setup 'done org-state this 'findpos 'note)))
11679 (when (and org-state dolog)
11680 ;; This is a non-nil state, and we need to log it
11681 (org-add-log-setup 'state org-state this 'findpos dolog)))
11682 ;; Fixup tag positioning
11683 (org-todo-trigger-tag-changes org-state)
11684 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11685 (when org-provide-todo-statistics
11686 (org-update-parent-todo-statistics))
11687 (run-hooks 'org-after-todo-state-change-hook)
11688 (if (and arg (not (member org-state org-done-keywords)))
11689 (setq head (org-get-todo-sequence-head org-state)))
11690 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11691 ;; Do we need to trigger a repeat?
11692 (when now-done-p
11693 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11694 ;; This is for the agenda, take a snapshot of the headline.
11695 (save-match-data
11696 (setq org-agenda-headline-snapshot-before-repeat
11697 (org-get-heading))))
11698 (org-auto-repeat-maybe org-state))
11699 ;; Fixup cursor location if close to the keyword
11700 (if (and (outline-on-heading-p)
11701 (not (bolp))
11702 (save-excursion (beginning-of-line 1)
11703 (looking-at org-todo-line-regexp))
11704 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11705 (progn
11706 (goto-char (or (match-end 2) (match-end 1)))
11707 (and (looking-at " ") (just-one-space))))
11708 (when org-trigger-hook
11709 (save-excursion
11710 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11712 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11713 "Block turning an entry into a TODO, using the hierarchy.
11714 This checks whether the current task should be blocked from state
11715 changes. Such blocking occurs when:
11717 1. The task has children which are not all in a completed state.
11719 2. A task has a parent with the property :ORDERED:, and there
11720 are siblings prior to the current task with incomplete
11721 status.
11723 3. The parent of the task is blocked because it has siblings that should
11724 be done first, or is child of a block grandparent TODO entry."
11726 (if (not org-enforce-todo-dependencies)
11727 t ; if locally turned off don't block
11728 (catch 'dont-block
11729 ;; If this is not a todo state change, or if this entry is already DONE,
11730 ;; do not block
11731 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11732 (member (plist-get change-plist :from)
11733 (cons 'done org-done-keywords))
11734 (member (plist-get change-plist :to)
11735 (cons 'todo org-not-done-keywords))
11736 (not (plist-get change-plist :to)))
11737 (throw 'dont-block t))
11738 ;; If this task has children, and any are undone, it's blocked
11739 (save-excursion
11740 (org-back-to-heading t)
11741 (let ((this-level (funcall outline-level)))
11742 (outline-next-heading)
11743 (let ((child-level (funcall outline-level)))
11744 (while (and (not (eobp))
11745 (> child-level this-level))
11746 ;; this todo has children, check whether they are all
11747 ;; completed
11748 (if (and (not (org-entry-is-done-p))
11749 (org-entry-is-todo-p))
11750 (throw 'dont-block nil))
11751 (outline-next-heading)
11752 (setq child-level (funcall outline-level))))))
11753 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11754 ;; any previous siblings are undone, it's blocked
11755 (save-excursion
11756 (org-back-to-heading t)
11757 (let* ((pos (point))
11758 (parent-pos (and (org-up-heading-safe) (point))))
11759 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11760 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11761 (forward-line 1)
11762 (re-search-forward org-not-done-heading-regexp pos t))
11763 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11764 ;; Search further up the hierarchy, to see if an ancestor is blocked
11765 (while t
11766 (goto-char parent-pos)
11767 (if (not (looking-at org-not-done-heading-regexp))
11768 (throw 'dont-block t)) ; do not block, parent is not a TODO
11769 (setq pos (point))
11770 (setq parent-pos (and (org-up-heading-safe) (point)))
11771 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11772 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11773 (forward-line 1)
11774 (re-search-forward org-not-done-heading-regexp pos t))
11775 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11777 (defcustom org-track-ordered-property-with-tag nil
11778 "Should the ORDERED property also be shown as a tag?
11779 The ORDERED property decides if an entry should require subtasks to be
11780 completed in sequence. Since a property is not very visible, setting
11781 this option means that toggling the ORDERED property with the command
11782 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11783 not relevant for the behavior, but it makes things more visible.
11785 Note that toggling the tag with tags commands will not change the property
11786 and therefore not influence behavior!
11788 This can be t, meaning the tag ORDERED should be used, It can also be a
11789 string to select a different tag for this task."
11790 :group 'org-todo
11791 :type '(choice
11792 (const :tag "No tracking" nil)
11793 (const :tag "Track with ORDERED tag" t)
11794 (string :tag "Use other tag")))
11796 (defun org-toggle-ordered-property ()
11797 "Toggle the ORDERED property of the current entry.
11798 For better visibility, you can track the value of this property with a tag.
11799 See variable `org-track-ordered-property-with-tag'."
11800 (interactive)
11801 (let* ((t1 org-track-ordered-property-with-tag)
11802 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11803 (save-excursion
11804 (org-back-to-heading)
11805 (if (org-entry-get nil "ORDERED")
11806 (progn
11807 (org-delete-property "ORDERED")
11808 (and tag (org-toggle-tag tag 'off))
11809 (message "Subtasks can be completed in arbitrary order"))
11810 (org-entry-put nil "ORDERED" "t")
11811 (and tag (org-toggle-tag tag 'on))
11812 (message "Subtasks must be completed in sequence")))))
11814 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11815 (defun org-block-todo-from-checkboxes (change-plist)
11816 "Block turning an entry into a TODO, using checkboxes.
11817 This checks whether the current task should be blocked from state
11818 changes because there are unchecked boxes in this entry."
11819 (if (not org-enforce-todo-checkbox-dependencies)
11820 t ; if locally turned off don't block
11821 (catch 'dont-block
11822 ;; If this is not a todo state change, or if this entry is already DONE,
11823 ;; do not block
11824 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11825 (member (plist-get change-plist :from)
11826 (cons 'done org-done-keywords))
11827 (member (plist-get change-plist :to)
11828 (cons 'todo org-not-done-keywords))
11829 (not (plist-get change-plist :to)))
11830 (throw 'dont-block t))
11831 ;; If this task has checkboxes that are not checked, it's blocked
11832 (save-excursion
11833 (org-back-to-heading t)
11834 (let ((beg (point)) end)
11835 (outline-next-heading)
11836 (setq end (point))
11837 (goto-char beg)
11838 (if (org-list-search-forward
11839 (concat (org-item-beginning-re)
11840 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11841 "\\[[- ]\\]")
11842 end t)
11843 (progn
11844 (if (boundp 'org-blocked-by-checkboxes)
11845 (setq org-blocked-by-checkboxes t))
11846 (throw 'dont-block nil)))))
11847 t))) ; do not block
11849 (defun org-entry-blocked-p ()
11850 "Is the current entry blocked?"
11851 (if (org-entry-get nil "NOBLOCKING")
11852 nil ;; Never block this entry
11853 (not
11854 (run-hook-with-args-until-failure
11855 'org-blocker-hook
11856 (list :type 'todo-state-change
11857 :position (point)
11858 :from 'todo
11859 :to 'done)))))
11861 (defun org-update-statistics-cookies (all)
11862 "Update the statistics cookie, either from TODO or from checkboxes.
11863 This should be called with the cursor in a line with a statistics cookie."
11864 (interactive "P")
11865 (if all
11866 (progn
11867 (org-update-checkbox-count 'all)
11868 (org-map-entries 'org-update-parent-todo-statistics))
11869 (if (not (org-at-heading-p))
11870 (org-update-checkbox-count)
11871 (let ((pos (move-marker (make-marker) (point)))
11872 end l1 l2)
11873 (ignore-errors (org-back-to-heading t))
11874 (if (not (org-at-heading-p))
11875 (org-update-checkbox-count)
11876 (setq l1 (org-outline-level))
11877 (setq end (save-excursion
11878 (outline-next-heading)
11879 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11880 (point)))
11881 (if (and (save-excursion
11882 (re-search-forward
11883 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11884 (not (save-excursion (re-search-forward
11885 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11886 (org-update-checkbox-count)
11887 (if (and l2 (> l2 l1))
11888 (progn
11889 (goto-char end)
11890 (org-update-parent-todo-statistics))
11891 (goto-char pos)
11892 (beginning-of-line 1)
11893 (while (re-search-forward
11894 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11895 (point-at-eol) t)
11896 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11897 (goto-char pos)
11898 (move-marker pos nil)))))
11900 (defvar org-entry-property-inherited-from) ;; defined below
11901 (defun org-update-parent-todo-statistics ()
11902 "Update any statistics cookie in the parent of the current headline.
11903 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11904 the entire subtree and this will travel up the hierarchy and update
11905 statistics everywhere."
11906 (let* ((prop (save-excursion (org-up-heading-safe)
11907 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11908 (recursive (or (not org-hierarchical-todo-statistics)
11909 (and prop (string-match "\\<recursive\\>" prop))))
11910 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11912 (first t)
11913 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11914 level ltoggle l1 new ndel
11915 (cnt-all 0) (cnt-done 0) is-percent kwd
11916 checkbox-beg ov ovs ove cookie-present)
11917 (catch 'exit
11918 (save-excursion
11919 (beginning-of-line 1)
11920 (setq ltoggle (funcall outline-level))
11921 ;; Three situations are to consider:
11923 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11924 ;; to the top-level ancestor on the headline;
11926 ;; 2. If parent has "recursive" property, repeat up to the
11927 ;; headline setting that property, taking inheritance into
11928 ;; account;
11930 ;; 3. Else, move up to direct parent and proceed only once.
11931 (while (and (setq level (org-up-heading-safe))
11932 (or recursive first)
11933 (>= (point) lim))
11934 (setq first nil cookie-present nil)
11935 (unless (and level
11936 (not (string-match
11937 "\\<checkbox\\>"
11938 (downcase (or (org-entry-get nil "COOKIE_DATA")
11939 "")))))
11940 (throw 'exit nil))
11941 (while (re-search-forward box-re (point-at-eol) t)
11942 (setq cnt-all 0 cnt-done 0 cookie-present t)
11943 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11944 (save-match-data
11945 (unless (outline-next-heading) (throw 'exit nil))
11946 (while (and (looking-at org-complex-heading-regexp)
11947 (> (setq l1 (length (match-string 1))) level))
11948 (setq kwd (and (or recursive (= l1 ltoggle))
11949 (match-string 2)))
11950 (if (or (eq org-provide-todo-statistics 'all-headlines)
11951 (and (listp org-provide-todo-statistics)
11952 (or (member kwd org-provide-todo-statistics)
11953 (member kwd org-done-keywords))))
11954 (setq cnt-all (1+ cnt-all))
11955 (if (eq org-provide-todo-statistics t)
11956 (and kwd (setq cnt-all (1+ cnt-all)))))
11957 (and (member kwd org-done-keywords)
11958 (setq cnt-done (1+ cnt-done)))
11959 (outline-next-heading)))
11960 (setq new
11961 (if is-percent
11962 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11963 (format "[%d/%d]" cnt-done cnt-all))
11964 ndel (- (match-end 0) checkbox-beg))
11965 ;; handle overlays when updating cookie from column view
11966 (when (setq ov (car (overlays-at checkbox-beg)))
11967 (setq ovs (overlay-start ov) ove (overlay-end ov))
11968 (delete-overlay ov))
11969 (goto-char checkbox-beg)
11970 (insert new)
11971 (delete-region (point) (+ (point) ndel))
11972 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11973 (when ov (move-overlay ov ovs ove)))
11974 (when cookie-present
11975 (run-hook-with-args 'org-after-todo-statistics-hook
11976 cnt-done (- cnt-all cnt-done))))))
11977 (run-hooks 'org-todo-statistics-hook)))
11979 (defvar org-after-todo-statistics-hook nil
11980 "Hook that is called after a TODO statistics cookie has been updated.
11981 Each function is called with two arguments: the number of not-done entries
11982 and the number of done entries.
11984 For example, the following function, when added to this hook, will switch
11985 an entry to DONE when all children are done, and back to TODO when new
11986 entries are set to a TODO status. Note that this hook is only called
11987 when there is a statistics cookie in the headline!
11989 (defun org-summary-todo (n-done n-not-done)
11990 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11991 (let (org-log-done org-log-states) ; turn off logging
11992 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11995 (defvar org-todo-statistics-hook nil
11996 "Hook that is run whenever Org thinks TODO statistics should be updated.
11997 This hook runs even if there is no statistics cookie present, in which case
11998 `org-after-todo-statistics-hook' would not run.")
12000 (defun org-todo-trigger-tag-changes (state)
12001 "Apply the changes defined in `org-todo-state-tags-triggers'."
12002 (let ((l org-todo-state-tags-triggers)
12003 changes)
12004 (when (or (not state) (equal state ""))
12005 (setq changes (append changes (cdr (assoc "" l)))))
12006 (when (and (stringp state) (> (length state) 0))
12007 (setq changes (append changes (cdr (assoc state l)))))
12008 (when (member state org-not-done-keywords)
12009 (setq changes (append changes (cdr (assoc 'todo l)))))
12010 (when (member state org-done-keywords)
12011 (setq changes (append changes (cdr (assoc 'done l)))))
12012 (dolist (c changes)
12013 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12015 (defun org-local-logging (value)
12016 "Get logging settings from a property VALUE."
12017 (let* (words w a)
12018 ;; directly set the variables, they are already local.
12019 (setq org-log-done nil
12020 org-log-repeat nil
12021 org-todo-log-states nil)
12022 (setq words (org-split-string value))
12023 (while (setq w (pop words))
12024 (cond
12025 ((setq a (assoc w org-startup-options))
12026 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12027 (set (nth 1 a) (nth 2 a))))
12028 ((setq a (org-extract-log-state-settings w))
12029 (and (member (car a) org-todo-keywords-1)
12030 (push a org-todo-log-states)))))))
12032 (defun org-get-todo-sequence-head (kwd)
12033 "Return the head of the TODO sequence to which KWD belongs.
12034 If KWD is not set, check if there is a text property remembering the
12035 right sequence."
12036 (let (p)
12037 (cond
12038 ((not kwd)
12039 (or (get-text-property (point-at-bol) 'org-todo-head)
12040 (progn
12041 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12042 nil (point-at-eol)))
12043 (get-text-property p 'org-todo-head))))
12044 ((not (member kwd org-todo-keywords-1))
12045 (car org-todo-keywords-1))
12046 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12048 (defun org-fast-todo-selection ()
12049 "Fast TODO keyword selection with single keys.
12050 Returns the new TODO keyword, or nil if no state change should occur."
12051 (let* ((fulltable org-todo-key-alist)
12052 (done-keywords org-done-keywords) ;; needed for the faces.
12053 (maxlen (apply 'max (mapcar
12054 (lambda (x)
12055 (if (stringp (car x)) (string-width (car x)) 0))
12056 fulltable)))
12057 (expert nil)
12058 (fwidth (+ maxlen 3 1 3))
12059 (ncol (/ (- (window-width) 4) fwidth))
12060 tg cnt e c tbl
12061 groups ingroup)
12062 (save-excursion
12063 (save-window-excursion
12064 (if expert
12065 (set-buffer (get-buffer-create " *Org todo*"))
12066 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12067 (erase-buffer)
12068 (org-set-local 'org-done-keywords done-keywords)
12069 (setq tbl fulltable cnt 0)
12070 (while (setq e (pop tbl))
12071 (cond
12072 ((equal e '(:startgroup))
12073 (push '() groups) (setq ingroup t)
12074 (when (not (= cnt 0))
12075 (setq cnt 0)
12076 (insert "\n"))
12077 (insert "{ "))
12078 ((equal e '(:endgroup))
12079 (setq ingroup nil cnt 0)
12080 (insert "}\n"))
12081 ((equal e '(:newline))
12082 (when (not (= cnt 0))
12083 (setq cnt 0)
12084 (insert "\n")
12085 (setq e (car tbl))
12086 (while (equal (car tbl) '(:newline))
12087 (insert "\n")
12088 (setq tbl (cdr tbl)))))
12090 (setq tg (car e) c (cdr e))
12091 (if ingroup (push tg (car groups)))
12092 (setq tg (org-add-props tg nil 'face
12093 (org-get-todo-face tg)))
12094 (if (and (= cnt 0) (not ingroup)) (insert " "))
12095 (insert "[" c "] " tg (make-string
12096 (- fwidth 4 (length tg)) ?\ ))
12097 (when (= (setq cnt (1+ cnt)) ncol)
12098 (insert "\n")
12099 (if ingroup (insert " "))
12100 (setq cnt 0)))))
12101 (insert "\n")
12102 (goto-char (point-min))
12103 (if (not expert) (org-fit-window-to-buffer))
12104 (message "[a-z..]:Set [SPC]:clear")
12105 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12106 (cond
12107 ((or (= c ?\C-g)
12108 (and (= c ?q) (not (rassoc c fulltable))))
12109 (setq quit-flag t))
12110 ((= c ?\ ) nil)
12111 ((setq e (rassoc c fulltable) tg (car e))
12113 (t (setq quit-flag t)))))))
12115 (defun org-entry-is-todo-p ()
12116 (member (org-get-todo-state) org-not-done-keywords))
12118 (defun org-entry-is-done-p ()
12119 (member (org-get-todo-state) org-done-keywords))
12121 (defun org-get-todo-state ()
12122 (save-excursion
12123 (org-back-to-heading t)
12124 (and (looking-at org-todo-line-regexp)
12125 (match-end 2)
12126 (match-string 2))))
12128 (defun org-at-date-range-p (&optional inactive-ok)
12129 "Is the cursor inside a date range?"
12130 (interactive)
12131 (save-excursion
12132 (catch 'exit
12133 (let ((pos (point)))
12134 (skip-chars-backward "^[<\r\n")
12135 (skip-chars-backward "<[")
12136 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12137 (>= (match-end 0) pos)
12138 (throw 'exit t))
12139 (skip-chars-backward "^<[\r\n")
12140 (skip-chars-backward "<[")
12141 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12142 (>= (match-end 0) pos)
12143 (throw 'exit t)))
12144 nil)))
12146 (defun org-get-repeat (&optional tagline)
12147 "Check if there is a deadline/schedule with repeater in this entry."
12148 (save-match-data
12149 (save-excursion
12150 (org-back-to-heading t)
12151 (and (re-search-forward (if tagline
12152 (concat tagline "\\s-*" org-repeat-re)
12153 org-repeat-re)
12154 (org-entry-end-position) t)
12155 (match-string-no-properties 1)))))
12157 (defvar org-last-changed-timestamp)
12158 (defvar org-last-inserted-timestamp)
12159 (defvar org-log-post-message)
12160 (defvar org-log-note-purpose)
12161 (defvar org-log-note-how)
12162 (defvar org-log-note-extra)
12163 (defun org-auto-repeat-maybe (done-word)
12164 "Check if the current headline contains a repeated deadline/schedule.
12165 If yes, set TODO state back to what it was and change the base date
12166 of repeating deadline/scheduled time stamps to new date.
12167 This function is run automatically after each state change to a DONE state."
12168 ;; last-state is dynamically scoped into this function
12169 (let* ((repeat (org-get-repeat))
12170 (aa (assoc org-last-state org-todo-kwd-alist))
12171 (interpret (nth 1 aa))
12172 (head (nth 2 aa))
12173 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12174 (msg "Entry repeats: ")
12175 (org-log-done nil)
12176 (org-todo-log-states nil)
12177 re type n what ts time to-state)
12178 (when repeat
12179 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12180 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12181 org-todo-repeat-to-state))
12182 (unless (and to-state (member to-state org-todo-keywords-1))
12183 (setq to-state (if (eq interpret 'type) org-last-state head)))
12184 (org-todo to-state)
12185 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12186 (org-entry-put nil "LAST_REPEAT" (format-time-string
12187 (org-time-stamp-format t t))))
12188 (when org-log-repeat
12189 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12190 (memq 'org-add-log-note post-command-hook))
12191 ;; OK, we are already setup for some record
12192 (if (eq org-log-repeat 'note)
12193 ;; make sure we take a note, not only a time stamp
12194 (setq org-log-note-how 'note))
12195 ;; Set up for taking a record
12196 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12197 org-last-state
12198 'findpos org-log-repeat)))
12199 (org-back-to-heading t)
12200 (org-add-planning-info nil nil 'closed)
12201 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12202 org-deadline-time-regexp "\\)\\|\\("
12203 org-ts-regexp "\\)"))
12204 (while (re-search-forward
12205 re (save-excursion (outline-next-heading) (point)) t)
12206 (setq type (if (match-end 1) org-scheduled-string
12207 (if (match-end 3) org-deadline-string "Plain:"))
12208 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12209 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12210 (setq n (string-to-number (match-string 2 ts))
12211 what (match-string 3 ts))
12212 (if (equal what "w") (setq n (* n 7) what "d"))
12213 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12214 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12215 ;; Preparation, see if we need to modify the start date for the change
12216 (when (match-end 1)
12217 (setq time (save-match-data (org-time-string-to-time ts)))
12218 (cond
12219 ((equal (match-string 1 ts) ".")
12220 ;; Shift starting date to today
12221 (org-timestamp-change
12222 (- (org-today) (time-to-days time))
12223 'day))
12224 ((equal (match-string 1 ts) "+")
12225 (let ((nshiftmax 10) (nshift 0))
12226 (while (or (= nshift 0)
12227 (<= (time-to-days time)
12228 (time-to-days (current-time))))
12229 (when (= (incf nshift) nshiftmax)
12230 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12231 (error "Abort")))
12232 (org-timestamp-change n (cdr (assoc what whata)))
12233 (org-at-timestamp-p t)
12234 (setq ts (match-string 1))
12235 (setq time (save-match-data (org-time-string-to-time ts)))))
12236 (org-timestamp-change (- n) (cdr (assoc what whata)))
12237 ;; rematch, so that we have everything in place for the real shift
12238 (org-at-timestamp-p t)
12239 (setq ts (match-string 1))
12240 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12241 (org-timestamp-change n (cdr (assoc what whata)))
12242 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12243 (setq org-log-post-message msg)
12244 (message "%s" msg))))
12246 (defun org-show-todo-tree (arg)
12247 "Make a compact tree which shows all headlines marked with TODO.
12248 The tree will show the lines where the regexp matches, and all higher
12249 headlines above the match.
12250 With a \\[universal-argument] prefix, prompt for a regexp to match.
12251 With a numeric prefix N, construct a sparse tree for the Nth element
12252 of `org-todo-keywords-1'."
12253 (interactive "P")
12254 (let ((case-fold-search nil)
12255 (kwd-re
12256 (cond ((null arg) org-not-done-regexp)
12257 ((equal arg '(4))
12258 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12259 (mapcar 'list org-todo-keywords-1))))
12260 (concat "\\("
12261 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12262 "\\)\\>")))
12263 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12264 (regexp-quote (nth (1- (prefix-numeric-value arg))
12265 org-todo-keywords-1)))
12266 (t (error "Invalid prefix argument: %s" arg)))))
12267 (message "%d TODO entries found"
12268 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12270 (defun org-deadline (&optional remove time)
12271 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12272 With argument REMOVE, remove any deadline from the item.
12273 With argument TIME, set the deadline at the corresponding date. TIME
12274 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12275 (interactive "P")
12276 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12277 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12278 'region-start-level 'region))
12279 org-loop-over-headlines-in-active-region)
12280 (org-map-entries
12281 `(org-deadline ',remove ,time)
12282 org-loop-over-headlines-in-active-region
12283 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12284 (let* ((old-date (org-entry-get nil "DEADLINE"))
12285 (repeater (and old-date
12286 (string-match
12287 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12288 old-date)
12289 (match-string 1 old-date))))
12290 (if remove
12291 (progn
12292 (when (and old-date org-log-redeadline)
12293 (org-add-log-setup 'deldeadline nil old-date 'findpos
12294 org-log-redeadline))
12295 (org-remove-timestamp-with-keyword org-deadline-string)
12296 (message "Item no longer has a deadline."))
12297 (org-add-planning-info 'deadline time 'closed)
12298 (when (and old-date org-log-redeadline
12299 (not (equal old-date
12300 (substring org-last-inserted-timestamp 1 -1))))
12301 (org-add-log-setup 'redeadline nil old-date 'findpos
12302 org-log-redeadline))
12303 (when repeater
12304 (save-excursion
12305 (org-back-to-heading t)
12306 (when (re-search-forward (concat org-deadline-string " "
12307 org-last-inserted-timestamp)
12308 (save-excursion
12309 (outline-next-heading) (point)) t)
12310 (goto-char (1- (match-end 0)))
12311 (insert " " repeater)
12312 (setq org-last-inserted-timestamp
12313 (concat (substring org-last-inserted-timestamp 0 -1)
12314 " " repeater
12315 (substring org-last-inserted-timestamp -1))))))
12316 (message "Deadline on %s" org-last-inserted-timestamp)))))
12318 (defun org-schedule (&optional remove time)
12319 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12320 With argument REMOVE, remove any scheduling date from the item.
12321 With argument TIME, scheduled at the corresponding date. TIME can
12322 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12323 (interactive "P")
12324 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12325 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12326 'region-start-level 'region))
12327 org-loop-over-headlines-in-active-region)
12328 (org-map-entries
12329 `(org-schedule ',remove ,time)
12330 org-loop-over-headlines-in-active-region
12331 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12332 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12333 (repeater (and old-date
12334 (string-match
12335 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12336 old-date)
12337 (match-string 1 old-date))))
12338 (if remove
12339 (progn
12340 (when (and old-date org-log-reschedule)
12341 (org-add-log-setup 'delschedule nil old-date 'findpos
12342 org-log-reschedule))
12343 (org-remove-timestamp-with-keyword org-scheduled-string)
12344 (message "Item is no longer scheduled."))
12345 (org-add-planning-info 'scheduled time 'closed)
12346 (when (and old-date org-log-reschedule
12347 (not (equal old-date
12348 (substring org-last-inserted-timestamp 1 -1))))
12349 (org-add-log-setup 'reschedule nil old-date 'findpos
12350 org-log-reschedule))
12351 (when repeater
12352 (save-excursion
12353 (org-back-to-heading t)
12354 (when (re-search-forward (concat org-scheduled-string " "
12355 org-last-inserted-timestamp)
12356 (save-excursion
12357 (outline-next-heading) (point)) t)
12358 (goto-char (1- (match-end 0)))
12359 (insert " " repeater)
12360 (setq org-last-inserted-timestamp
12361 (concat (substring org-last-inserted-timestamp 0 -1)
12362 " " repeater
12363 (substring org-last-inserted-timestamp -1))))))
12364 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12366 (defun org-get-scheduled-time (pom &optional inherit)
12367 "Get the scheduled time as a time tuple, of a format suitable
12368 for calling org-schedule with, or if there is no scheduling,
12369 returns nil."
12370 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12371 (when time
12372 (apply 'encode-time (org-parse-time-string time)))))
12374 (defun org-get-deadline-time (pom &optional inherit)
12375 "Get the deadline as a time tuple, of a format suitable for
12376 calling org-deadline with, or if there is no scheduling, returns
12377 nil."
12378 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12379 (when time
12380 (apply 'encode-time (org-parse-time-string time)))))
12382 (defun org-remove-timestamp-with-keyword (keyword)
12383 "Remove all time stamps with KEYWORD in the current entry."
12384 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12385 beg)
12386 (save-excursion
12387 (org-back-to-heading t)
12388 (setq beg (point))
12389 (outline-next-heading)
12390 (while (re-search-backward re beg t)
12391 (replace-match "")
12392 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12393 (equal (char-before) ?\ ))
12394 (backward-delete-char 1)
12395 (if (string-match "^[ \t]*$" (buffer-substring
12396 (point-at-bol) (point-at-eol)))
12397 (delete-region (point-at-bol)
12398 (min (point-max) (1+ (point-at-eol))))))))))
12400 (defun org-add-planning-info (what &optional time &rest remove)
12401 "Insert new timestamp with keyword in the line directly after the headline.
12402 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12403 If non is given, the user is prompted for a date.
12404 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12405 be removed."
12406 (interactive)
12407 (let (org-time-was-given org-end-time-was-given ts
12408 end default-time default-input)
12410 (catch 'exit
12411 (when (and (memq what '(scheduled deadline))
12412 (or (not time)
12413 (and (stringp time)
12414 (string-match "^[-+]+[0-9]" time))))
12415 ;; Try to get a default date/time from existing timestamp
12416 (save-excursion
12417 (org-back-to-heading t)
12418 (setq end (save-excursion (outline-next-heading) (point)))
12419 (when (re-search-forward (if (eq what 'scheduled)
12420 org-scheduled-time-regexp
12421 org-deadline-time-regexp)
12422 end t)
12423 (setq ts (match-string 1)
12424 default-time
12425 (apply 'encode-time (org-parse-time-string ts))
12426 default-input (and ts (org-get-compact-tod ts))))))
12427 (when what
12428 (setq time
12429 (if (stringp time)
12430 ;; This is a string (relative or absolute), set proper date
12431 (apply 'encode-time
12432 (org-read-date-analyze
12433 time default-time (decode-time default-time)))
12434 ;; If necessary, get the time from the user
12435 (or time (org-read-date nil 'to-time nil nil
12436 default-time default-input)))))
12438 (when (and org-insert-labeled-timestamps-at-point
12439 (member what '(scheduled deadline)))
12440 (insert
12441 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12442 (org-insert-time-stamp time org-time-was-given
12443 nil nil nil (list org-end-time-was-given))
12444 (setq what nil))
12445 (save-excursion
12446 (save-restriction
12447 (let (col list elt ts buffer-invisibility-spec)
12448 (org-back-to-heading t)
12449 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12450 (goto-char (match-end 1))
12451 (setq col (current-column))
12452 (goto-char (match-end 0))
12453 (if (eobp) (insert "\n") (forward-char 1))
12454 (when (and (not what)
12455 (not (looking-at
12456 (concat "[ \t]*"
12457 org-keyword-time-not-clock-regexp))))
12458 ;; Nothing to add, nothing to remove...... :-)
12459 (throw 'exit nil))
12460 (if (and (not (looking-at org-outline-regexp))
12461 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12462 "[^\r\n]*"))
12463 (not (equal (match-string 1) org-clock-string)))
12464 (narrow-to-region (match-beginning 0) (match-end 0))
12465 (insert-before-markers "\n")
12466 (backward-char 1)
12467 (narrow-to-region (point) (point))
12468 (and org-adapt-indentation (org-indent-to-column col)))
12469 ;; Check if we have to remove something.
12470 (setq list (cons what remove))
12471 (while list
12472 (setq elt (pop list))
12473 (when (or (and (eq elt 'scheduled)
12474 (re-search-forward org-scheduled-time-regexp nil t))
12475 (and (eq elt 'deadline)
12476 (re-search-forward org-deadline-time-regexp nil t))
12477 (and (eq elt 'closed)
12478 (re-search-forward org-closed-time-regexp nil t)))
12479 (replace-match "")
12480 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12481 (and (looking-at "[ \t]+") (replace-match ""))
12482 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12483 (when what
12484 (insert
12485 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12486 (cond ((eq what 'scheduled) org-scheduled-string)
12487 ((eq what 'deadline) org-deadline-string)
12488 ((eq what 'closed) org-closed-string))
12489 " ")
12490 (setq ts (org-insert-time-stamp
12491 time
12492 (or org-time-was-given
12493 (and (eq what 'closed) org-log-done-with-time))
12494 (eq what 'closed)
12495 nil nil (list org-end-time-was-given)))
12496 (insert
12497 (if (not (or (bolp) (eq (char-before) ?\ )
12498 (memq (char-after) '(32 10))
12499 (eobp))) " " ""))
12500 (end-of-line 1))
12501 (goto-char (point-min))
12502 (widen)
12503 (if (and (looking-at "[ \t]*\n")
12504 (equal (char-before) ?\n))
12505 (delete-region (1- (point)) (point-at-eol)))
12506 ts))))))
12508 (defvar org-log-note-marker (make-marker))
12509 (defvar org-log-note-purpose nil)
12510 (defvar org-log-note-state nil)
12511 (defvar org-log-note-previous-state nil)
12512 (defvar org-log-note-how nil)
12513 (defvar org-log-note-extra nil)
12514 (defvar org-log-note-window-configuration nil)
12515 (defvar org-log-note-return-to (make-marker))
12516 (defvar org-log-note-effective-time nil
12517 "Remembered current time so that dynamically scoped
12518 `org-extend-today-until' affects tha timestamps in state change
12519 log")
12521 (defvar org-log-post-message nil
12522 "Message to be displayed after a log note has been stored.
12523 The auto-repeater uses this.")
12525 (defun org-add-note ()
12526 "Add a note to the current entry.
12527 This is done in the same way as adding a state change note."
12528 (interactive)
12529 (org-add-log-setup 'note nil nil 'findpos nil))
12531 (defvar org-property-end-re)
12532 (defun org-add-log-setup (&optional purpose state prev-state
12533 findpos how extra)
12534 "Set up the post command hook to take a note.
12535 If this is about to TODO state change, the new state is expected in STATE.
12536 When FINDPOS is non-nil, find the correct position for the note in
12537 the current entry. If not, assume that it can be inserted at point.
12538 HOW is an indicator what kind of note should be created.
12539 EXTRA is additional text that will be inserted into the notes buffer."
12540 (let* ((org-log-into-drawer (org-log-into-drawer))
12541 (drawer (cond ((stringp org-log-into-drawer)
12542 org-log-into-drawer)
12543 (org-log-into-drawer "LOGBOOK"))))
12544 (save-restriction
12545 (save-excursion
12546 (when findpos
12547 (org-back-to-heading t)
12548 (narrow-to-region (point) (save-excursion
12549 (outline-next-heading) (point)))
12550 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12551 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12552 "[^\r\n]*\\)?"))
12553 (goto-char (match-end 0))
12554 (cond
12555 (drawer
12556 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12557 nil t)
12558 (progn
12559 (goto-char (match-end 0))
12560 (or org-log-states-order-reversed
12561 (and (re-search-forward org-property-end-re nil t)
12562 (goto-char (1- (match-beginning 0))))))
12563 (insert "\n:" drawer ":\n:END:")
12564 (beginning-of-line 0)
12565 (org-indent-line)
12566 (beginning-of-line 2)
12567 (org-indent-line)
12568 (end-of-line 0)))
12569 ((and org-log-state-notes-insert-after-drawers
12570 (save-excursion
12571 (forward-line) (looking-at org-drawer-regexp)))
12572 (forward-line)
12573 (while (looking-at org-drawer-regexp)
12574 (goto-char (match-end 0))
12575 (re-search-forward org-property-end-re (point-max) t)
12576 (forward-line))
12577 (forward-line -1)))
12578 (unless org-log-states-order-reversed
12579 (and (= (char-after) ?\n) (forward-char 1))
12580 (org-skip-over-state-notes)
12581 (skip-chars-backward " \t\n\r")))
12582 (move-marker org-log-note-marker (point))
12583 (setq org-log-note-purpose purpose
12584 org-log-note-state state
12585 org-log-note-previous-state prev-state
12586 org-log-note-how how
12587 org-log-note-extra extra
12588 org-log-note-effective-time (org-current-effective-time))
12589 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12591 (defun org-skip-over-state-notes ()
12592 "Skip past the list of State notes in an entry."
12593 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12594 (when (ignore-errors (goto-char (org-in-item-p)))
12595 (let* ((struct (org-list-struct))
12596 (prevs (org-list-prevs-alist struct)))
12597 (while (looking-at "[ \t]*- State")
12598 (goto-char (or (org-list-get-next-item (point) struct prevs)
12599 (org-list-get-item-end (point) struct)))))))
12601 (defun org-add-log-note (&optional purpose)
12602 "Pop up a window for taking a note, and add this note later at point."
12603 (remove-hook 'post-command-hook 'org-add-log-note)
12604 (setq org-log-note-window-configuration (current-window-configuration))
12605 (delete-other-windows)
12606 (move-marker org-log-note-return-to (point))
12607 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12608 (goto-char org-log-note-marker)
12609 (org-switch-to-buffer-other-window "*Org Note*")
12610 (erase-buffer)
12611 (if (memq org-log-note-how '(time state))
12612 (let (current-prefix-arg) (org-store-log-note))
12613 (let ((org-inhibit-startup t)) (org-mode))
12614 (insert (format "# Insert note for %s.
12615 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12616 (cond
12617 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12618 ((eq org-log-note-purpose 'done) "closed todo item")
12619 ((eq org-log-note-purpose 'state)
12620 (format "state change from \"%s\" to \"%s\""
12621 (or org-log-note-previous-state "")
12622 (or org-log-note-state "")))
12623 ((eq org-log-note-purpose 'reschedule)
12624 "rescheduling")
12625 ((eq org-log-note-purpose 'delschedule)
12626 "no longer scheduled")
12627 ((eq org-log-note-purpose 'redeadline)
12628 "changing deadline")
12629 ((eq org-log-note-purpose 'deldeadline)
12630 "removing deadline")
12631 ((eq org-log-note-purpose 'refile)
12632 "refiling")
12633 ((eq org-log-note-purpose 'note)
12634 "this entry")
12635 (t (error "This should not happen")))))
12636 (if org-log-note-extra (insert org-log-note-extra))
12637 (org-set-local 'org-finish-function 'org-store-log-note)
12638 (run-hooks 'org-log-buffer-setup-hook)))
12640 (defvar org-note-abort nil) ; dynamically scoped
12641 (defun org-store-log-note ()
12642 "Finish taking a log note, and insert it to where it belongs."
12643 (let ((txt (buffer-string))
12644 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12645 lines ind bul)
12646 (kill-buffer (current-buffer))
12647 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12648 (setq txt (replace-match "" t t txt)))
12649 (if (string-match "\\s-+\\'" txt)
12650 (setq txt (replace-match "" t t txt)))
12651 (setq lines (org-split-string txt "\n"))
12652 (when (and note (string-match "\\S-" note))
12653 (setq note
12654 (org-replace-escapes
12655 note
12656 (list (cons "%u" (user-login-name))
12657 (cons "%U" user-full-name)
12658 (cons "%t" (format-time-string
12659 (org-time-stamp-format 'long 'inactive)
12660 org-log-note-effective-time))
12661 (cons "%T" (format-time-string
12662 (org-time-stamp-format 'long nil)
12663 org-log-note-effective-time))
12664 (cons "%d" (format-time-string
12665 (org-time-stamp-format nil 'inactive)
12666 org-log-note-effective-time))
12667 (cons "%D" (format-time-string
12668 (org-time-stamp-format nil nil)
12669 org-log-note-effective-time))
12670 (cons "%s" (if org-log-note-state
12671 (concat "\"" org-log-note-state "\"")
12672 ""))
12673 (cons "%S" (if org-log-note-previous-state
12674 (concat "\"" org-log-note-previous-state "\"")
12675 "\"\"")))))
12676 (if lines (setq note (concat note " \\\\")))
12677 (push note lines))
12678 (when (or current-prefix-arg org-note-abort)
12679 (when org-log-into-drawer
12680 (org-remove-empty-drawer-at
12681 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12682 org-log-note-marker))
12683 (setq lines nil))
12684 (when lines
12685 (with-current-buffer (marker-buffer org-log-note-marker)
12686 (save-excursion
12687 (goto-char org-log-note-marker)
12688 (move-marker org-log-note-marker nil)
12689 (end-of-line 1)
12690 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12691 (setq ind (save-excursion
12692 (if (ignore-errors (goto-char (org-in-item-p)))
12693 (let ((struct (org-list-struct)))
12694 (org-list-get-ind
12695 (org-list-get-top-point struct) struct))
12696 (skip-chars-backward " \r\t\n")
12697 (cond
12698 ((and (org-at-heading-p)
12699 org-adapt-indentation)
12700 (1+ (org-current-level)))
12701 ((org-at-heading-p) 0)
12702 (t (org-get-indentation))))))
12703 (setq bul (org-list-bullet-string "-"))
12704 (org-indent-line-to ind)
12705 (insert bul (pop lines))
12706 (let ((ind-body (+ (length bul) ind)))
12707 (while lines
12708 (insert "\n")
12709 (org-indent-line-to ind-body)
12710 (insert (pop lines))))
12711 (message "Note stored")
12712 (org-back-to-heading t)
12713 (org-cycle-hide-drawers 'children)))))
12714 (set-window-configuration org-log-note-window-configuration)
12715 (with-current-buffer (marker-buffer org-log-note-return-to)
12716 (goto-char org-log-note-return-to))
12717 (move-marker org-log-note-return-to nil)
12718 (and org-log-post-message (message "%s" org-log-post-message)))
12720 (defun org-remove-empty-drawer-at (drawer pos)
12721 "Remove an empty drawer DRAWER at position POS.
12722 POS may also be a marker."
12723 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12724 (save-excursion
12725 (save-restriction
12726 (widen)
12727 (goto-char pos)
12728 (if (org-in-regexp
12729 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12730 (replace-match ""))))))
12732 (defvar org-ts-type nil)
12733 (defun org-sparse-tree (&optional arg type)
12734 "Create a sparse tree, prompt for the details.
12735 This command can create sparse trees. You first need to select the type
12736 of match used to create the tree:
12738 t Show all TODO entries.
12739 T Show entries with a specific TODO keyword.
12740 m Show entries selected by a tags/property match.
12741 p Enter a property name and its value (both with completion on existing
12742 names/values) and show entries with that property.
12743 r Show entries matching a regular expression (`/' can be used as well).
12744 b Show deadlines and scheduled items before a date.
12745 a Show deadlines and scheduled items after a date.
12746 d Show deadlines due within `org-deadline-warning-days'.
12747 D Show deadlines and scheduled items between a date range."
12748 (interactive "P")
12749 (let (ans kwd value ts-type)
12750 (setq type (or type org-sparse-tree-default-date-type))
12751 (setq org-ts-type type)
12752 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12753 (cond ((eq type 'all) "all timestamps")
12754 ((eq type 'scheduled) "only scheduled")
12755 ((eq type 'deadline) "only deadline")
12756 ((eq type 'active) "only active timestamps")
12757 ((eq type 'inactive) "only inactive timestamps")
12758 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12759 (t "scheduled/deadline")))
12760 (setq ans (read-char-exclusive))
12761 (cond
12762 ((equal ans ?c)
12763 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12764 ((equal ans ?d)
12765 (call-interactively 'org-check-deadlines))
12766 ((equal ans ?b)
12767 (call-interactively 'org-check-before-date))
12768 ((equal ans ?a)
12769 (call-interactively 'org-check-after-date))
12770 ((equal ans ?D)
12771 (call-interactively 'org-check-dates-range))
12772 ((equal ans ?t)
12773 (call-interactively 'org-show-todo-tree))
12774 ((equal ans ?T)
12775 (org-show-todo-tree '(4)))
12776 ((member ans '(?T ?m))
12777 (call-interactively 'org-match-sparse-tree))
12778 ((member ans '(?p ?P))
12779 (setq kwd (org-icompleting-read "Property: "
12780 (mapcar 'list (org-buffer-property-keys))))
12781 (setq value (org-icompleting-read "Value: "
12782 (mapcar 'list (org-property-values kwd))))
12783 (unless (string-match "\\`{.*}\\'" value)
12784 (setq value (concat "\"" value "\"")))
12785 (org-match-sparse-tree arg (concat kwd "=" value)))
12786 ((member ans '(?r ?R ?/))
12787 (call-interactively 'org-occur))
12788 (t (error "No such sparse tree command \"%c\"" ans)))))
12790 (defvar org-occur-highlights nil
12791 "List of overlays used for occur matches.")
12792 (make-variable-buffer-local 'org-occur-highlights)
12793 (defvar org-occur-parameters nil
12794 "Parameters of the active org-occur calls.
12795 This is a list, each call to org-occur pushes as cons cell,
12796 containing the regular expression and the callback, onto the list.
12797 The list can contain several entries if `org-occur' has been called
12798 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12799 will only contain one set of parameters. When the highlights are
12800 removed (for example with `C-c C-c', or with the next edit (depending
12801 on `org-remove-highlights-with-change'), this variable is emptied
12802 as well.")
12803 (make-variable-buffer-local 'org-occur-parameters)
12805 (defun org-occur (regexp &optional keep-previous callback)
12806 "Make a compact tree which shows all matches of REGEXP.
12807 The tree will show the lines where the regexp matches, and all higher
12808 headlines above the match. It will also show the heading after the match,
12809 to make sure editing the matching entry is easy.
12810 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12811 call to `org-occur' will be kept, to allow stacking of calls to this
12812 command.
12813 If CALLBACK is non-nil, it is a function which is called to confirm
12814 that the match should indeed be shown."
12815 (interactive "sRegexp: \nP")
12816 (when (equal regexp "")
12817 (error "Regexp cannot be empty"))
12818 (unless keep-previous
12819 (org-remove-occur-highlights nil nil t))
12820 (push (cons regexp callback) org-occur-parameters)
12821 (let ((cnt 0))
12822 (save-excursion
12823 (goto-char (point-min))
12824 (if (or (not keep-previous) ; do not want to keep
12825 (not org-occur-highlights)) ; no previous matches
12826 ;; hide everything
12827 (org-overview))
12828 (while (re-search-forward regexp nil t)
12829 (when (or (not callback)
12830 (save-match-data (funcall callback)))
12831 (setq cnt (1+ cnt))
12832 (when org-highlight-sparse-tree-matches
12833 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12834 (org-show-context 'occur-tree))))
12835 (when org-remove-highlights-with-change
12836 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12837 nil 'local))
12838 (unless org-sparse-tree-open-archived-trees
12839 (org-hide-archived-subtrees (point-min) (point-max)))
12840 (run-hooks 'org-occur-hook)
12841 (if (org-called-interactively-p 'interactive)
12842 (message "%d match(es) for regexp %s" cnt regexp))
12843 cnt))
12845 (defun org-occur-next-match (&optional n reset)
12846 "Function for `next-error-function' to find sparse tree matches.
12847 N is the number of matches to move, when negative move backwards.
12848 RESET is entirely ignored - this function always goes back to the
12849 starting point when no match is found."
12850 (let* ((limit (if (< n 0) (point-min) (point-max)))
12851 (search-func (if (< n 0)
12852 'previous-single-char-property-change
12853 'next-single-char-property-change))
12854 (n (abs n))
12855 (pos (point))
12857 (catch 'exit
12858 (while (setq p1 (funcall search-func (point) 'org-type))
12859 (when (equal p1 limit)
12860 (goto-char pos)
12861 (error "No more matches"))
12862 (when (equal (get-char-property p1 'org-type) 'org-occur)
12863 (setq n (1- n))
12864 (when (= n 0)
12865 (goto-char p1)
12866 (throw 'exit (point))))
12867 (goto-char p1))
12868 (goto-char p1)
12869 (error "No more matches"))))
12871 (defun org-show-context (&optional key)
12872 "Make sure point and context are visible.
12873 How much context is shown depends upon the variables
12874 `org-show-hierarchy-above', `org-show-following-heading',
12875 `org-show-entry-below' and `org-show-siblings'."
12876 (let ((heading-p (org-at-heading-p t))
12877 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12878 (following-p (org-get-alist-option org-show-following-heading key))
12879 (entry-p (org-get-alist-option org-show-entry-below key))
12880 (siblings-p (org-get-alist-option org-show-siblings key)))
12881 (catch 'exit
12882 ;; Show heading or entry text
12883 (if (and heading-p (not entry-p))
12884 (org-flag-heading nil) ; only show the heading
12885 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12886 (org-show-hidden-entry))) ; show entire entry
12887 (when following-p
12888 ;; Show next sibling, or heading below text
12889 (save-excursion
12890 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12891 (org-flag-heading nil))))
12892 (when siblings-p (org-show-siblings))
12893 (when hierarchy-p
12894 ;; show all higher headings, possibly with siblings
12895 (save-excursion
12896 (while (and (condition-case nil
12897 (progn (org-up-heading-all 1) t)
12898 (error nil))
12899 (not (bobp)))
12900 (org-flag-heading nil)
12901 (when siblings-p (org-show-siblings))))))))
12903 (defvar org-reveal-start-hook nil
12904 "Hook run before revealing a location.")
12906 (defun org-reveal (&optional siblings)
12907 "Show current entry, hierarchy above it, and the following headline.
12908 This can be used to show a consistent set of context around locations
12909 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12910 not t for the search context.
12912 With optional argument SIBLINGS, on each level of the hierarchy all
12913 siblings are shown. This repairs the tree structure to what it would
12914 look like when opened with hierarchical calls to `org-cycle'.
12915 With double optional argument \\[universal-argument] \\[universal-argument], \
12916 go to the parent and show the
12917 entire tree."
12918 (interactive "P")
12919 (run-hooks 'org-reveal-start-hook)
12920 (let ((org-show-hierarchy-above t)
12921 (org-show-following-heading t)
12922 (org-show-siblings (if siblings t org-show-siblings)))
12923 (org-show-context nil))
12924 (when (equal siblings '(16))
12925 (save-excursion
12926 (when (org-up-heading-safe)
12927 (org-show-subtree)
12928 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12930 (defun org-highlight-new-match (beg end)
12931 "Highlight from BEG to END and mark the highlight is an occur headline."
12932 (let ((ov (make-overlay beg end)))
12933 (overlay-put ov 'face 'secondary-selection)
12934 (overlay-put ov 'org-type 'org-occur)
12935 (push ov org-occur-highlights)))
12937 (defun org-remove-occur-highlights (&optional beg end noremove)
12938 "Remove the occur highlights from the buffer.
12939 BEG and END are ignored. If NOREMOVE is nil, remove this function
12940 from the `before-change-functions' in the current buffer."
12941 (interactive)
12942 (unless org-inhibit-highlight-removal
12943 (mapc 'delete-overlay org-occur-highlights)
12944 (setq org-occur-highlights nil)
12945 (setq org-occur-parameters nil)
12946 (unless noremove
12947 (remove-hook 'before-change-functions
12948 'org-remove-occur-highlights 'local))))
12950 ;;;; Priorities
12952 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12953 "Regular expression matching the priority indicator.")
12955 (defvar org-remove-priority-next-time nil)
12957 (defun org-priority-up ()
12958 "Increase the priority of the current item."
12959 (interactive)
12960 (org-priority 'up))
12962 (defun org-priority-down ()
12963 "Decrease the priority of the current item."
12964 (interactive)
12965 (org-priority 'down))
12967 (defun org-priority (&optional action show)
12968 "Change the priority of an item.
12969 ACTION can be `set', `up', `down', or a character."
12970 (interactive "P")
12971 (if (equal action '(4))
12972 (org-show-priority)
12973 (unless org-enable-priority-commands
12974 (error "Priority commands are disabled"))
12975 (setq action (or action 'set))
12976 (let (current new news have remove)
12977 (save-excursion
12978 (org-back-to-heading t)
12979 (if (looking-at org-priority-regexp)
12980 (setq current (string-to-char (match-string 2))
12981 have t))
12982 (cond
12983 ((eq action 'remove)
12984 (setq remove t new ?\ ))
12985 ((or (eq action 'set)
12986 (if (featurep 'xemacs) (characterp action) (integerp action)))
12987 (if (not (eq action 'set))
12988 (setq new action)
12989 (message "Priority %c-%c, SPC to remove: "
12990 org-highest-priority org-lowest-priority)
12991 (save-match-data
12992 (setq new (read-char-exclusive))))
12993 (if (and (= (upcase org-highest-priority) org-highest-priority)
12994 (= (upcase org-lowest-priority) org-lowest-priority))
12995 (setq new (upcase new)))
12996 (cond ((equal new ?\ ) (setq remove t))
12997 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12998 (error "Priority must be between `%c' and `%c'"
12999 org-highest-priority org-lowest-priority))))
13000 ((eq action 'up)
13001 (setq new (if have
13002 (1- current) ; normal cycling
13003 ;; last priority was empty
13004 (if (eq last-command this-command)
13005 org-lowest-priority ; wrap around empty to lowest
13006 ;; default
13007 (if org-priority-start-cycle-with-default
13008 org-default-priority
13009 (1- org-default-priority))))))
13010 ((eq action 'down)
13011 (setq new (if have
13012 (1+ current) ; normal cycling
13013 ;; last priority was empty
13014 (if (eq last-command this-command)
13015 org-highest-priority ; wrap around empty to highest
13016 ;; default
13017 (if org-priority-start-cycle-with-default
13018 org-default-priority
13019 (1+ org-default-priority))))))
13020 (t (error "Invalid action")))
13021 (if (or (< (upcase new) org-highest-priority)
13022 (> (upcase new) org-lowest-priority))
13023 (if (and (memq action '(up down))
13024 (not have) (not (eq last-command this-command)))
13025 ;; `new' is from default priority
13026 (error
13027 "The default can not be set, see `org-default-priority' why")
13028 ;; normal cycling: `new' is beyond highest/lowest priority
13029 ;; and is wrapped around to the empty priority
13030 (setq remove t)))
13031 (setq news (format "%c" new))
13032 (if have
13033 (if remove
13034 (replace-match "" t t nil 1)
13035 (replace-match news t t nil 2))
13036 (if remove
13037 (error "No priority cookie found in line")
13038 (let ((case-fold-search nil))
13039 (looking-at org-todo-line-regexp))
13040 (if (match-end 2)
13041 (progn
13042 (goto-char (match-end 2))
13043 (insert " [#" news "]"))
13044 (goto-char (match-beginning 3))
13045 (insert "[#" news "] "))))
13046 (org-preserve-lc (org-set-tags nil 'align)))
13047 (if remove
13048 (message "Priority removed")
13049 (message "Priority of current item set to %s" news)))))
13051 (defun org-show-priority ()
13052 "Show the priority of the current item.
13053 This priority is composed of the main priority given with the [#A] cookies,
13054 and by additional input from the age of a schedules or deadline entry."
13055 (interactive)
13056 (let ((pri (if (eq major-mode 'org-agenda-mode)
13057 (org-get-at-bol 'priority)
13058 (save-excursion
13059 (save-match-data
13060 (beginning-of-line)
13061 (and (looking-at org-heading-regexp)
13062 (org-get-priority (match-string 0))))))))
13063 (message "Priority is %d" (if pri pri -1000))))
13065 (defun org-get-priority (s)
13066 "Find priority cookie and return priority."
13067 (if (functionp org-get-priority-function)
13068 (funcall org-get-priority-function)
13069 (save-match-data
13070 (if (not (string-match org-priority-regexp s))
13071 (* 1000 (- org-lowest-priority org-default-priority))
13072 (* 1000 (- org-lowest-priority
13073 (string-to-char (match-string 2 s))))))))
13075 ;;;; Tags
13077 (defvar org-agenda-archives-mode)
13078 (defvar org-map-continue-from nil
13079 "Position from where mapping should continue.
13080 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13082 (defvar org-scanner-tags nil
13083 "The current tag list while the tags scanner is running.")
13084 (defvar org-trust-scanner-tags nil
13085 "Should `org-get-tags-at' use the tags for the scanner.
13086 This is for internal dynamical scoping only.
13087 When this is non-nil, the function `org-get-tags-at' will return the value
13088 of `org-scanner-tags' instead of building the list by itself. This
13089 can lead to large speed-ups when the tags scanner is used in a file with
13090 many entries, and when the list of tags is retrieved, for example to
13091 obtain a list of properties. Building the tags list for each entry in such
13092 a file becomes an N^2 operation - but with this variable set, it scales
13093 as N.")
13095 (defun org-scan-tags (action matcher todo-only &optional start-level)
13096 "Scan headline tags with inheritance and produce output ACTION.
13098 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13099 or `agenda' to produce an entry list for an agenda view. It can also be
13100 a Lisp form or a function that should be called at each matched headline, in
13101 this case the return value is a list of all return values from these calls.
13103 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13104 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13105 only lines with a not-done TODO keyword are included in the output.
13106 This should be the same variable that was scoped into
13107 and set by `org-make-tags-matcher' when it constructed MATCHER.
13109 START-LEVEL can be a string with asterisks, reducing the scope to
13110 headlines matching this string."
13111 (require 'org-agenda)
13112 (let* ((re (concat "^"
13113 (if start-level
13114 ;; Get the correct level to match
13115 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13116 org-outline-regexp)
13117 " *\\(\\<\\("
13118 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13119 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13120 (props (list 'face 'default
13121 'done-face 'org-agenda-done
13122 'undone-face 'default
13123 'mouse-face 'highlight
13124 'org-not-done-regexp org-not-done-regexp
13125 'org-todo-regexp org-todo-regexp
13126 'org-complex-heading-regexp org-complex-heading-regexp
13127 'help-echo
13128 (format "mouse-2 or RET jump to org file %s"
13129 (abbreviate-file-name
13130 (or (buffer-file-name (buffer-base-buffer))
13131 (buffer-name (buffer-base-buffer)))))))
13132 (case-fold-search nil)
13133 (org-map-continue-from nil)
13134 lspos tags tags-list
13135 (tags-alist (list (cons 0 org-file-tags)))
13136 (llast 0) rtn rtn1 level category i txt
13137 todo marker entry priority)
13138 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13139 (setq action (list 'lambda nil action)))
13140 (save-excursion
13141 (goto-char (point-min))
13142 (when (eq action 'sparse-tree)
13143 (org-overview)
13144 (org-remove-occur-highlights))
13145 (while (re-search-forward re nil t)
13146 (setq org-map-continue-from nil)
13147 (catch :skip
13148 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13149 tags (if (match-end 4) (org-match-string-no-properties 4)))
13150 (goto-char (setq lspos (match-beginning 0)))
13151 (setq level (org-reduced-level (org-outline-level))
13152 category (org-get-category))
13153 (setq i llast llast level)
13154 ;; remove tag lists from same and sublevels
13155 (while (>= i level)
13156 (when (setq entry (assoc i tags-alist))
13157 (setq tags-alist (delete entry tags-alist)))
13158 (setq i (1- i)))
13159 ;; add the next tags
13160 (when tags
13161 (setq tags (org-split-string tags ":")
13162 tags-alist
13163 (cons (cons level tags) tags-alist)))
13164 ;; compile tags for current headline
13165 (setq tags-list
13166 (if org-use-tag-inheritance
13167 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13168 tags)
13169 org-scanner-tags tags-list)
13170 (when org-use-tag-inheritance
13171 (setcdr (car tags-alist)
13172 (mapcar (lambda (x)
13173 (setq x (copy-sequence x))
13174 (org-add-prop-inherited x))
13175 (cdar tags-alist))))
13176 (when (and tags org-use-tag-inheritance
13177 (or (not (eq t org-use-tag-inheritance))
13178 org-tags-exclude-from-inheritance))
13179 ;; selective inheritance, remove uninherited ones
13180 (setcdr (car tags-alist)
13181 (org-remove-uninherited-tags (cdar tags-alist))))
13182 (when (and
13184 ;; eval matcher only when the todo condition is OK
13185 (and (or (not todo-only) (member todo org-not-done-keywords))
13186 (let ((case-fold-search t) (org-trust-scanner-tags t))
13187 (eval matcher)))
13189 ;; Call the skipper, but return t if it does not skip,
13190 ;; so that the `and' form continues evaluating
13191 (progn
13192 (unless (eq action 'sparse-tree) (org-agenda-skip))
13195 ;; Check if timestamps are deselecting this entry
13196 (or (not todo-only)
13197 (and (member todo org-not-done-keywords)
13198 (or (not org-agenda-tags-todo-honor-ignore-options)
13199 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13201 ;; Extra check for the archive tag
13202 ;; FIXME: Does the skipper already do this????
13204 (not (member org-archive-tag tags-list))
13205 ;; we have an archive tag, should we use this anyway?
13206 (or (not org-agenda-skip-archived-trees)
13207 (and (eq action 'agenda) org-agenda-archives-mode))))
13209 ;; select this headline
13210 (cond
13211 ((eq action 'sparse-tree)
13212 (and org-highlight-sparse-tree-matches
13213 (org-get-heading) (match-end 0)
13214 (org-highlight-new-match
13215 (match-beginning 1) (match-end 1)))
13216 (org-show-context 'tags-tree))
13217 ((eq action 'agenda)
13218 (setq txt (org-agenda-format-item
13220 (concat
13221 (if (eq org-tags-match-list-sublevels 'indented)
13222 (make-string (1- level) ?.) "")
13223 (org-get-heading))
13224 level category
13225 tags-list)
13226 priority (org-get-priority txt))
13227 (goto-char lspos)
13228 (setq marker (org-agenda-new-marker))
13229 (org-add-props txt props
13230 'org-marker marker 'org-hd-marker marker 'org-category category
13231 'todo-state todo
13232 'priority priority 'type "tagsmatch")
13233 (push txt rtn))
13234 ((functionp action)
13235 (setq org-map-continue-from nil)
13236 (save-excursion
13237 (setq rtn1 (funcall action))
13238 (push rtn1 rtn)))
13239 (t (error "Invalid action")))
13241 ;; if we are to skip sublevels, jump to end of subtree
13242 (unless org-tags-match-list-sublevels
13243 (org-end-of-subtree t)
13244 (backward-char 1))))
13245 ;; Get the correct position from where to continue
13246 (if org-map-continue-from
13247 (goto-char org-map-continue-from)
13248 (and (= (point) lspos) (end-of-line 1)))))
13249 (when (and (eq action 'sparse-tree)
13250 (not org-sparse-tree-open-archived-trees))
13251 (org-hide-archived-subtrees (point-min) (point-max)))
13252 (nreverse rtn)))
13254 (defun org-remove-uninherited-tags (tags)
13255 "Remove all tags that are not inherited from the list TAGS."
13256 (cond
13257 ((eq org-use-tag-inheritance t)
13258 (if org-tags-exclude-from-inheritance
13259 (org-delete-all org-tags-exclude-from-inheritance tags)
13260 tags))
13261 ((not org-use-tag-inheritance) nil)
13262 ((stringp org-use-tag-inheritance)
13263 (delq nil (mapcar
13264 (lambda (x)
13265 (if (and (string-match org-use-tag-inheritance x)
13266 (not (member x org-tags-exclude-from-inheritance)))
13267 x nil))
13268 tags)))
13269 ((listp org-use-tag-inheritance)
13270 (delq nil (mapcar
13271 (lambda (x)
13272 (if (member x org-use-tag-inheritance) x nil))
13273 tags)))))
13275 (defun org-match-sparse-tree (&optional todo-only match)
13276 "Create a sparse tree according to tags string MATCH.
13277 MATCH can contain positive and negative selection of tags, like
13278 \"+WORK+URGENT-WITHBOSS\".
13279 If optional argument TODO-ONLY is non-nil, only select lines that are
13280 also TODO lines."
13281 (interactive "P")
13282 (org-agenda-prepare-buffers (list (current-buffer)))
13283 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13285 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13287 (defvar org-cached-props nil)
13288 (defun org-cached-entry-get (pom property)
13289 (if (or (eq t org-use-property-inheritance)
13290 (and (stringp org-use-property-inheritance)
13291 (string-match org-use-property-inheritance property))
13292 (and (listp org-use-property-inheritance)
13293 (member property org-use-property-inheritance)))
13294 ;; Caching is not possible, check it directly
13295 (org-entry-get pom property 'inherit)
13296 ;; Get all properties, so that we can do complicated checks easily
13297 (cdr (assoc property (or org-cached-props
13298 (setq org-cached-props
13299 (org-entry-properties pom)))))))
13301 (defun org-global-tags-completion-table (&optional files)
13302 "Return the list of all tags in all agenda buffer/files.
13303 Optional FILES argument is a list of files which can be used
13304 instead of the agenda files."
13305 (save-excursion
13306 (org-uniquify
13307 (delq nil
13308 (apply 'append
13309 (mapcar
13310 (lambda (file)
13311 (set-buffer (find-file-noselect file))
13312 (append (org-get-buffer-tags)
13313 (mapcar (lambda (x) (if (stringp (car-safe x))
13314 (list (car-safe x)) nil))
13315 org-tag-alist)))
13316 (if (and files (car files))
13317 files
13318 (org-agenda-files))))))))
13320 (defun org-make-tags-matcher (match)
13321 "Create the TAGS/TODO matcher form for the selection string MATCH.
13323 The variable `todo-only' is scoped dynamically into this function.
13324 It will be set to t if the matcher restricts matching to TODO entries,
13325 otherwise will not be touched.
13327 Returns a cons of the selection string MATCH and the constructed
13328 lisp form implementing the matcher. The matcher is to be evaluated
13329 at an Org entry, with point on the headline, and returns t if the
13330 entry matches the selection string MATCH. The returned lisp form
13331 references two variables with information about the entry, which
13332 must be bound around the form's evaluation: todo, the TODO keyword
13333 at the entry (or nil of none); and tags-list, the list of all tags
13334 at the entry including inherited ones. Additionally, the category
13335 of the entry (if any) must be specified as the text property
13336 'org-category on the headline.
13338 See also `org-scan-tags'.
13340 (declare (special todo-only))
13341 (unless (boundp 'todo-only)
13342 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13343 (unless match
13344 ;; Get a new match request, with completion
13345 (let ((org-last-tags-completion-table
13346 (org-global-tags-completion-table)))
13347 (setq match (org-completing-read-no-i
13348 "Match: " 'org-tags-completion-function nil nil nil
13349 'org-tags-history))))
13351 ;; Parse the string and create a lisp form
13352 (let ((match0 match)
13353 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13354 minus tag mm
13355 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13356 orterms term orlist re-p str-p level-p level-op time-p
13357 prop-p pn pv po gv rest)
13358 (if (string-match "/+" match)
13359 ;; match contains also a todo-matching request
13360 (progn
13361 (setq tagsmatch (substring match 0 (match-beginning 0))
13362 todomatch (substring match (match-end 0)))
13363 (if (string-match "^!" todomatch)
13364 (setq todo-only t todomatch (substring todomatch 1)))
13365 (if (string-match "^\\s-*$" todomatch)
13366 (setq todomatch nil)))
13367 ;; only matching tags
13368 (setq tagsmatch match todomatch nil))
13370 ;; Make the tags matcher
13371 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13372 (setq tagsmatcher t)
13373 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13374 (while (setq term (pop orterms))
13375 (while (and (equal (substring term -1) "\\") orterms)
13376 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13377 (while (string-match re term)
13378 (setq rest (substring term (match-end 0))
13379 minus (and (match-end 1)
13380 (equal (match-string 1 term) "-"))
13381 tag (save-match-data (replace-regexp-in-string
13382 "\\\\-" "-"
13383 (match-string 2 term)))
13384 re-p (equal (string-to-char tag) ?{)
13385 level-p (match-end 4)
13386 prop-p (match-end 5)
13387 mm (cond
13388 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13389 (level-p
13390 (setq level-op (org-op-to-function (match-string 3 term)))
13391 `(,level-op level ,(string-to-number
13392 (match-string 4 term))))
13393 (prop-p
13394 (setq pn (match-string 5 term)
13395 po (match-string 6 term)
13396 pv (match-string 7 term)
13397 re-p (equal (string-to-char pv) ?{)
13398 str-p (equal (string-to-char pv) ?\")
13399 time-p (save-match-data
13400 (string-match "^\"[[<].*[]>]\"$" pv))
13401 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13402 (if time-p (setq pv (org-matcher-time pv)))
13403 (setq po (org-op-to-function po (if time-p 'time str-p)))
13404 (cond
13405 ((equal pn "CATEGORY")
13406 (setq gv '(get-text-property (point) 'org-category)))
13407 ((equal pn "TODO")
13408 (setq gv 'todo))
13410 (setq gv `(org-cached-entry-get nil ,pn))))
13411 (if re-p
13412 (if (eq po 'org<>)
13413 `(not (string-match ,pv (or ,gv "")))
13414 `(string-match ,pv (or ,gv "")))
13415 (if str-p
13416 `(,po (or ,gv "") ,pv)
13417 `(,po (string-to-number (or ,gv ""))
13418 ,(string-to-number pv) ))))
13419 (t `(member ,tag tags-list)))
13420 mm (if minus (list 'not mm) mm)
13421 term rest)
13422 (push mm tagsmatcher))
13423 (push (if (> (length tagsmatcher) 1)
13424 (cons 'and tagsmatcher)
13425 (car tagsmatcher))
13426 orlist)
13427 (setq tagsmatcher nil))
13428 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13429 (setq tagsmatcher
13430 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13431 ;; Make the todo matcher
13432 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13433 (setq todomatcher t)
13434 (setq orterms (org-split-string todomatch "|") orlist nil)
13435 (while (setq term (pop orterms))
13436 (while (string-match re term)
13437 (setq minus (and (match-end 1)
13438 (equal (match-string 1 term) "-"))
13439 kwd (match-string 2 term)
13440 re-p (equal (string-to-char kwd) ?{)
13441 term (substring term (match-end 0))
13442 mm (if re-p
13443 `(string-match ,(substring kwd 1 -1) todo)
13444 (list 'equal 'todo kwd))
13445 mm (if minus (list 'not mm) mm))
13446 (push mm todomatcher))
13447 (push (if (> (length todomatcher) 1)
13448 (cons 'and todomatcher)
13449 (car todomatcher))
13450 orlist)
13451 (setq todomatcher nil))
13452 (setq todomatcher (if (> (length orlist) 1)
13453 (cons 'or orlist) (car orlist))))
13455 ;; Return the string and lisp forms of the matcher
13456 (setq matcher (if todomatcher
13457 (list 'and tagsmatcher todomatcher)
13458 tagsmatcher))
13459 (when todo-only
13460 (setq matcher (list 'and '(member todo org-not-done-keywords)
13461 matcher)))
13462 (cons match0 matcher)))
13464 (defun org-op-to-function (op &optional stringp)
13465 "Turn an operator into the appropriate function."
13466 (setq op
13467 (cond
13468 ((equal op "<" ) '(< string< org-time<))
13469 ((equal op ">" ) '(> org-string> org-time>))
13470 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13471 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13472 ((member op '("=" "==")) '(= string= org-time=))
13473 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13474 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13476 (defun org<> (a b) (not (= a b)))
13477 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13478 (defun org-string>= (a b) (not (string< a b)))
13479 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13480 (defun org-string<> (a b) (not (string= a b)))
13481 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13482 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13483 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13484 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13485 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13486 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13487 (defun org-2ft (s)
13488 "Convert S to a floating point time.
13489 If S is already a number, just return it. If it is a string, parse
13490 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13491 (cond
13492 ((numberp s) s)
13493 ((stringp s)
13494 (condition-case nil
13495 (float-time (apply 'encode-time (org-parse-time-string s)))
13496 (error 0.)))
13497 (t 0.)))
13499 (defun org-time-today ()
13500 "Time in seconds today at 0:00.
13501 Returns the float number of seconds since the beginning of the
13502 epoch to the beginning of today (00:00)."
13503 (float-time (apply 'encode-time
13504 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13506 (defun org-matcher-time (s)
13507 "Interpret a time comparison value."
13508 (save-match-data
13509 (cond
13510 ((string= s "<now>") (float-time))
13511 ((string= s "<today>") (org-time-today))
13512 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13513 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13514 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13515 (+ (org-time-today)
13516 (* (string-to-number (match-string 1 s))
13517 (cdr (assoc (match-string 2 s)
13518 '(("d" . 86400.0) ("w" . 604800.0)
13519 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13520 (t (org-2ft s)))))
13522 (defun org-match-any-p (re list)
13523 "Does re match any element of list?"
13524 (setq list (mapcar (lambda (x) (string-match re x)) list))
13525 (delq nil list))
13527 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13528 (defvar org-tags-overlay (make-overlay 1 1))
13529 (org-detach-overlay org-tags-overlay)
13531 (defun org-get-local-tags-at (&optional pos)
13532 "Get a list of tags defined in the current headline."
13533 (org-get-tags-at pos 'local))
13535 (defun org-get-local-tags ()
13536 "Get a list of tags defined in the current headline."
13537 (org-get-tags-at nil 'local))
13539 (defun org-get-tags-at (&optional pos local)
13540 "Get a list of all headline tags applicable at POS.
13541 POS defaults to point. If tags are inherited, the list contains
13542 the targets in the same sequence as the headlines appear, i.e.
13543 the tags of the current headline come last.
13544 When LOCAL is non-nil, only return tags from the current headline,
13545 ignore inherited ones."
13546 (interactive)
13547 (if (and org-trust-scanner-tags
13548 (or (not pos) (equal pos (point)))
13549 (not local))
13550 org-scanner-tags
13551 (let (tags ltags lastpos parent)
13552 (save-excursion
13553 (save-restriction
13554 (widen)
13555 (goto-char (or pos (point)))
13556 (save-match-data
13557 (catch 'done
13558 (condition-case nil
13559 (progn
13560 (org-back-to-heading t)
13561 (while (not (equal lastpos (point)))
13562 (setq lastpos (point))
13563 (when (looking-at
13564 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13565 (setq ltags (org-split-string
13566 (org-match-string-no-properties 1) ":"))
13567 (when parent
13568 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13569 (setq tags (append
13570 (if parent
13571 (org-remove-uninherited-tags ltags)
13572 ltags)
13573 tags)))
13574 (or org-use-tag-inheritance (throw 'done t))
13575 (if local (throw 'done t))
13576 (or (org-up-heading-safe) (error nil))
13577 (setq parent t)))
13578 (error nil)))))
13579 (if local
13580 tags
13581 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13583 (defun org-add-prop-inherited (s)
13584 (add-text-properties 0 (length s) '(inherited t) s)
13587 (defun org-toggle-tag (tag &optional onoff)
13588 "Toggle the tag TAG for the current line.
13589 If ONOFF is `on' or `off', don't toggle but set to this state."
13590 (let (res current)
13591 (save-excursion
13592 (org-back-to-heading t)
13593 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13594 (point-at-eol) t)
13595 (progn
13596 (setq current (match-string 1))
13597 (replace-match ""))
13598 (setq current ""))
13599 (setq current (nreverse (org-split-string current ":")))
13600 (cond
13601 ((eq onoff 'on)
13602 (setq res t)
13603 (or (member tag current) (push tag current)))
13604 ((eq onoff 'off)
13605 (or (not (member tag current)) (setq current (delete tag current))))
13606 (t (if (member tag current)
13607 (setq current (delete tag current))
13608 (setq res t)
13609 (push tag current))))
13610 (end-of-line 1)
13611 (if current
13612 (progn
13613 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13614 (org-set-tags nil t))
13615 (delete-horizontal-space))
13616 (run-hooks 'org-after-tags-change-hook))
13617 res))
13619 (defun org-align-tags-here (to-col)
13620 ;; Assumes that this is a headline
13621 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13622 (beginning-of-line 1)
13623 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13624 (< pos (match-beginning 2)))
13625 (progn
13626 (setq tags-l (- (match-end 2) (match-beginning 2)))
13627 (goto-char (match-beginning 1))
13628 (insert " ")
13629 (delete-region (point) (1+ (match-beginning 2)))
13630 (setq ncol (max (current-column)
13631 (1+ col)
13632 (if (> to-col 0)
13633 to-col
13634 (- (abs to-col) tags-l))))
13635 (setq p (point))
13636 (insert (make-string (- ncol (current-column)) ?\ ))
13637 (setq ncol (current-column))
13638 (when indent-tabs-mode (tabify p (point-at-eol)))
13639 (org-move-to-column (min ncol col) t))
13640 (goto-char pos))))
13642 (defun org-set-tags-command (&optional arg just-align)
13643 "Call the set-tags command for the current entry."
13644 (interactive "P")
13645 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13646 (org-set-tags arg just-align)
13647 (save-excursion
13648 (org-back-to-heading t)
13649 (org-set-tags arg just-align))))
13651 (defun org-set-tags-to (data)
13652 "Set the tags of the current entry to DATA, replacing the current tags.
13653 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13654 If DATA is nil or the empty string, any tags will be removed."
13655 (interactive "sTags: ")
13656 (setq data
13657 (cond
13658 ((eq data nil) "")
13659 ((equal data "") "")
13660 ((stringp data)
13661 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13662 ":"))
13663 ((listp data)
13664 (concat ":" (mapconcat 'identity data ":") ":"))))
13665 (when data
13666 (save-excursion
13667 (org-back-to-heading t)
13668 (when (looking-at org-complex-heading-regexp)
13669 (if (match-end 5)
13670 (progn
13671 (goto-char (match-beginning 5))
13672 (insert data)
13673 (delete-region (point) (point-at-eol))
13674 (org-set-tags nil 'align))
13675 (goto-char (point-at-eol))
13676 (insert " " data)
13677 (org-set-tags nil 'align)))
13678 (beginning-of-line 1)
13679 (if (looking-at ".*?\\([ \t]+\\)$")
13680 (delete-region (match-beginning 1) (match-end 1))))))
13682 (defun org-align-all-tags ()
13683 "Align the tags i all headings."
13684 (interactive)
13685 (save-excursion
13686 (or (ignore-errors (org-back-to-heading t))
13687 (outline-next-heading))
13688 (if (org-at-heading-p)
13689 (org-set-tags t)
13690 (message "No headings"))))
13692 (defvar org-indent-indentation-per-level)
13693 (defun org-set-tags (&optional arg just-align)
13694 "Set the tags for the current headline.
13695 With prefix ARG, realign all tags in headings in the current buffer."
13696 (interactive "P")
13697 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13698 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13699 'region-start-level 'region))
13700 org-loop-over-headlines-in-active-region)
13701 (org-map-entries
13702 ;; We don't use ARG and JUST-ALIGN here these args are not
13703 ;; useful when looping over headlines
13704 `(org-set-tags)
13705 org-loop-over-headlines-in-active-region
13706 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13707 (let* ((re org-outline-regexp-bol)
13708 (current (unless arg (org-get-tags-string)))
13709 (col (current-column))
13710 (org-setting-tags t)
13711 table current-tags inherited-tags ; computed below when needed
13712 tags p0 c0 c1 rpl di tc level)
13713 (if arg
13714 (save-excursion
13715 (goto-char (point-min))
13716 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13717 (while (re-search-forward re nil t)
13718 (org-set-tags nil t)
13719 (end-of-line 1)))
13720 (message "All tags realigned to column %d" org-tags-column))
13721 (if just-align
13722 (setq tags current)
13723 ;; Get a new set of tags from the user
13724 (save-excursion
13725 (setq table (append org-tag-persistent-alist
13726 (or org-tag-alist (org-get-buffer-tags))
13727 (and
13728 org-complete-tags-always-offer-all-agenda-tags
13729 (org-global-tags-completion-table
13730 (org-agenda-files))))
13731 org-last-tags-completion-table table
13732 current-tags (org-split-string current ":")
13733 inherited-tags (nreverse
13734 (nthcdr (length current-tags)
13735 (nreverse (org-get-tags-at))))
13736 tags
13737 (if (or (eq t org-use-fast-tag-selection)
13738 (and org-use-fast-tag-selection
13739 (delq nil (mapcar 'cdr table))))
13740 (org-fast-tag-selection
13741 current-tags inherited-tags table
13742 (if org-fast-tag-selection-include-todo
13743 org-todo-key-alist))
13744 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13745 (org-trim
13746 (org-icompleting-read "Tags: "
13747 'org-tags-completion-function
13748 nil nil current 'org-tags-history))))))
13749 (while (string-match "[-+&]+" tags)
13750 ;; No boolean logic, just a list
13751 (setq tags (replace-match ":" t t tags))))
13753 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13755 (if org-tags-sort-function
13756 (setq tags (mapconcat 'identity
13757 (sort (org-split-string
13758 tags (org-re "[^[:alnum:]_@#%]+"))
13759 org-tags-sort-function) ":")))
13761 (if (string-match "\\`[\t ]*\\'" tags)
13762 (setq tags "")
13763 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13764 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13766 ;; Insert new tags at the correct column
13767 (beginning-of-line 1)
13768 (setq level (or (and (looking-at org-outline-regexp)
13769 (- (match-end 0) (point) 1))
13771 (cond
13772 ((and (equal current "") (equal tags "")))
13773 ((re-search-forward
13774 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13775 (point-at-eol) t)
13776 (if (equal tags "")
13777 (setq rpl "")
13778 (goto-char (match-beginning 0))
13779 (setq c0 (current-column)
13780 ;; compute offset for the case of org-indent-mode active
13781 di (if org-indent-mode
13782 (* (1- org-indent-indentation-per-level) (1- level))
13784 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13785 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13786 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13787 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13788 (replace-match rpl t t)
13789 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13790 tags)
13791 (t (error "Tags alignment failed")))
13792 (org-move-to-column col)
13793 (unless just-align
13794 (run-hooks 'org-after-tags-change-hook))))))
13796 (defun org-change-tag-in-region (beg end tag off)
13797 "Add or remove TAG for each entry in the region.
13798 This works in the agenda, and also in an org-mode buffer."
13799 (interactive
13800 (list (region-beginning) (region-end)
13801 (let ((org-last-tags-completion-table
13802 (if (derived-mode-p 'org-mode)
13803 (org-get-buffer-tags)
13804 (org-global-tags-completion-table))))
13805 (org-icompleting-read
13806 "Tag: " 'org-tags-completion-function nil nil nil
13807 'org-tags-history))
13808 (progn
13809 (message "[s]et or [r]emove? ")
13810 (equal (read-char-exclusive) ?r))))
13811 (if (fboundp 'deactivate-mark) (deactivate-mark))
13812 (let ((agendap (equal major-mode 'org-agenda-mode))
13813 l1 l2 m buf pos newhead (cnt 0))
13814 (goto-char end)
13815 (setq l2 (1- (org-current-line)))
13816 (goto-char beg)
13817 (setq l1 (org-current-line))
13818 (loop for l from l1 to l2 do
13819 (org-goto-line l)
13820 (setq m (get-text-property (point) 'org-hd-marker))
13821 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13822 (and agendap m))
13823 (setq buf (if agendap (marker-buffer m) (current-buffer))
13824 pos (if agendap m (point)))
13825 (with-current-buffer buf
13826 (save-excursion
13827 (save-restriction
13828 (goto-char pos)
13829 (setq cnt (1+ cnt))
13830 (org-toggle-tag tag (if off 'off 'on))
13831 (setq newhead (org-get-heading)))))
13832 (and agendap (org-agenda-change-all-lines newhead m))))
13833 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13835 (defun org-tags-completion-function (string predicate &optional flag)
13836 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13837 (confirm (lambda (x) (stringp (car x)))))
13838 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13839 (setq s1 (match-string 1 string)
13840 s2 (match-string 2 string))
13841 (setq s1 "" s2 string))
13842 (cond
13843 ((eq flag nil)
13844 ;; try completion
13845 (setq rtn (try-completion s2 ctable confirm))
13846 (if (stringp rtn)
13847 (setq rtn
13848 (concat s1 s2 (substring rtn (length s2))
13849 (if (and org-add-colon-after-tag-completion
13850 (assoc rtn ctable))
13851 ":" ""))))
13852 rtn)
13853 ((eq flag t)
13854 ;; all-completions
13855 (all-completions s2 ctable confirm)
13857 ((eq flag 'lambda)
13858 ;; exact match?
13859 (assoc s2 ctable)))
13862 (defun org-fast-tag-insert (kwd tags face &optional end)
13863 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13864 (insert (format "%-12s" (concat kwd ":"))
13865 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13866 (or end "")))
13868 (defun org-fast-tag-show-exit (flag)
13869 (save-excursion
13870 (org-goto-line 3)
13871 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13872 (replace-match ""))
13873 (when flag
13874 (end-of-line 1)
13875 (org-move-to-column (- (window-width) 19) t)
13876 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13878 (defun org-set-current-tags-overlay (current prefix)
13879 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13880 (if (featurep 'xemacs)
13881 (org-overlay-display org-tags-overlay (concat prefix s)
13882 'secondary-selection)
13883 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13884 (org-overlay-display org-tags-overlay (concat prefix s)))))
13886 (defvar org-last-tag-selection-key nil)
13887 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13888 "Fast tag selection with single keys.
13889 CURRENT is the current list of tags in the headline, INHERITED is the
13890 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13891 possibly with grouping information. TODO-TABLE is a similar table with
13892 TODO keywords, should these have keys assigned to them.
13893 If the keys are nil, a-z are automatically assigned.
13894 Returns the new tags string, or nil to not change the current settings."
13895 (let* ((fulltable (append table todo-table))
13896 (maxlen (apply 'max (mapcar
13897 (lambda (x)
13898 (if (stringp (car x)) (string-width (car x)) 0))
13899 fulltable)))
13900 (buf (current-buffer))
13901 (expert (eq org-fast-tag-selection-single-key 'expert))
13902 (buffer-tags nil)
13903 (fwidth (+ maxlen 3 1 3))
13904 (ncol (/ (- (window-width) 4) fwidth))
13905 (i-face 'org-done)
13906 (c-face 'org-todo)
13907 tg cnt e c char c1 c2 ntable tbl rtn
13908 ov-start ov-end ov-prefix
13909 (exit-after-next org-fast-tag-selection-single-key)
13910 (done-keywords org-done-keywords)
13911 groups ingroup)
13912 (save-excursion
13913 (beginning-of-line 1)
13914 (if (looking-at
13915 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13916 (setq ov-start (match-beginning 1)
13917 ov-end (match-end 1)
13918 ov-prefix "")
13919 (setq ov-start (1- (point-at-eol))
13920 ov-end (1+ ov-start))
13921 (skip-chars-forward "^\n\r")
13922 (setq ov-prefix
13923 (concat
13924 (buffer-substring (1- (point)) (point))
13925 (if (> (current-column) org-tags-column)
13927 (make-string (- org-tags-column (current-column)) ?\ ))))))
13928 (move-overlay org-tags-overlay ov-start ov-end)
13929 (save-window-excursion
13930 (if expert
13931 (set-buffer (get-buffer-create " *Org tags*"))
13932 (delete-other-windows)
13933 (split-window-vertically)
13934 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13935 (erase-buffer)
13936 (org-set-local 'org-done-keywords done-keywords)
13937 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13938 (org-fast-tag-insert "Current" current c-face "\n\n")
13939 (org-fast-tag-show-exit exit-after-next)
13940 (org-set-current-tags-overlay current ov-prefix)
13941 (setq tbl fulltable char ?a cnt 0)
13942 (while (setq e (pop tbl))
13943 (cond
13944 ((equal (car e) :startgroup)
13945 (push '() groups) (setq ingroup t)
13946 (when (not (= cnt 0))
13947 (setq cnt 0)
13948 (insert "\n"))
13949 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13950 ((equal (car e) :endgroup)
13951 (setq ingroup nil cnt 0)
13952 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13953 ((equal e '(:newline))
13954 (when (not (= cnt 0))
13955 (setq cnt 0)
13956 (insert "\n")
13957 (setq e (car tbl))
13958 (while (equal (car tbl) '(:newline))
13959 (insert "\n")
13960 (setq tbl (cdr tbl)))))
13962 (setq tg (copy-sequence (car e)) c2 nil)
13963 (if (cdr e)
13964 (setq c (cdr e))
13965 ;; automatically assign a character.
13966 (setq c1 (string-to-char
13967 (downcase (substring
13968 tg (if (= (string-to-char tg) ?@) 1 0)))))
13969 (if (or (rassoc c1 ntable) (rassoc c1 table))
13970 (while (or (rassoc char ntable) (rassoc char table))
13971 (setq char (1+ char)))
13972 (setq c2 c1))
13973 (setq c (or c2 char)))
13974 (if ingroup (push tg (car groups)))
13975 (setq tg (org-add-props tg nil 'face
13976 (cond
13977 ((not (assoc tg table))
13978 (org-get-todo-face tg))
13979 ((member tg current) c-face)
13980 ((member tg inherited) i-face))))
13981 (if (and (= cnt 0) (not ingroup)) (insert " "))
13982 (insert "[" c "] " tg (make-string
13983 (- fwidth 4 (length tg)) ?\ ))
13984 (push (cons tg c) ntable)
13985 (when (= (setq cnt (1+ cnt)) ncol)
13986 (insert "\n")
13987 (if ingroup (insert " "))
13988 (setq cnt 0)))))
13989 (setq ntable (nreverse ntable))
13990 (insert "\n")
13991 (goto-char (point-min))
13992 (if (not expert) (org-fit-window-to-buffer))
13993 (setq rtn
13994 (catch 'exit
13995 (while t
13996 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13997 (if (not groups) "no " "")
13998 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13999 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14000 (setq org-last-tag-selection-key c)
14001 (cond
14002 ((= c ?\r) (throw 'exit t))
14003 ((= c ?!)
14004 (setq groups (not groups))
14005 (goto-char (point-min))
14006 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14007 ((= c ?\C-c)
14008 (if (not expert)
14009 (org-fast-tag-show-exit
14010 (setq exit-after-next (not exit-after-next)))
14011 (setq expert nil)
14012 (delete-other-windows)
14013 (set-window-buffer (split-window-vertically) " *Org tags*")
14014 (org-switch-to-buffer-other-window " *Org tags*")
14015 (org-fit-window-to-buffer)))
14016 ((or (= c ?\C-g)
14017 (and (= c ?q) (not (rassoc c ntable))))
14018 (org-detach-overlay org-tags-overlay)
14019 (setq quit-flag t))
14020 ((= c ?\ )
14021 (setq current nil)
14022 (if exit-after-next (setq exit-after-next 'now)))
14023 ((= c ?\t)
14024 (condition-case nil
14025 (setq tg (org-icompleting-read
14026 "Tag: "
14027 (or buffer-tags
14028 (with-current-buffer buf
14029 (org-get-buffer-tags)))))
14030 (quit (setq tg "")))
14031 (when (string-match "\\S-" tg)
14032 (add-to-list 'buffer-tags (list tg))
14033 (if (member tg current)
14034 (setq current (delete tg current))
14035 (push tg current)))
14036 (if exit-after-next (setq exit-after-next 'now)))
14037 ((setq e (rassoc c todo-table) tg (car e))
14038 (with-current-buffer buf
14039 (save-excursion (org-todo tg)))
14040 (if exit-after-next (setq exit-after-next 'now)))
14041 ((setq e (rassoc c ntable) tg (car e))
14042 (if (member tg current)
14043 (setq current (delete tg current))
14044 (loop for g in groups do
14045 (if (member tg g)
14046 (mapc (lambda (x)
14047 (setq current (delete x current)))
14048 g)))
14049 (push tg current))
14050 (if exit-after-next (setq exit-after-next 'now))))
14052 ;; Create a sorted list
14053 (setq current
14054 (sort current
14055 (lambda (a b)
14056 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14057 (if (eq exit-after-next 'now) (throw 'exit t))
14058 (goto-char (point-min))
14059 (beginning-of-line 2)
14060 (delete-region (point) (point-at-eol))
14061 (org-fast-tag-insert "Current" current c-face)
14062 (org-set-current-tags-overlay current ov-prefix)
14063 (while (re-search-forward
14064 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14065 (setq tg (match-string 1))
14066 (add-text-properties
14067 (match-beginning 1) (match-end 1)
14068 (list 'face
14069 (cond
14070 ((member tg current) c-face)
14071 ((member tg inherited) i-face)
14072 (t (get-text-property (match-beginning 1) 'face))))))
14073 (goto-char (point-min)))))
14074 (org-detach-overlay org-tags-overlay)
14075 (if rtn
14076 (mapconcat 'identity current ":")
14077 nil))))
14079 (defun org-get-tags-string ()
14080 "Get the TAGS string in the current headline."
14081 (unless (org-at-heading-p t)
14082 (error "Not on a heading"))
14083 (save-excursion
14084 (beginning-of-line 1)
14085 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14086 (org-match-string-no-properties 1)
14087 "")))
14089 (defun org-get-tags ()
14090 "Get the list of tags specified in the current headline."
14091 (org-split-string (org-get-tags-string) ":"))
14093 (defun org-get-buffer-tags ()
14094 "Get a table of all tags used in the buffer, for completion."
14095 (let (tags)
14096 (save-excursion
14097 (goto-char (point-min))
14098 (while (re-search-forward
14099 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14100 (when (equal (char-after (point-at-bol 0)) ?*)
14101 (mapc (lambda (x) (add-to-list 'tags x))
14102 (org-split-string (org-match-string-no-properties 1) ":")))))
14103 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14104 (mapcar 'list tags)))
14106 ;;;; The mapping API
14108 (defun org-map-entries (func &optional match scope &rest skip)
14109 "Call FUNC at each headline selected by MATCH in SCOPE.
14111 FUNC is a function or a lisp form. The function will be called without
14112 arguments, with the cursor positioned at the beginning of the headline.
14113 The return values of all calls to the function will be collected and
14114 returned as a list.
14116 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14117 does not need to preserve point. After evaluation, the cursor will be
14118 moved to the end of the line (presumably of the headline of the
14119 processed entry) and search continues from there. Under some
14120 circumstances, this may not produce the wanted results. For example,
14121 if you have removed (e.g. archived) the current (sub)tree it could
14122 mean that the next entry will be skipped entirely. In such cases, you
14123 can specify the position from where search should continue by making
14124 FUNC set the variable `org-map-continue-from' to the desired buffer
14125 position.
14127 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14128 Only headlines that are matched by this query will be considered during
14129 the iteration. When MATCH is nil or t, all headlines will be
14130 visited by the iteration.
14132 SCOPE determines the scope of this command. It can be any of:
14134 nil The current buffer, respecting the restriction if any
14135 tree The subtree started with the entry at point
14136 region The entries within the active region, if any
14137 region-start-level
14138 The entries within the active region, but only those at
14139 the same level than the first one.
14140 file The current buffer, without restriction
14141 file-with-archives
14142 The current buffer, and any archives associated with it
14143 agenda All agenda files
14144 agenda-with-archives
14145 All agenda files with any archive files associated with them
14146 \(file1 file2 ...)
14147 If this is a list, all files in the list will be scanned
14149 The remaining args are treated as settings for the skipping facilities of
14150 the scanner. The following items can be given here:
14152 archive skip trees with the archive tag.
14153 comment skip trees with the COMMENT keyword
14154 function or Emacs Lisp form:
14155 will be used as value for `org-agenda-skip-function', so whenever
14156 the function returns t, FUNC will not be called for that
14157 entry and search will continue from the point where the
14158 function leaves it.
14160 If your function needs to retrieve the tags including inherited tags
14161 at the *current* entry, you can use the value of the variable
14162 `org-scanner-tags' which will be much faster than getting the value
14163 with `org-get-tags-at'. If your function gets properties with
14164 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14165 to t around the call to `org-entry-properties' to get the same speedup.
14166 Note that if your function moves around to retrieve tags and properties at
14167 a *different* entry, you cannot use these techniques."
14168 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14169 (not (org-region-active-p)))
14170 (let* ((org-agenda-archives-mode nil) ; just to make sure
14171 (org-agenda-skip-archived-trees (memq 'archive skip))
14172 (org-agenda-skip-comment-trees (memq 'comment skip))
14173 (org-agenda-skip-function
14174 (car (org-delete-all '(comment archive) skip)))
14175 (org-tags-match-list-sublevels t)
14176 (start-level (eq scope 'region-start-level))
14177 matcher file res
14178 org-todo-keywords-for-agenda
14179 org-done-keywords-for-agenda
14180 org-todo-keyword-alist-for-agenda
14181 org-drawers-for-agenda
14182 org-tag-alist-for-agenda
14183 todo-only)
14185 (cond
14186 ((eq match t) (setq matcher t))
14187 ((eq match nil) (setq matcher t))
14188 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14190 (save-excursion
14191 (save-restriction
14192 (cond ((eq scope 'tree)
14193 (org-back-to-heading t)
14194 (org-narrow-to-subtree)
14195 (setq scope nil))
14196 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14197 (org-region-active-p))
14198 ;; If needed, set start-level to a string like "2"
14199 (when start-level
14200 (save-excursion
14201 (goto-char (region-beginning))
14202 (unless (org-at-heading-p) (outline-next-heading))
14203 (setq start-level (org-current-level))))
14204 (narrow-to-region (region-beginning)
14205 (save-excursion
14206 (goto-char (region-end))
14207 (unless (and (bolp) (org-at-heading-p))
14208 (outline-next-heading))
14209 (point)))
14210 (setq scope nil)))
14212 (if (not scope)
14213 (progn
14214 (org-agenda-prepare-buffers
14215 (list (buffer-file-name (current-buffer))))
14216 (setq res (org-scan-tags func matcher todo-only start-level)))
14217 ;; Get the right scope
14218 (cond
14219 ((and scope (listp scope) (symbolp (car scope)))
14220 (setq scope (eval scope)))
14221 ((eq scope 'agenda)
14222 (setq scope (org-agenda-files t)))
14223 ((eq scope 'agenda-with-archives)
14224 (setq scope (org-agenda-files t))
14225 (setq scope (org-add-archive-files scope)))
14226 ((eq scope 'file)
14227 (setq scope (list (buffer-file-name))))
14228 ((eq scope 'file-with-archives)
14229 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14230 (org-agenda-prepare-buffers scope)
14231 (while (setq file (pop scope))
14232 (with-current-buffer (org-find-base-buffer-visiting file)
14233 (save-excursion
14234 (save-restriction
14235 (widen)
14236 (goto-char (point-min))
14237 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14238 res)))
14240 ;;;; Properties
14242 ;;; Setting and retrieving properties
14244 (defconst org-special-properties
14245 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14246 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14247 "The special properties valid in Org-mode.
14249 These are properties that are not defined in the property drawer,
14250 but in some other way.")
14252 (defconst org-default-properties
14253 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14254 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14255 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14256 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14257 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14258 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14259 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14260 "Some properties that are used by Org-mode for various purposes.
14261 Being in this list makes sure that they are offered for completion.")
14263 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14264 "Regular expression matching the first line of a property drawer.")
14266 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14267 "Regular expression matching the last line of a property drawer.")
14269 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14270 "Regular expression matching the first line of a property drawer.")
14272 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14273 "Regular expression matching the first line of a property drawer.")
14275 (defconst org-property-drawer-re
14276 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14277 org-property-end-re "\\)\n?")
14278 "Matches an entire property drawer.")
14280 (defconst org-clock-drawer-re
14281 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14282 org-property-end-re "\\)\n?")
14283 "Matches an entire clock drawer.")
14285 (defsubst org-re-property (property)
14286 "Return a regexp matching a PROPERTY line.
14287 Match group 1 will be set to the value."
14288 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14290 (defsubst org-re-property-keyword (property)
14291 "Return a regexp matching a PROPERTY line, possibly with no
14292 value for the property."
14293 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14295 (defun org-property-action ()
14296 "Do an action on properties."
14297 (interactive)
14298 (let (c)
14299 (org-at-property-p)
14300 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14301 (setq c (read-char-exclusive))
14302 (cond
14303 ((equal c ?s)
14304 (call-interactively 'org-set-property))
14305 ((equal c ?d)
14306 (call-interactively 'org-delete-property))
14307 ((equal c ?D)
14308 (call-interactively 'org-delete-property-globally))
14309 ((equal c ?c)
14310 (call-interactively 'org-compute-property-at-point))
14311 (t (error "No such property action %c" c)))))
14313 (defun org-inc-effort ()
14314 "Increment the value of the effort property in the current entry."
14315 (interactive)
14316 (org-set-effort nil t))
14318 (defun org-set-effort (&optional value increment)
14319 "Set the effort property of the current entry.
14320 With numerical prefix arg, use the nth allowed value, 0 stands for the
14321 10th allowed value.
14323 When INCREMENT is non-nil, set the property to the next allowed value."
14324 (interactive "P")
14325 (if (equal value 0) (setq value 10))
14326 (let* ((completion-ignore-case t)
14327 (prop org-effort-property)
14328 (cur (org-entry-get nil prop))
14329 (allowed (org-property-get-allowed-values nil prop 'table))
14330 (existing (mapcar 'list (org-property-values prop)))
14332 (val (cond
14333 ((stringp value) value)
14334 ((and allowed (integerp value))
14335 (or (car (nth (1- value) allowed))
14336 (car (org-last allowed))))
14337 ((and allowed increment)
14338 (or (caadr (member (list cur) allowed))
14339 (error "Allowed effort values are not set")))
14340 (allowed
14341 (message "Select 1-9,0, [RET%s]: %s"
14342 (if cur (concat "=" cur) "")
14343 (mapconcat 'car allowed " "))
14344 (setq rpl (read-char-exclusive))
14345 (if (equal rpl ?\r)
14347 (setq rpl (- rpl ?0))
14348 (if (equal rpl 0) (setq rpl 10))
14349 (if (and (> rpl 0) (<= rpl (length allowed)))
14350 (car (nth (1- rpl) allowed))
14351 (org-completing-read "Effort: " allowed nil))))
14353 (let (org-completion-use-ido org-completion-use-iswitchb)
14354 (org-completing-read
14355 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14356 (concat "[" cur "]") "")
14357 ": ")
14358 existing nil nil "" nil cur))))))
14359 (unless (equal (org-entry-get nil prop) val)
14360 (org-entry-put nil prop val))
14361 (message "%s is now %s" prop val)))
14363 (defun org-at-property-p ()
14364 "Is cursor inside a property drawer?"
14365 (save-excursion
14366 (beginning-of-line 1)
14367 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14368 (save-match-data ;; Used by calling procedures
14369 (let ((p (point))
14370 (range (unless (org-before-first-heading-p)
14371 (org-get-property-block))))
14372 (and range (<= (car range) p) (< p (cdr range))))))))
14374 (defun org-get-property-block (&optional beg end force)
14375 "Return the (beg . end) range of the body of the property drawer.
14376 BEG and END are the beginning and end of the current subtree, or of
14377 the part before the first headline. If they are not given, they will
14378 be found. If the drawer does not exist and FORCE is non-nil, create
14379 the drawer."
14380 (catch 'exit
14381 (save-excursion
14382 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14383 (progn (org-back-to-heading t) (point))))
14384 (end (or end (and (not (outline-next-heading)) (point-max))
14385 (point))))
14386 (goto-char beg)
14387 (if (re-search-forward org-property-start-re end t)
14388 (setq beg (1+ (match-end 0)))
14389 (if force
14390 (save-excursion
14391 (org-insert-property-drawer)
14392 (setq end (progn (outline-next-heading) (point))))
14393 (throw 'exit nil))
14394 (goto-char beg)
14395 (if (re-search-forward org-property-start-re end t)
14396 (setq beg (1+ (match-end 0)))))
14397 (if (re-search-forward org-property-end-re end t)
14398 (setq end (match-beginning 0))
14399 (or force (throw 'exit nil))
14400 (goto-char beg)
14401 (setq end beg)
14402 (org-indent-line)
14403 (insert ":END:\n"))
14404 (cons beg end)))))
14406 (defun org-entry-properties (&optional pom which specific)
14407 "Get all properties of the entry at point-or-marker POM.
14408 This includes the TODO keyword, the tags, time strings for deadline,
14409 scheduled, and clocking, and any additional properties defined in the
14410 entry. The return value is an alist, keys may occur multiple times
14411 if the property key was used several times.
14412 POM may also be nil, in which case the current entry is used.
14413 If WHICH is nil or `all', get all properties. If WHICH is
14414 `special' or `standard', only get that subclass. If WHICH
14415 is a string only get exactly this property. SPECIFIC can be a string, the
14416 specific property we are interested in. Specifying it can speed
14417 things up because then unnecessary parsing is avoided."
14418 (setq which (or which 'all))
14419 (org-with-point-at pom
14420 (let ((clockstr (substring org-clock-string 0 -1))
14421 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14422 (case-fold-search nil)
14423 beg end range props sum-props key key1 value string clocksum clocksumt)
14424 (save-excursion
14425 (when (condition-case nil
14426 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14427 (error nil))
14428 (setq beg (point))
14429 (setq sum-props (get-text-property (point) 'org-summaries))
14430 (setq clocksum (get-text-property (point) :org-clock-minutes)
14431 clocksumt (get-text-property (point) :org-clock-minutes-today))
14432 (outline-next-heading)
14433 (setq end (point))
14434 (when (memq which '(all special))
14435 ;; Get the special properties, like TODO and tags
14436 (goto-char beg)
14437 (when (and (or (not specific) (string= specific "TODO"))
14438 (looking-at org-todo-line-regexp) (match-end 2))
14439 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14440 (when (and (or (not specific) (string= specific "PRIORITY"))
14441 (looking-at org-priority-regexp))
14442 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14443 (when (or (not specific) (string= specific "FILE"))
14444 (push (cons "FILE" buffer-file-name) props))
14445 (when (and (or (not specific) (string= specific "TAGS"))
14446 (setq value (org-get-tags-string))
14447 (string-match "\\S-" value))
14448 (push (cons "TAGS" value) props))
14449 (when (and (or (not specific) (string= specific "ALLTAGS"))
14450 (setq value (org-get-tags-at)))
14451 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14452 ":"))
14453 props))
14454 (when (or (not specific) (string= specific "BLOCKED"))
14455 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14456 (when (or (not specific)
14457 (member specific
14458 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14459 "TIMESTAMP" "TIMESTAMP_IA")))
14460 (catch 'match
14461 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14462 (setq key (if (match-end 1)
14463 (substring (org-match-string-no-properties 1)
14464 0 -1))
14465 string (if (equal key clockstr)
14466 (org-trim
14467 (buffer-substring-no-properties
14468 (match-beginning 3) (goto-char
14469 (point-at-eol))))
14470 (substring (org-match-string-no-properties 3)
14471 1 -1)))
14472 ;; Get the correct property name from the key. This is
14473 ;; necessary if the user has configured time keywords.
14474 (setq key1 (concat key ":"))
14475 (cond
14476 ((not key)
14477 (setq key
14478 (if (= (char-after (match-beginning 3)) ?\[)
14479 "TIMESTAMP_IA" "TIMESTAMP")))
14480 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14481 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14482 ((equal key1 org-closed-string) (setq key "CLOSED"))
14483 ((equal key1 org-clock-string) (setq key "CLOCK")))
14484 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14485 (progn
14486 (push (cons key string) props)
14487 ;; no need to search further if match is found
14488 (throw 'match t))
14489 (when (or (equal key "CLOCK") (not (assoc key props)))
14490 (push (cons key string) props)))))))
14492 (when (memq which '(all standard))
14493 ;; Get the standard properties, like :PROP: ...
14494 (setq range (org-get-property-block beg end))
14495 (when range
14496 (goto-char (car range))
14497 (while (re-search-forward
14498 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14499 (cdr range) t)
14500 (setq key (org-match-string-no-properties 1)
14501 value (org-trim (or (org-match-string-no-properties 2) "")))
14502 (unless (member key excluded)
14503 (push (cons key (or value "")) props)))))
14504 (if clocksum
14505 (push (cons "CLOCKSUM"
14506 (org-columns-number-to-string (/ (float clocksum) 60.)
14507 'add_times))
14508 props))
14509 (if clocksumt
14510 (push (cons "CLOCKSUM_T"
14511 (org-columns-number-to-string (/ (float clocksumt) 60.)
14512 'add_times))
14513 props))
14514 (unless (assoc "CATEGORY" props)
14515 (push (cons "CATEGORY" (org-get-category)) props))
14516 (append sum-props (nreverse props)))))))
14518 (defun org-entry-get (pom property &optional inherit literal-nil)
14519 "Get value of PROPERTY for entry or content at point-or-marker POM.
14520 If INHERIT is non-nil and the entry does not have the property,
14521 then also check higher levels of the hierarchy.
14522 If INHERIT is the symbol `selective', use inheritance only if the setting
14523 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14524 If the property is present but empty, the return value is the empty string.
14525 If the property is not present at all, nil is returned.
14527 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14528 do not interpret it as the list atom nil. This is used for inheritance
14529 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14530 (org-with-point-at pom
14531 (if (and inherit (if (eq inherit 'selective)
14532 (org-property-inherit-p property)
14534 (org-entry-get-with-inheritance property literal-nil)
14535 (if (member property org-special-properties)
14536 ;; We need a special property. Use `org-entry-properties' to
14537 ;; retrieve it, but specify the wanted property
14538 (cdr (assoc property (org-entry-properties nil 'special property)))
14539 (let* ((range (org-get-property-block))
14540 (props (list (or (assoc property org-file-properties)
14541 (assoc property org-global-properties)
14542 (assoc property org-global-properties-fixed))))
14543 (ap (lambda (key)
14544 (when (re-search-forward
14545 (org-re-property key) (cdr range) t)
14546 (setq props
14547 (org-update-property-plist
14549 (if (match-end 1)
14550 (org-match-string-no-properties 1) "")
14551 props)))))
14552 val)
14553 (when (and range (goto-char (car range)))
14554 (funcall ap property)
14555 (goto-char (car range))
14556 (while (funcall ap (concat property "+")))
14557 (setq val (cdr (assoc property props)))
14558 (when val (if literal-nil val (org-not-nil val)))))))))
14560 (defun org-property-or-variable-value (var &optional inherit)
14561 "Check if there is a property fixing the value of VAR.
14562 If yes, return this value. If not, return the current value of the variable."
14563 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14564 (if (and prop (stringp prop) (string-match "\\S-" prop))
14565 (read prop)
14566 (symbol-value var))))
14568 (defun org-entry-delete (pom property)
14569 "Delete the property PROPERTY from entry at point-or-marker POM."
14570 (org-with-point-at pom
14571 (if (member property org-special-properties)
14572 nil ; cannot delete these properties.
14573 (let ((range (org-get-property-block)))
14574 (if (and range
14575 (goto-char (car range))
14576 (re-search-forward
14577 (org-re-property property)
14578 (cdr range) t))
14579 (progn
14580 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14582 nil)))))
14584 ;; Multi-values properties are properties that contain multiple values
14585 ;; These values are assumed to be single words, separated by whitespace.
14586 (defun org-entry-add-to-multivalued-property (pom property value)
14587 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14588 (let* ((old (org-entry-get pom property))
14589 (values (and old (org-split-string old "[ \t]"))))
14590 (setq value (org-entry-protect-space value))
14591 (unless (member value values)
14592 (setq values (cons value values))
14593 (org-entry-put pom property
14594 (mapconcat 'identity values " ")))))
14596 (defun org-entry-remove-from-multivalued-property (pom property value)
14597 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14598 (let* ((old (org-entry-get pom property))
14599 (values (and old (org-split-string old "[ \t]"))))
14600 (setq value (org-entry-protect-space value))
14601 (when (member value values)
14602 (setq values (delete value values))
14603 (org-entry-put pom property
14604 (mapconcat 'identity values " ")))))
14606 (defun org-entry-member-in-multivalued-property (pom property value)
14607 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14608 (let* ((old (org-entry-get pom property))
14609 (values (and old (org-split-string old "[ \t]"))))
14610 (setq value (org-entry-protect-space value))
14611 (member value values)))
14613 (defun org-entry-get-multivalued-property (pom property)
14614 "Return a list of values in a multivalued property."
14615 (let* ((value (org-entry-get pom property))
14616 (values (and value (org-split-string value "[ \t]"))))
14617 (mapcar 'org-entry-restore-space values)))
14619 (defun org-entry-put-multivalued-property (pom property &rest values)
14620 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14621 VALUES should be a list of strings. Spaces will be protected."
14622 (org-entry-put pom property
14623 (mapconcat 'org-entry-protect-space values " "))
14624 (let* ((value (org-entry-get pom property))
14625 (values (and value (org-split-string value "[ \t]"))))
14626 (mapcar 'org-entry-restore-space values)))
14628 (defun org-entry-protect-space (s)
14629 "Protect spaces and newline in string S."
14630 (while (string-match " " s)
14631 (setq s (replace-match "%20" t t s)))
14632 (while (string-match "\n" s)
14633 (setq s (replace-match "%0A" t t s)))
14636 (defun org-entry-restore-space (s)
14637 "Restore spaces and newline in string S."
14638 (while (string-match "%20" s)
14639 (setq s (replace-match " " t t s)))
14640 (while (string-match "%0A" s)
14641 (setq s (replace-match "\n" t t s)))
14644 (defvar org-entry-property-inherited-from (make-marker)
14645 "Marker pointing to the entry from where a property was inherited.
14646 Each call to `org-entry-get-with-inheritance' will set this marker to the
14647 location of the entry where the inheritance search matched. If there was
14648 no match, the marker will point nowhere.
14649 Note that also `org-entry-get' calls this function, if the INHERIT flag
14650 is set.")
14652 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14653 "Get PROPERTY of entry or content at point, search higher levels if needed.
14654 The search will stop at the first ancestor which has the property defined.
14655 If the value found is \"nil\", return nil to show that the property
14656 should be considered as undefined (this is the meaning of nil here).
14657 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14658 (move-marker org-entry-property-inherited-from nil)
14659 (let (tmp)
14660 (save-excursion
14661 (save-restriction
14662 (widen)
14663 (catch 'ex
14664 (while t
14665 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14666 (or (ignore-errors (org-back-to-heading t))
14667 (goto-char (point-min)))
14668 (move-marker org-entry-property-inherited-from (point))
14669 (throw 'ex tmp))
14670 (or (ignore-errors (org-up-heading-safe))
14671 (throw 'ex nil))))))
14672 (setq tmp (or tmp
14673 (cdr (assoc property org-file-properties))
14674 (cdr (assoc property org-global-properties))
14675 (cdr (assoc property org-global-properties-fixed))))
14676 (if literal-nil tmp (org-not-nil tmp))))
14678 (defvar org-property-changed-functions nil
14679 "Hook called when the value of a property has changed.
14680 Each hook function should accept two arguments, the name of the property
14681 and the new value.")
14683 (defun org-entry-put (pom property value)
14684 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14685 (org-with-point-at pom
14686 (org-back-to-heading t)
14687 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14688 range)
14689 (cond
14690 ((equal property "TODO")
14691 (when (and (stringp value) (string-match "\\S-" value)
14692 (not (member value org-todo-keywords-1)))
14693 (error "\"%s\" is not a valid TODO state" value))
14694 (if (or (not value)
14695 (not (string-match "\\S-" value)))
14696 (setq value 'none))
14697 (org-todo value)
14698 (org-set-tags nil 'align))
14699 ((equal property "PRIORITY")
14700 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14701 (string-to-char value) ?\ ))
14702 (org-set-tags nil 'align))
14703 ((equal property "CLOCKSUM")
14704 (if (not (re-search-forward
14705 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14706 (error "Cannot find a clock log")
14707 (goto-char (- (match-end 1) 2))
14708 (cond
14709 ((eq value 'earlier) (org-timestamp-down))
14710 ((eq value 'later) (org-timestamp-up)))
14711 (org-clock-sum-current-item)))
14712 ((equal property "SCHEDULED")
14713 (if (re-search-forward org-scheduled-time-regexp end t)
14714 (cond
14715 ((eq value 'earlier) (org-timestamp-change -1 'day))
14716 ((eq value 'later) (org-timestamp-change 1 'day))
14717 (t (call-interactively 'org-schedule)))
14718 (call-interactively 'org-schedule)))
14719 ((equal property "DEADLINE")
14720 (if (re-search-forward org-deadline-time-regexp end t)
14721 (cond
14722 ((eq value 'earlier) (org-timestamp-change -1 'day))
14723 ((eq value 'later) (org-timestamp-change 1 'day))
14724 (t (call-interactively 'org-deadline)))
14725 (call-interactively 'org-deadline)))
14726 ((member property org-special-properties)
14727 (error "The %s property can not yet be set with `org-entry-put'"
14728 property))
14729 (t ; a non-special property
14730 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14731 (setq range (org-get-property-block beg end 'force))
14732 (goto-char (car range))
14733 (if (re-search-forward
14734 (org-re-property-keyword property) (cdr range) t)
14735 (progn
14736 (delete-region (match-beginning 0) (match-end 0))
14737 (goto-char (match-beginning 0)))
14738 (goto-char (cdr range))
14739 (insert "\n")
14740 (backward-char 1)
14741 (org-indent-line))
14742 (insert ":" property ":")
14743 (and value (insert " " value))
14744 (org-indent-line)))))
14745 (run-hook-with-args 'org-property-changed-functions property value)))
14747 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14748 "Get all property keys in the current buffer.
14749 With INCLUDE-SPECIALS, also list the special properties that reflect things
14750 like tags and TODO state.
14751 With INCLUDE-DEFAULTS, also include properties that has special meaning
14752 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14753 and others.
14754 With INCLUDE-COLUMNS, also include property names given in COLUMN
14755 formats in the current buffer."
14756 (let (rtn range cfmt s p)
14757 (save-excursion
14758 (save-restriction
14759 (widen)
14760 (goto-char (point-min))
14761 (while (re-search-forward org-property-start-re nil t)
14762 (setq range (org-get-property-block))
14763 (goto-char (car range))
14764 (while (re-search-forward
14765 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14766 (cdr range) t)
14767 (add-to-list 'rtn (org-match-string-no-properties 1)))
14768 (outline-next-heading))))
14770 (when include-specials
14771 (setq rtn (append org-special-properties rtn)))
14773 (when include-defaults
14774 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14775 (add-to-list 'rtn org-effort-property))
14777 (when include-columns
14778 (save-excursion
14779 (save-restriction
14780 (widen)
14781 (goto-char (point-min))
14782 (while (re-search-forward
14783 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14784 nil t)
14785 (setq cfmt (match-string 2) s 0)
14786 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14787 cfmt s)
14788 (setq s (match-end 0)
14789 p (match-string 1 cfmt))
14790 (unless (or (equal p "ITEM")
14791 (member p org-special-properties))
14792 (add-to-list 'rtn (match-string 1 cfmt))))))))
14794 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14796 (defun org-property-values (key)
14797 "Return a list of all values of property KEY in the current buffer."
14798 (save-excursion
14799 (save-restriction
14800 (widen)
14801 (goto-char (point-min))
14802 (let ((re (org-re-property key))
14803 values)
14804 (while (re-search-forward re nil t)
14805 (add-to-list 'values (org-trim (match-string 1))))
14806 (delete "" values)))))
14808 (defun org-insert-property-drawer ()
14809 "Insert a property drawer into the current entry."
14810 (org-back-to-heading t)
14811 (looking-at org-outline-regexp)
14812 (let ((indent (if org-adapt-indentation
14813 (- (match-end 0) (match-beginning 0))
14815 (beg (point))
14816 (re (concat "^[ \t]*" org-keyword-time-regexp))
14817 end hiddenp)
14818 (outline-next-heading)
14819 (setq end (point))
14820 (goto-char beg)
14821 (while (re-search-forward re end t))
14822 (setq hiddenp (outline-invisible-p))
14823 (end-of-line 1)
14824 (and (equal (char-after) ?\n) (forward-char 1))
14825 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14826 (if (member (match-string 1) '("CLOCK:" ":END:"))
14827 ;; just skip this line
14828 (beginning-of-line 2)
14829 ;; Drawer start, find the end
14830 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14831 (beginning-of-line 1)))
14832 (org-skip-over-state-notes)
14833 (skip-chars-backward " \t\n\r")
14834 (if (eq (char-before) ?*) (forward-char 1))
14835 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14836 (beginning-of-line 0)
14837 (org-indent-to-column indent)
14838 (beginning-of-line 2)
14839 (org-indent-to-column indent)
14840 (beginning-of-line 0)
14841 (if hiddenp
14842 (save-excursion
14843 (org-back-to-heading t)
14844 (hide-entry))
14845 (org-flag-drawer t))))
14847 (defun org-insert-drawer (&optional arg drawer)
14848 "Insert a drawer at point.
14850 Optional argument DRAWER, when non-nil, is a string representing
14851 drawer's name. Otherwise, the user is prompted for a name.
14853 If a region is active, insert the drawer around that region
14854 instead.
14856 Point is left between drawer's boundaries."
14857 (interactive "P")
14858 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14859 "LOGBOOK"))
14860 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14861 ;; internally by Org. They are meant to be inserted
14862 ;; automatically.
14863 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14864 ;; Remove system drawers from list. Note: For some reason,
14865 ;; `org-completing-read' ignores the predicate while
14866 ;; `completing-read' handles it fine.
14867 (drawer (if arg "PROPERTIES"
14868 (or drawer
14869 (completing-read
14870 "Drawer: " org-drawers
14871 (lambda (d) (not (member d system-drawers))))))))
14872 (cond
14873 ;; With C-u, fall back on `org-insert-property-drawer'
14874 (arg (org-insert-property-drawer))
14875 ;; With an active region, insert a drawer at point.
14876 ((not (org-region-active-p))
14877 (progn
14878 (unless (bolp) (insert "\n"))
14879 (insert (format ":%s:\n\n:END:\n" drawer))
14880 (forward-line -2)))
14881 ;; Otherwise, insert the drawer at point
14883 (let ((rbeg (region-beginning))
14884 (rend (copy-marker (region-end))))
14885 (unwind-protect
14886 (progn
14887 (goto-char rbeg)
14888 (beginning-of-line)
14889 (when (save-excursion
14890 (re-search-forward org-outline-regexp-bol rend t))
14891 (error "Drawers cannot contain headlines"))
14892 ;; Position point at the beginning of the first
14893 ;; non-blank line in region. Insert drawer's opening
14894 ;; there, then indent it.
14895 (org-skip-whitespace)
14896 (beginning-of-line)
14897 (insert ":" drawer ":\n")
14898 (forward-line -1)
14899 (indent-for-tab-command)
14900 ;; Move point to the beginning of the first blank line
14901 ;; after the last non-blank line in region. Insert
14902 ;; drawer's closing, then indent it.
14903 (goto-char rend)
14904 (skip-chars-backward " \r\t\n")
14905 (insert "\n:END:")
14906 (deactivate-mark t)
14907 (indent-for-tab-command)
14908 (unless (eolp) (insert "\n")))
14909 ;; Clear marker, whatever the outcome of insertion is.
14910 (set-marker rend nil)))))))
14912 (defvar org-property-set-functions-alist nil
14913 "Property set function alist.
14914 Each entry should have the following format:
14916 (PROPERTY . READ-FUNCTION)
14918 The read function will be called with the same argument as
14919 `org-completing-read'.")
14921 (defun org-set-property-function (property)
14922 "Get the function that should be used to set PROPERTY.
14923 This is computed according to `org-property-set-functions-alist'."
14924 (or (cdr (assoc property org-property-set-functions-alist))
14925 'org-completing-read))
14927 (defun org-read-property-value (property)
14928 "Read PROPERTY value from user."
14929 (let* ((completion-ignore-case t)
14930 (allowed (org-property-get-allowed-values nil property 'table))
14931 (cur (org-entry-get nil property))
14932 (prompt (concat property " value"
14933 (if (and cur (string-match "\\S-" cur))
14934 (concat " [" cur "]") "") ": "))
14935 (set-function (org-set-property-function property))
14936 (val (if allowed
14937 (funcall set-function prompt allowed nil
14938 (not (get-text-property 0 'org-unrestricted
14939 (caar allowed))))
14940 (let (org-completion-use-ido org-completion-use-iswitchb)
14941 (funcall set-function prompt
14942 (mapcar 'list (org-property-values property))
14943 nil nil "" nil cur)))))
14944 (if (equal val "")
14946 val)))
14948 (defvar org-last-set-property nil)
14949 (defun org-read-property-name ()
14950 "Read a property name."
14951 (let* ((completion-ignore-case t)
14952 (keys (org-buffer-property-keys nil t t))
14953 (default-prop (or (save-excursion
14954 (save-match-data
14955 (beginning-of-line)
14956 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14957 (null (string= (match-string 1) "END"))
14958 (match-string 1))))
14959 org-last-set-property))
14960 (property (org-icompleting-read
14961 (concat "Property"
14962 (if default-prop (concat " [" default-prop "]") "")
14963 ": ")
14964 (mapcar 'list keys)
14965 nil nil nil nil
14966 default-prop
14968 (if (member property keys)
14969 property
14970 (or (cdr (assoc (downcase property)
14971 (mapcar (lambda (x) (cons (downcase x) x))
14972 keys)))
14973 property))))
14975 (defun org-set-property (property value)
14976 "In the current entry, set PROPERTY to VALUE.
14977 When called interactively, this will prompt for a property name, offering
14978 completion on existing and default properties. And then it will prompt
14979 for a value, offering completion either on allowed values (via an inherited
14980 xxx_ALL property) or on existing values in other instances of this property
14981 in the current file."
14982 (interactive (list nil nil))
14983 (let* ((property (or property (org-read-property-name)))
14984 (value (or value (org-read-property-value property)))
14985 (fn (cdr (assoc property org-properties-postprocess-alist))))
14986 (setq org-last-set-property property)
14987 ;; Possibly postprocess the inserted value:
14988 (when fn (setq value (funcall fn value)))
14989 (unless (equal (org-entry-get nil property) value)
14990 (org-entry-put nil property value))))
14992 (defun org-delete-property (property)
14993 "In the current entry, delete PROPERTY."
14994 (interactive
14995 (let* ((completion-ignore-case t)
14996 (prop (org-icompleting-read "Property: "
14997 (org-entry-properties nil 'standard))))
14998 (list prop)))
14999 (message "Property %s %s" property
15000 (if (org-entry-delete nil property)
15001 "deleted"
15002 "was not present in the entry")))
15004 (defun org-delete-property-globally (property)
15005 "Remove PROPERTY globally, from all entries."
15006 (interactive
15007 (let* ((completion-ignore-case t)
15008 (prop (org-icompleting-read
15009 "Globally remove property: "
15010 (mapcar 'list (org-buffer-property-keys)))))
15011 (list prop)))
15012 (save-excursion
15013 (save-restriction
15014 (widen)
15015 (goto-char (point-min))
15016 (let ((cnt 0))
15017 (while (re-search-forward
15018 (org-re-property property)
15019 nil t)
15020 (setq cnt (1+ cnt))
15021 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15022 (message "Property \"%s\" removed from %d entries" property cnt)))))
15024 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15026 (defun org-compute-property-at-point ()
15027 "Compute the property at point.
15028 This looks for an enclosing column format, extracts the operator and
15029 then applies it to the property in the column format's scope."
15030 (interactive)
15031 (unless (org-at-property-p)
15032 (error "Not at a property"))
15033 (let ((prop (org-match-string-no-properties 2)))
15034 (org-columns-get-format-and-top-level)
15035 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15036 (error "No operator defined for property %s" prop))
15037 (org-columns-compute prop)))
15039 (defvar org-property-allowed-value-functions nil
15040 "Hook for functions supplying allowed values for a specific property.
15041 The functions must take a single argument, the name of the property, and
15042 return a flat list of allowed values. If \":ETC\" is one of
15043 the values, this means that these values are intended as defaults for
15044 completion, but that other values should be allowed too.
15045 The functions must return nil if they are not responsible for this
15046 property.")
15048 (defun org-property-get-allowed-values (pom property &optional table)
15049 "Get allowed values for the property PROPERTY.
15050 When TABLE is non-nil, return an alist that can directly be used for
15051 completion."
15052 (let (vals)
15053 (cond
15054 ((equal property "TODO")
15055 (setq vals (org-with-point-at pom
15056 (append org-todo-keywords-1 '("")))))
15057 ((equal property "PRIORITY")
15058 (let ((n org-lowest-priority))
15059 (while (>= n org-highest-priority)
15060 (push (char-to-string n) vals)
15061 (setq n (1- n)))))
15062 ((member property org-special-properties))
15063 ((setq vals (run-hook-with-args-until-success
15064 'org-property-allowed-value-functions property)))
15066 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15067 (when (and vals (string-match "\\S-" vals))
15068 (setq vals (car (read-from-string (concat "(" vals ")"))))
15069 (setq vals (mapcar (lambda (x)
15070 (cond ((stringp x) x)
15071 ((numberp x) (number-to-string x))
15072 ((symbolp x) (symbol-name x))
15073 (t "???")))
15074 vals)))))
15075 (when (member ":ETC" vals)
15076 (setq vals (remove ":ETC" vals))
15077 (org-add-props (car vals) '(org-unrestricted t)))
15078 (if table (mapcar 'list vals) vals)))
15080 (defun org-property-previous-allowed-value (&optional previous)
15081 "Switch to the next allowed value for this property."
15082 (interactive)
15083 (org-property-next-allowed-value t))
15085 (defun org-property-next-allowed-value (&optional previous)
15086 "Switch to the next allowed value for this property."
15087 (interactive)
15088 (unless (org-at-property-p)
15089 (error "Not at a property"))
15090 (let* ((key (match-string 2))
15091 (value (match-string 3))
15092 (allowed (or (org-property-get-allowed-values (point) key)
15093 (and (member value '("[ ]" "[-]" "[X]"))
15094 '("[ ]" "[X]"))))
15095 nval)
15096 (unless allowed
15097 (error "Allowed values for this property have not been defined"))
15098 (if previous (setq allowed (reverse allowed)))
15099 (if (member value allowed)
15100 (setq nval (car (cdr (member value allowed)))))
15101 (setq nval (or nval (car allowed)))
15102 (if (equal nval value)
15103 (error "Only one allowed value for this property"))
15104 (org-at-property-p)
15105 (replace-match (concat " :" key ": " nval) t t)
15106 (org-indent-line)
15107 (beginning-of-line 1)
15108 (skip-chars-forward " \t")
15109 (run-hook-with-args 'org-property-changed-functions key nval)))
15111 (defun org-find-olp (path &optional this-buffer)
15112 "Return a marker pointing to the entry at outline path OLP.
15113 If anything goes wrong, throw an error.
15114 You can wrap this call to catch the error like this:
15116 (condition-case msg
15117 (org-mobile-locate-entry (match-string 4))
15118 (error (nth 1 msg)))
15120 The return value will then be either a string with the error message,
15121 or a marker if everything is OK.
15123 If THIS-BUFFER is set, the outline path does not contain a file,
15124 only headings."
15125 (let* ((file (if this-buffer buffer-file-name (pop path)))
15126 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15127 (level 1)
15128 (lmin 1)
15129 (lmax 1)
15130 limit re end found pos heading cnt flevel)
15131 (unless buffer (error "File not found :%s" file))
15132 (with-current-buffer buffer
15133 (save-excursion
15134 (save-restriction
15135 (widen)
15136 (setq limit (point-max))
15137 (goto-char (point-min))
15138 (while (setq heading (pop path))
15139 (setq re (format org-complex-heading-regexp-format
15140 (regexp-quote heading)))
15141 (setq cnt 0 pos (point))
15142 (while (re-search-forward re end t)
15143 (setq level (- (match-end 1) (match-beginning 1)))
15144 (if (and (>= level lmin) (<= level lmax))
15145 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15146 (when (= cnt 0) (error "Heading not found on level %d: %s"
15147 lmax heading))
15148 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15149 lmax heading))
15150 (goto-char found)
15151 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15152 (setq end (save-excursion (org-end-of-subtree t t))))
15153 (when (org-at-heading-p)
15154 (move-marker (make-marker) (point))))))))
15156 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15157 "Find node HEADING in BUFFER.
15158 Return a marker to the heading if it was found, or nil if not.
15159 If POS-ONLY is set, return just the position instead of a marker.
15161 The heading text must match exact, but it may have a TODO keyword,
15162 a priority cookie and tags in the standard locations."
15163 (with-current-buffer (or buffer (current-buffer))
15164 (save-excursion
15165 (save-restriction
15166 (widen)
15167 (goto-char (point-min))
15168 (let (case-fold-search)
15169 (if (re-search-forward
15170 (format org-complex-heading-regexp-format
15171 (regexp-quote heading)) nil t)
15172 (if pos-only
15173 (match-beginning 0)
15174 (move-marker (make-marker) (match-beginning 0)))))))))
15176 (defun org-find-exact-heading-in-directory (heading &optional dir)
15177 "Find Org node headline HEADING in all .org files in directory DIR.
15178 When the target headline is found, return a marker to this location."
15179 (let ((files (directory-files (or dir default-directory)
15180 nil "\\`[^.#].*\\.org\\'"))
15181 file visiting m buffer)
15182 (catch 'found
15183 (while (setq file (pop files))
15184 (message "trying %s" file)
15185 (setq visiting (org-find-base-buffer-visiting file))
15186 (setq buffer (or visiting (find-file-noselect file)))
15187 (setq m (org-find-exact-headline-in-buffer
15188 heading buffer))
15189 (when (and (not m) (not visiting)) (kill-buffer buffer))
15190 (and m (throw 'found m))))))
15192 (defun org-find-entry-with-id (ident)
15193 "Locate the entry that contains the ID property with exact value IDENT.
15194 IDENT can be a string, a symbol or a number, this function will search for
15195 the string representation of it.
15196 Return the position where this entry starts, or nil if there is no such entry."
15197 (interactive "sID: ")
15198 (let ((id (cond
15199 ((stringp ident) ident)
15200 ((symbol-name ident) (symbol-name ident))
15201 ((numberp ident) (number-to-string ident))
15202 (t (error "IDENT %s must be a string, symbol or number" ident))))
15203 (case-fold-search nil))
15204 (save-excursion
15205 (save-restriction
15206 (widen)
15207 (goto-char (point-min))
15208 (when (re-search-forward
15209 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15210 nil t)
15211 (org-back-to-heading t)
15212 (point))))))
15214 ;;;; Timestamps
15216 (defvar org-last-changed-timestamp nil)
15217 (defvar org-last-inserted-timestamp nil
15218 "The last time stamp inserted with `org-insert-time-stamp'.")
15219 (defvar org-time-was-given) ; dynamically scoped parameter
15220 (defvar org-end-time-was-given) ; dynamically scoped parameter
15221 (defvar org-ts-what) ; dynamically scoped parameter
15223 (defun org-time-stamp (arg &optional inactive)
15224 "Prompt for a date/time and insert a time stamp.
15225 If the user specifies a time like HH:MM or if this command is
15226 called with at least one prefix argument, the time stamp contains
15227 the date and the time. Otherwise, only the date is be included.
15229 All parts of a date not specified by the user is filled in from
15230 the current date/time. So if you just press return without
15231 typing anything, the time stamp will represent the current
15232 date/time.
15234 If there is already a timestamp at the cursor, it will be
15235 modified.
15237 With two universal prefix arguments, insert an active timestamp
15238 with the current time without prompting the user."
15239 (interactive "P")
15240 (let* ((ts nil)
15241 (default-time
15242 ;; Default time is either today, or, when entering a range,
15243 ;; the range start.
15244 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15245 (save-excursion
15246 (re-search-backward
15247 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15248 (- (point) 20) t)))
15249 (apply 'encode-time (org-parse-time-string (match-string 1)))
15250 (current-time)))
15251 (default-input (and ts (org-get-compact-tod ts)))
15252 (repeater (save-excursion
15253 (save-match-data
15254 (beginning-of-line)
15255 (when (re-search-forward
15256 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15257 (save-excursion (progn (end-of-line) (point))) t)
15258 (match-string 0)))))
15259 org-time-was-given org-end-time-was-given time)
15260 (cond
15261 ((and (org-at-timestamp-p t)
15262 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15263 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15264 (insert "--")
15265 (setq time (let ((this-command this-command))
15266 (org-read-date arg 'totime nil nil
15267 default-time default-input inactive)))
15268 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15269 ((org-at-timestamp-p t)
15270 (setq time (let ((this-command this-command))
15271 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15272 (when (org-at-timestamp-p t) ; just to get the match data
15273 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15274 (replace-match "")
15275 (setq org-last-changed-timestamp
15276 (org-insert-time-stamp
15277 time (or org-time-was-given arg)
15278 inactive nil nil (list org-end-time-was-given)))
15279 (when repeater (goto-char (1- (point))) (insert " " repeater)
15280 (setq org-last-changed-timestamp
15281 (concat (substring org-last-inserted-timestamp 0 -1)
15282 " " repeater ">"))))
15283 (message "Timestamp updated"))
15284 ((equal arg '(16))
15285 (org-insert-time-stamp (current-time) t))
15287 (setq time (let ((this-command this-command))
15288 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15289 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15290 nil nil (list org-end-time-was-given))))))
15292 ;; FIXME: can we use this for something else, like computing time differences?
15293 (defun org-get-compact-tod (s)
15294 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15295 (let* ((t1 (match-string 1 s))
15296 (h1 (string-to-number (match-string 2 s)))
15297 (m1 (string-to-number (match-string 3 s)))
15298 (t2 (and (match-end 4) (match-string 5 s)))
15299 (h2 (and t2 (string-to-number (match-string 6 s))))
15300 (m2 (and t2 (string-to-number (match-string 7 s))))
15301 dh dm)
15302 (if (not t2)
15304 (setq dh (- h2 h1) dm (- m2 m1))
15305 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15306 (concat t1 "+" (number-to-string dh)
15307 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15309 (defun org-time-stamp-inactive (&optional arg)
15310 "Insert an inactive time stamp.
15311 An inactive time stamp is enclosed in square brackets instead of angle
15312 brackets. It is inactive in the sense that it does not trigger agenda entries,
15313 does not link to the calendar and cannot be changed with the S-cursor keys.
15314 So these are more for recording a certain time/date."
15315 (interactive "P")
15316 (org-time-stamp arg 'inactive))
15318 (defvar org-date-ovl (make-overlay 1 1))
15319 (overlay-put org-date-ovl 'face 'org-date-selected)
15320 (org-detach-overlay org-date-ovl)
15322 (defvar org-ans1) ; dynamically scoped parameter
15323 (defvar org-ans2) ; dynamically scoped parameter
15325 (defvar org-plain-time-of-day-regexp) ; defined below
15327 (defvar org-overriding-default-time nil) ; dynamically scoped
15328 (defvar org-read-date-overlay nil)
15329 (defvar org-dcst nil) ; dynamically scoped
15330 (defvar org-read-date-history nil)
15331 (defvar org-read-date-final-answer nil)
15332 (defvar org-read-date-analyze-futurep nil)
15333 (defvar org-read-date-analyze-forced-year nil)
15334 (defvar org-read-date-inactive)
15336 (defun org-read-date (&optional org-with-time to-time from-string prompt
15337 default-time default-input inactive)
15338 "Read a date, possibly a time, and make things smooth for the user.
15339 The prompt will suggest to enter an ISO date, but you can also enter anything
15340 which will at least partially be understood by `parse-time-string'.
15341 Unrecognized parts of the date will default to the current day, month, year,
15342 hour and minute. If this command is called to replace a timestamp at point,
15343 or to enter the second timestamp of a range, the default time is taken
15344 from the existing stamp. Furthermore, the command prefers the future,
15345 so if you are giving a date where the year is not given, and the day-month
15346 combination is already past in the current year, it will assume you
15347 mean next year. For details, see the manual. A few examples:
15349 3-2-5 --> 2003-02-05
15350 feb 15 --> currentyear-02-15
15351 2/15 --> currentyear-02-15
15352 sep 12 9 --> 2009-09-12
15353 12:45 --> today 12:45
15354 22 sept 0:34 --> currentyear-09-22 0:34
15355 12 --> currentyear-currentmonth-12
15356 Fri --> nearest Friday (today or later)
15357 etc.
15359 Furthermore you can specify a relative date by giving, as the *first* thing
15360 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15361 change in days weeks, months, years.
15362 With a single plus or minus, the date is relative to today. With a double
15363 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15364 +4d --> four days from today
15365 +4 --> same as above
15366 +2w --> two weeks from today
15367 ++5 --> five days from default date
15369 The function understands only English month and weekday abbreviations.
15371 While prompting, a calendar is popped up - you can also select the
15372 date with the mouse (button 1). The calendar shows a period of three
15373 months. To scroll it to other months, use the keys `>' and `<'.
15374 If you don't like the calendar, turn it off with
15375 \(setq org-read-date-popup-calendar nil)
15377 With optional argument TO-TIME, the date will immediately be converted
15378 to an internal time.
15379 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15380 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15381 still enter a time, and this function will inform the calling routine
15382 about this change. The calling routine may then choose to change the
15383 format used to insert the time stamp into the buffer to include the time.
15384 With optional argument FROM-STRING, read from this string instead from
15385 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15386 the time/date that is used for everything that is not specified by the
15387 user."
15388 (require 'parse-time)
15389 (let* ((org-time-stamp-rounding-minutes
15390 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15391 (org-dcst org-display-custom-times)
15392 (ct (org-current-time))
15393 (org-def (or org-overriding-default-time default-time ct))
15394 (org-defdecode (decode-time org-def))
15395 (dummy (progn
15396 (when (< (nth 2 org-defdecode) org-extend-today-until)
15397 (setcar (nthcdr 2 org-defdecode) -1)
15398 (setcar (nthcdr 1 org-defdecode) 59)
15399 (setq org-def (apply 'encode-time org-defdecode)
15400 org-defdecode (decode-time org-def)))))
15401 (calendar-frame-setup nil)
15402 (calendar-setup nil)
15403 (calendar-move-hook nil)
15404 (calendar-view-diary-initially-flag nil)
15405 (calendar-view-holidays-initially-flag nil)
15406 (timestr (format-time-string
15407 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15408 (prompt (concat (if prompt (concat prompt " ") "")
15409 (format "Date+time [%s]: " timestr)))
15410 ans (org-ans0 "") org-ans1 org-ans2 final)
15412 (cond
15413 (from-string (setq ans from-string))
15414 (org-read-date-popup-calendar
15415 (save-excursion
15416 (save-window-excursion
15417 (calendar)
15418 (org-eval-in-calendar '(setq cursor-type nil) t)
15419 (unwind-protect
15420 (progn
15421 (calendar-forward-day (- (time-to-days org-def)
15422 (calendar-absolute-from-gregorian
15423 (calendar-current-date))))
15424 (org-eval-in-calendar nil t)
15425 (let* ((old-map (current-local-map))
15426 (map (copy-keymap calendar-mode-map))
15427 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15428 (org-defkey map (kbd "RET") 'org-calendar-select)
15429 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15430 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15431 (org-defkey minibuffer-local-map [(meta shift left)]
15432 (lambda () (interactive)
15433 (org-eval-in-calendar '(calendar-backward-month 1))))
15434 (org-defkey minibuffer-local-map [(meta shift right)]
15435 (lambda () (interactive)
15436 (org-eval-in-calendar '(calendar-forward-month 1))))
15437 (org-defkey minibuffer-local-map [(meta shift up)]
15438 (lambda () (interactive)
15439 (org-eval-in-calendar '(calendar-backward-year 1))))
15440 (org-defkey minibuffer-local-map [(meta shift down)]
15441 (lambda () (interactive)
15442 (org-eval-in-calendar '(calendar-forward-year 1))))
15443 (org-defkey minibuffer-local-map [?\e (shift left)]
15444 (lambda () (interactive)
15445 (org-eval-in-calendar '(calendar-backward-month 1))))
15446 (org-defkey minibuffer-local-map [?\e (shift right)]
15447 (lambda () (interactive)
15448 (org-eval-in-calendar '(calendar-forward-month 1))))
15449 (org-defkey minibuffer-local-map [?\e (shift up)]
15450 (lambda () (interactive)
15451 (org-eval-in-calendar '(calendar-backward-year 1))))
15452 (org-defkey minibuffer-local-map [?\e (shift down)]
15453 (lambda () (interactive)
15454 (org-eval-in-calendar '(calendar-forward-year 1))))
15455 (org-defkey minibuffer-local-map [(shift up)]
15456 (lambda () (interactive)
15457 (org-eval-in-calendar '(calendar-backward-week 1))))
15458 (org-defkey minibuffer-local-map [(shift down)]
15459 (lambda () (interactive)
15460 (org-eval-in-calendar '(calendar-forward-week 1))))
15461 (org-defkey minibuffer-local-map [(shift left)]
15462 (lambda () (interactive)
15463 (org-eval-in-calendar '(calendar-backward-day 1))))
15464 (org-defkey minibuffer-local-map [(shift right)]
15465 (lambda () (interactive)
15466 (org-eval-in-calendar '(calendar-forward-day 1))))
15467 (org-defkey minibuffer-local-map ">"
15468 (lambda () (interactive)
15469 (org-eval-in-calendar '(scroll-calendar-left 1))))
15470 (org-defkey minibuffer-local-map "<"
15471 (lambda () (interactive)
15472 (org-eval-in-calendar '(scroll-calendar-right 1))))
15473 (org-defkey minibuffer-local-map "\C-v"
15474 (lambda () (interactive)
15475 (org-eval-in-calendar
15476 '(calendar-scroll-left-three-months 1))))
15477 (org-defkey minibuffer-local-map "\M-v"
15478 (lambda () (interactive)
15479 (org-eval-in-calendar
15480 '(calendar-scroll-right-three-months 1))))
15481 (run-hooks 'org-read-date-minibuffer-setup-hook)
15482 (unwind-protect
15483 (progn
15484 (use-local-map map)
15485 (setq org-read-date-inactive inactive)
15486 (add-hook 'post-command-hook 'org-read-date-display)
15487 (setq org-ans0 (read-string prompt default-input
15488 'org-read-date-history nil))
15489 ;; org-ans0: from prompt
15490 ;; org-ans1: from mouse click
15491 ;; org-ans2: from calendar motion
15492 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15493 (remove-hook 'post-command-hook 'org-read-date-display)
15494 (use-local-map old-map)
15495 (when org-read-date-overlay
15496 (delete-overlay org-read-date-overlay)
15497 (setq org-read-date-overlay nil)))))
15498 (bury-buffer "*Calendar*")))))
15500 (t ; Naked prompt only
15501 (unwind-protect
15502 (setq ans (read-string prompt default-input
15503 'org-read-date-history timestr))
15504 (when org-read-date-overlay
15505 (delete-overlay org-read-date-overlay)
15506 (setq org-read-date-overlay nil)))))
15508 (setq final (org-read-date-analyze ans org-def org-defdecode))
15510 (when org-read-date-analyze-forced-year
15511 (message "Year was forced into %s"
15512 (if org-read-date-force-compatible-dates
15513 "compatible range (1970-2037)"
15514 "range representable on this machine"))
15515 (ding))
15517 ;; One round trip to get rid of 34th of August and stuff like that....
15518 (setq final (decode-time (apply 'encode-time final)))
15520 (setq org-read-date-final-answer ans)
15522 (if to-time
15523 (apply 'encode-time final)
15524 (if (and (boundp 'org-time-was-given) org-time-was-given)
15525 (format "%04d-%02d-%02d %02d:%02d"
15526 (nth 5 final) (nth 4 final) (nth 3 final)
15527 (nth 2 final) (nth 1 final))
15528 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15530 (defvar org-def)
15531 (defvar org-defdecode)
15532 (defvar org-with-time)
15533 (defun org-read-date-display ()
15534 "Display the current date prompt interpretation in the minibuffer."
15535 (when org-read-date-display-live
15536 (when org-read-date-overlay
15537 (delete-overlay org-read-date-overlay))
15538 (when (minibufferp (current-buffer))
15539 (save-excursion
15540 (end-of-line 1)
15541 (while (not (equal (buffer-substring
15542 (max (point-min) (- (point) 4)) (point))
15543 " "))
15544 (insert " ")))
15545 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15546 " " (or org-ans1 org-ans2)))
15547 (org-end-time-was-given nil)
15548 (f (org-read-date-analyze ans org-def org-defdecode))
15549 (fmts (if org-dcst
15550 org-time-stamp-custom-formats
15551 org-time-stamp-formats))
15552 (fmt (if (or org-with-time
15553 (and (boundp 'org-time-was-given) org-time-was-given))
15554 (cdr fmts)
15555 (car fmts)))
15556 (txt (format-time-string fmt (apply 'encode-time f)))
15557 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15558 (txt (concat "=> " txt)))
15559 (when (and org-end-time-was-given
15560 (string-match org-plain-time-of-day-regexp txt))
15561 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15562 org-end-time-was-given
15563 (substring txt (match-end 0)))))
15564 (when org-read-date-analyze-futurep
15565 (setq txt (concat txt " (=>F)")))
15566 (setq org-read-date-overlay
15567 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15568 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15570 (defun org-read-date-analyze (ans org-def org-defdecode)
15571 "Analyze the combined answer of the date prompt."
15572 ;; FIXME: cleanup and comment
15573 (let ((nowdecode (decode-time (current-time)))
15574 delta deltan deltaw deltadef year month day
15575 hour minute second wday pm h2 m2 tl wday1
15576 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15577 (setq org-read-date-analyze-futurep nil
15578 org-read-date-analyze-forced-year nil)
15579 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15580 (setq ans "+0"))
15582 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15583 (setq ans (replace-match "" t t ans)
15584 deltan (car delta)
15585 deltaw (nth 1 delta)
15586 deltadef (nth 2 delta)))
15588 ;; Check if there is an iso week date in there. If yes, store the
15589 ;; info and postpone interpreting it until the rest of the parsing
15590 ;; is done.
15591 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15592 (setq iso-year (if (match-end 1)
15593 (org-small-year-to-year
15594 (string-to-number (match-string 1 ans))))
15595 iso-weekday (if (match-end 3)
15596 (string-to-number (match-string 3 ans)))
15597 iso-week (string-to-number (match-string 2 ans)))
15598 (setq ans (replace-match "" t t ans)))
15600 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15601 (when (string-match
15602 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15603 (setq year (if (match-end 2)
15604 (string-to-number (match-string 2 ans))
15605 (progn (setq kill-year t)
15606 (string-to-number (format-time-string "%Y"))))
15607 month (string-to-number (match-string 3 ans))
15608 day (string-to-number (match-string 4 ans)))
15609 (if (< year 100) (setq year (+ 2000 year)))
15610 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15611 t nil ans)))
15613 ;; Help matching dotted european dates
15614 (when (string-match
15615 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15616 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15617 (setq kill-year t)
15618 (string-to-number (format-time-string "%Y")))
15619 day (string-to-number (match-string 1 ans))
15620 month (string-to-number (match-string 2 ans))
15621 ans (replace-match (format "%04d-%02d-%02d" year month day)
15622 t nil ans)))
15624 ;; Help matching american dates, like 5/30 or 5/30/7
15625 (when (string-match
15626 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15627 (setq year (if (match-end 4)
15628 (string-to-number (match-string 4 ans))
15629 (progn (setq kill-year t)
15630 (string-to-number (format-time-string "%Y"))))
15631 month (string-to-number (match-string 1 ans))
15632 day (string-to-number (match-string 2 ans)))
15633 (if (< year 100) (setq year (+ 2000 year)))
15634 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15635 t nil ans)))
15636 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15637 ;; If there is a time with am/pm, and *no* time without it, we convert
15638 ;; so that matching will be successful.
15639 (loop for i from 1 to 2 do ; twice, for end time as well
15640 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15641 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15642 (setq hour (string-to-number (match-string 1 ans))
15643 minute (if (match-end 3)
15644 (string-to-number (match-string 3 ans))
15646 pm (equal ?p
15647 (string-to-char (downcase (match-string 4 ans)))))
15648 (if (and (= hour 12) (not pm))
15649 (setq hour 0)
15650 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15651 (setq ans (replace-match (format "%02d:%02d" hour minute)
15652 t t ans))))
15654 ;; Check if a time range is given as a duration
15655 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15656 (setq hour (string-to-number (match-string 1 ans))
15657 h2 (+ hour (string-to-number (match-string 3 ans)))
15658 minute (string-to-number (match-string 2 ans))
15659 m2 (+ minute (if (match-end 5) (string-to-number
15660 (match-string 5 ans))0)))
15661 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15662 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15663 t t ans)))
15665 ;; Check if there is a time range
15666 (when (boundp 'org-end-time-was-given)
15667 (setq org-time-was-given nil)
15668 (when (and (string-match org-plain-time-of-day-regexp ans)
15669 (match-end 8))
15670 (setq org-end-time-was-given (match-string 8 ans))
15671 (setq ans (concat (substring ans 0 (match-beginning 7))
15672 (substring ans (match-end 7))))))
15674 (setq tl (parse-time-string ans)
15675 day (or (nth 3 tl) (nth 3 org-defdecode))
15676 month (or (nth 4 tl)
15677 (if (and org-read-date-prefer-future
15678 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15679 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15680 (nth 4 org-defdecode)))
15681 year (or (and (not kill-year) (nth 5 tl))
15682 (if (and org-read-date-prefer-future
15683 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15684 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15685 (nth 5 org-defdecode)))
15686 hour (or (nth 2 tl) (nth 2 org-defdecode))
15687 minute (or (nth 1 tl) (nth 1 org-defdecode))
15688 second (or (nth 0 tl) 0)
15689 wday (nth 6 tl))
15691 (when (and (eq org-read-date-prefer-future 'time)
15692 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15693 (equal day (nth 3 nowdecode))
15694 (equal month (nth 4 nowdecode))
15695 (equal year (nth 5 nowdecode))
15696 (nth 2 tl)
15697 (or (< (nth 2 tl) (nth 2 nowdecode))
15698 (and (= (nth 2 tl) (nth 2 nowdecode))
15699 (nth 1 tl)
15700 (< (nth 1 tl) (nth 1 nowdecode)))))
15701 (setq day (1+ day)
15702 futurep t))
15704 ;; Special date definitions below
15705 (cond
15706 (iso-week
15707 ;; There was an iso week
15708 (require 'cal-iso)
15709 (setq futurep nil)
15710 (setq year (or iso-year year)
15711 day (or iso-weekday wday 1)
15712 wday nil ; to make sure that the trigger below does not match
15713 iso-date (calendar-gregorian-from-absolute
15714 (calendar-absolute-from-iso
15715 (list iso-week day year))))
15716 ; FIXME: Should we also push ISO weeks into the future?
15717 ; (when (and org-read-date-prefer-future
15718 ; (not iso-year)
15719 ; (< (calendar-absolute-from-gregorian iso-date)
15720 ; (time-to-days (current-time))))
15721 ; (setq year (1+ year)
15722 ; iso-date (calendar-gregorian-from-absolute
15723 ; (calendar-absolute-from-iso
15724 ; (list iso-week day year)))))
15725 (setq month (car iso-date)
15726 year (nth 2 iso-date)
15727 day (nth 1 iso-date)))
15728 (deltan
15729 (setq futurep nil)
15730 (unless deltadef
15731 (let ((now (decode-time (current-time))))
15732 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15733 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15734 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15735 ((equal deltaw "m") (setq month (+ month deltan)))
15736 ((equal deltaw "y") (setq year (+ year deltan)))))
15737 ((and wday (not (nth 3 tl)))
15738 ;; Weekday was given, but no day, so pick that day in the week
15739 ;; on or after the derived date.
15740 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15741 (unless (equal wday wday1)
15742 (setq day (+ day (% (- wday wday1 -7) 7))))))
15743 (if (and (boundp 'org-time-was-given)
15744 (nth 2 tl))
15745 (setq org-time-was-given t))
15746 (if (< year 100) (setq year (+ 2000 year)))
15747 ;; Check of the date is representable
15748 (if org-read-date-force-compatible-dates
15749 (progn
15750 (if (< year 1970)
15751 (setq year 1970 org-read-date-analyze-forced-year t))
15752 (if (> year 2037)
15753 (setq year 2037 org-read-date-analyze-forced-year t)))
15754 (condition-case nil
15755 (ignore (encode-time second minute hour day month year))
15756 (error
15757 (setq year (nth 5 org-defdecode))
15758 (setq org-read-date-analyze-forced-year t))))
15759 (setq org-read-date-analyze-futurep futurep)
15760 (list second minute hour day month year)))
15762 (defvar parse-time-weekdays)
15763 (defun org-read-date-get-relative (s today default)
15764 "Check string S for special relative date string.
15765 TODAY and DEFAULT are internal times, for today and for a default.
15766 Return shift list (N what def-flag)
15767 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15768 N is the number of WHATs to shift.
15769 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15770 the DEFAULT date rather than TODAY."
15771 (require 'parse-time)
15772 (when (and
15773 (string-match
15774 (concat
15775 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15776 "\\([0-9]+\\)?"
15777 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15778 "\\([ \t]\\|$\\)") s)
15779 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15780 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15781 (string-to-char (substring (match-string 1 s) -1))
15782 ?+))
15783 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15784 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15785 (what (if (match-end 3) (match-string 3 s) "d"))
15786 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15787 (date (if rel default today))
15788 (wday (nth 6 (decode-time date)))
15789 delta)
15790 (if wday1
15791 (progn
15792 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15793 (if (= dir ?-) (setq delta (- delta 7)))
15794 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15795 (list delta "d" rel))
15796 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15798 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15799 "Turn a user-specified date into the internal representation.
15800 The internal representation needed by the calendar is (month day year).
15801 This is a wrapper to handle the brain-dead convention in calendar that
15802 user function argument order change dependent on argument order."
15803 (if (boundp 'calendar-date-style)
15804 (cond
15805 ((eq calendar-date-style 'american)
15806 (list arg1 arg2 arg3))
15807 ((eq calendar-date-style 'european)
15808 (list arg2 arg1 arg3))
15809 ((eq calendar-date-style 'iso)
15810 (list arg2 arg3 arg1)))
15811 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15812 (if (org-bound-and-true-p european-calendar-style)
15813 (list arg2 arg1 arg3)
15814 (list arg1 arg2 arg3)))))
15816 (defun org-eval-in-calendar (form &optional keepdate)
15817 "Eval FORM in the calendar window and return to current window.
15818 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15819 otherwise stick to the current value of `org-ans2'."
15820 (let ((sf (selected-frame))
15821 (sw (selected-window)))
15822 (select-window (get-buffer-window "*Calendar*" t))
15823 (eval form)
15824 (when (and (not keepdate) (calendar-cursor-to-date))
15825 (let* ((date (calendar-cursor-to-date))
15826 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15827 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15828 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15829 (select-window sw)
15830 (org-select-frame-set-input-focus sf)))
15832 (defun org-calendar-select ()
15833 "Return to `org-read-date' with the date currently selected.
15834 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15835 (interactive)
15836 (when (calendar-cursor-to-date)
15837 (let* ((date (calendar-cursor-to-date))
15838 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15839 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15840 (if (active-minibuffer-window) (exit-minibuffer))))
15842 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15843 "Insert a date stamp for the date given by the internal TIME.
15844 WITH-HM means use the stamp format that includes the time of the day.
15845 INACTIVE means use square brackets instead of angular ones, so that the
15846 stamp will not contribute to the agenda.
15847 PRE and POST are optional strings to be inserted before and after the
15848 stamp.
15849 The command returns the inserted time stamp."
15850 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15851 stamp)
15852 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15853 (insert-before-markers (or pre ""))
15854 (when (listp extra)
15855 (setq extra (car extra))
15856 (if (and (stringp extra)
15857 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15858 (setq extra (format "-%02d:%02d"
15859 (string-to-number (match-string 1 extra))
15860 (string-to-number (match-string 2 extra))))
15861 (setq extra nil)))
15862 (when extra
15863 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15864 (insert-before-markers (setq stamp (format-time-string fmt time)))
15865 (insert-before-markers (or post ""))
15866 (setq org-last-inserted-timestamp stamp)))
15868 (defun org-toggle-time-stamp-overlays ()
15869 "Toggle the use of custom time stamp formats."
15870 (interactive)
15871 (setq org-display-custom-times (not org-display-custom-times))
15872 (unless org-display-custom-times
15873 (let ((p (point-min)) (bmp (buffer-modified-p)))
15874 (while (setq p (next-single-property-change p 'display))
15875 (if (and (get-text-property p 'display)
15876 (eq (get-text-property p 'face) 'org-date))
15877 (remove-text-properties
15878 p (setq p (next-single-property-change p 'display))
15879 '(display t))))
15880 (set-buffer-modified-p bmp)))
15881 (if (featurep 'xemacs)
15882 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15883 (org-restart-font-lock)
15884 (setq org-table-may-need-update t)
15885 (if org-display-custom-times
15886 (message "Time stamps are overlaid with custom format")
15887 (message "Time stamp overlays removed")))
15889 (defun org-display-custom-time (beg end)
15890 "Overlay modified time stamp format over timestamp between BEG and END."
15891 (let* ((ts (buffer-substring beg end))
15892 t1 w1 with-hm tf time str w2 (off 0))
15893 (save-match-data
15894 (setq t1 (org-parse-time-string ts t))
15895 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15896 (setq off (- (match-end 0) (match-beginning 0)))))
15897 (setq end (- end off))
15898 (setq w1 (- end beg)
15899 with-hm (and (nth 1 t1) (nth 2 t1))
15900 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15901 time (org-fix-decoded-time t1)
15902 str (org-add-props
15903 (format-time-string
15904 (substring tf 1 -1) (apply 'encode-time time))
15905 nil 'mouse-face 'highlight)
15906 w2 (length str))
15907 (if (not (= w2 w1))
15908 (add-text-properties (1+ beg) (+ 2 beg)
15909 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15910 (if (featurep 'xemacs)
15911 (progn
15912 (put-text-property beg end 'invisible t)
15913 (put-text-property beg end 'end-glyph (make-glyph str)))
15914 (put-text-property beg end 'display str))))
15916 (defun org-translate-time (string)
15917 "Translate all timestamps in STRING to custom format.
15918 But do this only if the variable `org-display-custom-times' is set."
15919 (when org-display-custom-times
15920 (save-match-data
15921 (let* ((start 0)
15922 (re org-ts-regexp-both)
15923 t1 with-hm inactive tf time str beg end)
15924 (while (setq start (string-match re string start))
15925 (setq beg (match-beginning 0)
15926 end (match-end 0)
15927 t1 (save-match-data
15928 (org-parse-time-string (substring string beg end) t))
15929 with-hm (and (nth 1 t1) (nth 2 t1))
15930 inactive (equal (substring string beg (1+ beg)) "[")
15931 tf (funcall (if with-hm 'cdr 'car)
15932 org-time-stamp-custom-formats)
15933 time (org-fix-decoded-time t1)
15934 str (format-time-string
15935 (concat
15936 (if inactive "[" "<") (substring tf 1 -1)
15937 (if inactive "]" ">"))
15938 (apply 'encode-time time))
15939 string (replace-match str t t string)
15940 start (+ start (length str)))))))
15941 string)
15943 (defun org-fix-decoded-time (time)
15944 "Set 0 instead of nil for the first 6 elements of time.
15945 Don't touch the rest."
15946 (let ((n 0))
15947 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15949 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
15951 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
15952 "Difference between TIMESTAMP-STRING and now in days.
15953 If SECONDS is non-nil, return the difference in seconds."
15954 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
15955 (- (funcall fdiff (org-time-string-to-time timestamp-string))
15956 (funcall fdiff (current-time)))))
15958 (defun org-deadline-close (timestamp-string &optional ndays)
15959 "Is the time in TIMESTAMP-STRING close to the current date?"
15960 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15961 (and (< (org-time-stamp-to-now timestamp-string) ndays)
15962 (not (org-entry-is-done-p))))
15964 (defun org-get-wdays (ts)
15965 "Get the deadline lead time appropriate for timestring TS."
15966 (cond
15967 ((<= org-deadline-warning-days 0)
15968 ;; 0 or negative, enforce this value no matter what
15969 (- org-deadline-warning-days))
15970 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15971 ;; lead time is specified.
15972 (floor (* (string-to-number (match-string 1 ts))
15973 (cdr (assoc (match-string 2 ts)
15974 '(("d" . 1) ("w" . 7)
15975 ("m" . 30.4) ("y" . 365.25)))))))
15976 ;; go for the default.
15977 (t org-deadline-warning-days)))
15979 (defun org-calendar-select-mouse (ev)
15980 "Return to `org-read-date' with the date currently selected.
15981 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15982 (interactive "e")
15983 (mouse-set-point ev)
15984 (when (calendar-cursor-to-date)
15985 (let* ((date (calendar-cursor-to-date))
15986 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15987 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15988 (if (active-minibuffer-window) (exit-minibuffer))))
15990 (defun org-check-deadlines (ndays)
15991 "Check if there are any deadlines due or past due.
15992 A deadline is considered due if it happens within `org-deadline-warning-days'
15993 days from today's date. If the deadline appears in an entry marked DONE,
15994 it is not shown. The prefix arg NDAYS can be used to test that many
15995 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15996 (interactive "P")
15997 (let* ((org-warn-days
15998 (cond
15999 ((equal ndays '(4)) 100000)
16000 (ndays (prefix-numeric-value ndays))
16001 (t (abs org-deadline-warning-days))))
16002 (case-fold-search nil)
16003 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16004 (callback
16005 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16007 (message "%d deadlines past-due or due within %d days"
16008 (org-occur regexp nil callback)
16009 org-warn-days)))
16011 (defsubst org-re-timestamp (type)
16012 "Return a regexp for timestamp TYPE.
16013 Allowed values for TYPE are:
16015 all: all timestamps
16016 active: only active timestamps (<...>)
16017 inactive: only inactive timestamps ([...])
16018 scheduled: only scheduled timestamps
16019 deadline: only deadline timestamps
16021 When TYPE is nil, fall back on returning a regexp that matches
16022 both scheduled and deadline timestamps."
16023 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16024 ((eq type 'active) org-ts-regexp)
16025 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16026 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16027 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16028 ((eq type 'scheduled-or-deadline)
16029 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16031 (defun org-check-before-date (date)
16032 "Check if there are deadlines or scheduled entries before DATE."
16033 (interactive (list (org-read-date)))
16034 (let ((case-fold-search nil)
16035 (regexp (org-re-timestamp org-ts-type))
16036 (callback
16037 (lambda () (time-less-p
16038 (org-time-string-to-time (match-string 1))
16039 (org-time-string-to-time date)))))
16040 (message "%d entries before %s"
16041 (org-occur regexp nil callback) date)))
16043 (defun org-check-after-date (date)
16044 "Check if there are deadlines or scheduled entries after DATE."
16045 (interactive (list (org-read-date)))
16046 (let ((case-fold-search nil)
16047 (regexp (org-re-timestamp org-ts-type))
16048 (callback
16049 (lambda () (not
16050 (time-less-p
16051 (org-time-string-to-time (match-string 1))
16052 (org-time-string-to-time date))))))
16053 (message "%d entries after %s"
16054 (org-occur regexp nil callback) date)))
16056 (defun org-check-dates-range (start-date end-date)
16057 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16058 (interactive (list (org-read-date nil nil nil "Range starts")
16059 (org-read-date nil nil nil "Range end")))
16060 (let ((case-fold-search nil)
16061 (regexp (org-re-timestamp org-ts-type))
16062 (callback
16063 (lambda ()
16064 (let ((match (match-string 1)))
16065 (and
16066 (not (time-less-p
16067 (org-time-string-to-time match)
16068 (org-time-string-to-time start-date)))
16069 (time-less-p
16070 (org-time-string-to-time match)
16071 (org-time-string-to-time end-date)))))))
16072 (message "%d entries between %s and %s"
16073 (org-occur regexp nil callback) start-date end-date)))
16075 (defun org-evaluate-time-range (&optional to-buffer)
16076 "Evaluate a time range by computing the difference between start and end.
16077 Normally the result is just printed in the echo area, but with prefix arg
16078 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16079 If the time range is actually in a table, the result is inserted into the
16080 next column.
16081 For time difference computation, a year is assumed to be exactly 365
16082 days in order to avoid rounding problems."
16083 (interactive "P")
16085 (org-clock-update-time-maybe)
16086 (save-excursion
16087 (unless (org-at-date-range-p t)
16088 (goto-char (point-at-bol))
16089 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16090 (if (not (org-at-date-range-p t))
16091 (error "Not at a time-stamp range, and none found in current line")))
16092 (let* ((ts1 (match-string 1))
16093 (ts2 (match-string 2))
16094 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16095 (match-end (match-end 0))
16096 (time1 (org-time-string-to-time ts1))
16097 (time2 (org-time-string-to-time ts2))
16098 (t1 (org-float-time time1))
16099 (t2 (org-float-time time2))
16100 (diff (abs (- t2 t1)))
16101 (negative (< (- t2 t1) 0))
16102 ;; (ys (floor (* 365 24 60 60)))
16103 (ds (* 24 60 60))
16104 (hs (* 60 60))
16105 (fy "%dy %dd %02d:%02d")
16106 (fy1 "%dy %dd")
16107 (fd "%dd %02d:%02d")
16108 (fd1 "%dd")
16109 (fh "%02d:%02d")
16110 y d h m align)
16111 (if havetime
16112 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16114 d (floor (/ diff ds)) diff (mod diff ds)
16115 h (floor (/ diff hs)) diff (mod diff hs)
16116 m (floor (/ diff 60)))
16117 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16119 d (floor (+ (/ diff ds) 0.5))
16120 h 0 m 0))
16121 (if (not to-buffer)
16122 (message "%s" (org-make-tdiff-string y d h m))
16123 (if (org-at-table-p)
16124 (progn
16125 (goto-char match-end)
16126 (setq align t)
16127 (and (looking-at " *|") (goto-char (match-end 0))))
16128 (goto-char match-end))
16129 (if (looking-at
16130 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16131 (replace-match ""))
16132 (if negative (insert " -"))
16133 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16134 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16135 (insert " " (format fh h m))))
16136 (if align (org-table-align))
16137 (message "Time difference inserted")))))
16139 (defun org-make-tdiff-string (y d h m)
16140 (let ((fmt "")
16141 (l nil))
16142 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16143 l (push y l)))
16144 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16145 l (push d l)))
16146 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16147 l (push h l)))
16148 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16149 l (push m l)))
16150 (apply 'format fmt (nreverse l))))
16152 (defun org-time-string-to-time (s &optional buffer pos)
16153 "Convert a timestamp string into internal time."
16154 (condition-case errdata
16155 (apply 'encode-time (org-parse-time-string s))
16156 (error (error "Bad timestamp `%s'%s\nError was: %s"
16157 s (if (not (and buffer pos))
16159 (format " at %d in buffer `%s'" pos buffer))
16160 (cdr errdata)))))
16162 (defun org-time-string-to-seconds (s)
16163 "Convert a timestamp string to a number of seconds."
16164 (org-float-time (org-time-string-to-time s)))
16166 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16167 "Convert a time stamp to an absolute day number.
16168 If there is a specifier for a cyclic time stamp, get the closest date to
16169 DAYNR.
16170 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16171 The variable date is bound by the calendar when this is called."
16172 (cond
16173 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16174 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16175 daynr
16176 (+ daynr 1000)))
16177 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16178 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16179 (time-to-days (current-time))) (match-string 0 s)
16180 prefer show-all))
16181 (t (time-to-days
16182 (condition-case errdata
16183 (apply 'encode-time (org-parse-time-string s))
16184 (error (error "Bad timestamp `%s'%s\nError was: %s"
16185 s (if (not (and buffer pos))
16187 (format " at %d in buffer `%s'" pos buffer))
16188 (cdr errdata))))))))
16190 (defun org-days-to-iso-week (days)
16191 "Return the iso week number."
16192 (require 'cal-iso)
16193 (car (calendar-iso-from-absolute days)))
16195 (defun org-small-year-to-year (year)
16196 "Convert 2-digit years into 4-digit years.
16197 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16198 The year 2000 cannot be abbreviated. Any year larger than 99
16199 is returned unchanged."
16200 (if (< year 38)
16201 (setq year (+ 2000 year))
16202 (if (< year 100)
16203 (setq year (+ 1900 year))))
16204 year)
16206 (defun org-time-from-absolute (d)
16207 "Return the time corresponding to date D.
16208 D may be an absolute day number, or a calendar-type list (month day year)."
16209 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16210 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16212 (defun org-calendar-holiday ()
16213 "List of holidays, for Diary display in Org-mode."
16214 (require 'holidays)
16215 (let ((hl (funcall
16216 (if (fboundp 'calendar-check-holidays)
16217 'calendar-check-holidays 'check-calendar-holidays) date)))
16218 (if hl (mapconcat 'identity hl "; "))))
16220 (defun org-diary-sexp-entry (sexp entry date)
16221 "Process a SEXP diary ENTRY for DATE."
16222 (require 'diary-lib)
16223 (let ((result (if calendar-debug-sexp
16224 (let ((stack-trace-on-error t))
16225 (eval (car (read-from-string sexp))))
16226 (condition-case nil
16227 (eval (car (read-from-string sexp)))
16228 (error
16229 (beep)
16230 (message "Bad sexp at line %d in %s: %s"
16231 (org-current-line)
16232 (buffer-file-name) sexp)
16233 (sleep-for 2))))))
16234 (cond ((stringp result) (split-string result "; "))
16235 ((and (consp result)
16236 (not (consp (cdr result)))
16237 (stringp (cdr result))) (cdr result))
16238 ((and (consp result)
16239 (stringp (car result))) result)
16240 (result entry))))
16242 (defun org-diary-to-ical-string (frombuf)
16243 "Get iCalendar entries from diary entries in buffer FROMBUF.
16244 This uses the icalendar.el library."
16245 (let* ((tmpdir (if (featurep 'xemacs)
16246 (temp-directory)
16247 temporary-file-directory))
16248 (tmpfile (make-temp-name
16249 (expand-file-name "orgics" tmpdir)))
16250 buf rtn b e)
16251 (with-current-buffer frombuf
16252 (icalendar-export-region (point-min) (point-max) tmpfile)
16253 (setq buf (find-buffer-visiting tmpfile))
16254 (set-buffer buf)
16255 (goto-char (point-min))
16256 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16257 (setq b (match-beginning 0)))
16258 (goto-char (point-max))
16259 (if (re-search-backward "^END:VEVENT" nil t)
16260 (setq e (match-end 0)))
16261 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16262 (kill-buffer buf)
16263 (delete-file tmpfile)
16264 rtn))
16266 (defun org-closest-date (start current change prefer show-all)
16267 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16268 When PREFER is `past', return a date that is either CURRENT or past.
16269 When PREFER is `future', return a date that is either CURRENT or future.
16270 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16271 ;; Make the proper lists from the dates
16272 (catch 'exit
16273 (let ((a1 '(("h" . hour)
16274 ("d" . day)
16275 ("w" . week)
16276 ("m" . month)
16277 ("y" . year)))
16278 (shour (nth 2 (org-parse-time-string start)))
16279 dn dw sday cday n1 n2 n0
16280 d m y y1 y2 date1 date2 nmonths nm ny m2)
16282 (setq start (org-date-to-gregorian start)
16283 current (org-date-to-gregorian
16284 (if show-all
16285 current
16286 (time-to-days (current-time))))
16287 sday (calendar-absolute-from-gregorian start)
16288 cday (calendar-absolute-from-gregorian current))
16290 (if (<= cday sday) (throw 'exit sday))
16292 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16293 (setq dn (string-to-number (match-string 1 change))
16294 dw (cdr (assoc (match-string 2 change) a1)))
16295 (error "Invalid change specifier: %s" change))
16296 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16297 (cond
16298 ((eq dw 'hour)
16299 (let ((missing-hours
16300 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16301 dn)))
16302 (setq n1 (if (zerop missing-hours) cday
16303 (- cday (1+ (floor (/ missing-hours 24)))))
16304 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16305 ((eq dw 'day)
16306 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16307 n2 (+ n1 dn)))
16308 ((eq dw 'year)
16309 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16310 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16311 (setq date1 (list m d y1)
16312 n1 (calendar-absolute-from-gregorian date1)
16313 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16314 n2 (calendar-absolute-from-gregorian date2)))
16315 ((eq dw 'month)
16316 ;; approx number of month between the two dates
16317 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16318 ;; How often does dn fit in there?
16319 (setq d (nth 1 start) m (car start) y (nth 2 start)
16320 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16321 m (+ m nm)
16322 ny (floor (/ m 12))
16323 y (+ y ny)
16324 m (- m (* ny 12)))
16325 (while (> m 12) (setq m (- m 12) y (1+ y)))
16326 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16327 (setq m2 (+ m dn) y2 y)
16328 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16329 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16330 (while (<= n2 cday)
16331 (setq n1 n2 m m2 y y2)
16332 (setq m2 (+ m dn) y2 y)
16333 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16334 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16335 ;; Make sure n1 is the earlier date
16336 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16337 (if show-all
16338 (cond
16339 ((eq prefer 'past) (if (= cday n2) n2 n1))
16340 ((eq prefer 'future) (if (= cday n1) n1 n2))
16341 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16342 (cond
16343 ((eq prefer 'past) (if (= cday n2) n2 n1))
16344 ((eq prefer 'future) (if (= cday n1) n1 n2))
16345 (t (if (= cday n1) n1 n2)))))))
16347 (defun org-date-to-gregorian (date)
16348 "Turn any specification of DATE into a Gregorian date for the calendar."
16349 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16350 ((and (listp date) (= (length date) 3)) date)
16351 ((stringp date)
16352 (setq date (org-parse-time-string date))
16353 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16354 ((listp date)
16355 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16357 (defun org-parse-time-string (s &optional nodefault)
16358 "Parse the standard Org-mode time string.
16359 This should be a lot faster than the normal `parse-time-string'.
16360 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16361 hour and minute fields will be nil if not given."
16362 (if (string-match org-ts-regexp0 s)
16363 (list 0
16364 (if (or (match-beginning 8) (not nodefault))
16365 (string-to-number (or (match-string 8 s) "0")))
16366 (if (or (match-beginning 7) (not nodefault))
16367 (string-to-number (or (match-string 7 s) "0")))
16368 (string-to-number (match-string 4 s))
16369 (string-to-number (match-string 3 s))
16370 (string-to-number (match-string 2 s))
16371 nil nil nil)
16372 (error "Not a standard Org-mode time string: %s" s)))
16374 (defun org-timestamp-up (&optional arg)
16375 "Increase the date item at the cursor by one.
16376 If the cursor is on the year, change the year. If it is on the month,
16377 the day or the time, change that.
16378 With prefix ARG, change by that many units."
16379 (interactive "p")
16380 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16382 (defun org-timestamp-down (&optional arg)
16383 "Decrease the date item at the cursor by one.
16384 If the cursor is on the year, change the year. If it is on the month,
16385 the day or the time, change that.
16386 With prefix ARG, change by that many units."
16387 (interactive "p")
16388 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16390 (defun org-timestamp-up-day (&optional arg)
16391 "Increase the date in the time stamp by one day.
16392 With prefix ARG, change that many days."
16393 (interactive "p")
16394 (if (and (not (org-at-timestamp-p t))
16395 (org-at-heading-p))
16396 (org-todo 'up)
16397 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16399 (defun org-timestamp-down-day (&optional arg)
16400 "Decrease the date in the time stamp by one day.
16401 With prefix ARG, change that many days."
16402 (interactive "p")
16403 (if (and (not (org-at-timestamp-p t))
16404 (org-at-heading-p))
16405 (org-todo 'down)
16406 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16408 (defun org-at-timestamp-p (&optional inactive-ok)
16409 "Determine if the cursor is in or at a timestamp."
16410 (interactive)
16411 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16412 (pos (point))
16413 (ans (or (looking-at tsr)
16414 (save-excursion
16415 (skip-chars-backward "^[<\n\r\t")
16416 (if (> (point) (point-min)) (backward-char 1))
16417 (and (looking-at tsr)
16418 (> (- (match-end 0) pos) -1))))))
16419 (and ans
16420 (boundp 'org-ts-what)
16421 (setq org-ts-what
16422 (cond
16423 ((= pos (match-beginning 0)) 'bracket)
16424 ;; Point is considered to be "on the bracket" whether
16425 ;; it's really on it or right after it.
16426 ((= pos (1- (match-end 0))) 'bracket)
16427 ((= pos (match-end 0)) 'after)
16428 ((org-pos-in-match-range pos 2) 'year)
16429 ((org-pos-in-match-range pos 3) 'month)
16430 ((org-pos-in-match-range pos 7) 'hour)
16431 ((org-pos-in-match-range pos 8) 'minute)
16432 ((or (org-pos-in-match-range pos 4)
16433 (org-pos-in-match-range pos 5)) 'day)
16434 ((and (> pos (or (match-end 8) (match-end 5)))
16435 (< pos (match-end 0)))
16436 (- pos (or (match-end 8) (match-end 5))))
16437 (t 'day))))
16438 ans))
16440 (defun org-toggle-timestamp-type ()
16441 "Toggle the type (<active> or [inactive]) of a time stamp."
16442 (interactive)
16443 (when (org-at-timestamp-p t)
16444 (let ((beg (match-beginning 0)) (end (match-end 0))
16445 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16446 (save-excursion
16447 (goto-char beg)
16448 (while (re-search-forward "[][<>]" end t)
16449 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16450 t t)))
16451 (message "Timestamp is now %sactive"
16452 (if (equal (char-after beg) ?<) "" "in")))))
16454 (defvar org-clock-history) ; defined in org-clock.el
16455 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16456 (defun org-timestamp-change (n &optional what updown)
16457 "Change the date in the time stamp at point.
16458 The date will be changed by N times WHAT. WHAT can be `day', `month',
16459 `year', `minute', `second'. If WHAT is not given, the cursor position
16460 in the timestamp determines what will be changed."
16461 (let ((origin (point)) origin-cat
16462 with-hm inactive
16463 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16464 org-ts-what
16465 extra rem
16466 ts time time0 fixnext clrgx)
16467 (if (not (org-at-timestamp-p t))
16468 (error "Not at a timestamp"))
16469 (if (and (not what) (eq org-ts-what 'bracket))
16470 (org-toggle-timestamp-type)
16471 ;; Point isn't on brackets. Remember the part of the time-stamp
16472 ;; the point was in. Indeed, size of time-stamps may change,
16473 ;; but point must be kept in the same category nonetheless.
16474 (setq origin-cat org-ts-what)
16475 (if (and (not what) (not (eq org-ts-what 'day))
16476 org-display-custom-times
16477 (get-text-property (point) 'display)
16478 (not (get-text-property (1- (point)) 'display)))
16479 (setq org-ts-what 'day))
16480 (setq org-ts-what (or what org-ts-what)
16481 inactive (= (char-after (match-beginning 0)) ?\[)
16482 ts (match-string 0))
16483 (replace-match "")
16484 (if (string-match
16485 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16487 (setq extra (match-string 1 ts)))
16488 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16489 (setq with-hm t))
16490 (setq time0 (org-parse-time-string ts))
16491 (when (and updown
16492 (eq org-ts-what 'minute)
16493 (not current-prefix-arg))
16494 ;; This looks like s-up and s-down. Change by one rounding step.
16495 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16496 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16497 (setcar (cdr time0) (+ (nth 1 time0)
16498 (if (> n 0) (- rem) (- dm rem))))))
16499 (setq time
16500 (encode-time (or (car time0) 0)
16501 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16502 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16503 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16504 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16505 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16506 (nthcdr 6 time0)))
16507 (when (and (member org-ts-what '(hour minute))
16508 extra
16509 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16510 (setq extra (org-modify-ts-extra
16511 extra
16512 (if (eq org-ts-what 'hour) 2 5)
16513 n dm)))
16514 (when (integerp org-ts-what)
16515 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16516 (if (eq what 'calendar)
16517 (let ((cal-date (org-get-date-from-calendar)))
16518 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16519 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16520 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16521 (setcar time0 (or (car time0) 0))
16522 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16523 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16524 (setq time (apply 'encode-time time0))))
16525 ;; Insert the new time-stamp, and ensure point stays in the same
16526 ;; category as before (i.e. not after the last position in that
16527 ;; category).
16528 (let ((pos (point)))
16529 ;; Stay before inserted string. `save-excursion' is of no use.
16530 (setq org-last-changed-timestamp
16531 (org-insert-time-stamp time with-hm inactive nil nil extra))
16532 (goto-char pos))
16533 (save-match-data
16534 (looking-at org-ts-regexp3)
16535 (goto-char (cond
16536 ;; `day' category ends before `hour' if any, or at
16537 ;; the end of the day name.
16538 ((eq origin-cat 'day)
16539 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16540 ((eq origin-cat 'hour) (min (match-end 7) origin))
16541 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16542 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16543 ;; `year' and `month' have both fixed size: point
16544 ;; couldn't have moved into another part.
16545 (t origin))))
16546 ;; Update clock if on a CLOCK line.
16547 (org-clock-update-time-maybe)
16548 ;; Maybe adjust the closest clock in `org-clock-history'
16549 (when org-clock-adjust-closest
16550 (if (not (and (org-at-clock-log-p)
16551 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16552 org-clock-history))))))
16553 (message "No clock to adjust")
16554 (cond ((save-excursion ; fix previous clock?
16555 (re-search-backward org-ts-regexp0 nil t)
16556 (org-looking-back (concat org-clock-string " \\[")))
16557 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16558 ((save-excursion ; fix next clock?
16559 (re-search-backward org-ts-regexp0 nil t)
16560 (looking-at (concat org-ts-regexp0 "\\] =>")))
16561 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16562 (save-window-excursion
16563 ;; Find closest clock to point, adjust the previous/next one in history
16564 (let* ((p (save-excursion (org-back-to-heading t)))
16565 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16566 (clfixnth
16567 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16568 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16569 (if (not clfixpos)
16570 (message "No clock to adjust")
16571 (save-excursion
16572 (org-goto-marker-or-bmk clfixpos)
16573 (org-show-subtree)
16574 (when (re-search-forward clrgx nil t)
16575 (goto-char (match-beginning 1))
16576 (let (org-clock-adjust-closest)
16577 (org-timestamp-change n org-ts-what updown))
16578 (message "Clock adjusted in %s for heading: %s"
16579 (file-name-nondirectory (buffer-file-name))
16580 (org-get-heading t t)))))))))
16581 ;; Try to recenter the calendar window, if any.
16582 (if (and org-calendar-follow-timestamp-change
16583 (get-buffer-window "*Calendar*" t)
16584 (memq org-ts-what '(day month year)))
16585 (org-recenter-calendar (time-to-days time))))))
16587 (defun org-modify-ts-extra (s pos n dm)
16588 "Change the different parts of the lead-time and repeat fields in timestamp."
16589 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16590 ng h m new rem)
16591 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16592 (cond
16593 ((or (org-pos-in-match-range pos 2)
16594 (org-pos-in-match-range pos 3))
16595 (setq m (string-to-number (match-string 3 s))
16596 h (string-to-number (match-string 2 s)))
16597 (if (org-pos-in-match-range pos 2)
16598 (setq h (+ h n))
16599 (setq n (* dm (org-no-warnings (signum n))))
16600 (when (not (= 0 (setq rem (% m dm))))
16601 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16602 (setq m (+ m n)))
16603 (if (< m 0) (setq m (+ m 60) h (1- h)))
16604 (if (> m 59) (setq m (- m 60) h (1+ h)))
16605 (setq h (min 24 (max 0 h)))
16606 (setq ng 1 new (format "-%02d:%02d" h m)))
16607 ((org-pos-in-match-range pos 6)
16608 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16609 ((org-pos-in-match-range pos 5)
16610 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16612 ((org-pos-in-match-range pos 9)
16613 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16614 ((org-pos-in-match-range pos 8)
16615 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16617 (when ng
16618 (setq s (concat
16619 (substring s 0 (match-beginning ng))
16621 (substring s (match-end ng))))))
16624 (defun org-recenter-calendar (date)
16625 "If the calendar is visible, recenter it to DATE."
16626 (let ((cwin (get-buffer-window "*Calendar*" t)))
16627 (when cwin
16628 (let ((calendar-move-hook nil))
16629 (with-selected-window cwin
16630 (calendar-goto-date (if (listp date) date
16631 (calendar-gregorian-from-absolute date))))))))
16633 (defun org-goto-calendar (&optional arg)
16634 "Go to the Emacs calendar at the current date.
16635 If there is a time stamp in the current line, go to that date.
16636 A prefix ARG can be used to force the current date."
16637 (interactive "P")
16638 (let ((tsr org-ts-regexp) diff
16639 (calendar-move-hook nil)
16640 (calendar-view-holidays-initially-flag nil)
16641 (calendar-view-diary-initially-flag nil))
16642 (if (or (org-at-timestamp-p)
16643 (save-excursion
16644 (beginning-of-line 1)
16645 (looking-at (concat ".*" tsr))))
16646 (let ((d1 (time-to-days (current-time)))
16647 (d2 (time-to-days
16648 (org-time-string-to-time (match-string 1)))))
16649 (setq diff (- d2 d1))))
16650 (calendar)
16651 (calendar-goto-today)
16652 (if (and diff (not arg)) (calendar-forward-day diff))))
16654 (defun org-get-date-from-calendar ()
16655 "Return a list (month day year) of date at point in calendar."
16656 (with-current-buffer "*Calendar*"
16657 (save-match-data
16658 (calendar-cursor-to-date))))
16660 (defun org-date-from-calendar ()
16661 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16662 If there is already a time stamp at the cursor position, update it."
16663 (interactive)
16664 (if (org-at-timestamp-p t)
16665 (org-timestamp-change 0 'calendar)
16666 (let ((cal-date (org-get-date-from-calendar)))
16667 (org-insert-time-stamp
16668 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16670 (defun org-minutes-to-hh:mm-string (m)
16671 "Compute H:MM from a number of minutes."
16672 (let ((h (/ m 60)))
16673 (setq m (- m (* 60 h)))
16674 (format org-time-clocksum-format h m)))
16676 (defun org-hh:mm-string-to-minutes (s)
16677 "Convert a string H:MM to a number of minutes.
16678 If the string is just a number, interpret it as minutes.
16679 In fact, the first hh:mm or number in the string will be taken,
16680 there can be extra stuff in the string.
16681 If no number is found, the return value is 0."
16682 (cond
16683 ((integerp s) s)
16684 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16685 (+ (* (string-to-number (match-string 1 s)) 60)
16686 (string-to-number (match-string 2 s))))
16687 ((string-match "\\([0-9]+\\)" s)
16688 (string-to-number (match-string 1 s)))
16689 (t 0)))
16691 (defcustom org-effort-durations
16692 `(("h" . 60)
16693 ("d" . ,(* 60 8))
16694 ("w" . ,(* 60 8 5))
16695 ("m" . ,(* 60 8 5 4))
16696 ("y" . ,(* 60 8 5 40)))
16697 "Conversion factor to minutes for an effort modifier.
16699 Each entry has the form (MODIFIER . MINUTES).
16701 In an effort string, a number followed by MODIFIER is multiplied
16702 by the specified number of MINUTES to obtain an effort in
16703 minutes.
16705 For example, if the value of this variable is ((\"hours\" . 60)), then an
16706 effort string \"2hours\" is equivalent to 120 minutes."
16707 :group 'org-agenda
16708 :version "24.1"
16709 :type '(alist :key-type (string :tag "Modifier")
16710 :value-type (number :tag "Minutes")))
16712 (defcustom org-image-actual-width t
16713 "Should we use the actual width of images when inlining them?
16715 When set to `t', always use the image width.
16717 When set to a number, use imagemagick (when available) to set
16718 the image's width to this value.
16720 When set to a number in a list, try to get the width from the
16721 #+ATTR.* keyword if it matches a width specification like
16722 width=\"[0-9]+\", and fall back on that number if none is found.
16724 When set to nil, try to get the width from an #+ATTR.* keyword
16725 and fall back on the original width if none is found.
16727 This requires Emacs >= 24.1, build with imagemagick support."
16728 :group 'org-appearance
16729 :version "24.3"
16730 :type '(choice
16731 (const :tag "Use the image width" t)
16732 (integer :tag "Use a number of pixels")
16733 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16734 (const :tag "Use #+ATTR* or don't resize" nil)))
16736 (defun org-duration-string-to-minutes (s &optional output-to-string)
16737 "Convert a duration string S to minutes.
16739 A bare number is interpreted as minutes, modifiers can be set by
16740 customizing `org-effort-durations' (which see).
16742 Entries containing a colon are interpreted as H:MM by
16743 `org-hh:mm-string-to-minutes'."
16744 (let ((result 0)
16745 (re (concat "\\([0-9.]+\\) *\\("
16746 (regexp-opt (mapcar 'car org-effort-durations))
16747 "\\)")))
16748 (while (string-match re s)
16749 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16750 (string-to-number (match-string 1 s))))
16751 (setq s (replace-match "" nil t s)))
16752 (setq result (floor result))
16753 (incf result (org-hh:mm-string-to-minutes s))
16754 (if output-to-string (number-to-string result) result)))
16756 ;;;; Files
16758 (defun org-save-all-org-buffers ()
16759 "Save all Org-mode buffers without user confirmation."
16760 (interactive)
16761 (message "Saving all Org-mode buffers...")
16762 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16763 (when (featurep 'org-id) (org-id-locations-save))
16764 (message "Saving all Org-mode buffers... done"))
16766 (defun org-revert-all-org-buffers ()
16767 "Revert all Org-mode buffers.
16768 Prompt for confirmation when there are unsaved changes.
16769 Be sure you know what you are doing before letting this function
16770 overwrite your changes.
16772 This function is useful in a setup where one tracks org files
16773 with a version control system, to revert on one machine after pulling
16774 changes from another. I believe the procedure must be like this:
16776 1. M-x org-save-all-org-buffers
16777 2. Pull changes from the other machine, resolve conflicts
16778 3. M-x org-revert-all-org-buffers"
16779 (interactive)
16780 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16781 (error "Abort"))
16782 (save-excursion
16783 (save-window-excursion
16784 (mapc
16785 (lambda (b)
16786 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16787 (with-current-buffer b buffer-file-name))
16788 (org-pop-to-buffer-same-window b)
16789 (revert-buffer t 'no-confirm)))
16790 (buffer-list))
16791 (when (and (featurep 'org-id) org-id-track-globally)
16792 (org-id-locations-load)))))
16794 ;;;; Agenda files
16796 ;;;###autoload
16797 (defun org-switchb (&optional arg)
16798 "Switch between Org buffers.
16799 With one prefix argument, restrict available buffers to files.
16800 With two prefix arguments, restrict available buffers to agenda files.
16802 Defaults to `iswitchb' for buffer name completion.
16803 Set `org-completion-use-ido' to make it use ido instead."
16804 (interactive "P")
16805 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16806 ((equal arg '(16)) (org-buffer-list 'agenda))
16807 (t (org-buffer-list))))
16808 (org-completion-use-iswitchb org-completion-use-iswitchb)
16809 (org-completion-use-ido org-completion-use-ido))
16810 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16811 (setq org-completion-use-iswitchb t))
16812 (org-pop-to-buffer-same-window
16813 (org-icompleting-read "Org buffer: "
16814 (mapcar 'list (mapcar 'buffer-name blist))
16815 nil t))))
16817 ;;; Define some older names previously used for this functionality
16818 ;;;###autoload
16819 (defalias 'org-ido-switchb 'org-switchb)
16820 ;;;###autoload
16821 (defalias 'org-iswitchb 'org-switchb)
16823 (defun org-buffer-list (&optional predicate exclude-tmp)
16824 "Return a list of Org buffers.
16825 PREDICATE can be `export', `files' or `agenda'.
16827 export restrict the list to Export buffers.
16828 files restrict the list to buffers visiting Org files.
16829 agenda restrict the list to buffers visiting agenda files.
16831 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16832 (let* ((bfn nil)
16833 (agenda-files (and (eq predicate 'agenda)
16834 (mapcar 'file-truename (org-agenda-files t))))
16835 (filter
16836 (cond
16837 ((eq predicate 'files)
16838 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16839 ((eq predicate 'export)
16840 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16841 ((eq predicate 'agenda)
16842 (lambda (b)
16843 (with-current-buffer b
16844 (and (derived-mode-p 'org-mode)
16845 (setq bfn (buffer-file-name b))
16846 (member (file-truename bfn) agenda-files)))))
16847 (t (lambda (b) (with-current-buffer b
16848 (or (derived-mode-p 'org-mode)
16849 (string-match "\*Org .*Export"
16850 (buffer-name b)))))))))
16851 (delq nil
16852 (mapcar
16853 (lambda(b)
16854 (if (and (funcall filter b)
16855 (or (not exclude-tmp)
16856 (not (string-match "tmp" (buffer-name b)))))
16858 nil))
16859 (buffer-list)))))
16861 (defun org-agenda-files (&optional unrestricted archives)
16862 "Get the list of agenda files.
16863 Optional UNRESTRICTED means return the full list even if a restriction
16864 is currently in place.
16865 When ARCHIVES is t, include all archive files that are really being
16866 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16867 `org-agenda-archives-mode' is t."
16868 (let ((files
16869 (cond
16870 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16871 ((stringp org-agenda-files) (org-read-agenda-file-list))
16872 ((listp org-agenda-files) org-agenda-files)
16873 (t (error "Invalid value of `org-agenda-files'")))))
16874 (setq files (apply 'append
16875 (mapcar (lambda (f)
16876 (if (file-directory-p f)
16877 (directory-files
16878 f t org-agenda-file-regexp)
16879 (list f)))
16880 files)))
16881 (when org-agenda-skip-unavailable-files
16882 (setq files (delq nil
16883 (mapcar (function
16884 (lambda (file)
16885 (and (file-readable-p file) file)))
16886 files))))
16887 (when (or (eq archives t)
16888 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16889 (setq files (org-add-archive-files files)))
16890 files))
16892 (defun org-agenda-file-p (&optional file)
16893 "Return non-nil, if FILE is an agenda file.
16894 If FILE is omitted, use the file associated with the current
16895 buffer."
16896 (member (or file (buffer-file-name))
16897 (org-agenda-files t)))
16899 (defun org-edit-agenda-file-list ()
16900 "Edit the list of agenda files.
16901 Depending on setup, this either uses customize to edit the variable
16902 `org-agenda-files', or it visits the file that is holding the list. In the
16903 latter case, the buffer is set up in a way that saving it automatically kills
16904 the buffer and restores the previous window configuration."
16905 (interactive)
16906 (if (stringp org-agenda-files)
16907 (let ((cw (current-window-configuration)))
16908 (find-file org-agenda-files)
16909 (org-set-local 'org-window-configuration cw)
16910 (org-add-hook 'after-save-hook
16911 (lambda ()
16912 (set-window-configuration
16913 (prog1 org-window-configuration
16914 (kill-buffer (current-buffer))))
16915 (org-install-agenda-files-menu)
16916 (message "New agenda file list installed"))
16917 nil 'local)
16918 (message "%s" (substitute-command-keys
16919 "Edit list and finish with \\[save-buffer]")))
16920 (customize-variable 'org-agenda-files)))
16922 (defun org-store-new-agenda-file-list (list)
16923 "Set new value for the agenda file list and save it correctly."
16924 (if (stringp org-agenda-files)
16925 (let ((fe (org-read-agenda-file-list t)) b u)
16926 (while (setq b (find-buffer-visiting org-agenda-files))
16927 (kill-buffer b))
16928 (with-temp-file org-agenda-files
16929 (insert
16930 (mapconcat
16931 (lambda (f) ;; Keep un-expanded entries.
16932 (if (setq u (assoc f fe))
16933 (cdr u)
16935 list "\n")
16936 "\n")))
16937 (let ((org-mode-hook nil) (org-inhibit-startup t)
16938 (org-insert-mode-line-in-empty-file nil))
16939 (setq org-agenda-files list)
16940 (customize-save-variable 'org-agenda-files org-agenda-files))))
16942 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16943 "Read the list of agenda files from a file.
16944 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16945 filenames, used by `org-store-new-agenda-file-list' to write back
16946 un-expanded file names."
16947 (when (file-directory-p org-agenda-files)
16948 (error "`org-agenda-files' cannot be a single directory"))
16949 (when (stringp org-agenda-files)
16950 (with-temp-buffer
16951 (insert-file-contents org-agenda-files)
16952 (mapcar
16953 (lambda (f)
16954 (let ((e (expand-file-name (substitute-in-file-name f)
16955 org-directory)))
16956 (if pair-with-expansion
16957 (cons e f)
16958 e)))
16959 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16961 ;;;###autoload
16962 (defun org-cycle-agenda-files ()
16963 "Cycle through the files in `org-agenda-files'.
16964 If the current buffer visits an agenda file, find the next one in the list.
16965 If the current buffer does not, find the first agenda file."
16966 (interactive)
16967 (let* ((fs (org-agenda-files t))
16968 (files (append fs (list (car fs))))
16969 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16970 file)
16971 (unless files (error "No agenda files"))
16972 (catch 'exit
16973 (while (setq file (pop files))
16974 (if (equal (file-truename file) tcf)
16975 (when (car files)
16976 (find-file (car files))
16977 (throw 'exit t))))
16978 (find-file (car fs)))
16979 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16981 (defun org-agenda-file-to-front (&optional to-end)
16982 "Move/add the current file to the top of the agenda file list.
16983 If the file is not present in the list, it is added to the front. If it is
16984 present, it is moved there. With optional argument TO-END, add/move to the
16985 end of the list."
16986 (interactive "P")
16987 (let ((org-agenda-skip-unavailable-files nil)
16988 (file-alist (mapcar (lambda (x)
16989 (cons (file-truename x) x))
16990 (org-agenda-files t)))
16991 (ctf (file-truename
16992 (or buffer-file-name
16993 (error "Please save the current buffer to a file"))))
16994 x had)
16995 (setq x (assoc ctf file-alist) had x)
16997 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16998 (if to-end
16999 (setq file-alist (append (delq x file-alist) (list x)))
17000 (setq file-alist (cons x (delq x file-alist))))
17001 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17002 (org-install-agenda-files-menu)
17003 (message "File %s to %s of agenda file list"
17004 (if had "moved" "added") (if to-end "end" "front"))))
17006 (defun org-remove-file (&optional file)
17007 "Remove current file from the list of files in variable `org-agenda-files'.
17008 These are the files which are being checked for agenda entries.
17009 Optional argument FILE means use this file instead of the current."
17010 (interactive)
17011 (let* ((org-agenda-skip-unavailable-files nil)
17012 (file (or file buffer-file-name
17013 (error "Current buffer does not visit a file")))
17014 (true-file (file-truename file))
17015 (afile (abbreviate-file-name file))
17016 (files (delq nil (mapcar
17017 (lambda (x)
17018 (if (equal true-file
17019 (file-truename x))
17020 nil x))
17021 (org-agenda-files t)))))
17022 (if (not (= (length files) (length (org-agenda-files t))))
17023 (progn
17024 (org-store-new-agenda-file-list files)
17025 (org-install-agenda-files-menu)
17026 (message "Removed file: %s" afile))
17027 (message "File was not in list: %s (not removed)" afile))))
17029 (defun org-file-menu-entry (file)
17030 (vector file (list 'find-file file) t))
17032 (defun org-check-agenda-file (file)
17033 "Make sure FILE exists. If not, ask user what to do."
17034 (when (not (file-exists-p file))
17035 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17036 (abbreviate-file-name file))
17037 (let ((r (downcase (read-char-exclusive))))
17038 (cond
17039 ((equal r ?r)
17040 (org-remove-file file)
17041 (throw 'nextfile t))
17042 (t (error "Abort"))))))
17044 (defun org-get-agenda-file-buffer (file)
17045 "Get a buffer visiting FILE. If the buffer needs to be created, add
17046 it to the list of buffers which might be released later."
17047 (let ((buf (org-find-base-buffer-visiting file)))
17048 (if buf
17049 buf ; just return it
17050 ;; Make a new buffer and remember it
17051 (setq buf (find-file-noselect file))
17052 (if buf (push buf org-agenda-new-buffers))
17053 buf)))
17055 (defun org-release-buffers (blist)
17056 "Release all buffers in list, asking the user for confirmation when needed.
17057 When a buffer is unmodified, it is just killed. When modified, it is saved
17058 \(if the user agrees) and then killed."
17059 (let (buf file)
17060 (while (setq buf (pop blist))
17061 (setq file (buffer-file-name buf))
17062 (when (and (buffer-modified-p buf)
17063 file
17064 (y-or-n-p (format "Save file %s? " file)))
17065 (with-current-buffer buf (save-buffer)))
17066 (kill-buffer buf))))
17068 (defun org-agenda-prepare-buffers (files)
17069 "Create buffers for all agenda files, protect archived trees and comments."
17070 (interactive)
17071 (let ((pa '(:org-archived t))
17072 (pc '(:org-comment t))
17073 (pall '(:org-archived t :org-comment t))
17074 (inhibit-read-only t)
17075 (rea (concat ":" org-archive-tag ":"))
17076 bmp file re)
17077 (save-excursion
17078 (save-restriction
17079 (while (setq file (pop files))
17080 (catch 'nextfile
17081 (if (bufferp file)
17082 (set-buffer file)
17083 (org-check-agenda-file file)
17084 (set-buffer (org-get-agenda-file-buffer file)))
17085 (widen)
17086 (setq bmp (buffer-modified-p))
17087 (org-refresh-category-properties)
17088 (setq org-todo-keywords-for-agenda
17089 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17090 (setq org-done-keywords-for-agenda
17091 (append org-done-keywords-for-agenda org-done-keywords))
17092 (setq org-todo-keyword-alist-for-agenda
17093 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17094 (setq org-drawers-for-agenda
17095 (append org-drawers-for-agenda org-drawers))
17096 (setq org-tag-alist-for-agenda
17097 (append org-tag-alist-for-agenda org-tag-alist))
17099 (save-excursion
17100 (remove-text-properties (point-min) (point-max) pall)
17101 (when org-agenda-skip-archived-trees
17102 (goto-char (point-min))
17103 (while (re-search-forward rea nil t)
17104 (if (org-at-heading-p t)
17105 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17106 (goto-char (point-min))
17107 (setq re (format org-heading-keyword-regexp-format
17108 org-comment-string))
17109 (while (re-search-forward re nil t)
17110 (add-text-properties
17111 (match-beginning 0) (org-end-of-subtree t) pc)))
17112 (set-buffer-modified-p bmp)))))
17113 (setq org-todo-keywords-for-agenda
17114 (org-uniquify org-todo-keywords-for-agenda))
17115 (setq org-todo-keyword-alist-for-agenda
17116 (org-uniquify org-todo-keyword-alist-for-agenda)
17117 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17119 ;;;; Embedded LaTeX
17121 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17122 "Keymap for the minor `org-cdlatex-mode'.")
17124 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17125 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17126 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17127 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17128 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17130 (defvar org-cdlatex-texmathp-advice-is-done nil
17131 "Flag remembering if we have applied the advice to texmathp already.")
17133 (define-minor-mode org-cdlatex-mode
17134 "Toggle the minor `org-cdlatex-mode'.
17135 This mode supports entering LaTeX environment and math in LaTeX fragments
17136 in Org-mode.
17137 \\{org-cdlatex-mode-map}"
17138 nil " OCDL" nil
17139 (when org-cdlatex-mode
17140 (require 'cdlatex)
17141 (run-hooks 'cdlatex-mode-hook)
17142 (cdlatex-compute-tables))
17143 (unless org-cdlatex-texmathp-advice-is-done
17144 (setq org-cdlatex-texmathp-advice-is-done t)
17145 (defadvice texmathp (around org-math-always-on activate)
17146 "Always return t in org-mode buffers.
17147 This is because we want to insert math symbols without dollars even outside
17148 the LaTeX math segments. If Orgmode thinks that point is actually inside
17149 an embedded LaTeX fragment, let texmathp do its job.
17150 \\[org-cdlatex-mode-map]"
17151 (interactive)
17152 (let (p)
17153 (cond
17154 ((not (derived-mode-p 'org-mode)) ad-do-it)
17155 ((eq this-command 'cdlatex-math-symbol)
17156 (setq ad-return-value t
17157 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17159 (let ((p (org-inside-LaTeX-fragment-p)))
17160 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17161 (setq ad-return-value t
17162 texmathp-why '("Org-mode embedded math" . 0))
17163 (if p ad-do-it)))))))))
17165 (defun turn-on-org-cdlatex ()
17166 "Unconditionally turn on `org-cdlatex-mode'."
17167 (org-cdlatex-mode 1))
17169 (defun org-inside-LaTeX-fragment-p ()
17170 "Test if point is inside a LaTeX fragment.
17171 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17172 sequence appearing also before point.
17173 Even though the matchers for math are configurable, this function assumes
17174 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17175 delimiters are skipped when they have been removed by customization.
17176 The return value is nil, or a cons cell with the delimiter and the
17177 position of this delimiter.
17179 This function does a reasonably good job, but can locally be fooled by
17180 for example currency specifications. For example it will assume being in
17181 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17182 fragments that are properly closed, but during editing, we have to live
17183 with the uncertainty caused by missing closing delimiters. This function
17184 looks only before point, not after."
17185 (catch 'exit
17186 (let ((pos (point))
17187 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17188 (lim (progn
17189 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17190 (point)))
17191 dd-on str (start 0) m re)
17192 (goto-char pos)
17193 (when dodollar
17194 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17195 re (nth 1 (assoc "$" org-latex-regexps)))
17196 (while (string-match re str start)
17197 (cond
17198 ((= (match-end 0) (length str))
17199 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17200 ((= (match-end 0) (- (length str) 5))
17201 (throw 'exit nil))
17202 (t (setq start (match-end 0))))))
17203 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17204 (goto-char pos)
17205 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17206 (and (match-beginning 2) (throw 'exit nil))
17207 ;; count $$
17208 (while (re-search-backward "\\$\\$" lim t)
17209 (setq dd-on (not dd-on)))
17210 (goto-char pos)
17211 (if dd-on (cons "$$" m))))))
17213 (defun org-inside-latex-macro-p ()
17214 "Is point inside a LaTeX macro or its arguments?"
17215 (save-match-data
17216 (org-in-regexp
17217 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17219 (defun org-try-cdlatex-tab ()
17220 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17221 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17222 - inside a LaTeX fragment, or
17223 - after the first word in a line, where an abbreviation expansion could
17224 insert a LaTeX environment."
17225 (when org-cdlatex-mode
17226 (cond
17227 ;; Before any word on the line: No expansion possible.
17228 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17229 ;; Just after first word on the line: Expand it. Make sure it
17230 ;; cannot happen on headlines, though.
17231 ((save-excursion
17232 (skip-chars-backward "a-zA-Z0-9*")
17233 (skip-chars-backward " \t")
17234 (and (bolp) (not (org-at-heading-p))))
17235 (cdlatex-tab) t)
17236 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17238 (defun org-cdlatex-underscore-caret (&optional arg)
17239 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17240 Revert to the normal definition outside of these fragments."
17241 (interactive "P")
17242 (if (org-inside-LaTeX-fragment-p)
17243 (call-interactively 'cdlatex-sub-superscript)
17244 (let (org-cdlatex-mode)
17245 (call-interactively (key-binding (vector last-input-event))))))
17247 (defun org-cdlatex-math-modify (&optional arg)
17248 "Execute `cdlatex-math-modify' in LaTeX fragments.
17249 Revert to the normal definition outside of these fragments."
17250 (interactive "P")
17251 (if (org-inside-LaTeX-fragment-p)
17252 (call-interactively 'cdlatex-math-modify)
17253 (let (org-cdlatex-mode)
17254 (call-interactively (key-binding (vector last-input-event))))))
17256 (defvar org-latex-fragment-image-overlays nil
17257 "List of overlays carrying the images of latex fragments.")
17258 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17260 (defun org-remove-latex-fragment-image-overlays ()
17261 "Remove all overlays with LaTeX fragment images in current buffer."
17262 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17263 (setq org-latex-fragment-image-overlays nil))
17265 (defun org-preview-latex-fragment (&optional subtree)
17266 "Preview the LaTeX fragment at point, or all locally or globally.
17267 If the cursor is in a LaTeX fragment, create the image and overlay
17268 it over the source code. If there is no fragment at point, display
17269 all fragments in the current text, from one headline to the next. With
17270 prefix SUBTREE, display all fragments in the current subtree. With a
17271 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17272 the cursor is before the first headline,
17273 display all fragments in the buffer.
17274 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17275 (interactive "P")
17276 (unless buffer-file-name
17277 (error "Can't preview LaTeX fragment in a non-file buffer"))
17278 (org-remove-latex-fragment-image-overlays)
17279 (save-excursion
17280 (save-restriction
17281 (let (beg end at msg)
17282 (cond
17283 ((or (equal subtree '(16))
17284 (not (save-excursion
17285 (re-search-backward org-outline-regexp-bol nil t))))
17286 (setq beg (point-min) end (point-max)
17287 msg "Creating images for buffer...%s"))
17288 ((equal subtree '(4))
17289 (org-back-to-heading)
17290 (setq beg (point) end (org-end-of-subtree t)
17291 msg "Creating images for subtree...%s"))
17293 (if (setq at (org-inside-LaTeX-fragment-p))
17294 (goto-char (max (point-min) (- (cdr at) 2)))
17295 (org-back-to-heading))
17296 (setq beg (point) end (progn (outline-next-heading) (point))
17297 msg (if at "Creating image...%s"
17298 "Creating images for entry...%s"))))
17299 (message msg "")
17300 (narrow-to-region beg end)
17301 (goto-char beg)
17302 (org-format-latex
17303 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17304 (file-name-nondirectory
17305 buffer-file-name)))
17306 default-directory 'overlays msg at 'forbuffer
17307 org-latex-create-formula-image-program)
17308 (message msg "done. Use `C-c C-c' to remove images.")))))
17310 (defvar org-latex-regexps
17311 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17312 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17313 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17314 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17315 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17316 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17317 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17318 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17319 "Regular expressions for matching embedded LaTeX.")
17321 (defvar org-export-have-math nil) ;; dynamic scoping
17322 (defun org-format-latex (prefix &optional dir overlays msg at
17323 forbuffer processing-type)
17324 "Replace LaTeX fragments with links to an image, and produce images.
17325 Some of the options can be changed using the variable
17326 `org-format-latex-options'."
17327 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17328 (let* ((prefixnodir (file-name-nondirectory prefix))
17329 (absprefix (expand-file-name prefix dir))
17330 (todir (file-name-directory absprefix))
17331 (opt org-format-latex-options)
17332 (optnew org-format-latex-options)
17333 (matchers (plist-get opt :matchers))
17334 (re-list org-latex-regexps)
17335 (org-format-latex-header-extra
17336 (plist-get (org-infile-export-plist) :latex-header-extra))
17337 (cnt 0) txt hash link beg end re e checkdir
17338 string
17339 m n block-type block linkfile movefile ov)
17340 ;; Check the different regular expressions
17341 (while (setq e (pop re-list))
17342 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17343 block (if block-type "\n\n" ""))
17344 (when (member m matchers)
17345 (goto-char (point-min))
17346 (while (re-search-forward re nil t)
17347 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17348 (not (get-text-property (match-beginning n)
17349 'org-protected))
17350 (or (not overlays)
17351 (not (eq (get-char-property (match-beginning n)
17352 'org-overlay-type)
17353 'org-latex-overlay))))
17354 (setq org-export-have-math t)
17355 (cond
17356 ((eq processing-type 'verbatim)
17357 ;; Leave the text verbatim, just protect it
17358 (add-text-properties (match-beginning n) (match-end n)
17359 '(org-protected t)))
17360 ((eq processing-type 'mathjax)
17361 ;; Prepare for MathJax processing
17362 (setq string (match-string n))
17363 (if (member m '("$" "$1"))
17364 (save-excursion
17365 (delete-region (match-beginning n) (match-end n))
17366 (goto-char (match-beginning n))
17367 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17368 "\\)")
17369 '(org-protected t))))
17370 (add-text-properties (match-beginning n) (match-end n)
17371 '(org-protected t))))
17372 ((or (eq processing-type 'dvipng)
17373 (eq processing-type 'imagemagick))
17374 ;; Process to an image
17375 (setq txt (match-string n)
17376 beg (match-beginning n) end (match-end n)
17377 cnt (1+ cnt))
17378 (let ((face (face-at-point))
17379 (fg (plist-get opt :foreground))
17380 (bg (plist-get opt :background))
17381 print-length print-level) ; make sure full list is printed
17382 (when forbuffer
17383 ; Get the colors from the face at point
17384 (goto-char beg)
17385 (when (eq fg 'auto)
17386 (setq fg (face-attribute face :foreground nil 'default)))
17387 (when (eq bg 'auto)
17388 (setq bg (face-attribute face :background nil 'default)))
17389 (setq optnew (copy-sequence opt))
17390 (plist-put optnew :foreground fg)
17391 (plist-put optnew :background bg))
17392 (setq hash (sha1 (prin1-to-string
17393 (list org-format-latex-header
17394 org-format-latex-header-extra
17395 org-export-latex-default-packages-alist
17396 org-export-latex-packages-alist
17397 org-format-latex-options
17398 forbuffer txt fg bg)))
17399 linkfile (format "%s_%s.png" prefix hash)
17400 movefile (format "%s_%s.png" absprefix hash)))
17401 (setq link (concat block "[[file:" linkfile "]]" block))
17402 (if msg (message msg cnt))
17403 (goto-char beg)
17404 (unless checkdir ; make sure the directory exists
17405 (setq checkdir t)
17406 (or (file-directory-p todir) (make-directory todir t)))
17407 (org-create-formula-image
17408 txt movefile optnew forbuffer processing-type)
17409 (if overlays
17410 (progn
17411 (mapc (lambda (o)
17412 (if (eq (overlay-get o 'org-overlay-type)
17413 'org-latex-overlay)
17414 (delete-overlay o)))
17415 (overlays-in beg end))
17416 (setq ov (make-overlay beg end))
17417 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17418 (if (featurep 'xemacs)
17419 (progn
17420 (overlay-put ov 'invisible t)
17421 (overlay-put
17422 ov 'end-glyph
17423 (make-glyph (vector 'png :file movefile))))
17424 (overlay-put
17425 ov 'display
17426 (list 'image :type 'png :file movefile :ascent 'center)))
17427 (push ov org-latex-fragment-image-overlays)
17428 (goto-char end))
17429 (delete-region beg end)
17430 (insert (org-add-props link
17431 (list 'org-latex-src
17432 (replace-regexp-in-string
17433 "\"" "" txt)
17434 'org-latex-src-embed-type
17435 (if block-type 'paragraph 'character))))))
17436 ((eq processing-type 'mathml)
17437 ;; Process to MathML
17438 (unless (save-match-data (org-format-latex-mathml-available-p))
17439 (error "LaTeX to MathML converter not configured"))
17440 (setq txt (match-string n)
17441 beg (match-beginning n) end (match-end n)
17442 cnt (1+ cnt))
17443 (if msg (message msg cnt))
17444 (goto-char beg)
17445 (delete-region beg end)
17446 (insert (org-format-latex-as-mathml
17447 txt block-type prefix dir)))
17449 (error "Unknown conversion type %s for latex fragments"
17450 processing-type)))))))))
17452 (defun org-create-math-formula (latex-frag &optional mathml-file)
17453 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17454 Use `org-latex-to-mathml-convert-command'. If the conversion is
17455 sucessful, return the portion between \"<math...> </math>\"
17456 elements otherwise return nil. When MATHML-FILE is specified,
17457 write the results in to that file. When invoked as an
17458 interactive command, prompt for LATEX-FRAG, with initial value
17459 set to the current active region and echo the results for user
17460 inspection."
17461 (interactive (list (let ((frag (when (org-region-active-p)
17462 (buffer-substring-no-properties
17463 (region-beginning) (region-end)))))
17464 (read-string "LaTeX Fragment: " frag nil frag))))
17465 (unless latex-frag (error "Invalid latex-frag"))
17466 (let* ((tmp-in-file (file-relative-name
17467 (make-temp-name (expand-file-name "ltxmathml-in"))))
17468 (ignore (write-region latex-frag nil tmp-in-file))
17469 (tmp-out-file (file-relative-name
17470 (make-temp-name (expand-file-name "ltxmathml-out"))))
17471 (cmd (format-spec
17472 org-latex-to-mathml-convert-command
17473 `((?j . ,(shell-quote-argument
17474 (expand-file-name org-latex-to-mathml-jar-file)))
17475 (?I . ,(shell-quote-argument tmp-in-file))
17476 (?o . ,(shell-quote-argument tmp-out-file)))))
17477 mathml shell-command-output)
17478 (when (org-called-interactively-p 'any)
17479 (unless (org-format-latex-mathml-available-p)
17480 (error "LaTeX to MathML converter not configured")))
17481 (message "Running %s" cmd)
17482 (setq shell-command-output (shell-command-to-string cmd))
17483 (setq mathml
17484 (when (file-readable-p tmp-out-file)
17485 (with-current-buffer (find-file-noselect tmp-out-file t)
17486 (goto-char (point-min))
17487 (when (re-search-forward
17488 (concat
17489 (regexp-quote
17490 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17491 "\\(.\\|\n\\)*"
17492 (regexp-quote "</math>")) nil t)
17493 (prog1 (match-string 0) (kill-buffer))))))
17494 (cond
17495 (mathml
17496 (setq mathml
17497 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17498 (when mathml-file
17499 (write-region mathml nil mathml-file))
17500 (when (org-called-interactively-p 'any)
17501 (message mathml)))
17502 ((message "LaTeX to MathML conversion failed")
17503 (message shell-command-output)))
17504 (delete-file tmp-in-file)
17505 (when (file-exists-p tmp-out-file)
17506 (delete-file tmp-out-file))
17507 mathml))
17509 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17510 prefix &optional dir)
17511 "Use `org-create-math-formula' but check local cache first."
17512 (let* ((absprefix (expand-file-name prefix dir))
17513 (print-length nil) (print-level nil)
17514 (formula-id (concat
17515 "formula-"
17516 (sha1
17517 (prin1-to-string
17518 (list latex-frag
17519 org-latex-to-mathml-convert-command)))))
17520 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17521 (formula-cache-dir (file-name-directory formula-cache)))
17523 (unless (file-directory-p formula-cache-dir)
17524 (make-directory formula-cache-dir t))
17526 (unless (file-exists-p formula-cache)
17527 (org-create-math-formula latex-frag formula-cache))
17529 (if (file-exists-p formula-cache)
17530 ;; Successful conversion. Return the link to MathML file.
17531 (org-add-props
17532 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17533 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17534 'org-latex-src-embed-type (if latex-frag-type
17535 'paragraph 'character)))
17536 ;; Failed conversion. Return the LaTeX fragment verbatim
17537 (add-text-properties
17538 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17539 latex-frag)))
17541 (defun org-create-formula-image (string tofile options buffer &optional type)
17542 "Create an image from LaTeX source using dvipng or convert.
17543 This function calls either `org-create-formula-image-with-dvipng'
17544 or `org-create-formula-image-with-imagemagick' depending on the
17545 value of `org-latex-create-formula-image-program' or on the value
17546 of the optional TYPE variable.
17548 Note: ultimately these two function should be combined as they
17549 share a good deal of logic."
17550 (org-check-external-command
17551 "latex" "needed to convert LaTeX fragments to images")
17552 (funcall
17553 (case (or type org-latex-create-formula-image-program)
17554 ('dvipng
17555 (org-check-external-command
17556 "dvipng" "needed to convert LaTeX fragments to images")
17557 #'org-create-formula-image-with-dvipng)
17558 ('imagemagick
17559 (org-check-external-command
17560 "convert" "you need to install imagemagick")
17561 #'org-create-formula-image-with-imagemagick)
17562 (t (error
17563 "invalid value of `org-latex-create-formula-image-program'")))
17564 string tofile options buffer))
17566 ;; This function borrows from Ganesh Swami's latex2png.el
17567 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17568 "This calls dvipng."
17569 (require 'org-latex)
17570 (let* ((tmpdir (if (featurep 'xemacs)
17571 (temp-directory)
17572 temporary-file-directory))
17573 (texfilebase (make-temp-name
17574 (expand-file-name "orgtex" tmpdir)))
17575 (texfile (concat texfilebase ".tex"))
17576 (dvifile (concat texfilebase ".dvi"))
17577 (pngfile (concat texfilebase ".png"))
17578 (fnh (if (featurep 'xemacs)
17579 (font-height (face-font 'default))
17580 (face-attribute 'default :height nil)))
17581 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17582 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17583 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17584 "Black"))
17585 (bg (or (plist-get options (if buffer :background :html-background))
17586 "Transparent")))
17587 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17588 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17589 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17590 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17591 (with-temp-file texfile
17592 (insert (org-splice-latex-header
17593 org-format-latex-header
17594 org-export-latex-default-packages-alist
17595 org-export-latex-packages-alist t
17596 org-format-latex-header-extra))
17597 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17598 (require 'org-latex)
17599 (org-export-latex-fix-inputenc))
17600 (let ((dir default-directory))
17601 (condition-case nil
17602 (progn
17603 (cd tmpdir)
17604 (call-process "latex" nil nil nil texfile))
17605 (error nil))
17606 (cd dir))
17607 (if (not (file-exists-p dvifile))
17608 (progn (message "Failed to create dvi file from %s" texfile) nil)
17609 (condition-case nil
17610 (if (featurep 'xemacs)
17611 (call-process "dvipng" nil nil nil
17612 "-fg" fg "-bg" bg
17613 "-T" "tight"
17614 "-o" pngfile
17615 dvifile)
17616 (call-process "dvipng" nil nil nil
17617 "-fg" fg "-bg" bg
17618 "-D" dpi
17619 ;;"-x" scale "-y" scale
17620 "-T" "tight"
17621 "-o" pngfile
17622 dvifile))
17623 (error nil))
17624 (if (not (file-exists-p pngfile))
17625 (if org-format-latex-signal-error
17626 (error "Failed to create png file from %s" texfile)
17627 (message "Failed to create png file from %s" texfile)
17628 nil)
17629 ;; Use the requested file name and clean up
17630 (copy-file pngfile tofile 'replace)
17631 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17632 (if (file-exists-p (concat texfilebase e))
17633 (delete-file (concat texfilebase e))))
17634 pngfile))))
17636 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17637 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17638 "This calls convert, which is included into imagemagick."
17639 (require 'org-latex)
17640 (let* ((tmpdir (if (featurep 'xemacs)
17641 (temp-directory)
17642 temporary-file-directory))
17643 (texfilebase (make-temp-name
17644 (expand-file-name "orgtex" tmpdir)))
17645 (texfile (concat texfilebase ".tex"))
17646 (pdffile (concat texfilebase ".pdf"))
17647 (pngfile (concat texfilebase ".png"))
17648 (fnh (if (featurep 'xemacs)
17649 (font-height (face-font 'default))
17650 (face-attribute 'default :height nil)))
17651 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17652 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17653 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17654 "black"))
17655 (bg (or (plist-get options (if buffer :background :html-background))
17656 "white")))
17657 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17658 (setq fg (org-latex-color-format fg)))
17659 (if (eq bg 'default) (setq bg (org-latex-color :background))
17660 (setq bg (org-latex-color-format
17661 (if (string= bg "Transparent") "white" bg))))
17662 (with-temp-file texfile
17663 (insert (org-splice-latex-header
17664 org-format-latex-header
17665 org-export-latex-default-packages-alist
17666 org-export-latex-packages-alist t
17667 org-format-latex-header-extra))
17668 (insert "\n\\begin{document}\n"
17669 "\\definecolor{fg}{rgb}{" fg "}\n"
17670 "\\definecolor{bg}{rgb}{" bg "}\n"
17671 "\n\\pagecolor{bg}\n"
17672 "\n{\\color{fg}\n"
17673 string
17674 "\n}\n"
17675 "\n\\end{document}\n" )
17676 (require 'org-latex)
17677 (org-export-latex-fix-inputenc))
17678 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17679 (condition-case nil
17680 (progn
17681 (cd tmpdir)
17682 (setq cmds org-latex-to-pdf-process)
17683 (while cmds
17684 (setq latex-frags-cmds (pop cmds))
17685 (if (listp latex-frags-cmds)
17686 (setq cmds nil)
17687 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17688 (while latex-frags-cmds
17689 (setq cmd (pop latex-frags-cmds))
17690 (while (string-match "%b" cmd)
17691 (setq cmd (replace-match
17692 (save-match-data
17693 (shell-quote-argument texfile))
17694 t t cmd)))
17695 (while (string-match "%f" cmd)
17696 (setq cmd (replace-match
17697 (save-match-data
17698 (shell-quote-argument (file-name-nondirectory texfile)))
17699 t t cmd)))
17700 (while (string-match "%o" cmd)
17701 (setq cmd (replace-match
17702 (save-match-data
17703 (shell-quote-argument (file-name-directory texfile)))
17704 t t cmd)))
17705 (setq cmd (split-string cmd))
17706 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17707 (error nil))
17708 (cd dir))
17709 (if (not (file-exists-p pdffile))
17710 (progn (message "Failed to create pdf file from %s" texfile) nil)
17711 (condition-case nil
17712 (if (featurep 'xemacs)
17713 (call-process "convert" nil nil nil
17714 "-density" "96"
17715 "-trim"
17716 "-antialias"
17717 pdffile
17718 "-quality" "100"
17719 ;; "-sharpen" "0x1.0"
17720 pngfile)
17721 (call-process "convert" nil nil nil
17722 "-density" dpi
17723 "-trim"
17724 "-antialias"
17725 pdffile
17726 "-quality" "100"
17727 ; "-sharpen" "0x1.0"
17728 pngfile))
17729 (error nil))
17730 (if (not (file-exists-p pngfile))
17731 (if org-format-latex-signal-error
17732 (error "Failed to create png file from %s" texfile)
17733 (message "Failed to create png file from %s" texfile)
17734 nil)
17735 ;; Use the requested file name and clean up
17736 (copy-file pngfile tofile 'replace)
17737 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17738 (if (file-exists-p (concat texfilebase e))
17739 (delete-file (concat texfilebase e))))
17740 pngfile))))
17742 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17743 "Fill a LaTeX header template TPL.
17744 In the template, the following place holders will be recognized:
17746 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17747 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17748 [PACKAGES] \\usepackage statements for PKG
17749 [NO-PACKAGES] do not include PKG
17750 [EXTRA] the string EXTRA
17751 [NO-EXTRA] do not include EXTRA
17753 For backward compatibility, if both the positive and the negative place
17754 holder is missing, the positive one (without the \"NO-\") will be
17755 assumed to be present at the end of the template.
17756 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17757 EXTRA is a string.
17758 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17759 (let (rpl (end ""))
17760 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17761 (setq rpl (if (or (match-end 1) (not def-pkg))
17762 "" (org-latex-packages-to-string def-pkg snippets-p t))
17763 tpl (replace-match rpl t t tpl))
17764 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17766 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17767 (setq rpl (if (or (match-end 1) (not pkg))
17768 "" (org-latex-packages-to-string pkg snippets-p t))
17769 tpl (replace-match rpl t t tpl))
17770 (if pkg (setq end
17771 (concat end "\n"
17772 (org-latex-packages-to-string pkg snippets-p)))))
17774 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17775 (setq rpl (if (or (match-end 1) (not extra))
17776 "" (concat extra "\n"))
17777 tpl (replace-match rpl t t tpl))
17778 (if (and extra (string-match "\\S-" extra))
17779 (setq end (concat end "\n" extra))))
17781 (if (string-match "\\S-" end)
17782 (concat tpl "\n" end)
17783 tpl)))
17785 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17786 "Turn an alist of packages into a string with the \\usepackage macros."
17787 (setq pkg (mapconcat (lambda(p)
17788 (cond
17789 ((stringp p) p)
17790 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17791 (format "%% Package %s omitted" (cadr p)))
17792 ((equal "" (car p))
17793 (format "\\usepackage{%s}" (cadr p)))
17795 (format "\\usepackage[%s]{%s}"
17796 (car p) (cadr p)))))
17798 "\n"))
17799 (if newline (concat pkg "\n") pkg))
17801 (defun org-dvipng-color (attr)
17802 "Return a RGB color specification for dvipng."
17803 (apply 'format "rgb %s %s %s"
17804 (mapcar 'org-normalize-color
17805 (if (featurep 'xemacs)
17806 (color-rgb-components
17807 (face-property 'default
17808 (cond ((eq attr :foreground) 'foreground)
17809 ((eq attr :background) 'background))))
17810 (color-values (face-attribute 'default attr nil))))))
17812 (defun org-dvipng-color-format (color-name)
17813 "Convert COLOR-NAME to a RGB color value for dvipng."
17814 (apply 'format "rgb %s %s %s"
17815 (mapcar 'org-normalize-color
17816 (color-values color-name))))
17818 (defun org-latex-color (attr)
17819 "Return a RGB color for the LaTeX color package."
17820 (apply 'format "%s,%s,%s"
17821 (mapcar 'org-normalize-color
17822 (if (featurep 'xemacs)
17823 (color-rgb-components
17824 (face-property 'default
17825 (cond ((eq attr :foreground) 'foreground)
17826 ((eq attr :background) 'background))))
17827 (color-values (face-attribute 'default attr nil))))))
17829 (defun org-latex-color-format (color-name)
17830 "Convert COLOR-NAME to a RGB color value."
17831 (apply 'format "%s,%s,%s"
17832 (mapcar 'org-normalize-color
17833 (color-values color-name))))
17835 (defun org-normalize-color (value)
17836 "Return string to be used as color value for an RGB component."
17837 (format "%g" (/ value 65535.0)))
17839 ;; Image display
17842 (defvar org-inline-image-overlays nil)
17843 (make-variable-buffer-local 'org-inline-image-overlays)
17845 (defun org-toggle-inline-images (&optional include-linked)
17846 "Toggle the display of inline images.
17847 INCLUDE-LINKED is passed to `org-display-inline-images'."
17848 (interactive "P")
17849 (if org-inline-image-overlays
17850 (progn
17851 (org-remove-inline-images)
17852 (message "Inline image display turned off"))
17853 (org-display-inline-images include-linked)
17854 (if (and (org-called-interactively-p)
17855 org-inline-image-overlays)
17856 (message "%d images displayed inline"
17857 (length org-inline-image-overlays))
17858 (message "No images to display inline"))))
17860 (defun org-redisplay-inline-images ()
17861 "Refresh the display of inline images."
17862 (interactive)
17863 (if (not org-inline-image-overlays)
17864 (org-toggle-inline-images)
17865 (org-toggle-inline-images)
17866 (org-toggle-inline-images)))
17868 (defun org-display-inline-images (&optional include-linked refresh beg end)
17869 "Display inline images.
17870 Normally only links without a description part are inlined, because this
17871 is how it will work for export. When INCLUDE-LINKED is set, also links
17872 with a description part will be inlined. This can be nice for a quick
17873 look at those images, but it does not reflect what exported files will look
17874 like.
17875 When REFRESH is set, refresh existing images between BEG and END.
17876 This will create new image displays only if necessary.
17877 BEG and END default to the buffer boundaries."
17878 (interactive "P")
17879 (unless refresh
17880 (org-remove-inline-images)
17881 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17882 (save-excursion
17883 (save-restriction
17884 (widen)
17885 (setq beg (or beg (point-min)) end (or end (point-max)))
17886 (goto-char beg)
17887 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17888 (substring (org-image-file-name-regexp) 0 -2)
17889 "\\)\\]" (if include-linked "" "\\]")))
17890 old file ov img type attrwidth width)
17891 (while (re-search-forward re end t)
17892 (setq old (get-char-property-and-overlay (match-beginning 1)
17893 'org-image-overlay)
17894 file (expand-file-name
17895 (concat (or (match-string 3) "") (match-string 4))))
17896 (when (image-type-available-p 'imagemagick)
17897 (setq attrwidth (if (or (listp org-image-actual-width)
17898 (null org-image-actual-width))
17899 (save-excursion
17900 (save-match-data
17901 (when (re-search-backward
17902 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
17903 (save-excursion
17904 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
17905 (string-to-number (match-string 1))))))
17906 width (cond ((eq org-image-actual-width t) nil)
17907 ((null org-image-actual-width) attrwidth)
17908 ((numberp org-image-actual-width)
17909 org-image-actual-width)
17910 ((listp org-image-actual-width)
17911 (or attrwidth (car org-image-actual-width))))
17912 type (if width 'imagemagick)))
17913 (when (file-exists-p file)
17914 (if (and (car-safe old) refresh)
17915 (image-refresh (overlay-get (cdr old) 'display))
17916 (setq img (save-match-data (create-image file type nil :width width)))
17917 (when img
17918 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17919 (overlay-put ov 'display img)
17920 (overlay-put ov 'face 'default)
17921 (overlay-put ov 'org-image-overlay t)
17922 (overlay-put ov 'modification-hooks
17923 (list 'org-display-inline-remove-overlay))
17924 (push ov org-inline-image-overlays)))))))))
17926 (define-obsolete-function-alias
17927 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17929 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17930 "Remove inline-display overlay if a corresponding region is modified."
17931 (let ((inhibit-modification-hooks t))
17932 (when (and ov after)
17933 (delete ov org-inline-image-overlays)
17934 (delete-overlay ov))))
17936 (defun org-remove-inline-images ()
17937 "Remove inline display of images."
17938 (interactive)
17939 (mapc 'delete-overlay org-inline-image-overlays)
17940 (setq org-inline-image-overlays nil))
17942 ;;;; Key bindings
17944 ;; Outline functions from `outline-mode-prefix-map'
17945 ;; that can be remapped in Org:
17946 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17947 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17948 (define-key org-mode-map [remap outline-forward-same-level]
17949 'org-forward-heading-same-level)
17950 (define-key org-mode-map [remap outline-backward-same-level]
17951 'org-backward-heading-same-level)
17952 (define-key org-mode-map [remap show-branches]
17953 'org-kill-note-or-show-branches)
17954 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17955 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17956 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17958 ;; Outline functions from `outline-mode-prefix-map' that can not
17959 ;; be remapped in Org:
17961 ;; - the column "key binding" shows whether the Outline function is still
17962 ;; available in Org mode on the same key that it has been bound to in
17963 ;; Outline mode:
17964 ;; - "overridden": key used for a different functionality in Org mode
17965 ;; - else: key still bound to the same Outline function in Org mode
17967 ;; | Outline function | key binding | Org replacement |
17968 ;; |------------------------------------+-------------+-----------------------|
17969 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17970 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17971 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17972 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17973 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17974 ;; | `show-entry' | overridden | no replacement |
17975 ;; | `show-children' | `C-c C-i' | visibility cycling |
17976 ;; | `show-branches' | `C-c C-k' | still same function |
17977 ;; | `show-subtree' | overridden | visibility cycling |
17978 ;; | `show-all' | overridden | no replacement |
17979 ;; | `hide-subtree' | overridden | visibility cycling |
17980 ;; | `hide-body' | overridden | no replacement |
17981 ;; | `hide-entry' | overridden | visibility cycling |
17982 ;; | `hide-leaves' | overridden | no replacement |
17983 ;; | `hide-sublevels' | overridden | no replacement |
17984 ;; | `hide-other' | overridden | no replacement |
17986 ;; Make `C-c C-x' a prefix key
17987 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17989 ;; TAB key with modifiers
17990 (org-defkey org-mode-map "\C-i" 'org-cycle)
17991 (org-defkey org-mode-map [(tab)] 'org-cycle)
17992 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17993 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17994 ;; The following line is necessary under Suse GNU/Linux
17995 (unless (featurep 'xemacs)
17996 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17997 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17998 (define-key org-mode-map [backtab] 'org-shifttab)
18000 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18001 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18002 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18004 ;; Cursor keys with modifiers
18005 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18006 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18007 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18008 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18010 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18011 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18012 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18013 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18015 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18016 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18017 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18018 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18020 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18021 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18022 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18023 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18025 ;; Babel keys
18026 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18027 (mapc (lambda (pair)
18028 (define-key org-babel-map (car pair) (cdr pair)))
18029 org-babel-key-bindings)
18031 ;;; Extra keys for tty access.
18032 ;; We only set them when really needed because otherwise the
18033 ;; menus don't show the simple keys
18035 (when (or org-use-extra-keys
18036 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18037 (not window-system))
18038 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18039 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18040 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18041 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18042 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18043 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18044 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18045 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18046 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18047 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18048 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18049 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18050 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18051 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18052 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18053 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18054 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18055 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18056 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18057 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18058 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18059 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18060 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18061 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18062 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18063 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18064 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18065 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18067 ;; All the other keys
18069 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18070 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18071 (if (boundp 'narrow-map)
18072 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18073 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18074 (if (boundp 'narrow-map)
18075 (org-defkey narrow-map "b" 'org-narrow-to-block)
18076 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18077 (if (boundp 'narrow-map)
18078 (org-defkey narrow-map "e" 'org-narrow-to-element)
18079 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18080 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18081 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18082 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18083 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18084 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18085 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18086 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18087 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18088 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18089 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18090 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18091 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18092 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18093 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18094 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18095 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18096 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18097 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18098 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18099 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18100 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18101 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18102 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18103 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18104 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18105 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18106 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18107 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18108 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18109 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18110 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18111 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18112 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18113 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18114 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18115 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18116 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18117 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18118 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18119 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18120 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18121 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18122 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18123 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18124 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18125 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18126 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18127 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18128 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18129 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18130 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18131 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18132 (org-defkey org-mode-map "\C-c^" 'org-sort)
18133 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18134 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18135 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18136 (org-defkey org-mode-map "\C-m" 'org-return)
18137 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18138 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18139 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18140 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18141 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18142 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18143 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18144 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18145 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18146 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18147 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18148 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18149 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18150 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18151 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18152 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18153 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18154 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18155 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18156 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18157 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18158 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18159 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18161 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18162 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18163 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18165 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18166 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18167 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18168 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18169 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18170 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18171 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18172 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18173 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18174 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18175 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18176 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18177 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18178 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18179 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18180 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18181 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18182 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18183 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18184 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18185 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18186 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18188 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18189 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18190 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18191 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18192 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18194 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18196 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18198 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18199 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18201 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18204 (when (featurep 'xemacs)
18205 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18208 (defconst org-speed-commands-default
18210 ("Outline Navigation")
18211 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18212 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18213 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18214 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18215 ("u" . (org-speed-move-safe 'outline-up-heading))
18216 ("j" . org-goto)
18217 ("g" . (org-refile t))
18218 ("Outline Visibility")
18219 ("c" . org-cycle)
18220 ("C" . org-shifttab)
18221 (" " . org-display-outline-path)
18222 (":" . org-columns)
18223 ("Outline Structure Editing")
18224 ("U" . org-shiftmetaup)
18225 ("D" . org-shiftmetadown)
18226 ("r" . org-metaright)
18227 ("l" . org-metaleft)
18228 ("R" . org-shiftmetaright)
18229 ("L" . org-shiftmetaleft)
18230 ("i" . (progn (forward-char 1) (call-interactively
18231 'org-insert-heading-respect-content)))
18232 ("^" . org-sort)
18233 ("w" . org-refile)
18234 ("a" . org-archive-subtree-default-with-confirmation)
18235 ("." . org-mark-subtree)
18236 ("#" . org-toggle-comment)
18237 ("Clock Commands")
18238 ("I" . org-clock-in)
18239 ("O" . org-clock-out)
18240 ("Meta Data Editing")
18241 ("t" . org-todo)
18242 ("," . (org-priority))
18243 ("0" . (org-priority ?\ ))
18244 ("1" . (org-priority ?A))
18245 ("2" . (org-priority ?B))
18246 ("3" . (org-priority ?C))
18247 (";" . org-set-tags-command)
18248 ("e" . org-set-effort)
18249 ("E" . org-inc-effort)
18250 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18251 (org-entry-put (point) "APPT_WARNTIME" m)))
18252 ("Agenda Views etc")
18253 ("v" . org-agenda)
18254 ("/" . org-sparse-tree)
18255 ("Misc")
18256 ("o" . org-open-at-point)
18257 ("?" . org-speed-command-help)
18258 ("<" . (org-agenda-set-restriction-lock 'subtree))
18259 (">" . (org-agenda-remove-restriction-lock))
18261 "The default speed commands.")
18263 (defun org-print-speed-command (e)
18264 (if (> (length (car e)) 1)
18265 (progn
18266 (princ "\n")
18267 (princ (car e))
18268 (princ "\n")
18269 (princ (make-string (length (car e)) ?-))
18270 (princ "\n"))
18271 (princ (car e))
18272 (princ " ")
18273 (if (symbolp (cdr e))
18274 (princ (symbol-name (cdr e)))
18275 (prin1 (cdr e)))
18276 (princ "\n")))
18278 (defun org-speed-command-help ()
18279 "Show the available speed commands."
18280 (interactive)
18281 (if (not org-use-speed-commands)
18282 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18283 (with-output-to-temp-buffer "*Help*"
18284 (princ "User-defined Speed commands\n===========================\n")
18285 (mapc 'org-print-speed-command org-speed-commands-user)
18286 (princ "\n")
18287 (princ "Built-in Speed commands\n=======================\n")
18288 (mapc 'org-print-speed-command org-speed-commands-default))
18289 (with-current-buffer "*Help*"
18290 (setq truncate-lines t))))
18292 (defun org-speed-move-safe (cmd)
18293 "Execute CMD, but make sure that the cursor always ends up in a headline.
18294 If not, return to the original position and throw an error."
18295 (interactive)
18296 (let ((pos (point)))
18297 (call-interactively cmd)
18298 (unless (and (bolp) (org-at-heading-p))
18299 (goto-char pos)
18300 (error "Boundary reached while executing %s" cmd))))
18302 (defvar org-self-insert-command-undo-counter 0)
18304 (defvar org-table-auto-blank-field) ; defined in org-table.el
18305 (defvar org-speed-command nil)
18307 (define-obsolete-function-alias
18308 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18310 (defun org-speed-command-activate (keys)
18311 "Hook for activating single-letter speed commands.
18312 `org-speed-commands-default' specifies a minimal command set.
18313 Use `org-speed-commands-user' for further customization."
18314 (when (or (and (bolp) (looking-at org-outline-regexp))
18315 (and (functionp org-use-speed-commands)
18316 (funcall org-use-speed-commands)))
18317 (cdr (assoc keys (append org-speed-commands-user
18318 org-speed-commands-default)))))
18320 (define-obsolete-function-alias
18321 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18323 (defun org-babel-speed-command-activate (keys)
18324 "Hook for activating single-letter code block commands."
18325 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18326 (cdr (assoc keys org-babel-key-bindings))))
18328 (defcustom org-speed-command-hook
18329 '(org-speed-command-default-hook org-babel-speed-command-hook)
18330 "Hook for activating speed commands at strategic locations.
18331 Hook functions are called in sequence until a valid handler is
18332 found.
18334 Each hook takes a single argument, a user-pressed command key
18335 which is also a `self-insert-command' from the global map.
18337 Within the hook, examine the cursor position and the command key
18338 and return nil or a valid handler as appropriate. Handler could
18339 be one of an interactive command, a function, or a form.
18341 Set `org-use-speed-commands' to non-nil value to enable this
18342 hook. The default setting is `org-speed-command-activate'."
18343 :group 'org-structure
18344 :version "24.1"
18345 :type 'hook)
18347 (defun org-self-insert-command (N)
18348 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18349 If the cursor is in a table looking at whitespace, the whitespace is
18350 overwritten, and the table is not marked as requiring realignment."
18351 (interactive "p")
18352 (org-check-before-invisible-edit 'insert)
18353 (cond
18354 ((and org-use-speed-commands
18355 (setq org-speed-command
18356 (run-hook-with-args-until-success
18357 'org-speed-command-hook (this-command-keys))))
18358 (cond
18359 ((commandp org-speed-command)
18360 (setq this-command org-speed-command)
18361 (call-interactively org-speed-command))
18362 ((functionp org-speed-command)
18363 (funcall org-speed-command))
18364 ((and org-speed-command (listp org-speed-command))
18365 (eval org-speed-command))
18366 (t (let (org-use-speed-commands)
18367 (call-interactively 'org-self-insert-command)))))
18368 ((and
18369 (org-table-p)
18370 (progn
18371 ;; check if we blank the field, and if that triggers align
18372 (and (featurep 'org-table) org-table-auto-blank-field
18373 (member last-command
18374 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18375 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18376 ;; got extra space, this field does not determine column width
18377 (let (org-table-may-need-update) (org-table-blank-field))
18378 ;; no extra space, this field may determine column width
18379 (org-table-blank-field)))
18381 (eq N 1)
18382 (looking-at "[^|\n]* |"))
18383 (let (org-table-may-need-update)
18384 (goto-char (1- (match-end 0)))
18385 (backward-delete-char 1)
18386 (goto-char (match-beginning 0))
18387 (self-insert-command N)))
18389 (setq org-table-may-need-update t)
18390 (self-insert-command N)
18391 (org-fix-tags-on-the-fly)
18392 (if org-self-insert-cluster-for-undo
18393 (if (not (eq last-command 'org-self-insert-command))
18394 (setq org-self-insert-command-undo-counter 1)
18395 (if (>= org-self-insert-command-undo-counter 20)
18396 (setq org-self-insert-command-undo-counter 1)
18397 (and (> org-self-insert-command-undo-counter 0)
18398 buffer-undo-list (listp buffer-undo-list)
18399 (not (cadr buffer-undo-list)) ; remove nil entry
18400 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18401 (setq org-self-insert-command-undo-counter
18402 (1+ org-self-insert-command-undo-counter))))))))
18404 (defun org-check-before-invisible-edit (kind)
18405 "Check is editing if kind KIND would be dangerous with invisible text around.
18406 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18407 ;; First, try to get out of here as quickly as possible, to reduce overhead
18408 (if (and org-catch-invisible-edits
18409 (or (not (boundp 'visible-mode)) (not visible-mode))
18410 (or (get-char-property (point) 'invisible)
18411 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18412 ;; OK, we need to take a closer look
18413 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18414 (invisible-before-point (if (bobp) nil (get-char-property
18415 (1- (point)) 'invisible)))
18416 (border-and-ok-direction
18418 ;; Check if we are acting predictably before invisible text
18419 (and invisible-at-point (not invisible-before-point)
18420 (memq kind '(insert delete-backward)))
18421 ;; Check if we are acting predictably after invisible text
18422 ;; This works not well, and I have turned it off. It seems
18423 ;; better to always show and stop after invisible text.
18424 ;; (and (not invisible-at-point) invisible-before-point
18425 ;; (memq kind '(insert delete)))
18427 (when (or (memq invisible-at-point '(outline org-hide-block t))
18428 (memq invisible-before-point '(outline org-hide-block t)))
18429 (if (eq org-catch-invisible-edits 'error)
18430 (error "Editing in invisible areas is prohibited - make visible first"))
18431 (if (and org-custom-properties-overlays
18432 (y-or-n-p "Display invisible properties in this buffer? "))
18433 (org-toggle-custom-properties-visibility)
18434 ;; Make the area visible
18435 (save-excursion
18436 (if invisible-before-point
18437 (goto-char (previous-single-char-property-change
18438 (point) 'invisible)))
18439 (org-cycle))
18440 (cond
18441 ((eq org-catch-invisible-edits 'show)
18442 ;; That's it, we do the edit after showing
18443 (message
18444 "Unfolding invisible region around point before editing")
18445 (sit-for 1))
18446 ((and (eq org-catch-invisible-edits 'smart)
18447 border-and-ok-direction)
18448 (message "Unfolding invisible region around point before editing"))
18450 ;; Don't do the edit, make the user repeat it in full visibility
18451 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18453 (defun org-fix-tags-on-the-fly ()
18454 (when (and (equal (char-after (point-at-bol)) ?*)
18455 (org-at-heading-p))
18456 (org-align-tags-here org-tags-column)))
18458 (defun org-delete-backward-char (N)
18459 "Like `delete-backward-char', insert whitespace at field end in tables.
18460 When deleting backwards, in tables this function will insert whitespace in
18461 front of the next \"|\" separator, to keep the table aligned. The table will
18462 still be marked for re-alignment if the field did fill the entire column,
18463 because, in this case the deletion might narrow the column."
18464 (interactive "p")
18465 (org-check-before-invisible-edit 'delete-backward)
18466 (if (and (org-table-p)
18467 (eq N 1)
18468 (string-match "|" (buffer-substring (point-at-bol) (point)))
18469 (looking-at ".*?|"))
18470 (let ((pos (point))
18471 (noalign (looking-at "[^|\n\r]* |"))
18472 (c org-table-may-need-update))
18473 (backward-delete-char N)
18474 (if (not overwrite-mode)
18475 (progn
18476 (skip-chars-forward "^|")
18477 (insert " ")
18478 (goto-char (1- pos))))
18479 ;; noalign: if there were two spaces at the end, this field
18480 ;; does not determine the width of the column.
18481 (if noalign (setq org-table-may-need-update c)))
18482 (backward-delete-char N)
18483 (org-fix-tags-on-the-fly)))
18485 (defun org-delete-char (N)
18486 "Like `delete-char', but insert whitespace at field end in tables.
18487 When deleting characters, in tables this function will insert whitespace in
18488 front of the next \"|\" separator, to keep the table aligned. The table will
18489 still be marked for re-alignment if the field did fill the entire column,
18490 because, in this case the deletion might narrow the column."
18491 (interactive "p")
18492 (org-check-before-invisible-edit 'delete)
18493 (if (and (org-table-p)
18494 (not (bolp))
18495 (not (= (char-after) ?|))
18496 (eq N 1))
18497 (if (looking-at ".*?|")
18498 (let ((pos (point))
18499 (noalign (looking-at "[^|\n\r]* |"))
18500 (c org-table-may-need-update))
18501 (replace-match (concat
18502 (substring (match-string 0) 1 -1)
18503 " |"))
18504 (goto-char pos)
18505 ;; noalign: if there were two spaces at the end, this field
18506 ;; does not determine the width of the column.
18507 (if noalign (setq org-table-may-need-update c)))
18508 (delete-char N))
18509 (delete-char N)
18510 (org-fix-tags-on-the-fly)))
18512 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18513 (put 'org-self-insert-command 'delete-selection t)
18514 (put 'orgtbl-self-insert-command 'delete-selection t)
18515 (put 'org-delete-char 'delete-selection 'supersede)
18516 (put 'org-delete-backward-char 'delete-selection 'supersede)
18517 (put 'org-yank 'delete-selection 'yank)
18519 ;; Make `flyspell-mode' delay after some commands
18520 (put 'org-self-insert-command 'flyspell-delayed t)
18521 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18522 (put 'org-delete-char 'flyspell-delayed t)
18523 (put 'org-delete-backward-char 'flyspell-delayed t)
18525 ;; Make pabbrev-mode expand after org-mode commands
18526 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18527 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18529 ;; How to do this: Measure non-white length of current string
18530 ;; If equal to column width, we should realign.
18532 (defun org-remap (map &rest commands)
18533 "In MAP, remap the functions given in COMMANDS.
18534 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18535 (let (new old)
18536 (while commands
18537 (setq old (pop commands) new (pop commands))
18538 (if (fboundp 'command-remapping)
18539 (org-defkey map (vector 'remap old) new)
18540 (substitute-key-definition old new map global-map)))))
18542 (when (eq org-enable-table-editor 'optimized)
18543 ;; If the user wants maximum table support, we need to hijack
18544 ;; some standard editing functions
18545 (org-remap org-mode-map
18546 'self-insert-command 'org-self-insert-command
18547 'delete-char 'org-delete-char
18548 'delete-backward-char 'org-delete-backward-char)
18549 (org-defkey org-mode-map "|" 'org-force-self-insert))
18551 (defvar org-ctrl-c-ctrl-c-hook nil
18552 "Hook for functions attaching themselves to `C-c C-c'.
18554 This can be used to add additional functionality to the C-c C-c
18555 key which executes context-dependent commands. This hook is run
18556 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18557 run after the last test.
18559 Each function will be called with no arguments. The function
18560 must check if the context is appropriate for it to act. If yes,
18561 it should do its thing and then return a non-nil value. If the
18562 context is wrong, just do nothing and return nil.")
18564 (defvar org-ctrl-c-ctrl-c-final-hook nil
18565 "Hook for functions attaching themselves to `C-c C-c'.
18567 This can be used to add additional functionality to the C-c C-c
18568 key which executes context-dependent commands. This hook is run
18569 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18570 before the first test.
18572 Each function will be called with no arguments. The function
18573 must check if the context is appropriate for it to act. If yes,
18574 it should do its thing and then return a non-nil value. If the
18575 context is wrong, just do nothing and return nil.")
18577 (defvar org-tab-first-hook nil
18578 "Hook for functions to attach themselves to TAB.
18579 See `org-ctrl-c-ctrl-c-hook' for more information.
18580 This hook runs as the first action when TAB is pressed, even before
18581 `org-cycle' messes around with the `outline-regexp' to cater for
18582 inline tasks and plain list item folding.
18583 If any function in this hook returns t, any other actions that
18584 would have been caused by TAB (such as table field motion or visibility
18585 cycling) will not occur.")
18587 (defvar org-tab-after-check-for-table-hook nil
18588 "Hook for functions to attach themselves to TAB.
18589 See `org-ctrl-c-ctrl-c-hook' for more information.
18590 This hook runs after it has been established that the cursor is not in a
18591 table, but before checking if the cursor is in a headline or if global cycling
18592 should be done.
18593 If any function in this hook returns t, not other actions like visibility
18594 cycling will be done.")
18596 (defvar org-tab-after-check-for-cycling-hook nil
18597 "Hook for functions to attach themselves to TAB.
18598 See `org-ctrl-c-ctrl-c-hook' for more information.
18599 This hook runs after it has been established that not table field motion and
18600 not visibility should be done because of current context. This is probably
18601 the place where a package like yasnippets can hook in.")
18603 (defvar org-tab-before-tab-emulation-hook nil
18604 "Hook for functions to attach themselves to TAB.
18605 See `org-ctrl-c-ctrl-c-hook' for more information.
18606 This hook runs after every other options for TAB have been exhausted, but
18607 before indentation and \t insertion takes place.")
18609 (defvar org-metaleft-hook nil
18610 "Hook for functions attaching themselves to `M-left'.
18611 See `org-ctrl-c-ctrl-c-hook' for more information.")
18612 (defvar org-metaright-hook nil
18613 "Hook for functions attaching themselves to `M-right'.
18614 See `org-ctrl-c-ctrl-c-hook' for more information.")
18615 (defvar org-metaup-hook nil
18616 "Hook for functions attaching themselves to `M-up'.
18617 See `org-ctrl-c-ctrl-c-hook' for more information.")
18618 (defvar org-metadown-hook nil
18619 "Hook for functions attaching themselves to `M-down'.
18620 See `org-ctrl-c-ctrl-c-hook' for more information.")
18621 (defvar org-shiftmetaleft-hook nil
18622 "Hook for functions attaching themselves to `M-S-left'.
18623 See `org-ctrl-c-ctrl-c-hook' for more information.")
18624 (defvar org-shiftmetaright-hook nil
18625 "Hook for functions attaching themselves to `M-S-right'.
18626 See `org-ctrl-c-ctrl-c-hook' for more information.")
18627 (defvar org-shiftmetaup-hook nil
18628 "Hook for functions attaching themselves to `M-S-up'.
18629 See `org-ctrl-c-ctrl-c-hook' for more information.")
18630 (defvar org-shiftmetadown-hook nil
18631 "Hook for functions attaching themselves to `M-S-down'.
18632 See `org-ctrl-c-ctrl-c-hook' for more information.")
18633 (defvar org-metareturn-hook nil
18634 "Hook for functions attaching themselves to `M-RET'.
18635 See `org-ctrl-c-ctrl-c-hook' for more information.")
18636 (defvar org-shiftup-hook nil
18637 "Hook for functions attaching themselves to `S-up'.
18638 See `org-ctrl-c-ctrl-c-hook' for more information.")
18639 (defvar org-shiftup-final-hook nil
18640 "Hook for functions attaching themselves to `S-up'.
18641 This one runs after all other options except shift-select have been excluded.
18642 See `org-ctrl-c-ctrl-c-hook' for more information.")
18643 (defvar org-shiftdown-hook nil
18644 "Hook for functions attaching themselves to `S-down'.
18645 See `org-ctrl-c-ctrl-c-hook' for more information.")
18646 (defvar org-shiftdown-final-hook nil
18647 "Hook for functions attaching themselves to `S-down'.
18648 This one runs after all other options except shift-select have been excluded.
18649 See `org-ctrl-c-ctrl-c-hook' for more information.")
18650 (defvar org-shiftleft-hook nil
18651 "Hook for functions attaching themselves to `S-left'.
18652 See `org-ctrl-c-ctrl-c-hook' for more information.")
18653 (defvar org-shiftleft-final-hook nil
18654 "Hook for functions attaching themselves to `S-left'.
18655 This one runs after all other options except shift-select have been excluded.
18656 See `org-ctrl-c-ctrl-c-hook' for more information.")
18657 (defvar org-shiftright-hook nil
18658 "Hook for functions attaching themselves to `S-right'.
18659 See `org-ctrl-c-ctrl-c-hook' for more information.")
18660 (defvar org-shiftright-final-hook nil
18661 "Hook for functions attaching themselves to `S-right'.
18662 This one runs after all other options except shift-select have been excluded.
18663 See `org-ctrl-c-ctrl-c-hook' for more information.")
18665 (defun org-modifier-cursor-error ()
18666 "Throw an error, a modified cursor command was applied in wrong context."
18667 (error "This command is active in special context like tables, headlines or items"))
18669 (defun org-shiftselect-error ()
18670 "Throw an error because Shift-Cursor command was applied in wrong context."
18671 (if (and (boundp 'shift-select-mode) shift-select-mode)
18672 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18673 (error "This command works only in special context like headlines or timestamps")))
18675 (defun org-call-for-shift-select (cmd)
18676 (let ((this-command-keys-shift-translated t))
18677 (call-interactively cmd)))
18679 (defun org-shifttab (&optional arg)
18680 "Global visibility cycling or move to previous table field.
18681 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18682 on context.
18683 See the individual commands for more information."
18684 (interactive "P")
18685 (cond
18686 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18687 ((integerp arg)
18688 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18689 (message "Content view to level: %d" arg)
18690 (org-content (prefix-numeric-value arg2))
18691 (setq org-cycle-global-status 'overview)))
18692 (t (call-interactively 'org-global-cycle))))
18694 (defun org-shiftmetaleft ()
18695 "Promote subtree or delete table column.
18696 Calls `org-promote-subtree', `org-outdent-item-tree', or
18697 `org-table-delete-column', depending on context. See the
18698 individual commands for more information."
18699 (interactive)
18700 (cond
18701 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18702 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18703 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18704 ((if (not (org-region-active-p)) (org-at-item-p)
18705 (save-excursion (goto-char (region-beginning))
18706 (org-at-item-p)))
18707 (call-interactively 'org-outdent-item-tree))
18708 (t (org-modifier-cursor-error))))
18710 (defun org-shiftmetaright ()
18711 "Demote subtree or insert table column.
18712 Calls `org-demote-subtree', `org-indent-item-tree', or
18713 `org-table-insert-column', depending on context. See the
18714 individual commands for more information."
18715 (interactive)
18716 (cond
18717 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18718 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18719 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18720 ((if (not (org-region-active-p)) (org-at-item-p)
18721 (save-excursion (goto-char (region-beginning))
18722 (org-at-item-p)))
18723 (call-interactively 'org-indent-item-tree))
18724 (t (org-modifier-cursor-error))))
18726 (defun org-shiftmetaup (&optional arg)
18727 "Move subtree up or kill table row.
18728 Calls `org-move-subtree-up' or `org-table-kill-row' or
18729 `org-move-item-up' or `org-timestamp-up', depending on context.
18730 See the individual commands for more information."
18731 (interactive "P")
18732 (cond
18733 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18734 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18735 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18736 ((org-at-item-p) (call-interactively 'org-move-item-up))
18737 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18738 (call-interactively 'org-timestamp-up)))
18739 (t (org-modifier-cursor-error))))
18741 (defun org-shiftmetadown (&optional arg)
18742 "Move subtree down or insert table row.
18743 Calls `org-move-subtree-down' or `org-table-insert-row' or
18744 `org-move-item-down' or `org-timestamp-up', depending on context.
18745 See the individual commands for more information."
18746 (interactive "P")
18747 (cond
18748 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18749 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18750 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18751 ((org-at-item-p) (call-interactively 'org-move-item-down))
18752 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18753 (call-interactively 'org-timestamp-down)))
18754 (t (org-modifier-cursor-error))))
18756 (defsubst org-hidden-tree-error ()
18757 (error
18758 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18760 (defun org-metaleft (&optional arg)
18761 "Promote heading or move table column to left.
18762 Calls `org-do-promote' or `org-table-move-column', depending on context.
18763 With no specific context, calls the Emacs default `backward-word'.
18764 See the individual commands for more information."
18765 (interactive "P")
18766 (cond
18767 ((run-hook-with-args-until-success 'org-metaleft-hook))
18768 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18769 ((org-with-limited-levels
18770 (or (org-at-heading-p)
18771 (and (org-region-active-p)
18772 (save-excursion
18773 (goto-char (region-beginning))
18774 (org-at-heading-p)))))
18775 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18776 (call-interactively 'org-do-promote))
18777 ;; At an inline task.
18778 ((org-at-heading-p)
18779 (call-interactively 'org-inlinetask-promote))
18780 ((or (org-at-item-p)
18781 (and (org-region-active-p)
18782 (save-excursion
18783 (goto-char (region-beginning))
18784 (org-at-item-p))))
18785 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18786 (call-interactively 'org-outdent-item))
18787 (t (call-interactively 'backward-word))))
18789 (defun org-metaright (&optional arg)
18790 "Demote a subtree, a list item or move table column to right.
18791 In front of a drawer or a block keyword, indent it correctly.
18792 With no specific context, calls the Emacs default `forward-word'.
18793 See the individual commands for more information."
18794 (interactive "P")
18795 (cond
18796 ((run-hook-with-args-until-success 'org-metaright-hook))
18797 ((org-at-table-p) (call-interactively 'org-table-move-column))
18798 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18799 ((org-at-block-p) (call-interactively 'org-indent-block))
18800 ((org-with-limited-levels
18801 (or (org-at-heading-p)
18802 (and (org-region-active-p)
18803 (save-excursion
18804 (goto-char (region-beginning))
18805 (org-at-heading-p)))))
18806 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18807 (call-interactively 'org-do-demote))
18808 ;; At an inline task.
18809 ((org-at-heading-p)
18810 (call-interactively 'org-inlinetask-demote))
18811 ((or (org-at-item-p)
18812 (and (org-region-active-p)
18813 (save-excursion
18814 (goto-char (region-beginning))
18815 (org-at-item-p))))
18816 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18817 (call-interactively 'org-indent-item))
18818 (t (call-interactively 'forward-word))))
18820 (defun org-check-for-hidden (what)
18821 "Check if there are hidden headlines/items in the current visual line.
18822 WHAT can be either `headlines' or `items'. If the current line is
18823 an outline or item heading and it has a folded subtree below it,
18824 this function returns t, nil otherwise."
18825 (let ((re (cond
18826 ((eq what 'headlines) org-outline-regexp-bol)
18827 ((eq what 'items) (org-item-beginning-re))
18828 (t (error "This should not happen"))))
18829 beg end)
18830 (save-excursion
18831 (catch 'exit
18832 (unless (org-region-active-p)
18833 (setq beg (point-at-bol))
18834 (beginning-of-line 2)
18835 (while (and (not (eobp)) ;; this is like `next-line'
18836 (get-char-property (1- (point)) 'invisible))
18837 (beginning-of-line 2))
18838 (setq end (point))
18839 (goto-char beg)
18840 (goto-char (point-at-eol))
18841 (setq end (max end (point)))
18842 (while (re-search-forward re end t)
18843 (if (get-char-property (match-beginning 0) 'invisible)
18844 (throw 'exit t))))
18845 nil))))
18847 (defun org-metaup (&optional arg)
18848 "Move subtree up or move table row up.
18849 Calls `org-move-subtree-up' or `org-table-move-row' or
18850 `org-move-item-up', depending on context. See the individual commands
18851 for more information."
18852 (interactive "P")
18853 (cond
18854 ((run-hook-with-args-until-success 'org-metaup-hook))
18855 ((org-region-active-p)
18856 (let* ((a (min (region-beginning) (region-end)))
18857 (b (1- (max (region-beginning) (region-end))))
18858 (c (save-excursion (goto-char a)
18859 (move-beginning-of-line 0)))
18860 (d (save-excursion (goto-char a)
18861 (move-end-of-line 0) (point))))
18862 (transpose-regions a b c d)
18863 (goto-char c)))
18864 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18865 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18866 ((org-at-item-p) (call-interactively 'org-move-item-up))
18867 (t (org-drag-element-backward))))
18869 (defun org-metadown (&optional arg)
18870 "Move subtree down or move table row down.
18871 Calls `org-move-subtree-down' or `org-table-move-row' or
18872 `org-move-item-down', depending on context. See the individual
18873 commands for more information."
18874 (interactive "P")
18875 (cond
18876 ((run-hook-with-args-until-success 'org-metadown-hook))
18877 ((org-region-active-p)
18878 (let* ((a (min (region-beginning) (region-end)))
18879 (b (max (region-beginning) (region-end)))
18880 (c (save-excursion (goto-char b)
18881 (move-beginning-of-line 1)))
18882 (d (save-excursion (goto-char b)
18883 (move-end-of-line 1) (1+ (point)))))
18884 (transpose-regions a b c d)
18885 (goto-char d)))
18886 ((org-at-table-p) (call-interactively 'org-table-move-row))
18887 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18888 ((org-at-item-p) (call-interactively 'org-move-item-down))
18889 (t (org-drag-element-forward))))
18891 (defun org-shiftup (&optional arg)
18892 "Increase item in timestamp or increase priority of current headline.
18893 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18894 depending on context. See the individual commands for more information."
18895 (interactive "P")
18896 (cond
18897 ((run-hook-with-args-until-success 'org-shiftup-hook))
18898 ((and org-support-shift-select (org-region-active-p))
18899 (org-call-for-shift-select 'previous-line))
18900 ((org-at-timestamp-p t)
18901 (call-interactively (if org-edit-timestamp-down-means-later
18902 'org-timestamp-down 'org-timestamp-up)))
18903 ((and (not (eq org-support-shift-select 'always))
18904 org-enable-priority-commands
18905 (org-at-heading-p))
18906 (call-interactively 'org-priority-up))
18907 ((and (not org-support-shift-select) (org-at-item-p))
18908 (call-interactively 'org-previous-item))
18909 ((org-clocktable-try-shift 'up arg))
18910 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18911 (org-support-shift-select
18912 (org-call-for-shift-select 'previous-line))
18913 (t (org-shiftselect-error))))
18915 (defun org-shiftdown (&optional arg)
18916 "Decrease item in timestamp or decrease priority of current headline.
18917 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18918 depending on context. See the individual commands for more information."
18919 (interactive "P")
18920 (cond
18921 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18922 ((and org-support-shift-select (org-region-active-p))
18923 (org-call-for-shift-select 'next-line))
18924 ((org-at-timestamp-p t)
18925 (call-interactively (if org-edit-timestamp-down-means-later
18926 'org-timestamp-up 'org-timestamp-down)))
18927 ((and (not (eq org-support-shift-select 'always))
18928 org-enable-priority-commands
18929 (org-at-heading-p))
18930 (call-interactively 'org-priority-down))
18931 ((and (not org-support-shift-select) (org-at-item-p))
18932 (call-interactively 'org-next-item))
18933 ((org-clocktable-try-shift 'down arg))
18934 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18935 (org-support-shift-select
18936 (org-call-for-shift-select 'next-line))
18937 (t (org-shiftselect-error))))
18939 (defun org-shiftright (&optional arg)
18940 "Cycle the thing at point or in the current line, depending on context.
18941 Depending on context, this does one of the following:
18943 - switch a timestamp at point one day into the future
18944 - on a headline, switch to the next TODO keyword.
18945 - on an item, switch entire list to the next bullet type
18946 - on a property line, switch to the next allowed value
18947 - on a clocktable definition line, move time block into the future"
18948 (interactive "P")
18949 (cond
18950 ((run-hook-with-args-until-success 'org-shiftright-hook))
18951 ((and org-support-shift-select (org-region-active-p))
18952 (org-call-for-shift-select 'forward-char))
18953 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18954 ((and (not (eq org-support-shift-select 'always))
18955 (org-at-heading-p))
18956 (let ((org-inhibit-logging
18957 (not org-treat-S-cursor-todo-selection-as-state-change))
18958 (org-inhibit-blocking
18959 (not org-treat-S-cursor-todo-selection-as-state-change)))
18960 (org-call-with-arg 'org-todo 'right)))
18961 ((or (and org-support-shift-select
18962 (not (eq org-support-shift-select 'always))
18963 (org-at-item-bullet-p))
18964 (and (not org-support-shift-select) (org-at-item-p)))
18965 (org-call-with-arg 'org-cycle-list-bullet nil))
18966 ((and (not (eq org-support-shift-select 'always))
18967 (org-at-property-p))
18968 (call-interactively 'org-property-next-allowed-value))
18969 ((org-clocktable-try-shift 'right arg))
18970 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18971 (org-support-shift-select
18972 (org-call-for-shift-select 'forward-char))
18973 (t (org-shiftselect-error))))
18975 (defun org-shiftleft (&optional arg)
18976 "Cycle the thing at point or in the current line, depending on context.
18977 Depending on context, this does one of the following:
18979 - switch a timestamp at point one day into the past
18980 - on a headline, switch to the previous TODO keyword.
18981 - on an item, switch entire list to the previous bullet type
18982 - on a property line, switch to the previous allowed value
18983 - on a clocktable definition line, move time block into the past"
18984 (interactive "P")
18985 (cond
18986 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18987 ((and org-support-shift-select (org-region-active-p))
18988 (org-call-for-shift-select 'backward-char))
18989 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18990 ((and (not (eq org-support-shift-select 'always))
18991 (org-at-heading-p))
18992 (let ((org-inhibit-logging
18993 (not org-treat-S-cursor-todo-selection-as-state-change))
18994 (org-inhibit-blocking
18995 (not org-treat-S-cursor-todo-selection-as-state-change)))
18996 (org-call-with-arg 'org-todo 'left)))
18997 ((or (and org-support-shift-select
18998 (not (eq org-support-shift-select 'always))
18999 (org-at-item-bullet-p))
19000 (and (not org-support-shift-select) (org-at-item-p)))
19001 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19002 ((and (not (eq org-support-shift-select 'always))
19003 (org-at-property-p))
19004 (call-interactively 'org-property-previous-allowed-value))
19005 ((org-clocktable-try-shift 'left arg))
19006 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19007 (org-support-shift-select
19008 (org-call-for-shift-select 'backward-char))
19009 (t (org-shiftselect-error))))
19011 (defun org-shiftcontrolright ()
19012 "Switch to next TODO set."
19013 (interactive)
19014 (cond
19015 ((and org-support-shift-select (org-region-active-p))
19016 (org-call-for-shift-select 'forward-word))
19017 ((and (not (eq org-support-shift-select 'always))
19018 (org-at-heading-p))
19019 (org-call-with-arg 'org-todo 'nextset))
19020 (org-support-shift-select
19021 (org-call-for-shift-select 'forward-word))
19022 (t (org-shiftselect-error))))
19024 (defun org-shiftcontrolleft ()
19025 "Switch to previous TODO set."
19026 (interactive)
19027 (cond
19028 ((and org-support-shift-select (org-region-active-p))
19029 (org-call-for-shift-select 'backward-word))
19030 ((and (not (eq org-support-shift-select 'always))
19031 (org-at-heading-p))
19032 (org-call-with-arg 'org-todo 'previousset))
19033 (org-support-shift-select
19034 (org-call-for-shift-select 'backward-word))
19035 (t (org-shiftselect-error))))
19037 (defun org-shiftcontrolup ()
19038 "Change timestamps synchronously up in CLOCK log lines."
19039 (interactive)
19040 (cond ((and (not org-support-shift-select)
19041 (org-at-clock-log-p)
19042 (org-at-timestamp-p t))
19043 (org-clock-timestamps-up))
19044 (t (org-shiftselect-error))))
19046 (defun org-shiftcontroldown ()
19047 "Change timestamps synchronously down in CLOCK log lines."
19048 (interactive)
19049 (cond ((and (not org-support-shift-select)
19050 (org-at-clock-log-p)
19051 (org-at-timestamp-p t))
19052 (org-clock-timestamps-down))
19053 (t (org-shiftselect-error))))
19055 (defun org-ctrl-c-ret ()
19056 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19057 (interactive)
19058 (cond
19059 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19060 (t (call-interactively 'org-insert-heading))))
19062 (defun org-find-visible ()
19063 (let ((s (point)))
19064 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19065 (get-char-property s 'invisible)))
19067 (defun org-find-invisible ()
19068 (let ((s (point)))
19069 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19070 (not (get-char-property s 'invisible))))
19073 (defun org-copy-visible (beg end)
19074 "Copy the visible parts of the region."
19075 (interactive "r")
19076 (let (snippets s)
19077 (save-excursion
19078 (save-restriction
19079 (narrow-to-region beg end)
19080 (setq s (goto-char (point-min)))
19081 (while (not (= (point) (point-max)))
19082 (goto-char (org-find-invisible))
19083 (push (buffer-substring s (point)) snippets)
19084 (setq s (goto-char (org-find-visible))))))
19085 (kill-new (apply 'concat (nreverse snippets)))))
19087 (defun org-copy-special ()
19088 "Copy region in table or copy current subtree.
19089 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19090 See the individual commands for more information."
19091 (interactive)
19092 (call-interactively
19093 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19095 (defun org-cut-special ()
19096 "Cut region in table or cut current subtree.
19097 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19098 See the individual commands for more information."
19099 (interactive)
19100 (call-interactively
19101 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19103 (defun org-paste-special (arg)
19104 "Paste rectangular region into table, or past subtree relative to level.
19105 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19106 See the individual commands for more information."
19107 (interactive "P")
19108 (if (org-at-table-p)
19109 (org-table-paste-rectangle)
19110 (org-paste-subtree arg)))
19112 (defun org-edit-special (&optional arg)
19113 "Call a special editor for the stuff at point.
19114 When at a table, call the formula editor with `org-table-edit-formulas'.
19115 When at the first line of an src example, call `org-edit-src-code'.
19116 When in an #+include line, visit the include file. Otherwise call
19117 `ffap' to visit the file at point."
19118 (interactive)
19119 ;; possibly prep session before editing source
19120 (when arg
19121 (let* ((info (org-babel-get-src-block-info))
19122 (lang (nth 0 info))
19123 (params (nth 2 info))
19124 (session (cdr (assoc :session params))))
19125 (when (and info session) ;; we are in a source-code block with a session
19126 (funcall
19127 (intern (concat "org-babel-prep-session:" lang)) session params))))
19128 (cond ;; proceed with `org-edit-special'
19129 ((save-excursion
19130 (beginning-of-line 1)
19131 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19132 (find-file (org-trim (match-string 1))))
19133 ((org-edit-src-code))
19134 ((org-edit-fixed-width-region))
19135 ((org-at-table.el-p)
19136 (org-edit-src-code))
19137 ((or (org-at-table-p)
19138 (save-excursion
19139 (beginning-of-line 1)
19140 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19141 (call-interactively 'org-table-edit-formulas))
19142 (t (call-interactively 'ffap))))
19144 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19145 (defun org-ctrl-c-ctrl-c (&optional arg)
19146 "Set tags in headline, or update according to changed information at point.
19148 This command does many different things, depending on context:
19150 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19151 this is what we do.
19153 - If the cursor is on a statistics cookie, update it.
19155 - If the cursor is in a headline, prompt for tags and insert them
19156 into the current line, aligned to `org-tags-column'. When called
19157 with prefix arg, realign all tags in the current buffer.
19159 - If the cursor is in one of the special #+KEYWORD lines, this
19160 triggers scanning the buffer for these lines and updating the
19161 information.
19163 - If the cursor is inside a table, realign the table. This command
19164 works even if the automatic table editor has been turned off.
19166 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19167 the entire table.
19169 - If the cursor is at a footnote reference or definition, jump to
19170 the corresponding definition or references, respectively.
19172 - If the cursor is a the beginning of a dynamic block, update it.
19174 - If the current buffer is a capture buffer, close note and file it.
19176 - If the cursor is on a <<<target>>>, update radio targets and
19177 corresponding links in this buffer.
19179 - If the cursor is on a numbered item in a plain list, renumber the
19180 ordered list.
19182 - If the cursor is on a checkbox, toggle it.
19184 - If the cursor is on a code block, evaluate it. The variable
19185 `org-confirm-babel-evaluate' can be used to control prompting
19186 before code block evaluation, by default every code block
19187 evaluation requires confirmation. Code block evaluation can be
19188 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19189 (interactive "P")
19190 (let ((org-enable-table-editor t))
19191 (cond
19192 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19193 org-occur-highlights
19194 org-latex-fragment-image-overlays)
19195 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19196 (org-remove-occur-highlights)
19197 (org-remove-latex-fragment-image-overlays)
19198 (message "Temporary highlights/overlays removed from current buffer"))
19199 ((and (local-variable-p 'org-finish-function (current-buffer))
19200 (fboundp org-finish-function))
19201 (funcall org-finish-function))
19202 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19203 ((org-in-regexp org-ts-regexp-both)
19204 (org-timestamp-change 0 'day))
19205 ((or (looking-at org-property-start-re)
19206 (org-at-property-p))
19207 (call-interactively 'org-property-action))
19208 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19209 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19210 (or (org-at-heading-p) (org-at-item-p)))
19211 (call-interactively 'org-update-statistics-cookies))
19212 ((org-at-heading-p) (call-interactively 'org-set-tags))
19213 ((org-at-table.el-p)
19214 (message "Use C-c ' to edit table.el tables"))
19215 ((org-at-table-p)
19216 (org-table-maybe-eval-formula)
19217 (if arg
19218 (call-interactively 'org-table-recalculate)
19219 (org-table-maybe-recalculate-line))
19220 (call-interactively 'org-table-align)
19221 (orgtbl-send-table 'maybe))
19222 ((or (org-footnote-at-reference-p)
19223 (org-footnote-at-definition-p))
19224 (call-interactively 'org-footnote-action))
19225 ((org-at-item-checkbox-p)
19226 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19227 ;; list only if at top item.
19228 (let* ((cbox (match-string 1))
19229 (struct (org-list-struct))
19230 (old-struct (copy-tree struct))
19231 (parents (org-list-parents-alist struct))
19232 (orderedp (org-entry-get nil "ORDERED"))
19233 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19234 block-item)
19235 ;; Use a light version of `org-toggle-checkbox' to avoid
19236 ;; computing list structure twice.
19237 (let ((new-box (cond
19238 ((equal arg '(16)) "[-]")
19239 ((equal arg '(4)) nil)
19240 ((equal "[X]" cbox) "[ ]")
19241 (t "[X]"))))
19242 (if (and firstp arg)
19243 ;; If at first item of sub-list, remove check-box from
19244 ;; every item at the same level.
19245 (mapc
19246 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19247 (org-list-get-all-items
19248 (point-at-bol) struct (org-list-prevs-alist struct)))
19249 (org-list-set-checkbox (point-at-bol) struct new-box)))
19250 ;; Replicate `org-list-write-struct', while grabbing a return
19251 ;; value from `org-list-struct-fix-box'.
19252 (org-list-struct-fix-ind struct parents 2)
19253 (org-list-struct-fix-item-end struct)
19254 (let ((prevs (org-list-prevs-alist struct)))
19255 (org-list-struct-fix-bul struct prevs)
19256 (org-list-struct-fix-ind struct parents)
19257 (setq block-item
19258 (org-list-struct-fix-box struct parents prevs orderedp)))
19259 (org-list-struct-apply-struct struct old-struct)
19260 (org-update-checkbox-count-maybe)
19261 (when block-item
19262 (message
19263 "Checkboxes were removed due to unchecked box at line %d"
19264 (org-current-line block-item)))
19265 (when firstp (org-list-send-list 'maybe))))
19266 ((org-at-item-p)
19267 ;; Cursor at an item: repair list. Do checkbox related actions
19268 ;; only if function was called with an argument. Send list only
19269 ;; if at top item.
19270 (let* ((struct (org-list-struct))
19271 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19272 old-struct)
19273 (when arg
19274 (setq old-struct (copy-tree struct))
19275 (if firstp
19276 ;; If at first item of sub-list, add check-box to every
19277 ;; item at the same level.
19278 (mapc
19279 (lambda (pos)
19280 (unless (org-list-get-checkbox pos struct)
19281 (org-list-set-checkbox pos struct "[ ]")))
19282 (org-list-get-all-items
19283 (point-at-bol) struct (org-list-prevs-alist struct)))
19284 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19285 (org-list-write-struct
19286 struct (org-list-parents-alist struct) old-struct)
19287 (when arg (org-update-checkbox-count-maybe))
19288 (when firstp (org-list-send-list 'maybe))))
19289 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19290 ;; Dynamic block
19291 (beginning-of-line 1)
19292 (save-excursion (org-update-dblock)))
19293 ((save-excursion
19294 (let ((case-fold-search t))
19295 (beginning-of-line 1)
19296 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19297 (cond
19298 ((or (equal (match-string 1) "TBLFM")
19299 (equal (match-string 1) "tblfm"))
19300 ;; Recalculate the table before this line
19301 (save-excursion
19302 (beginning-of-line 1)
19303 (skip-chars-backward " \r\n\t")
19304 (if (org-at-table-p)
19305 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19307 (let ((org-inhibit-startup-visibility-stuff t)
19308 (org-startup-align-all-tables nil))
19309 (when (boundp 'org-table-coordinate-overlays)
19310 (mapc 'delete-overlay org-table-coordinate-overlays)
19311 (setq org-table-coordinate-overlays nil))
19312 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19313 (message "Local setup has been refreshed"))))
19314 ((org-clock-update-time-maybe))
19316 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19317 (error "C-c C-c can do nothing useful at this location"))))))
19319 (defun org-mode-restart ()
19320 "Restart Org-mode, to scan again for special lines.
19321 Also updates the keyword regular expressions."
19322 (interactive)
19323 (org-mode)
19324 (message "Org-mode restarted"))
19326 (defun org-kill-note-or-show-branches ()
19327 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19328 (interactive)
19329 (if (not org-finish-function)
19330 (progn
19331 (hide-subtree)
19332 (call-interactively 'show-branches))
19333 (let ((org-note-abort t))
19334 (funcall org-finish-function))))
19336 (defun org-return (&optional indent)
19337 "Goto next table row or insert a newline.
19338 Calls `org-table-next-row' or `newline', depending on context.
19339 See the individual commands for more information."
19340 (interactive)
19341 (let (org-ts-what)
19342 (cond
19343 ((or (bobp) (org-in-src-block-p))
19344 (if indent (newline-and-indent) (newline)))
19345 ((org-at-table-p)
19346 (org-table-justify-field-maybe)
19347 (call-interactively 'org-table-next-row))
19348 ;; when `newline-and-indent' is called within a list, make sure
19349 ;; text moved stays inside the item.
19350 ((and (org-in-item-p) indent)
19351 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19352 (progn
19353 (save-match-data (newline))
19354 (org-indent-line-to (length (match-string 0))))
19355 (let ((ind (org-get-indentation)))
19356 (newline)
19357 (if (org-looking-back org-list-end-re)
19358 (org-indent-line)
19359 (org-indent-line-to ind)))))
19360 ((and org-return-follows-link
19361 (org-at-timestamp-p t)
19362 (not (eq org-ts-what 'after)))
19363 (org-follow-timestamp-link))
19364 ((and org-return-follows-link
19365 (let ((tprop (get-text-property (point) 'face)))
19366 (or (eq tprop 'org-link)
19367 (and (listp tprop) (memq 'org-link tprop)))))
19368 (call-interactively 'org-open-at-point))
19369 ((and (org-at-heading-p)
19370 (looking-at
19371 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19372 (org-show-entry)
19373 (end-of-line 1)
19374 (newline))
19375 (t (if indent (newline-and-indent) (newline))))))
19377 (defun org-return-indent ()
19378 "Goto next table row or insert a newline and indent.
19379 Calls `org-table-next-row' or `newline-and-indent', depending on
19380 context. See the individual commands for more information."
19381 (interactive)
19382 (org-return t))
19384 (defun org-ctrl-c-star ()
19385 "Compute table, or change heading status of lines.
19386 Calls `org-table-recalculate' or `org-toggle-heading',
19387 depending on context."
19388 (interactive)
19389 (cond
19390 ((org-at-table-p)
19391 (call-interactively 'org-table-recalculate))
19393 ;; Convert all lines in region to list items
19394 (call-interactively 'org-toggle-heading))))
19396 (defun org-ctrl-c-minus ()
19397 "Insert separator line in table or modify bullet status of line.
19398 Also turns a plain line or a region of lines into list items.
19399 Calls `org-table-insert-hline', `org-toggle-item', or
19400 `org-cycle-list-bullet', depending on context."
19401 (interactive)
19402 (cond
19403 ((org-at-table-p)
19404 (call-interactively 'org-table-insert-hline))
19405 ((org-region-active-p)
19406 (call-interactively 'org-toggle-item))
19407 ((org-in-item-p)
19408 (call-interactively 'org-cycle-list-bullet))
19410 (call-interactively 'org-toggle-item))))
19412 (defun org-toggle-item (arg)
19413 "Convert headings or normal lines to items, items to normal lines.
19414 If there is no active region, only the current line is considered.
19416 If the first non blank line in the region is an headline, convert
19417 all headlines to items, shifting text accordingly.
19419 If it is an item, convert all items to normal lines.
19421 If it is normal text, change region into an item. With a prefix
19422 argument ARG, change each line in region into an item."
19423 (interactive "P")
19424 (let ((shift-text
19425 (function
19426 ;; Shift text in current section to IND, from point to END.
19427 ;; The function leaves point to END line.
19428 (lambda (ind end)
19429 (let ((min-i 1000) (end (copy-marker end)))
19430 ;; First determine the minimum indentation (MIN-I) of
19431 ;; the text.
19432 (save-excursion
19433 (catch 'exit
19434 (while (< (point) end)
19435 (let ((i (org-get-indentation)))
19436 (cond
19437 ;; Skip blank lines and inline tasks.
19438 ((looking-at "^[ \t]*$"))
19439 ((looking-at org-outline-regexp-bol))
19440 ;; We can't find less than 0 indentation.
19441 ((zerop i) (throw 'exit (setq min-i 0)))
19442 ((< i min-i) (setq min-i i))))
19443 (forward-line))))
19444 ;; Then indent each line so that a line indented to
19445 ;; MIN-I becomes indented to IND. Ignore blank lines
19446 ;; and inline tasks in the process.
19447 (let ((delta (- ind min-i)))
19448 (while (< (point) end)
19449 (unless (or (looking-at "^[ \t]*$")
19450 (looking-at org-outline-regexp-bol))
19451 (org-indent-line-to (+ (org-get-indentation) delta)))
19452 (forward-line)))))))
19453 (skip-blanks
19454 (function
19455 ;; Return beginning of first non-blank line, starting from
19456 ;; line at POS.
19457 (lambda (pos)
19458 (save-excursion
19459 (goto-char pos)
19460 (skip-chars-forward " \r\t\n")
19461 (point-at-bol)))))
19462 beg end)
19463 ;; Determine boundaries of changes.
19464 (if (org-region-active-p)
19465 (setq beg (funcall skip-blanks (region-beginning))
19466 end (copy-marker (region-end)))
19467 (setq beg (funcall skip-blanks (point-at-bol))
19468 end (copy-marker (point-at-eol))))
19469 ;; Depending on the starting line, choose an action on the text
19470 ;; between BEG and END.
19471 (org-with-limited-levels
19472 (save-excursion
19473 (goto-char beg)
19474 (cond
19475 ;; Case 1. Start at an item: de-itemize. Note that it only
19476 ;; happens when a region is active: `org-ctrl-c-minus'
19477 ;; would call `org-cycle-list-bullet' otherwise.
19478 ((org-at-item-p)
19479 (while (< (point) end)
19480 (when (org-at-item-p)
19481 (skip-chars-forward " \t")
19482 (delete-region (point) (match-end 0)))
19483 (forward-line)))
19484 ;; Case 2. Start at an heading: convert to items.
19485 ((org-at-heading-p)
19486 (let* ((bul (org-list-bullet-string "-"))
19487 (bul-len (length bul))
19488 ;; Indentation of the first heading. It should be
19489 ;; relative to the indentation of its parent, if any.
19490 (start-ind (save-excursion
19491 (cond
19492 ((not org-adapt-indentation) 0)
19493 ((not (outline-previous-heading)) 0)
19494 (t (length (match-string 0))))))
19495 ;; Level of first heading. Further headings will be
19496 ;; compared to it to determine hierarchy in the list.
19497 (ref-level (org-reduced-level (org-outline-level))))
19498 (while (< (point) end)
19499 (let* ((level (org-reduced-level (org-outline-level)))
19500 (delta (max 0 (- level ref-level))))
19501 ;; If current headline is less indented than the first
19502 ;; one, set it as reference, in order to preserve
19503 ;; subtrees.
19504 (when (< level ref-level) (setq ref-level level))
19505 (replace-match bul t t)
19506 (org-indent-line-to (+ start-ind (* delta bul-len)))
19507 ;; Ensure all text down to END (or SECTION-END) belongs
19508 ;; to the newly created item.
19509 (let ((section-end (save-excursion
19510 (or (outline-next-heading) (point)))))
19511 (forward-line)
19512 (funcall shift-text
19513 (+ start-ind (* (1+ delta) bul-len))
19514 (min end section-end)))))))
19515 ;; Case 3. Normal line with ARG: turn each non-item line into
19516 ;; an item.
19517 (arg
19518 (while (< (point) end)
19519 (unless (or (org-at-heading-p) (org-at-item-p))
19520 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19521 (replace-match
19522 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19523 (forward-line)))
19524 ;; Case 4. Normal line without ARG: make the first line of
19525 ;; region an item, and shift indentation of others
19526 ;; lines to set them as item's body.
19527 (t (let* ((bul (org-list-bullet-string "-"))
19528 (bul-len (length bul))
19529 (ref-ind (org-get-indentation)))
19530 (skip-chars-forward " \t")
19531 (insert bul)
19532 (forward-line)
19533 (while (< (point) end)
19534 ;; Ensure that lines less indented than first one
19535 ;; still get included in item body.
19536 (funcall shift-text
19537 (+ ref-ind bul-len)
19538 (min end (save-excursion (or (outline-next-heading)
19539 (point)))))
19540 (forward-line)))))))))
19542 (defun org-toggle-heading (&optional nstars)
19543 "Convert headings to normal text, or items or text to headings.
19544 If there is no active region, only the current line is considered.
19546 With a \\[universal-argument] prefix, convert the whole list at
19547 point into heading.
19549 In a region:
19551 - If the first non blank line is an headline, remove the stars
19552 from all headlines in the region.
19554 - If it is a normal line turn each and every normal line (i.e. not an
19555 heading or an item) in the region into a heading.
19557 - If it is a plain list item, turn all plain list items into headings.
19559 When converting a line into a heading, the number of stars is chosen
19560 such that the lines become children of the current entry. However,
19561 when a prefix argument is given, its value determines the number of
19562 stars to add."
19563 (interactive "P")
19564 (let ((skip-blanks
19565 (function
19566 ;; Return beginning of first non-blank line, starting from
19567 ;; line at POS.
19568 (lambda (pos)
19569 (save-excursion
19570 (goto-char pos)
19571 (while (org-at-comment-p) (forward-line))
19572 (skip-chars-forward " \r\t\n")
19573 (point-at-bol)))))
19574 beg end toggled)
19575 ;; Determine boundaries of changes. If a universal prefix has
19576 ;; been given, put the list in a region. If region ends at a bol,
19577 ;; do not consider the last line to be in the region.
19579 (when (and current-prefix-arg (org-at-item-p))
19580 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19581 (org-mark-element))
19583 (if (org-region-active-p)
19584 (setq beg (funcall skip-blanks (region-beginning))
19585 end (copy-marker (save-excursion
19586 (goto-char (region-end))
19587 (if (bolp) (point) (point-at-eol)))))
19588 (setq beg (funcall skip-blanks (point-at-bol))
19589 end (copy-marker (point-at-eol))))
19590 ;; Ensure inline tasks don't count as headings.
19591 (org-with-limited-levels
19592 (save-excursion
19593 (goto-char beg)
19594 (cond
19595 ;; Case 1. Started at an heading: de-star headings.
19596 ((org-at-heading-p)
19597 (while (< (point) end)
19598 (when (org-at-heading-p t)
19599 (looking-at org-outline-regexp) (replace-match "")
19600 (setq toggled t))
19601 (forward-line)))
19602 ;; Case 2. Started at an item: change items into headlines.
19603 ;; One star will be added by `org-list-to-subtree'.
19604 ((org-at-item-p)
19605 (let* ((stars (make-string
19606 (if nstars
19607 ;; subtract the star that will be added again by
19608 ;; `org-list-to-subtree'
19609 (1- (prefix-numeric-value current-prefix-arg))
19610 (or (org-current-level) 0))
19611 ?*))
19612 (add-stars
19613 (cond (nstars "") ; stars from prefix only
19614 ((equal stars "") "") ; before first heading
19615 (org-odd-levels-only "*") ; inside heading, odd
19616 (t "")))) ; inside heading, oddeven
19617 (while (< (point) end)
19618 (when (org-at-item-p)
19619 ;; Pay attention to cases when region ends before list.
19620 (let* ((struct (org-list-struct))
19621 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19622 (save-restriction
19623 (narrow-to-region (point) list-end)
19624 (insert
19625 (org-list-to-subtree
19626 (org-list-parse-list t)
19627 '(:istart (concat stars add-stars (funcall get-stars depth))
19628 :icount (concat stars add-stars (funcall get-stars depth)))))))
19629 (setq toggled t))
19630 (forward-line))))
19631 ;; Case 3. Started at normal text: make every line an heading,
19632 ;; skipping headlines and items.
19633 (t (let* ((stars (make-string
19634 (if nstars
19635 (prefix-numeric-value current-prefix-arg)
19636 (or (org-current-level) 0))
19637 ?*))
19638 (add-stars
19639 (cond (nstars "") ; stars from prefix only
19640 ((equal stars "") "*") ; before first heading
19641 (org-odd-levels-only "**") ; inside heading, odd
19642 (t "*"))) ; inside heading, oddeven
19643 (rpl (concat stars add-stars " ")))
19644 (while (< (point) end)
19645 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19646 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19647 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19648 (forward-line)))))))
19649 (unless toggled (message "Cannot toggle heading from here"))))
19651 (defun org-meta-return (&optional arg)
19652 "Insert a new heading or wrap a region in a table.
19653 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19654 See the individual commands for more information."
19655 (interactive "P")
19656 (cond
19657 ((run-hook-with-args-until-success 'org-metareturn-hook))
19658 ((or (org-at-drawer-p) (org-at-property-p))
19659 (newline-and-indent))
19660 ((org-at-table-p)
19661 (call-interactively 'org-table-wrap-region))
19662 (t (call-interactively 'org-insert-heading))))
19664 ;;; Menu entries
19666 (defsubst org-in-subtree-not-table-p ()
19667 "Are we in a subtree and not in a table?"
19668 (and (not (org-before-first-heading-p))
19669 (not (org-at-table-p))))
19671 ;; Define the Org-mode menus
19672 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19673 '("Tbl"
19674 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19675 ["Next Field" org-cycle (org-at-table-p)]
19676 ["Previous Field" org-shifttab (org-at-table-p)]
19677 ["Next Row" org-return (org-at-table-p)]
19678 "--"
19679 ["Blank Field" org-table-blank-field (org-at-table-p)]
19680 ["Edit Field" org-table-edit-field (org-at-table-p)]
19681 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19682 "--"
19683 ("Column"
19684 ["Move Column Left" org-metaleft (org-at-table-p)]
19685 ["Move Column Right" org-metaright (org-at-table-p)]
19686 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19687 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19688 ("Row"
19689 ["Move Row Up" org-metaup (org-at-table-p)]
19690 ["Move Row Down" org-metadown (org-at-table-p)]
19691 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19692 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19693 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19694 "--"
19695 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19696 ("Rectangle"
19697 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19698 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19699 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19700 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19701 "--"
19702 ("Calculate"
19703 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19704 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19705 ["Edit Formulas" org-edit-special (org-at-table-p)]
19706 "--"
19707 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19708 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19709 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19710 "--"
19711 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19712 "--"
19713 ["Sum Column/Rectangle" org-table-sum
19714 (or (org-at-table-p) (org-region-active-p))]
19715 ["Which Column?" org-table-current-column (org-at-table-p)])
19716 ["Debug Formulas"
19717 org-table-toggle-formula-debugger
19718 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19719 ["Show Col/Row Numbers"
19720 org-table-toggle-coordinate-overlays
19721 :style toggle
19722 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19723 "--"
19724 ["Create" org-table-create (and (not (org-at-table-p))
19725 org-enable-table-editor)]
19726 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19727 ["Import from File" org-table-import (not (org-at-table-p))]
19728 ["Export to File" org-table-export (org-at-table-p)]
19729 "--"
19730 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19732 (easy-menu-define org-org-menu org-mode-map "Org menu"
19733 '("Org"
19734 ("Show/Hide"
19735 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19736 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19737 ["Sparse Tree..." org-sparse-tree t]
19738 ["Reveal Context" org-reveal t]
19739 ["Show All" show-all t]
19740 "--"
19741 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19742 "--"
19743 ["New Heading" org-insert-heading t]
19744 ("Navigate Headings"
19745 ["Up" outline-up-heading t]
19746 ["Next" outline-next-visible-heading t]
19747 ["Previous" outline-previous-visible-heading t]
19748 ["Next Same Level" outline-forward-same-level t]
19749 ["Previous Same Level" outline-backward-same-level t]
19750 "--"
19751 ["Jump" org-goto t])
19752 ("Edit Structure"
19753 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19754 "--"
19755 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19756 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19757 "--"
19758 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19759 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19760 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19761 "--"
19762 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19763 "--"
19764 ["Copy visible text" org-copy-visible t]
19765 "--"
19766 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19767 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19768 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19769 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19770 "--"
19771 ["Sort Region/Children" org-sort t]
19772 "--"
19773 ["Convert to odd levels" org-convert-to-odd-levels t]
19774 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19775 ("Editing"
19776 ["Emphasis..." org-emphasize t]
19777 ["Edit Source Example" org-edit-special t]
19778 "--"
19779 ["Footnote new/jump" org-footnote-action t]
19780 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19781 ("Archive"
19782 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19783 "--"
19784 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19785 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19786 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19788 "--"
19789 ("Hyperlinks"
19790 ["Store Link (Global)" org-store-link t]
19791 ["Find existing link to here" org-occur-link-in-agenda-files t]
19792 ["Insert Link" org-insert-link t]
19793 ["Follow Link" org-open-at-point t]
19794 "--"
19795 ["Next link" org-next-link t]
19796 ["Previous link" org-previous-link t]
19797 "--"
19798 ["Descriptive Links"
19799 org-toggle-link-display
19800 :style radio
19801 :selected org-descriptive-links
19803 ["Literal Links"
19804 org-toggle-link-display
19805 :style radio
19806 :selected (not org-descriptive-links)])
19807 "--"
19808 ("TODO Lists"
19809 ["TODO/DONE/-" org-todo t]
19810 ("Select keyword"
19811 ["Next keyword" org-shiftright (org-at-heading-p)]
19812 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19813 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19814 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19815 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19816 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19817 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19818 "--"
19819 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19820 :selected org-enforce-todo-dependencies :style toggle :active t]
19821 "Settings for tree at point"
19822 ["Do Children sequentially" org-toggle-ordered-property :style radio
19823 :selected (org-entry-get nil "ORDERED")
19824 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19825 ["Do Children parallel" org-toggle-ordered-property :style radio
19826 :selected (not (org-entry-get nil "ORDERED"))
19827 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19828 "--"
19829 ["Set Priority" org-priority t]
19830 ["Priority Up" org-shiftup t]
19831 ["Priority Down" org-shiftdown t]
19832 "--"
19833 ["Get news from all feeds" org-feed-update-all t]
19834 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19835 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19836 ("TAGS and Properties"
19837 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19838 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19839 "--"
19840 ["Set property" org-set-property (not (org-before-first-heading-p))]
19841 ["Column view of properties" org-columns t]
19842 ["Insert Column View DBlock" org-insert-columns-dblock t])
19843 ("Dates and Scheduling"
19844 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19845 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19846 ("Change Date"
19847 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19848 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19849 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19850 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19851 ["Compute Time Range" org-evaluate-time-range t]
19852 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19853 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19854 "--"
19855 ["Custom time format" org-toggle-time-stamp-overlays
19856 :style radio :selected org-display-custom-times]
19857 "--"
19858 ["Goto Calendar" org-goto-calendar t]
19859 ["Date from Calendar" org-date-from-calendar t]
19860 "--"
19861 ["Start/Restart Timer" org-timer-start t]
19862 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19863 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19864 ["Insert Timer String" org-timer t]
19865 ["Insert Timer Item" org-timer-item t])
19866 ("Logging work"
19867 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19868 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19869 ["Clock out" org-clock-out t]
19870 ["Clock cancel" org-clock-cancel t]
19871 "--"
19872 ["Mark as default task" org-clock-mark-default-task t]
19873 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19874 ["Goto running clock" org-clock-goto t]
19875 "--"
19876 ["Display times" org-clock-display t]
19877 ["Create clock table" org-clock-report t]
19878 "--"
19879 ["Record DONE time"
19880 (progn (setq org-log-done (not org-log-done))
19881 (message "Switching to %s will %s record a timestamp"
19882 (car org-done-keywords)
19883 (if org-log-done "automatically" "not")))
19884 :style toggle :selected org-log-done])
19885 "--"
19886 ["Agenda Command..." org-agenda t]
19887 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19888 ("File List for Agenda")
19889 ("Special views current file"
19890 ["TODO Tree" org-show-todo-tree t]
19891 ["Check Deadlines" org-check-deadlines t]
19892 ["Timeline" org-timeline t]
19893 ["Tags/Property tree" org-match-sparse-tree t])
19894 "--"
19895 ["Export/Publish..." org-export t]
19896 ("LaTeX"
19897 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19898 :selected org-cdlatex-mode]
19899 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19900 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19901 ["Modify math symbol" org-cdlatex-math-modify
19902 (org-inside-LaTeX-fragment-p)]
19903 ["Insert citation" org-reftex-citation t]
19904 "--"
19905 ["Template for BEAMER" (progn (require 'org-beamer)
19906 (org-insert-beamer-options-template)) t])
19907 "--"
19908 ("MobileOrg"
19909 ["Push Files and Views" org-mobile-push t]
19910 ["Get Captured and Flagged" org-mobile-pull t]
19911 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19912 "--"
19913 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19914 "--"
19915 ("Documentation"
19916 ["Show Version" org-version t]
19917 ["Info Documentation" org-info t])
19918 ("Customize"
19919 ["Browse Org Group" org-customize t]
19920 "--"
19921 ["Expand This Menu" org-create-customize-menu
19922 (fboundp 'customize-menu-create)])
19923 ["Send bug report" org-submit-bug-report t]
19924 "--"
19925 ("Refresh/Reload"
19926 ["Refresh setup current buffer" org-mode-restart t]
19927 ["Reload Org (after update)" org-reload t]
19928 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19931 (defun org-info (&optional node)
19932 "Read documentation for Org-mode in the info system.
19933 With optional NODE, go directly to that node."
19934 (interactive)
19935 (info (format "(org)%s" (or node ""))))
19937 ;;;###autoload
19938 (defun org-submit-bug-report ()
19939 "Submit a bug report on Org-mode via mail.
19941 Don't hesitate to report any problems or inaccurate documentation.
19943 If you don't have setup sending mail from (X)Emacs, please copy the
19944 output buffer into your mail program, as it gives us important
19945 information about your Org-mode version and configuration."
19946 (interactive)
19947 (require 'reporter)
19948 (org-load-modules-maybe)
19949 (org-require-autoloaded-modules)
19950 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19951 (reporter-submit-bug-report
19952 "emacs-orgmode@gnu.org"
19953 (org-version nil 'full)
19954 (let (list)
19955 (save-window-excursion
19956 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19957 (delete-other-windows)
19958 (erase-buffer)
19959 (insert "You are about to submit a bug report to the Org-mode mailing list.
19961 We would like to add your full Org-mode and Outline configuration to the
19962 bug report. This greatly simplifies the work of the maintainer and
19963 other experts on the mailing list.
19965 HOWEVER, some variables you have customized may contain private
19966 information. The names of customers, colleagues, or friends, might
19967 appear in the form of file names, tags, todo states, or search strings.
19968 If you answer yes to the prompt, you might want to check and remove
19969 such private information before sending the email.")
19970 (add-text-properties (point-min) (point-max) '(face org-warning))
19971 (when (yes-or-no-p "Include your Org-mode configuration ")
19972 (mapatoms
19973 (lambda (v)
19974 (and (boundp v)
19975 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19976 (or (and (symbol-value v)
19977 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19978 (and
19979 (get v 'custom-type) (get v 'standard-value)
19980 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19981 (push v list)))))
19982 (kill-buffer (get-buffer "*Warn about privacy*"))
19983 list))
19984 nil nil
19985 "Remember to cover the basics, that is, what you expected to happen and
19986 what in fact did happen. You don't know how to make a good report? See
19988 http://orgmode.org/manual/Feedback.html#Feedback
19990 Your bug report will be posted to the Org-mode mailing list.
19991 ------------------------------------------------------------------------")
19992 (save-excursion
19993 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19994 (replace-match "\\1Bug: \\3 [\\2]")))))
19997 (defun org-install-agenda-files-menu ()
19998 (let ((bl (buffer-list)))
19999 (save-excursion
20000 (while bl
20001 (set-buffer (pop bl))
20002 (if (derived-mode-p 'org-mode) (setq bl nil)))
20003 (when (derived-mode-p 'org-mode)
20004 (easy-menu-change
20005 '("Org") "File List for Agenda"
20006 (append
20007 (list
20008 ["Edit File List" (org-edit-agenda-file-list) t]
20009 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20010 ["Remove Current File from List" org-remove-file t]
20011 ["Cycle through agenda files" org-cycle-agenda-files t]
20012 ["Occur in all agenda files" org-occur-in-agenda-files t]
20013 "--")
20014 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20016 ;;;; Documentation
20018 (defun org-require-autoloaded-modules ()
20019 (interactive)
20020 (mapc 'require
20021 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20022 org-docbook org-exp org-html org-icalendar
20023 org-id org-latex
20024 org-publish org-remember org-table
20025 org-timer org-xoxo)))
20027 ;;;###autoload
20028 (defun org-reload (&optional uncompiled)
20029 "Reload all org lisp files.
20030 With prefix arg UNCOMPILED, load the uncompiled versions."
20031 (interactive "P")
20032 (require 'loadhist)
20033 (let* ((org-dir (org-find-library-dir "org"))
20034 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20035 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20036 (remove-re (mapconcat 'identity
20037 (mapcar (lambda (f) (concat "^" f "$"))
20038 (list (if (featurep 'xemacs)
20039 "org-colview"
20040 "org-colview-xemacs")
20041 "org" "org-loaddefs" "org-version"))
20042 "\\|"))
20043 (feats (delete-dups
20044 (mapcar 'file-name-sans-extension
20045 (mapcar 'file-name-nondirectory
20046 (delq nil
20047 (mapcar 'feature-file
20048 features))))))
20049 (lfeat (append
20050 (sort
20051 (setq feats
20052 (delq nil (mapcar
20053 (lambda (f)
20054 (if (and (string-match feature-re f)
20055 (not (string-match remove-re f)))
20056 f nil))
20057 feats)))
20058 'string-lessp)
20059 (list "org-version" "org")))
20060 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20061 load-uncore load-misses)
20062 (setq load-misses
20063 (delq 't
20064 (mapcar (lambda (f)
20065 (or (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20066 (and (string= org-dir contrib-dir)
20067 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20068 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20069 (add-to-list 'load-uncore f 'append)
20072 lfeat)))
20073 (if load-uncore
20074 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20075 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20076 (if load-misses
20077 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20078 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20079 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20081 ;;;###autoload
20082 (defun org-customize ()
20083 "Call the customize function with org as argument."
20084 (interactive)
20085 (org-load-modules-maybe)
20086 (org-require-autoloaded-modules)
20087 (customize-browse 'org))
20089 (defun org-create-customize-menu ()
20090 "Create a full customization menu for Org-mode, insert it into the menu."
20091 (interactive)
20092 (org-load-modules-maybe)
20093 (org-require-autoloaded-modules)
20094 (if (fboundp 'customize-menu-create)
20095 (progn
20096 (easy-menu-change
20097 '("Org") "Customize"
20098 `(["Browse Org group" org-customize t]
20099 "--"
20100 ,(customize-menu-create 'org)
20101 ["Set" Custom-set t]
20102 ["Save" Custom-save t]
20103 ["Reset to Current" Custom-reset-current t]
20104 ["Reset to Saved" Custom-reset-saved t]
20105 ["Reset to Standard Settings" Custom-reset-standard t]))
20106 (message "\"Org\"-menu now contains full customization menu"))
20107 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20109 ;;;; Miscellaneous stuff
20111 ;;; Generally useful functions
20113 (defun org-get-at-bol (property)
20114 "Get text property PROPERTY at beginning of line."
20115 (get-text-property (point-at-bol) property))
20117 (defun org-find-text-property-in-string (prop s)
20118 "Return the first non-nil value of property PROP in string S."
20119 (or (get-text-property 0 prop s)
20120 (get-text-property (or (next-single-property-change 0 prop s) 0)
20121 prop s)))
20123 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20124 "Display the given MESSAGE as a warning."
20125 (if (fboundp 'display-warning)
20126 (display-warning 'org message
20127 (if (featurep 'xemacs) 'warning :warning))
20128 (let ((buf (get-buffer-create "*Org warnings*")))
20129 (with-current-buffer buf
20130 (goto-char (point-max))
20131 (insert "Warning (Org): " message)
20132 (unless (bolp)
20133 (newline)))
20134 (display-buffer buf)
20135 (sit-for 0))))
20137 (defun org-eval (form)
20138 "Eval FORM and return result."
20139 (condition-case error
20140 (eval form)
20141 (error (format "%%![Error: %s]" error))))
20143 (defun org-in-clocktable-p ()
20144 "Check if the cursor is in a clocktable."
20145 (let ((pos (point)) start)
20146 (save-excursion
20147 (end-of-line 1)
20148 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20149 (setq start (match-beginning 0))
20150 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20151 (>= (match-end 0) pos)
20152 start))))
20154 (defun org-in-commented-line ()
20155 "Is point in a line starting with `#'?"
20156 (equal (char-after (point-at-bol)) ?#))
20158 (defun org-in-indented-comment-line ()
20159 "Is point in a line starting with `#' after some white space?"
20160 (save-excursion
20161 (save-match-data
20162 (goto-char (point-at-bol))
20163 (looking-at "[ \t]*#"))))
20165 (defun org-in-verbatim-emphasis ()
20166 (save-match-data
20167 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20169 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20170 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20171 (if (and marker (marker-buffer marker)
20172 (buffer-live-p (marker-buffer marker)))
20173 (progn
20174 (org-pop-to-buffer-same-window (marker-buffer marker))
20175 (if (or (> marker (point-max)) (< marker (point-min)))
20176 (widen))
20177 (goto-char marker)
20178 (org-show-context 'org-goto))
20179 (if bookmark
20180 (bookmark-jump bookmark)
20181 (error "Cannot find location"))))
20183 (defun org-quote-csv-field (s)
20184 "Quote field for inclusion in CSV material."
20185 (if (string-match "[\",]" s)
20186 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20189 (defun org-force-self-insert (N)
20190 "Needed to enforce self-insert under remapping."
20191 (interactive "p")
20192 (self-insert-command N))
20194 (defun org-string-width (s)
20195 "Compute width of string, ignoring invisible characters.
20196 This ignores character with invisibility property `org-link', and also
20197 characters with property `org-cwidth', because these will become invisible
20198 upon the next fontification round."
20199 (let (b l)
20200 (when (or (eq t buffer-invisibility-spec)
20201 (assq 'org-link buffer-invisibility-spec))
20202 (while (setq b (text-property-any 0 (length s)
20203 'invisible 'org-link s))
20204 (setq s (concat (substring s 0 b)
20205 (substring s (or (next-single-property-change
20206 b 'invisible s) (length s)))))))
20207 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20208 (setq s (concat (substring s 0 b)
20209 (substring s (or (next-single-property-change
20210 b 'org-cwidth s) (length s))))))
20211 (setq l (string-width s) b -1)
20212 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20213 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20216 (defun org-shorten-string (s maxlength)
20217 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20218 If the string is shorter or has length MAXLENGTH, just return the
20219 original string. If it is longer, the functions finds a space in the
20220 string, breaks this string off at that locations and adds three dots
20221 as ellipsis. Including the ellipsis, the string will not be longer
20222 than MAXLENGTH. If finding a good breaking point in the string does
20223 not work, the string is just chopped off in the middle of a word
20224 if necessary."
20225 (if (<= (length s) maxlength)
20227 (let* ((n (max (- maxlength 4) 1))
20228 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20229 (if (string-match re s)
20230 (concat (match-string 1 s) "...")
20231 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20233 (defun org-get-indentation (&optional line)
20234 "Get the indentation of the current line, interpreting tabs.
20235 When LINE is given, assume it represents a line and compute its indentation."
20236 (if line
20237 (if (string-match "^ *" (org-remove-tabs line))
20238 (match-end 0))
20239 (save-excursion
20240 (beginning-of-line 1)
20241 (skip-chars-forward " \t")
20242 (current-column))))
20244 (defun org-get-string-indentation (s)
20245 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20246 (let ((n -1) (i 0) (w tab-width) c)
20247 (catch 'exit
20248 (while (< (setq n (1+ n)) (length s))
20249 (setq c (aref s n))
20250 (cond ((= c ?\ ) (setq i (1+ i)))
20251 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20252 (t (throw 'exit t)))))
20255 (defun org-remove-tabs (s &optional width)
20256 "Replace tabulators in S with spaces.
20257 Assumes that s is a single line, starting in column 0."
20258 (setq width (or width tab-width))
20259 (while (string-match "\t" s)
20260 (setq s (replace-match
20261 (make-string
20262 (- (* width (/ (+ (match-beginning 0) width) width))
20263 (match-beginning 0)) ?\ )
20264 t t s)))
20267 (defun org-fix-indentation (line ind)
20268 "Fix indentation in LINE.
20269 IND is a cons cell with target and minimum indentation.
20270 If the current indentation in LINE is smaller than the minimum,
20271 leave it alone. If it is larger than ind, set it to the target."
20272 (let* ((l (org-remove-tabs line))
20273 (i (org-get-indentation l))
20274 (i1 (car ind)) (i2 (cdr ind)))
20275 (if (>= i i2) (setq l (substring line i2)))
20276 (if (> i1 0)
20277 (concat (make-string i1 ?\ ) l)
20278 l)))
20280 (defun org-remove-indentation (code &optional n)
20281 "Remove the maximum common indentation from the lines in CODE.
20282 N may optionally be the number of spaces to remove."
20283 (with-temp-buffer
20284 (insert code)
20285 (org-do-remove-indentation n)
20286 (buffer-string)))
20288 (defun org-do-remove-indentation (&optional n)
20289 "Remove the maximum common indentation from the buffer."
20290 (untabify (point-min) (point-max))
20291 (let ((min 10000) re)
20292 (if n
20293 (setq min n)
20294 (goto-char (point-min))
20295 (while (re-search-forward "^ *[^ \n]" nil t)
20296 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20297 (unless (or (= min 0) (= min 10000))
20298 (setq re (format "^ \\{%d\\}" min))
20299 (goto-char (point-min))
20300 (while (re-search-forward re nil t)
20301 (replace-match "")
20302 (end-of-line 1))
20303 min)))
20305 (defun org-fill-template (template alist)
20306 "Find each %key of ALIST in TEMPLATE and replace it."
20307 (let ((case-fold-search nil)
20308 entry key value)
20309 (setq alist (sort (copy-sequence alist)
20310 (lambda (a b) (< (length (car a)) (length (car b))))))
20311 (while (setq entry (pop alist))
20312 (setq template
20313 (replace-regexp-in-string
20314 (concat "%" (regexp-quote (car entry)))
20315 (or (cdr entry) "") template t t)))
20316 template))
20318 (defun org-base-buffer (buffer)
20319 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20320 (if (not buffer)
20321 buffer
20322 (or (buffer-base-buffer buffer)
20323 buffer)))
20325 (defun org-trim (s)
20326 "Remove whitespace at beginning and end of string."
20327 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20328 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20331 (defun org-wrap (string &optional width lines)
20332 "Wrap string to either a number of lines, or a width in characters.
20333 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20334 that costs. If there is a word longer than WIDTH, the text is actually
20335 wrapped to the length of that word.
20336 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20337 many lines, whatever width that takes.
20338 The return value is a list of lines, without newlines at the end."
20339 (let* ((words (org-split-string string "[ \t\n]+"))
20340 (maxword (apply 'max (mapcar 'org-string-width words)))
20341 w ll)
20342 (cond (width
20343 (org-do-wrap words (max maxword width)))
20344 (lines
20345 (setq w maxword)
20346 (setq ll (org-do-wrap words maxword))
20347 (if (<= (length ll) lines)
20349 (setq ll words)
20350 (while (> (length ll) lines)
20351 (setq w (1+ w))
20352 (setq ll (org-do-wrap words w)))
20353 ll))
20354 (t (error "Cannot wrap this")))))
20356 (defun org-do-wrap (words width)
20357 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20358 (let (lines line)
20359 (while words
20360 (setq line (pop words))
20361 (while (and words (< (+ (length line) (length (car words))) width))
20362 (setq line (concat line " " (pop words))))
20363 (setq lines (push line lines)))
20364 (nreverse lines)))
20366 (defun org-split-string (string &optional separators)
20367 "Splits STRING into substrings at SEPARATORS.
20368 No empty strings are returned if there are matches at the beginning
20369 and end of string."
20370 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20371 (start 0)
20372 notfirst
20373 (list nil))
20374 (while (and (string-match rexp string
20375 (if (and notfirst
20376 (= start (match-beginning 0))
20377 (< start (length string)))
20378 (1+ start) start))
20379 (< (match-beginning 0) (length string)))
20380 (setq notfirst t)
20381 (or (eq (match-beginning 0) 0)
20382 (and (eq (match-beginning 0) (match-end 0))
20383 (eq (match-beginning 0) start))
20384 (setq list
20385 (cons (substring string start (match-beginning 0))
20386 list)))
20387 (setq start (match-end 0)))
20388 (or (eq start (length string))
20389 (setq list
20390 (cons (substring string start)
20391 list)))
20392 (nreverse list)))
20394 (defun org-quote-vert (s)
20395 "Replace \"|\" with \"\\vert\"."
20396 (while (string-match "|" s)
20397 (setq s (replace-match "\\vert" t t s)))
20400 (defun org-uuidgen-p (s)
20401 "Is S an ID created by UUIDGEN?"
20402 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20404 (defun org-in-src-block-p nil
20405 "Whether point is in a code source block."
20406 (let (ov)
20407 (when (setq ov (overlays-at (point)))
20408 (memq 'org-block-background
20409 (overlay-properties
20410 (car ov))))))
20412 (defun org-context ()
20413 "Return a list of contexts of the current cursor position.
20414 If several contexts apply, all are returned.
20415 Each context entry is a list with a symbol naming the context, and
20416 two positions indicating start and end of the context. Possible
20417 contexts are:
20419 :headline anywhere in a headline
20420 :headline-stars on the leading stars in a headline
20421 :todo-keyword on a TODO keyword (including DONE) in a headline
20422 :tags on the TAGS in a headline
20423 :priority on the priority cookie in a headline
20424 :item on the first line of a plain list item
20425 :item-bullet on the bullet/number of a plain list item
20426 :checkbox on the checkbox in a plain list item
20427 :table in an org-mode table
20428 :table-special on a special filed in a table
20429 :table-table in a table.el table
20430 :clocktable in a clocktable
20431 :src-block in a source block
20432 :link on a hyperlink
20433 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20434 :target on a <<target>>
20435 :radio-target on a <<<radio-target>>>
20436 :latex-fragment on a LaTeX fragment
20437 :latex-preview on a LaTeX fragment with overlaid preview image
20439 This function expects the position to be visible because it uses font-lock
20440 faces as a help to recognize the following contexts: :table-special, :link,
20441 and :keyword."
20442 (let* ((f (get-text-property (point) 'face))
20443 (faces (if (listp f) f (list f)))
20444 (case-fold-search t)
20445 (p (point)) clist o)
20446 ;; First the large context
20447 (cond
20448 ((org-at-heading-p t)
20449 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20450 (when (progn
20451 (beginning-of-line 1)
20452 (looking-at org-todo-line-tags-regexp))
20453 (push (org-point-in-group p 1 :headline-stars) clist)
20454 (push (org-point-in-group p 2 :todo-keyword) clist)
20455 (push (org-point-in-group p 4 :tags) clist))
20456 (goto-char p)
20457 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20458 (if (looking-at "\\[#[A-Z0-9]\\]")
20459 (push (org-point-in-group p 0 :priority) clist)))
20461 ((org-at-item-p)
20462 (push (org-point-in-group p 2 :item-bullet) clist)
20463 (push (list :item (point-at-bol)
20464 (save-excursion (org-end-of-item) (point)))
20465 clist)
20466 (and (org-at-item-checkbox-p)
20467 (push (org-point-in-group p 0 :checkbox) clist)))
20469 ((org-at-table-p)
20470 (push (list :table (org-table-begin) (org-table-end)) clist)
20471 (if (memq 'org-formula faces)
20472 (push (list :table-special
20473 (previous-single-property-change p 'face)
20474 (next-single-property-change p 'face)) clist)))
20475 ((org-at-table-p 'any)
20476 (push (list :table-table) clist)))
20477 (goto-char p)
20479 (let ((case-fold-search t))
20480 ;; New the "medium" contexts: clocktables, source blocks
20481 (cond ((org-in-clocktable-p)
20482 (push (list :clocktable
20483 (and (or (looking-at "#\\+BEGIN: clocktable")
20484 (search-backward "#+BEGIN: clocktable" nil t))
20485 (match-beginning 0))
20486 (and (re-search-forward "#\\+END:?" nil t)
20487 (match-end 0))) clist))
20488 ((org-in-src-block-p)
20489 (push (list :src-block
20490 (and (or (looking-at "#\\+BEGIN_SRC")
20491 (search-backward "#+BEGIN_SRC" nil t))
20492 (match-beginning 0))
20493 (and (search-forward "#+END_SRC" nil t)
20494 (match-beginning 0))) clist))))
20495 (goto-char p)
20497 ;; Now the small context
20498 (cond
20499 ((org-at-timestamp-p)
20500 (push (org-point-in-group p 0 :timestamp) clist))
20501 ((memq 'org-link faces)
20502 (push (list :link
20503 (previous-single-property-change p 'face)
20504 (next-single-property-change p 'face)) clist))
20505 ((memq 'org-special-keyword faces)
20506 (push (list :keyword
20507 (previous-single-property-change p 'face)
20508 (next-single-property-change p 'face)) clist))
20509 ((org-at-target-p)
20510 (push (org-point-in-group p 0 :target) clist)
20511 (goto-char (1- (match-beginning 0)))
20512 (if (looking-at org-radio-target-regexp)
20513 (push (org-point-in-group p 0 :radio-target) clist))
20514 (goto-char p))
20515 ((setq o (car (delq nil
20516 (mapcar
20517 (lambda (x)
20518 (if (memq x org-latex-fragment-image-overlays) x))
20519 (overlays-at (point))))))
20520 (push (list :latex-fragment
20521 (overlay-start o) (overlay-end o)) clist)
20522 (push (list :latex-preview
20523 (overlay-start o) (overlay-end o)) clist))
20524 ((org-inside-LaTeX-fragment-p)
20525 ;; FIXME: positions wrong.
20526 (push (list :latex-fragment (point) (point)) clist)))
20528 (setq clist (nreverse (delq nil clist)))
20529 clist))
20531 ;; FIXME: Compare with at-regexp-p Do we need both?
20532 (defun org-in-regexp (re &optional nlines visually)
20533 "Check if point is inside a match of regexp.
20534 Normally only the current line is checked, but you can include NLINES extra
20535 lines both before and after point into the search.
20536 If VISUALLY is set, require that the cursor is not after the match but
20537 really on, so that the block visually is on the match."
20538 (catch 'exit
20539 (let ((pos (point))
20540 (eol (point-at-eol (+ 1 (or nlines 0))))
20541 (inc (if visually 1 0)))
20542 (save-excursion
20543 (beginning-of-line (- 1 (or nlines 0)))
20544 (while (re-search-forward re eol t)
20545 (if (and (<= (match-beginning 0) pos)
20546 (>= (+ inc (match-end 0)) pos))
20547 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20549 (defun org-at-regexp-p (regexp)
20550 "Is point inside a match of REGEXP in the current line?"
20551 (catch 'exit
20552 (save-excursion
20553 (let ((pos (point)) (end (point-at-eol)))
20554 (beginning-of-line 1)
20555 (while (re-search-forward regexp end t)
20556 (if (and (<= (match-beginning 0) pos)
20557 (>= (match-end 0) pos))
20558 (throw 'exit t)))
20559 nil))))
20561 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20562 "Non-nil when point is between matches of START-RE and END-RE.
20564 Also return a non-nil value when point is on one of the matches.
20566 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20567 buffer positions. Default values are the positions of headlines
20568 surrounding the point.
20570 The functions returns a cons cell whose car (resp. cdr) is the
20571 position before START-RE (resp. after END-RE)."
20572 (save-match-data
20573 (let ((pos (point))
20574 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20575 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20576 beg end)
20577 (save-excursion
20578 ;; Point is on a block when on START-RE or if START-RE can be
20579 ;; found before it...
20580 (and (or (org-at-regexp-p start-re)
20581 (re-search-backward start-re limit-up t))
20582 (setq beg (match-beginning 0))
20583 ;; ... and END-RE after it...
20584 (goto-char (match-end 0))
20585 (re-search-forward end-re limit-down t)
20586 (> (setq end (match-end 0)) pos)
20587 ;; ... without another START-RE in-between.
20588 (goto-char (match-beginning 0))
20589 (not (re-search-backward start-re (1+ beg) t))
20590 ;; Return value.
20591 (cons beg end))))))
20593 (defun org-in-block-p (names)
20594 "Non-nil when point belongs to a block whose name belongs to NAMES.
20596 NAMES is a list of strings containing names of blocks.
20598 Return first block name matched, or nil. Beware that in case of
20599 nested blocks, the returned name may not belong to the closest
20600 block from point."
20601 (save-match-data
20602 (catch 'exit
20603 (let ((case-fold-search t)
20604 (lim-up (save-excursion (outline-previous-heading)))
20605 (lim-down (save-excursion (outline-next-heading))))
20606 (mapc (lambda (name)
20607 (let ((n (regexp-quote name)))
20608 (when (org-between-regexps-p
20609 (concat "^[ \t]*#\\+begin_" n)
20610 (concat "^[ \t]*#\\+end_" n)
20611 lim-up lim-down)
20612 (throw 'exit n))))
20613 names))
20614 nil)))
20616 (defun org-occur-in-agenda-files (regexp &optional nlines)
20617 "Call `multi-occur' with buffers for all agenda files."
20618 (interactive "sOrg-files matching: \np")
20619 (let* ((files (org-agenda-files))
20620 (tnames (mapcar 'file-truename files))
20621 (extra org-agenda-text-search-extra-files)
20623 (when (eq (car extra) 'agenda-archives)
20624 (setq extra (cdr extra))
20625 (setq files (org-add-archive-files files)))
20626 (while (setq f (pop extra))
20627 (unless (member (file-truename f) tnames)
20628 (add-to-list 'files f 'append)
20629 (add-to-list 'tnames (file-truename f) 'append)))
20630 (multi-occur
20631 (mapcar (lambda (x)
20632 (with-current-buffer
20633 (or (get-file-buffer x) (find-file-noselect x))
20634 (widen)
20635 (current-buffer)))
20636 files)
20637 regexp)))
20639 (if (boundp 'occur-mode-find-occurrence-hook)
20640 ;; Emacs 23
20641 (add-hook 'occur-mode-find-occurrence-hook
20642 (lambda ()
20643 (when (derived-mode-p 'org-mode)
20644 (org-reveal))))
20645 ;; Emacs 22
20646 (defadvice occur-mode-goto-occurrence
20647 (after org-occur-reveal activate)
20648 (and (derived-mode-p 'org-mode) (org-reveal)))
20649 (defadvice occur-mode-goto-occurrence-other-window
20650 (after org-occur-reveal activate)
20651 (and (derived-mode-p 'org-mode) (org-reveal)))
20652 (defadvice occur-mode-display-occurrence
20653 (after org-occur-reveal activate)
20654 (when (derived-mode-p 'org-mode)
20655 (let ((pos (occur-mode-find-occurrence)))
20656 (with-current-buffer (marker-buffer pos)
20657 (save-excursion
20658 (goto-char pos)
20659 (org-reveal)))))))
20661 (defun org-occur-link-in-agenda-files ()
20662 "Create a link and search for it in the agendas.
20663 The link is not stored in `org-stored-links', it is just created
20664 for the search purpose."
20665 (interactive)
20666 (let ((link (condition-case nil
20667 (org-store-link nil)
20668 (error "Unable to create a link to here"))))
20669 (org-occur-in-agenda-files (regexp-quote link))))
20671 (defun org-uniquify (list)
20672 "Remove duplicate elements from LIST."
20673 (let (res)
20674 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20675 res))
20677 (defun org-delete-all (elts list)
20678 "Remove all elements in ELTS from LIST."
20679 (while elts
20680 (setq list (delete (pop elts) list)))
20681 list)
20683 (defun org-count (cl-item cl-seq)
20684 "Count the number of occurrences of ITEM in SEQ.
20685 Taken from `count' in cl-seq.el with all keyword arguments removed."
20686 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20687 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20688 (while (< cl-start cl-end)
20689 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20690 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20691 (setq cl-start (1+ cl-start)))
20692 cl-count))
20694 (defun org-remove-if (predicate seq)
20695 "Remove everything from SEQ that fulfills PREDICATE."
20696 (let (res e)
20697 (while seq
20698 (setq e (pop seq))
20699 (if (not (funcall predicate e)) (push e res)))
20700 (nreverse res)))
20702 (defun org-remove-if-not (predicate seq)
20703 "Remove everything from SEQ that does not fulfill PREDICATE."
20704 (let (res e)
20705 (while seq
20706 (setq e (pop seq))
20707 (if (funcall predicate e) (push e res)))
20708 (nreverse res)))
20710 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20711 "Reduce two-argument FUNCTION across SEQ.
20712 Taken from `reduce' in cl-seq.el with all keyword arguments but
20713 \":initial-value\" removed."
20714 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20715 (cadr (memq :initial-value cl-keys)))
20716 (cl-seq (pop cl-seq))
20717 (t (funcall cl-func)))))
20718 (while cl-seq
20719 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20720 cl-accum))
20722 (defun org-back-over-empty-lines ()
20723 "Move backwards over whitespace, to the beginning of the first empty line.
20724 Returns the number of empty lines passed."
20725 (let ((pos (point)))
20726 (if (cdr (assoc 'heading org-blank-before-new-entry))
20727 (skip-chars-backward " \t\n\r")
20728 (unless (eobp)
20729 (forward-line -1)))
20730 (beginning-of-line 2)
20731 (goto-char (min (point) pos))
20732 (count-lines (point) pos)))
20734 (defun org-skip-whitespace ()
20735 (skip-chars-forward " \t\n\r"))
20737 (defun org-point-in-group (point group &optional context)
20738 "Check if POINT is in match-group GROUP.
20739 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20740 match. If the match group does not exist or point is not inside it,
20741 return nil."
20742 (and (match-beginning group)
20743 (>= point (match-beginning group))
20744 (<= point (match-end group))
20745 (if context
20746 (list context (match-beginning group) (match-end group))
20747 t)))
20749 (defun org-switch-to-buffer-other-window (&rest args)
20750 "Switch to buffer in a second window on the current frame.
20751 In particular, do not allow pop-up frames.
20752 Returns the newly created buffer."
20753 (let (pop-up-frames special-display-buffer-names special-display-regexps
20754 special-display-function)
20755 (apply 'switch-to-buffer-other-window args)))
20757 (defun org-combine-plists (&rest plists)
20758 "Create a single property list from all plists in PLISTS.
20759 The process starts by copying the first list, and then setting properties
20760 from the other lists. Settings in the last list are the most significant
20761 ones and overrule settings in the other lists."
20762 (let ((rtn (copy-sequence (pop plists)))
20763 p v ls)
20764 (while plists
20765 (setq ls (pop plists))
20766 (while ls
20767 (setq p (pop ls) v (pop ls))
20768 (setq rtn (plist-put rtn p v))))
20769 rtn))
20771 (defun org-replace-escapes (string table)
20772 "Replace %-escapes in STRING with values in TABLE.
20773 TABLE is an association list with keys like \"%a\" and string values.
20774 The sequences in STRING may contain normal field width and padding information,
20775 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20776 so values can contain further %-escapes if they are define later in TABLE."
20777 (let ((tbl (copy-alist table))
20778 (case-fold-search nil)
20779 (pchg 0)
20780 e re rpl)
20781 (while (setq e (pop tbl))
20782 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20783 (when (and (cdr e) (string-match re (cdr e)))
20784 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20785 (safe "SREF"))
20786 (add-text-properties 0 3 (list 'sref sref) safe)
20787 (setcdr e (replace-match safe t t (cdr e)))))
20788 (while (string-match re string)
20789 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20790 (cdr e)))
20791 (setq string (replace-match rpl t t string))))
20792 (while (setq pchg (next-property-change pchg string))
20793 (let ((sref (get-text-property pchg 'sref string)))
20794 (when (and sref (string-match "SREF" string pchg))
20795 (setq string (replace-match sref t t string)))))
20796 string))
20798 (defun org-sublist (list start end)
20799 "Return a section of LIST, from START to END.
20800 Counting starts at 1."
20801 (let (rtn (c start))
20802 (setq list (nthcdr (1- start) list))
20803 (while (and list (<= c end))
20804 (push (pop list) rtn)
20805 (setq c (1+ c)))
20806 (nreverse rtn)))
20808 (defun org-find-base-buffer-visiting (file)
20809 "Like `find-buffer-visiting' but always return the base buffer and
20810 not an indirect buffer."
20811 (let ((buf (or (get-file-buffer file)
20812 (find-buffer-visiting file))))
20813 (if buf
20814 (or (buffer-base-buffer buf) buf)
20815 nil)))
20817 (defun org-image-file-name-regexp (&optional extensions)
20818 "Return regexp matching the file names of images.
20819 If EXTENSIONS is given, only match these."
20820 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20821 (image-file-name-regexp)
20822 (let ((image-file-name-extensions
20823 (or extensions
20824 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20825 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20826 (concat "\\."
20827 (regexp-opt (nconc (mapcar 'upcase
20828 image-file-name-extensions)
20829 image-file-name-extensions)
20831 "\\'"))))
20833 (defun org-file-image-p (file &optional extensions)
20834 "Return non-nil if FILE is an image."
20835 (save-match-data
20836 (string-match (org-image-file-name-regexp extensions) file)))
20838 (defun org-get-cursor-date ()
20839 "Return the date at cursor in as a time.
20840 This works in the calendar and in the agenda, anywhere else it just
20841 returns the current time."
20842 (let (date day defd)
20843 (cond
20844 ((eq major-mode 'calendar-mode)
20845 (setq date (calendar-cursor-to-date)
20846 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20847 ((eq major-mode 'org-agenda-mode)
20848 (setq day (get-text-property (point) 'day))
20849 (if day
20850 (setq date (calendar-gregorian-from-absolute day)
20851 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20852 (nth 2 date))))))
20853 (or defd (current-time))))
20855 (defun org-mark-subtree (&optional up)
20856 "Mark the current subtree.
20857 This puts point at the start of the current subtree, and mark at
20858 the end. If a numeric prefix UP is given, move up into the
20859 hierarchy of headlines by UP levels before marking the subtree."
20860 (interactive "P")
20861 (org-with-limited-levels
20862 (cond ((org-at-heading-p) (beginning-of-line))
20863 ((org-before-first-heading-p) (error "Not in a subtree"))
20864 (t (outline-previous-visible-heading 1))))
20865 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20866 (if (org-called-interactively-p 'any)
20867 (call-interactively 'org-mark-element)
20868 (org-mark-element)))
20871 ;;; Macros
20873 ;; Macros are expanded with `org-macro-replace-all', which relies
20874 ;; internally on `org-macro-expand'.
20876 ;; Default templates for expansion are stored in the buffer-local
20877 ;; variable `org-macro-templates'. This variable is updated by
20878 ;; `org-macro-initialize-templates'.
20880 ;; Along with macros defined through #+MACRO: keyword, default
20881 ;; templates include the following hard-coded macros:
20882 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
20883 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
20885 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
20886 ;; {{{title}}} will also be provided.
20889 (defvar org-macro-templates nil
20890 "Alist containing all macro templates in current buffer.
20891 Associations are in the shape of (NAME . TEMPLATE) where NAME
20892 stands for macro's name and template for its replacement value,
20893 both as strings. This is an internal variable. Do not set it
20894 directly, use instead:
20896 #+MACRO: name template")
20897 (make-variable-buffer-local 'org-macro-templates)
20899 (defun org-macro-expand (macro templates)
20900 "Return expanded MACRO, as a string.
20901 MACRO is an object, obtained, for example, with
20902 `org-element-context'. TEMPLATES is an alist of templates used
20903 for expansion. See `org-macro-templates' for a buffer-local
20904 default value. Return nil if no template was found."
20905 (let ((template
20906 ;; Macro names are case-insensitive.
20907 (cdr (assoc-string (org-element-property :key macro) templates t))))
20908 (when template
20909 (let ((value (replace-regexp-in-string
20910 "\\$[0-9]+"
20911 (lambda (arg)
20912 (or (nth (1- (string-to-number (substring arg 1)))
20913 (org-element-property :args macro))
20914 ;; No argument provided: remove
20915 ;; place-holder.
20916 ""))
20917 template)))
20918 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
20919 (when (string-match "\\`(eval\\>" value)
20920 (setq value (eval (read value))))
20921 ;; Return string.
20922 (format "%s" (or value ""))))))
20924 (defun org-macro-replace-all (templates)
20925 "Replace all macros in current buffer by their expansion.
20926 TEMPLATES is an alist of templates used for expansion. See
20927 `org-macro-templates' for a buffer-local default value."
20928 (save-excursion
20929 (goto-char (point-min))
20930 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
20931 (let ((object (org-element-context)))
20932 (when (eq (org-element-type object) 'macro)
20933 (let ((value (org-macro-expand object templates)))
20934 (when value
20935 (delete-region
20936 (org-element-property :begin object)
20937 ;; Preserve white spaces after the macro.
20938 (progn (goto-char (org-element-property :end object))
20939 (skip-chars-backward " \t")
20940 (point)))
20941 ;; Leave point before replacement in case of recursive
20942 ;; expansions.
20943 (save-excursion (insert value)))))))))
20945 (defun org-macro-initialize-templates ()
20946 "Collect macro templates defined in current buffer.
20947 Templates are stored in buffer-local variable
20948 `org-macro-templates'. In addition to buffer-defined macros, the
20949 function installs the following ones: \"property\", \"date\",
20950 \"time\". and, if appropriate, \"input-file\" and
20951 \"modification-time\"."
20952 (let ((case-fold-search t)
20953 (set-template
20954 (lambda (cell)
20955 ;; Add CELL to `org-macro-templates' if there's no
20956 ;; association matching its name already. Otherwise,
20957 ;; replace old association with the new one in that
20958 ;; variable.
20959 (let ((old-template (assoc (car cell) org-macro-templates)))
20960 (if old-template (setcdr old-template (cdr cell))
20961 (push cell org-macro-templates))))))
20962 ;; Install buffer-local macros.
20963 (org-with-wide-buffer
20964 (goto-char (point-min))
20965 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
20966 (let ((element (org-element-at-point)))
20967 (when (eq (org-element-type element) 'keyword)
20968 (let ((value (org-element-property :value element)))
20969 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
20970 (funcall set-template
20971 (cons (match-string 1 value)
20972 (or (match-string 2 value) "")))))))))
20973 ;; Install hard-coded macros.
20974 (mapc (lambda (cell) (funcall set-template cell))
20975 (list
20976 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
20977 (cons "time" "(eval (format-time-string \"$1\"))")))
20978 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
20979 (when (and visited-file (file-exists-p visited-file))
20980 (mapc (lambda (cell) (funcall set-template cell))
20981 (list
20982 (cons "input-file" (file-name-nondirectory visited-file))
20983 (cons "modification-time"
20984 (format "(eval (format-time-string \"$1\" '%s))"
20985 (prin1-to-string
20986 (nth 5 (file-attributes visited-file)))))))))))
20989 ;;; Indentation
20991 (defun org-indent-line ()
20992 "Indent line depending on context."
20993 (interactive)
20994 (let* ((pos (point))
20995 (itemp (org-at-item-p))
20996 (case-fold-search t)
20997 (org-drawer-regexp (or org-drawer-regexp "\000"))
20998 (inline-task-p (and (featurep 'org-inlinetask)
20999 (org-inlinetask-in-task-p)))
21000 (inline-re (and inline-task-p
21001 (org-inlinetask-outline-regexp)))
21002 column)
21003 (if (and orgstruct-is-++ (eq pos (point)))
21004 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21005 (indent-according-to-mode))
21006 (beginning-of-line 1)
21007 (cond
21008 ;; Headings
21009 ((looking-at org-outline-regexp) (setq column 0))
21010 ;; Included files
21011 ((looking-at "#\\+include:") (setq column 0))
21012 ;; Footnote definition
21013 ((looking-at org-footnote-definition-re) (setq column 0))
21014 ;; Literal examples
21015 ((looking-at "[ \t]*:\\( \\|$\\)")
21016 (setq column (org-get-indentation))) ; do nothing
21017 ;; Lists
21018 ((ignore-errors (goto-char (org-in-item-p)))
21019 (setq column (if itemp
21020 (org-get-indentation)
21021 (org-list-item-body-column (point))))
21022 (goto-char pos))
21023 ;; Drawers
21024 ((and (looking-at "[ \t]*:END:")
21025 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21026 (save-excursion
21027 (goto-char (1- (match-beginning 1)))
21028 (setq column (current-column))))
21029 ;; Special blocks
21030 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21031 (save-excursion
21032 (re-search-backward
21033 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21034 (setq column (org-get-indentation (match-string 0))))
21035 ((and (not (looking-at "[ \t]*#\\+begin_"))
21036 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21037 (save-excursion
21038 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21039 (setq column
21040 (cond ((equal (downcase (match-string 1)) "src")
21041 ;; src blocks: let `org-edit-src-exit' handle them
21042 (org-get-indentation))
21043 ((equal (downcase (match-string 1)) "example")
21044 (max (org-get-indentation)
21045 (org-get-indentation (match-string 0))))
21047 (org-get-indentation (match-string 0))))))
21048 ;; This line has nothing special, look at the previous relevant
21049 ;; line to compute indentation
21051 (beginning-of-line 0)
21052 (while (and (not (bobp))
21053 (not (looking-at org-drawer-regexp))
21054 ;; When point started in an inline task, do not move
21055 ;; above task starting line.
21056 (not (and inline-task-p (looking-at inline-re)))
21057 ;; Skip drawers, blocks, empty lines, verbatim,
21058 ;; comments, tables, footnotes definitions, lists,
21059 ;; inline tasks.
21060 (or (and (looking-at "[ \t]*:END:")
21061 (re-search-backward org-drawer-regexp nil t))
21062 (and (looking-at "[ \t]*#\\+end_")
21063 (re-search-backward "[ \t]*#\\+begin_"nil t))
21064 (looking-at "[ \t]*[\n:#|]")
21065 (looking-at org-footnote-definition-re)
21066 (and (ignore-errors (goto-char (org-in-item-p)))
21067 (goto-char
21068 (org-list-get-top-point (org-list-struct))))
21069 (and (not inline-task-p)
21070 (featurep 'org-inlinetask)
21071 (org-inlinetask-in-task-p)
21072 (or (org-inlinetask-goto-beginning) t))))
21073 (beginning-of-line 0))
21074 (cond
21075 ;; There was an heading above.
21076 ((looking-at "\\*+[ \t]+")
21077 (if (not org-adapt-indentation)
21078 (setq column 0)
21079 (goto-char (match-end 0))
21080 (setq column (current-column))))
21081 ;; A drawer had started and is unfinished
21082 ((looking-at org-drawer-regexp)
21083 (goto-char (1- (match-beginning 1)))
21084 (setq column (current-column)))
21085 ;; Else, nothing noticeable found: get indentation and go on.
21086 (t (setq column (org-get-indentation))))))
21087 ;; Now apply indentation and move cursor accordingly
21088 (goto-char pos)
21089 (if (<= (current-column) (current-indentation))
21090 (org-indent-line-to column)
21091 (save-excursion (org-indent-line-to column)))
21092 ;; Special polishing for properties, see `org-property-format'
21093 (setq column (current-column))
21094 (beginning-of-line 1)
21095 (if (looking-at
21096 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21097 (replace-match (concat (match-string 1)
21098 (format org-property-format
21099 (match-string 2) (match-string 3)))
21100 t t))
21101 (org-move-to-column column))))
21103 (defun org-indent-drawer ()
21104 "Indent the drawer at point."
21105 (interactive)
21106 (let ((p (point))
21107 (e (and (save-excursion (re-search-forward ":END:" nil t))
21108 (match-end 0)))
21109 (folded
21110 (save-excursion
21111 (end-of-line)
21112 (when (overlays-at (point))
21113 (member 'invisible (overlay-properties
21114 (car (overlays-at (point)))))))))
21115 (when folded (org-cycle))
21116 (indent-for-tab-command)
21117 (while (and (move-beginning-of-line 2) (< (point) e))
21118 (indent-for-tab-command))
21119 (goto-char p)
21120 (when folded (org-cycle)))
21121 (message "Drawer at point indented"))
21123 (defun org-indent-block ()
21124 "Indent the block at point."
21125 (interactive)
21126 (let ((p (point))
21127 (case-fold-search t)
21128 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21129 (match-end 0)))
21130 (folded
21131 (save-excursion
21132 (end-of-line)
21133 (when (overlays-at (point))
21134 (member 'invisible (overlay-properties
21135 (car (overlays-at (point)))))))))
21136 (when folded (org-cycle))
21137 (indent-for-tab-command)
21138 (while (and (move-beginning-of-line 2) (< (point) e))
21139 (indent-for-tab-command))
21140 (goto-char p)
21141 (when folded (org-cycle)))
21142 (message "Block at point indented"))
21144 (defun org-indent-region (start end)
21145 "Indent region."
21146 (interactive "r")
21147 (save-excursion
21148 (let ((line-end (org-current-line end)))
21149 (goto-char start)
21150 (while (< (org-current-line) line-end)
21151 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21152 (t (call-interactively 'org-indent-line)))
21153 (move-beginning-of-line 2)))))
21156 ;;; Filling
21158 ;; We use our own fill-paragraph and auto-fill functions.
21160 ;; `org-fill-paragraph' relies on adaptive filling and context
21161 ;; checking. Appropriate `fill-prefix' is computed with
21162 ;; `org-adaptive-fill-function'.
21164 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21165 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21166 ;; `org-adaptive-fill-function' value. Internally,
21167 ;; `org-comment-line-break-function' breaks the line.
21169 ;; `org-setup-filling' installs filling and auto-filling related
21170 ;; variables during `org-mode' initialization.
21172 (defun org-setup-filling ()
21173 (interactive)
21174 ;; Prevent auto-fill from inserting unwanted new items.
21175 (when (boundp 'fill-nobreak-predicate)
21176 (org-set-local
21177 'fill-nobreak-predicate
21178 (org-uniquify
21179 (append fill-nobreak-predicate
21180 '(org-fill-paragraph-separate-nobreak-p
21181 org-fill-line-break-nobreak-p)))))
21182 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21183 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21184 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21185 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21187 (defvar org-element-paragraph-separate) ; org-element.el
21188 (defun org-fill-paragraph-separate-nobreak-p ()
21189 "Non-nil when a line break at point would insert a new item."
21190 (looking-at (substring org-element-paragraph-separate 1)))
21192 (defun org-fill-line-break-nobreak-p ()
21193 "Non-nil when a line break at point would create an Org line break."
21194 (save-excursion
21195 (skip-chars-backward "[ \t]")
21196 (skip-chars-backward "\\\\")
21197 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21199 (declare-function message-in-body-p "message" ())
21200 (defun org-adaptive-fill-function ()
21201 "Compute a fill prefix for the current line.
21202 Return fill prefix, as a string, or nil if current line isn't
21203 meant to be filled."
21204 (org-with-wide-buffer
21205 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21206 ;; FIXME: This is really the job of orgstruct++-mode
21207 (let* ((p (line-beginning-position))
21208 (element (save-excursion (beginning-of-line)
21209 (org-element-at-point)))
21210 (type (org-element-type element))
21211 (post-affiliated (org-element-property :post-affiliated element)))
21212 (unless (< p post-affiliated)
21213 (case type
21214 (comment (looking-at "[ \t]*# ?") (match-string 0))
21215 (footnote-definition "")
21216 ((item plain-list)
21217 (make-string (org-list-item-body-column post-affiliated) ? ))
21218 (paragraph
21219 ;; Fill prefix is usually the same as the current line,
21220 ;; except if the paragraph is at the beginning of an item.
21221 (let ((parent (org-element-property :parent element)))
21222 (cond ((eq (org-element-type parent) 'item)
21223 (make-string (org-list-item-body-column
21224 (org-element-property :begin parent))
21225 ? ))
21226 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21227 (match-string 0))
21228 (t ""))))
21229 (comment-block
21230 ;; Only fill contents if P is within block boundaries.
21231 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21232 (forward-line)
21233 (point)))
21234 (cend (save-excursion
21235 (goto-char (org-element-property :end element))
21236 (skip-chars-backward " \r\t\n")
21237 (line-beginning-position))))
21238 (when (and (>= p cbeg) (< p cend))
21239 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21240 (match-string 0)
21241 ""))))))))))
21243 (declare-function message-goto-body "message" ())
21244 (defvar message-cite-prefix-regexp) ; From message.el
21245 (defvar org-element-all-objects) ; From org-element.el
21246 (defun org-fill-paragraph (&optional justify)
21247 "Fill element at point, when applicable.
21249 This function only applies to comment blocks, comments, example
21250 blocks and paragraphs. Also, as a special case, re-align table
21251 when point is at one.
21253 If JUSTIFY is non-nil (interactively, with prefix argument),
21254 justify as well. If `sentence-end-double-space' is non-nil, then
21255 period followed by one space does not end a sentence, so don't
21256 break a line there. The variable `fill-column' controls the
21257 width for filling.
21259 For convenience, when point is at a plain list, an item or
21260 a footnote definition, try to fill the first paragraph within."
21261 ;; Falls back on message-fill-paragraph when necessary
21262 (interactive)
21263 (if (and (derived-mode-p 'message-mode)
21264 (or (not (message-in-body-p))
21265 (save-excursion (move-beginning-of-line 1)
21266 (looking-at message-cite-prefix-regexp))))
21267 (let ((fill-paragraph-function
21268 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21269 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21270 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21271 (paragraph-separate
21272 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21273 (fill-paragraph nil))
21274 (save-excursion
21275 ;; Move to end of line in order to get the first paragraph
21276 ;; within a plain list or a footnote definition.
21277 (end-of-line)
21278 (let ((element (org-element-at-point)))
21279 ;; First check if point is in a blank line at the beginning of
21280 ;; the buffer. In that case, ignore filling.
21281 (if (< (point) (org-element-property :begin element)) t
21282 (case (org-element-type element)
21283 ;; Align Org tables, leave table.el tables as-is.
21284 (table-row (org-table-align) t)
21285 (table
21286 (when (eq (org-element-property :type element) 'org)
21287 (org-table-align))
21289 (paragraph
21290 ;; Paragraphs may contain `line-break' type objects.
21291 (let ((beg (max (point-min)
21292 (org-element-property :contents-begin element)))
21293 (end (min (point-max)
21294 (org-element-property :contents-end element))))
21295 ;; Do nothing if point is at an affiliated keyword.
21296 (if (< (point) beg) t
21297 (when (derived-mode-p 'message-mode)
21298 ;; In `message-mode', do not fill following
21299 ;; citation in current paragraph nor text before
21300 ;; message body.
21301 (let ((body-start (save-excursion (message-goto-body))))
21302 (when body-start (setq beg (max body-start beg))))
21303 (when (save-excursion
21304 (re-search-forward
21305 (concat "^" message-cite-prefix-regexp) end t))
21306 (setq end (match-beginning 0))))
21307 ;; Fill paragraph, taking line breaks into
21308 ;; consideration. For that, slice the paragraph
21309 ;; using line breaks as separators, and fill the
21310 ;; parts in reverse order to avoid messing with
21311 ;; markers.
21312 (save-excursion
21313 (goto-char end)
21314 (mapc
21315 (lambda (pos)
21316 (fill-region-as-paragraph pos (point) justify)
21317 (goto-char pos))
21318 ;; Find the list of ending positions for line
21319 ;; breaks in the current paragraph. Add paragraph
21320 ;; beginning to include first slice.
21321 (nreverse
21322 (cons
21324 (org-element-map
21325 (org-element--parse-objects
21326 beg end nil org-element-all-objects)
21327 'line-break
21328 (lambda (lb) (org-element-property :end lb)))))))
21329 t)))
21330 ;; Contents of `comment-block' type elements should be
21331 ;; filled as plain text, but only if point is within block
21332 ;; markers.
21333 (comment-block
21334 (let* ((case-fold-search t)
21335 (beg (save-excursion
21336 (goto-char (org-element-property :begin element))
21337 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21338 (forward-line)
21339 (point)))
21340 (end (save-excursion
21341 (goto-char (org-element-property :end element))
21342 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21343 (line-beginning-position))))
21344 (when (and (>= (point) beg) (< (point) end))
21345 (fill-region-as-paragraph
21346 (save-excursion
21347 (end-of-line)
21348 (re-search-backward "^[ \t]*$" beg 'move)
21349 (line-beginning-position))
21350 (save-excursion
21351 (beginning-of-line)
21352 (re-search-forward "^[ \t]*$" end 'move)
21353 (line-beginning-position))
21354 justify)))
21356 ;; Fill comments.
21357 (comment (fill-comment-paragraph justify))
21358 ;; Ignore every other element.
21359 (otherwise t)))))))
21361 (defun org-auto-fill-function ()
21362 "Auto-fill function."
21363 ;; Check if auto-filling is meaningful.
21364 (let ((fc (current-fill-column)))
21365 (when (and fc (> (current-column) fc))
21366 (let* ((fill-prefix (org-adaptive-fill-function))
21367 ;; Enforce empty fill prefix, if required. Otherwise, it
21368 ;; will be computed again.
21369 (adaptive-fill-mode (not (equal fill-prefix ""))))
21370 (when fill-prefix (do-auto-fill))))))
21372 (defun org-comment-line-break-function (&optional soft)
21373 "Break line at point and indent, continuing comment if within one.
21374 The inserted newline is marked hard if variable
21375 `use-hard-newlines' is true, unless optional argument SOFT is
21376 non-nil."
21377 (if soft (insert-and-inherit ?\n) (newline 1))
21378 (save-excursion (forward-char -1) (delete-horizontal-space))
21379 (delete-horizontal-space)
21380 (indent-to-left-margin)
21381 (insert-before-markers-and-inherit fill-prefix))
21384 ;;; Comments
21386 ;; Org comments syntax is quite complex. It requires the entire line
21387 ;; to be just a comment. Also, even with the right syntax at the
21388 ;; beginning of line, some some elements (i.e. verse-block or
21389 ;; example-block) don't accept comments. Usual Emacs comment commands
21390 ;; cannot cope with those requirements. Therefore, Org replaces them.
21392 ;; Org still relies on `comment-dwim', but cannot trust
21393 ;; `comment-only-p'. So, `comment-region-function' and
21394 ;; `uncomment-region-function' both point
21395 ;; to`org-comment-or-uncomment-region'. Eventually,
21396 ;; `org-insert-comment' takes care of insertion of comments at the
21397 ;; beginning of line.
21399 ;; `org-setup-comments-handling' install comments related variables
21400 ;; during `org-mode' initialization.
21402 (defun org-setup-comments-handling ()
21403 (interactive)
21404 (org-set-local 'comment-use-syntax nil)
21405 (org-set-local 'comment-start "# ")
21406 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21407 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21408 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21409 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21411 (defun org-insert-comment ()
21412 "Insert an empty comment above current line.
21413 If the line is empty, insert comment at its beginning."
21414 (beginning-of-line)
21415 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21416 (org-indent-line)
21417 (insert "# "))
21419 (defvar comment-empty-lines) ; From newcomment.el.
21420 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21421 "Comment or uncomment each non-blank line in the region.
21422 Uncomment each non-blank line between BEG and END if it only
21423 contains commented lines. Otherwise, comment them."
21424 (save-restriction
21425 ;; Restrict region
21426 (narrow-to-region (save-excursion (goto-char beg)
21427 (skip-chars-forward " \r\t\n" end)
21428 (line-beginning-position))
21429 (save-excursion (goto-char end)
21430 (skip-chars-backward " \r\t\n" beg)
21431 (line-end-position)))
21432 (let ((uncommentp
21433 ;; UNCOMMENTP is non-nil when every non blank line between
21434 ;; BEG and END is a comment.
21435 (save-excursion
21436 (goto-char (point-min))
21437 (while (and (not (eobp))
21438 (let ((element (org-element-at-point)))
21439 (and (eq (org-element-type element) 'comment)
21440 (goto-char (min (point-max)
21441 (org-element-property
21442 :end element)))))))
21443 (eobp))))
21444 (if uncommentp
21445 ;; Only blank lines and comments in region: uncomment it.
21446 (save-excursion
21447 (goto-char (point-min))
21448 (while (not (eobp))
21449 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21450 (replace-match "" nil nil nil 1))
21451 (forward-line)))
21452 ;; Comment each line in region.
21453 (let ((min-indent (point-max)))
21454 ;; First find the minimum indentation across all lines.
21455 (save-excursion
21456 (goto-char (point-min))
21457 (while (and (not (eobp)) (not (zerop min-indent)))
21458 (unless (looking-at "[ \t]*$")
21459 (setq min-indent (min min-indent (current-indentation))))
21460 (forward-line)))
21461 ;; Then loop over all lines.
21462 (save-excursion
21463 (goto-char (point-min))
21464 (while (not (eobp))
21465 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21466 (org-move-to-column min-indent t)
21467 (insert comment-start))
21468 (forward-line))))))))
21471 ;;; Other stuff.
21473 (defun org-toggle-fixed-width-section (arg)
21474 "Toggle the fixed-width export.
21475 If there is no active region, the QUOTE keyword at the current headline is
21476 inserted or removed. When present, it causes the text between this headline
21477 and the next to be exported as fixed-width text, and unmodified.
21478 If there is an active region, this command adds or removes a colon as the
21479 first character of this line. If the first character of a line is a colon,
21480 this line is also exported in fixed-width font."
21481 (interactive "P")
21482 (let* ((cc 0)
21483 (regionp (org-region-active-p))
21484 (beg (if regionp (region-beginning) (point)))
21485 (end (if regionp (region-end)))
21486 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21487 (case-fold-search nil)
21488 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21489 off)
21490 (if regionp
21491 (save-excursion
21492 (goto-char beg)
21493 (setq cc (current-column))
21494 (beginning-of-line 1)
21495 (setq off (looking-at re))
21496 (while (> nlines 0)
21497 (setq nlines (1- nlines))
21498 (beginning-of-line 1)
21499 (cond
21500 (arg
21501 (org-move-to-column cc t)
21502 (insert ": \n")
21503 (forward-line -1))
21504 ((and off (looking-at re))
21505 (replace-match "" t t nil 1))
21506 ((not off) (org-move-to-column cc t) (insert ": ")))
21507 (forward-line 1)))
21508 (save-excursion
21509 (org-back-to-heading)
21510 (cond
21511 ((looking-at (format org-heading-keyword-regexp-format
21512 org-quote-string))
21513 (goto-char (match-end 1))
21514 (looking-at (concat " +" org-quote-string))
21515 (replace-match "" t t)
21516 (when (eolp) (insert " ")))
21517 ((looking-at org-outline-regexp)
21518 (goto-char (match-end 0))
21519 (insert org-quote-string " ")))))))
21521 (defun org-reftex-citation ()
21522 "Use reftex-citation to insert a citation into the buffer.
21523 This looks for a line like
21525 #+BIBLIOGRAPHY: foo plain option:-d
21527 and derives from it that foo.bib is the bibliography file relevant
21528 for this document. It then installs the necessary environment for RefTeX
21529 to work in this buffer and calls `reftex-citation' to insert a citation
21530 into the buffer.
21532 Export of such citations to both LaTeX and HTML is handled by the contributed
21533 package org-exp-bibtex by Taru Karttunen."
21534 (interactive)
21535 (let ((reftex-docstruct-symbol 'rds)
21536 (reftex-cite-format "\\cite{%l}")
21537 rds bib)
21538 (save-excursion
21539 (save-restriction
21540 (widen)
21541 (let ((case-fold-search t)
21542 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21543 (if (not (save-excursion
21544 (or (re-search-forward re nil t)
21545 (re-search-backward re nil t))))
21546 (error "No bibliography defined in file")
21547 (setq bib (concat (match-string 1) ".bib")
21548 rds (list (list 'bib bib)))))))
21549 (call-interactively 'reftex-citation)))
21551 ;;;; Functions extending outline functionality
21553 (defun org-beginning-of-line (&optional arg)
21554 "Go to the beginning of the current line. If that is invisible, continue
21555 to a visible line beginning. This makes the function of C-a more intuitive.
21556 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21557 first attempt, and only move to after the tags when the cursor is already
21558 beyond the end of the headline."
21559 (interactive "P")
21560 (let ((pos (point))
21561 (special (if (consp org-special-ctrl-a/e)
21562 (car org-special-ctrl-a/e)
21563 org-special-ctrl-a/e))
21564 refpos)
21565 (if (org-bound-and-true-p line-move-visual)
21566 (beginning-of-visual-line 1)
21567 (beginning-of-line 1))
21568 (if (and arg (fboundp 'move-beginning-of-line))
21569 (call-interactively 'move-beginning-of-line)
21570 (if (bobp)
21572 (backward-char 1)
21573 (if (org-truely-invisible-p)
21574 (while (and (not (bobp)) (org-truely-invisible-p))
21575 (backward-char 1)
21576 (beginning-of-line 1))
21577 (forward-char 1))))
21578 (when special
21579 (cond
21580 ((and (looking-at org-complex-heading-regexp)
21581 (= (char-after (match-end 1)) ?\ ))
21582 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21583 (point-at-eol)))
21584 (goto-char
21585 (if (eq special t)
21586 (cond ((> pos refpos) refpos)
21587 ((= pos (point)) refpos)
21588 (t (point)))
21589 (cond ((> pos (point)) (point))
21590 ((not (eq last-command this-command)) (point))
21591 (t refpos)))))
21592 ((org-at-item-p)
21593 ;; Being at an item and not looking at an the item means point
21594 ;; was previously moved to beginning of a visual line, which
21595 ;; doesn't contain the item. Therefore, do nothing special,
21596 ;; just stay here.
21597 (when (looking-at org-list-full-item-re)
21598 ;; Set special position at first white space character after
21599 ;; bullet, and check-box, if any.
21600 (let ((after-bullet
21601 (let ((box (match-end 3)))
21602 (if (not box) (match-end 1)
21603 (let ((after (char-after box)))
21604 (if (and after (= after ? )) (1+ box) box))))))
21605 ;; Special case: Move point to special position when
21606 ;; currently after it or at beginning of line.
21607 (if (eq special t)
21608 (when (or (> pos after-bullet) (= (point) pos))
21609 (goto-char after-bullet))
21610 ;; Reversed case: Move point to special position when
21611 ;; point was already at beginning of line and command is
21612 ;; repeated.
21613 (when (and (= (point) pos) (eq last-command this-command))
21614 (goto-char after-bullet))))))))
21615 (org-no-warnings
21616 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21618 (defun org-end-of-line (&optional arg)
21619 "Go to the end of the line.
21620 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21621 tags on the first attempt, and only move to after the tags when
21622 the cursor is already beyond the end of the headline."
21623 (interactive "P")
21624 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21625 org-special-ctrl-a/e))
21626 (type (org-element-type
21627 (save-excursion (beginning-of-line) (org-element-at-point)))))
21628 (cond
21629 ((or (not special) arg)
21630 (call-interactively
21631 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line)))
21632 ((memq type '(headline inlinetask))
21633 (let ((pos (point)))
21634 (beginning-of-line 1)
21635 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21636 (if (eq special t)
21637 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21638 (goto-char (match-beginning 1))
21639 (goto-char (match-end 0)))
21640 (if (or (< pos (match-end 0))
21641 (not (eq this-command last-command)))
21642 (goto-char (match-end 0))
21643 (goto-char (match-beginning 1))))
21644 (call-interactively
21645 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line)))))
21646 ((memq type
21647 '(center-block comment-block drawer dynamic-block example-block
21648 export-block item plain-list property-drawer
21649 quote-block special-block src-block verse-block))
21650 ;; Never move past the ellipsis.
21651 (or (eolp) (move-end-of-line 1))
21652 (when (org-invisible-p2) (backward-char)))
21654 (call-interactively
21655 (if (fboundp 'move-end-of-line) 'move-end-of-line 'end-of-line))))
21656 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21658 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21659 (define-key org-mode-map "\C-e" 'org-end-of-line)
21661 (defun org-backward-sentence (&optional arg)
21662 "Go to beginning of sentence, or beginning of table field.
21663 This will call `backward-sentence' or `org-table-beginning-of-field',
21664 depending on context."
21665 (interactive "P")
21666 (cond
21667 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21668 (t (call-interactively 'backward-sentence))))
21670 (defun org-forward-sentence (&optional arg)
21671 "Go to end of sentence, or end of table field.
21672 This will call `forward-sentence' or `org-table-end-of-field',
21673 depending on context."
21674 (interactive "P")
21675 (cond
21676 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21677 (t (call-interactively 'forward-sentence))))
21679 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21680 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21682 (defun org-kill-line (&optional arg)
21683 "Kill line, to tags or end of line."
21684 (interactive "P")
21685 (cond
21686 ((or (not org-special-ctrl-k)
21687 (bolp)
21688 (not (org-at-heading-p)))
21689 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21690 org-ctrl-k-protect-subtree)
21691 (if (or (eq org-ctrl-k-protect-subtree 'error)
21692 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21693 (error "C-k aborted - would kill hidden subtree")))
21694 (call-interactively
21695 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21696 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21697 (kill-region (point) (match-beginning 1))
21698 (org-set-tags nil t))
21699 (t (kill-region (point) (point-at-eol)))))
21701 (define-key org-mode-map "\C-k" 'org-kill-line)
21703 (defun org-yank (&optional arg)
21704 "Yank. If the kill is a subtree, treat it specially.
21705 This command will look at the current kill and check if is a single
21706 subtree, or a series of subtrees[1]. If it passes the test, and if the
21707 cursor is at the beginning of a line or after the stars of a currently
21708 empty headline, then the yank is handled specially. How exactly depends
21709 on the value of the following variables, both set by default.
21711 org-yank-folded-subtrees
21712 When set, the subtree(s) will be folded after insertion, but only
21713 if doing so would now swallow text after the yanked text.
21715 org-yank-adjusted-subtrees
21716 When set, the subtree will be promoted or demoted in order to
21717 fit into the local outline tree structure, which means that the level
21718 will be adjusted so that it becomes the smaller one of the two
21719 *visible* surrounding headings.
21721 Any prefix to this command will cause `yank' to be called directly with
21722 no special treatment. In particular, a simple \\[universal-argument] prefix \
21723 will just
21724 plainly yank the text as it is.
21726 \[1] The test checks if the first non-white line is a heading
21727 and if there are no other headings with fewer stars."
21728 (interactive "P")
21729 (org-yank-generic 'yank arg))
21731 (defun org-yank-generic (command arg)
21732 "Perform some yank-like command.
21734 This function implements the behavior described in the `org-yank'
21735 documentation. However, it has been generalized to work for any
21736 interactive command with similar behavior."
21738 ;; pretend to be command COMMAND
21739 (setq this-command command)
21741 (if arg
21742 (call-interactively command)
21744 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21745 (and (org-kill-is-subtree-p)
21746 (or (bolp)
21747 (and (looking-at "[ \t]*$")
21748 (string-match
21749 "\\`\\*+\\'"
21750 (buffer-substring (point-at-bol) (point)))))))
21751 swallowp)
21752 (cond
21753 ((and subtreep org-yank-folded-subtrees)
21754 (let ((beg (point))
21755 end)
21756 (if (and subtreep org-yank-adjusted-subtrees)
21757 (org-paste-subtree nil nil 'for-yank)
21758 (call-interactively command))
21760 (setq end (point))
21761 (goto-char beg)
21762 (when (and (bolp) subtreep
21763 (not (setq swallowp
21764 (org-yank-folding-would-swallow-text beg end))))
21765 (org-with-limited-levels
21766 (or (looking-at org-outline-regexp)
21767 (re-search-forward org-outline-regexp-bol end t))
21768 (while (and (< (point) end) (looking-at org-outline-regexp))
21769 (hide-subtree)
21770 (org-cycle-show-empty-lines 'folded)
21771 (condition-case nil
21772 (outline-forward-same-level 1)
21773 (error (goto-char end))))))
21774 (when swallowp
21775 (message
21776 "Inserted text not folded because that would swallow text"))
21778 (goto-char end)
21779 (skip-chars-forward " \t\n\r")
21780 (beginning-of-line 1)
21781 (push-mark beg 'nomsg)))
21782 ((and subtreep org-yank-adjusted-subtrees)
21783 (let ((beg (point-at-bol)))
21784 (org-paste-subtree nil nil 'for-yank)
21785 (push-mark beg 'nomsg)))
21787 (call-interactively command))))))
21789 (defun org-yank-folding-would-swallow-text (beg end)
21790 "Would hide-subtree at BEG swallow any text after END?"
21791 (let (level)
21792 (org-with-limited-levels
21793 (save-excursion
21794 (goto-char beg)
21795 (when (or (looking-at org-outline-regexp)
21796 (re-search-forward org-outline-regexp-bol end t))
21797 (setq level (org-outline-level)))
21798 (goto-char end)
21799 (skip-chars-forward " \t\r\n\v\f")
21800 (if (or (eobp)
21801 (and (bolp) (looking-at org-outline-regexp)
21802 (<= (org-outline-level) level)))
21803 nil ; Nothing would be swallowed
21804 t))))) ; something would swallow
21806 (define-key org-mode-map "\C-y" 'org-yank)
21808 (defun org-truely-invisible-p ()
21809 "Check if point is at a character currently not visible.
21810 This version does not only check the character property, but also
21811 `visible-mode'."
21812 ;; Early versions of noutline don't have `outline-invisible-p'.
21813 (if (org-bound-and-true-p visible-mode)
21815 (outline-invisible-p)))
21817 (defun org-invisible-p2 ()
21818 "Check if point is at a character currently not visible."
21819 (save-excursion
21820 (if (and (eolp) (not (bobp))) (backward-char 1))
21821 ;; Early versions of noutline don't have `outline-invisible-p'.
21822 (outline-invisible-p)))
21824 (defun org-back-to-heading (&optional invisible-ok)
21825 "Call `outline-back-to-heading', but provide a better error message."
21826 (condition-case nil
21827 (outline-back-to-heading invisible-ok)
21828 (error (error "Before first headline at position %d in buffer %s"
21829 (point) (current-buffer)))))
21831 (defun org-before-first-heading-p ()
21832 "Before first heading?"
21833 (save-excursion
21834 (end-of-line)
21835 (null (re-search-backward org-outline-regexp-bol nil t))))
21837 (defun org-at-heading-p (&optional ignored)
21838 (outline-on-heading-p t))
21839 ;; Compatibility alias with Org versions < 7.8.03
21840 (defalias 'org-on-heading-p 'org-at-heading-p)
21842 (defun org-at-comment-p nil
21843 "Is cursor in a line starting with a # character?"
21844 (save-excursion
21845 (beginning-of-line)
21846 (looking-at "^#")))
21848 (defun org-at-drawer-p nil
21849 "Is cursor at a drawer keyword?"
21850 (save-excursion
21851 (move-beginning-of-line 1)
21852 (looking-at org-drawer-regexp)))
21854 (defun org-at-block-p nil
21855 "Is cursor at a block keyword?"
21856 (save-excursion
21857 (move-beginning-of-line 1)
21858 (looking-at org-block-regexp)))
21860 (defun org-point-at-end-of-empty-headline ()
21861 "If point is at the end of an empty headline, return t, else nil.
21862 If the heading only contains a TODO keyword, it is still still considered
21863 empty."
21864 (and (looking-at "[ \t]*$")
21865 (when org-todo-line-regexp
21866 (save-excursion
21867 (beginning-of-line 1)
21868 (let ((case-fold-search nil))
21869 (looking-at org-todo-line-regexp)
21870 (string= (match-string 3) ""))))))
21872 (defun org-at-heading-or-item-p ()
21873 (or (org-at-heading-p) (org-at-item-p)))
21875 (defun org-at-target-p ()
21876 (or (org-in-regexp org-radio-target-regexp)
21877 (org-in-regexp org-target-regexp)))
21878 ;; Compatibility alias with Org versions < 7.8.03
21879 (defalias 'org-on-target-p 'org-at-target-p)
21881 (defun org-up-heading-all (arg)
21882 "Move to the heading line of which the present line is a subheading.
21883 This function considers both visible and invisible heading lines.
21884 With argument, move up ARG levels."
21885 (if (fboundp 'outline-up-heading-all)
21886 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21887 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21889 (defun org-up-heading-safe ()
21890 "Move to the heading line of which the present line is a subheading.
21891 This version will not throw an error. It will return the level of the
21892 headline found, or nil if no higher level is found.
21894 Also, this function will be a lot faster than `outline-up-heading',
21895 because it relies on stars being the outline starters. This can really
21896 make a significant difference in outlines with very many siblings."
21897 (let (start-level re)
21898 (org-back-to-heading t)
21899 (setq start-level (funcall outline-level))
21900 (if (equal start-level 1)
21902 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21903 (if (re-search-backward re nil t)
21904 (funcall outline-level)))))
21906 (defun org-first-sibling-p ()
21907 "Is this heading the first child of its parents?"
21908 (interactive)
21909 (let ((re org-outline-regexp-bol)
21910 level l)
21911 (unless (org-at-heading-p t)
21912 (error "Not at a heading"))
21913 (setq level (funcall outline-level))
21914 (save-excursion
21915 (if (not (re-search-backward re nil t))
21917 (setq l (funcall outline-level))
21918 (< l level)))))
21920 (defun org-goto-sibling (&optional previous)
21921 "Goto the next sibling, even if it is invisible.
21922 When PREVIOUS is set, go to the previous sibling instead. Returns t
21923 when a sibling was found. When none is found, return nil and don't
21924 move point."
21925 (let ((fun (if previous 're-search-backward 're-search-forward))
21926 (pos (point))
21927 (re org-outline-regexp-bol)
21928 level l)
21929 (when (condition-case nil (org-back-to-heading t) (error nil))
21930 (setq level (funcall outline-level))
21931 (catch 'exit
21932 (or previous (forward-char 1))
21933 (while (funcall fun re nil t)
21934 (setq l (funcall outline-level))
21935 (when (< l level) (goto-char pos) (throw 'exit nil))
21936 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21937 (goto-char pos)
21938 nil))))
21940 (defun org-show-siblings ()
21941 "Show all siblings of the current headline."
21942 (save-excursion
21943 (while (org-goto-sibling) (org-flag-heading nil)))
21944 (save-excursion
21945 (while (org-goto-sibling 'previous)
21946 (org-flag-heading nil))))
21948 (defun org-goto-first-child ()
21949 "Goto the first child, even if it is invisible.
21950 Return t when a child was found. Otherwise don't move point and
21951 return nil."
21952 (let (level (pos (point)) (re org-outline-regexp-bol))
21953 (when (condition-case nil (org-back-to-heading t) (error nil))
21954 (setq level (outline-level))
21955 (forward-char 1)
21956 (if (and (re-search-forward re nil t) (> (outline-level) level))
21957 (progn (goto-char (match-beginning 0)) t)
21958 (goto-char pos) nil))))
21960 (defun org-show-hidden-entry ()
21961 "Show an entry where even the heading is hidden."
21962 (save-excursion
21963 (org-show-entry)))
21965 (defun org-flag-heading (flag &optional entry)
21966 "Flag the current heading. FLAG non-nil means make invisible.
21967 When ENTRY is non-nil, show the entire entry."
21968 (save-excursion
21969 (org-back-to-heading t)
21970 ;; Check if we should show the entire entry
21971 (if entry
21972 (progn
21973 (org-show-entry)
21974 (save-excursion
21975 (and (outline-next-heading)
21976 (org-flag-heading nil))))
21977 (outline-flag-region (max (point-min) (1- (point)))
21978 (save-excursion (outline-end-of-heading) (point))
21979 flag))))
21981 (defun org-get-next-sibling ()
21982 "Move to next heading of the same level, and return point.
21983 If there is no such heading, return nil.
21984 This is like outline-next-sibling, but invisible headings are ok."
21985 (let ((level (funcall outline-level)))
21986 (outline-next-heading)
21987 (while (and (not (eobp)) (> (funcall outline-level) level))
21988 (outline-next-heading))
21989 (if (or (eobp) (< (funcall outline-level) level))
21991 (point))))
21993 (defun org-get-last-sibling ()
21994 "Move to previous heading of the same level, and return point.
21995 If there is no such heading, return nil."
21996 (let ((opoint (point))
21997 (level (funcall outline-level)))
21998 (outline-previous-heading)
21999 (when (and (/= (point) opoint) (outline-on-heading-p t))
22000 (while (and (> (funcall outline-level) level)
22001 (not (bobp)))
22002 (outline-previous-heading))
22003 (if (< (funcall outline-level) level)
22005 (point)))))
22007 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22008 "Goto to the end of a subtree."
22009 ;; This contains an exact copy of the original function, but it uses
22010 ;; `org-back-to-heading', to make it work also in invisible
22011 ;; trees. And is uses an invisible-ok argument.
22012 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22013 ;; Furthermore, when used inside Org, finding the end of a large subtree
22014 ;; with many children and grandchildren etc, this can be much faster
22015 ;; than the outline version.
22016 (org-back-to-heading invisible-ok)
22017 (let ((first t)
22018 (level (funcall outline-level)))
22019 (if (and (derived-mode-p 'org-mode) (< level 1000))
22020 ;; A true heading (not a plain list item), in Org-mode
22021 ;; This means we can easily find the end by looking
22022 ;; only for the right number of stars. Using a regexp to do
22023 ;; this is so much faster than using a Lisp loop.
22024 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22025 (forward-char 1)
22026 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22027 ;; something else, do it the slow way
22028 (while (and (not (eobp))
22029 (or first (> (funcall outline-level) level)))
22030 (setq first nil)
22031 (outline-next-heading)))
22032 (unless to-heading
22033 (if (memq (preceding-char) '(?\n ?\^M))
22034 (progn
22035 ;; Go to end of line before heading
22036 (forward-char -1)
22037 (if (memq (preceding-char) '(?\n ?\^M))
22038 ;; leave blank line before heading
22039 (forward-char -1))))))
22040 (point))
22042 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22043 "Use Org version in org-mode, for dramatic speed-up."
22044 (if (derived-mode-p 'org-mode)
22045 (progn
22046 (org-end-of-subtree nil t)
22047 (unless (eobp) (backward-char 1)))
22048 ad-do-it))
22050 (defun org-end-of-meta-data-and-drawers ()
22051 "Jump to the first text after meta data and drawers in the current entry.
22052 This will move over empty lines, lines with planning time stamps,
22053 clocking lines, and drawers."
22054 (org-back-to-heading t)
22055 (let ((end (save-excursion (outline-next-heading) (point)))
22056 (re (concat "\\(" org-drawer-regexp "\\)"
22057 "\\|" "[ \t]*" org-keyword-time-regexp)))
22058 (forward-line 1)
22059 (while (re-search-forward re end t)
22060 (if (not (match-end 1))
22061 ;; empty or planning line
22062 (forward-line 1)
22063 ;; a drawer, find the end
22064 (re-search-forward "^[ \t]*:END:" end 'move)
22065 (forward-line 1)))
22066 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22067 (point)))
22069 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22070 "Move forward to the arg'th subheading at same level as this one.
22071 Stop at the first and last subheadings of a superior heading.
22072 Normally this only looks at visible headings, but when INVISIBLE-OK is
22073 non-nil it will also look at invisible ones."
22074 (interactive "p")
22075 (org-back-to-heading invisible-ok)
22076 (org-at-heading-p)
22077 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22078 (re (format "^\\*\\{1,%d\\} " level))
22080 (forward-char 1)
22081 (while (> arg 0)
22082 (while (and (re-search-forward re nil 'move)
22083 (setq l (- (match-end 0) (match-beginning 0) 1))
22084 (= l level)
22085 (not invisible-ok)
22086 (progn (backward-char 1) (outline-invisible-p)))
22087 (if (< l level) (setq arg 1)))
22088 (setq arg (1- arg)))
22089 (beginning-of-line 1)))
22091 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22092 "Move backward to the arg'th subheading at same level as this one.
22093 Stop at the first and last subheadings of a superior heading."
22094 (interactive "p")
22095 (org-back-to-heading)
22096 (org-at-heading-p)
22097 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22098 (re (format "^\\*\\{1,%d\\} " level))
22100 (while (> arg 0)
22101 (while (and (re-search-backward re nil 'move)
22102 (setq l (- (match-end 0) (match-beginning 0) 1))
22103 (= l level)
22104 (not invisible-ok)
22105 (outline-invisible-p))
22106 (if (< l level) (setq arg 1)))
22107 (setq arg (1- arg)))))
22109 (defun org-forward-element ()
22110 "Move forward by one element.
22111 Move to the next element at the same level, when possible."
22112 (interactive)
22113 (cond ((eobp) (error "Cannot move further down"))
22114 ((org-with-limited-levels (org-at-heading-p))
22115 (let ((origin (point)))
22116 (org-forward-heading-same-level 1)
22117 (unless (org-with-limited-levels (org-at-heading-p))
22118 (goto-char origin)
22119 (error "Cannot move further down"))))
22121 (let* ((elem (org-element-at-point))
22122 (end (org-element-property :end elem))
22123 (parent (org-element-property :parent elem)))
22124 (if (and parent (= (org-element-property :contents-end parent) end))
22125 (goto-char (org-element-property :end parent))
22126 (goto-char end))))))
22128 (defun org-backward-element ()
22129 "Move backward by one element.
22130 Move to the previous element at the same level, when possible."
22131 (interactive)
22132 (cond ((bobp) (error "Cannot move further up"))
22133 ((org-with-limited-levels (org-at-heading-p))
22134 ;; At an headline, move to the previous one, if any, or stay
22135 ;; here.
22136 (let ((origin (point)))
22137 (org-backward-heading-same-level 1)
22138 (unless (org-with-limited-levels (org-at-heading-p))
22139 (goto-char origin)
22140 (error "Cannot move further up"))))
22142 (let* ((trail (org-element-at-point 'keep-trail))
22143 (elem (car trail))
22144 (prev-elem (nth 1 trail))
22145 (beg (org-element-property :begin elem)))
22146 (cond
22147 ;; Move to beginning of current element if point isn't
22148 ;; there already.
22149 ((/= (point) beg) (goto-char beg))
22150 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22151 ((org-before-first-heading-p) (goto-char (point-min)))
22152 (t (org-back-to-heading)))))))
22154 (defun org-up-element ()
22155 "Move to upper element."
22156 (interactive)
22157 (if (org-with-limited-levels (org-at-heading-p))
22158 (unless (org-up-heading-safe) (error "No surrounding element"))
22159 (let* ((elem (org-element-at-point))
22160 (parent (org-element-property :parent elem)))
22161 (if parent (goto-char (org-element-property :begin parent))
22162 (if (org-with-limited-levels (org-before-first-heading-p))
22163 (error "No surrounding element")
22164 (org-with-limited-levels (org-back-to-heading)))))))
22166 (defvar org-element-greater-elements)
22167 (defun org-down-element ()
22168 "Move to inner element."
22169 (interactive)
22170 (let ((element (org-element-at-point)))
22171 (cond
22172 ((memq (org-element-type element) '(plain-list table))
22173 (goto-char (org-element-property :contents-begin element))
22174 (forward-char))
22175 ((memq (org-element-type element) org-element-greater-elements)
22176 ;; If contents are hidden, first disclose them.
22177 (when (org-element-property :hiddenp element) (org-cycle))
22178 (goto-char (or (org-element-property :contents-begin element)
22179 (error "No content for this element"))))
22180 (t (error "No inner element")))))
22182 (defun org-drag-element-backward ()
22183 "Move backward element at point."
22184 (interactive)
22185 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22186 (let* ((trail (org-element-at-point 'keep-trail))
22187 (elem (car trail))
22188 (prev-elem (nth 1 trail)))
22189 ;; Error out if no previous element or previous element is
22190 ;; a parent of the current one.
22191 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22192 (error "Cannot drag element backward")
22193 (let ((pos (point)))
22194 (org-element-swap-A-B prev-elem elem)
22195 (goto-char (+ (org-element-property :begin prev-elem)
22196 (- pos (org-element-property :begin elem)))))))))
22198 (defun org-drag-element-forward ()
22199 "Move forward element at point."
22200 (interactive)
22201 (let* ((pos (point))
22202 (elem (org-element-at-point)))
22203 (when (= (point-max) (org-element-property :end elem))
22204 (error "Cannot drag element forward"))
22205 (goto-char (org-element-property :end elem))
22206 (let ((next-elem (org-element-at-point)))
22207 (when (or (org-element-nested-p elem next-elem)
22208 (and (eq (org-element-type next-elem) 'headline)
22209 (not (eq (org-element-type elem) 'headline))))
22210 (goto-char pos)
22211 (error "Cannot drag element forward"))
22212 ;; Compute new position of point: it's shifted by NEXT-ELEM
22213 ;; body's length (without final blanks) and by the length of
22214 ;; blanks between ELEM and NEXT-ELEM.
22215 (let ((size-next (- (save-excursion
22216 (goto-char (org-element-property :end next-elem))
22217 (skip-chars-backward " \r\t\n")
22218 (forward-line)
22219 ;; Small correction if buffer doesn't end
22220 ;; with a newline character.
22221 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22222 (org-element-property :begin next-elem)))
22223 (size-blank (- (org-element-property :end elem)
22224 (save-excursion
22225 (goto-char (org-element-property :end elem))
22226 (skip-chars-backward " \r\t\n")
22227 (forward-line)
22228 (point)))))
22229 (org-element-swap-A-B elem next-elem)
22230 (goto-char (+ pos size-next size-blank))))))
22232 (defun org-mark-element ()
22233 "Put point at beginning of this element, mark at end.
22235 Interactively, if this command is repeated or (in Transient Mark
22236 mode) if the mark is active, it marks the next element after the
22237 ones already marked."
22238 (interactive)
22239 (let (deactivate-mark)
22240 (if (and (org-called-interactively-p 'any)
22241 (or (and (eq last-command this-command) (mark t))
22242 (and transient-mark-mode mark-active)))
22243 (set-mark
22244 (save-excursion
22245 (goto-char (mark))
22246 (goto-char (org-element-property :end (org-element-at-point)))))
22247 (let ((element (org-element-at-point)))
22248 (end-of-line)
22249 (push-mark (org-element-property :end element) t t)
22250 (goto-char (org-element-property :begin element))))))
22252 (defun org-narrow-to-element ()
22253 "Narrow buffer to current element."
22254 (interactive)
22255 (let ((elem (org-element-at-point)))
22256 (cond
22257 ((eq (car elem) 'headline)
22258 (narrow-to-region
22259 (org-element-property :begin elem)
22260 (org-element-property :end elem)))
22261 ((memq (car elem) org-element-greater-elements)
22262 (narrow-to-region
22263 (org-element-property :contents-begin elem)
22264 (org-element-property :contents-end elem)))
22266 (narrow-to-region
22267 (org-element-property :begin elem)
22268 (org-element-property :end elem))))))
22270 (defun org-transpose-element ()
22271 "Transpose current and previous elements, keeping blank lines between.
22272 Point is moved after both elements."
22273 (interactive)
22274 (org-skip-whitespace)
22275 (let ((end (org-element-property :end (org-element-at-point))))
22276 (org-drag-element-backward)
22277 (goto-char end)))
22279 (defun org-unindent-buffer ()
22280 "Un-indent the visible part of the buffer.
22281 Relative indentation (between items, inside blocks, etc.) isn't
22282 modified."
22283 (interactive)
22284 (unless (eq major-mode 'org-mode)
22285 (error "Cannot un-indent a buffer not in Org mode"))
22286 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22287 unindent-tree ; For byte-compiler.
22288 (unindent-tree
22289 (function
22290 (lambda (contents)
22291 (mapc
22292 (lambda (element)
22293 (if (memq (org-element-type element) '(headline section))
22294 (funcall unindent-tree (org-element-contents element))
22295 (save-excursion
22296 (save-restriction
22297 (narrow-to-region
22298 (org-element-property :begin element)
22299 (org-element-property :end element))
22300 (org-do-remove-indentation)))))
22301 (reverse contents))))))
22302 (funcall unindent-tree (org-element-contents parse-tree))))
22304 (defun org-show-subtree ()
22305 "Show everything after this heading at deeper levels."
22306 (interactive)
22307 (outline-flag-region
22308 (point)
22309 (save-excursion
22310 (org-end-of-subtree t t))
22311 nil))
22313 (defun org-show-entry ()
22314 "Show the body directly following this heading.
22315 Show the heading too, if it is currently invisible."
22316 (interactive)
22317 (save-excursion
22318 (condition-case nil
22319 (progn
22320 (org-back-to-heading t)
22321 (outline-flag-region
22322 (max (point-min) (1- (point)))
22323 (save-excursion
22324 (if (re-search-forward
22325 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22326 (match-beginning 1)
22327 (point-max)))
22328 nil)
22329 (org-cycle-hide-drawers 'children))
22330 (error nil))))
22332 (defun org-make-options-regexp (kwds &optional extra)
22333 "Make a regular expression for keyword lines."
22334 (concat
22335 "^#\\+\\("
22336 (mapconcat 'regexp-quote kwds "\\|")
22337 (if extra (concat "\\|" extra))
22338 "\\):[ \t]*\\(.*\\)"))
22340 ;; Make isearch reveal the necessary context
22341 (defun org-isearch-end ()
22342 "Reveal context after isearch exits."
22343 (when isearch-success ; only if search was successful
22344 (if (featurep 'xemacs)
22345 ;; Under XEmacs, the hook is run in the correct place,
22346 ;; we directly show the context.
22347 (org-show-context 'isearch)
22348 ;; In Emacs the hook runs *before* restoring the overlays.
22349 ;; So we have to use a one-time post-command-hook to do this.
22350 ;; (Emacs 22 has a special variable, see function `org-mode')
22351 (unless (and (boundp 'isearch-mode-end-hook-quit)
22352 isearch-mode-end-hook-quit)
22353 ;; Only when the isearch was not quitted.
22354 (org-add-hook 'post-command-hook 'org-isearch-post-command
22355 'append 'local)))))
22357 (defun org-isearch-post-command ()
22358 "Remove self from hook, and show context."
22359 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22360 (org-show-context 'isearch))
22363 ;;;; Integration with and fixes for other packages
22365 ;;; Imenu support
22367 (defvar org-imenu-markers nil
22368 "All markers currently used by Imenu.")
22369 (make-variable-buffer-local 'org-imenu-markers)
22371 (defun org-imenu-new-marker (&optional pos)
22372 "Return a new marker for use by Imenu, and remember the marker."
22373 (let ((m (make-marker)))
22374 (move-marker m (or pos (point)))
22375 (push m org-imenu-markers)
22378 (defun org-imenu-get-tree ()
22379 "Produce the index for Imenu."
22380 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22381 (setq org-imenu-markers nil)
22382 (let* ((n org-imenu-depth)
22383 (re (concat "^" (org-get-limited-outline-regexp)))
22384 (subs (make-vector (1+ n) nil))
22385 (last-level 0)
22386 m level head)
22387 (save-excursion
22388 (save-restriction
22389 (widen)
22390 (goto-char (point-max))
22391 (while (re-search-backward re nil t)
22392 (setq level (org-reduced-level (funcall outline-level)))
22393 (when (and (<= level n)
22394 (looking-at org-complex-heading-regexp))
22395 (setq head (org-link-display-format
22396 (org-match-string-no-properties 4))
22397 m (org-imenu-new-marker))
22398 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22399 (if (>= level last-level)
22400 (push (cons head m) (aref subs level))
22401 (push (cons head (aref subs (1+ level))) (aref subs level))
22402 (loop for i from (1+ level) to n do (aset subs i nil)))
22403 (setq last-level level)))))
22404 (aref subs 1)))
22406 (eval-after-load "imenu"
22407 '(progn
22408 (add-hook 'imenu-after-jump-hook
22409 (lambda ()
22410 (if (derived-mode-p 'org-mode)
22411 (org-show-context 'org-goto))))))
22413 (defun org-link-display-format (link)
22414 "Replace a link with either the description, or the link target
22415 if no description is present"
22416 (save-match-data
22417 (if (string-match org-bracket-link-analytic-regexp link)
22418 (replace-match (if (match-end 5)
22419 (match-string 5 link)
22420 (concat (match-string 1 link)
22421 (match-string 3 link)))
22422 nil t link)
22423 link)))
22425 (defun org-toggle-link-display ()
22426 "Toggle the literal or descriptive display of links."
22427 (interactive)
22428 (if org-descriptive-links
22429 (progn (org-remove-from-invisibility-spec '(org-link))
22430 (org-restart-font-lock)
22431 (setq org-descriptive-links nil))
22432 (progn (add-to-invisibility-spec '(org-link))
22433 (org-restart-font-lock)
22434 (setq org-descriptive-links t))))
22436 ;; Speedbar support
22438 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22439 "Overlay marking the agenda restriction line in speedbar.")
22440 (overlay-put org-speedbar-restriction-lock-overlay
22441 'face 'org-agenda-restriction-lock)
22442 (overlay-put org-speedbar-restriction-lock-overlay
22443 'help-echo "Agendas are currently limited to this item.")
22444 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22446 (defun org-speedbar-set-agenda-restriction ()
22447 "Restrict future agenda commands to the location at point in speedbar.
22448 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22449 (interactive)
22450 (require 'org-agenda)
22451 (let (p m tp np dir txt)
22452 (cond
22453 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22454 'org-imenu t))
22455 (setq m (get-text-property p 'org-imenu-marker))
22456 (with-current-buffer (marker-buffer m)
22457 (goto-char m)
22458 (org-agenda-set-restriction-lock 'subtree)))
22459 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22460 'speedbar-function 'speedbar-find-file))
22461 (setq tp (previous-single-property-change
22462 (1+ p) 'speedbar-function)
22463 np (next-single-property-change
22464 tp 'speedbar-function)
22465 dir (speedbar-line-directory)
22466 txt (buffer-substring-no-properties (or tp (point-min))
22467 (or np (point-max))))
22468 (with-current-buffer (find-file-noselect
22469 (let ((default-directory dir))
22470 (expand-file-name txt)))
22471 (unless (derived-mode-p 'org-mode)
22472 (error "Cannot restrict to non-Org-mode file"))
22473 (org-agenda-set-restriction-lock 'file)))
22474 (t (error "Don't know how to restrict Org-mode's agenda")))
22475 (move-overlay org-speedbar-restriction-lock-overlay
22476 (point-at-bol) (point-at-eol))
22477 (setq current-prefix-arg nil)
22478 (org-agenda-maybe-redo)))
22480 (eval-after-load "speedbar"
22481 '(progn
22482 (speedbar-add-supported-extension ".org")
22483 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22484 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22485 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22486 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22487 (add-hook 'speedbar-visiting-tag-hook
22488 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22490 ;;; Fixes and Hacks for problems with other packages
22492 ;; Make flyspell not check words in links, to not mess up our keymap
22493 (defun org-mode-flyspell-verify ()
22494 "Don't let flyspell put overlays at active buttons, or on
22495 {todo,all-time,additional-option-like}-keywords."
22496 (let ((pos (max (1- (point)) (point-min)))
22497 (word (thing-at-point 'word)))
22498 (and (not (get-text-property pos 'keymap))
22499 (not (get-text-property pos 'org-no-flyspell))
22500 (not (member word org-todo-keywords-1))
22501 (not (member word org-all-time-keywords))
22502 (not (member word org-options-keywords))
22503 (not (member word (mapcar 'car org-startup-options)))
22504 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22506 (defun org-remove-flyspell-overlays-in (beg end)
22507 "Remove flyspell overlays in region."
22508 (and (org-bound-and-true-p flyspell-mode)
22509 (fboundp 'flyspell-delete-region-overlays)
22510 (flyspell-delete-region-overlays beg end))
22511 (add-text-properties beg end '(org-no-flyspell t)))
22513 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22514 (eval-after-load "bookmark"
22515 '(if (boundp 'bookmark-after-jump-hook)
22516 ;; We can use the hook
22517 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22518 ;; Hook not available, use advice
22519 (defadvice bookmark-jump (after org-make-visible activate)
22520 "Make the position visible."
22521 (org-bookmark-jump-unhide))))
22523 ;; Make sure saveplace shows the location if it was hidden
22524 (eval-after-load "saveplace"
22525 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22526 "Make the position visible."
22527 (org-bookmark-jump-unhide)))
22529 ;; Make sure ecb shows the location if it was hidden
22530 (eval-after-load "ecb"
22531 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22532 "Make hierarchy visible when jumping into location from ECB tree buffer."
22533 (if (derived-mode-p 'org-mode)
22534 (org-show-context))))
22536 (defun org-bookmark-jump-unhide ()
22537 "Unhide the current position, to show the bookmark location."
22538 (and (derived-mode-p 'org-mode)
22539 (or (outline-invisible-p)
22540 (save-excursion (goto-char (max (point-min) (1- (point))))
22541 (outline-invisible-p)))
22542 (org-show-context 'bookmark-jump)))
22544 ;; Make session.el ignore our circular variable
22545 (eval-after-load "session"
22546 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22548 ;;;; Experimental code
22550 (defun org-closed-in-range ()
22551 "Sparse tree of items closed in a certain time range.
22552 Still experimental, may disappear in the future."
22553 (interactive)
22554 ;; Get the time interval from the user.
22555 (let* ((time1 (org-float-time
22556 (org-read-date nil 'to-time nil "Starting date: ")))
22557 (time2 (org-float-time
22558 (org-read-date nil 'to-time nil "End date:")))
22559 ;; callback function
22560 (callback (lambda ()
22561 (let ((time
22562 (org-float-time
22563 (apply 'encode-time
22564 (org-parse-time-string
22565 (match-string 1))))))
22566 ;; check if time in interval
22567 (and (>= time time1) (<= time time2))))))
22568 ;; make tree, check each match with the callback
22569 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22571 ;;;; Finish up
22573 (provide 'org)
22575 (run-hooks 'org-load-hook)
22577 ;;; org.el ends here