org.el: Leave scheduled/deadline lines untouched when filling an adjacent paragraph.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
bloba11d7345a19531cfb4604f2dd366de09fd3c5252
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
10 ;; Version: 7.8.08
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (make-variable-buffer-local 'org-table-formula-constants-local)
72 ;;;; Require other packages
74 (eval-when-compile
75 (require 'cl)
76 (require 'gnus-sum))
78 (require 'calendar)
79 (require 'format-spec)
81 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
82 (when (fboundp 'defvaralias)
83 (unless (boundp 'calendar-view-holidays-initially-flag)
84 (defvaralias 'calendar-view-holidays-initially-flag
85 'view-calendar-holidays-initially))
86 (unless (boundp 'calendar-view-diary-initially-flag)
87 (defvaralias 'calendar-view-diary-initially-flag
88 'view-diary-entries-initially))
89 (unless (boundp 'diary-fancy-buffer)
90 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
92 (require 'outline) (require 'noutline)
93 ;; Other stuff we need.
94 (require 'time-date)
95 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
96 (require 'easymenu)
97 (require 'overlay)
99 (require 'org-macs)
100 (require 'org-entities)
101 (require 'org-compat)
102 (require 'org-faces)
103 (require 'org-list)
104 (require 'org-pcomplete)
105 (require 'org-src)
106 (require 'org-footnote)
108 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
109 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
110 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
111 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
112 (declare-function org-at-clock-log-p "org-clock" ())
113 (declare-function org-clock-timestamps-up "org-clock" ())
114 (declare-function org-clock-timestamps-down "org-clock" ())
116 ;; babel
117 (require 'ob)
118 (require 'ob-table)
119 (require 'ob-lob)
120 (require 'ob-ref)
121 (require 'ob-tangle)
122 (require 'ob-comint)
123 (require 'ob-keys)
125 ;; load languages based on value of `org-babel-load-languages'
126 (defvar org-babel-load-languages)
127 ;;;###autoload
128 (defun org-babel-do-load-languages (sym value)
129 "Load the languages defined in `org-babel-load-languages'."
130 (set-default sym value)
131 (mapc (lambda (pair)
132 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
133 (if active
134 (progn
135 (require (intern (concat "ob-" lang))))
136 (progn
137 (funcall 'fmakunbound
138 (intern (concat "org-babel-execute:" lang)))
139 (funcall 'fmakunbound
140 (intern (concat "org-babel-expand-body:" lang)))))))
141 org-babel-load-languages))
143 (defcustom org-babel-load-languages '((emacs-lisp . t))
144 "Languages which can be evaluated in Org-mode buffers.
145 This list can be used to load support for any of the languages
146 below, note that each language will depend on a different set of
147 system executables and/or Emacs modes. When a language is
148 \"loaded\", then code blocks in that language can be evaluated
149 with `org-babel-execute-src-block' bound by default to C-c
150 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
151 be set to remove code block evaluation from the C-c C-c
152 keybinding. By default only Emacs Lisp (which has no
153 requirements) is loaded."
154 :group 'org-babel
155 :set 'org-babel-do-load-languages
156 :version "24.1"
157 :type '(alist :tag "Babel Languages"
158 :key-type
159 (choice
160 (const :tag "Awk" awk)
161 (const :tag "C" C)
162 (const :tag "R" R)
163 (const :tag "Asymptote" asymptote)
164 (const :tag "Calc" calc)
165 (const :tag "Clojure" clojure)
166 (const :tag "CSS" css)
167 (const :tag "Ditaa" ditaa)
168 (const :tag "Dot" dot)
169 (const :tag "Emacs Lisp" emacs-lisp)
170 (const :tag "Fortran" fortran)
171 (const :tag "Gnuplot" gnuplot)
172 (const :tag "Haskell" haskell)
173 (const :tag "IO" io)
174 (const :tag "Java" java)
175 (const :tag "Javascript" js)
176 (const :tag "LaTeX" latex)
177 (const :tag "Ledger" ledger)
178 (const :tag "Lilypond" lilypond)
179 (const :tag "Maxima" maxima)
180 (const :tag "Matlab" matlab)
181 (const :tag "Mscgen" mscgen)
182 (const :tag "Ocaml" ocaml)
183 (const :tag "Octave" octave)
184 (const :tag "Org" org)
185 (const :tag "Perl" perl)
186 (const :tag "Pico Lisp" picolisp)
187 (const :tag "PlantUML" plantuml)
188 (const :tag "Python" python)
189 (const :tag "Ruby" ruby)
190 (const :tag "Sass" sass)
191 (const :tag "Scala" scala)
192 (const :tag "Scheme" scheme)
193 (const :tag "Screen" screen)
194 (const :tag "Shell Script" sh)
195 (const :tag "Shen" shen)
196 (const :tag "Sql" sql)
197 (const :tag "Sqlite" sqlite))
198 :value-type (boolean :tag "Activate" :value t)))
200 ;;;; Customization variables
201 (defcustom org-clone-delete-id nil
202 "Remove ID property of clones of a subtree.
203 When non-nil, clones of a subtree don't inherit the ID property.
204 Otherwise they inherit the ID property with a new unique
205 identifier."
206 :type 'boolean
207 :version "24.1"
208 :group 'org-id)
210 ;;; Version
212 (defconst org-version "7.8.08"
213 "The version number of the file org.el.")
215 ;;;###autoload
216 (defun org-version (&optional here)
217 "Show the org-mode version in the echo area.
218 With prefix arg HERE, insert it at point."
219 (interactive "P")
220 (let* ((origin default-directory)
221 (version org-version)
222 (git-version)
223 (dir (concat (file-name-directory (locate-library "org")) "../" )))
224 (when (and (file-exists-p (expand-file-name ".git" dir))
225 (executable-find "git"))
226 (unwind-protect
227 (progn
228 (cd dir)
229 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
230 (with-current-buffer "*Shell Command Output*"
231 (goto-char (point-min))
232 (setq git-version (buffer-substring (point) (point-at-eol))))
233 (subst-char-in-string ?- ?. git-version t)
234 (when (string-match "\\S-"
235 (shell-command-to-string
236 "git diff-index --name-only HEAD --"))
237 (setq git-version (concat git-version ".dirty")))
238 (setq version (concat version " (" git-version ")"))))
239 (cd origin)))
240 (setq version (format "Org-mode version %s" version))
241 (if here (insert version))
242 (message version)))
244 ;;; Compatibility constants
246 ;;; The custom variables
248 (defgroup org nil
249 "Outline-based notes management and organizer."
250 :tag "Org"
251 :group 'outlines
252 :group 'calendar)
254 (defcustom org-mode-hook nil
255 "Mode hook for Org-mode, run after the mode was turned on."
256 :group 'org
257 :type 'hook)
259 (defcustom org-load-hook nil
260 "Hook that is run after org.el has been loaded."
261 :group 'org
262 :type 'hook)
264 (defcustom org-log-buffer-setup-hook nil
265 "Hook that is run after an Org log buffer is created."
266 :group 'org
267 :version "24.1"
268 :type 'hook)
270 (defvar org-modules) ; defined below
271 (defvar org-modules-loaded nil
272 "Have the modules been loaded already?")
274 (defun org-load-modules-maybe (&optional force)
275 "Load all extensions listed in `org-modules'."
276 (when (or force (not org-modules-loaded))
277 (mapc (lambda (ext)
278 (condition-case nil (require ext)
279 (error (message "Problems while trying to load feature `%s'" ext))))
280 org-modules)
281 (setq org-modules-loaded t)))
283 (defun org-set-modules (var value)
284 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
285 (set var value)
286 (when (featurep 'org)
287 (org-load-modules-maybe 'force)))
289 (when (org-bound-and-true-p org-modules)
290 (let ((a (member 'org-infojs org-modules)))
291 (and a (setcar a 'org-jsinfo))))
293 (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)
294 "Modules that should always be loaded together with org.el.
295 If a description starts with <C>, the file is not part of Emacs
296 and loading it will require that you have downloaded and properly installed
297 the org-mode distribution.
299 You can also use this system to load external packages (i.e. neither Org
300 core modules, nor modules from the CONTRIB directory). Just add symbols
301 to the end of the list. If the package is called org-xyz.el, then you need
302 to add the symbol `xyz', and the package must have a call to
304 (provide 'org-xyz)"
305 :group 'org
306 :set 'org-set-modules
307 :type
308 '(set :greedy t
309 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
310 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
311 (const :tag " crypt: Encryption of subtrees" org-crypt)
312 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
313 (const :tag " docview: Links to doc-view buffers" org-docview)
314 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
315 (const :tag " id: Global IDs for identifying entries" org-id)
316 (const :tag " info: Links to Info nodes" org-info)
317 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
318 (const :tag " habit: Track your consistency with habits" org-habit)
319 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
320 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
321 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
322 (const :tag " mew Links to Mew folders/messages" org-mew)
323 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
324 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
325 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
326 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
327 (const :tag " vm: Links to VM folders/messages" org-vm)
328 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
329 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
330 (const :tag " mouse: Additional mouse support" org-mouse)
331 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
333 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
334 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
335 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
336 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
337 (const :tag "C collector: Collect properties into tables" org-collector)
338 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
339 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
340 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
341 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
342 (const :tag "C eval: Include command output as text" org-eval)
343 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
344 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
345 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
346 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
347 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
349 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
351 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
352 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
353 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
354 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
355 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
356 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
357 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
358 (const :tag "C mtags: Support for muse-like tags" org-mtags)
359 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
360 (const :tag "C registry: A registry for Org-mode links" org-registry)
361 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
362 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
363 (const :tag "C secretary: Team management with org-mode" org-secretary)
364 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
365 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
366 (const :tag "C track: Keep up with Org-mode development" org-track)
367 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
368 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
369 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
371 (defcustom org-support-shift-select nil
372 "Non-nil means make shift-cursor commands select text when possible.
374 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
375 start selecting a region, or enlarge regions started in this way.
376 In Org-mode, in special contexts, these same keys are used for
377 other purposes, important enough to compete with shift selection.
378 Org tries to balance these needs by supporting `shift-select-mode'
379 outside these special contexts, under control of this variable.
381 The default of this variable is nil, to avoid confusing behavior. Shifted
382 cursor keys will then execute Org commands in the following contexts:
383 - on a headline, changing TODO state (left/right) and priority (up/down)
384 - on a time stamp, changing the time
385 - in a plain list item, changing the bullet type
386 - in a property definition line, switching between allowed values
387 - in the BEGIN line of a clock table (changing the time block).
388 Outside these contexts, the commands will throw an error.
390 When this variable is t and the cursor is not in a special
391 context, Org-mode will support shift-selection for making and
392 enlarging regions. To make this more effective, the bullet
393 cycling will no longer happen anywhere in an item line, but only
394 if the cursor is exactly on the bullet.
396 If you set this variable to the symbol `always', then the keys
397 will not be special in headlines, property lines, and item lines,
398 to make shift selection work there as well. If this is what you
399 want, you can use the following alternative commands: `C-c C-t'
400 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
401 can be used to switch TODO sets, `C-c -' to cycle item bullet
402 types, and properties can be edited by hand or in column view.
404 However, when the cursor is on a timestamp, shift-cursor commands
405 will still edit the time stamp - this is just too good to give up.
407 XEmacs user should have this variable set to nil, because
408 `shift-select-mode' is in Emacs 23 or later only."
409 :group 'org
410 :type '(choice
411 (const :tag "Never" nil)
412 (const :tag "When outside special context" t)
413 (const :tag "Everywhere except timestamps" always)))
415 (defcustom org-loop-over-headlines-in-active-region nil
416 "Shall some commands act upon headlines in the active region?
418 When set to `t', some commands will be performed in all headlines
419 within the active region.
421 When set to `start-level', some commands will be performed in all
422 headlines within the active region, provided that these headlines
423 are of the same level than the first one.
425 When set to a string, those commands will be performed on the
426 matching headlines within the active region. Such string must be
427 a tags/property/todo match as it is used in the agenda tags view.
429 The list of commands is: `org-schedule', `org-deadline',
430 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
431 `org-archive-to-archive-sibling'. The archiving commands skip
432 already archived entries."
433 :type '(choice (const :tag "Don't loop" nil)
434 (const :tag "All headlines in active region" t)
435 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
436 (string :tag "Tags/Property/Todo matcher"))
437 :version "24.1"
438 :group 'org-todo
439 :group 'org-archive)
441 (defgroup org-startup nil
442 "Options concerning startup of Org-mode."
443 :tag "Org Startup"
444 :group 'org)
446 (defcustom org-startup-folded t
447 "Non-nil means entering Org-mode will switch to OVERVIEW.
448 This can also be configured on a per-file basis by adding one of
449 the following lines anywhere in the buffer:
451 #+STARTUP: fold (or `overview', this is equivalent)
452 #+STARTUP: nofold (or `showall', this is equivalent)
453 #+STARTUP: content
454 #+STARTUP: showeverything"
455 :group 'org-startup
456 :type '(choice
457 (const :tag "nofold: show all" nil)
458 (const :tag "fold: overview" t)
459 (const :tag "content: all headlines" content)
460 (const :tag "show everything, even drawers" showeverything)))
462 (defcustom org-startup-truncated t
463 "Non-nil means entering Org-mode will set `truncate-lines'.
464 This is useful since some lines containing links can be very long and
465 uninteresting. Also tables look terrible when wrapped."
466 :group 'org-startup
467 :type 'boolean)
469 (defcustom org-startup-indented nil
470 "Non-nil means turn on `org-indent-mode' on startup.
471 This can also be configured on a per-file basis by adding one of
472 the following lines anywhere in the buffer:
474 #+STARTUP: indent
475 #+STARTUP: noindent"
476 :group 'org-structure
477 :type '(choice
478 (const :tag "Not" nil)
479 (const :tag "Globally (slow on startup in large files)" t)))
481 (defcustom org-use-sub-superscripts t
482 "Non-nil means interpret \"_\" and \"^\" for export.
483 When this option is turned on, you can use TeX-like syntax for sub- and
484 superscripts. Several characters after \"_\" or \"^\" will be
485 considered as a single item - so grouping with {} is normally not
486 needed. For example, the following things will be parsed as single
487 sub- or superscripts.
489 10^24 or 10^tau several digits will be considered 1 item.
490 10^-12 or 10^-tau a leading sign with digits or a word
491 x^2-y^3 will be read as x^2 - y^3, because items are
492 terminated by almost any nonword/nondigit char.
493 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
495 Still, ambiguity is possible - so when in doubt use {} to enclose the
496 sub/superscript. If you set this variable to the symbol `{}',
497 the braces are *required* in order to trigger interpretations as
498 sub/superscript. This can be helpful in documents that need \"_\"
499 frequently in plain text.
501 Not all export backends support this, but HTML does.
503 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
504 :group 'org-startup
505 :group 'org-export-translation
506 :version "24.1"
507 :type '(choice
508 (const :tag "Always interpret" t)
509 (const :tag "Only with braces" {})
510 (const :tag "Never interpret" nil)))
512 (if (fboundp 'defvaralias)
513 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
516 (defcustom org-startup-with-beamer-mode nil
517 "Non-nil means turn on `org-beamer-mode' on startup.
518 This can also be configured on a per-file basis by adding one of
519 the following lines anywhere in the buffer:
521 #+STARTUP: beamer"
522 :group 'org-startup
523 :version "24.1"
524 :type 'boolean)
526 (defcustom org-startup-align-all-tables nil
527 "Non-nil means align all tables when visiting a file.
528 This is useful when the column width in tables is forced with <N> cookies
529 in table fields. Such tables will look correct only after the first re-align.
530 This can also be configured on a per-file basis by adding one of
531 the following lines anywhere in the buffer:
532 #+STARTUP: align
533 #+STARTUP: noalign"
534 :group 'org-startup
535 :type 'boolean)
537 (defcustom org-startup-with-inline-images nil
538 "Non-nil means show inline images when loading a new Org file.
539 This can also be configured on a per-file basis by adding one of
540 the following lines anywhere in the buffer:
541 #+STARTUP: inlineimages
542 #+STARTUP: noinlineimages"
543 :group 'org-startup
544 :version "24.1"
545 :type 'boolean)
547 (defcustom org-insert-mode-line-in-empty-file nil
548 "Non-nil means insert the first line setting Org-mode in empty files.
549 When the function `org-mode' is called interactively in an empty file, this
550 normally means that the file name does not automatically trigger Org-mode.
551 To ensure that the file will always be in Org-mode in the future, a
552 line enforcing Org-mode will be inserted into the buffer, if this option
553 has been set."
554 :group 'org-startup
555 :type 'boolean)
557 (defcustom org-replace-disputed-keys nil
558 "Non-nil means use alternative key bindings for some keys.
559 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
560 These keys are also used by other packages like shift-selection-mode'
561 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
562 If you want to use Org-mode together with one of these other modes,
563 or more generally if you would like to move some Org-mode commands to
564 other keys, set this variable and configure the keys with the variable
565 `org-disputed-keys'.
567 This option is only relevant at load-time of Org-mode, and must be set
568 *before* org.el is loaded. Changing it requires a restart of Emacs to
569 become effective."
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-use-extra-keys nil
574 "Non-nil means use extra key sequence definitions for certain commands.
575 This happens automatically if you run XEmacs or if `window-system'
576 is nil. This variable lets you do the same manually. You must
577 set it before loading org.
579 Example: on Carbon Emacs 22 running graphically, with an external
580 keyboard on a Powerbook, the default way of setting M-left might
581 not work for either Alt or ESC. Setting this variable will make
582 it work for ESC."
583 :group 'org-startup
584 :type 'boolean)
586 (if (fboundp 'defvaralias)
587 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
589 (defcustom org-disputed-keys
590 '(([(shift up)] . [(meta p)])
591 ([(shift down)] . [(meta n)])
592 ([(shift left)] . [(meta -)])
593 ([(shift right)] . [(meta +)])
594 ([(control shift right)] . [(meta shift +)])
595 ([(control shift left)] . [(meta shift -)]))
596 "Keys for which Org-mode and other modes compete.
597 This is an alist, cars are the default keys, second element specifies
598 the alternative to use when `org-replace-disputed-keys' is t.
600 Keys can be specified in any syntax supported by `define-key'.
601 The value of this option takes effect only at Org-mode's startup,
602 therefore you'll have to restart Emacs to apply it after changing."
603 :group 'org-startup
604 :type 'alist)
606 (defun org-key (key)
607 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
608 Or return the original if not disputed.
609 Also apply the translations defined in `org-xemacs-key-equivalents'."
610 (when org-replace-disputed-keys
611 (let* ((nkey (key-description key))
612 (x (org-find-if (lambda (x)
613 (equal (key-description (car x)) nkey))
614 org-disputed-keys)))
615 (setq key (if x (cdr x) key))))
616 (when (featurep 'xemacs)
617 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
618 key)
620 (defun org-find-if (predicate seq)
621 (catch 'exit
622 (while seq
623 (if (funcall predicate (car seq))
624 (throw 'exit (car seq))
625 (pop seq)))))
627 (defun org-defkey (keymap key def)
628 "Define a key, possibly translated, as returned by `org-key'."
629 (define-key keymap (org-key key) def))
631 (defcustom org-ellipsis nil
632 "The ellipsis to use in the Org-mode outline.
633 When nil, just use the standard three dots. When a string, use that instead,
634 When a face, use the standard 3 dots, but with the specified face.
635 The change affects only Org-mode (which will then use its own display table).
636 Changing this requires executing `M-x org-mode' in a buffer to become
637 effective."
638 :group 'org-startup
639 :type '(choice (const :tag "Default" nil)
640 (face :tag "Face" :value org-warning)
641 (string :tag "String" :value "...#")))
643 (defvar org-display-table nil
644 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
646 (defgroup org-keywords nil
647 "Keywords in Org-mode."
648 :tag "Org Keywords"
649 :group 'org)
651 (defcustom org-deadline-string "DEADLINE:"
652 "String to mark deadline entries.
653 A deadline is this string, followed by a time stamp. Should be a word,
654 terminated by a colon. You can insert a schedule keyword and
655 a timestamp with \\[org-deadline].
656 Changes become only effective after restarting Emacs."
657 :group 'org-keywords
658 :type 'string)
660 (defcustom org-scheduled-string "SCHEDULED:"
661 "String to mark scheduled TODO entries.
662 A schedule is this string, followed by a time stamp. Should be a word,
663 terminated by a colon. You can insert a schedule keyword and
664 a timestamp with \\[org-schedule].
665 Changes become only effective after restarting Emacs."
666 :group 'org-keywords
667 :type 'string)
669 (defcustom org-closed-string "CLOSED:"
670 "String used as the prefix for timestamps logging closing a TODO entry."
671 :group 'org-keywords
672 :type 'string)
674 (defcustom org-clock-string "CLOCK:"
675 "String used as prefix for timestamps clocking work hours on an item."
676 :group 'org-keywords
677 :type 'string)
679 (defcustom org-comment-string "COMMENT"
680 "Entries starting with this keyword will never be exported.
681 An entry can be toggled between COMMENT and normal with
682 \\[org-toggle-comment].
683 Changes become only effective after restarting Emacs."
684 :group 'org-keywords
685 :type 'string)
687 (defcustom org-quote-string "QUOTE"
688 "Entries starting with this keyword will be exported in fixed-width font.
689 Quoting applies only to the text in the entry following the headline, and does
690 not extend beyond the next headline, even if that is lower level.
691 An entry can be toggled between QUOTE and normal with
692 \\[org-toggle-fixed-width-section]."
693 :group 'org-keywords
694 :type 'string)
696 (defconst org-repeat-re
697 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
698 "Regular expression for specifying repeated events.
699 After a match, group 1 contains the repeat expression.")
701 (defgroup org-structure nil
702 "Options concerning the general structure of Org-mode files."
703 :tag "Org Structure"
704 :group 'org)
706 (defgroup org-reveal-location nil
707 "Options about how to make context of a location visible."
708 :tag "Org Reveal Location"
709 :group 'org-structure)
711 (defconst org-context-choice
712 '(choice
713 (const :tag "Always" t)
714 (const :tag "Never" nil)
715 (repeat :greedy t :tag "Individual contexts"
716 (cons
717 (choice :tag "Context"
718 (const agenda)
719 (const org-goto)
720 (const occur-tree)
721 (const tags-tree)
722 (const link-search)
723 (const mark-goto)
724 (const bookmark-jump)
725 (const isearch)
726 (const default))
727 (boolean))))
728 "Contexts for the reveal options.")
730 (defcustom org-show-hierarchy-above '((default . t))
731 "Non-nil means show full hierarchy when revealing a location.
732 Org-mode often shows locations in an org-mode file which might have
733 been invisible before. When this is set, the hierarchy of headings
734 above the exposed location is shown.
735 Turning this off for example for sparse trees makes them very compact.
736 Instead of t, this can also be an alist specifying this option for different
737 contexts. Valid contexts are
738 agenda when exposing an entry from the agenda
739 org-goto when using the command `org-goto' on key C-c C-j
740 occur-tree when using the command `org-occur' on key C-c /
741 tags-tree when constructing a sparse tree based on tags matches
742 link-search when exposing search matches associated with a link
743 mark-goto when exposing the jump goal of a mark
744 bookmark-jump when exposing a bookmark location
745 isearch when exiting from an incremental search
746 default default for all contexts not set explicitly"
747 :group 'org-reveal-location
748 :type org-context-choice)
750 (defcustom org-show-following-heading '((default . nil))
751 "Non-nil means show following heading when revealing a location.
752 Org-mode often shows locations in an org-mode file which might have
753 been invisible before. When this is set, the heading following the
754 match is shown.
755 Turning this off for example for sparse trees makes them very compact,
756 but makes it harder to edit the location of the match. In such a case,
757 use the command \\[org-reveal] to show more context.
758 Instead of t, this can also be an alist specifying this option for different
759 contexts. See `org-show-hierarchy-above' for valid contexts."
760 :group 'org-reveal-location
761 :type org-context-choice)
763 (defcustom org-show-siblings '((default . nil) (isearch t))
764 "Non-nil means show all sibling heading when revealing a location.
765 Org-mode often shows locations in an org-mode file which might have
766 been invisible before. When this is set, the sibling of the current entry
767 heading are all made visible. If `org-show-hierarchy-above' is t,
768 the same happens on each level of the hierarchy above the current entry.
770 By default this is on for the isearch context, off for all other contexts.
771 Turning this off for example for sparse trees makes them very compact,
772 but makes it harder to edit the location of the match. In such a case,
773 use the command \\[org-reveal] to show more context.
774 Instead of t, this can also be an alist specifying this option for different
775 contexts. See `org-show-hierarchy-above' for valid contexts."
776 :group 'org-reveal-location
777 :type org-context-choice)
779 (defcustom org-show-entry-below '((default . nil))
780 "Non-nil means show the entry below a headline when revealing a location.
781 Org-mode often shows locations in an org-mode file which might have
782 been invisible before. When this is set, the text below the headline that is
783 exposed is also shown.
785 By default this is off for all contexts.
786 Instead of t, this can also be an alist specifying this option for different
787 contexts. See `org-show-hierarchy-above' for valid contexts."
788 :group 'org-reveal-location
789 :type org-context-choice)
791 (defcustom org-indirect-buffer-display 'other-window
792 "How should indirect tree buffers be displayed?
793 This applies to indirect buffers created with the commands
794 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
795 Valid values are:
796 current-window Display in the current window
797 other-window Just display in another window.
798 dedicated-frame Create one new frame, and re-use it each time.
799 new-frame Make a new frame each time. Note that in this case
800 previously-made indirect buffers are kept, and you need to
801 kill these buffers yourself."
802 :group 'org-structure
803 :group 'org-agenda-windows
804 :type '(choice
805 (const :tag "In current window" current-window)
806 (const :tag "In current frame, other window" other-window)
807 (const :tag "Each time a new frame" new-frame)
808 (const :tag "One dedicated frame" dedicated-frame)))
810 (defcustom org-use-speed-commands nil
811 "Non-nil means activate single letter commands at beginning of a headline.
812 This may also be a function to test for appropriate locations where speed
813 commands should be active."
814 :group 'org-structure
815 :type '(choice
816 (const :tag "Never" nil)
817 (const :tag "At beginning of headline stars" t)
818 (function)))
820 (defcustom org-speed-commands-user nil
821 "Alist of additional speed commands.
822 This list will be checked before `org-speed-commands-default'
823 when the variable `org-use-speed-commands' is non-nil
824 and when the cursor is at the beginning of a headline.
825 The car if each entry is a string with a single letter, which must
826 be assigned to `self-insert-command' in the global map.
827 The cdr is either a command to be called interactively, a function
828 to be called, or a form to be evaluated.
829 An entry that is just a list with a single string will be interpreted
830 as a descriptive headline that will be added when listing the speed
831 commands in the Help buffer using the `?' speed command."
832 :group 'org-structure
833 :type '(repeat :value ("k" . ignore)
834 (choice :value ("k" . ignore)
835 (list :tag "Descriptive Headline" (string :tag "Headline"))
836 (cons :tag "Letter and Command"
837 (string :tag "Command letter")
838 (choice
839 (function)
840 (sexp))))))
842 (defgroup org-cycle nil
843 "Options concerning visibility cycling in Org-mode."
844 :tag "Org Cycle"
845 :group 'org-structure)
847 (defcustom org-cycle-skip-children-state-if-no-children t
848 "Non-nil means skip CHILDREN state in entries that don't have any."
849 :group 'org-cycle
850 :type 'boolean)
852 (defcustom org-cycle-max-level nil
853 "Maximum level which should still be subject to visibility cycling.
854 Levels higher than this will, for cycling, be treated as text, not a headline.
855 When `org-odd-levels-only' is set, a value of N in this variable actually
856 means 2N-1 stars as the limiting headline.
857 When nil, cycle all levels.
858 Note that the limiting level of cycling is also influenced by
859 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
860 `org-inlinetask-min-level' is, cycling will be limited to levels one less
861 than its value."
862 :group 'org-cycle
863 :type '(choice
864 (const :tag "No limit" nil)
865 (integer :tag "Maximum level")))
867 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
868 "Names of drawers. Drawers are not opened by cycling on the headline above.
869 Drawers only open with a TAB on the drawer line itself. A drawer looks like
870 this:
871 :DRAWERNAME:
872 .....
873 :END:
874 The drawer \"PROPERTIES\" is special for capturing properties through
875 the property API.
877 Drawers can be defined on the per-file basis with a line like:
879 #+DRAWERS: HIDDEN STATE PROPERTIES"
880 :group 'org-structure
881 :group 'org-cycle
882 :type '(repeat (string :tag "Drawer Name")))
884 (defcustom org-hide-block-startup nil
885 "Non-nil means entering Org-mode will fold all blocks.
886 This can also be set in on a per-file basis with
888 #+STARTUP: hideblocks
889 #+STARTUP: showblocks"
890 :group 'org-startup
891 :group 'org-cycle
892 :type 'boolean)
894 (defcustom org-cycle-global-at-bob nil
895 "Cycle globally if cursor is at beginning of buffer and not at a headline.
896 This makes it possible to do global cycling without having to use S-TAB or
897 \\[universal-argument] TAB. For this special case to work, the first line \
898 of the buffer
899 must not be a headline - it may be empty or some other text. When used in
900 this way, `org-cycle-hook' is disables temporarily, to make sure the
901 cursor stays at the beginning of the buffer.
902 When this option is nil, don't do anything special at the beginning
903 of the buffer."
904 :group 'org-cycle
905 :type 'boolean)
907 (defcustom org-cycle-level-after-item/entry-creation t
908 "Non-nil means cycle entry level or item indentation in new empty entries.
910 When the cursor is at the end of an empty headline, i.e with only stars
911 and maybe a TODO keyword, TAB will then switch the entry to become a child,
912 and then all possible ancestor states, before returning to the original state.
913 This makes data entry extremely fast: M-RET to create a new headline,
914 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
916 When the cursor is at the end of an empty plain list item, one TAB will
917 make it a subitem, two or more tabs will back up to make this an item
918 higher up in the item hierarchy."
919 :group 'org-cycle
920 :type 'boolean)
922 (defcustom org-cycle-emulate-tab t
923 "Where should `org-cycle' emulate TAB.
924 nil Never
925 white Only in completely white lines
926 whitestart Only at the beginning of lines, before the first non-white char
927 t Everywhere except in headlines
928 exc-hl-bol Everywhere except at the start of a headline
929 If TAB is used in a place where it does not emulate TAB, the current subtree
930 visibility is cycled."
931 :group 'org-cycle
932 :type '(choice (const :tag "Never" nil)
933 (const :tag "Only in completely white lines" white)
934 (const :tag "Before first char in a line" whitestart)
935 (const :tag "Everywhere except in headlines" t)
936 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
939 (defcustom org-cycle-separator-lines 2
940 "Number of empty lines needed to keep an empty line between collapsed trees.
941 If you leave an empty line between the end of a subtree and the following
942 headline, this empty line is hidden when the subtree is folded.
943 Org-mode will leave (exactly) one empty line visible if the number of
944 empty lines is equal or larger to the number given in this variable.
945 So the default 2 means at least 2 empty lines after the end of a subtree
946 are needed to produce free space between a collapsed subtree and the
947 following headline.
949 If the number is negative, and the number of empty lines is at least -N,
950 all empty lines are shown.
952 Special case: when 0, never leave empty lines in collapsed view."
953 :group 'org-cycle
954 :type 'integer)
955 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
957 (defcustom org-pre-cycle-hook nil
958 "Hook that is run before visibility cycling is happening.
959 The function(s) in this hook must accept a single argument which indicates
960 the new state that will be set right after running this hook. The
961 argument is a symbol. Before a global state change, it can have the values
962 `overview', `content', or `all'. Before a local state change, it can have
963 the values `folded', `children', or `subtree'."
964 :group 'org-cycle
965 :type 'hook)
967 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
968 org-cycle-hide-drawers
969 org-cycle-show-empty-lines
970 org-optimize-window-after-visibility-change)
971 "Hook that is run after `org-cycle' has changed the buffer visibility.
972 The function(s) in this hook must accept a single argument which indicates
973 the new state that was set by the most recent `org-cycle' command. The
974 argument is a symbol. After a global state change, it can have the values
975 `overview', `content', or `all'. After a local state change, it can have
976 the values `folded', `children', or `subtree'."
977 :group 'org-cycle
978 :type 'hook)
980 (defgroup org-edit-structure nil
981 "Options concerning structure editing in Org-mode."
982 :tag "Org Edit Structure"
983 :group 'org-structure)
985 (defcustom org-odd-levels-only nil
986 "Non-nil means skip even levels and only use odd levels for the outline.
987 This has the effect that two stars are being added/taken away in
988 promotion/demotion commands. It also influences how levels are
989 handled by the exporters.
990 Changing it requires restart of `font-lock-mode' to become effective
991 for fontification also in regions already fontified.
992 You may also set this on a per-file basis by adding one of the following
993 lines to the buffer:
995 #+STARTUP: odd
996 #+STARTUP: oddeven"
997 :group 'org-edit-structure
998 :group 'org-appearance
999 :type 'boolean)
1001 (defcustom org-adapt-indentation t
1002 "Non-nil means adapt indentation to outline node level.
1004 When this variable is set, Org assumes that you write outlines by
1005 indenting text in each node to align with the headline (after the stars).
1006 The following issues are influenced by this variable:
1008 - When this is set and the *entire* text in an entry is indented, the
1009 indentation is increased by one space in a demotion command, and
1010 decreased by one in a promotion command. If any line in the entry
1011 body starts with text at column 0, indentation is not changed at all.
1013 - Property drawers and planning information is inserted indented when
1014 this variable s set. When nil, they will not be indented.
1016 - TAB indents a line relative to context. The lines below a headline
1017 will be indented when this variable is set.
1019 Note that this is all about true indentation, by adding and removing
1020 space characters. See also `org-indent.el' which does level-dependent
1021 indentation in a virtual way, i.e. at display time in Emacs."
1022 :group 'org-edit-structure
1023 :type 'boolean)
1025 (defcustom org-special-ctrl-a/e nil
1026 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1028 When t, `C-a' will bring back the cursor to the beginning of the
1029 headline text, i.e. after the stars and after a possible TODO
1030 keyword. In an item, this will be the position after bullet and
1031 check-box, if any. When the cursor is already at that position,
1032 another `C-a' will bring it to the beginning of the line.
1034 `C-e' will jump to the end of the headline, ignoring the presence
1035 of tags in the headline. A second `C-e' will then jump to the
1036 true end of the line, after any tags. This also means that, when
1037 this variable is non-nil, `C-e' also will never jump beyond the
1038 end of the heading of a folded section, i.e. not after the
1039 ellipses.
1041 When set to the symbol `reversed', the first `C-a' or `C-e' works
1042 normally, going to the true line boundary first. Only a directly
1043 following, identical keypress will bring the cursor to the
1044 special positions.
1046 This may also be a cons cell where the behavior for `C-a' and
1047 `C-e' is set separately."
1048 :group 'org-edit-structure
1049 :type '(choice
1050 (const :tag "off" nil)
1051 (const :tag "on: after stars/bullet and before tags first" t)
1052 (const :tag "reversed: true line boundary first" reversed)
1053 (cons :tag "Set C-a and C-e separately"
1054 (choice :tag "Special C-a"
1055 (const :tag "off" nil)
1056 (const :tag "on: after stars/bullet first" t)
1057 (const :tag "reversed: before stars/bullet first" reversed))
1058 (choice :tag "Special C-e"
1059 (const :tag "off" nil)
1060 (const :tag "on: before tags first" t)
1061 (const :tag "reversed: after tags first" reversed)))))
1062 (if (fboundp 'defvaralias)
1063 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1065 (defcustom org-special-ctrl-k nil
1066 "Non-nil means `C-k' will behave specially in headlines.
1067 When nil, `C-k' will call the default `kill-line' command.
1068 When t, the following will happen while the cursor is in the headline:
1070 - When the cursor is at the beginning of a headline, kill the entire
1071 line and possible the folded subtree below the line.
1072 - When in the middle of the headline text, kill the headline up to the tags.
1073 - When after the headline text, kill the tags."
1074 :group 'org-edit-structure
1075 :type 'boolean)
1077 (defcustom org-ctrl-k-protect-subtree nil
1078 "Non-nil means, do not delete a hidden subtree with C-k.
1079 When set to the symbol `error', simply throw an error when C-k is
1080 used to kill (part-of) a headline that has hidden text behind it.
1081 Any other non-nil value will result in a query to the user, if it is
1082 OK to kill that hidden subtree. When nil, kill without remorse."
1083 :group 'org-edit-structure
1084 :version "24.1"
1085 :type '(choice
1086 (const :tag "Do not protect hidden subtrees" nil)
1087 (const :tag "Protect hidden subtrees with a security query" t)
1088 (const :tag "Never kill a hidden subtree with C-k" error)))
1090 (defcustom org-catch-invisible-edits nil
1091 "Check if in invisible region before inserting or deleting a character.
1092 Valid values are:
1094 nil Do not check, so just do invisible edits.
1095 error Throw an error and do nothing.
1096 show Make point visible, and do the requested edit.
1097 show-and-error Make point visible, then throw an error and abort the edit.
1098 smart Make point visible, and do insertion/deletion if it is
1099 adjacent to visible text and the change feels predictable.
1100 Never delete a previously invisible character or add in the
1101 middle or right after an invisible region. Basically, this
1102 allows insertion and backward-delete right before ellipses.
1103 FIXME: maybe in this case we should not even show?"
1104 :group 'org-edit-structure
1105 :version "24.1"
1106 :type '(choice
1107 (const :tag "Do not check" nil)
1108 (const :tag "Throw error when trying to edit" error)
1109 (const :tag "Unhide, but do not do the edit" show-and-error)
1110 (const :tag "Show invisible part and do the edit" show)
1111 (const :tag "Be smart and do the right thing" smart)))
1113 (defcustom org-yank-folded-subtrees t
1114 "Non-nil means when yanking subtrees, fold them.
1115 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1116 it starts with a heading and all other headings in it are either children
1117 or siblings, then fold all the subtrees. However, do this only if no
1118 text after the yank would be swallowed into a folded tree by this action."
1119 :group 'org-edit-structure
1120 :type 'boolean)
1122 (defcustom org-yank-adjusted-subtrees nil
1123 "Non-nil means when yanking subtrees, adjust the level.
1124 With this setting, `org-paste-subtree' is used to insert the subtree, see
1125 this function for details."
1126 :group 'org-edit-structure
1127 :type 'boolean)
1129 (defcustom org-M-RET-may-split-line '((default . t))
1130 "Non-nil means M-RET will split the line at the cursor position.
1131 When nil, it will go to the end of the line before making a
1132 new line.
1133 You may also set this option in a different way for different
1134 contexts. Valid contexts are:
1136 headline when creating a new headline
1137 item when creating a new item
1138 table in a table field
1139 default the value to be used for all contexts not explicitly
1140 customized"
1141 :group 'org-structure
1142 :group 'org-table
1143 :type '(choice
1144 (const :tag "Always" t)
1145 (const :tag "Never" nil)
1146 (repeat :greedy t :tag "Individual contexts"
1147 (cons
1148 (choice :tag "Context"
1149 (const headline)
1150 (const item)
1151 (const table)
1152 (const default))
1153 (boolean)))))
1156 (defcustom org-insert-heading-respect-content nil
1157 "Non-nil means insert new headings after the current subtree.
1158 When nil, the new heading is created directly after the current line.
1159 The commands \\[org-insert-heading-respect-content] and
1160 \\[org-insert-todo-heading-respect-content] turn this variable on
1161 for the duration of the command."
1162 :group 'org-structure
1163 :type 'boolean)
1165 (defcustom org-blank-before-new-entry '((heading . auto)
1166 (plain-list-item . auto))
1167 "Should `org-insert-heading' leave a blank line before new heading/item?
1168 The value is an alist, with `heading' and `plain-list-item' as CAR,
1169 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1170 which case Org will look at the surrounding headings/items and try to
1171 make an intelligent decision whether to insert a blank line or not.
1173 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1174 set, the setting here is ignored and no empty line is inserted, to avoid
1175 breaking the list structure."
1176 :group 'org-edit-structure
1177 :type '(list
1178 (cons (const heading)
1179 (choice (const :tag "Never" nil)
1180 (const :tag "Always" t)
1181 (const :tag "Auto" auto)))
1182 (cons (const plain-list-item)
1183 (choice (const :tag "Never" nil)
1184 (const :tag "Always" t)
1185 (const :tag "Auto" auto)))))
1187 (defcustom org-insert-heading-hook nil
1188 "Hook being run after inserting a new heading."
1189 :group 'org-edit-structure
1190 :type 'hook)
1192 (defcustom org-enable-fixed-width-editor t
1193 "Non-nil means lines starting with \":\" are treated as fixed-width.
1194 This currently only means they are never auto-wrapped.
1195 When nil, such lines will be treated like ordinary lines.
1196 See also the QUOTE keyword."
1197 :group 'org-edit-structure
1198 :type 'boolean)
1200 (defcustom org-goto-auto-isearch t
1201 "Non-nil means typing characters in `org-goto' starts incremental search."
1202 :group 'org-edit-structure
1203 :type 'boolean)
1205 (defgroup org-sparse-trees nil
1206 "Options concerning sparse trees in Org-mode."
1207 :tag "Org Sparse Trees"
1208 :group 'org-structure)
1210 (defcustom org-highlight-sparse-tree-matches t
1211 "Non-nil means highlight all matches that define a sparse tree.
1212 The highlights will automatically disappear the next time the buffer is
1213 changed by an edit command."
1214 :group 'org-sparse-trees
1215 :type 'boolean)
1217 (defcustom org-remove-highlights-with-change t
1218 "Non-nil means any change to the buffer will remove temporary highlights.
1219 Such highlights are created by `org-occur' and `org-clock-display'.
1220 When nil, `C-c C-c needs to be used to get rid of the highlights.
1221 The highlights created by `org-preview-latex-fragment' always need
1222 `C-c C-c' to be removed."
1223 :group 'org-sparse-trees
1224 :group 'org-time
1225 :type 'boolean)
1228 (defcustom org-occur-hook '(org-first-headline-recenter)
1229 "Hook that is run after `org-occur' has constructed a sparse tree.
1230 This can be used to recenter the window to show as much of the structure
1231 as possible."
1232 :group 'org-sparse-trees
1233 :type 'hook)
1235 (defgroup org-imenu-and-speedbar nil
1236 "Options concerning imenu and speedbar in Org-mode."
1237 :tag "Org Imenu and Speedbar"
1238 :group 'org-structure)
1240 (defcustom org-imenu-depth 2
1241 "The maximum level for Imenu access to Org-mode headlines.
1242 This also applied for speedbar access."
1243 :group 'org-imenu-and-speedbar
1244 :type 'integer)
1246 (defgroup org-table nil
1247 "Options concerning tables in Org-mode."
1248 :tag "Org Table"
1249 :group 'org)
1251 (defcustom org-enable-table-editor 'optimized
1252 "Non-nil means lines starting with \"|\" are handled by the table editor.
1253 When nil, such lines will be treated like ordinary lines.
1255 When equal to the symbol `optimized', the table editor will be optimized to
1256 do the following:
1257 - Automatic overwrite mode in front of whitespace in table fields.
1258 This makes the structure of the table stay in tact as long as the edited
1259 field does not exceed the column width.
1260 - Minimize the number of realigns. Normally, the table is aligned each time
1261 TAB or RET are pressed to move to another field. With optimization this
1262 happens only if changes to a field might have changed the column width.
1263 Optimization requires replacing the functions `self-insert-command',
1264 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1265 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1266 very good at guessing when a re-align will be necessary, but you can always
1267 force one with \\[org-ctrl-c-ctrl-c].
1269 If you would like to use the optimized version in Org-mode, but the
1270 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1272 This variable can be used to turn on and off the table editor during a session,
1273 but in order to toggle optimization, a restart is required.
1275 See also the variable `org-table-auto-blank-field'."
1276 :group 'org-table
1277 :type '(choice
1278 (const :tag "off" nil)
1279 (const :tag "on" t)
1280 (const :tag "on, optimized" optimized)))
1282 (defcustom org-self-insert-cluster-for-undo t
1283 "Non-nil means cluster self-insert commands for undo when possible.
1284 If this is set, then, like in the Emacs command loop, 20 consecutive
1285 characters will be undone together.
1286 This is configurable, because there is some impact on typing performance."
1287 :group 'org-table
1288 :type 'boolean)
1290 (defcustom org-table-tab-recognizes-table.el t
1291 "Non-nil means TAB will automatically notice a table.el table.
1292 When it sees such a table, it moves point into it and - if necessary -
1293 calls `table-recognize-table'."
1294 :group 'org-table-editing
1295 :type 'boolean)
1297 (defgroup org-link nil
1298 "Options concerning links in Org-mode."
1299 :tag "Org Link"
1300 :group 'org)
1302 (defvar org-link-abbrev-alist-local nil
1303 "Buffer-local version of `org-link-abbrev-alist', which see.
1304 The value of this is taken from the #+LINK lines.")
1305 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1307 (defcustom org-link-abbrev-alist nil
1308 "Alist of link abbreviations.
1309 The car of each element is a string, to be replaced at the start of a link.
1310 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1311 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1313 [[linkkey:tag][description]]
1315 The 'linkkey' must be a word word, starting with a letter, followed
1316 by letters, numbers, '-' or '_'.
1318 If REPLACE is a string, the tag will simply be appended to create the link.
1319 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1320 the placeholder \"%h\" will cause a url-encoded version of the tag to
1321 be inserted at that point (see the function `url-hexify-string').
1323 REPLACE may also be a function that will be called with the tag as the
1324 only argument to create the link, which should be returned as a string.
1326 See the manual for examples."
1327 :group 'org-link
1328 :type '(repeat
1329 (cons
1330 (string :tag "Protocol")
1331 (choice
1332 (string :tag "Format")
1333 (function)))))
1335 (defcustom org-descriptive-links t
1336 "Non-nil means Org will display descriptive links.
1337 E.g. [[http://orgmode.org][Org website]] will be displayed as
1338 \"Org Website\", hiding the link itself and just displaying its
1339 description. When set to `nil', Org will display the full links
1340 literally.
1342 You can interactively set the value of this variable by calling
1343 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1344 :group 'org-link
1345 :type 'boolean)
1347 (defcustom org-link-file-path-type 'adaptive
1348 "How the path name in file links should be stored.
1349 Valid values are:
1351 relative Relative to the current directory, i.e. the directory of the file
1352 into which the link is being inserted.
1353 absolute Absolute path, if possible with ~ for home directory.
1354 noabbrev Absolute path, no abbreviation of home directory.
1355 adaptive Use relative path for files in the current directory and sub-
1356 directories of it. For other files, use an absolute path."
1357 :group 'org-link
1358 :type '(choice
1359 (const relative)
1360 (const absolute)
1361 (const noabbrev)
1362 (const adaptive)))
1364 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1365 "Types of links that should be activated in Org-mode files.
1366 This is a list of symbols, each leading to the activation of a certain link
1367 type. In principle, it does not hurt to turn on most link types - there may
1368 be a small gain when turning off unused link types. The types are:
1370 bracket The recommended [[link][description]] or [[link]] links with hiding.
1371 angle Links in angular brackets that may contain whitespace like
1372 <bbdb:Carsten Dominik>.
1373 plain Plain links in normal text, no whitespace, like http://google.com.
1374 radio Text that is matched by a radio target, see manual for details.
1375 tag Tag settings in a headline (link to tag search).
1376 date Time stamps (link to calendar).
1377 footnote Footnote labels.
1379 Changing this variable requires a restart of Emacs to become effective."
1380 :group 'org-link
1381 :type '(set :greedy t
1382 (const :tag "Double bracket links" bracket)
1383 (const :tag "Angular bracket links" angle)
1384 (const :tag "Plain text links" plain)
1385 (const :tag "Radio target matches" radio)
1386 (const :tag "Tags" tag)
1387 (const :tag "Timestamps" date)
1388 (const :tag "Footnotes" footnote)))
1390 (defcustom org-make-link-description-function nil
1391 "Function to use to generate link descriptions from links.
1392 If nil the link location will be used. This function must take
1393 two parameters; the first is the link and the second the
1394 description `org-insert-link' has generated, and should return the
1395 description to use."
1396 :group 'org-link
1397 :type 'function)
1399 (defgroup org-link-store nil
1400 "Options concerning storing links in Org-mode."
1401 :tag "Org Store Link"
1402 :group 'org-link)
1404 (defcustom org-email-link-description-format "Email %c: %.30s"
1405 "Format of the description part of a link to an email or usenet message.
1406 The following %-escapes will be replaced by corresponding information:
1408 %F full \"From\" field
1409 %f name, taken from \"From\" field, address if no name
1410 %T full \"To\" field
1411 %t first name in \"To\" field, address if no name
1412 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1413 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1414 %s subject
1415 %d date
1416 %m message-id.
1418 You may use normal field width specification between the % and the letter.
1419 This is for example useful to limit the length of the subject.
1421 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1422 :group 'org-link-store
1423 :type 'string)
1425 (defcustom org-from-is-user-regexp
1426 (let (r1 r2)
1427 (when (and user-mail-address (not (string= user-mail-address "")))
1428 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1429 (when (and user-full-name (not (string= user-full-name "")))
1430 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1431 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1432 "Regexp matched against the \"From:\" header of an email or usenet message.
1433 It should match if the message is from the user him/herself."
1434 :group 'org-link-store
1435 :type 'regexp)
1437 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1438 "Non-nil means storing a link to an Org file will use entry IDs.
1440 Note that before this variable is even considered, org-id must be loaded,
1441 so please customize `org-modules' and turn it on.
1443 The variable can have the following values:
1445 t Create an ID if needed to make a link to the current entry.
1447 create-if-interactive
1448 If `org-store-link' is called directly (interactively, as a user
1449 command), do create an ID to support the link. But when doing the
1450 job for remember, only use the ID if it already exists. The
1451 purpose of this setting is to avoid proliferation of unwanted
1452 IDs, just because you happen to be in an Org file when you
1453 call `org-remember' that automatically and preemptively
1454 creates a link. If you do want to get an ID link in a remember
1455 template to an entry not having an ID, create it first by
1456 explicitly creating a link to it, using `C-c C-l' first.
1458 create-if-interactive-and-no-custom-id
1459 Like create-if-interactive, but do not create an ID if there is
1460 a CUSTOM_ID property defined in the entry. This is the default.
1462 use-existing
1463 Use existing ID, do not create one.
1465 nil Never use an ID to make a link, instead link using a text search for
1466 the headline text."
1467 :group 'org-link-store
1468 :type '(choice
1469 (const :tag "Create ID to make link" t)
1470 (const :tag "Create if storing link interactively"
1471 create-if-interactive)
1472 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1473 create-if-interactive-and-no-custom-id)
1474 (const :tag "Only use existing" use-existing)
1475 (const :tag "Do not use ID to create link" nil)))
1477 (defcustom org-context-in-file-links t
1478 "Non-nil means file links from `org-store-link' contain context.
1479 A search string will be added to the file name with :: as separator and
1480 used to find the context when the link is activated by the command
1481 `org-open-at-point'. When this option is t, the entire active region
1482 will be placed in the search string of the file link. If set to a
1483 positive integer, only the first n lines of context will be stored.
1485 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1486 negates this setting for the duration of the command."
1487 :group 'org-link-store
1488 :type '(choice boolean integer))
1490 (defcustom org-keep-stored-link-after-insertion nil
1491 "Non-nil means keep link in list for entire session.
1493 The command `org-store-link' adds a link pointing to the current
1494 location to an internal list. These links accumulate during a session.
1495 The command `org-insert-link' can be used to insert links into any
1496 Org-mode file (offering completion for all stored links). When this
1497 option is nil, every link which has been inserted once using \\[org-insert-link]
1498 will be removed from the list, to make completing the unused links
1499 more efficient."
1500 :group 'org-link-store
1501 :type 'boolean)
1503 (defgroup org-link-follow nil
1504 "Options concerning following links in Org-mode."
1505 :tag "Org Follow Link"
1506 :group 'org-link)
1508 (defcustom org-link-translation-function nil
1509 "Function to translate links with different syntax to Org syntax.
1510 This can be used to translate links created for example by the Planner
1511 or emacs-wiki packages to Org syntax.
1512 The function must accept two parameters, a TYPE containing the link
1513 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1514 which is everything after the link protocol. It should return a cons
1515 with possibly modified values of type and path.
1516 Org contains a function for this, so if you set this variable to
1517 `org-translate-link-from-planner', you should be able follow many
1518 links created by planner."
1519 :group 'org-link-follow
1520 :type 'function)
1522 (defcustom org-follow-link-hook nil
1523 "Hook that is run after a link has been followed."
1524 :group 'org-link-follow
1525 :type 'hook)
1527 (defcustom org-tab-follows-link nil
1528 "Non-nil means on links TAB will follow the link.
1529 Needs to be set before org.el is loaded.
1530 This really should not be used, it does not make sense, and the
1531 implementation is bad."
1532 :group 'org-link-follow
1533 :type 'boolean)
1535 (defcustom org-return-follows-link nil
1536 "Non-nil means on links RET will follow the link."
1537 :group 'org-link-follow
1538 :type 'boolean)
1540 (defcustom org-mouse-1-follows-link
1541 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1542 "Non-nil means mouse-1 on a link will follow the link.
1543 A longer mouse click will still set point. Does not work on XEmacs.
1544 Needs to be set before org.el is loaded."
1545 :group 'org-link-follow
1546 :type 'boolean)
1548 (defcustom org-mark-ring-length 4
1549 "Number of different positions to be recorded in the ring.
1550 Changing this requires a restart of Emacs to work correctly."
1551 :group 'org-link-follow
1552 :type 'integer)
1554 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1555 "Non-nil means internal links in Org files must exactly match a headline.
1556 When nil, the link search tries to match a phrase with all words
1557 in the search text."
1558 :group 'org-link-follow
1559 :version "24.1"
1560 :type '(choice
1561 (const :tag "Use fuzzy text search" nil)
1562 (const :tag "Match only exact headline" t)
1563 (const :tag "Match exact headline or query to create it"
1564 query-to-create)))
1566 (defcustom org-link-frame-setup
1567 '((vm . vm-visit-folder-other-frame)
1568 (vm-imap . vm-visit-imap-folder-other-frame)
1569 (gnus . org-gnus-no-new-news)
1570 (file . find-file-other-window)
1571 (wl . wl-other-frame))
1572 "Setup the frame configuration for following links.
1573 When following a link with Emacs, it may often be useful to display
1574 this link in another window or frame. This variable can be used to
1575 set this up for the different types of links.
1576 For VM, use any of
1577 `vm-visit-folder'
1578 `vm-visit-folder-other-window'
1579 `vm-visit-folder-other-frame'
1580 For Gnus, use any of
1581 `gnus'
1582 `gnus-other-frame'
1583 `org-gnus-no-new-news'
1584 For FILE, use any of
1585 `find-file'
1586 `find-file-other-window'
1587 `find-file-other-frame'
1588 For Wanderlust use any of
1589 `wl'
1590 `wl-other-frame'
1591 For the calendar, use the variable `calendar-setup'.
1592 For BBDB, it is currently only possible to display the matches in
1593 another window."
1594 :group 'org-link-follow
1595 :type '(list
1596 (cons (const vm)
1597 (choice
1598 (const vm-visit-folder)
1599 (const vm-visit-folder-other-window)
1600 (const vm-visit-folder-other-frame)))
1601 (cons (const gnus)
1602 (choice
1603 (const gnus)
1604 (const gnus-other-frame)
1605 (const org-gnus-no-new-news)))
1606 (cons (const file)
1607 (choice
1608 (const find-file)
1609 (const find-file-other-window)
1610 (const find-file-other-frame)))
1611 (cons (const wl)
1612 (choice
1613 (const wl)
1614 (const wl-other-frame)))))
1616 (defcustom org-display-internal-link-with-indirect-buffer nil
1617 "Non-nil means use indirect buffer to display infile links.
1618 Activating internal links (from one location in a file to another location
1619 in the same file) normally just jumps to the location. When the link is
1620 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1621 is displayed in
1622 another window. When this option is set, the other window actually displays
1623 an indirect buffer clone of the current buffer, to avoid any visibility
1624 changes to the current buffer."
1625 :group 'org-link-follow
1626 :type 'boolean)
1628 (defcustom org-open-non-existing-files nil
1629 "Non-nil means `org-open-file' will open non-existing files.
1630 When nil, an error will be generated.
1631 This variable applies only to external applications because they
1632 might choke on non-existing files. If the link is to a file that
1633 will be opened in Emacs, the variable is ignored."
1634 :group 'org-link-follow
1635 :type 'boolean)
1637 (defcustom org-open-directory-means-index-dot-org nil
1638 "Non-nil means a link to a directory really means to index.org.
1639 When nil, following a directory link will run dired or open a finder/explorer
1640 window on that directory."
1641 :group 'org-link-follow
1642 :type 'boolean)
1644 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1645 "Function and arguments to call for following mailto links.
1646 This is a list with the first element being a Lisp function, and the
1647 remaining elements being arguments to the function. In string arguments,
1648 %a will be replaced by the address, and %s will be replaced by the subject
1649 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1650 :group 'org-link-follow
1651 :type '(choice
1652 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1653 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1654 (const :tag "message-mail" (message-mail "%a" "%s"))
1655 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1657 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1658 "Non-nil means ask for confirmation before executing shell links.
1659 Shell links can be dangerous: just think about a link
1661 [[shell:rm -rf ~/*][Google Search]]
1663 This link would show up in your Org-mode document as \"Google Search\",
1664 but really it would remove your entire home directory.
1665 Therefore we advise against setting this variable to nil.
1666 Just change it to `y-or-n-p' if you want to confirm with a
1667 single keystroke rather than having to type \"yes\"."
1668 :group 'org-link-follow
1669 :type '(choice
1670 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1671 (const :tag "with y-or-n (faster)" y-or-n-p)
1672 (const :tag "no confirmation (dangerous)" nil)))
1673 (put 'org-confirm-shell-link-function
1674 'safe-local-variable
1675 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1677 (defcustom org-confirm-shell-link-not-regexp ""
1678 "A regexp to skip confirmation for shell links."
1679 :group 'org-link-follow
1680 :version "24.1"
1681 :type 'regexp)
1683 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1684 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1685 Elisp links can be dangerous: just think about a link
1687 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1689 This link would show up in your Org-mode document as \"Google Search\",
1690 but really it would remove your entire home directory.
1691 Therefore we advise against setting this variable to nil.
1692 Just change it to `y-or-n-p' if you want to confirm with a
1693 single keystroke rather than having to type \"yes\"."
1694 :group 'org-link-follow
1695 :type '(choice
1696 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1697 (const :tag "with y-or-n (faster)" y-or-n-p)
1698 (const :tag "no confirmation (dangerous)" nil)))
1699 (put 'org-confirm-shell-link-function
1700 'safe-local-variable
1701 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1703 (defcustom org-confirm-elisp-link-not-regexp ""
1704 "A regexp to skip confirmation for Elisp links."
1705 :group 'org-link-follow
1706 :version "24.1"
1707 :type 'regexp)
1709 (defconst org-file-apps-defaults-gnu
1710 '((remote . emacs)
1711 (system . mailcap)
1712 (t . mailcap))
1713 "Default file applications on a UNIX or GNU/Linux system.
1714 See `org-file-apps'.")
1716 (defconst org-file-apps-defaults-macosx
1717 '((remote . emacs)
1718 (t . "open %s")
1719 (system . "open %s")
1720 ("ps.gz" . "gv %s")
1721 ("eps.gz" . "gv %s")
1722 ("dvi" . "xdvi %s")
1723 ("fig" . "xfig %s"))
1724 "Default file applications on a MacOS X system.
1725 The system \"open\" is known as a default, but we use X11 applications
1726 for some files for which the OS does not have a good default.
1727 See `org-file-apps'.")
1729 (defconst org-file-apps-defaults-windowsnt
1730 (list
1731 '(remote . emacs)
1732 (cons t
1733 (list (if (featurep 'xemacs)
1734 'mswindows-shell-execute
1735 'w32-shell-execute)
1736 "open" 'file))
1737 (cons 'system
1738 (list (if (featurep 'xemacs)
1739 'mswindows-shell-execute
1740 'w32-shell-execute)
1741 "open" 'file)))
1742 "Default file applications on a Windows NT system.
1743 The system \"open\" is used for most files.
1744 See `org-file-apps'.")
1746 (defcustom org-file-apps
1748 (auto-mode . emacs)
1749 ("\\.mm\\'" . default)
1750 ("\\.x?html?\\'" . default)
1751 ("\\.pdf\\'" . default)
1753 "External applications for opening `file:path' items in a document.
1754 Org-mode uses system defaults for different file types, but
1755 you can use this variable to set the application for a given file
1756 extension. The entries in this list are cons cells where the car identifies
1757 files and the cdr the corresponding command. Possible values for the
1758 file identifier are
1759 \"string\" A string as a file identifier can be interpreted in different
1760 ways, depending on its contents:
1762 - Alphanumeric characters only:
1763 Match links with this file extension.
1764 Example: (\"pdf\" . \"evince %s\")
1765 to open PDFs with evince.
1767 - Regular expression: Match links where the
1768 filename matches the regexp. If you want to
1769 use groups here, use shy groups.
1771 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1772 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1773 to open *.html and *.xhtml with firefox.
1775 - Regular expression which contains (non-shy) groups:
1776 Match links where the whole link, including \"::\", and
1777 anything after that, matches the regexp.
1778 In a custom command string, %1, %2, etc. are replaced with
1779 the parts of the link that were matched by the groups.
1780 For backwards compatibility, if a command string is given
1781 that does not use any of the group matches, this case is
1782 handled identically to the second one (i.e. match against
1783 file name only).
1784 In a custom lisp form, you can access the group matches with
1785 (match-string n link).
1787 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1788 to open [[file:document.pdf::5]] with evince at page 5.
1790 `directory' Matches a directory
1791 `remote' Matches a remote file, accessible through tramp or efs.
1792 Remote files most likely should be visited through Emacs
1793 because external applications cannot handle such paths.
1794 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1795 so all files Emacs knows how to handle. Using this with
1796 command `emacs' will open most files in Emacs. Beware that this
1797 will also open html files inside Emacs, unless you add
1798 (\"html\" . default) to the list as well.
1799 t Default for files not matched by any of the other options.
1800 `system' The system command to open files, like `open' on Windows
1801 and Mac OS X, and mailcap under GNU/Linux. This is the command
1802 that will be selected if you call `C-c C-o' with a double
1803 \\[universal-argument] \\[universal-argument] prefix.
1805 Possible values for the command are:
1806 `emacs' The file will be visited by the current Emacs process.
1807 `default' Use the default application for this file type, which is the
1808 association for t in the list, most likely in the system-specific
1809 part.
1810 This can be used to overrule an unwanted setting in the
1811 system-specific variable.
1812 `system' Use the system command for opening files, like \"open\".
1813 This command is specified by the entry whose car is `system'.
1814 Most likely, the system-specific version of this variable
1815 does define this command, but you can overrule/replace it
1816 here.
1817 string A command to be executed by a shell; %s will be replaced
1818 by the path to the file.
1819 sexp A Lisp form which will be evaluated. The file path will
1820 be available in the Lisp variable `file'.
1821 For more examples, see the system specific constants
1822 `org-file-apps-defaults-macosx'
1823 `org-file-apps-defaults-windowsnt'
1824 `org-file-apps-defaults-gnu'."
1825 :group 'org-link-follow
1826 :type '(repeat
1827 (cons (choice :value ""
1828 (string :tag "Extension")
1829 (const :tag "System command to open files" system)
1830 (const :tag "Default for unrecognized files" t)
1831 (const :tag "Remote file" remote)
1832 (const :tag "Links to a directory" directory)
1833 (const :tag "Any files that have Emacs modes"
1834 auto-mode))
1835 (choice :value ""
1836 (const :tag "Visit with Emacs" emacs)
1837 (const :tag "Use default" default)
1838 (const :tag "Use the system command" system)
1839 (string :tag "Command")
1840 (sexp :tag "Lisp form")))))
1844 (defgroup org-refile nil
1845 "Options concerning refiling entries in Org-mode."
1846 :tag "Org Refile"
1847 :group 'org)
1849 (defcustom org-directory "~/org"
1850 "Directory with org files.
1851 This is just a default location to look for Org files. There is no need
1852 at all to put your files into this directory. It is only used in the
1853 following situations:
1855 1. When a remember template specifies a target file that is not an
1856 absolute path. The path will then be interpreted relative to
1857 `org-directory'
1858 2. When a remember note is filed away in an interactive way (when exiting the
1859 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1860 with `org-directory' as the default path."
1861 :group 'org-refile
1862 :group 'org-remember
1863 :type 'directory)
1865 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1866 "Default target for storing notes.
1867 Used as a fall back file for org-remember.el and org-capture.el, for
1868 templates that do not specify a target file."
1869 :group 'org-refile
1870 :group 'org-remember
1871 :type '(choice
1872 (const :tag "Default from remember-data-file" nil)
1873 file))
1875 (defcustom org-goto-interface 'outline
1876 "The default interface to be used for `org-goto'.
1877 Allowed values are:
1878 outline The interface shows an outline of the relevant file
1879 and the correct heading is found by moving through
1880 the outline or by searching with incremental search.
1881 outline-path-completion Headlines in the current buffer are offered via
1882 completion. This is the interface also used by
1883 the refile command."
1884 :group 'org-refile
1885 :type '(choice
1886 (const :tag "Outline" outline)
1887 (const :tag "Outline-path-completion" outline-path-completion)))
1889 (defcustom org-goto-max-level 5
1890 "Maximum target level when running `org-goto' with refile interface."
1891 :group 'org-refile
1892 :type 'integer)
1894 (defcustom org-reverse-note-order nil
1895 "Non-nil means store new notes at the beginning of a file or entry.
1896 When nil, new notes will be filed to the end of a file or entry.
1897 This can also be a list with cons cells of regular expressions that
1898 are matched against file names, and values."
1899 :group 'org-remember
1900 :group 'org-refile
1901 :type '(choice
1902 (const :tag "Reverse always" t)
1903 (const :tag "Reverse never" nil)
1904 (repeat :tag "By file name regexp"
1905 (cons regexp boolean))))
1907 (defcustom org-log-refile nil
1908 "Information to record when a task is refiled.
1910 Possible values are:
1912 nil Don't add anything
1913 time Add a time stamp to the task
1914 note Prompt for a note and add it with template `org-log-note-headings'
1916 This option can also be set with on a per-file-basis with
1918 #+STARTUP: nologrefile
1919 #+STARTUP: logrefile
1920 #+STARTUP: lognoterefile
1922 You can have local logging settings for a subtree by setting the LOGGING
1923 property to one or more of these keywords.
1925 When bulk-refiling from the agenda, the value `note' is forbidden and
1926 will temporarily be changed to `time'."
1927 :group 'org-refile
1928 :group 'org-progress
1929 :version "24.1"
1930 :type '(choice
1931 (const :tag "No logging" nil)
1932 (const :tag "Record timestamp" time)
1933 (const :tag "Record timestamp with note." note)))
1935 (defcustom org-refile-targets nil
1936 "Targets for refiling entries with \\[org-refile].
1937 This is a list of cons cells. Each cell contains:
1938 - a specification of the files to be considered, either a list of files,
1939 or a symbol whose function or variable value will be used to retrieve
1940 a file name or a list of file names. If you use `org-agenda-files' for
1941 that, all agenda files will be scanned for targets. Nil means consider
1942 headings in the current buffer.
1943 - A specification of how to find candidate refile targets. This may be
1944 any of:
1945 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1946 This tag has to be present in all target headlines, inheritance will
1947 not be considered.
1948 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1949 todo keyword.
1950 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1951 headlines that are refiling targets.
1952 - a cons cell (:level . N). Any headline of level N is considered a target.
1953 Note that, when `org-odd-levels-only' is set, level corresponds to
1954 order in hierarchy, not to the number of stars.
1955 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1956 Note that, when `org-odd-levels-only' is set, level corresponds to
1957 order in hierarchy, not to the number of stars.
1959 Each element of this list generates a set of possible targets.
1960 The union of these sets is presented (with completion) to
1961 the user by `org-refile'.
1963 You can set the variable `org-refile-target-verify-function' to a function
1964 to verify each headline found by the simple criteria above.
1966 When this variable is nil, all top-level headlines in the current buffer
1967 are used, equivalent to the value `((nil . (:level . 1))'."
1968 :group 'org-refile
1969 :type '(repeat
1970 (cons
1971 (choice :value org-agenda-files
1972 (const :tag "All agenda files" org-agenda-files)
1973 (const :tag "Current buffer" nil)
1974 (function) (variable) (file))
1975 (choice :tag "Identify target headline by"
1976 (cons :tag "Specific tag" (const :value :tag) (string))
1977 (cons :tag "TODO keyword" (const :value :todo) (string))
1978 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1979 (cons :tag "Level number" (const :value :level) (integer))
1980 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1982 (defcustom org-refile-target-verify-function nil
1983 "Function to verify if the headline at point should be a refile target.
1984 The function will be called without arguments, with point at the
1985 beginning of the headline. It should return t and leave point
1986 where it is if the headline is a valid target for refiling.
1988 If the target should not be selected, the function must return nil.
1989 In addition to this, it may move point to a place from where the search
1990 should be continued. For example, the function may decide that the entire
1991 subtree of the current entry should be excluded and move point to the end
1992 of the subtree."
1993 :group 'org-refile
1994 :type 'function)
1996 (defcustom org-refile-use-cache nil
1997 "Non-nil means cache refile targets to speed up the process.
1998 The cache for a particular file will be updated automatically when
1999 the buffer has been killed, or when any of the marker used for flagging
2000 refile targets no longer points at a live buffer.
2001 If you have added new entries to a buffer that might themselves be targets,
2002 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2003 find that easier, `C-u C-u C-u C-c C-w'."
2004 :group 'org-refile
2005 :version "24.1"
2006 :type 'boolean)
2008 (defcustom org-refile-use-outline-path nil
2009 "Non-nil means provide refile targets as paths.
2010 So a level 3 headline will be available as level1/level2/level3.
2012 When the value is `file', also include the file name (without directory)
2013 into the path. In this case, you can also stop the completion after
2014 the file name, to get entries inserted as top level in the file.
2016 When `full-file-path', include the full file path."
2017 :group 'org-refile
2018 :type '(choice
2019 (const :tag "Not" nil)
2020 (const :tag "Yes" t)
2021 (const :tag "Start with file name" file)
2022 (const :tag "Start with full file path" full-file-path)))
2024 (defcustom org-outline-path-complete-in-steps t
2025 "Non-nil means complete the outline path in hierarchical steps.
2026 When Org-mode uses the refile interface to select an outline path
2027 \(see variable `org-refile-use-outline-path'), the completion of
2028 the path can be done is a single go, or if can be done in steps down
2029 the headline hierarchy. Going in steps is probably the best if you
2030 do not use a special completion package like `ido' or `icicles'.
2031 However, when using these packages, going in one step can be very
2032 fast, while still showing the whole path to the entry."
2033 :group 'org-refile
2034 :type 'boolean)
2036 (defcustom org-refile-allow-creating-parent-nodes nil
2037 "Non-nil means allow to create new nodes as refile targets.
2038 New nodes are then created by adding \"/new node name\" to the completion
2039 of an existing node. When the value of this variable is `confirm',
2040 new node creation must be confirmed by the user (recommended)
2041 When nil, the completion must match an existing entry.
2043 Note that, if the new heading is not seen by the criteria
2044 listed in `org-refile-targets', multiple instances of the same
2045 heading would be created by trying again to file under the new
2046 heading."
2047 :group 'org-refile
2048 :type '(choice
2049 (const :tag "Never" nil)
2050 (const :tag "Always" t)
2051 (const :tag "Prompt for confirmation" confirm)))
2053 (defcustom org-refile-active-region-within-subtree nil
2054 "Non-nil means also refile active region within a subtree.
2056 By default `org-refile' doesn't allow refiling regions if they
2057 don't contain a set of subtrees, but it might be convenient to
2058 do so sometimes: in that case, the first line of the region is
2059 converted to a headline before refiling."
2060 :group 'org-refile
2061 :version "24.1"
2062 :type 'boolean)
2064 (defgroup org-todo nil
2065 "Options concerning TODO items in Org-mode."
2066 :tag "Org TODO"
2067 :group 'org)
2069 (defgroup org-progress nil
2070 "Options concerning Progress logging in Org-mode."
2071 :tag "Org Progress"
2072 :group 'org-time)
2074 (defvar org-todo-interpretation-widgets
2075 '((:tag "Sequence (cycling hits every state)" sequence)
2076 (:tag "Type (cycling directly to DONE)" type))
2077 "The available interpretation symbols for customizing `org-todo-keywords'.
2078 Interested libraries should add to this list.")
2080 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2081 "List of TODO entry keyword sequences and their interpretation.
2082 \\<org-mode-map>This is a list of sequences.
2084 Each sequence starts with a symbol, either `sequence' or `type',
2085 indicating if the keywords should be interpreted as a sequence of
2086 action steps, or as different types of TODO items. The first
2087 keywords are states requiring action - these states will select a headline
2088 for inclusion into the global TODO list Org-mode produces. If one of
2089 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2090 signify that no further action is necessary. If \"|\" is not found,
2091 the last keyword is treated as the only DONE state of the sequence.
2093 The command \\[org-todo] cycles an entry through these states, and one
2094 additional state where no keyword is present. For details about this
2095 cycling, see the manual.
2097 TODO keywords and interpretation can also be set on a per-file basis with
2098 the special #+SEQ_TODO and #+TYP_TODO lines.
2100 Each keyword can optionally specify a character for fast state selection
2101 \(in combination with the variable `org-use-fast-todo-selection')
2102 and specifiers for state change logging, using the same syntax
2103 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2104 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2105 indicates to record a time stamp each time this state is selected.
2107 Each keyword may also specify if a timestamp or a note should be
2108 recorded when entering or leaving the state, by adding additional
2109 characters in the parenthesis after the keyword. This looks like this:
2110 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2111 record only the time of the state change. With X and Y being either
2112 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2113 Y when leaving the state if and only if the *target* state does not
2114 define X. You may omit any of the fast-selection key or X or /Y,
2115 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2117 For backward compatibility, this variable may also be just a list
2118 of keywords - in this case the interpretation (sequence or type) will be
2119 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2120 :group 'org-todo
2121 :group 'org-keywords
2122 :type '(choice
2123 (repeat :tag "Old syntax, just keywords"
2124 (string :tag "Keyword"))
2125 (repeat :tag "New syntax"
2126 (cons
2127 (choice
2128 :tag "Interpretation"
2129 ;;Quick and dirty way to see
2130 ;;`org-todo-interpretations'. This takes the
2131 ;;place of item arguments
2132 :convert-widget
2133 (lambda (widget)
2134 (widget-put widget
2135 :args (mapcar
2136 #'(lambda (x)
2137 (widget-convert
2138 (cons 'const x)))
2139 org-todo-interpretation-widgets))
2140 widget))
2141 (repeat
2142 (string :tag "Keyword"))))))
2144 (defvar org-todo-keywords-1 nil
2145 "All TODO and DONE keywords active in a buffer.")
2146 (make-variable-buffer-local 'org-todo-keywords-1)
2147 (defvar org-todo-keywords-for-agenda nil)
2148 (defvar org-done-keywords-for-agenda nil)
2149 (defvar org-drawers-for-agenda nil)
2150 (defvar org-todo-keyword-alist-for-agenda nil)
2151 (defvar org-tag-alist-for-agenda nil)
2152 (defvar org-agenda-contributing-files nil)
2153 (defvar org-not-done-keywords nil)
2154 (make-variable-buffer-local 'org-not-done-keywords)
2155 (defvar org-done-keywords nil)
2156 (make-variable-buffer-local 'org-done-keywords)
2157 (defvar org-todo-heads nil)
2158 (make-variable-buffer-local 'org-todo-heads)
2159 (defvar org-todo-sets nil)
2160 (make-variable-buffer-local 'org-todo-sets)
2161 (defvar org-todo-log-states nil)
2162 (make-variable-buffer-local 'org-todo-log-states)
2163 (defvar org-todo-kwd-alist nil)
2164 (make-variable-buffer-local 'org-todo-kwd-alist)
2165 (defvar org-todo-key-alist nil)
2166 (make-variable-buffer-local 'org-todo-key-alist)
2167 (defvar org-todo-key-trigger nil)
2168 (make-variable-buffer-local 'org-todo-key-trigger)
2170 (defcustom org-todo-interpretation 'sequence
2171 "Controls how TODO keywords are interpreted.
2172 This variable is in principle obsolete and is only used for
2173 backward compatibility, if the interpretation of todo keywords is
2174 not given already in `org-todo-keywords'. See that variable for
2175 more information."
2176 :group 'org-todo
2177 :group 'org-keywords
2178 :type '(choice (const sequence)
2179 (const type)))
2181 (defcustom org-use-fast-todo-selection t
2182 "Non-nil means use the fast todo selection scheme with C-c C-t.
2183 This variable describes if and under what circumstances the cycling
2184 mechanism for TODO keywords will be replaced by a single-key, direct
2185 selection scheme.
2187 When nil, fast selection is never used.
2189 When the symbol `prefix', it will be used when `org-todo' is called with
2190 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2191 in an agenda buffer.
2193 When t, fast selection is used by default. In this case, the prefix
2194 argument forces cycling instead.
2196 In all cases, the special interface is only used if access keys have actually
2197 been assigned by the user, i.e. if keywords in the configuration are followed
2198 by a letter in parenthesis, like TODO(t)."
2199 :group 'org-todo
2200 :type '(choice
2201 (const :tag "Never" nil)
2202 (const :tag "By default" t)
2203 (const :tag "Only with C-u C-c C-t" prefix)))
2205 (defcustom org-provide-todo-statistics t
2206 "Non-nil means update todo statistics after insert and toggle.
2207 ALL-HEADLINES means update todo statistics by including headlines
2208 with no TODO keyword as well, counting them as not done.
2209 A list of TODO keywords means the same, but skip keywords that are
2210 not in this list.
2212 When this is set, todo statistics is updated in the parent of the
2213 current entry each time a todo state is changed."
2214 :group 'org-todo
2215 :type '(choice
2216 (const :tag "Yes, only for TODO entries" t)
2217 (const :tag "Yes, including all entries" 'all-headlines)
2218 (repeat :tag "Yes, for TODOs in this list"
2219 (string :tag "TODO keyword"))
2220 (other :tag "No TODO statistics" nil)))
2222 (defcustom org-hierarchical-todo-statistics t
2223 "Non-nil means TODO statistics covers just direct children.
2224 When nil, all entries in the subtree are considered.
2225 This has only an effect if `org-provide-todo-statistics' is set.
2226 To set this to nil for only a single subtree, use a COOKIE_DATA
2227 property and include the word \"recursive\" into the value."
2228 :group 'org-todo
2229 :type 'boolean)
2231 (defcustom org-after-todo-state-change-hook nil
2232 "Hook which is run after the state of a TODO item was changed.
2233 The new state (a string with a TODO keyword, or nil) is available in the
2234 Lisp variable `state'."
2235 :group 'org-todo
2236 :type 'hook)
2238 (defvar org-blocker-hook nil
2239 "Hook for functions that are allowed to block a state change.
2241 Each function gets as its single argument a property list, see
2242 `org-trigger-hook' for more information about this list.
2244 If any of the functions in this hook returns nil, the state change
2245 is blocked.")
2247 (defvar org-trigger-hook nil
2248 "Hook for functions that are triggered by a state change.
2250 Each function gets as its single argument a property list with at least
2251 the following elements:
2253 (:type type-of-change :position pos-at-entry-start
2254 :from old-state :to new-state)
2256 Depending on the type, more properties may be present.
2258 This mechanism is currently implemented for:
2260 TODO state changes
2261 ------------------
2262 :type todo-state-change
2263 :from previous state (keyword as a string), or nil, or a symbol
2264 'todo' or 'done', to indicate the general type of state.
2265 :to new state, like in :from")
2267 (defcustom org-enforce-todo-dependencies nil
2268 "Non-nil means undone TODO entries will block switching the parent to DONE.
2269 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2270 be blocked if any prior sibling is not yet done.
2271 Finally, if the parent is blocked because of ordered siblings of its own,
2272 the child will also be blocked."
2273 :set (lambda (var val)
2274 (set var val)
2275 (if val
2276 (add-hook 'org-blocker-hook
2277 'org-block-todo-from-children-or-siblings-or-parent)
2278 (remove-hook 'org-blocker-hook
2279 'org-block-todo-from-children-or-siblings-or-parent)))
2280 :group 'org-todo
2281 :type 'boolean)
2283 (defcustom org-enforce-todo-checkbox-dependencies nil
2284 "Non-nil means unchecked boxes will block switching the parent to DONE.
2285 When this is nil, checkboxes have no influence on switching TODO states.
2286 When non-nil, you first need to check off all check boxes before the TODO
2287 entry can be switched to DONE.
2288 This variable needs to be set before org.el is loaded, and you need to
2289 restart Emacs after a change to make the change effective. The only way
2290 to change is while Emacs is running is through the customize interface."
2291 :set (lambda (var val)
2292 (set var val)
2293 (if val
2294 (add-hook 'org-blocker-hook
2295 'org-block-todo-from-checkboxes)
2296 (remove-hook 'org-blocker-hook
2297 'org-block-todo-from-checkboxes)))
2298 :group 'org-todo
2299 :type 'boolean)
2301 (defcustom org-treat-insert-todo-heading-as-state-change nil
2302 "Non-nil means inserting a TODO heading is treated as state change.
2303 So when the command \\[org-insert-todo-heading] is used, state change
2304 logging will apply if appropriate. When nil, the new TODO item will
2305 be inserted directly, and no logging will take place."
2306 :group 'org-todo
2307 :type 'boolean)
2309 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2310 "Non-nil means switching TODO states with S-cursor counts as state change.
2311 This is the default behavior. However, setting this to nil allows a
2312 convenient way to select a TODO state and bypass any logging associated
2313 with that."
2314 :group 'org-todo
2315 :type 'boolean)
2317 (defcustom org-todo-state-tags-triggers nil
2318 "Tag changes that should be triggered by TODO state changes.
2319 This is a list. Each entry is
2321 (state-change (tag . flag) .......)
2323 State-change can be a string with a state, and empty string to indicate the
2324 state that has no TODO keyword, or it can be one of the symbols `todo'
2325 or `done', meaning any not-done or done state, respectively."
2326 :group 'org-todo
2327 :group 'org-tags
2328 :type '(repeat
2329 (cons (choice :tag "When changing to"
2330 (const :tag "Not-done state" todo)
2331 (const :tag "Done state" done)
2332 (string :tag "State"))
2333 (repeat
2334 (cons :tag "Tag action"
2335 (string :tag "Tag")
2336 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2338 (defcustom org-log-done nil
2339 "Information to record when a task moves to the DONE state.
2341 Possible values are:
2343 nil Don't add anything, just change the keyword
2344 time Add a time stamp to the task
2345 note Prompt for a note and add it with template `org-log-note-headings'
2347 This option can also be set with on a per-file-basis with
2349 #+STARTUP: nologdone
2350 #+STARTUP: logdone
2351 #+STARTUP: lognotedone
2353 You can have local logging settings for a subtree by setting the LOGGING
2354 property to one or more of these keywords."
2355 :group 'org-todo
2356 :group 'org-progress
2357 :type '(choice
2358 (const :tag "No logging" nil)
2359 (const :tag "Record CLOSED timestamp" time)
2360 (const :tag "Record CLOSED timestamp with note." note)))
2362 ;; Normalize old uses of org-log-done.
2363 (cond
2364 ((eq org-log-done t) (setq org-log-done 'time))
2365 ((and (listp org-log-done) (memq 'done org-log-done))
2366 (setq org-log-done 'note)))
2368 (defcustom org-log-reschedule nil
2369 "Information to record when the scheduling date of a tasks is modified.
2371 Possible values are:
2373 nil Don't add anything, just change the date
2374 time Add a time stamp to the task
2375 note Prompt for a note and add it with template `org-log-note-headings'
2377 This option can also be set with on a per-file-basis with
2379 #+STARTUP: nologreschedule
2380 #+STARTUP: logreschedule
2381 #+STARTUP: lognotereschedule"
2382 :group 'org-todo
2383 :group 'org-progress
2384 :type '(choice
2385 (const :tag "No logging" nil)
2386 (const :tag "Record timestamp" time)
2387 (const :tag "Record timestamp with note." note)))
2389 (defcustom org-log-redeadline nil
2390 "Information to record when the deadline date of a tasks is modified.
2392 Possible values are:
2394 nil Don't add anything, just change the date
2395 time Add a time stamp to the task
2396 note Prompt for a note and add it with template `org-log-note-headings'
2398 This option can also be set with on a per-file-basis with
2400 #+STARTUP: nologredeadline
2401 #+STARTUP: logredeadline
2402 #+STARTUP: lognoteredeadline
2404 You can have local logging settings for a subtree by setting the LOGGING
2405 property to one or more of these keywords."
2406 :group 'org-todo
2407 :group 'org-progress
2408 :type '(choice
2409 (const :tag "No logging" nil)
2410 (const :tag "Record timestamp" time)
2411 (const :tag "Record timestamp with note." note)))
2413 (defcustom org-log-note-clock-out nil
2414 "Non-nil means record a note when clocking out of an item.
2415 This can also be configured on a per-file basis by adding one of
2416 the following lines anywhere in the buffer:
2418 #+STARTUP: lognoteclock-out
2419 #+STARTUP: nolognoteclock-out"
2420 :group 'org-todo
2421 :group 'org-progress
2422 :type 'boolean)
2424 (defcustom org-log-done-with-time t
2425 "Non-nil means the CLOSED time stamp will contain date and time.
2426 When nil, only the date will be recorded."
2427 :group 'org-progress
2428 :type 'boolean)
2430 (defcustom org-log-note-headings
2431 '((done . "CLOSING NOTE %t")
2432 (state . "State %-12s from %-12S %t")
2433 (note . "Note taken on %t")
2434 (reschedule . "Rescheduled from %S on %t")
2435 (delschedule . "Not scheduled, was %S on %t")
2436 (redeadline . "New deadline from %S on %t")
2437 (deldeadline . "Removed deadline, was %S on %t")
2438 (refile . "Refiled on %t")
2439 (clock-out . ""))
2440 "Headings for notes added to entries.
2441 The value is an alist, with the car being a symbol indicating the note
2442 context, and the cdr is the heading to be used. The heading may also be the
2443 empty string.
2444 %t in the heading will be replaced by a time stamp.
2445 %T will be an active time stamp instead the default inactive one
2446 %d will be replaced by a short-format time stamp.
2447 %D will be replaced by an active short-format time stamp.
2448 %s will be replaced by the new TODO state, in double quotes.
2449 %S will be replaced by the old TODO state, in double quotes.
2450 %u will be replaced by the user name.
2451 %U will be replaced by the full user name.
2453 In fact, it is not a good idea to change the `state' entry, because
2454 agenda log mode depends on the format of these entries."
2455 :group 'org-todo
2456 :group 'org-progress
2457 :type '(list :greedy t
2458 (cons (const :tag "Heading when closing an item" done) string)
2459 (cons (const :tag
2460 "Heading when changing todo state (todo sequence only)"
2461 state) string)
2462 (cons (const :tag "Heading when just taking a note" note) string)
2463 (cons (const :tag "Heading when clocking out" clock-out) string)
2464 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2465 (cons (const :tag "Heading when rescheduling" reschedule) string)
2466 (cons (const :tag "Heading when changing deadline" redeadline) string)
2467 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2468 (cons (const :tag "Heading when refiling" refile) string)))
2470 (unless (assq 'note org-log-note-headings)
2471 (push '(note . "%t") org-log-note-headings))
2473 (defcustom org-log-into-drawer nil
2474 "Non-nil means insert state change notes and time stamps into a drawer.
2475 When nil, state changes notes will be inserted after the headline and
2476 any scheduling and clock lines, but not inside a drawer.
2478 The value of this variable should be the name of the drawer to use.
2479 LOGBOOK is proposed as the default drawer for this purpose, you can
2480 also set this to a string to define the drawer of your choice.
2482 A value of t is also allowed, representing \"LOGBOOK\".
2484 If this variable is set, `org-log-state-notes-insert-after-drawers'
2485 will be ignored.
2487 You can set the property LOG_INTO_DRAWER to overrule this setting for
2488 a subtree."
2489 :group 'org-todo
2490 :group 'org-progress
2491 :type '(choice
2492 (const :tag "Not into a drawer" nil)
2493 (const :tag "LOGBOOK" t)
2494 (string :tag "Other")))
2496 (if (fboundp 'defvaralias)
2497 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2499 (defun org-log-into-drawer ()
2500 "Return the value of `org-log-into-drawer', but let properties overrule.
2501 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2502 used instead of the default value."
2503 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2504 (cond
2505 ((or (not p) (equal p "nil")) org-log-into-drawer)
2506 ((equal p "t") "LOGBOOK")
2507 (t p))))
2509 (defcustom org-log-state-notes-insert-after-drawers nil
2510 "Non-nil means insert state change notes after any drawers in entry.
2511 Only the drawers that *immediately* follow the headline and the
2512 deadline/scheduled line are skipped.
2513 When nil, insert notes right after the heading and perhaps the line
2514 with deadline/scheduling if present.
2516 This variable will have no effect if `org-log-into-drawer' is
2517 set."
2518 :group 'org-todo
2519 :group 'org-progress
2520 :type 'boolean)
2522 (defcustom org-log-states-order-reversed t
2523 "Non-nil means the latest state note will be directly after heading.
2524 When nil, the state change notes will be ordered according to time."
2525 :group 'org-todo
2526 :group 'org-progress
2527 :type 'boolean)
2529 (defcustom org-todo-repeat-to-state nil
2530 "The TODO state to which a repeater should return the repeating task.
2531 By default this is the first task in a TODO sequence, or the previous state
2532 in a TODO_TYP set. But you can specify another task here.
2533 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2534 :group 'org-todo
2535 :version "24.1"
2536 :type '(choice (const :tag "Head of sequence" nil)
2537 (string :tag "Specific state")))
2539 (defcustom org-log-repeat 'time
2540 "Non-nil means record moving through the DONE state when triggering repeat.
2541 An auto-repeating task is immediately switched back to TODO when
2542 marked DONE. If you are not logging state changes (by adding \"@\"
2543 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2544 record a closing note, there will be no record of the task moving
2545 through DONE. This variable forces taking a note anyway.
2547 nil Don't force a record
2548 time Record a time stamp
2549 note Record a note
2551 This option can also be set with on a per-file-basis with
2553 #+STARTUP: logrepeat
2554 #+STARTUP: lognoterepeat
2555 #+STARTUP: nologrepeat
2557 You can have local logging settings for a subtree by setting the LOGGING
2558 property to one or more of these keywords."
2559 :group 'org-todo
2560 :group 'org-progress
2561 :type '(choice
2562 (const :tag "Don't force a record" nil)
2563 (const :tag "Force recording the DONE state" time)
2564 (const :tag "Force recording a note with the DONE state" note)))
2567 (defgroup org-priorities nil
2568 "Priorities in Org-mode."
2569 :tag "Org Priorities"
2570 :group 'org-todo)
2572 (defcustom org-enable-priority-commands t
2573 "Non-nil means priority commands are active.
2574 When nil, these commands will be disabled, so that you never accidentally
2575 set a priority."
2576 :group 'org-priorities
2577 :type 'boolean)
2579 (defcustom org-highest-priority ?A
2580 "The highest priority of TODO items. A character like ?A, ?B etc.
2581 Must have a smaller ASCII number than `org-lowest-priority'."
2582 :group 'org-priorities
2583 :type 'character)
2585 (defcustom org-lowest-priority ?C
2586 "The lowest priority of TODO items. A character like ?A, ?B etc.
2587 Must have a larger ASCII number than `org-highest-priority'."
2588 :group 'org-priorities
2589 :type 'character)
2591 (defcustom org-default-priority ?B
2592 "The default priority of TODO items.
2593 This is the priority an item gets if no explicit priority is given.
2594 When starting to cycle on an empty priority the first step in the cycle
2595 depends on `org-priority-start-cycle-with-default'. The resulting first
2596 step priority must not exceed the range from `org-highest-priority' to
2597 `org-lowest-priority' which means that `org-default-priority' has to be
2598 in this range exclusive or inclusive the range boundaries. Else the
2599 first step refuses to set the default and the second will fall back
2600 to (depending on the command used) the highest or lowest priority."
2601 :group 'org-priorities
2602 :type 'character)
2604 (defcustom org-priority-start-cycle-with-default t
2605 "Non-nil means start with default priority when starting to cycle.
2606 When this is nil, the first step in the cycle will be (depending on the
2607 command used) one higher or lower than the default priority.
2608 See also `org-default-priority'."
2609 :group 'org-priorities
2610 :type 'boolean)
2612 (defcustom org-get-priority-function nil
2613 "Function to extract the priority from a string.
2614 The string is normally the headline. If this is nil Org computes the
2615 priority from the priority cookie like [#A] in the headline. It returns
2616 an integer, increasing by 1000 for each priority level.
2617 The user can set a different function here, which should take a string
2618 as an argument and return the numeric priority."
2619 :group 'org-priorities
2620 :version "24.1"
2621 :type 'function)
2623 (defgroup org-time nil
2624 "Options concerning time stamps and deadlines in Org-mode."
2625 :tag "Org Time"
2626 :group 'org)
2628 (defcustom org-insert-labeled-timestamps-at-point nil
2629 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2630 When nil, these labeled time stamps are forces into the second line of an
2631 entry, just after the headline. When scheduling from the global TODO list,
2632 the time stamp will always be forced into the second line."
2633 :group 'org-time
2634 :type 'boolean)
2636 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2637 "Formats for `format-time-string' which are used for time stamps.
2638 It is not recommended to change this constant.")
2640 (defcustom org-time-stamp-rounding-minutes '(0 5)
2641 "Number of minutes to round time stamps to.
2642 These are two values, the first applies when first creating a time stamp.
2643 The second applies when changing it with the commands `S-up' and `S-down'.
2644 When changing the time stamp, this means that it will change in steps
2645 of N minutes, as given by the second value.
2647 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2648 numbers should be factors of 60, so for example 5, 10, 15.
2650 When this is larger than 1, you can still force an exact time stamp by using
2651 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2652 and by using a prefix arg to `S-up/down' to specify the exact number
2653 of minutes to shift."
2654 :group 'org-time
2655 :get #'(lambda (var) ; Make sure both elements are there
2656 (if (integerp (default-value var))
2657 (list (default-value var) 5)
2658 (default-value var)))
2659 :type '(list
2660 (integer :tag "when inserting times")
2661 (integer :tag "when modifying times")))
2663 ;; Normalize old customizations of this variable.
2664 (when (integerp org-time-stamp-rounding-minutes)
2665 (setq org-time-stamp-rounding-minutes
2666 (list org-time-stamp-rounding-minutes
2667 org-time-stamp-rounding-minutes)))
2669 (defcustom org-display-custom-times nil
2670 "Non-nil means overlay custom formats over all time stamps.
2671 The formats are defined through the variable `org-time-stamp-custom-formats'.
2672 To turn this on on a per-file basis, insert anywhere in the file:
2673 #+STARTUP: customtime"
2674 :group 'org-time
2675 :set 'set-default
2676 :type 'sexp)
2677 (make-variable-buffer-local 'org-display-custom-times)
2679 (defcustom org-time-stamp-custom-formats
2680 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2681 "Custom formats for time stamps. See `format-time-string' for the syntax.
2682 These are overlaid over the default ISO format if the variable
2683 `org-display-custom-times' is set. Time like %H:%M should be at the
2684 end of the second format. The custom formats are also honored by export
2685 commands, if custom time display is turned on at the time of export."
2686 :group 'org-time
2687 :type 'sexp)
2689 (defun org-time-stamp-format (&optional long inactive)
2690 "Get the right format for a time string."
2691 (let ((f (if long (cdr org-time-stamp-formats)
2692 (car org-time-stamp-formats))))
2693 (if inactive
2694 (concat "[" (substring f 1 -1) "]")
2695 f)))
2697 (defcustom org-time-clocksum-format "%d:%02d"
2698 "The format string used when creating CLOCKSUM lines.
2699 This is also used when org-mode generates a time duration."
2700 :group 'org-time
2701 :type 'string)
2703 (defcustom org-time-clocksum-use-fractional nil
2704 "If non-nil, \\[org-clock-display] uses fractional times.
2705 org-mode generates a time duration."
2706 :group 'org-time
2707 :type 'boolean)
2709 (defcustom org-time-clocksum-fractional-format "%.2f"
2710 "The format string used when creating CLOCKSUM lines, or when
2711 org-mode generates a time duration."
2712 :group 'org-time
2713 :type 'string)
2715 (defcustom org-deadline-warning-days 14
2716 "No. of days before expiration during which a deadline becomes active.
2717 This variable governs the display in sparse trees and in the agenda.
2718 When 0 or negative, it means use this number (the absolute value of it)
2719 even if a deadline has a different individual lead time specified.
2721 Custom commands can set this variable in the options section."
2722 :group 'org-time
2723 :group 'org-agenda-daily/weekly
2724 :type 'integer)
2726 (defcustom org-read-date-prefer-future t
2727 "Non-nil means assume future for incomplete date input from user.
2728 This affects the following situations:
2729 1. The user gives a month but not a year.
2730 For example, if it is April and you enter \"feb 2\", this will be read
2731 as Feb 2, *next* year. \"May 5\", however, will be this year.
2732 2. The user gives a day, but no month.
2733 For example, if today is the 15th, and you enter \"3\", Org-mode will
2734 read this as the third of *next* month. However, if you enter \"17\",
2735 it will be considered as *this* month.
2737 If you set this variable to the symbol `time', then also the following
2738 will work:
2740 3. If the user gives a time, but no day. If the time is before now,
2741 to will be interpreted as tomorrow.
2743 Currently none of this works for ISO week specifications.
2745 When this option is nil, the current day, month and year will always be
2746 used as defaults.
2748 See also `org-agenda-jump-prefer-future'."
2749 :group 'org-time
2750 :type '(choice
2751 (const :tag "Never" nil)
2752 (const :tag "Check month and day" t)
2753 (const :tag "Check month, day, and time" time)))
2755 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2756 "Should the agenda jump command prefer the future for incomplete dates?
2757 The default is to do the same as configured in `org-read-date-prefer-future'.
2758 But you can also set a deviating value here.
2759 This may t or nil, or the symbol `org-read-date-prefer-future'."
2760 :group 'org-agenda
2761 :group 'org-time
2762 :version "24.1"
2763 :type '(choice
2764 (const :tag "Use org-read-date-prefer-future"
2765 org-read-date-prefer-future)
2766 (const :tag "Never" nil)
2767 (const :tag "Always" t)))
2769 (defcustom org-read-date-force-compatible-dates t
2770 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2772 Depending on the system Emacs is running on, certain dates cannot
2773 be represented with the type used internally to represent time.
2774 Dates between 1970-1-1 and 2038-1-1 can always be represented
2775 correctly. Some systems allow for earlier dates, some for later,
2776 some for both. One way to find out it to insert any date into an
2777 Org buffer, putting the cursor on the year and hitting S-up and
2778 S-down to test the range.
2780 When this variable is set to t, the date/time prompt will not let
2781 you specify dates outside the 1970-2037 range, so it is certain that
2782 these dates will work in whatever version of Emacs you are
2783 running, and also that you can move a file from one Emacs implementation
2784 to another. WHenever Org is forcing the year for you, it will display
2785 a message and beep.
2787 When this variable is nil, Org will check if the date is
2788 representable in the specific Emacs implementation you are using.
2789 If not, it will force a year, usually the current year, and beep
2790 to remind you. Currently this setting is not recommended because
2791 the likelihood that you will open your Org files in an Emacs that
2792 has limited date range is not negligible.
2794 A workaround for this problem is to use diary sexp dates for time
2795 stamps outside of this range."
2796 :group 'org-time
2797 :version "24.1"
2798 :type 'boolean)
2800 (defcustom org-read-date-display-live t
2801 "Non-nil means display current interpretation of date prompt live.
2802 This display will be in an overlay, in the minibuffer."
2803 :group 'org-time
2804 :type 'boolean)
2806 (defcustom org-read-date-popup-calendar t
2807 "Non-nil means pop up a calendar when prompting for a date.
2808 In the calendar, the date can be selected with mouse-1. However, the
2809 minibuffer will also be active, and you can simply enter the date as well.
2810 When nil, only the minibuffer will be available."
2811 :group 'org-time
2812 :type 'boolean)
2813 (if (fboundp 'defvaralias)
2814 (defvaralias 'org-popup-calendar-for-date-prompt
2815 'org-read-date-popup-calendar))
2817 (defcustom org-read-date-minibuffer-setup-hook nil
2818 "Hook to be used to set up keys for the date/time interface.
2819 Add key definitions to `minibuffer-local-map', which will be a temporary
2820 copy."
2821 :group 'org-time
2822 :type 'hook)
2824 (defcustom org-extend-today-until 0
2825 "The hour when your day really ends. Must be an integer.
2826 This has influence for the following applications:
2827 - When switching the agenda to \"today\". It it is still earlier than
2828 the time given here, the day recognized as TODAY is actually yesterday.
2829 - When a date is read from the user and it is still before the time given
2830 here, the current date and time will be assumed to be yesterday, 23:59.
2831 Also, timestamps inserted in remember templates follow this rule.
2833 IMPORTANT: This is a feature whose implementation is and likely will
2834 remain incomplete. Really, it is only here because past midnight seems to
2835 be the favorite working time of John Wiegley :-)"
2836 :group 'org-time
2837 :type 'integer)
2839 (defcustom org-use-effective-time nil
2840 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2841 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2842 \"effective time\" of any timestamps between midnight and 8am will be
2843 23:59 of the previous day."
2844 :group 'org-time
2845 :version "24.1"
2846 :type 'boolean)
2848 (defcustom org-edit-timestamp-down-means-later nil
2849 "Non-nil means S-down will increase the time in a time stamp.
2850 When nil, S-up will increase."
2851 :group 'org-time
2852 :type 'boolean)
2854 (defcustom org-calendar-follow-timestamp-change t
2855 "Non-nil means make the calendar window follow timestamp changes.
2856 When a timestamp is modified and the calendar window is visible, it will be
2857 moved to the new date."
2858 :group 'org-time
2859 :type 'boolean)
2861 (defgroup org-tags nil
2862 "Options concerning tags in Org-mode."
2863 :tag "Org Tags"
2864 :group 'org)
2866 (defcustom org-tag-alist nil
2867 "List of tags allowed in Org-mode files.
2868 When this list is nil, Org-mode will base TAG input on what is already in the
2869 buffer.
2870 The value of this variable is an alist, the car of each entry must be a
2871 keyword as a string, the cdr may be a character that is used to select
2872 that tag through the fast-tag-selection interface.
2873 See the manual for details."
2874 :group 'org-tags
2875 :type '(repeat
2876 (choice
2877 (cons (string :tag "Tag name")
2878 (character :tag "Access char"))
2879 (list :tag "Start radio group"
2880 (const :startgroup)
2881 (option (string :tag "Group description")))
2882 (list :tag "End radio group"
2883 (const :endgroup)
2884 (option (string :tag "Group description")))
2885 (const :tag "New line" (:newline)))))
2887 (defcustom org-tag-persistent-alist nil
2888 "List of tags that will always appear in all Org-mode files.
2889 This is in addition to any in buffer settings or customizations
2890 of `org-tag-alist'.
2891 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2892 The value of this variable is an alist, the car of each entry must be a
2893 keyword as a string, the cdr may be a character that is used to select
2894 that tag through the fast-tag-selection interface.
2895 See the manual for details.
2896 To disable these tags on a per-file basis, insert anywhere in the file:
2897 #+STARTUP: noptag"
2898 :group 'org-tags
2899 :type '(repeat
2900 (choice
2901 (cons (string :tag "Tag name")
2902 (character :tag "Access char"))
2903 (const :tag "Start radio group" (:startgroup))
2904 (const :tag "End radio group" (:endgroup))
2905 (const :tag "New line" (:newline)))))
2907 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2908 "If non-nil, always offer completion for all tags of all agenda files.
2909 Instead of customizing this variable directly, you might want to
2910 set it locally for capture buffers, because there no list of
2911 tags in that file can be created dynamically (there are none).
2913 (add-hook 'org-capture-mode-hook
2914 (lambda ()
2915 (set (make-local-variable
2916 'org-complete-tags-always-offer-all-agenda-tags)
2917 t)))"
2918 :group 'org-tags
2919 :version "24.1"
2920 :type 'boolean)
2922 (defvar org-file-tags nil
2923 "List of tags that can be inherited by all entries in the file.
2924 The tags will be inherited if the variable `org-use-tag-inheritance'
2925 says they should be.
2926 This variable is populated from #+FILETAGS lines.")
2928 (defcustom org-use-fast-tag-selection 'auto
2929 "Non-nil means use fast tag selection scheme.
2930 This is a special interface to select and deselect tags with single keys.
2931 When nil, fast selection is never used.
2932 When the symbol `auto', fast selection is used if and only if selection
2933 characters for tags have been configured, either through the variable
2934 `org-tag-alist' or through a #+TAGS line in the buffer.
2935 When t, fast selection is always used and selection keys are assigned
2936 automatically if necessary."
2937 :group 'org-tags
2938 :type '(choice
2939 (const :tag "Always" t)
2940 (const :tag "Never" nil)
2941 (const :tag "When selection characters are configured" 'auto)))
2943 (defcustom org-fast-tag-selection-single-key nil
2944 "Non-nil means fast tag selection exits after first change.
2945 When nil, you have to press RET to exit it.
2946 During fast tag selection, you can toggle this flag with `C-c'.
2947 This variable can also have the value `expert'. In this case, the window
2948 displaying the tags menu is not even shown, until you press C-c again."
2949 :group 'org-tags
2950 :type '(choice
2951 (const :tag "No" nil)
2952 (const :tag "Yes" t)
2953 (const :tag "Expert" expert)))
2955 (defvar org-fast-tag-selection-include-todo nil
2956 "Non-nil means fast tags selection interface will also offer TODO states.
2957 This is an undocumented feature, you should not rely on it.")
2959 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2960 "The column to which tags should be indented in a headline.
2961 If this number is positive, it specifies the column. If it is negative,
2962 it means that the tags should be flushright to that column. For example,
2963 -80 works well for a normal 80 character screen.
2964 When 0, place tags directly after headline text, with only one space in
2965 between."
2966 :group 'org-tags
2967 :type 'integer)
2969 (defcustom org-auto-align-tags t
2970 "Non-nil keeps tags aligned when modifying headlines.
2971 Some operations (i.e. demoting) change the length of a headline and
2972 therefore shift the tags around. With this option turned on, after
2973 each such operation the tags are again aligned to `org-tags-column'."
2974 :group 'org-tags
2975 :type 'boolean)
2977 (defcustom org-use-tag-inheritance t
2978 "Non-nil means tags in levels apply also for sublevels.
2979 When nil, only the tags directly given in a specific line apply there.
2980 This may also be a list of tags that should be inherited, or a regexp that
2981 matches tags that should be inherited. Additional control is possible
2982 with the variable `org-tags-exclude-from-inheritance' which gives an
2983 explicit list of tags to be excluded from inheritance., even if the value of
2984 `org-use-tag-inheritance' would select it for inheritance.
2986 If this option is t, a match early-on in a tree can lead to a large
2987 number of matches in the subtree when constructing the agenda or creating
2988 a sparse tree. If you only want to see the first match in a tree during
2989 a search, check out the variable `org-tags-match-list-sublevels'."
2990 :group 'org-tags
2991 :type '(choice
2992 (const :tag "Not" nil)
2993 (const :tag "Always" t)
2994 (repeat :tag "Specific tags" (string :tag "Tag"))
2995 (regexp :tag "Tags matched by regexp")))
2997 (defcustom org-tags-exclude-from-inheritance nil
2998 "List of tags that should never be inherited.
2999 This is a way to exclude a few tags from inheritance. For way to do
3000 the opposite, to actively allow inheritance for selected tags,
3001 see the variable `org-use-tag-inheritance'."
3002 :group 'org-tags
3003 :type '(repeat (string :tag "Tag")))
3005 (defun org-tag-inherit-p (tag)
3006 "Check if TAG is one that should be inherited."
3007 (cond
3008 ((member tag org-tags-exclude-from-inheritance) nil)
3009 ((eq org-use-tag-inheritance t) t)
3010 ((not org-use-tag-inheritance) nil)
3011 ((stringp org-use-tag-inheritance)
3012 (string-match org-use-tag-inheritance tag))
3013 ((listp org-use-tag-inheritance)
3014 (member tag org-use-tag-inheritance))
3015 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3017 (defcustom org-tags-match-list-sublevels t
3018 "Non-nil means list also sublevels of headlines matching a search.
3019 This variable applies to tags/property searches, and also to stuck
3020 projects because this search is based on a tags match as well.
3022 When set to the symbol `indented', sublevels are indented with
3023 leading dots.
3025 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3026 the sublevels of a headline matching a tag search often also match
3027 the same search. Listing all of them can create very long lists.
3028 Setting this variable to nil causes subtrees of a match to be skipped.
3030 This variable is semi-obsolete and probably should always be true. It
3031 is better to limit inheritance to certain tags using the variables
3032 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3033 :group 'org-tags
3034 :type '(choice
3035 (const :tag "No, don't list them" nil)
3036 (const :tag "Yes, do list them" t)
3037 (const :tag "List them, indented with leading dots" indented)))
3039 (defcustom org-tags-sort-function nil
3040 "When set, tags are sorted using this function as a comparator."
3041 :group 'org-tags
3042 :type '(choice
3043 (const :tag "No sorting" nil)
3044 (const :tag "Alphabetical" string<)
3045 (const :tag "Reverse alphabetical" string>)
3046 (function :tag "Custom function" nil)))
3048 (defvar org-tags-history nil
3049 "History of minibuffer reads for tags.")
3050 (defvar org-last-tags-completion-table nil
3051 "The last used completion table for tags.")
3052 (defvar org-after-tags-change-hook nil
3053 "Hook that is run after the tags in a line have changed.")
3055 (defgroup org-properties nil
3056 "Options concerning properties in Org-mode."
3057 :tag "Org Properties"
3058 :group 'org)
3060 (defcustom org-property-format "%-10s %s"
3061 "How property key/value pairs should be formatted by `indent-line'.
3062 When `indent-line' hits a property definition, it will format the line
3063 according to this format, mainly to make sure that the values are
3064 lined-up with respect to each other."
3065 :group 'org-properties
3066 :type 'string)
3068 (defcustom org-properties-postprocess-alist nil
3069 "Alist of properties and functions to adjust inserted values.
3070 Elements of this alist must be of the form
3072 ([string] [function])
3074 where [string] must be a property name and [function] must be a
3075 lambda expression: this lambda expression must take one argument,
3076 the value to adjust, and return the new value as a string.
3078 For example, this element will allow the property \"Remaining\"
3079 to be updated wrt the relation between the \"Effort\" property
3080 and the clock summary:
3082 ((\"Remaining\" (lambda(value)
3083 (let ((clocksum (org-clock-sum-current-item))
3084 (effort (org-duration-string-to-minutes
3085 (org-entry-get (point) \"Effort\"))))
3086 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3087 :group 'org-properties
3088 :version "24.1"
3089 :type 'alist)
3091 (defcustom org-use-property-inheritance nil
3092 "Non-nil means properties apply also for sublevels.
3094 This setting is chiefly used during property searches. Turning it on can
3095 cause significant overhead when doing a search, which is why it is not
3096 on by default.
3098 When nil, only the properties directly given in the current entry count.
3099 When t, every property is inherited. The value may also be a list of
3100 properties that should have inheritance, or a regular expression matching
3101 properties that should be inherited.
3103 However, note that some special properties use inheritance under special
3104 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3105 and the properties ending in \"_ALL\" when they are used as descriptor
3106 for valid values of a property.
3108 Note for programmers:
3109 When querying an entry with `org-entry-get', you can control if inheritance
3110 should be used. By default, `org-entry-get' looks only at the local
3111 properties. You can request inheritance by setting the inherit argument
3112 to t (to force inheritance) or to `selective' (to respect the setting
3113 in this variable)."
3114 :group 'org-properties
3115 :type '(choice
3116 (const :tag "Not" nil)
3117 (const :tag "Always" t)
3118 (repeat :tag "Specific properties" (string :tag "Property"))
3119 (regexp :tag "Properties matched by regexp")))
3121 (defun org-property-inherit-p (property)
3122 "Check if PROPERTY is one that should be inherited."
3123 (cond
3124 ((eq org-use-property-inheritance t) t)
3125 ((not org-use-property-inheritance) nil)
3126 ((stringp org-use-property-inheritance)
3127 (string-match org-use-property-inheritance property))
3128 ((listp org-use-property-inheritance)
3129 (member property org-use-property-inheritance))
3130 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3132 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3133 "The default column format, if no other format has been defined.
3134 This variable can be set on the per-file basis by inserting a line
3136 #+COLUMNS: %25ITEM ....."
3137 :group 'org-properties
3138 :type 'string)
3140 (defcustom org-columns-ellipses ".."
3141 "The ellipses to be used when a field in column view is truncated.
3142 When this is the empty string, as many characters as possible are shown,
3143 but then there will be no visual indication that the field has been truncated.
3144 When this is a string of length N, the last N characters of a truncated
3145 field are replaced by this string. If the column is narrower than the
3146 ellipses string, only part of the ellipses string will be shown."
3147 :group 'org-properties
3148 :type 'string)
3150 (defcustom org-columns-modify-value-for-display-function nil
3151 "Function that modifies values for display in column view.
3152 For example, it can be used to cut out a certain part from a time stamp.
3153 The function must take 2 arguments:
3155 column-title The title of the column (*not* the property name)
3156 value The value that should be modified.
3158 The function should return the value that should be displayed,
3159 or nil if the normal value should be used."
3160 :group 'org-properties
3161 :type 'function)
3163 (defcustom org-effort-property "Effort"
3164 "The property that is being used to keep track of effort estimates.
3165 Effort estimates given in this property need to have the format H:MM."
3166 :group 'org-properties
3167 :group 'org-progress
3168 :type '(string :tag "Property"))
3170 (defconst org-global-properties-fixed
3171 '(("VISIBILITY_ALL" . "folded children content all")
3172 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3173 "List of property/value pairs that can be inherited by any entry.
3175 These are fixed values, for the preset properties. The user variable
3176 that can be used to add to this list is `org-global-properties'.
3178 The entries in this list are cons cells where the car is a property
3179 name and cdr is a string with the value. If the value represents
3180 multiple items like an \"_ALL\" property, separate the items by
3181 spaces.")
3183 (defcustom org-global-properties nil
3184 "List of property/value pairs that can be inherited by any entry.
3186 This list will be combined with the constant `org-global-properties-fixed'.
3188 The entries in this list are cons cells where the car is a property
3189 name and cdr is a string with the value.
3191 You can set buffer-local values for the same purpose in the variable
3192 `org-file-properties' this by adding lines like
3194 #+PROPERTY: NAME VALUE"
3195 :group 'org-properties
3196 :type '(repeat
3197 (cons (string :tag "Property")
3198 (string :tag "Value"))))
3200 (defvar org-file-properties nil
3201 "List of property/value pairs that can be inherited by any entry.
3202 Valid for the current buffer.
3203 This variable is populated from #+PROPERTY lines.")
3204 (make-variable-buffer-local 'org-file-properties)
3206 (defgroup org-agenda nil
3207 "Options concerning agenda views in Org-mode."
3208 :tag "Org Agenda"
3209 :group 'org)
3211 (defvar org-category nil
3212 "Variable used by org files to set a category for agenda display.
3213 Such files should use a file variable to set it, for example
3215 # -*- mode: org; org-category: \"ELisp\"
3217 or contain a special line
3219 #+CATEGORY: ELisp
3221 If the file does not specify a category, then file's base name
3222 is used instead.")
3223 (make-variable-buffer-local 'org-category)
3224 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3226 (defcustom org-agenda-files nil
3227 "The files to be used for agenda display.
3228 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3229 \\[org-remove-file]. You can also use customize to edit the list.
3231 If an entry is a directory, all files in that directory that are matched by
3232 `org-agenda-file-regexp' will be part of the file list.
3234 If the value of the variable is not a list but a single file name, then
3235 the list of agenda files is actually stored and maintained in that file, one
3236 agenda file per line. In this file paths can be given relative to
3237 `org-directory'. Tilde expansion and environment variable substitution
3238 are also made."
3239 :group 'org-agenda
3240 :type '(choice
3241 (repeat :tag "List of files and directories" file)
3242 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3244 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3245 "Regular expression to match files for `org-agenda-files'.
3246 If any element in the list in that variable contains a directory instead
3247 of a normal file, all files in that directory that are matched by this
3248 regular expression will be included."
3249 :group 'org-agenda
3250 :type 'regexp)
3252 (defcustom org-agenda-text-search-extra-files nil
3253 "List of extra files to be searched by text search commands.
3254 These files will be search in addition to the agenda files by the
3255 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3256 Note that these files will only be searched for text search commands,
3257 not for the other agenda views like todo lists, tag searches or the weekly
3258 agenda. This variable is intended to list notes and possibly archive files
3259 that should also be searched by these two commands.
3260 In fact, if the first element in the list is the symbol `agenda-archives',
3261 than all archive files of all agenda files will be added to the search
3262 scope."
3263 :group 'org-agenda
3264 :type '(set :greedy t
3265 (const :tag "Agenda Archives" agenda-archives)
3266 (repeat :inline t (file))))
3268 (if (fboundp 'defvaralias)
3269 (defvaralias 'org-agenda-multi-occur-extra-files
3270 'org-agenda-text-search-extra-files))
3272 (defcustom org-agenda-skip-unavailable-files nil
3273 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3274 A nil value means to remove them, after a query, from the list."
3275 :group 'org-agenda
3276 :type 'boolean)
3278 (defcustom org-calendar-to-agenda-key [?c]
3279 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3280 The command `org-calendar-goto-agenda' will be bound to this key. The
3281 default is the character `c' because then `c' can be used to switch back and
3282 forth between agenda and calendar."
3283 :group 'org-agenda
3284 :type 'sexp)
3286 (defcustom org-calendar-agenda-action-key [?k]
3287 "The key to be installed in `calendar-mode-map' for agenda-action.
3288 The command `org-agenda-action' will be bound to this key. The
3289 default is the character `k' because we use the same key in the agenda."
3290 :group 'org-agenda
3291 :type 'sexp)
3293 (defcustom org-calendar-insert-diary-entry-key [?i]
3294 "The key to be installed in `calendar-mode-map' for adding diary entries.
3295 This option is irrelevant until `org-agenda-diary-file' has been configured
3296 to point to an Org-mode file. When that is the case, the command
3297 `org-agenda-diary-entry' will be bound to the key given here, by default
3298 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3299 if you want to continue doing this, you need to change this to a different
3300 key."
3301 :group 'org-agenda
3302 :type 'sexp)
3304 (defcustom org-agenda-diary-file 'diary-file
3305 "File to which to add new entries with the `i' key in agenda and calendar.
3306 When this is the symbol `diary-file', the functionality in the Emacs
3307 calendar will be used to add entries to the `diary-file'. But when this
3308 points to a file, `org-agenda-diary-entry' will be used instead."
3309 :group 'org-agenda
3310 :type '(choice
3311 (const :tag "The standard Emacs diary file" diary-file)
3312 (file :tag "Special Org file diary entries")))
3314 (eval-after-load "calendar"
3315 '(progn
3316 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3317 'org-calendar-goto-agenda)
3318 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3319 'org-agenda-action)
3320 (add-hook 'calendar-mode-hook
3321 (lambda ()
3322 (unless (eq org-agenda-diary-file 'diary-file)
3323 (define-key calendar-mode-map
3324 org-calendar-insert-diary-entry-key
3325 'org-agenda-diary-entry))))))
3327 (defgroup org-latex nil
3328 "Options for embedding LaTeX code into Org-mode."
3329 :tag "Org LaTeX"
3330 :group 'org)
3332 (defcustom org-format-latex-options
3333 '(:foreground default :background default :scale 1.0
3334 :html-foreground "Black" :html-background "Transparent"
3335 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3336 "Options for creating images from LaTeX fragments.
3337 This is a property list with the following properties:
3338 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3339 `default' means use the foreground of the default face.
3340 :background the background color, or \"Transparent\".
3341 `default' means use the background of the default face.
3342 :scale a scaling factor for the size of the images, to get more pixels
3343 :html-foreground, :html-background, :html-scale
3344 the same numbers for HTML export.
3345 :matchers a list indicating which matchers should be used to
3346 find LaTeX fragments. Valid members of this list are:
3347 \"begin\" find environments
3348 \"$1\" find single characters surrounded by $.$
3349 \"$\" find math expressions surrounded by $...$
3350 \"$$\" find math expressions surrounded by $$....$$
3351 \"\\(\" find math expressions surrounded by \\(...\\)
3352 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3353 :group 'org-latex
3354 :type 'plist)
3356 (defcustom org-format-latex-signal-error t
3357 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3358 When nil, just push out a message."
3359 :group 'org-latex
3360 :version "24.1"
3361 :type 'boolean)
3363 (defcustom org-latex-to-mathml-jar-file nil
3364 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3365 Use this to specify additional executable file say a jar file.
3367 When using MathToWeb as the converter, specify the full-path to
3368 your mathtoweb.jar file."
3369 :group 'org-latex
3370 :version "24.1"
3371 :type '(choice
3372 (const :tag "None" nil)
3373 (file :tag "JAR file" :must-match t)))
3375 (defcustom org-latex-to-mathml-convert-command nil
3376 "Command to convert LaTeX fragments to MathML.
3377 Replace format-specifiers in the command as noted below and use
3378 `shell-command' to convert LaTeX to MathML.
3379 %j: Executable file in fully expanded form as specified by
3380 `org-latex-to-mathml-jar-file'.
3381 %I: Input LaTeX file in fully expanded form
3382 %o: Output MathML file
3383 This command is used by `org-create-math-formula'.
3385 When using MathToWeb as the converter, set this to
3386 \"java -jar %j -unicode -force -df %o %I\"."
3387 :group 'org-latex
3388 :version "24.1"
3389 :type '(choice
3390 (const :tag "None" nil)
3391 (string :tag "\nShell command")))
3393 (defun org-format-latex-mathml-available-p ()
3394 "Return t if `org-latex-to-mathml-convert-command' is usable."
3395 (save-match-data
3396 (when (and (boundp 'org-latex-to-mathml-convert-command)
3397 org-latex-to-mathml-convert-command)
3398 (let ((executable (car (split-string
3399 org-latex-to-mathml-convert-command))))
3400 (when (executable-find executable)
3401 (if (string-match
3402 "%j" org-latex-to-mathml-convert-command)
3403 (file-readable-p org-latex-to-mathml-jar-file)
3404 t))))))
3406 (defcustom org-format-latex-header "\\documentclass{article}
3407 \\usepackage[usenames]{color}
3408 \\usepackage{amsmath}
3409 \\usepackage[mathscr]{eucal}
3410 \\pagestyle{empty} % do not remove
3411 \[PACKAGES]
3412 \[DEFAULT-PACKAGES]
3413 % The settings below are copied from fullpage.sty
3414 \\setlength{\\textwidth}{\\paperwidth}
3415 \\addtolength{\\textwidth}{-3cm}
3416 \\setlength{\\oddsidemargin}{1.5cm}
3417 \\addtolength{\\oddsidemargin}{-2.54cm}
3418 \\setlength{\\evensidemargin}{\\oddsidemargin}
3419 \\setlength{\\textheight}{\\paperheight}
3420 \\addtolength{\\textheight}{-\\headheight}
3421 \\addtolength{\\textheight}{-\\headsep}
3422 \\addtolength{\\textheight}{-\\footskip}
3423 \\addtolength{\\textheight}{-3cm}
3424 \\setlength{\\topmargin}{1.5cm}
3425 \\addtolength{\\topmargin}{-2.54cm}"
3426 "The document header used for processing LaTeX fragments.
3427 It is imperative that this header make sure that no page number
3428 appears on the page. The package defined in the variables
3429 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3430 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3431 will be appended."
3432 :group 'org-latex
3433 :type 'string)
3435 (defvar org-format-latex-header-extra nil)
3437 (defun org-set-packages-alist (var val)
3438 "Set the packages alist and make sure it has 3 elements per entry."
3439 (set var (mapcar (lambda (x)
3440 (if (and (consp x) (= (length x) 2))
3441 (list (car x) (nth 1 x) t)
3443 val)))
3445 (defun org-get-packages-alist (var)
3447 "Get the packages alist and make sure it has 3 elements per entry."
3448 (mapcar (lambda (x)
3449 (if (and (consp x) (= (length x) 2))
3450 (list (car x) (nth 1 x) t)
3452 (default-value var)))
3454 ;; The following variables are defined here because is it also used
3455 ;; when formatting latex fragments. Originally it was part of the
3456 ;; LaTeX exporter, which is why the name includes "export".
3457 (defcustom org-export-latex-default-packages-alist
3458 '(("AUTO" "inputenc" t)
3459 ("T1" "fontenc" t)
3460 ("" "fixltx2e" nil)
3461 ("" "graphicx" t)
3462 ("" "longtable" nil)
3463 ("" "float" nil)
3464 ("" "wrapfig" nil)
3465 ("" "soul" t)
3466 ("" "textcomp" t)
3467 ("" "marvosym" t)
3468 ("" "wasysym" t)
3469 ("" "latexsym" t)
3470 ("" "amssymb" t)
3471 ("" "hyperref" nil)
3472 "\\tolerance=1000"
3474 "Alist of default packages to be inserted in the header.
3475 Change this only if one of the packages here causes an incompatibility
3476 with another package you are using.
3477 The packages in this list are needed by one part or another of Org-mode
3478 to function properly.
3480 - inputenc, fontenc: for basic font and character selection
3481 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3482 for interpreting the entities in `org-entities'. You can skip some of these
3483 packages if you don't use any of the symbols in it.
3484 - graphicx: for including images
3485 - float, wrapfig: for figure placement
3486 - longtable: for long tables
3487 - hyperref: for cross references
3489 Therefore you should not modify this variable unless you know what you
3490 are doing. The one reason to change it anyway is that you might be loading
3491 some other package that conflicts with one of the default packages.
3492 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3493 If SNIPPET-FLAG is t, the package also needs to be included when
3494 compiling LaTeX snippets into images for inclusion into HTML."
3495 :group 'org-export-latex
3496 :set 'org-set-packages-alist
3497 :get 'org-get-packages-alist
3498 :version "24.1"
3499 :type '(repeat
3500 (choice
3501 (list :tag "options/package pair"
3502 (string :tag "options")
3503 (string :tag "package")
3504 (boolean :tag "Snippet"))
3505 (string :tag "A line of LaTeX"))))
3507 (defcustom org-export-latex-packages-alist nil
3508 "Alist of packages to be inserted in every LaTeX header.
3509 These will be inserted after `org-export-latex-default-packages-alist'.
3510 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3511 SNIPPET-FLAG, when t, indicates that this package is also needed when
3512 turning LaTeX snippets into images for inclusion into HTML.
3513 Make sure that you only list packages here which:
3514 - you want in every file
3515 - do not conflict with the default packages in
3516 `org-export-latex-default-packages-alist'
3517 - do not conflict with the setup in `org-format-latex-header'."
3518 :group 'org-export-latex
3519 :set 'org-set-packages-alist
3520 :get 'org-get-packages-alist
3521 :type '(repeat
3522 (choice
3523 (list :tag "options/package pair"
3524 (string :tag "options")
3525 (string :tag "package")
3526 (boolean :tag "Snippet"))
3527 (string :tag "A line of LaTeX"))))
3530 (defgroup org-appearance nil
3531 "Settings for Org-mode appearance."
3532 :tag "Org Appearance"
3533 :group 'org)
3535 (defcustom org-level-color-stars-only nil
3536 "Non-nil means fontify only the stars in each headline.
3537 When nil, the entire headline is fontified.
3538 Changing it requires restart of `font-lock-mode' to become effective
3539 also in regions already fontified."
3540 :group 'org-appearance
3541 :type 'boolean)
3543 (defcustom org-hide-leading-stars nil
3544 "Non-nil means hide the first N-1 stars in a headline.
3545 This works by using the face `org-hide' for these stars. This
3546 face is white for a light background, and black for a dark
3547 background. You may have to customize the face `org-hide' to
3548 make this work.
3549 Changing it requires restart of `font-lock-mode' to become effective
3550 also in regions already fontified.
3551 You may also set this on a per-file basis by adding one of the following
3552 lines to the buffer:
3554 #+STARTUP: hidestars
3555 #+STARTUP: showstars"
3556 :group 'org-appearance
3557 :type 'boolean)
3559 (defcustom org-hidden-keywords nil
3560 "List of symbols corresponding to keywords to be hidden the org buffer.
3561 For example, a value '(title) for this list will make the document's title
3562 appear in the buffer without the initial #+TITLE: keyword."
3563 :group 'org-appearance
3564 :version "24.1"
3565 :type '(set (const :tag "#+AUTHOR" author)
3566 (const :tag "#+DATE" date)
3567 (const :tag "#+EMAIL" email)
3568 (const :tag "#+TITLE" title)))
3570 (defcustom org-fontify-done-headline nil
3571 "Non-nil means change the face of a headline if it is marked DONE.
3572 Normally, only the TODO/DONE keyword indicates the state of a headline.
3573 When this is non-nil, the headline after the keyword is set to the
3574 `org-headline-done' as an additional indication."
3575 :group 'org-appearance
3576 :type 'boolean)
3578 (defcustom org-fontify-emphasized-text t
3579 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3580 Changing this variable requires a restart of Emacs to take effect."
3581 :group 'org-appearance
3582 :type 'boolean)
3584 (defcustom org-fontify-whole-heading-line nil
3585 "Non-nil means fontify the whole line for headings.
3586 This is useful when setting a background color for the
3587 org-level-* faces."
3588 :group 'org-appearance
3589 :type 'boolean)
3591 (defcustom org-highlight-latex-fragments-and-specials nil
3592 "Non-nil means fontify what is treated specially by the exporters."
3593 :group 'org-appearance
3594 :type 'boolean)
3596 (defcustom org-hide-emphasis-markers nil
3597 "Non-nil mean font-lock should hide the emphasis marker characters."
3598 :group 'org-appearance
3599 :type 'boolean)
3601 (defcustom org-pretty-entities nil
3602 "Non-nil means show entities as UTF8 characters.
3603 When nil, the \\name form remains in the buffer."
3604 :group 'org-appearance
3605 :version "24.1"
3606 :type 'boolean)
3608 (defcustom org-pretty-entities-include-sub-superscripts t
3609 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3610 :group 'org-appearance
3611 :version "24.1"
3612 :type 'boolean)
3614 (defvar org-emph-re nil
3615 "Regular expression for matching emphasis.
3616 After a match, the match groups contain these elements:
3617 0 The match of the full regular expression, including the characters
3618 before and after the proper match
3619 1 The character before the proper match, or empty at beginning of line
3620 2 The proper match, including the leading and trailing markers
3621 3 The leading marker like * or /, indicating the type of highlighting
3622 4 The text between the emphasis markers, not including the markers
3623 5 The character after the match, empty at the end of a line")
3624 (defvar org-verbatim-re nil
3625 "Regular expression for matching verbatim text.")
3626 (defvar org-emphasis-regexp-components) ; defined just below
3627 (defvar org-emphasis-alist) ; defined just below
3628 (defun org-set-emph-re (var val)
3629 "Set variable and compute the emphasis regular expression."
3630 (set var val)
3631 (when (and (boundp 'org-emphasis-alist)
3632 (boundp 'org-emphasis-regexp-components)
3633 org-emphasis-alist org-emphasis-regexp-components)
3634 (let* ((e org-emphasis-regexp-components)
3635 (pre (car e))
3636 (post (nth 1 e))
3637 (border (nth 2 e))
3638 (body (nth 3 e))
3639 (nl (nth 4 e))
3640 (body1 (concat body "*?"))
3641 (markers (mapconcat 'car org-emphasis-alist ""))
3642 (vmarkers (mapconcat
3643 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3644 org-emphasis-alist "")))
3645 ;; make sure special characters appear at the right position in the class
3646 (if (string-match "\\^" markers)
3647 (setq markers (concat (replace-match "" t t markers) "^")))
3648 (if (string-match "-" markers)
3649 (setq markers (concat (replace-match "" t t markers) "-")))
3650 (if (string-match "\\^" vmarkers)
3651 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3652 (if (string-match "-" vmarkers)
3653 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3654 (if (> nl 0)
3655 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3656 (int-to-string nl) "\\}")))
3657 ;; Make the regexp
3658 (setq org-emph-re
3659 (concat "\\([" pre "]\\|^\\)"
3660 "\\("
3661 "\\([" markers "]\\)"
3662 "\\("
3663 "[^" border "]\\|"
3664 "[^" border "]"
3665 body1
3666 "[^" border "]"
3667 "\\)"
3668 "\\3\\)"
3669 "\\([" post "]\\|$\\)"))
3670 (setq org-verbatim-re
3671 (concat "\\([" pre "]\\|^\\)"
3672 "\\("
3673 "\\([" vmarkers "]\\)"
3674 "\\("
3675 "[^" border "]\\|"
3676 "[^" border "]"
3677 body1
3678 "[^" border "]"
3679 "\\)"
3680 "\\3\\)"
3681 "\\([" post "]\\|$\\)")))))
3683 (defcustom org-emphasis-regexp-components
3684 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3685 "Components used to build the regular expression for emphasis.
3686 This is a list with five entries. Terminology: In an emphasis string
3687 like \" *strong word* \", we call the initial space PREMATCH, the final
3688 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3689 and \"trong wor\" is the body. The different components in this variable
3690 specify what is allowed/forbidden in each part:
3692 pre Chars allowed as prematch. Beginning of line will be allowed too.
3693 post Chars allowed as postmatch. End of line will be allowed too.
3694 border The chars *forbidden* as border characters.
3695 body-regexp A regexp like \".\" to match a body character. Don't use
3696 non-shy groups here, and don't allow newline here.
3697 newline The maximum number of newlines allowed in an emphasis exp.
3699 Use customize to modify this, or restart Emacs after changing it."
3700 :group 'org-appearance
3701 :set 'org-set-emph-re
3702 :type '(list
3703 (sexp :tag "Allowed chars in pre ")
3704 (sexp :tag "Allowed chars in post ")
3705 (sexp :tag "Forbidden chars in border ")
3706 (sexp :tag "Regexp for body ")
3707 (integer :tag "number of newlines allowed")
3708 (option (boolean :tag "Please ignore this button"))))
3710 (defcustom org-emphasis-alist
3711 `(("*" bold "<b>" "</b>")
3712 ("/" italic "<i>" "</i>")
3713 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3714 ("=" org-code "<code>" "</code>" verbatim)
3715 ("~" org-verbatim "<code>" "</code>" verbatim)
3716 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3717 "<del>" "</del>")
3719 "Special syntax for emphasized text.
3720 Text starting and ending with a special character will be emphasized, for
3721 example *bold*, _underlined_ and /italic/. This variable sets the marker
3722 characters, the face to be used by font-lock for highlighting in Org-mode
3723 Emacs buffers, and the HTML tags to be used for this.
3724 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3725 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3726 Use customize to modify this, or restart Emacs after changing it."
3727 :group 'org-appearance
3728 :set 'org-set-emph-re
3729 :type '(repeat
3730 (list
3731 (string :tag "Marker character")
3732 (choice
3733 (face :tag "Font-lock-face")
3734 (plist :tag "Face property list"))
3735 (string :tag "HTML start tag")
3736 (string :tag "HTML end tag")
3737 (option (const verbatim)))))
3739 (defvar org-protecting-blocks
3740 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3741 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3742 This is needed for font-lock setup.")
3744 ;;; Miscellaneous options
3746 (defgroup org-completion nil
3747 "Completion in Org-mode."
3748 :tag "Org Completion"
3749 :group 'org)
3751 (defcustom org-completion-use-ido nil
3752 "Non-nil means use ido completion wherever possible.
3753 Note that `ido-mode' must be active for this variable to be relevant.
3754 If you decide to turn this variable on, you might well want to turn off
3755 `org-outline-path-complete-in-steps'.
3756 See also `org-completion-use-iswitchb'."
3757 :group 'org-completion
3758 :type 'boolean)
3760 (defcustom org-completion-use-iswitchb nil
3761 "Non-nil means use iswitchb completion wherever possible.
3762 Note that `iswitchb-mode' must be active for this variable to be relevant.
3763 If you decide to turn this variable on, you might well want to turn off
3764 `org-outline-path-complete-in-steps'.
3765 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3766 :group 'org-completion
3767 :type 'boolean)
3769 (defcustom org-completion-fallback-command 'hippie-expand
3770 "The expansion command called by \\[pcomplete] in normal context.
3771 Normal means, no org-mode-specific context."
3772 :group 'org-completion
3773 :type 'function)
3775 ;;; Functions and variables from their packages
3776 ;; Declared here to avoid compiler warnings
3778 ;; XEmacs only
3779 (defvar outline-mode-menu-heading)
3780 (defvar outline-mode-menu-show)
3781 (defvar outline-mode-menu-hide)
3782 (defvar zmacs-regions) ; XEmacs regions
3784 ;; Emacs only
3785 (defvar mark-active)
3787 ;; Various packages
3788 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3789 (declare-function calendar-forward-day "cal-move" (arg))
3790 (declare-function calendar-goto-date "cal-move" (date))
3791 (declare-function calendar-goto-today "cal-move" ())
3792 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3793 (defvar calc-embedded-close-formula)
3794 (defvar calc-embedded-open-formula)
3795 (declare-function cdlatex-tab "ext:cdlatex" ())
3796 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3797 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3798 (defvar font-lock-unfontify-region-function)
3799 (declare-function iswitchb-read-buffer "iswitchb"
3800 (prompt &optional default require-match start matches-set))
3801 (defvar iswitchb-temp-buflist)
3802 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3803 (defvar org-agenda-tags-todo-honor-ignore-options)
3804 (declare-function org-agenda-skip "org-agenda" ())
3805 (declare-function
3806 org-agenda-format-item "org-agenda"
3807 (extra txt &optional category tags dotime noprefix remove-re habitp))
3808 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3809 (declare-function org-agenda-change-all-lines "org-agenda"
3810 (newhead hdmarker &optional fixface just-this))
3811 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3812 (declare-function org-agenda-maybe-redo "org-agenda" ())
3813 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3814 (beg end))
3815 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3816 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3817 "org-agenda" (&optional end))
3818 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3819 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3820 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3821 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3822 (declare-function org-indent-mode "org-indent" (&optional arg))
3823 (declare-function parse-time-string "parse-time" (string))
3824 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3825 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3826 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3827 (defvar remember-data-file)
3828 (defvar texmathp-why)
3829 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3830 (declare-function table--at-cell-p "table" (position &optional object at-column))
3832 (defvar w3m-current-url)
3833 (defvar w3m-current-title)
3835 (defvar org-latex-regexps)
3837 ;;; Autoload and prepare some org modules
3839 ;; Some table stuff that needs to be defined here, because it is used
3840 ;; by the functions setting up org-mode or checking for table context.
3842 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3843 "Detect an org-type or table-type table.")
3844 (defconst org-table-line-regexp "^[ \t]*|"
3845 "Detect an org-type table line.")
3846 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3847 "Detect an org-type table line.")
3848 (defconst org-table-hline-regexp "^[ \t]*|-"
3849 "Detect an org-type table hline.")
3850 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3851 "Detect a table-type table hline.")
3852 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3853 "Detect the first line outside a table when searching from within it.
3854 This works for both table types.")
3856 ;; Autoload the functions in org-table.el that are needed by functions here.
3858 (eval-and-compile
3859 (org-autoload "org-table"
3860 '(org-table-align org-table-begin org-table-blank-field
3861 org-table-convert org-table-convert-region org-table-copy-down
3862 org-table-copy-region org-table-create
3863 org-table-create-or-convert-from-region
3864 org-table-create-with-table.el org-table-current-dline
3865 org-table-cut-region org-table-delete-column org-table-edit-field
3866 org-table-edit-formulas org-table-end org-table-eval-formula
3867 org-table-export org-table-field-info
3868 org-table-get-stored-formulas org-table-goto-column
3869 org-table-hline-and-move org-table-import org-table-insert-column
3870 org-table-insert-hline org-table-insert-row org-table-iterate
3871 org-table-justify-field-maybe org-table-kill-row
3872 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3873 org-table-move-column org-table-move-column-left
3874 org-table-move-column-right org-table-move-row
3875 org-table-move-row-down org-table-move-row-up
3876 org-table-next-field org-table-next-row org-table-paste-rectangle
3877 org-table-previous-field org-table-recalculate
3878 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3879 org-table-toggle-coordinate-overlays
3880 org-table-toggle-formula-debugger org-table-wrap-region
3881 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3882 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3883 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3885 (defun org-at-table-p (&optional table-type)
3886 "Return t if the cursor is inside an org-type table.
3887 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3888 (if org-enable-table-editor
3889 (save-excursion
3890 (beginning-of-line 1)
3891 (looking-at (if table-type org-table-any-line-regexp
3892 org-table-line-regexp)))
3893 nil))
3894 (defsubst org-table-p () (org-at-table-p))
3896 (defun org-at-table.el-p ()
3897 "Return t if and only if we are at a table.el table."
3898 (and (org-at-table-p 'any)
3899 (save-excursion
3900 (goto-char (org-table-begin 'any))
3901 (looking-at org-table1-hline-regexp))))
3902 (defun org-table-recognize-table.el ()
3903 "If there is a table.el table nearby, recognize it and move into it."
3904 (if org-table-tab-recognizes-table.el
3905 (if (org-at-table.el-p)
3906 (progn
3907 (beginning-of-line 1)
3908 (if (looking-at org-table-dataline-regexp)
3910 (if (looking-at org-table1-hline-regexp)
3911 (progn
3912 (beginning-of-line 2)
3913 (if (looking-at org-table-any-border-regexp)
3914 (beginning-of-line -1)))))
3915 (if (re-search-forward "|" (org-table-end t) t)
3916 (progn
3917 (require 'table)
3918 (if (table--at-cell-p (point))
3920 (message "recognizing table.el table...")
3921 (table-recognize-table)
3922 (message "recognizing table.el table...done")))
3923 (error "This should not happen"))
3925 nil)
3926 nil))
3928 (defun org-at-table-hline-p ()
3929 "Return t if the cursor is inside a hline in a table."
3930 (if org-enable-table-editor
3931 (save-excursion
3932 (beginning-of-line 1)
3933 (looking-at org-table-hline-regexp))
3934 nil))
3936 (defvar org-table-clean-did-remove-column nil)
3938 (defun org-table-map-tables (function &optional quietly)
3939 "Apply FUNCTION to the start of all tables in the buffer."
3940 (save-excursion
3941 (save-restriction
3942 (widen)
3943 (goto-char (point-min))
3944 (while (re-search-forward org-table-any-line-regexp nil t)
3945 (unless quietly
3946 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3947 (beginning-of-line 1)
3948 (when (looking-at org-table-line-regexp)
3949 (save-excursion (funcall function))
3950 (or (looking-at org-table-line-regexp)
3951 (forward-char 1)))
3952 (re-search-forward org-table-any-border-regexp nil 1))))
3953 (unless quietly (message "Mapping tables: done")))
3955 ;; Declare and autoload functions from org-exp.el & Co
3957 (declare-function org-default-export-plist "org-exp")
3958 (declare-function org-infile-export-plist "org-exp")
3959 (declare-function org-get-current-options "org-exp")
3960 (eval-and-compile
3961 (org-autoload "org-exp"
3962 '(org-export org-export-visible
3963 org-insert-export-options-template
3964 org-table-clean-before-export))
3965 (org-autoload "org-ascii"
3966 '(org-export-as-ascii org-export-ascii-preprocess
3967 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3968 org-export-region-as-ascii))
3969 (org-autoload "org-latex"
3970 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3971 org-replace-region-by-latex org-export-region-as-latex
3972 org-export-as-latex org-export-as-pdf
3973 org-export-as-pdf-and-open))
3974 (org-autoload "org-html"
3975 '(org-export-as-html-and-open
3976 org-export-as-html-batch org-export-as-html-to-buffer
3977 org-replace-region-by-html org-export-region-as-html
3978 org-export-as-html))
3979 (org-autoload "org-docbook"
3980 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3981 org-replace-region-by-docbook org-export-region-as-docbook
3982 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3983 org-export-as-docbook))
3984 (org-autoload "org-icalendar"
3985 '(org-export-icalendar-this-file
3986 org-export-icalendar-all-agenda-files
3987 org-export-icalendar-combine-agenda-files))
3988 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3989 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3991 ;; Declare and autoload functions from org-agenda.el
3993 (eval-and-compile
3994 (org-autoload "org-agenda"
3995 '(org-agenda org-agenda-list org-search-view
3996 org-todo-list org-tags-view org-agenda-list-stuck-projects
3997 org-diary org-agenda-to-appt
3998 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4000 ;; Autoload org-remember
4002 (eval-and-compile
4003 (org-autoload "org-remember"
4004 '(org-remember-insinuate org-remember-annotation
4005 org-remember-apply-template org-remember org-remember-handler)))
4007 (eval-and-compile
4008 (org-autoload "org-capture"
4009 '(org-capture org-capture-insert-template-here
4010 org-capture-import-remember-templates)))
4012 ;; Autoload org-clock.el
4014 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4015 (beg end))
4016 (declare-function org-clock-update-mode-line "org-clock" ())
4017 (declare-function org-resolve-clocks "org-clock"
4018 (&optional also-non-dangling-p prompt last-valid))
4019 (defvar org-clock-start-time)
4020 (defvar org-clock-marker (make-marker)
4021 "Marker recording the last clock-in.")
4022 (defvar org-clock-hd-marker (make-marker)
4023 "Marker recording the last clock-in, but the headline position.")
4024 (defvar org-clock-heading ""
4025 "The heading of the current clock entry.")
4026 (defun org-clock-is-active ()
4027 "Return non-nil if clock is currently running.
4028 The return value is actually the clock marker."
4029 (marker-buffer org-clock-marker))
4031 (eval-and-compile
4032 (org-autoload
4033 "org-clock"
4034 '(org-clock-in org-clock-out org-clock-cancel
4035 org-clock-goto org-clock-sum org-clock-display
4036 org-clock-remove-overlays org-clock-report
4037 org-clocktable-shift org-dblock-write:clocktable
4038 org-get-clocktable org-resolve-clocks)))
4040 (defun org-clock-update-time-maybe ()
4041 "If this is a CLOCK line, update it and return t.
4042 Otherwise, return nil."
4043 (interactive)
4044 (save-excursion
4045 (beginning-of-line 1)
4046 (skip-chars-forward " \t")
4047 (when (looking-at org-clock-string)
4048 (let ((re (concat "[ \t]*" org-clock-string
4049 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4050 "\\([ \t]*=>.*\\)?\\)?"))
4051 ts te h m s neg)
4052 (cond
4053 ((not (looking-at re))
4054 nil)
4055 ((not (match-end 2))
4056 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4057 (> org-clock-marker (point))
4058 (<= org-clock-marker (point-at-eol)))
4059 ;; The clock is running here
4060 (setq org-clock-start-time
4061 (apply 'encode-time
4062 (org-parse-time-string (match-string 1))))
4063 (org-clock-update-mode-line)))
4065 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4066 (end-of-line 1)
4067 (setq ts (match-string 1)
4068 te (match-string 3))
4069 (setq s (- (org-float-time
4070 (apply 'encode-time (org-parse-time-string te)))
4071 (org-float-time
4072 (apply 'encode-time (org-parse-time-string ts))))
4073 neg (< s 0)
4074 s (abs s)
4075 h (floor (/ s 3600))
4076 s (- s (* 3600 h))
4077 m (floor (/ s 60))
4078 s (- s (* 60 s)))
4079 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4080 t))))))
4082 (defun org-check-running-clock ()
4083 "Check if the current buffer contains the running clock.
4084 If yes, offer to stop it and to save the buffer with the changes."
4085 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4086 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4087 (buffer-name))))
4088 (org-clock-out)
4089 (when (y-or-n-p "Save changed buffer?")
4090 (save-buffer))))
4092 (defun org-clocktable-try-shift (dir n)
4093 "Check if this line starts a clock table, if yes, shift the time block."
4094 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4095 (org-clocktable-shift dir n)))
4097 ;; Autoload org-timer.el
4099 (eval-and-compile
4100 (org-autoload
4101 "org-timer"
4102 '(org-timer-start org-timer org-timer-item
4103 org-timer-change-times-in-region
4104 org-timer-set-timer
4105 org-timer-reset-timers
4106 org-timer-show-remaining-time)))
4108 ;; Autoload org-feed.el
4110 (eval-and-compile
4111 (org-autoload
4112 "org-feed"
4113 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4116 ;; Autoload org-indent.el
4118 ;; Define the variable already here, to make sure we have it.
4119 (defvar org-indent-mode nil
4120 "Non-nil if Org-Indent mode is enabled.
4121 Use the command `org-indent-mode' to change this variable.")
4123 (eval-and-compile
4124 (org-autoload
4125 "org-indent"
4126 '(org-indent-mode)))
4128 ;; Autoload org-mobile.el
4130 (eval-and-compile
4131 (org-autoload
4132 "org-mobile"
4133 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4135 ;; Autoload archiving code
4136 ;; The stuff that is needed for cycling and tags has to be defined here.
4138 (defgroup org-archive nil
4139 "Options concerning archiving in Org-mode."
4140 :tag "Org Archive"
4141 :group 'org-structure)
4143 (defcustom org-archive-location "%s_archive::"
4144 "The location where subtrees should be archived.
4146 The value of this variable is a string, consisting of two parts,
4147 separated by a double-colon. The first part is a filename and
4148 the second part is a headline.
4150 When the filename is omitted, archiving happens in the same file.
4151 %s in the filename will be replaced by the current file
4152 name (without the directory part). Archiving to a different file
4153 is useful to keep archived entries from contributing to the
4154 Org-mode Agenda.
4156 The archived entries will be filed as subtrees of the specified
4157 headline. When the headline is omitted, the subtrees are simply
4158 filed away at the end of the file, as top-level entries. Also in
4159 the heading you can use %s to represent the file name, this can be
4160 useful when using the same archive for a number of different files.
4162 Here are a few examples:
4163 \"%s_archive::\"
4164 If the current file is Projects.org, archive in file
4165 Projects.org_archive, as top-level trees. This is the default.
4167 \"::* Archived Tasks\"
4168 Archive in the current file, under the top-level headline
4169 \"* Archived Tasks\".
4171 \"~/org/archive.org::\"
4172 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4174 \"~/org/archive.org::* From %s\"
4175 Archive in file ~/org/archive.org (absolute path), under headlines
4176 \"From FILENAME\" where file name is the current file name.
4178 \"basement::** Finished Tasks\"
4179 Archive in file ./basement (relative path), as level 3 trees
4180 below the level 2 heading \"** Finished Tasks\".
4182 You may set this option on a per-file basis by adding to the buffer a
4183 line like
4185 #+ARCHIVE: basement::** Finished Tasks
4187 You may also define it locally for a subtree by setting an ARCHIVE property
4188 in the entry. If such a property is found in an entry, or anywhere up
4189 the hierarchy, it will be used."
4190 :group 'org-archive
4191 :type 'string)
4193 (defcustom org-archive-tag "ARCHIVE"
4194 "The tag that marks a subtree as archived.
4195 An archived subtree does not open during visibility cycling, and does
4196 not contribute to the agenda listings.
4197 After changing this, font-lock must be restarted in the relevant buffers to
4198 get the proper fontification."
4199 :group 'org-archive
4200 :group 'org-keywords
4201 :type 'string)
4203 (defcustom org-agenda-skip-archived-trees t
4204 "Non-nil means the agenda will skip any items located in archived trees.
4205 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4206 variable is no longer recommended, you should leave it at the value t.
4207 Instead, use the key `v' to cycle the archives-mode in the agenda."
4208 :group 'org-archive
4209 :group 'org-agenda-skip
4210 :type 'boolean)
4212 (defcustom org-columns-skip-archived-trees t
4213 "Non-nil means ignore archived trees when creating column view."
4214 :group 'org-archive
4215 :group 'org-properties
4216 :type 'boolean)
4218 (defcustom org-cycle-open-archived-trees nil
4219 "Non-nil means `org-cycle' will open archived trees.
4220 An archived tree is a tree marked with the tag ARCHIVE.
4221 When nil, archived trees will stay folded. You can still open them with
4222 normal outline commands like `show-all', but not with the cycling commands."
4223 :group 'org-archive
4224 :group 'org-cycle
4225 :type 'boolean)
4227 (defcustom org-sparse-tree-open-archived-trees nil
4228 "Non-nil means sparse tree construction shows matches in archived trees.
4229 When nil, matches in these trees are highlighted, but the trees are kept in
4230 collapsed state."
4231 :group 'org-archive
4232 :group 'org-sparse-trees
4233 :type 'boolean)
4235 (defun org-cycle-hide-archived-subtrees (state)
4236 "Re-hide all archived subtrees after a visibility state change."
4237 (when (and (not org-cycle-open-archived-trees)
4238 (not (memq state '(overview folded))))
4239 (save-excursion
4240 (let* ((globalp (memq state '(contents all)))
4241 (beg (if globalp (point-min) (point)))
4242 (end (if globalp (point-max) (org-end-of-subtree t))))
4243 (org-hide-archived-subtrees beg end)
4244 (goto-char beg)
4245 (if (looking-at (concat ".*:" org-archive-tag ":"))
4246 (message "%s" (substitute-command-keys
4247 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4249 (defun org-force-cycle-archived ()
4250 "Cycle subtree even if it is archived."
4251 (interactive)
4252 (setq this-command 'org-cycle)
4253 (let ((org-cycle-open-archived-trees t))
4254 (call-interactively 'org-cycle)))
4256 (defun org-hide-archived-subtrees (beg end)
4257 "Re-hide all archived subtrees after a visibility state change."
4258 (save-excursion
4259 (let* ((re (concat ":" org-archive-tag ":")))
4260 (goto-char beg)
4261 (while (re-search-forward re end t)
4262 (when (org-at-heading-p)
4263 (org-flag-subtree t)
4264 (org-end-of-subtree t))))))
4266 (defun org-flag-subtree (flag)
4267 (save-excursion
4268 (org-back-to-heading t)
4269 (outline-end-of-heading)
4270 (outline-flag-region (point)
4271 (progn (org-end-of-subtree t) (point))
4272 flag)))
4274 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4276 (eval-and-compile
4277 (org-autoload "org-archive"
4278 '(org-add-archive-files org-archive-subtree
4279 org-archive-to-archive-sibling org-toggle-archive-tag
4280 org-archive-subtree-default
4281 org-archive-subtree-default-with-confirmation)))
4283 ;; Autoload Column View Code
4285 (declare-function org-columns-number-to-string "org-colview")
4286 (declare-function org-columns-get-format-and-top-level "org-colview")
4287 (declare-function org-columns-compute "org-colview")
4289 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4290 '(org-columns-number-to-string org-columns-get-format-and-top-level
4291 org-columns-compute org-agenda-columns org-columns-remove-overlays
4292 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4294 ;; Autoload ID code
4296 (declare-function org-id-store-link "org-id")
4297 (declare-function org-id-locations-load "org-id")
4298 (declare-function org-id-locations-save "org-id")
4299 (defvar org-id-track-globally)
4300 (org-autoload "org-id"
4301 '(org-id-get-create org-id-new org-id-copy org-id-get
4302 org-id-get-with-outline-path-completion
4303 org-id-get-with-outline-drilling org-id-store-link
4304 org-id-goto org-id-find org-id-store-link))
4306 ;; Autoload Plotting Code
4308 (org-autoload "org-plot"
4309 '(org-plot/gnuplot))
4311 ;;; Variables for pre-computed regular expressions, all buffer local
4313 (defvar org-drawer-regexp nil
4314 "Matches first line of a hidden block.")
4315 (make-variable-buffer-local 'org-drawer-regexp)
4316 (defvar org-todo-regexp nil
4317 "Matches any of the TODO state keywords.")
4318 (make-variable-buffer-local 'org-todo-regexp)
4319 (defvar org-not-done-regexp nil
4320 "Matches any of the TODO state keywords except the last one.")
4321 (make-variable-buffer-local 'org-not-done-regexp)
4322 (defvar org-not-done-heading-regexp nil
4323 "Matches a TODO headline that is not done.")
4324 (make-variable-buffer-local 'org-not-done-regexp)
4325 (defvar org-todo-line-regexp nil
4326 "Matches a headline and puts TODO state into group 2 if present.")
4327 (make-variable-buffer-local 'org-todo-line-regexp)
4328 (defvar org-complex-heading-regexp nil
4329 "Matches a headline and puts everything into groups:
4330 group 1: the stars
4331 group 2: The todo keyword, maybe
4332 group 3: Priority cookie
4333 group 4: True headline
4334 group 5: Tags")
4335 (make-variable-buffer-local 'org-complex-heading-regexp)
4336 (defvar org-complex-heading-regexp-format nil
4337 "Printf format to make regexp to match an exact headline.
4338 This regexp will match the headline of any node which has the
4339 exact headline text that is put into the format, but may have any
4340 TODO state, priority and tags.")
4341 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4342 (defvar org-todo-line-tags-regexp nil
4343 "Matches a headline and puts TODO state into group 2 if present.
4344 Also put tags into group 4 if tags are present.")
4345 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4346 (defvar org-ds-keyword-length 12
4347 "Maximum length of the Deadline and SCHEDULED keywords.")
4348 (make-variable-buffer-local 'org-ds-keyword-length)
4349 (defvar org-deadline-regexp nil
4350 "Matches the DEADLINE keyword.")
4351 (make-variable-buffer-local 'org-deadline-regexp)
4352 (defvar org-deadline-time-regexp nil
4353 "Matches the DEADLINE keyword together with a time stamp.")
4354 (make-variable-buffer-local 'org-deadline-time-regexp)
4355 (defvar org-deadline-line-regexp nil
4356 "Matches the DEADLINE keyword and the rest of the line.")
4357 (make-variable-buffer-local 'org-deadline-line-regexp)
4358 (defvar org-scheduled-regexp nil
4359 "Matches the SCHEDULED keyword.")
4360 (make-variable-buffer-local 'org-scheduled-regexp)
4361 (defvar org-scheduled-time-regexp nil
4362 "Matches the SCHEDULED keyword together with a time stamp.")
4363 (make-variable-buffer-local 'org-scheduled-time-regexp)
4364 (defvar org-closed-time-regexp nil
4365 "Matches the CLOSED keyword together with a time stamp.")
4366 (make-variable-buffer-local 'org-closed-time-regexp)
4368 (defvar org-keyword-time-regexp nil
4369 "Matches any of the 4 keywords, together with the time stamp.")
4370 (make-variable-buffer-local 'org-keyword-time-regexp)
4371 (defvar org-keyword-time-not-clock-regexp nil
4372 "Matches any of the 3 keywords, together with the time stamp.")
4373 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4374 (defvar org-maybe-keyword-time-regexp nil
4375 "Matches a timestamp, possibly preceded by a keyword.")
4376 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4377 (defvar org-planning-or-clock-line-re nil
4378 "Matches a line with planning or clock info.")
4379 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4380 (defvar org-all-time-keywords nil
4381 "List of time keywords.")
4382 (make-variable-buffer-local 'org-all-time-keywords)
4384 (defconst org-plain-time-of-day-regexp
4385 (concat
4386 "\\(\\<[012]?[0-9]"
4387 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4388 "\\(--?"
4389 "\\(\\<[012]?[0-9]"
4390 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4391 "\\)?")
4392 "Regular expression to match a plain time or time range.
4393 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4394 groups carry important information:
4395 0 the full match
4396 1 the first time, range or not
4397 8 the second time, if it is a range.")
4399 (defconst org-plain-time-extension-regexp
4400 (concat
4401 "\\(\\<[012]?[0-9]"
4402 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4403 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4404 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4405 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4406 groups carry important information:
4407 0 the full match
4408 7 hours of duration
4409 9 minutes of duration")
4411 (defconst org-stamp-time-of-day-regexp
4412 (concat
4413 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4414 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4415 "\\(--?"
4416 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4417 "Regular expression to match a timestamp time or time range.
4418 After a match, the following groups carry important information:
4419 0 the full match
4420 1 date plus weekday, for back referencing to make sure both times are on the same day
4421 2 the first time, range or not
4422 4 the second time, if it is a range.")
4424 (defconst org-startup-options
4425 '(("fold" org-startup-folded t)
4426 ("overview" org-startup-folded t)
4427 ("nofold" org-startup-folded nil)
4428 ("showall" org-startup-folded nil)
4429 ("showeverything" org-startup-folded showeverything)
4430 ("content" org-startup-folded content)
4431 ("indent" org-startup-indented t)
4432 ("noindent" org-startup-indented nil)
4433 ("hidestars" org-hide-leading-stars t)
4434 ("showstars" org-hide-leading-stars nil)
4435 ("odd" org-odd-levels-only t)
4436 ("oddeven" org-odd-levels-only nil)
4437 ("align" org-startup-align-all-tables t)
4438 ("noalign" org-startup-align-all-tables nil)
4439 ("inlineimages" org-startup-with-inline-images t)
4440 ("noinlineimages" org-startup-with-inline-images nil)
4441 ("customtime" org-display-custom-times t)
4442 ("logdone" org-log-done time)
4443 ("lognotedone" org-log-done note)
4444 ("nologdone" org-log-done nil)
4445 ("lognoteclock-out" org-log-note-clock-out t)
4446 ("nolognoteclock-out" org-log-note-clock-out nil)
4447 ("logrepeat" org-log-repeat state)
4448 ("lognoterepeat" org-log-repeat note)
4449 ("nologrepeat" org-log-repeat nil)
4450 ("logreschedule" org-log-reschedule time)
4451 ("lognotereschedule" org-log-reschedule note)
4452 ("nologreschedule" org-log-reschedule nil)
4453 ("logredeadline" org-log-redeadline time)
4454 ("lognoteredeadline" org-log-redeadline note)
4455 ("nologredeadline" org-log-redeadline nil)
4456 ("logrefile" org-log-refile time)
4457 ("lognoterefile" org-log-refile note)
4458 ("nologrefile" org-log-refile nil)
4459 ("fninline" org-footnote-define-inline t)
4460 ("nofninline" org-footnote-define-inline nil)
4461 ("fnlocal" org-footnote-section nil)
4462 ("fnauto" org-footnote-auto-label t)
4463 ("fnprompt" org-footnote-auto-label nil)
4464 ("fnconfirm" org-footnote-auto-label confirm)
4465 ("fnplain" org-footnote-auto-label plain)
4466 ("fnadjust" org-footnote-auto-adjust t)
4467 ("nofnadjust" org-footnote-auto-adjust nil)
4468 ("constcgs" constants-unit-system cgs)
4469 ("constSI" constants-unit-system SI)
4470 ("noptag" org-tag-persistent-alist nil)
4471 ("hideblocks" org-hide-block-startup t)
4472 ("nohideblocks" org-hide-block-startup nil)
4473 ("beamer" org-startup-with-beamer-mode t)
4474 ("entitiespretty" org-pretty-entities t)
4475 ("entitiesplain" org-pretty-entities nil))
4476 "Variable associated with STARTUP options for org-mode.
4477 Each element is a list of three items: The startup options as written
4478 in the #+STARTUP line, the corresponding variable, and the value to
4479 set this variable to if the option is found. An optional forth element PUSH
4480 means to push this value onto the list in the variable.")
4482 (defun org-update-property-plist (key val props)
4483 "Update PROPS with KEY and VAL."
4484 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4485 (key (if appending (substring key 0 (- (length key) 1)) key))
4486 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4487 (previous (cdr (assoc key props))))
4488 (if appending
4489 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4490 (cons (cons key val) remainder))))
4492 (defconst org-block-regexp
4493 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4494 "Regular expression for hiding blocks.")
4495 (defconst org-heading-keyword-regexp-format
4496 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4497 "Printf format for a regexp matching an headline with some keyword.
4498 This regexp will match the headline of any node which has the
4499 exact keyword that is put into the format. The keyword isn't in
4500 any group by default, but the stars and the body are.")
4501 (defconst org-heading-keyword-maybe-regexp-format
4502 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4503 "Printf format for a regexp matching an headline, possibly with some keyword.
4504 This regexp can match any headline with the specified keyword, or
4505 without a keyword. The keyword isn't in any group by default,
4506 but the stars and the body are.")
4508 (defun org-set-regexps-and-options ()
4509 "Precompute regular expressions for current buffer."
4510 (when (eq major-mode 'org-mode)
4511 (org-set-local 'org-todo-kwd-alist nil)
4512 (org-set-local 'org-todo-key-alist nil)
4513 (org-set-local 'org-todo-key-trigger nil)
4514 (org-set-local 'org-todo-keywords-1 nil)
4515 (org-set-local 'org-done-keywords nil)
4516 (org-set-local 'org-todo-heads nil)
4517 (org-set-local 'org-todo-sets nil)
4518 (org-set-local 'org-todo-log-states nil)
4519 (org-set-local 'org-file-properties nil)
4520 (org-set-local 'org-file-tags nil)
4521 (let ((re (org-make-options-regexp
4522 '("CATEGORY" "TODO" "COLUMNS"
4523 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4524 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4525 "OPTIONS")
4526 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4527 (splitre "[ \t]+")
4528 (scripts org-use-sub-superscripts)
4529 kwds kws0 kwsa key log value cat arch tags const links hw dws
4530 tail sep kws1 prio props ftags drawers beamer-p
4531 ext-setup-or-nil setup-contents (start 0))
4532 (save-excursion
4533 (save-restriction
4534 (widen)
4535 (goto-char (point-min))
4536 (while (or (and ext-setup-or-nil
4537 (string-match re ext-setup-or-nil start)
4538 (setq start (match-end 0)))
4539 (and (setq ext-setup-or-nil nil start 0)
4540 (re-search-forward re nil t)))
4541 (setq key (upcase (match-string 1 ext-setup-or-nil))
4542 value (org-match-string-no-properties 2 ext-setup-or-nil))
4543 (if (stringp value) (setq value (org-trim value)))
4544 (cond
4545 ((equal key "CATEGORY")
4546 (setq cat value))
4547 ((member key '("SEQ_TODO" "TODO"))
4548 (push (cons 'sequence (org-split-string value splitre)) kwds))
4549 ((equal key "TYP_TODO")
4550 (push (cons 'type (org-split-string value splitre)) kwds))
4551 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4552 ;; general TODO-like setup
4553 (push (cons (intern (downcase (match-string 1 key)))
4554 (org-split-string value splitre)) kwds))
4555 ((equal key "TAGS")
4556 (setq tags (append tags (if tags '("\\n") nil)
4557 (org-split-string value splitre))))
4558 ((equal key "COLUMNS")
4559 (org-set-local 'org-columns-default-format value))
4560 ((equal key "LINK")
4561 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4562 (push (cons (match-string 1 value)
4563 (org-trim (match-string 2 value)))
4564 links)))
4565 ((equal key "PRIORITIES")
4566 (setq prio (org-split-string value " +")))
4567 ((equal key "PROPERTY")
4568 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4569 (setq props (org-update-property-plist (match-string 1 value)
4570 (match-string 2 value)
4571 props))))
4572 ((equal key "FILETAGS")
4573 (when (string-match "\\S-" value)
4574 (setq ftags
4575 (append
4576 ftags
4577 (apply 'append
4578 (mapcar (lambda (x) (org-split-string x ":"))
4579 (org-split-string value)))))))
4580 ((equal key "DRAWERS")
4581 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4582 ((equal key "CONSTANTS")
4583 (setq const (append const (org-split-string value splitre))))
4584 ((equal key "STARTUP")
4585 (let ((opts (org-split-string value splitre))
4586 l var val)
4587 (while (setq l (pop opts))
4588 (when (setq l (assoc l org-startup-options))
4589 (setq var (nth 1 l) val (nth 2 l))
4590 (if (not (nth 3 l))
4591 (set (make-local-variable var) val)
4592 (if (not (listp (symbol-value var)))
4593 (set (make-local-variable var) nil))
4594 (set (make-local-variable var) (symbol-value var))
4595 (add-to-list var val))))))
4596 ((equal key "ARCHIVE")
4597 (setq arch value)
4598 (remove-text-properties 0 (length arch)
4599 '(face t fontified t) arch))
4600 ((equal key "LATEX_CLASS")
4601 (setq beamer-p (equal value "beamer")))
4602 ((equal key "OPTIONS")
4603 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4604 (setq scripts (read (match-string 2 value)))))
4605 ((equal key "SETUPFILE")
4606 (setq setup-contents (org-file-contents
4607 (expand-file-name
4608 (org-remove-double-quotes value))
4609 'noerror))
4610 (if (not ext-setup-or-nil)
4611 (setq ext-setup-or-nil setup-contents start 0)
4612 (setq ext-setup-or-nil
4613 (concat (substring ext-setup-or-nil 0 start)
4614 "\n" setup-contents "\n"
4615 (substring ext-setup-or-nil start)))))))
4616 ;; search for property blocks
4617 (goto-char (point-min))
4618 (while (re-search-forward org-block-regexp nil t)
4619 (when (equal "PROPERTY" (upcase (match-string 1)))
4620 (setq value (replace-regexp-in-string
4621 "[\n\r]" " " (match-string 4)))
4622 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4623 (setq props (org-update-property-plist (match-string 1 value)
4624 (match-string 2 value)
4625 props)))))))
4626 (org-set-local 'org-use-sub-superscripts scripts)
4627 (when cat
4628 (org-set-local 'org-category (intern cat))
4629 (push (cons "CATEGORY" cat) props))
4630 (when prio
4631 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4632 (setq prio (mapcar 'string-to-char prio))
4633 (org-set-local 'org-highest-priority (nth 0 prio))
4634 (org-set-local 'org-lowest-priority (nth 1 prio))
4635 (org-set-local 'org-default-priority (nth 2 prio)))
4636 (and props (org-set-local 'org-file-properties (nreverse props)))
4637 (and ftags (org-set-local 'org-file-tags
4638 (mapcar 'org-add-prop-inherited ftags)))
4639 (and drawers (org-set-local 'org-drawers drawers))
4640 (and arch (org-set-local 'org-archive-location arch))
4641 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4642 ;; Process the TODO keywords
4643 (unless kwds
4644 ;; Use the global values as if they had been given locally.
4645 (setq kwds (default-value 'org-todo-keywords))
4646 (if (stringp (car kwds))
4647 (setq kwds (list (cons org-todo-interpretation
4648 (default-value 'org-todo-keywords)))))
4649 (setq kwds (reverse kwds)))
4650 (setq kwds (nreverse kwds))
4651 (let (inter kws kw)
4652 (while (setq kws (pop kwds))
4653 (let ((kws (or
4654 (run-hook-with-args-until-success
4655 'org-todo-setup-filter-hook kws)
4656 kws)))
4657 (setq inter (pop kws) sep (member "|" kws)
4658 kws0 (delete "|" (copy-sequence kws))
4659 kwsa nil
4660 kws1 (mapcar
4661 (lambda (x)
4662 ;; 1 2
4663 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4664 (progn
4665 (setq kw (match-string 1 x)
4666 key (and (match-end 2) (match-string 2 x))
4667 log (org-extract-log-state-settings x))
4668 (push (cons kw (and key (string-to-char key))) kwsa)
4669 (and log (push log org-todo-log-states))
4671 (error "Invalid TODO keyword %s" x)))
4672 kws0)
4673 kwsa (if kwsa (append '((:startgroup))
4674 (nreverse kwsa)
4675 '((:endgroup))))
4676 hw (car kws1)
4677 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4678 tail (list inter hw (car dws) (org-last dws))))
4679 (add-to-list 'org-todo-heads hw 'append)
4680 (push kws1 org-todo-sets)
4681 (setq org-done-keywords (append org-done-keywords dws nil))
4682 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4683 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4684 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4685 (setq org-todo-sets (nreverse org-todo-sets)
4686 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4687 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4688 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4689 ;; Process the constants
4690 (when const
4691 (let (e cst)
4692 (while (setq e (pop const))
4693 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4694 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4695 (setq org-table-formula-constants-local cst)))
4697 ;; Process the tags.
4698 (when tags
4699 (let (e tgs)
4700 (while (setq e (pop tags))
4701 (cond
4702 ((equal e "{") (push '(:startgroup) tgs))
4703 ((equal e "}") (push '(:endgroup) tgs))
4704 ((equal e "\\n") (push '(:newline) tgs))
4705 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4706 (push (cons (match-string 1 e)
4707 (string-to-char (match-string 2 e)))
4708 tgs))
4709 (t (push (list e) tgs))))
4710 (org-set-local 'org-tag-alist nil)
4711 (while (setq e (pop tgs))
4712 (or (and (stringp (car e))
4713 (assoc (car e) org-tag-alist))
4714 (push e org-tag-alist)))))
4716 ;; Compute the regular expressions and other local variables.
4717 ;; Using `org-outline-regexp-bol' would complicate them much,
4718 ;; because of the fixed white space at the end of that string.
4719 (if (not org-done-keywords)
4720 (setq org-done-keywords (and org-todo-keywords-1
4721 (list (org-last org-todo-keywords-1)))))
4722 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4723 (length org-scheduled-string)
4724 (length org-clock-string)
4725 (length org-closed-string)))
4726 org-drawer-regexp
4727 (concat "^[ \t]*:\\("
4728 (mapconcat 'regexp-quote org-drawers "\\|")
4729 "\\):[ \t]*$")
4730 org-not-done-keywords
4731 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4732 org-todo-regexp
4733 (concat "\\("
4734 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4735 "\\)")
4736 org-not-done-regexp
4737 (concat "\\("
4738 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4739 "\\)")
4740 org-not-done-heading-regexp
4741 (format org-heading-keyword-regexp-format org-not-done-regexp)
4742 org-todo-line-regexp
4743 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4744 org-complex-heading-regexp
4745 (concat "^\\(\\*+\\)"
4746 "\\(?: +" org-todo-regexp "\\)?"
4747 "\\(?: +\\(\\[#.\\]\\)\\)?"
4748 "\\(?: +\\(.*?\\)\\)?"
4749 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4750 "[ \t]*$")
4751 org-complex-heading-regexp-format
4752 (concat "^\\(\\*+\\)"
4753 "\\(?: +" org-todo-regexp "\\)?"
4754 "\\(?: +\\(\\[#.\\]\\)\\)?"
4755 "\\(?: +"
4756 ;; Stats cookies can be stuck to body.
4757 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4758 "\\(%s\\)"
4759 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4760 "\\)"
4761 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4762 "[ \t]*$")
4763 org-todo-line-tags-regexp
4764 (concat "^\\(\\*+\\)"
4765 "\\(?: +" org-todo-regexp "\\)?"
4766 "\\(?: +\\(.*?\\)\\)?"
4767 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4768 "[ \t]*$")
4769 org-deadline-regexp (concat "\\<" org-deadline-string)
4770 org-deadline-time-regexp
4771 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4772 org-deadline-line-regexp
4773 (concat "\\<\\(" org-deadline-string "\\).*")
4774 org-scheduled-regexp
4775 (concat "\\<" org-scheduled-string)
4776 org-scheduled-time-regexp
4777 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4778 org-closed-time-regexp
4779 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4780 org-keyword-time-regexp
4781 (concat "\\<\\(" org-scheduled-string
4782 "\\|" org-deadline-string
4783 "\\|" org-closed-string
4784 "\\|" org-clock-string "\\)"
4785 " *[[<]\\([^]>]+\\)[]>]")
4786 org-keyword-time-not-clock-regexp
4787 (concat "\\<\\(" org-scheduled-string
4788 "\\|" org-deadline-string
4789 "\\|" org-closed-string
4790 "\\)"
4791 " *[[<]\\([^]>]+\\)[]>]")
4792 org-maybe-keyword-time-regexp
4793 (concat "\\(\\<\\(" org-scheduled-string
4794 "\\|" org-deadline-string
4795 "\\|" org-closed-string
4796 "\\|" org-clock-string "\\)\\)?"
4797 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4798 org-planning-or-clock-line-re
4799 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4800 "\\|" org-deadline-string
4801 "\\|" org-closed-string "\\|" org-clock-string
4802 "\\)\\>\\)")
4803 org-all-time-keywords
4804 (mapcar (lambda (w) (substring w 0 -1))
4805 (list org-scheduled-string org-deadline-string
4806 org-clock-string org-closed-string))
4808 (org-compute-latex-and-specials-regexp)
4809 (org-set-font-lock-defaults))))
4811 (defun org-file-contents (file &optional noerror)
4812 "Return the contents of FILE, as a string."
4813 (if (or (not file)
4814 (not (file-readable-p file)))
4815 (if noerror
4816 (progn
4817 (message "Cannot read file \"%s\"" file)
4818 (ding) (sit-for 2)
4820 (error "Cannot read file \"%s\"" file))
4821 (with-temp-buffer
4822 (insert-file-contents file)
4823 (buffer-string))))
4825 (defun org-extract-log-state-settings (x)
4826 "Extract the log state setting from a TODO keyword string.
4827 This will extract info from a string like \"WAIT(w@/!)\"."
4828 (let (kw key log1 log2)
4829 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4830 (setq kw (match-string 1 x)
4831 key (and (match-end 2) (match-string 2 x))
4832 log1 (and (match-end 3) (match-string 3 x))
4833 log2 (and (match-end 4) (match-string 4 x)))
4834 (and (or log1 log2)
4835 (list kw
4836 (and log1 (if (equal log1 "!") 'time 'note))
4837 (and log2 (if (equal log2 "!") 'time 'note)))))))
4839 (defun org-remove-keyword-keys (list)
4840 "Remove a pair of parenthesis at the end of each string in LIST."
4841 (mapcar (lambda (x)
4842 (if (string-match "(.*)$" x)
4843 (substring x 0 (match-beginning 0))
4845 list))
4847 (defun org-assign-fast-keys (alist)
4848 "Assign fast keys to a keyword-key alist.
4849 Respect keys that are already there."
4850 (let (new e (alt ?0))
4851 (while (setq e (pop alist))
4852 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4853 (cdr e)) ;; Key already assigned.
4854 (push e new)
4855 (let ((clist (string-to-list (downcase (car e))))
4856 (used (append new alist)))
4857 (when (= (car clist) ?@)
4858 (pop clist))
4859 (while (and clist (rassoc (car clist) used))
4860 (pop clist))
4861 (unless clist
4862 (while (rassoc alt used)
4863 (incf alt)))
4864 (push (cons (car e) (or (car clist) alt)) new))))
4865 (nreverse new)))
4867 ;;; Some variables used in various places
4869 (defvar org-window-configuration nil
4870 "Used in various places to store a window configuration.")
4871 (defvar org-selected-window nil
4872 "Used in various places to store a window configuration.")
4873 (defvar org-finish-function nil
4874 "Function to be called when `C-c C-c' is used.
4875 This is for getting out of special buffers like remember.")
4878 ;; FIXME: Occasionally check by commenting these, to make sure
4879 ;; no other functions uses these, forgetting to let-bind them.
4880 (defvar entry)
4881 (defvar org-last-state)
4882 (defvar date)
4884 ;; Defined somewhere in this file, but used before definition.
4885 (defvar org-entities) ;; defined in org-entities.el
4886 (defvar org-struct-menu)
4887 (defvar org-org-menu)
4888 (defvar org-tbl-menu)
4890 ;;;; Define the Org-mode
4892 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4893 (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"))
4896 ;; We use a before-change function to check if a table might need
4897 ;; an update.
4898 (defvar org-table-may-need-update t
4899 "Indicates that a table might need an update.
4900 This variable is set by `org-before-change-function'.
4901 `org-table-align' sets it back to nil.")
4902 (defun org-before-change-function (beg end)
4903 "Every change indicates that a table might need an update."
4904 (setq org-table-may-need-update t))
4905 (defvar org-mode-map)
4906 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4907 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4908 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4909 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4910 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4911 (defvar org-table-buffer-is-an nil)
4913 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4914 ;; some places -- e.g. see the macro org-with-limited-levels.
4916 ;; In Org buffers, the value of `outline-regexp' is that of
4917 ;; `org-outline-regexp'. The only function still directly relying on
4918 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4919 ;; job when `orgstruct-mode' is active.
4920 (defvar org-outline-regexp "\\*+ "
4921 "Regexp to match Org headlines.")
4922 (defconst org-outline-regexp-bol "^\\*+ "
4923 "Regexp to match Org headlines.
4924 This is similar to `org-outline-regexp' but additionally makes
4925 sure that we are at the beginning of the line.")
4927 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4928 "Matches an headline, putting stars and text into groups.
4929 Stars are put in group 1 and the trimmed body in group 2.")
4931 (defvar bidi-paragraph-direction)
4932 (defvar buffer-face-mode-face)
4934 ;;;###autoload
4935 (define-derived-mode org-mode outline-mode "Org"
4936 "Outline-based notes management and organizer, alias
4937 \"Carsten's outline-mode for keeping track of everything.\"
4939 Org-mode develops organizational tasks around a NOTES file which
4940 contains information about projects as plain text. Org-mode is
4941 implemented on top of outline-mode, which is ideal to keep the content
4942 of large files well structured. It supports ToDo items, deadlines and
4943 time stamps, which magically appear in the diary listing of the Emacs
4944 calendar. Tables are easily created with a built-in table editor.
4945 Plain text URL-like links connect to websites, emails (VM), Usenet
4946 messages (Gnus), BBDB entries, and any files related to the project.
4947 For printing and sharing of notes, an Org-mode file (or a part of it)
4948 can be exported as a structured ASCII or HTML file.
4950 The following commands are available:
4952 \\{org-mode-map}"
4954 ;; Get rid of Outline menus, they are not needed
4955 ;; Need to do this here because define-derived-mode sets up
4956 ;; the keymap so late. Still, it is a waste to call this each time
4957 ;; we switch another buffer into org-mode.
4958 (if (featurep 'xemacs)
4959 (when (boundp 'outline-mode-menu-heading)
4960 ;; Assume this is Greg's port, it uses easymenu
4961 (easy-menu-remove outline-mode-menu-heading)
4962 (easy-menu-remove outline-mode-menu-show)
4963 (easy-menu-remove outline-mode-menu-hide))
4964 (define-key org-mode-map [menu-bar headings] 'undefined)
4965 (define-key org-mode-map [menu-bar hide] 'undefined)
4966 (define-key org-mode-map [menu-bar show] 'undefined))
4968 (org-load-modules-maybe)
4969 (easy-menu-add org-org-menu)
4970 (easy-menu-add org-tbl-menu)
4971 (org-install-agenda-files-menu)
4972 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4973 (add-to-invisibility-spec '(org-cwidth))
4974 (add-to-invisibility-spec '(org-hide-block . t))
4975 (when (featurep 'xemacs)
4976 (org-set-local 'line-move-ignore-invisible t))
4977 (org-set-local 'outline-regexp org-outline-regexp)
4978 (org-set-local 'outline-level 'org-outline-level)
4979 (setq bidi-paragraph-direction 'left-to-right)
4980 (when (and org-ellipsis
4981 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4982 (fboundp 'make-glyph-code))
4983 (unless org-display-table
4984 (setq org-display-table (make-display-table)))
4985 (set-display-table-slot
4986 org-display-table 4
4987 (vconcat (mapcar
4988 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4989 org-ellipsis)))
4990 (if (stringp org-ellipsis) org-ellipsis "..."))))
4991 (setq buffer-display-table org-display-table))
4992 (org-set-regexps-and-options)
4993 (when (and org-tag-faces (not org-tags-special-faces-re))
4994 ;; tag faces set outside customize.... force initialization.
4995 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4996 ;; Calc embedded
4997 (org-set-local 'calc-embedded-open-mode "# ")
4998 (modify-syntax-entry ?@ "w")
4999 (if org-startup-truncated (setq truncate-lines t))
5000 (org-set-local 'font-lock-unfontify-region-function
5001 'org-unfontify-region)
5002 ;; Activate before-change-function
5003 (org-set-local 'org-table-may-need-update t)
5004 (org-add-hook 'before-change-functions 'org-before-change-function nil
5005 'local)
5006 ;; Check for running clock before killing a buffer
5007 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5008 ;; Paragraphs and auto-filling
5009 (org-set-autofill-regexps)
5010 (setq indent-line-function 'org-indent-line-function)
5011 (org-update-radio-target-regexp)
5012 ;; Beginning/end of defun
5013 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5014 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5015 ;; Next error for sparse trees
5016 (org-set-local 'next-error-function 'org-occur-next-match)
5017 ;; Make sure dependence stuff works reliably, even for users who set it
5018 ;; too late :-(
5019 (if org-enforce-todo-dependencies
5020 (add-hook 'org-blocker-hook
5021 'org-block-todo-from-children-or-siblings-or-parent)
5022 (remove-hook 'org-blocker-hook
5023 'org-block-todo-from-children-or-siblings-or-parent))
5024 (if org-enforce-todo-checkbox-dependencies
5025 (add-hook 'org-blocker-hook
5026 'org-block-todo-from-checkboxes)
5027 (remove-hook 'org-blocker-hook
5028 'org-block-todo-from-checkboxes))
5030 ;; Comment characters
5031 (org-set-local 'comment-start "#")
5032 (org-set-local 'comment-padding " ")
5034 ;; Align options lines
5035 (org-set-local
5036 'align-mode-rules-list
5037 '((org-in-buffer-settings
5038 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5039 (modes . '(org-mode)))))
5041 ;; Imenu
5042 (org-set-local 'imenu-create-index-function
5043 'org-imenu-get-tree)
5045 ;; Make isearch reveal context
5046 (if (or (featurep 'xemacs)
5047 (not (boundp 'outline-isearch-open-invisible-function)))
5048 ;; Emacs 21 and XEmacs make use of the hook
5049 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5050 ;; Emacs 22 deals with this through a special variable
5051 (org-set-local 'outline-isearch-open-invisible-function
5052 (lambda (&rest ignore) (org-show-context 'isearch))))
5054 ;; Turn on org-beamer-mode?
5055 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5057 ;; Setup the pcomplete hooks
5058 (set (make-local-variable 'pcomplete-command-completion-function)
5059 'org-pcomplete-initial)
5060 (set (make-local-variable 'pcomplete-command-name-function)
5061 'org-command-at-point)
5062 (set (make-local-variable 'pcomplete-default-completion-function)
5063 'ignore)
5064 (set (make-local-variable 'pcomplete-parse-arguments-function)
5065 'org-parse-arguments)
5066 (set (make-local-variable 'pcomplete-termination-string) "")
5067 (when (>= emacs-major-version 23)
5068 (set (make-local-variable 'buffer-face-mode-face) 'org-default)
5069 (buffer-face-mode))
5071 ;; If empty file that did not turn on org-mode automatically, make it to.
5072 (if (and org-insert-mode-line-in-empty-file
5073 (org-called-interactively-p 'any)
5074 (= (point-min) (point-max)))
5075 (insert "# -*- mode: org -*-\n\n"))
5076 (unless org-inhibit-startup
5077 (when org-startup-align-all-tables
5078 (let ((bmp (buffer-modified-p)))
5079 (org-table-map-tables 'org-table-align 'quietly)
5080 (set-buffer-modified-p bmp)))
5081 (when org-startup-with-inline-images
5082 (org-display-inline-images))
5083 (when org-startup-indented
5084 (require 'org-indent)
5085 (org-indent-mode 1))
5086 (unless org-inhibit-startup-visibility-stuff
5087 (org-set-startup-visibility))))
5089 (when (fboundp 'abbrev-table-put)
5090 (abbrev-table-put org-mode-abbrev-table
5091 :parents (list text-mode-abbrev-table)))
5093 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5095 (defun org-current-time ()
5096 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5097 (if (> (car org-time-stamp-rounding-minutes) 1)
5098 (let ((r (car org-time-stamp-rounding-minutes))
5099 (time (decode-time)))
5100 (apply 'encode-time
5101 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5102 (nthcdr 2 time))))
5103 (current-time)))
5105 (defun org-today ()
5106 "Return today date, considering `org-extend-today-until'."
5107 (time-to-days
5108 (time-subtract (current-time)
5109 (list 0 (* 3600 org-extend-today-until) 0))))
5111 ;;;; Font-Lock stuff, including the activators
5113 (defvar org-mouse-map (make-sparse-keymap))
5114 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5115 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5116 (when org-mouse-1-follows-link
5117 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5118 (when org-tab-follows-link
5119 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5120 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5122 (require 'font-lock)
5124 (defconst org-non-link-chars "]\t\n\r<>")
5125 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5126 "shell" "elisp" "doi" "message"))
5127 (defvar org-link-types-re nil
5128 "Matches a link that has a url-like prefix like \"http:\"")
5129 (defvar org-link-re-with-space nil
5130 "Matches a link with spaces, optional angular brackets around it.")
5131 (defvar org-link-re-with-space2 nil
5132 "Matches a link with spaces, optional angular brackets around it.")
5133 (defvar org-link-re-with-space3 nil
5134 "Matches a link with spaces, only for internal part in bracket links.")
5135 (defvar org-angle-link-re nil
5136 "Matches link with angular brackets, spaces are allowed.")
5137 (defvar org-plain-link-re nil
5138 "Matches plain link, without spaces.")
5139 (defvar org-bracket-link-regexp nil
5140 "Matches a link in double brackets.")
5141 (defvar org-bracket-link-analytic-regexp nil
5142 "Regular expression used to analyze links.
5143 Here is what the match groups contain after a match:
5144 1: http:
5145 2: http
5146 3: path
5147 4: [desc]
5148 5: desc")
5149 (defvar org-bracket-link-analytic-regexp++ nil
5150 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5151 (defvar org-any-link-re nil
5152 "Regular expression matching any link.")
5154 (defcustom org-match-sexp-depth 3
5155 "Number of stacked braces for sub/superscript matching.
5156 This has to be set before loading org.el to be effective."
5157 :group 'org-export-translation ; ??????????????????????????/
5158 :type 'integer)
5160 (defun org-create-multibrace-regexp (left right n)
5161 "Create a regular expression which will match a balanced sexp.
5162 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5163 as single character strings.
5164 The regexp returned will match the entire expression including the
5165 delimiters. It will also define a single group which contains the
5166 match except for the outermost delimiters. The maximum depth of
5167 stacked delimiters is N. Escaping delimiters is not possible."
5168 (let* ((nothing (concat "[^" left right "]*?"))
5169 (or "\\|")
5170 (re nothing)
5171 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5172 (while (> n 1)
5173 (setq n (1- n)
5174 re (concat re or next)
5175 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5176 (concat left "\\(" re "\\)" right)))
5178 (defvar org-match-substring-regexp
5179 (concat
5180 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5181 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5182 "\\|"
5183 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5184 "\\|"
5185 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5186 "The regular expression matching a sub- or superscript.")
5188 (defvar org-match-substring-with-braces-regexp
5189 (concat
5190 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5191 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5192 "\\)")
5193 "The regular expression matching a sub- or superscript, forcing braces.")
5195 (defun org-make-link-regexps ()
5196 "Update the link regular expressions.
5197 This should be called after the variable `org-link-types' has changed."
5198 (setq org-link-types-re
5199 (concat
5200 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5201 org-link-re-with-space
5202 (concat
5203 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5204 "\\([^" org-non-link-chars " ]"
5205 "[^" org-non-link-chars "]*"
5206 "[^" org-non-link-chars " ]\\)>?")
5207 org-link-re-with-space2
5208 (concat
5209 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5210 "\\([^" org-non-link-chars " ]"
5211 "[^\t\n\r]*"
5212 "[^" org-non-link-chars " ]\\)>?")
5213 org-link-re-with-space3
5214 (concat
5215 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5216 "\\([^" org-non-link-chars " ]"
5217 "[^\t\n\r]*\\)")
5218 org-angle-link-re
5219 (concat
5220 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5221 "\\([^" org-non-link-chars " ]"
5222 "[^" org-non-link-chars "]*"
5223 "\\)>")
5224 org-plain-link-re
5225 (concat
5226 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5227 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5228 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5229 org-bracket-link-regexp
5230 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5231 org-bracket-link-analytic-regexp
5232 (concat
5233 "\\[\\["
5234 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5235 "\\([^]]+\\)"
5236 "\\]"
5237 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5238 "\\]")
5239 org-bracket-link-analytic-regexp++
5240 (concat
5241 "\\[\\["
5242 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5243 "\\([^]]+\\)"
5244 "\\]"
5245 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5246 "\\]")
5247 org-any-link-re
5248 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5249 org-angle-link-re "\\)\\|\\("
5250 org-plain-link-re "\\)")))
5252 (org-make-link-regexps)
5254 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5255 "Regular expression for fast time stamp matching.")
5256 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5257 "Regular expression for fast time stamp matching.")
5258 (defconst org-ts-regexp0
5259 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5260 "Regular expression matching time strings for analysis.
5261 This one does not require the space after the date, so it can be used
5262 on a string that terminates immediately after the date.")
5263 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5264 "Regular expression matching time strings for analysis.")
5265 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5266 "Regular expression matching time stamps, with groups.")
5267 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5268 "Regular expression matching time stamps (also [..]), with groups.")
5269 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5270 "Regular expression matching a time stamp range.")
5271 (defconst org-tr-regexp-both
5272 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5273 "Regular expression matching a time stamp range.")
5274 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5275 org-ts-regexp "\\)?")
5276 "Regular expression matching a time stamp or time stamp range.")
5277 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5278 org-ts-regexp-both "\\)?")
5279 "Regular expression matching a time stamp or time stamp range.
5280 The time stamps may be either active or inactive.")
5282 (defvar org-emph-face nil)
5284 (defun org-do-emphasis-faces (limit)
5285 "Run through the buffer and add overlays to emphasized strings."
5286 (let (rtn a)
5287 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5288 (if (not (= (char-after (match-beginning 3))
5289 (char-after (match-beginning 4))))
5290 (progn
5291 (setq rtn t)
5292 (setq a (assoc (match-string 3) org-emphasis-alist))
5293 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5294 'face
5295 (nth 1 a))
5296 (and (nth 4 a)
5297 (org-remove-flyspell-overlays-in
5298 (match-beginning 0) (match-end 0)))
5299 (add-text-properties (match-beginning 2) (match-end 2)
5300 '(font-lock-multiline t org-emphasis t))
5301 (when org-hide-emphasis-markers
5302 (add-text-properties (match-end 4) (match-beginning 5)
5303 '(invisible org-link))
5304 (add-text-properties (match-beginning 3) (match-end 3)
5305 '(invisible org-link)))))
5306 (backward-char 1))
5307 rtn))
5309 (defun org-emphasize (&optional char)
5310 "Insert or change an emphasis, i.e. a font like bold or italic.
5311 If there is an active region, change that region to a new emphasis.
5312 If there is no region, just insert the marker characters and position
5313 the cursor between them.
5314 CHAR should be either the marker character, or the first character of the
5315 HTML tag associated with that emphasis. If CHAR is a space, the means
5316 to remove the emphasis of the selected region.
5317 If char is not given (for example in an interactive call) it
5318 will be prompted for."
5319 (interactive)
5320 (let ((eal org-emphasis-alist) e det
5321 (erc org-emphasis-regexp-components)
5322 (prompt "")
5323 (string "") beg end move tag c s)
5324 (if (org-region-active-p)
5325 (setq beg (region-beginning) end (region-end)
5326 string (buffer-substring beg end))
5327 (setq move t))
5329 (while (setq e (pop eal))
5330 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5331 c (aref tag 0))
5332 (push (cons c (string-to-char (car e))) det)
5333 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5334 (substring tag 1)))))
5335 (setq det (nreverse det))
5336 (unless char
5337 (message "%s" (concat "Emphasis marker or tag:" prompt))
5338 (setq char (read-char-exclusive)))
5339 (setq char (or (cdr (assoc char det)) char))
5340 (if (equal char ?\ )
5341 (setq s "" move nil)
5342 (unless (assoc (char-to-string char) org-emphasis-alist)
5343 (error "No such emphasis marker: \"%c\"" char))
5344 (setq s (char-to-string char)))
5345 (while (and (> (length string) 1)
5346 (equal (substring string 0 1) (substring string -1))
5347 (assoc (substring string 0 1) org-emphasis-alist))
5348 (setq string (substring string 1 -1)))
5349 (setq string (concat s string s))
5350 (if beg (delete-region beg end))
5351 (unless (or (bolp)
5352 (string-match (concat "[" (nth 0 erc) "\n]")
5353 (char-to-string (char-before (point)))))
5354 (insert " "))
5355 (unless (or (eobp)
5356 (string-match (concat "[" (nth 1 erc) "\n]")
5357 (char-to-string (char-after (point)))))
5358 (insert " ") (backward-char 1))
5359 (insert string)
5360 (and move (backward-char 1))))
5362 (defconst org-nonsticky-props
5363 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5365 (defsubst org-rear-nonsticky-at (pos)
5366 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5368 (defun org-activate-plain-links (limit)
5369 "Run through the buffer and add overlays to links."
5370 (catch 'exit
5371 (let (f)
5372 (if (re-search-forward org-plain-link-re limit t)
5373 (progn
5374 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5375 (setq f (get-text-property (match-beginning 0) 'face))
5376 (if (or (eq f 'org-tag)
5377 (and (listp f) (memq 'org-tag f)))
5379 (add-text-properties (match-beginning 0) (match-end 0)
5380 (list 'mouse-face 'highlight
5381 'face 'org-link
5382 'keymap org-mouse-map))
5383 (org-rear-nonsticky-at (match-end 0)))
5384 t)))))
5386 (defun org-activate-code (limit)
5387 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5388 (progn
5389 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5390 (remove-text-properties (match-beginning 0) (match-end 0)
5391 '(display t invisible t intangible t))
5392 t)))
5394 (defcustom org-src-fontify-natively nil
5395 "When non-nil, fontify code in code blocks."
5396 :type 'boolean
5397 :version "24.1"
5398 :group 'org-appearance
5399 :group 'org-babel)
5401 (defun org-fontify-meta-lines-and-blocks (limit)
5402 (condition-case nil
5403 (org-fontify-meta-lines-and-blocks-1 limit)
5404 (error (message "org-mode fontification error"))))
5406 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5407 "Fontify #+ lines and blocks, in the correct ways."
5408 (let ((case-fold-search t))
5409 (if (re-search-forward
5410 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5411 limit t)
5412 (let ((beg (match-beginning 0))
5413 (block-start (match-end 0))
5414 (block-end nil)
5415 (lang (match-string 7))
5416 (beg1 (line-beginning-position 2))
5417 (dc1 (downcase (match-string 2)))
5418 (dc3 (downcase (match-string 3)))
5419 end end1 quoting block-type ovl)
5420 (cond
5421 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5422 ;; a single line of backend-specific content
5423 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5424 (remove-text-properties (match-beginning 0) (match-end 0)
5425 '(display t invisible t intangible t))
5426 (add-text-properties (match-beginning 1) (match-end 3)
5427 '(font-lock-fontified t face org-meta-line))
5428 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5429 '(font-lock-fontified t face org-block))
5430 ; for backend-specific code
5432 ((and (match-end 4) (equal dc3 "begin"))
5433 ;; Truly a block
5434 (setq block-type (downcase (match-string 5))
5435 quoting (member block-type org-protecting-blocks))
5436 (when (re-search-forward
5437 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5438 nil t) ;; on purpose, we look further than LIMIT
5439 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5440 (setq block-end (match-beginning 0))
5441 (when quoting
5442 (remove-text-properties beg end
5443 '(display t invisible t intangible t)))
5444 (add-text-properties
5445 beg end
5446 '(font-lock-fontified t font-lock-multiline t))
5447 (add-text-properties beg beg1 '(face org-meta-line))
5448 (add-text-properties end1 (min (point-max) (1+ end))
5449 '(face org-meta-line)) ; for end_src
5450 (cond
5451 ((and lang (not (string= lang "")) org-src-fontify-natively)
5452 (org-src-font-lock-fontify-block lang block-start block-end)
5453 ;; remove old background overlays
5454 (mapc (lambda (ov)
5455 (if (eq (overlay-get ov 'face) 'org-block-background)
5456 (delete-overlay ov)))
5457 (overlays-at (/ (+ beg1 block-end) 2)))
5458 ;; add a background overlay
5459 (setq ovl (make-overlay beg1 block-end))
5460 (overlay-put ovl 'face 'org-block-background)
5461 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5462 (quoting
5463 (add-text-properties beg1 (min (point-max) (1+ end1))
5464 '(face org-block))) ; end of source block
5465 ((not org-fontify-quote-and-verse-blocks))
5466 ((string= block-type "quote")
5467 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5468 ((string= block-type "verse")
5469 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5470 (add-text-properties beg beg1 '(face org-block-begin-line))
5471 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5473 ((member dc1 '("title:" "author:" "email:" "date:"))
5474 (add-text-properties
5475 beg (match-end 3)
5476 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5477 '(font-lock-fontified t invisible t)
5478 '(font-lock-fontified t face org-document-info-keyword)))
5479 (add-text-properties
5480 (match-beginning 6) (match-end 6)
5481 (if (string-equal dc1 "title:")
5482 '(font-lock-fontified t face org-document-title)
5483 '(font-lock-fontified t face org-document-info))))
5484 ((not (member (char-after beg) '(?\ ?\t)))
5485 ;; just any other in-buffer setting, but not indented
5486 (add-text-properties
5487 beg (match-end 0)
5488 '(font-lock-fontified t face org-meta-line))
5490 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5491 "orgtbl:" "tblfm:" "tblname:" "results:"
5492 "call:" "header:" "headers:" "name:"))
5493 (and (match-end 4) (equal dc3 "attr")))
5494 (add-text-properties
5495 beg (match-end 0)
5496 '(font-lock-fontified t face org-meta-line))
5498 ((member dc3 '(" " ""))
5499 (add-text-properties
5500 beg (match-end 0)
5501 '(font-lock-fontified t face font-lock-comment-face)))
5502 (t nil))))))
5504 (defun org-strip-protective-commas (beg end)
5505 "Strip protective commas between BEG and END in the current buffer."
5506 (interactive "r")
5507 (save-excursion
5508 (save-match-data
5509 (goto-char beg)
5510 (let ((front-line (save-excursion
5511 (re-search-forward
5512 "[^[:space:]]" end t)
5513 (goto-char (match-beginning 0))
5514 (current-column))))
5515 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5516 (goto-char (match-beginning 1))
5517 (when (= (current-column) front-line)
5518 (replace-match "" nil nil nil 1)))))))
5520 (defun org-activate-angle-links (limit)
5521 "Run through the buffer and add overlays to links."
5522 (if (re-search-forward org-angle-link-re limit t)
5523 (progn
5524 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5525 (add-text-properties (match-beginning 0) (match-end 0)
5526 (list 'mouse-face 'highlight
5527 'keymap org-mouse-map))
5528 (org-rear-nonsticky-at (match-end 0))
5529 t)))
5531 (defun org-activate-footnote-links (limit)
5532 "Run through the buffer and add overlays to footnotes."
5533 (let ((fn (org-footnote-next-reference-or-definition limit)))
5534 (when fn
5535 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5536 (org-remove-flyspell-overlays-in beg end)
5537 (add-text-properties beg end
5538 (list 'mouse-face 'highlight
5539 'keymap org-mouse-map
5540 'help-echo
5541 (if (= (point-at-bol) beg)
5542 "Footnote definition"
5543 "Footnote reference")
5544 'font-lock-fontified t
5545 'font-lock-multiline t
5546 'face 'org-footnote))))))
5548 (defun org-activate-bracket-links (limit)
5549 "Run through the buffer and add overlays to bracketed links."
5550 (if (re-search-forward org-bracket-link-regexp limit t)
5551 (let* ((help (concat "LINK: "
5552 (org-match-string-no-properties 1)))
5553 ;; FIXME: above we should remove the escapes.
5554 ;; but that requires another match, protecting match data,
5555 ;; a lot of overhead for font-lock.
5556 (ip (org-maybe-intangible
5557 (list 'invisible 'org-link
5558 'keymap org-mouse-map 'mouse-face 'highlight
5559 'font-lock-multiline t 'help-echo help)))
5560 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5561 'font-lock-multiline t 'help-echo help)))
5562 ;; We need to remove the invisible property here. Table narrowing
5563 ;; may have made some of this invisible.
5564 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5565 (remove-text-properties (match-beginning 0) (match-end 0)
5566 '(invisible nil))
5567 (if (match-end 3)
5568 (progn
5569 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5570 (org-rear-nonsticky-at (match-beginning 3))
5571 (add-text-properties (match-beginning 3) (match-end 3) vp)
5572 (org-rear-nonsticky-at (match-end 3))
5573 (add-text-properties (match-end 3) (match-end 0) ip)
5574 (org-rear-nonsticky-at (match-end 0)))
5575 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5576 (org-rear-nonsticky-at (match-beginning 1))
5577 (add-text-properties (match-beginning 1) (match-end 1) vp)
5578 (org-rear-nonsticky-at (match-end 1))
5579 (add-text-properties (match-end 1) (match-end 0) ip)
5580 (org-rear-nonsticky-at (match-end 0)))
5581 t)))
5583 (defun org-activate-dates (limit)
5584 "Run through the buffer and add overlays to dates."
5585 (if (re-search-forward org-tsr-regexp-both limit t)
5586 (progn
5587 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5588 (add-text-properties (match-beginning 0) (match-end 0)
5589 (list 'mouse-face 'highlight
5590 'keymap org-mouse-map))
5591 (org-rear-nonsticky-at (match-end 0))
5592 (when org-display-custom-times
5593 (if (match-end 3)
5594 (org-display-custom-time (match-beginning 3) (match-end 3)))
5595 (org-display-custom-time (match-beginning 1) (match-end 1)))
5596 t)))
5598 (defvar org-target-link-regexp nil
5599 "Regular expression matching radio targets in plain text.")
5600 (make-variable-buffer-local 'org-target-link-regexp)
5601 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5602 "Regular expression matching a link target.")
5603 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5604 "Regular expression matching a radio target.")
5605 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5606 "Regular expression matching any target.")
5608 (defun org-activate-target-links (limit)
5609 "Run through the buffer and add overlays to target matches."
5610 (when org-target-link-regexp
5611 (let ((case-fold-search t))
5612 (if (re-search-forward org-target-link-regexp limit t)
5613 (progn
5614 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5615 (add-text-properties (match-beginning 0) (match-end 0)
5616 (list 'mouse-face 'highlight
5617 'keymap org-mouse-map
5618 'help-echo "Radio target link"
5619 'org-linked-text t))
5620 (org-rear-nonsticky-at (match-end 0))
5621 t)))))
5623 (defun org-update-radio-target-regexp ()
5624 "Find all radio targets in this file and update the regular expression."
5625 (interactive)
5626 (when (memq 'radio org-activate-links)
5627 (setq org-target-link-regexp
5628 (org-make-target-link-regexp (org-all-targets 'radio)))
5629 (org-restart-font-lock)))
5631 (defun org-hide-wide-columns (limit)
5632 (let (s e)
5633 (setq s (text-property-any (point) (or limit (point-max))
5634 'org-cwidth t))
5635 (when s
5636 (setq e (next-single-property-change s 'org-cwidth))
5637 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5638 (goto-char e)
5639 t)))
5641 (defvar org-latex-and-specials-regexp nil
5642 "Regular expression for highlighting export special stuff.")
5643 (defvar org-match-substring-regexp)
5644 (defvar org-match-substring-with-braces-regexp)
5646 ;; This should be with the exporter code, but we also use if for font-locking
5647 (defconst org-export-html-special-string-regexps
5648 '(("\\\\-" . "&shy;")
5649 ("---\\([^-]\\)" . "&mdash;\\1")
5650 ("--\\([^-]\\)" . "&ndash;\\1")
5651 ("\\.\\.\\." . "&hellip;"))
5652 "Regular expressions for special string conversion.")
5655 (defun org-compute-latex-and-specials-regexp ()
5656 "Compute regular expression for stuff treated specially by exporters."
5657 (if (not org-highlight-latex-fragments-and-specials)
5658 (org-set-local 'org-latex-and-specials-regexp nil)
5659 (require 'org-exp)
5660 (let*
5661 ((matchers (plist-get org-format-latex-options :matchers))
5662 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5663 org-latex-regexps)))
5664 (org-export-allow-BIND nil)
5665 (options (org-combine-plists (org-default-export-plist)
5666 (org-infile-export-plist)))
5667 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5668 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5669 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5670 (org-export-html-expand (plist-get options :expand-quoted-html))
5671 (org-export-with-special-strings (plist-get options :special-strings))
5672 (re-sub
5673 (cond
5674 ((equal org-export-with-sub-superscripts '{})
5675 (list org-match-substring-with-braces-regexp))
5676 (org-export-with-sub-superscripts
5677 (list org-match-substring-regexp))
5678 (t nil)))
5679 (re-latex
5680 (if org-export-with-LaTeX-fragments
5681 (mapcar (lambda (x) (nth 1 x)) latexs)))
5682 (re-macros
5683 (if org-export-with-TeX-macros
5684 (list (concat "\\\\"
5685 (regexp-opt
5686 (append
5688 (delq nil
5689 (mapcar 'car-safe
5690 (append org-entities-user
5691 org-entities)))
5692 (if (boundp 'org-latex-entities)
5693 (mapcar (lambda (x)
5694 (or (car-safe x) x))
5695 org-latex-entities)
5696 nil))
5697 'words))) ; FIXME
5699 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5700 (re-special (if org-export-with-special-strings
5701 (mapcar (lambda (x) (car x))
5702 org-export-html-special-string-regexps)))
5703 (re-rest
5704 (delq nil
5705 (list
5706 (if org-export-html-expand "@<[^>\n]+>")
5707 ))))
5708 (org-set-local
5709 'org-latex-and-specials-regexp
5710 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5711 re-rest) "\\|")))))
5713 (defun org-do-latex-and-special-faces (limit)
5714 "Run through the buffer and add overlays to links."
5715 (when org-latex-and-specials-regexp
5716 (let (rtn d)
5717 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5718 limit t))
5719 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5720 'face))
5721 '(org-code org-verbatim underline)))
5722 (progn
5723 (setq rtn t
5724 d (cond ((member (char-after (1+ (match-beginning 0)))
5725 '(?_ ?^)) 1)
5726 (t 0)))
5727 (font-lock-prepend-text-property
5728 (+ d (match-beginning 0)) (match-end 0)
5729 'face 'org-latex-and-export-specials)
5730 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5731 '(font-lock-multiline t)))))
5732 rtn)))
5734 (defun org-restart-font-lock ()
5735 "Restart `font-lock-mode', to force refontification."
5736 (when (and (boundp 'font-lock-mode) font-lock-mode)
5737 (font-lock-mode -1)
5738 (font-lock-mode 1)))
5740 (defun org-all-targets (&optional radio)
5741 "Return a list of all targets in this file.
5742 With optional argument RADIO, only find radio targets."
5743 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5744 rtn)
5745 (save-excursion
5746 (goto-char (point-min))
5747 (while (re-search-forward re nil t)
5748 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5749 rtn)))
5751 (defun org-make-target-link-regexp (targets)
5752 "Make regular expression matching all strings in TARGETS.
5753 The regular expression finds the targets also if there is a line break
5754 between words."
5755 (and targets
5756 (concat
5757 "\\<\\("
5758 (mapconcat
5759 (lambda (x)
5760 (setq x (regexp-quote x))
5761 (while (string-match " +" x)
5762 (setq x (replace-match "\\s-+" t t x)))
5764 targets
5765 "\\|")
5766 "\\)\\>")))
5768 (defun org-activate-tags (limit)
5769 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5770 (progn
5771 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5772 (add-text-properties (match-beginning 1) (match-end 1)
5773 (list 'mouse-face 'highlight
5774 'keymap org-mouse-map))
5775 (org-rear-nonsticky-at (match-end 1))
5776 t)))
5778 (defun org-outline-level ()
5779 "Compute the outline level of the heading at point.
5780 This function assumes that the cursor is at the beginning of a line matched
5781 by `outline-regexp'. Otherwise it returns garbage.
5782 If this is called at a normal headline, the level is the number of stars.
5783 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5784 (save-excursion
5785 (looking-at org-outline-regexp)
5786 (1- (- (match-end 0) (match-beginning 0)))))
5788 (defvar org-font-lock-keywords nil)
5790 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5791 "Regular expression matching a property line.")
5793 (defvar org-font-lock-hook nil
5794 "Functions to be called for special font lock stuff.")
5796 (defvar org-font-lock-set-keywords-hook nil
5797 "Functions that can manipulate `org-font-lock-extra-keywords'.
5798 This is called after `org-font-lock-extra-keywords' is defined, but before
5799 it is installed to be used by font lock. This can be useful if something
5800 needs to be inserted at a specific position in the font-lock sequence.")
5802 (defun org-font-lock-hook (limit)
5803 (run-hook-with-args 'org-font-lock-hook limit))
5805 (defun org-set-font-lock-defaults ()
5806 (let* ((em org-fontify-emphasized-text)
5807 (lk org-activate-links)
5808 (org-font-lock-extra-keywords
5809 (list
5810 ;; Call the hook
5811 '(org-font-lock-hook)
5812 ;; Headlines
5813 `(,(if org-fontify-whole-heading-line
5814 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5815 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5816 (1 (org-get-level-face 1))
5817 (2 (org-get-level-face 2))
5818 (3 (org-get-level-face 3)))
5819 ;; Table lines
5820 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5821 (1 'org-table t))
5822 ;; Table internals
5823 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5824 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5825 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5826 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5827 ;; Drawers
5828 (list org-drawer-regexp '(0 'org-special-keyword t))
5829 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5830 ;; Properties
5831 (list org-property-re
5832 '(1 'org-special-keyword t)
5833 '(3 'org-property-value t))
5834 ;; Links
5835 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5836 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5837 (if (memq 'plain lk) '(org-activate-plain-links))
5838 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5839 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5840 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5841 (if (memq 'footnote lk) '(org-activate-footnote-links))
5842 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5843 '(org-hide-wide-columns (0 nil append))
5844 ;; TODO keyword
5845 (list (format org-heading-keyword-regexp-format
5846 org-todo-regexp)
5847 '(2 (org-get-todo-face 2) t))
5848 ;; DONE
5849 (if org-fontify-done-headline
5850 (list (format org-heading-keyword-regexp-format
5851 (concat
5852 "\\(?:"
5853 (mapconcat 'regexp-quote org-done-keywords "\\|")
5854 "\\)"))
5855 '(2 'org-headline-done t))
5856 nil)
5857 ;; Priorities
5858 '(org-font-lock-add-priority-faces)
5859 ;; Tags
5860 '(org-font-lock-add-tag-faces)
5861 ;; Special keywords
5862 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5863 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5864 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5865 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5866 ;; Emphasis
5867 (if em
5868 (if (featurep 'xemacs)
5869 '(org-do-emphasis-faces (0 nil append))
5870 '(org-do-emphasis-faces)))
5871 ;; Checkboxes
5872 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5873 1 'org-checkbox prepend)
5874 (if (cdr (assq 'checkbox org-list-automatic-rules))
5875 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5876 (0 (org-get-checkbox-statistics-face) t)))
5877 ;; Description list items
5878 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5879 1 'bold prepend)
5880 ;; ARCHIVEd headings
5881 (list (concat
5882 org-outline-regexp-bol
5883 "\\(.*:" org-archive-tag ":.*\\)")
5884 '(1 'org-archived prepend))
5885 ;; Specials
5886 '(org-do-latex-and-special-faces)
5887 '(org-fontify-entities)
5888 '(org-raise-scripts)
5889 ;; Code
5890 '(org-activate-code (1 'org-code t))
5891 ;; COMMENT
5892 (list (format org-heading-keyword-regexp-format
5893 (concat "\\("
5894 org-comment-string "\\|" org-quote-string
5895 "\\)"))
5896 '(2 'org-special-keyword t))
5897 '("^#.*" (0 'font-lock-comment-face t))
5898 ;; Blocks and meta lines
5899 '(org-fontify-meta-lines-and-blocks)
5901 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5902 (run-hooks 'org-font-lock-set-keywords-hook)
5903 ;; Now set the full font-lock-keywords
5904 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5905 (org-set-local 'font-lock-defaults
5906 '(org-font-lock-keywords t nil nil backward-paragraph))
5907 (kill-local-variable 'font-lock-keywords) nil))
5909 (defun org-toggle-pretty-entities ()
5910 "Toggle the composition display of entities as UTF8 characters."
5911 (interactive)
5912 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5913 (org-restart-font-lock)
5914 (if org-pretty-entities
5915 (message "Entities are displayed as UTF8 characters")
5916 (save-restriction
5917 (widen)
5918 (org-decompose-region (point-min) (point-max))
5919 (message "Entities are displayed plain"))))
5921 (defun org-fontify-entities (limit)
5922 "Find an entity to fontify."
5923 (let (ee)
5924 (when org-pretty-entities
5925 (catch 'match
5926 (while (re-search-forward
5927 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5928 limit t)
5929 (if (and (not (org-in-indented-comment-line))
5930 (setq ee (org-entity-get (match-string 1)))
5931 (= (length (nth 6 ee)) 1))
5932 (progn
5933 (add-text-properties
5934 (match-beginning 0) (match-end 1)
5935 (list 'font-lock-fontified t))
5936 (compose-region (match-beginning 0) (match-end 1)
5937 (nth 6 ee) nil)
5938 (backward-char 1)
5939 (throw 'match t))))
5940 nil))))
5942 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5943 "Fontify string S like in Org-mode."
5944 (with-temp-buffer
5945 (insert s)
5946 (let ((org-odd-levels-only odd-levels))
5947 (org-mode)
5948 (font-lock-fontify-buffer)
5949 (buffer-string))))
5951 (defvar org-m nil)
5952 (defvar org-l nil)
5953 (defvar org-f nil)
5954 (defun org-get-level-face (n)
5955 "Get the right face for match N in font-lock matching of headlines."
5956 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5957 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5958 (if org-cycle-level-faces
5959 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5960 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5961 (cond
5962 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5963 ((eq n 2) org-f)
5964 (t (if org-level-color-stars-only nil org-f))))
5967 (defun org-get-todo-face (kwd)
5968 "Get the right face for a TODO keyword KWD.
5969 If KWD is a number, get the corresponding match group."
5970 (if (numberp kwd) (setq kwd (match-string kwd)))
5971 (or (org-face-from-face-or-color
5972 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5973 (and (member kwd org-done-keywords) 'org-done)
5974 'org-todo))
5976 (defun org-face-from-face-or-color (context inherit face-or-color)
5977 "Create a face list that inherits INHERIT, but sets the foreground color.
5978 When FACE-OR-COLOR is not a string, just return it."
5979 (if (stringp face-or-color)
5980 (list :inherit inherit
5981 (cdr (assoc context org-faces-easy-properties))
5982 face-or-color)
5983 face-or-color))
5985 (defun org-font-lock-add-tag-faces (limit)
5986 "Add the special tag faces."
5987 (when (and org-tag-faces org-tags-special-faces-re)
5988 (while (re-search-forward org-tags-special-faces-re limit t)
5989 (add-text-properties (match-beginning 1) (match-end 1)
5990 (list 'face (org-get-tag-face 1)
5991 'font-lock-fontified t))
5992 (backward-char 1))))
5994 (defun org-font-lock-add-priority-faces (limit)
5995 "Add the special priority faces."
5996 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5997 (add-text-properties
5998 (match-beginning 0) (match-end 0)
5999 (list 'face (or (org-face-from-face-or-color
6000 'priority 'org-special-keyword
6001 (cdr (assoc (char-after (match-beginning 1))
6002 org-priority-faces)))
6003 'org-special-keyword)
6004 'font-lock-fontified t))))
6006 (defun org-get-tag-face (kwd)
6007 "Get the right face for a TODO keyword KWD.
6008 If KWD is a number, get the corresponding match group."
6009 (if (numberp kwd) (setq kwd (match-string kwd)))
6010 (or (org-face-from-face-or-color
6011 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6012 'org-tag))
6014 (defun org-unfontify-region (beg end &optional maybe_loudly)
6015 "Remove fontification and activation overlays from links."
6016 (font-lock-default-unfontify-region beg end)
6017 (let* ((buffer-undo-list t)
6018 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6019 (inhibit-modification-hooks t)
6020 deactivate-mark buffer-file-name buffer-file-truename)
6021 (org-decompose-region beg end)
6022 (remove-text-properties beg end
6023 '(mouse-face t keymap t org-linked-text t
6024 invisible t intangible t
6025 org-no-flyspell t org-emphasis t))
6026 (org-remove-font-lock-display-properties beg end)))
6028 (defconst org-script-display '(((raise -0.3) (height 0.7))
6029 ((raise 0.3) (height 0.7))
6030 ((raise -0.5))
6031 ((raise 0.5)))
6032 "Display properties for showing superscripts and subscripts.")
6034 (defun org-remove-font-lock-display-properties (beg end)
6035 "Remove specific display properties that have been added by font lock.
6036 The will remove the raise properties that are used to show superscripts
6037 and subscripts."
6038 (let (next prop)
6039 (while (< beg end)
6040 (setq next (next-single-property-change beg 'display nil end)
6041 prop (get-text-property beg 'display))
6042 (if (member prop org-script-display)
6043 (put-text-property beg next 'display nil))
6044 (setq beg next))))
6046 (defun org-raise-scripts (limit)
6047 "Add raise properties to sub/superscripts."
6048 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6049 (if (re-search-forward
6050 (if (eq org-use-sub-superscripts t)
6051 org-match-substring-regexp
6052 org-match-substring-with-braces-regexp)
6053 limit t)
6054 (let* ((pos (point)) table-p comment-p
6055 (mpos (match-beginning 3))
6056 (emph-p (get-text-property mpos 'org-emphasis))
6057 (link-p (get-text-property mpos 'mouse-face))
6058 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6059 (goto-char (point-at-bol))
6060 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6061 comment-p (org-looking-at-p "[ \t]*#"))
6062 (goto-char pos)
6063 ;; FIXME: Should we go back one character here, for a_b^c
6064 ;; (goto-char (1- pos)) ;????????????????????
6065 (if (or comment-p emph-p link-p keyw-p)
6067 (put-text-property (match-beginning 3) (match-end 0)
6068 'display
6069 (if (equal (char-after (match-beginning 2)) ?^)
6070 (nth (if table-p 3 1) org-script-display)
6071 (nth (if table-p 2 0) org-script-display)))
6072 (add-text-properties (match-beginning 2) (match-end 2)
6073 (list 'invisible t
6074 'org-dwidth t 'org-dwidth-n 1))
6075 (if (and (eq (char-after (match-beginning 3)) ?{)
6076 (eq (char-before (match-end 3)) ?}))
6077 (progn
6078 (add-text-properties
6079 (match-beginning 3) (1+ (match-beginning 3))
6080 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6081 (add-text-properties
6082 (1- (match-end 3)) (match-end 3)
6083 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6084 t)))))
6086 ;;;; Visibility cycling, including org-goto and indirect buffer
6088 ;;; Cycling
6090 (defvar org-cycle-global-status nil)
6091 (make-variable-buffer-local 'org-cycle-global-status)
6092 (defvar org-cycle-subtree-status nil)
6093 (make-variable-buffer-local 'org-cycle-subtree-status)
6095 ;;;###autoload
6097 (defvar org-inlinetask-min-level)
6099 (defun org-cycle (&optional arg)
6100 "TAB-action and visibility cycling for Org-mode.
6102 This is the command invoked in Org-mode by the TAB key. Its main purpose
6103 is outline visibility cycling, but it also invokes other actions
6104 in special contexts.
6106 - When this function is called with a prefix argument, rotate the entire
6107 buffer through 3 states (global cycling)
6108 1. OVERVIEW: Show only top-level headlines.
6109 2. CONTENTS: Show all headlines of all levels, but no body text.
6110 3. SHOW ALL: Show everything.
6111 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6112 determined by the variable `org-startup-folded', and by any VISIBILITY
6113 properties in the buffer.
6114 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6115 including any drawers.
6117 - When inside a table, re-align the table and move to the next field.
6119 - When point is at the beginning of a headline, rotate the subtree started
6120 by this line through 3 different states (local cycling)
6121 1. FOLDED: Only the main headline is shown.
6122 2. CHILDREN: The main headline and the direct children are shown.
6123 From this state, you can move to one of the children
6124 and zoom in further.
6125 3. SUBTREE: Show the entire subtree, including body text.
6126 If there is no subtree, switch directly from CHILDREN to FOLDED.
6128 - When point is at the beginning of an empty headline and the variable
6129 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6130 of the headline by demoting and promoting it to likely levels. This
6131 speeds up creation document structure by pressing TAB once or several
6132 times right after creating a new headline.
6134 - When there is a numeric prefix, go up to a heading with level ARG, do
6135 a `show-subtree' and return to the previous cursor position. If ARG
6136 is negative, go up that many levels.
6138 - When point is not at the beginning of a headline, execute the global
6139 binding for TAB, which is re-indenting the line. See the option
6140 `org-cycle-emulate-tab' for details.
6142 - Special case: if point is at the beginning of the buffer and there is
6143 no headline in line 1, this function will act as if called with prefix arg
6144 (C-u TAB, same as S-TAB) also when called without prefix arg.
6145 But only if also the variable `org-cycle-global-at-bob' is t."
6146 (interactive "P")
6147 (org-load-modules-maybe)
6148 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6149 (and org-cycle-level-after-item/entry-creation
6150 (or (org-cycle-level)
6151 (org-cycle-item-indentation))))
6152 (let* ((limit-level
6153 (or org-cycle-max-level
6154 (and (boundp 'org-inlinetask-min-level)
6155 org-inlinetask-min-level
6156 (1- org-inlinetask-min-level))))
6157 (nstars (and limit-level
6158 (if org-odd-levels-only
6159 (and limit-level (1- (* limit-level 2)))
6160 limit-level)))
6161 (org-outline-regexp
6162 (if (not (eq major-mode 'org-mode))
6163 outline-regexp
6164 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6165 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6166 (not (looking-at org-outline-regexp))))
6167 (org-cycle-hook
6168 (if bob-special
6169 (delq 'org-optimize-window-after-visibility-change
6170 (copy-sequence org-cycle-hook))
6171 org-cycle-hook))
6172 (pos (point)))
6174 (if (or bob-special (equal arg '(4)))
6175 ;; special case: use global cycling
6176 (setq arg t))
6178 (cond
6180 ((equal arg '(16))
6181 (setq last-command 'dummy)
6182 (org-set-startup-visibility)
6183 (message "Startup visibility, plus VISIBILITY properties"))
6185 ((equal arg '(64))
6186 (show-all)
6187 (message "Entire buffer visible, including drawers"))
6189 ;; Table: enter it or move to the next field.
6190 ((org-at-table-p 'any)
6191 (if (org-at-table.el-p)
6192 (message "Use C-c ' to edit table.el tables")
6193 (if arg (org-table-edit-field t)
6194 (org-table-justify-field-maybe)
6195 (call-interactively 'org-table-next-field))))
6197 ((run-hook-with-args-until-success
6198 'org-tab-after-check-for-table-hook))
6200 ;; Global cycling: delegate to `org-cycle-internal-global'.
6201 ((eq arg t) (org-cycle-internal-global))
6203 ;; Drawers: delegate to `org-flag-drawer'.
6204 ((and org-drawers org-drawer-regexp
6205 (save-excursion
6206 (beginning-of-line 1)
6207 (looking-at org-drawer-regexp)))
6208 (org-flag-drawer ; toggle block visibility
6209 (not (get-char-property (match-end 0) 'invisible))))
6211 ;; Show-subtree, ARG levels up from here.
6212 ((integerp arg)
6213 (save-excursion
6214 (org-back-to-heading)
6215 (outline-up-heading (if (< arg 0) (- arg)
6216 (- (funcall outline-level) arg)))
6217 (org-show-subtree)))
6219 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6220 ((and (featurep 'org-inlinetask)
6221 (org-inlinetask-at-task-p)
6222 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6223 (org-inlinetask-toggle-visibility))
6225 ((org-try-cdlatex-tab))
6227 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6228 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6229 (save-excursion (beginning-of-line 1)
6230 (looking-at org-outline-regexp)))
6231 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6232 (org-cycle-internal-local))
6234 ;; From there: TAB emulation and template completion.
6235 (buffer-read-only (org-back-to-heading))
6237 ((run-hook-with-args-until-success
6238 'org-tab-after-check-for-cycling-hook))
6240 ((org-try-structure-completion))
6242 ((run-hook-with-args-until-success
6243 'org-tab-before-tab-emulation-hook))
6245 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6246 (or (not (bolp))
6247 (not (looking-at org-outline-regexp))))
6248 (call-interactively (global-key-binding "\t")))
6250 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6251 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6252 (or (and (eq org-cycle-emulate-tab 'white)
6253 (= (match-end 0) (point-at-eol)))
6254 (and (eq org-cycle-emulate-tab 'whitestart)
6255 (>= (match-end 0) pos))))
6257 (eq org-cycle-emulate-tab t))
6258 (call-interactively (global-key-binding "\t")))
6260 (t (save-excursion
6261 (org-back-to-heading)
6262 (org-cycle)))))))
6264 (defun org-cycle-internal-global ()
6265 "Do the global cycling action."
6266 ;; Hack to avoid display of messages for .org attachments in Gnus
6267 (let ((ga (string-match "\\*fontification" (buffer-name))))
6268 (cond
6269 ((and (eq last-command this-command)
6270 (eq org-cycle-global-status 'overview))
6271 ;; We just created the overview - now do table of contents
6272 ;; This can be slow in very large buffers, so indicate action
6273 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6274 (unless ga (message "CONTENTS..."))
6275 (org-content)
6276 (unless ga (message "CONTENTS...done"))
6277 (setq org-cycle-global-status 'contents)
6278 (run-hook-with-args 'org-cycle-hook 'contents))
6280 ((and (eq last-command this-command)
6281 (eq org-cycle-global-status 'contents))
6282 ;; We just showed the table of contents - now show everything
6283 (run-hook-with-args 'org-pre-cycle-hook 'all)
6284 (show-all)
6285 (unless ga (message "SHOW ALL"))
6286 (setq org-cycle-global-status 'all)
6287 (run-hook-with-args 'org-cycle-hook 'all))
6290 ;; Default action: go to overview
6291 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6292 (org-overview)
6293 (unless ga (message "OVERVIEW"))
6294 (setq org-cycle-global-status 'overview)
6295 (run-hook-with-args 'org-cycle-hook 'overview)))))
6297 (defun org-cycle-internal-local ()
6298 "Do the local cycling action."
6299 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6300 ;; First, determine end of headline (EOH), end of subtree or item
6301 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6302 (save-excursion
6303 (if (org-at-item-p)
6304 (progn
6305 (beginning-of-line)
6306 (setq struct (org-list-struct))
6307 (setq eoh (point-at-eol))
6308 (setq eos (org-list-get-item-end-before-blank (point) struct))
6309 (setq has-children (org-list-has-child-p (point) struct)))
6310 (org-back-to-heading)
6311 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6312 (setq eos (save-excursion
6313 (org-end-of-subtree t)
6314 (unless (eobp)
6315 (skip-chars-forward " \t\n"))
6316 (if (eobp) (point) (1- (point)))))
6317 (setq has-children
6318 (or (save-excursion
6319 (let ((level (funcall outline-level)))
6320 (outline-next-heading)
6321 (and (org-at-heading-p t)
6322 (> (funcall outline-level) level))))
6323 (save-excursion
6324 (org-list-search-forward (org-item-beginning-re) eos t)))))
6325 ;; Determine end invisible part of buffer (EOL)
6326 (beginning-of-line 2)
6327 ;; XEmacs doesn't have `next-single-char-property-change'
6328 (if (featurep 'xemacs)
6329 (while (and (not (eobp)) ;; this is like `next-line'
6330 (get-char-property (1- (point)) 'invisible))
6331 (beginning-of-line 2))
6332 (while (and (not (eobp)) ;; this is like `next-line'
6333 (get-char-property (1- (point)) 'invisible))
6334 (goto-char (next-single-char-property-change (point) 'invisible))
6335 (and (eolp) (beginning-of-line 2))))
6336 (setq eol (point)))
6337 ;; Find out what to do next and set `this-command'
6338 (cond
6339 ((= eos eoh)
6340 ;; Nothing is hidden behind this heading
6341 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6342 (message "EMPTY ENTRY")
6343 (setq org-cycle-subtree-status nil)
6344 (save-excursion
6345 (goto-char eos)
6346 (outline-next-heading)
6347 (if (outline-invisible-p) (org-flag-heading nil))))
6348 ((and (or (>= eol eos)
6349 (not (string-match "\\S-" (buffer-substring eol eos))))
6350 (or has-children
6351 (not (setq children-skipped
6352 org-cycle-skip-children-state-if-no-children))))
6353 ;; Entire subtree is hidden in one line: children view
6354 (run-hook-with-args 'org-pre-cycle-hook 'children)
6355 (if (org-at-item-p)
6356 (org-list-set-item-visibility (point-at-bol) struct 'children)
6357 (org-show-entry)
6358 (org-with-limited-levels (show-children))
6359 ;; FIXME: This slows down the func way too much.
6360 ;; How keep drawers hidden in subtree anyway?
6361 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6362 ;; (org-cycle-hide-drawers 'subtree))
6364 ;; Fold every list in subtree to top-level items.
6365 (when (eq org-cycle-include-plain-lists 'integrate)
6366 (save-excursion
6367 (org-back-to-heading)
6368 (while (org-list-search-forward (org-item-beginning-re) eos t)
6369 (beginning-of-line 1)
6370 (let* ((struct (org-list-struct))
6371 (prevs (org-list-prevs-alist struct))
6372 (end (org-list-get-bottom-point struct)))
6373 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6374 (org-list-get-all-items (point) struct prevs))
6375 (goto-char end))))))
6376 (message "CHILDREN")
6377 (save-excursion
6378 (goto-char eos)
6379 (outline-next-heading)
6380 (if (outline-invisible-p) (org-flag-heading nil)))
6381 (setq org-cycle-subtree-status 'children)
6382 (run-hook-with-args 'org-cycle-hook 'children))
6383 ((or children-skipped
6384 (and (eq last-command this-command)
6385 (eq org-cycle-subtree-status 'children)))
6386 ;; We just showed the children, or no children are there,
6387 ;; now show everything.
6388 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6389 (outline-flag-region eoh eos nil)
6390 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6391 (setq org-cycle-subtree-status 'subtree)
6392 (run-hook-with-args 'org-cycle-hook 'subtree))
6394 ;; Default action: hide the subtree.
6395 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6396 (outline-flag-region eoh eos t)
6397 (message "FOLDED")
6398 (setq org-cycle-subtree-status 'folded)
6399 (run-hook-with-args 'org-cycle-hook 'folded)))))
6401 ;;;###autoload
6402 (defun org-global-cycle (&optional arg)
6403 "Cycle the global visibility. For details see `org-cycle'.
6404 With \\[universal-argument] prefix arg, switch to startup visibility.
6405 With a numeric prefix, show all headlines up to that level."
6406 (interactive "P")
6407 (let ((org-cycle-include-plain-lists
6408 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6409 (cond
6410 ((integerp arg)
6411 (show-all)
6412 (hide-sublevels arg)
6413 (setq org-cycle-global-status 'contents))
6414 ((equal arg '(4))
6415 (org-set-startup-visibility)
6416 (message "Startup visibility, plus VISIBILITY properties."))
6418 (org-cycle '(4))))))
6420 (defun org-set-startup-visibility ()
6421 "Set the visibility required by startup options and properties."
6422 (cond
6423 ((eq org-startup-folded t)
6424 (org-cycle '(4)))
6425 ((eq org-startup-folded 'content)
6426 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6427 (org-cycle '(4)) (org-cycle '(4)))))
6428 (unless (eq org-startup-folded 'showeverything)
6429 (if org-hide-block-startup (org-hide-block-all))
6430 (org-set-visibility-according-to-property 'no-cleanup)
6431 (org-cycle-hide-archived-subtrees 'all)
6432 (org-cycle-hide-drawers 'all)
6433 (org-cycle-show-empty-lines t)))
6435 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6436 "Switch subtree visibilities according to :VISIBILITY: property."
6437 (interactive)
6438 (let (org-show-entry-below state)
6439 (save-excursion
6440 (goto-char (point-min))
6441 (while (re-search-forward
6442 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6443 nil t)
6444 (setq state (match-string 1))
6445 (save-excursion
6446 (org-back-to-heading t)
6447 (hide-subtree)
6448 (org-reveal)
6449 (cond
6450 ((equal state '("fold" "folded"))
6451 (hide-subtree))
6452 ((equal state "children")
6453 (org-show-hidden-entry)
6454 (show-children))
6455 ((equal state "content")
6456 (save-excursion
6457 (save-restriction
6458 (org-narrow-to-subtree)
6459 (org-content))))
6460 ((member state '("all" "showall"))
6461 (show-subtree)))))
6462 (unless no-cleanup
6463 (org-cycle-hide-archived-subtrees 'all)
6464 (org-cycle-hide-drawers 'all)
6465 (org-cycle-show-empty-lines 'all)))))
6467 ;; This function uses outline-regexp instead of the more fundamental
6468 ;; org-outline-regexp so that org-cycle-global works outside of Org
6469 ;; buffers, where outline-regexp is needed.
6470 (defun org-overview ()
6471 "Switch to overview mode, showing only top-level headlines.
6472 Really, this shows all headlines with level equal or greater than the level
6473 of the first headline in the buffer. This is important, because if the
6474 first headline is not level one, then (hide-sublevels 1) gives confusing
6475 results."
6476 (interactive)
6477 (let ((level (save-excursion
6478 (goto-char (point-min))
6479 (if (re-search-forward (concat "^" outline-regexp) nil t)
6480 (progn
6481 (goto-char (match-beginning 0))
6482 (funcall outline-level))))))
6483 (and level (hide-sublevels level))))
6485 (defun org-content (&optional arg)
6486 "Show all headlines in the buffer, like a table of contents.
6487 With numerical argument N, show content up to level N."
6488 (interactive "P")
6489 (save-excursion
6490 ;; Visit all headings and show their offspring
6491 (and (integerp arg) (org-overview))
6492 (goto-char (point-max))
6493 (catch 'exit
6494 (while (and (progn (condition-case nil
6495 (outline-previous-visible-heading 1)
6496 (error (goto-char (point-min))))
6498 (looking-at org-outline-regexp))
6499 (if (integerp arg)
6500 (show-children (1- arg))
6501 (show-branches))
6502 (if (bobp) (throw 'exit nil))))))
6505 (defun org-optimize-window-after-visibility-change (state)
6506 "Adjust the window after a change in outline visibility.
6507 This function is the default value of the hook `org-cycle-hook'."
6508 (when (get-buffer-window (current-buffer))
6509 (cond
6510 ((eq state 'content) nil)
6511 ((eq state 'all) nil)
6512 ((eq state 'folded) nil)
6513 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6514 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6516 (defun org-remove-empty-overlays-at (pos)
6517 "Remove outline overlays that do not contain non-white stuff."
6518 (mapc
6519 (lambda (o)
6520 (and (eq 'outline (overlay-get o 'invisible))
6521 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6522 (overlay-end o))))
6523 (delete-overlay o)))
6524 (overlays-at pos)))
6526 (defun org-clean-visibility-after-subtree-move ()
6527 "Fix visibility issues after moving a subtree."
6528 ;; First, find a reasonable region to look at:
6529 ;; Start two siblings above, end three below
6530 (let* ((beg (save-excursion
6531 (and (org-get-last-sibling)
6532 (org-get-last-sibling))
6533 (point)))
6534 (end (save-excursion
6535 (and (org-get-next-sibling)
6536 (org-get-next-sibling)
6537 (org-get-next-sibling))
6538 (if (org-at-heading-p)
6539 (point-at-eol)
6540 (point))))
6541 (level (looking-at "\\*+"))
6542 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6543 (save-excursion
6544 (save-restriction
6545 (narrow-to-region beg end)
6546 (when re
6547 ;; Properly fold already folded siblings
6548 (goto-char (point-min))
6549 (while (re-search-forward re nil t)
6550 (if (and (not (outline-invisible-p))
6551 (save-excursion
6552 (goto-char (point-at-eol)) (outline-invisible-p)))
6553 (hide-entry))))
6554 (org-cycle-show-empty-lines 'overview)
6555 (org-cycle-hide-drawers 'overview)))))
6557 (defun org-cycle-show-empty-lines (state)
6558 "Show empty lines above all visible headlines.
6559 The region to be covered depends on STATE when called through
6560 `org-cycle-hook'. Lisp program can use t for STATE to get the
6561 entire buffer covered. Note that an empty line is only shown if there
6562 are at least `org-cycle-separator-lines' empty lines before the headline."
6563 (when (not (= org-cycle-separator-lines 0))
6564 (save-excursion
6565 (let* ((n (abs org-cycle-separator-lines))
6566 (re (cond
6567 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6568 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6569 (t (let ((ns (number-to-string (- n 2))))
6570 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6571 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6572 beg end b e)
6573 (cond
6574 ((memq state '(overview contents t))
6575 (setq beg (point-min) end (point-max)))
6576 ((memq state '(children folded))
6577 (setq beg (point) end (progn (org-end-of-subtree t t)
6578 (beginning-of-line 2)
6579 (point)))))
6580 (when beg
6581 (goto-char beg)
6582 (while (re-search-forward re end t)
6583 (unless (get-char-property (match-end 1) 'invisible)
6584 (setq e (match-end 1))
6585 (if (< org-cycle-separator-lines 0)
6586 (setq b (save-excursion
6587 (goto-char (match-beginning 0))
6588 (org-back-over-empty-lines)
6589 (if (save-excursion
6590 (goto-char (max (point-min) (1- (point))))
6591 (org-at-heading-p))
6592 (1- (point))
6593 (point))))
6594 (setq b (match-beginning 1)))
6595 (outline-flag-region b e nil)))))))
6596 ;; Never hide empty lines at the end of the file.
6597 (save-excursion
6598 (goto-char (point-max))
6599 (outline-previous-heading)
6600 (outline-end-of-heading)
6601 (if (and (looking-at "[ \t\n]+")
6602 (= (match-end 0) (point-max)))
6603 (outline-flag-region (point) (match-end 0) nil))))
6605 (defun org-show-empty-lines-in-parent ()
6606 "Move to the parent and re-show empty lines before visible headlines."
6607 (save-excursion
6608 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6609 (org-cycle-show-empty-lines context))))
6611 (defun org-files-list ()
6612 "Return `org-agenda-files' list, plus all open org-mode files.
6613 This is useful for operations that need to scan all of a user's
6614 open and agenda-wise Org files."
6615 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6616 (dolist (buf (buffer-list))
6617 (with-current-buffer buf
6618 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6619 (let ((file (expand-file-name (buffer-file-name))))
6620 (unless (member file files)
6621 (push file files))))))
6622 files))
6624 (defsubst org-entry-beginning-position ()
6625 "Return the beginning position of the current entry."
6626 (save-excursion (outline-back-to-heading t) (point)))
6628 (defsubst org-entry-end-position ()
6629 "Return the end position of the current entry."
6630 (save-excursion (outline-next-heading) (point)))
6632 (defun org-cycle-hide-drawers (state)
6633 "Re-hide all drawers after a visibility state change."
6634 (when (and (eq major-mode 'org-mode)
6635 (not (memq state '(overview folded contents))))
6636 (save-excursion
6637 (let* ((globalp (memq state '(contents all)))
6638 (beg (if globalp (point-min) (point)))
6639 (end (if globalp (point-max)
6640 (if (eq state 'children)
6641 (save-excursion (outline-next-heading) (point))
6642 (org-end-of-subtree t)))))
6643 (goto-char beg)
6644 (while (re-search-forward org-drawer-regexp end t)
6645 (org-flag-drawer t))))))
6647 (defun org-flag-drawer (flag)
6648 (save-excursion
6649 (beginning-of-line 1)
6650 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6651 (let ((b (match-end 0)))
6652 (if (re-search-forward
6653 "^[ \t]*:END:"
6654 (save-excursion (outline-next-heading) (point)) t)
6655 (outline-flag-region b (point-at-eol) flag)
6656 (error ":END: line missing at position %s" b))))))
6658 (defun org-subtree-end-visible-p ()
6659 "Is the end of the current subtree visible?"
6660 (pos-visible-in-window-p
6661 (save-excursion (org-end-of-subtree t) (point))))
6663 (defun org-first-headline-recenter (&optional N)
6664 "Move cursor to the first headline and recenter the headline.
6665 Optional argument N means put the headline into the Nth line of the window."
6666 (goto-char (point-min))
6667 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6668 (beginning-of-line)
6669 (recenter (prefix-numeric-value N))))
6671 ;;; Saving and restoring visibility
6673 (defun org-outline-overlay-data (&optional use-markers)
6674 "Return a list of the locations of all outline overlays.
6675 These are overlays with the `invisible' property value `outline'.
6676 The return value is a list of cons cells, with start and stop
6677 positions for each overlay.
6678 If USE-MARKERS is set, return the positions as markers."
6679 (let (beg end)
6680 (save-excursion
6681 (save-restriction
6682 (widen)
6683 (delq nil
6684 (mapcar (lambda (o)
6685 (when (eq (overlay-get o 'invisible) 'outline)
6686 (setq beg (overlay-start o)
6687 end (overlay-end o))
6688 (and beg end (> end beg)
6689 (if use-markers
6690 (cons (move-marker (make-marker) beg)
6691 (move-marker (make-marker) end))
6692 (cons beg end)))))
6693 (overlays-in (point-min) (point-max))))))))
6695 (defun org-set-outline-overlay-data (data)
6696 "Create visibility overlays for all positions in DATA.
6697 DATA should have been made by `org-outline-overlay-data'."
6698 (let (o)
6699 (save-excursion
6700 (save-restriction
6701 (widen)
6702 (show-all)
6703 (mapc (lambda (c)
6704 (outline-flag-region (car c) (cdr c) t))
6705 data)))))
6707 ;;; Folding of blocks
6709 (defvar org-hide-block-overlays nil
6710 "Overlays hiding blocks.")
6711 (make-variable-buffer-local 'org-hide-block-overlays)
6713 (defun org-block-map (function &optional start end)
6714 "Call FUNCTION at the head of all source blocks in the current buffer.
6715 Optional arguments START and END can be used to limit the range."
6716 (let ((start (or start (point-min)))
6717 (end (or end (point-max))))
6718 (save-excursion
6719 (goto-char start)
6720 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6721 (save-excursion
6722 (save-match-data
6723 (goto-char (match-beginning 0))
6724 (funcall function)))))))
6726 (defun org-hide-block-toggle-all ()
6727 "Toggle the visibility of all blocks in the current buffer."
6728 (org-block-map #'org-hide-block-toggle))
6730 (defun org-hide-block-all ()
6731 "Fold all blocks in the current buffer."
6732 (interactive)
6733 (org-show-block-all)
6734 (org-block-map #'org-hide-block-toggle-maybe))
6736 (defun org-show-block-all ()
6737 "Unfold all blocks in the current buffer."
6738 (interactive)
6739 (mapc 'delete-overlay org-hide-block-overlays)
6740 (setq org-hide-block-overlays nil))
6742 (defun org-hide-block-toggle-maybe ()
6743 "Toggle visibility of block at point."
6744 (interactive)
6745 (let ((case-fold-search t))
6746 (if (save-excursion
6747 (beginning-of-line 1)
6748 (looking-at org-block-regexp))
6749 (progn (org-hide-block-toggle)
6750 t) ;; to signal that we took action
6751 nil))) ;; to signal that we did not
6753 (defun org-hide-block-toggle (&optional force)
6754 "Toggle the visibility of the current block."
6755 (interactive)
6756 (save-excursion
6757 (beginning-of-line)
6758 (if (re-search-forward org-block-regexp nil t)
6759 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6760 (end (match-end 0)) ;; end of entire body
6762 (if (memq t (mapcar (lambda (overlay)
6763 (eq (overlay-get overlay 'invisible)
6764 'org-hide-block))
6765 (overlays-at start)))
6766 (if (or (not force) (eq force 'off))
6767 (mapc (lambda (ov)
6768 (when (member ov org-hide-block-overlays)
6769 (setq org-hide-block-overlays
6770 (delq ov org-hide-block-overlays)))
6771 (when (eq (overlay-get ov 'invisible)
6772 'org-hide-block)
6773 (delete-overlay ov)))
6774 (overlays-at start)))
6775 (setq ov (make-overlay start end))
6776 (overlay-put ov 'invisible 'org-hide-block)
6777 ;; make the block accessible to isearch
6778 (overlay-put
6779 ov 'isearch-open-invisible
6780 (lambda (ov)
6781 (when (member ov org-hide-block-overlays)
6782 (setq org-hide-block-overlays
6783 (delq ov org-hide-block-overlays)))
6784 (when (eq (overlay-get ov 'invisible)
6785 'org-hide-block)
6786 (delete-overlay ov))))
6787 (push ov org-hide-block-overlays)))
6788 (error "Not looking at a source block"))))
6790 ;; org-tab-after-check-for-cycling-hook
6791 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6792 ;; Remove overlays when changing major mode
6793 (add-hook 'org-mode-hook
6794 (lambda () (org-add-hook 'change-major-mode-hook
6795 'org-show-block-all 'append 'local)))
6797 ;;; Org-goto
6799 (defvar org-goto-window-configuration nil)
6800 (defvar org-goto-marker nil)
6801 (defvar org-goto-map
6802 (let ((map (make-sparse-keymap)))
6803 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6804 (while (setq cmd (pop cmds))
6805 (substitute-key-definition cmd cmd map global-map)))
6806 (suppress-keymap map)
6807 (org-defkey map "\C-m" 'org-goto-ret)
6808 (org-defkey map [(return)] 'org-goto-ret)
6809 (org-defkey map [(left)] 'org-goto-left)
6810 (org-defkey map [(right)] 'org-goto-right)
6811 (org-defkey map [(control ?g)] 'org-goto-quit)
6812 (org-defkey map "\C-i" 'org-cycle)
6813 (org-defkey map [(tab)] 'org-cycle)
6814 (org-defkey map [(down)] 'outline-next-visible-heading)
6815 (org-defkey map [(up)] 'outline-previous-visible-heading)
6816 (if org-goto-auto-isearch
6817 (if (fboundp 'define-key-after)
6818 (define-key-after map [t] 'org-goto-local-auto-isearch)
6819 nil)
6820 (org-defkey map "q" 'org-goto-quit)
6821 (org-defkey map "n" 'outline-next-visible-heading)
6822 (org-defkey map "p" 'outline-previous-visible-heading)
6823 (org-defkey map "f" 'outline-forward-same-level)
6824 (org-defkey map "b" 'outline-backward-same-level)
6825 (org-defkey map "u" 'outline-up-heading))
6826 (org-defkey map "/" 'org-occur)
6827 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6828 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6829 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6830 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6831 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6832 map))
6834 (defconst org-goto-help
6835 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6836 RET=jump to location [Q]uit and return to previous location
6837 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6839 (defvar org-goto-start-pos) ; dynamically scoped parameter
6841 ;; FIXME: Docstring does not mention both interfaces
6842 (defun org-goto (&optional alternative-interface)
6843 "Look up a different location in the current file, keeping current visibility.
6845 When you want look-up or go to a different location in a document, the
6846 fastest way is often to fold the entire buffer and then dive into the tree.
6847 This method has the disadvantage, that the previous location will be folded,
6848 which may not be what you want.
6850 This command works around this by showing a copy of the current buffer
6851 in an indirect buffer, in overview mode. You can dive into the tree in
6852 that copy, use org-occur and incremental search to find a location.
6853 When pressing RET or `Q', the command returns to the original buffer in
6854 which the visibility is still unchanged. After RET it will also jump to
6855 the location selected in the indirect buffer and expose the headline
6856 hierarchy above."
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 numerical prefix ARG, go up to this level and then take that tree.
7002 If ARG is negative, go up that many levels.
7003 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7004 indirect buffer previously made with this command, to avoid proliferation of
7005 indirect buffers. However, when you call the command with a \
7006 \\[universal-argument] prefix, or
7007 when `org-indirect-buffer-display' is `new-frame', the last buffer
7008 is kept so that you can work with several indirect buffers at the same time.
7009 If `org-indirect-buffer-display' is `dedicated-frame', the \
7010 \\[universal-argument] prefix also
7011 requests that a new frame be made for the new buffer, so that the dedicated
7012 frame is not changed."
7013 (interactive "P")
7014 (let ((cbuf (current-buffer))
7015 (cwin (selected-window))
7016 (pos (point))
7017 beg end level heading ibuf)
7018 (save-excursion
7019 (org-back-to-heading t)
7020 (when (numberp arg)
7021 (setq level (org-outline-level))
7022 (if (< arg 0) (setq arg (+ level arg)))
7023 (while (> (setq level (org-outline-level)) arg)
7024 (outline-up-heading 1 t)))
7025 (setq beg (point)
7026 heading (org-get-heading))
7027 (org-end-of-subtree t t)
7028 (if (org-at-heading-p) (backward-char 1))
7029 (setq end (point)))
7030 (if (and (buffer-live-p org-last-indirect-buffer)
7031 (not (eq org-indirect-buffer-display 'new-frame))
7032 (not arg))
7033 (kill-buffer org-last-indirect-buffer))
7034 (setq ibuf (org-get-indirect-buffer cbuf)
7035 org-last-indirect-buffer ibuf)
7036 (cond
7037 ((or (eq org-indirect-buffer-display 'new-frame)
7038 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7039 (select-frame (make-frame))
7040 (delete-other-windows)
7041 (org-pop-to-buffer-same-window ibuf)
7042 (org-set-frame-title heading))
7043 ((eq org-indirect-buffer-display 'dedicated-frame)
7044 (raise-frame
7045 (select-frame (or (and org-indirect-dedicated-frame
7046 (frame-live-p org-indirect-dedicated-frame)
7047 org-indirect-dedicated-frame)
7048 (setq org-indirect-dedicated-frame (make-frame)))))
7049 (delete-other-windows)
7050 (org-pop-to-buffer-same-window ibuf)
7051 (org-set-frame-title (concat "Indirect: " heading)))
7052 ((eq org-indirect-buffer-display 'current-window)
7053 (org-pop-to-buffer-same-window ibuf))
7054 ((eq org-indirect-buffer-display 'other-window)
7055 (pop-to-buffer ibuf))
7056 (t (error "Invalid value")))
7057 (if (featurep 'xemacs)
7058 (save-excursion (org-mode) (turn-on-font-lock)))
7059 (narrow-to-region beg end)
7060 (show-all)
7061 (goto-char pos)
7062 (run-hook-with-args 'org-cycle-hook 'all)
7063 (and (window-live-p cwin) (select-window cwin))))
7065 (defun org-get-indirect-buffer (&optional buffer)
7066 (setq buffer (or buffer (current-buffer)))
7067 (let ((n 1) (base (buffer-name buffer)) bname)
7068 (while (buffer-live-p
7069 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7070 (setq n (1+ n)))
7071 (condition-case nil
7072 (make-indirect-buffer buffer bname 'clone)
7073 (error (make-indirect-buffer buffer bname)))))
7075 (defun org-set-frame-title (title)
7076 "Set the title of the current frame to the string TITLE."
7077 ;; FIXME: how to name a single frame in XEmacs???
7078 (unless (featurep 'xemacs)
7079 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7081 ;;;; Structure editing
7083 ;;; Inserting headlines
7085 (defun org-previous-line-empty-p ()
7086 (save-excursion
7087 (and (not (bobp))
7088 (or (beginning-of-line 0) t)
7089 (save-match-data
7090 (looking-at "[ \t]*$")))))
7092 (defun org-insert-heading (&optional force-heading invisible-ok)
7093 "Insert a new heading or item with same depth at point.
7094 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7095 If point is at the beginning of a headline, insert a sibling before the
7096 current headline. If point is not at the beginning, split the line,
7097 create the new headline with the text in the current line after point
7098 \(but see also the variable `org-M-RET-may-split-line').
7100 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7101 This is important for non-interactive uses of the command."
7102 (interactive "P")
7103 (if (or (= (buffer-size) 0)
7104 (and (not (save-excursion
7105 (and (ignore-errors (org-back-to-heading invisible-ok))
7106 (org-at-heading-p))))
7107 (or force-heading (not (org-in-item-p)))))
7108 (progn
7109 (insert "\n* ")
7110 (run-hooks 'org-insert-heading-hook))
7111 (when (or force-heading (not (org-insert-item)))
7112 (let* ((empty-line-p nil)
7113 (level nil)
7114 (on-heading (org-at-heading-p))
7115 (head (save-excursion
7116 (condition-case nil
7117 (progn
7118 (org-back-to-heading invisible-ok)
7119 (when (and (not on-heading)
7120 (featurep 'org-inlinetask)
7121 (integerp org-inlinetask-min-level)
7122 (>= (length (match-string 0))
7123 org-inlinetask-min-level))
7124 ;; Find a heading level before the inline task
7125 (while (and (setq level (org-up-heading-safe))
7126 (>= level org-inlinetask-min-level)))
7127 (if (org-at-heading-p)
7128 (org-back-to-heading invisible-ok)
7129 (error "This should not happen")))
7130 (setq empty-line-p (org-previous-line-empty-p))
7131 (match-string 0))
7132 (error "*"))))
7133 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7134 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7135 pos hide-previous previous-pos)
7136 (cond
7137 ((and (org-at-heading-p) (bolp)
7138 (or (bobp)
7139 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7140 ;; insert before the current line
7141 (open-line (if blank 2 1)))
7142 ((and (bolp)
7143 (not org-insert-heading-respect-content)
7144 (or (bobp)
7145 (save-excursion
7146 (backward-char 1) (not (outline-invisible-p)))))
7147 ;; insert right here
7148 nil)
7150 ;; somewhere in the line
7151 (save-excursion
7152 (setq previous-pos (point-at-bol))
7153 (end-of-line)
7154 (setq hide-previous (outline-invisible-p)))
7155 (and org-insert-heading-respect-content (org-show-subtree))
7156 (let ((split
7157 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7158 (save-excursion
7159 (let ((p (point)))
7160 (goto-char (point-at-bol))
7161 (and (looking-at org-complex-heading-regexp)
7162 (match-beginning 4)
7163 (> p (match-beginning 4)))))))
7164 tags pos)
7165 (cond
7166 (org-insert-heading-respect-content
7167 (org-end-of-subtree nil t)
7168 (when (featurep 'org-inlinetask)
7169 (while (and (not (eobp))
7170 (looking-at "\\(\\*+\\)[ \t]+")
7171 (>= (length (match-string 1))
7172 org-inlinetask-min-level))
7173 (org-end-of-subtree nil t)))
7174 (or (bolp) (newline))
7175 (or (org-previous-line-empty-p)
7176 (and blank (newline)))
7177 (open-line 1))
7178 ((org-at-heading-p)
7179 (when hide-previous
7180 (show-children)
7181 (org-show-entry))
7182 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7183 (setq tags (and (match-end 2) (match-string 2)))
7184 (and (match-end 1)
7185 (delete-region (match-beginning 1) (match-end 1)))
7186 (setq pos (point-at-bol))
7187 (or split (end-of-line 1))
7188 (delete-horizontal-space)
7189 (if (string-match "\\`\\*+\\'"
7190 (buffer-substring (point-at-bol) (point)))
7191 (insert " "))
7192 (newline (if blank 2 1))
7193 (when tags
7194 (save-excursion
7195 (goto-char pos)
7196 (end-of-line 1)
7197 (insert " " tags)
7198 (org-set-tags nil 'align))))
7200 (or split (end-of-line 1))
7201 (newline (if blank 2 1)))))))
7202 (insert head) (just-one-space)
7203 (setq pos (point))
7204 (end-of-line 1)
7205 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7206 (when (and org-insert-heading-respect-content hide-previous)
7207 (save-excursion
7208 (goto-char previous-pos)
7209 (hide-subtree)))
7210 (run-hooks 'org-insert-heading-hook)))))
7212 (defun org-get-heading (&optional no-tags no-todo)
7213 "Return the heading of the current entry, without the stars.
7214 When NO-TAGS is non-nil, don't include tags.
7215 When NO-TODO is non-nil, don't include TODO keywords."
7216 (save-excursion
7217 (org-back-to-heading t)
7218 (cond
7219 ((and no-tags no-todo)
7220 (looking-at org-complex-heading-regexp)
7221 (match-string 4))
7222 (no-tags
7223 (looking-at (concat org-outline-regexp
7224 "\\(.*?\\)"
7225 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7226 (match-string 1))
7227 (no-todo
7228 (looking-at org-todo-line-regexp)
7229 (match-string 3))
7230 (t (looking-at org-heading-regexp)
7231 (match-string 2)))))
7233 (defun org-heading-components ()
7234 "Return the components of the current heading.
7235 This is a list with the following elements:
7236 - the level as an integer
7237 - the reduced level, different if `org-odd-levels-only' is set.
7238 - the TODO keyword, or nil
7239 - the priority character, like ?A, or nil if no priority is given
7240 - the headline text itself, or the tags string if no headline text
7241 - the tags string, or nil."
7242 (save-excursion
7243 (org-back-to-heading t)
7244 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7245 (list (length (match-string 1))
7246 (org-reduced-level (length (match-string 1)))
7247 (org-match-string-no-properties 2)
7248 (and (match-end 3) (aref (match-string 3) 2))
7249 (org-match-string-no-properties 4)
7250 (org-match-string-no-properties 5)))))
7252 (defun org-get-entry ()
7253 "Get the entry text, after heading, entire subtree."
7254 (save-excursion
7255 (org-back-to-heading t)
7256 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7258 (defun org-insert-heading-after-current ()
7259 "Insert a new heading with same level as current, after current subtree."
7260 (interactive)
7261 (org-back-to-heading)
7262 (org-insert-heading)
7263 (org-move-subtree-down)
7264 (end-of-line 1))
7266 (defun org-insert-heading-respect-content ()
7267 (interactive)
7268 (let ((org-insert-heading-respect-content t))
7269 (org-insert-heading t)))
7271 (defun org-insert-todo-heading-respect-content (&optional force-state)
7272 (interactive "P")
7273 (let ((org-insert-heading-respect-content t))
7274 (org-insert-todo-heading force-state t)))
7276 (defun org-insert-todo-heading (arg &optional force-heading)
7277 "Insert a new heading with the same level and TODO state as current heading.
7278 If the heading has no TODO state, or if the state is DONE, use the first
7279 state (TODO by default). Also with prefix arg, force first state."
7280 (interactive "P")
7281 (when (or force-heading (not (org-insert-item 'checkbox)))
7282 (org-insert-heading force-heading)
7283 (save-excursion
7284 (org-back-to-heading)
7285 (outline-previous-heading)
7286 (looking-at org-todo-line-regexp))
7287 (let*
7288 ((new-mark-x
7289 (if (or arg
7290 (not (match-beginning 2))
7291 (member (match-string 2) org-done-keywords))
7292 (car org-todo-keywords-1)
7293 (match-string 2)))
7294 (new-mark
7296 (run-hook-with-args-until-success
7297 'org-todo-get-default-hook new-mark-x nil)
7298 new-mark-x)))
7299 (beginning-of-line 1)
7300 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7301 (if org-treat-insert-todo-heading-as-state-change
7302 (org-todo new-mark)
7303 (insert new-mark " "))))
7304 (when org-provide-todo-statistics
7305 (org-update-parent-todo-statistics))))
7307 (defun org-insert-subheading (arg)
7308 "Insert a new subheading and demote it.
7309 Works for outline headings and for plain lists alike."
7310 (interactive "P")
7311 (org-insert-heading arg)
7312 (cond
7313 ((org-at-heading-p) (org-do-demote))
7314 ((org-at-item-p) (org-indent-item))))
7316 (defun org-insert-todo-subheading (arg)
7317 "Insert a new subheading with TODO keyword or checkbox and demote it.
7318 Works for outline headings and for plain lists alike."
7319 (interactive "P")
7320 (org-insert-todo-heading arg)
7321 (cond
7322 ((org-at-heading-p) (org-do-demote))
7323 ((org-at-item-p) (org-indent-item))))
7325 ;;; Promotion and Demotion
7327 (defvar org-after-demote-entry-hook nil
7328 "Hook run after an entry has been demoted.
7329 The cursor will be at the beginning of the entry.
7330 When a subtree is being demoted, the hook will be called for each node.")
7332 (defvar org-after-promote-entry-hook nil
7333 "Hook run after an entry has been promoted.
7334 The cursor will be at the beginning of the entry.
7335 When a subtree is being promoted, the hook will be called for each node.")
7337 (defun org-promote-subtree ()
7338 "Promote the entire subtree.
7339 See also `org-promote'."
7340 (interactive)
7341 (save-excursion
7342 (org-with-limited-levels (org-map-tree 'org-promote)))
7343 (org-fix-position-after-promote))
7345 (defun org-demote-subtree ()
7346 "Demote the entire subtree. See `org-demote'.
7347 See also `org-promote'."
7348 (interactive)
7349 (save-excursion
7350 (org-with-limited-levels (org-map-tree 'org-demote)))
7351 (org-fix-position-after-promote))
7354 (defun org-do-promote ()
7355 "Promote the current heading higher up the tree.
7356 If the region is active in `transient-mark-mode', promote all headings
7357 in the region."
7358 (interactive)
7359 (save-excursion
7360 (if (org-region-active-p)
7361 (org-map-region 'org-promote (region-beginning) (region-end))
7362 (org-promote)))
7363 (org-fix-position-after-promote))
7365 (defun org-do-demote ()
7366 "Demote the current heading lower down the tree.
7367 If the region is active in `transient-mark-mode', demote all headings
7368 in the region."
7369 (interactive)
7370 (save-excursion
7371 (if (org-region-active-p)
7372 (org-map-region 'org-demote (region-beginning) (region-end))
7373 (org-demote)))
7374 (org-fix-position-after-promote))
7376 (defun org-fix-position-after-promote ()
7377 "Make sure that after pro/demotion cursor position is right."
7378 (let ((pos (point)))
7379 (when (save-excursion
7380 (beginning-of-line 1)
7381 (looking-at org-todo-line-regexp)
7382 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7383 (cond ((eobp) (insert " "))
7384 ((eolp) (insert " "))
7385 ((equal (char-after) ?\ ) (forward-char 1))))))
7387 (defun org-current-level ()
7388 "Return the level of the current entry, or nil if before the first headline.
7389 The level is the number of stars at the beginning of the headline."
7390 (save-excursion
7391 (org-with-limited-levels
7392 (if (ignore-errors (org-back-to-heading t))
7393 (funcall outline-level)))))
7395 (defun org-get-previous-line-level ()
7396 "Return the outline depth of the last headline before the current line.
7397 Returns 0 for the first headline in the buffer, and nil if before the
7398 first headline."
7399 (let ((current-level (org-current-level))
7400 (prev-level (when (> (line-number-at-pos) 1)
7401 (save-excursion
7402 (beginning-of-line 0)
7403 (org-current-level)))))
7404 (cond ((null current-level) nil) ; Before first headline
7405 ((null prev-level) 0) ; At first headline
7406 (prev-level))))
7408 (defun org-reduced-level (l)
7409 "Compute the effective level of a heading.
7410 This takes into account the setting of `org-odd-levels-only'."
7411 (cond
7412 ((zerop l) 0)
7413 (org-odd-levels-only (1+ (floor (/ l 2))))
7414 (t l)))
7416 (defun org-level-increment ()
7417 "Return the number of stars that will be added or removed at a
7418 time to headlines when structure editing, based on the value of
7419 `org-odd-levels-only'."
7420 (if org-odd-levels-only 2 1))
7422 (defun org-get-valid-level (level &optional change)
7423 "Rectify a level change under the influence of `org-odd-levels-only'
7424 LEVEL is a current level, CHANGE is by how much the level should be
7425 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7426 even level numbers will become the next higher odd number."
7427 (if org-odd-levels-only
7428 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7429 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7430 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7431 (max 1 (+ level (or change 0)))))
7433 (if (boundp 'define-obsolete-function-alias)
7434 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7435 (define-obsolete-function-alias 'org-get-legal-level
7436 'org-get-valid-level)
7437 (define-obsolete-function-alias 'org-get-legal-level
7438 'org-get-valid-level "23.1")))
7440 (defun org-promote ()
7441 "Promote the current heading higher up the tree.
7442 If the region is active in `transient-mark-mode', promote all headings
7443 in the region."
7444 (org-back-to-heading t)
7445 (let* ((level (save-match-data (funcall outline-level)))
7446 (after-change-functions (remove 'flyspell-after-change-function
7447 after-change-functions))
7448 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7449 (diff (abs (- level (length up-head) -1))))
7450 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7451 (replace-match up-head nil t)
7452 ;; Fixup tag positioning
7453 (and org-auto-align-tags (org-set-tags nil t))
7454 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7455 (run-hooks 'org-after-promote-entry-hook)))
7457 (defun org-demote ()
7458 "Demote the current heading lower down the tree.
7459 If the region is active in `transient-mark-mode', demote all headings
7460 in the region."
7461 (org-back-to-heading t)
7462 (let* ((level (save-match-data (funcall outline-level)))
7463 (after-change-functions (remove 'flyspell-after-change-function
7464 after-change-functions))
7465 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7466 (diff (abs (- level (length down-head) -1))))
7467 (replace-match down-head nil t)
7468 ;; Fixup tag positioning
7469 (and org-auto-align-tags (org-set-tags nil t))
7470 (if org-adapt-indentation (org-fixup-indentation diff))
7471 (run-hooks 'org-after-demote-entry-hook)))
7473 (defun org-cycle-level ()
7474 "Cycle the level of an empty headline through possible states.
7475 This goes first to child, then to parent, level, then up the hierarchy.
7476 After top level, it switches back to sibling level."
7477 (interactive)
7478 (let ((org-adapt-indentation nil))
7479 (when (org-point-at-end-of-empty-headline)
7480 (setq this-command 'org-cycle-level) ; Only needed for caching
7481 (let ((cur-level (org-current-level))
7482 (prev-level (org-get-previous-line-level)))
7483 (cond
7484 ;; If first headline in file, promote to top-level.
7485 ((= prev-level 0)
7486 (loop repeat (/ (- cur-level 1) (org-level-increment))
7487 do (org-do-promote)))
7488 ;; If same level as prev, demote one.
7489 ((= prev-level cur-level)
7490 (org-do-demote))
7491 ;; If parent is top-level, promote to top level if not already.
7492 ((= prev-level 1)
7493 (loop repeat (/ (- cur-level 1) (org-level-increment))
7494 do (org-do-promote)))
7495 ;; If top-level, return to prev-level.
7496 ((= cur-level 1)
7497 (loop repeat (/ (- prev-level 1) (org-level-increment))
7498 do (org-do-demote)))
7499 ;; If less than prev-level, promote one.
7500 ((< cur-level prev-level)
7501 (org-do-promote))
7502 ;; If deeper than prev-level, promote until higher than
7503 ;; prev-level.
7504 ((> cur-level prev-level)
7505 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7506 do (org-do-promote))))
7507 t))))
7509 (defun org-map-tree (fun)
7510 "Call FUN for every heading underneath the current one."
7511 (org-back-to-heading)
7512 (let ((level (funcall outline-level)))
7513 (save-excursion
7514 (funcall fun)
7515 (while (and (progn
7516 (outline-next-heading)
7517 (> (funcall outline-level) level))
7518 (not (eobp)))
7519 (funcall fun)))))
7521 (defun org-map-region (fun beg end)
7522 "Call FUN for every heading between BEG and END."
7523 (let ((org-ignore-region t))
7524 (save-excursion
7525 (setq end (copy-marker end))
7526 (goto-char beg)
7527 (if (and (re-search-forward org-outline-regexp-bol nil t)
7528 (< (point) end))
7529 (funcall fun))
7530 (while (and (progn
7531 (outline-next-heading)
7532 (< (point) end))
7533 (not (eobp)))
7534 (funcall fun)))))
7536 (defvar org-property-end-re) ; silence byte-compiler
7537 (defun org-fixup-indentation (diff)
7538 "Change the indentation in the current entry by DIFF.
7539 However, if any line in the current entry has no indentation, or if it
7540 would end up with no indentation after the change, nothing at all is done."
7541 (save-excursion
7542 (let ((end (save-excursion (outline-next-heading)
7543 (point-marker)))
7544 (prohibit (if (> diff 0)
7545 "^\\S-"
7546 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7547 col)
7548 (unless (save-excursion (end-of-line 1)
7549 (re-search-forward prohibit end t))
7550 (while (and (< (point) end)
7551 (re-search-forward "^[ \t]+" end t))
7552 (goto-char (match-end 0))
7553 (setq col (current-column))
7554 (if (< diff 0) (replace-match ""))
7555 (org-indent-to-column (+ diff col))))
7556 (move-marker end nil))))
7558 (defun org-convert-to-odd-levels ()
7559 "Convert an org-mode file with all levels allowed to one with odd levels.
7560 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7561 level 5 etc."
7562 (interactive)
7563 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7564 (let ((outline-level 'org-outline-level)
7565 (org-odd-levels-only nil) n)
7566 (save-excursion
7567 (goto-char (point-min))
7568 (while (re-search-forward "^\\*\\*+ " nil t)
7569 (setq n (- (length (match-string 0)) 2))
7570 (while (>= (setq n (1- n)) 0)
7571 (org-demote))
7572 (end-of-line 1))))))
7574 (defun org-convert-to-oddeven-levels ()
7575 "Convert an org-mode file with only odd levels to one with odd/even levels.
7576 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7577 file contains a section with an even level, conversion would
7578 destroy the structure of the file. An error is signaled in this
7579 case."
7580 (interactive)
7581 (goto-char (point-min))
7582 ;; First check if there are no even levels
7583 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7584 (org-show-context t)
7585 (error "Not all levels are odd in this file. Conversion not possible"))
7586 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7587 (let ((outline-regexp org-outline-regexp)
7588 (outline-level 'org-outline-level)
7589 (org-odd-levels-only nil) n)
7590 (save-excursion
7591 (goto-char (point-min))
7592 (while (re-search-forward "^\\*\\*+ " nil t)
7593 (setq n (/ (1- (length (match-string 0))) 2))
7594 (while (>= (setq n (1- n)) 0)
7595 (org-promote))
7596 (end-of-line 1))))))
7598 (defun org-tr-level (n)
7599 "Make N odd if required."
7600 (if org-odd-levels-only (1+ (/ n 2)) n))
7602 ;;; Vertical tree motion, cutting and pasting of subtrees
7604 (defun org-move-subtree-up (&optional arg)
7605 "Move the current subtree up past ARG headlines of the same level."
7606 (interactive "p")
7607 (org-move-subtree-down (- (prefix-numeric-value arg))))
7609 (defun org-move-subtree-down (&optional arg)
7610 "Move the current subtree down past ARG headlines of the same level."
7611 (interactive "p")
7612 (setq arg (prefix-numeric-value arg))
7613 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7614 'org-get-last-sibling))
7615 (ins-point (make-marker))
7616 (cnt (abs arg))
7617 (col (current-column))
7618 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7619 ;; Select the tree
7620 (org-back-to-heading)
7621 (setq beg0 (point))
7622 (save-excursion
7623 (setq ne-beg (org-back-over-empty-lines))
7624 (setq beg (point)))
7625 (save-match-data
7626 (save-excursion (outline-end-of-heading)
7627 (setq folded (outline-invisible-p)))
7628 (outline-end-of-subtree))
7629 (outline-next-heading)
7630 (setq ne-end (org-back-over-empty-lines))
7631 (setq end (point))
7632 (goto-char beg0)
7633 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7634 ;; include less whitespace
7635 (save-excursion
7636 (goto-char beg)
7637 (forward-line (- ne-beg ne-end))
7638 (setq beg (point))))
7639 ;; Find insertion point, with error handling
7640 (while (> cnt 0)
7641 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7642 (progn (goto-char beg0)
7643 (error "Cannot move past superior level or buffer limit")))
7644 (setq cnt (1- cnt)))
7645 (if (> arg 0)
7646 ;; Moving forward - still need to move over subtree
7647 (progn (org-end-of-subtree t t)
7648 (save-excursion
7649 (org-back-over-empty-lines)
7650 (or (bolp) (newline)))))
7651 (setq ne-ins (org-back-over-empty-lines))
7652 (move-marker ins-point (point))
7653 (setq txt (buffer-substring beg end))
7654 (org-save-markers-in-region beg end)
7655 (delete-region beg end)
7656 (org-remove-empty-overlays-at beg)
7657 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7658 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7659 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7660 (let ((bbb (point)))
7661 (insert-before-markers txt)
7662 (org-reinstall-markers-in-region bbb)
7663 (move-marker ins-point bbb))
7664 (or (bolp) (insert "\n"))
7665 (setq ins-end (point))
7666 (goto-char ins-point)
7667 (org-skip-whitespace)
7668 (when (and (< arg 0)
7669 (org-first-sibling-p)
7670 (> ne-ins ne-beg))
7671 ;; Move whitespace back to beginning
7672 (save-excursion
7673 (goto-char ins-end)
7674 (let ((kill-whole-line t))
7675 (kill-line (- ne-ins ne-beg)) (point)))
7676 (insert (make-string (- ne-ins ne-beg) ?\n)))
7677 (move-marker ins-point nil)
7678 (if folded
7679 (hide-subtree)
7680 (org-show-entry)
7681 (show-children)
7682 (org-cycle-hide-drawers 'children))
7683 (org-clean-visibility-after-subtree-move)
7684 ;; move back to the initial column we were at
7685 (move-to-column col)))
7687 (defvar org-subtree-clip ""
7688 "Clipboard for cut and paste of subtrees.
7689 This is actually only a copy of the kill, because we use the normal kill
7690 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7692 (defvar org-subtree-clip-folded nil
7693 "Was the last copied subtree folded?
7694 This is used to fold the tree back after pasting.")
7696 (defun org-cut-subtree (&optional n)
7697 "Cut the current subtree into the clipboard.
7698 With prefix arg N, cut this many sequential subtrees.
7699 This is a short-hand for marking the subtree and then cutting it."
7700 (interactive "p")
7701 (org-copy-subtree n 'cut))
7703 (defun org-copy-subtree (&optional n cut force-store-markers)
7704 "Cut the current subtree into the clipboard.
7705 With prefix arg N, cut this many sequential subtrees.
7706 This is a short-hand for marking the subtree and then copying it.
7707 If CUT is non-nil, actually cut the subtree.
7708 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7709 of some markers in the region, even if CUT is non-nil. This is
7710 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7711 (interactive "p")
7712 (let (beg end folded (beg0 (point)))
7713 (if (org-called-interactively-p 'any)
7714 (org-back-to-heading nil) ; take what looks like a subtree
7715 (org-back-to-heading t)) ; take what is really there
7716 (org-back-over-empty-lines)
7717 (setq beg (point))
7718 (skip-chars-forward " \t\r\n")
7719 (save-match-data
7720 (save-excursion (outline-end-of-heading)
7721 (setq folded (outline-invisible-p)))
7722 (condition-case nil
7723 (org-forward-same-level (1- n) t)
7724 (error nil))
7725 (org-end-of-subtree t t))
7726 (org-back-over-empty-lines)
7727 (setq end (point))
7728 (goto-char beg0)
7729 (when (> end beg)
7730 (setq org-subtree-clip-folded folded)
7731 (when (or cut force-store-markers)
7732 (org-save-markers-in-region beg end))
7733 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7734 (setq org-subtree-clip (current-kill 0))
7735 (message "%s: Subtree(s) with %d characters"
7736 (if cut "Cut" "Copied")
7737 (length org-subtree-clip)))))
7739 (defun org-paste-subtree (&optional level tree for-yank)
7740 "Paste the clipboard as a subtree, with modification of headline level.
7741 The entire subtree is promoted or demoted in order to match a new headline
7742 level.
7744 If the cursor is at the beginning of a headline, the same level as
7745 that headline is used to paste the tree
7747 If not, the new level is derived from the *visible* headings
7748 before and after the insertion point, and taken to be the inferior headline
7749 level of the two. So if the previous visible heading is level 3 and the
7750 next is level 4 (or vice versa), level 4 will be used for insertion.
7751 This makes sure that the subtree remains an independent subtree and does
7752 not swallow low level entries.
7754 You can also force a different level, either by using a numeric prefix
7755 argument, or by inserting the heading marker by hand. For example, if the
7756 cursor is after \"*****\", then the tree will be shifted to level 5.
7758 If optional TREE is given, use this text instead of the kill ring.
7760 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7761 move back over whitespace before inserting, and move point to the end of
7762 the inserted text when done."
7763 (interactive "P")
7764 (setq tree (or tree (and kill-ring (current-kill 0))))
7765 (unless (org-kill-is-subtree-p tree)
7766 (error "%s"
7767 (substitute-command-keys
7768 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7769 (org-with-limited-levels
7770 (let* ((visp (not (outline-invisible-p)))
7771 (txt tree)
7772 (^re_ "\\(\\*+\\)[ \t]*")
7773 (old-level (if (string-match org-outline-regexp-bol txt)
7774 (- (match-end 0) (match-beginning 0) 1)
7775 -1))
7776 (force-level (cond (level (prefix-numeric-value level))
7777 ((and (looking-at "[ \t]*$")
7778 (string-match
7779 "^\\*+$" (buffer-substring
7780 (point-at-bol) (point))))
7781 (- (match-end 1) (match-beginning 1)))
7782 ((and (bolp)
7783 (looking-at org-outline-regexp))
7784 (- (match-end 0) (point) 1))
7785 (t nil)))
7786 (previous-level (save-excursion
7787 (condition-case nil
7788 (progn
7789 (outline-previous-visible-heading 1)
7790 (if (looking-at ^re_)
7791 (- (match-end 0) (match-beginning 0) 1)
7793 (error 1))))
7794 (next-level (save-excursion
7795 (condition-case nil
7796 (progn
7797 (or (looking-at org-outline-regexp)
7798 (outline-next-visible-heading 1))
7799 (if (looking-at ^re_)
7800 (- (match-end 0) (match-beginning 0) 1)
7802 (error 1))))
7803 (new-level (or force-level (max previous-level next-level)))
7804 (shift (if (or (= old-level -1)
7805 (= new-level -1)
7806 (= old-level new-level))
7808 (- new-level old-level)))
7809 (delta (if (> shift 0) -1 1))
7810 (func (if (> shift 0) 'org-demote 'org-promote))
7811 (org-odd-levels-only nil)
7812 beg end newend)
7813 ;; Remove the forced level indicator
7814 (if force-level
7815 (delete-region (point-at-bol) (point)))
7816 ;; Paste
7817 (beginning-of-line (if (bolp) 1 2))
7818 (unless for-yank (org-back-over-empty-lines))
7819 (setq beg (point))
7820 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7821 (insert-before-markers txt)
7822 (unless (string-match "\n\\'" txt) (insert "\n"))
7823 (setq newend (point))
7824 (org-reinstall-markers-in-region beg)
7825 (setq end (point))
7826 (goto-char beg)
7827 (skip-chars-forward " \t\n\r")
7828 (setq beg (point))
7829 (if (and (outline-invisible-p) visp)
7830 (save-excursion (outline-show-heading)))
7831 ;; Shift if necessary
7832 (unless (= shift 0)
7833 (save-restriction
7834 (narrow-to-region beg end)
7835 (while (not (= shift 0))
7836 (org-map-region func (point-min) (point-max))
7837 (setq shift (+ delta shift)))
7838 (goto-char (point-min))
7839 (setq newend (point-max))))
7840 (when (or (org-called-interactively-p 'interactive) for-yank)
7841 (message "Clipboard pasted as level %d subtree" new-level))
7842 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7843 kill-ring
7844 (eq org-subtree-clip (current-kill 0))
7845 org-subtree-clip-folded)
7846 ;; The tree was folded before it was killed/copied
7847 (hide-subtree))
7848 (and for-yank (goto-char newend)))))
7850 (defun org-kill-is-subtree-p (&optional txt)
7851 "Check if the current kill is an outline subtree, or a set of trees.
7852 Returns nil if kill does not start with a headline, or if the first
7853 headline level is not the largest headline level in the tree.
7854 So this will actually accept several entries of equal levels as well,
7855 which is OK for `org-paste-subtree'.
7856 If optional TXT is given, check this string instead of the current kill."
7857 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7858 (re (org-get-limited-outline-regexp))
7859 (^re (concat "^" re))
7860 (start-level (and kill
7861 (string-match
7862 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7863 kill)
7864 (- (match-end 2) (match-beginning 2) 1)))
7865 (start (1+ (or (match-beginning 2) -1))))
7866 (if (not start-level)
7867 (progn
7868 nil) ;; does not even start with a heading
7869 (catch 'exit
7870 (while (setq start (string-match ^re kill (1+ start)))
7871 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7872 (throw 'exit nil)))
7873 t))))
7875 (defvar org-markers-to-move nil
7876 "Markers that should be moved with a cut-and-paste operation.
7877 Those markers are stored together with their positions relative to
7878 the start of the region.")
7880 (defun org-save-markers-in-region (beg end)
7881 "Check markers in region.
7882 If these markers are between BEG and END, record their position relative
7883 to BEG, so that after moving the block of text, we can put the markers back
7884 into place.
7885 This function gets called just before an entry or tree gets cut from the
7886 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7887 called immediately, to move the markers with the entries."
7888 (setq org-markers-to-move nil)
7889 (when (featurep 'org-clock)
7890 (org-clock-save-markers-for-cut-and-paste beg end))
7891 (when (featurep 'org-agenda)
7892 (org-agenda-save-markers-for-cut-and-paste beg end)))
7894 (defun org-check-and-save-marker (marker beg end)
7895 "Check if MARKER is between BEG and END.
7896 If yes, remember the marker and the distance to BEG."
7897 (when (and (marker-buffer marker)
7898 (equal (marker-buffer marker) (current-buffer)))
7899 (if (and (>= marker beg) (< marker end))
7900 (push (cons marker (- marker beg)) org-markers-to-move))))
7902 (defun org-reinstall-markers-in-region (beg)
7903 "Move all remembered markers to their position relative to BEG."
7904 (mapc (lambda (x)
7905 (move-marker (car x) (+ beg (cdr x))))
7906 org-markers-to-move)
7907 (setq org-markers-to-move nil))
7909 (defun org-narrow-to-subtree ()
7910 "Narrow buffer to the current subtree."
7911 (interactive)
7912 (save-excursion
7913 (save-match-data
7914 (org-with-limited-levels
7915 (narrow-to-region
7916 (progn (org-back-to-heading t) (point))
7917 (progn (org-end-of-subtree t t)
7918 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7919 (point)))))))
7921 (defun org-narrow-to-block ()
7922 "Narrow buffer to the current block."
7923 (interactive)
7924 (let* ((case-fold-search t)
7925 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7926 "^[ \t]*#\\+end_.*")))
7927 (if blockp
7928 (narrow-to-region (car blockp) (cdr blockp))
7929 (error "Not in a block"))))
7931 (eval-when-compile
7932 (defvar org-property-drawer-re))
7934 (defvar org-property-start-re) ;; defined below
7935 (defun org-clone-subtree-with-time-shift (n &optional shift)
7936 "Clone the task (subtree) at point N times.
7937 The clones will be inserted as siblings.
7939 In interactive use, the user will be prompted for the number of
7940 clones to be produced, and for a time SHIFT, which may be a
7941 repeater as used in time stamps, for example `+3d'.
7943 When a valid repeater is given and the entry contains any time
7944 stamps, the clones will become a sequence in time, with time
7945 stamps in the subtree shifted for each clone produced. If SHIFT
7946 is nil or the empty string, time stamps will be left alone. The
7947 ID property of the original subtree is removed.
7949 If the original subtree did contain time stamps with a repeater,
7950 the following will happen:
7951 - the repeater will be removed in each clone
7952 - an additional clone will be produced, with the current, unshifted
7953 date(s) in the entry.
7954 - the original entry will be placed *after* all the clones, with
7955 repeater intact.
7956 - the start days in the repeater in the original entry will be shifted
7957 to past the last clone.
7958 In this way you can spell out a number of instances of a repeating task,
7959 and still retain the repeater to cover future instances of the task."
7960 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7961 (let (beg end template task idprop
7962 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7963 (drawer-re org-drawer-regexp))
7964 (if (not (and (integerp n) (> n 0)))
7965 (error "Invalid number of replications %s" n))
7966 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7967 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7968 shift)))
7969 (error "Invalid shift specification %s" shift))
7970 (when doshift
7971 (setq shift-n (string-to-number (match-string 1 shift))
7972 shift-what (cdr (assoc (match-string 2 shift)
7973 '(("d" . day) ("w" . week)
7974 ("m" . month) ("y" . year))))))
7975 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7976 (setq nmin 1 nmax n)
7977 (org-back-to-heading t)
7978 (setq beg (point))
7979 (setq idprop (org-entry-get nil "ID"))
7980 (org-end-of-subtree t t)
7981 (or (bolp) (insert "\n"))
7982 (setq end (point))
7983 (setq template (buffer-substring beg end))
7984 (when (and doshift
7985 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7986 (delete-region beg end)
7987 (setq end beg)
7988 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7989 (goto-char end)
7990 (loop for n from nmin to nmax do
7991 ;; prepare clone
7992 (with-temp-buffer
7993 (insert template)
7994 (org-mode)
7995 (goto-char (point-min))
7996 (org-show-subtree)
7997 (and idprop (if org-clone-delete-id
7998 (org-entry-delete nil "ID")
7999 (org-id-get-create t)))
8000 (unless (= n 0)
8001 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8002 (kill-whole-line))
8003 (goto-char (point-min))
8004 (while (re-search-forward drawer-re nil t)
8005 (mapc (lambda (d)
8006 (org-remove-empty-drawer-at d (point))) org-drawers)))
8007 (goto-char (point-min))
8008 (when doshift
8009 (while (re-search-forward org-ts-regexp-both nil t)
8010 (org-timestamp-change (* n shift-n) shift-what))
8011 (unless (= n n-no-remove)
8012 (goto-char (point-min))
8013 (while (re-search-forward org-ts-regexp nil t)
8014 (save-excursion
8015 (goto-char (match-beginning 0))
8016 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8017 (delete-region (match-beginning 1) (match-end 1)))))))
8018 (setq task (buffer-string)))
8019 (insert task))
8020 (goto-char beg)))
8022 ;;; Outline Sorting
8024 (defun org-sort (with-case)
8025 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8026 Optional argument WITH-CASE means sort case-sensitively."
8027 (interactive "P")
8028 (cond
8029 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8030 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8032 (org-call-with-arg 'org-sort-entries with-case))))
8034 (defun org-sort-remove-invisible (s)
8035 (remove-text-properties 0 (length s) org-rm-props s)
8036 (while (string-match org-bracket-link-regexp s)
8037 (setq s (replace-match (if (match-end 2)
8038 (match-string 3 s)
8039 (match-string 1 s)) t t s)))
8042 (defvar org-priority-regexp) ; defined later in the file
8044 (defvar org-after-sorting-entries-or-items-hook nil
8045 "Hook that is run after a bunch of entries or items have been sorted.
8046 When children are sorted, the cursor is in the parent line when this
8047 hook gets called. When a region or a plain list is sorted, the cursor
8048 will be in the first entry of the sorted region/list.")
8050 (defun org-sort-entries
8051 (&optional with-case sorting-type getkey-func compare-func property)
8052 "Sort entries on a certain level of an outline tree.
8053 If there is an active region, the entries in the region are sorted.
8054 Else, if the cursor is before the first entry, sort the top-level items.
8055 Else, the children of the entry at point are sorted.
8057 Sorting can be alphabetically, numerically, by date/time as given by
8058 a time stamp, by a property or by priority.
8060 The command prompts for the sorting type unless it has been given to the
8061 function through the SORTING-TYPE argument, which needs to be a character,
8062 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8063 precise meaning of each character:
8065 n Numerically, by converting the beginning of the entry/item to a number.
8066 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8067 t By date/time, either the first active time stamp in the entry, or, if
8068 none exist, by the first inactive one.
8069 s By the scheduled date/time.
8070 d By deadline date/time.
8071 c By creation time, which is assumed to be the first inactive time stamp
8072 at the beginning of a line.
8073 p By priority according to the cookie.
8074 r By the value of a property.
8076 Capital letters will reverse the sort order.
8078 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8079 called with point at the beginning of the record. It must return either
8080 a string or a number that should serve as the sorting key for that record.
8082 Comparing entries ignores case by default. However, with an optional argument
8083 WITH-CASE, the sorting considers case as well."
8084 (interactive "P")
8085 (let ((case-func (if with-case 'identity 'downcase))
8086 start beg end stars re re2
8087 txt what tmp)
8088 ;; Find beginning and end of region to sort
8089 (cond
8090 ((org-region-active-p)
8091 ;; we will sort the region
8092 (setq end (region-end)
8093 what "region")
8094 (goto-char (region-beginning))
8095 (if (not (org-at-heading-p)) (outline-next-heading))
8096 (setq start (point)))
8097 ((or (org-at-heading-p)
8098 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8099 ;; we will sort the children of the current headline
8100 (org-back-to-heading)
8101 (setq start (point)
8102 end (progn (org-end-of-subtree t t)
8103 (or (bolp) (insert "\n"))
8104 (org-back-over-empty-lines)
8105 (point))
8106 what "children")
8107 (goto-char start)
8108 (show-subtree)
8109 (outline-next-heading))
8111 ;; we will sort the top-level entries in this file
8112 (goto-char (point-min))
8113 (or (org-at-heading-p) (outline-next-heading))
8114 (setq start (point))
8115 (goto-char (point-max))
8116 (beginning-of-line 1)
8117 (when (looking-at ".*?\\S-")
8118 ;; File ends in a non-white line
8119 (end-of-line 1)
8120 (insert "\n"))
8121 (setq end (point-max))
8122 (setq what "top-level")
8123 (goto-char start)
8124 (show-all)))
8126 (setq beg (point))
8127 (if (>= beg end) (error "Nothing to sort"))
8129 (looking-at "\\(\\*+\\)")
8130 (setq stars (match-string 1)
8131 re (concat "^" (regexp-quote stars) " +")
8132 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8133 txt (buffer-substring beg end))
8134 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8135 (if (and (not (equal stars "*")) (string-match re2 txt))
8136 (error "Region to sort contains a level above the first entry"))
8138 (unless sorting-type
8139 (message
8140 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8141 [t]ime [s]cheduled [d]eadline [c]reated
8142 A/N/T/S/D/C/P/O/F means reversed:"
8143 what)
8144 (setq sorting-type (read-char-exclusive))
8146 (and (= (downcase sorting-type) ?f)
8147 (setq getkey-func
8148 (org-icompleting-read "Sort using function: "
8149 obarray 'fboundp t nil nil))
8150 (setq getkey-func (intern getkey-func)))
8152 (and (= (downcase sorting-type) ?r)
8153 (setq property
8154 (org-icompleting-read "Property: "
8155 (mapcar 'list (org-buffer-property-keys t))
8156 nil t))))
8158 (message "Sorting entries...")
8160 (save-restriction
8161 (narrow-to-region start end)
8162 (let ((dcst (downcase sorting-type))
8163 (case-fold-search nil)
8164 (now (current-time)))
8165 (sort-subr
8166 (/= dcst sorting-type)
8167 ;; This function moves to the beginning character of the "record" to
8168 ;; be sorted.
8169 (lambda nil
8170 (if (re-search-forward re nil t)
8171 (goto-char (match-beginning 0))
8172 (goto-char (point-max))))
8173 ;; This function moves to the last character of the "record" being
8174 ;; sorted.
8175 (lambda nil
8176 (save-match-data
8177 (condition-case nil
8178 (outline-forward-same-level 1)
8179 (error
8180 (goto-char (point-max))))))
8181 ;; This function returns the value that gets sorted against.
8182 (lambda nil
8183 (cond
8184 ((= dcst ?n)
8185 (if (looking-at org-complex-heading-regexp)
8186 (string-to-number (match-string 4))
8187 nil))
8188 ((= dcst ?a)
8189 (if (looking-at org-complex-heading-regexp)
8190 (funcall case-func (match-string 4))
8191 nil))
8192 ((= dcst ?t)
8193 (let ((end (save-excursion (outline-next-heading) (point))))
8194 (if (or (re-search-forward org-ts-regexp end t)
8195 (re-search-forward org-ts-regexp-both end t))
8196 (org-time-string-to-seconds (match-string 0))
8197 (org-float-time now))))
8198 ((= dcst ?c)
8199 (let ((end (save-excursion (outline-next-heading) (point))))
8200 (if (re-search-forward
8201 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8202 end t)
8203 (org-time-string-to-seconds (match-string 0))
8204 (org-float-time now))))
8205 ((= dcst ?s)
8206 (let ((end (save-excursion (outline-next-heading) (point))))
8207 (if (re-search-forward org-scheduled-time-regexp end t)
8208 (org-time-string-to-seconds (match-string 1))
8209 (org-float-time now))))
8210 ((= dcst ?d)
8211 (let ((end (save-excursion (outline-next-heading) (point))))
8212 (if (re-search-forward org-deadline-time-regexp end t)
8213 (org-time-string-to-seconds (match-string 1))
8214 (org-float-time now))))
8215 ((= dcst ?p)
8216 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8217 (string-to-char (match-string 2))
8218 org-default-priority))
8219 ((= dcst ?r)
8220 (or (org-entry-get nil property) ""))
8221 ((= dcst ?o)
8222 (if (looking-at org-complex-heading-regexp)
8223 (- 9999 (length (member (match-string 2)
8224 org-todo-keywords-1)))))
8225 ((= dcst ?f)
8226 (if getkey-func
8227 (progn
8228 (setq tmp (funcall getkey-func))
8229 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8230 tmp)
8231 (error "Invalid key function `%s'" getkey-func)))
8232 (t (error "Invalid sorting type `%c'" sorting-type))))
8234 (cond
8235 ((= dcst ?a) 'string<)
8236 ((= dcst ?f) compare-func)
8237 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8238 (t nil)))))
8239 (run-hooks 'org-after-sorting-entries-or-items-hook)
8240 (message "Sorting entries...done")))
8242 (defun org-do-sort (table what &optional with-case sorting-type)
8243 "Sort TABLE of WHAT according to SORTING-TYPE.
8244 The user will be prompted for the SORTING-TYPE if the call to this
8245 function does not specify it. WHAT is only for the prompt, to indicate
8246 what is being sorted. The sorting key will be extracted from
8247 the car of the elements of the table.
8248 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8249 (unless sorting-type
8250 (message
8251 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8252 what)
8253 (setq sorting-type (read-char-exclusive)))
8254 (let ((dcst (downcase sorting-type))
8255 extractfun comparefun)
8256 ;; Define the appropriate functions
8257 (cond
8258 ((= dcst ?n)
8259 (setq extractfun 'string-to-number
8260 comparefun (if (= dcst sorting-type) '< '>)))
8261 ((= dcst ?a)
8262 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8263 (lambda(x) (downcase (org-sort-remove-invisible x))))
8264 comparefun (if (= dcst sorting-type)
8265 'string<
8266 (lambda (a b) (and (not (string< a b))
8267 (not (string= a b)))))))
8268 ((= dcst ?t)
8269 (setq extractfun
8270 (lambda (x)
8271 (if (or (string-match org-ts-regexp x)
8272 (string-match org-ts-regexp-both x))
8273 (org-float-time
8274 (org-time-string-to-time (match-string 0 x)))
8276 comparefun (if (= dcst sorting-type) '< '>)))
8277 (t (error "Invalid sorting type `%c'" sorting-type)))
8279 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8280 table)
8281 (lambda (a b) (funcall comparefun (car a) (car b))))))
8284 ;;; The orgstruct minor mode
8286 ;; Define a minor mode which can be used in other modes in order to
8287 ;; integrate the org-mode structure editing commands.
8289 ;; This is really a hack, because the org-mode structure commands use
8290 ;; keys which normally belong to the major mode. Here is how it
8291 ;; works: The minor mode defines all the keys necessary to operate the
8292 ;; structure commands, but wraps the commands into a function which
8293 ;; tests if the cursor is currently at a headline or a plain list
8294 ;; item. If that is the case, the structure command is used,
8295 ;; temporarily setting many Org-mode variables like regular
8296 ;; expressions for filling etc. However, when any of those keys is
8297 ;; used at a different location, function uses `key-binding' to look
8298 ;; up if the key has an associated command in another currently active
8299 ;; keymap (minor modes, major mode, global), and executes that
8300 ;; command. There might be problems if any of the keys is otherwise
8301 ;; used as a prefix key.
8303 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8304 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8305 ;; addresses this by checking explicitly for both bindings.
8307 (defvar orgstruct-mode-map (make-sparse-keymap)
8308 "Keymap for the minor `orgstruct-mode'.")
8310 (defvar org-local-vars nil
8311 "List of local variables, for use by `orgstruct-mode'.")
8313 ;;;###autoload
8314 (define-minor-mode orgstruct-mode
8315 "Toggle the minor mode `orgstruct-mode'.
8316 This mode is for using Org-mode structure commands in other
8317 modes. The following keys behave as if Org-mode were active, if
8318 the cursor is on a headline, or on a plain list item (both as
8319 defined by Org-mode).
8321 M-up Move entry/item up
8322 M-down Move entry/item down
8323 M-left Promote
8324 M-right Demote
8325 M-S-up Move entry/item up
8326 M-S-down Move entry/item down
8327 M-S-left Promote subtree
8328 M-S-right Demote subtree
8329 M-q Fill paragraph and items like in Org-mode
8330 C-c ^ Sort entries
8331 C-c - Cycle list bullet
8332 TAB Cycle item visibility
8333 M-RET Insert new heading/item
8334 S-M-RET Insert new TODO heading / Checkbox item
8335 C-c C-c Set tags / toggle checkbox"
8336 nil " OrgStruct" nil
8337 (org-load-modules-maybe)
8338 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8340 ;;;###autoload
8341 (defun turn-on-orgstruct ()
8342 "Unconditionally turn on `orgstruct-mode'."
8343 (orgstruct-mode 1))
8345 (defun orgstruct++-mode (&optional arg)
8346 "Toggle `orgstruct-mode', the enhanced version of it.
8347 In addition to setting orgstruct-mode, this also exports all indentation
8348 and autofilling variables from org-mode into the buffer. It will also
8349 recognize item context in multiline items.
8350 Note that turning off orgstruct-mode will *not* remove the
8351 indentation/paragraph settings. This can only be done by refreshing the
8352 major mode, for example with \\[normal-mode]."
8353 (interactive "P")
8354 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8355 (if (< arg 1)
8356 (orgstruct-mode -1)
8357 (orgstruct-mode 1)
8358 (let (var val)
8359 (mapc
8360 (lambda (x)
8361 (when (string-match
8362 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8363 (symbol-name (car x)))
8364 (setq var (car x) val (nth 1 x))
8365 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8366 org-local-vars)
8367 (org-set-local 'orgstruct-is-++ t))))
8369 (defvar orgstruct-is-++ nil
8370 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8371 (make-variable-buffer-local 'orgstruct-is-++)
8373 ;;;###autoload
8374 (defun turn-on-orgstruct++ ()
8375 "Unconditionally turn on `orgstruct++-mode'."
8376 (orgstruct++-mode 1))
8378 (defun orgstruct-error ()
8379 "Error when there is no default binding for a structure key."
8380 (interactive)
8381 (error "This key has no function outside structure elements"))
8383 (defun orgstruct-setup ()
8384 "Setup orgstruct keymaps."
8385 (let ((nfunc 0)
8386 (bindings
8387 (list
8388 '([(meta up)] org-metaup)
8389 '([(meta down)] org-metadown)
8390 '([(meta left)] org-metaleft)
8391 '([(meta right)] org-metaright)
8392 '([(meta shift up)] org-shiftmetaup)
8393 '([(meta shift down)] org-shiftmetadown)
8394 '([(meta shift left)] org-shiftmetaleft)
8395 '([(meta shift right)] org-shiftmetaright)
8396 '([?\e (up)] org-metaup)
8397 '([?\e (down)] org-metadown)
8398 '([?\e (left)] org-metaleft)
8399 '([?\e (right)] org-metaright)
8400 '([?\e (shift up)] org-shiftmetaup)
8401 '([?\e (shift down)] org-shiftmetadown)
8402 '([?\e (shift left)] org-shiftmetaleft)
8403 '([?\e (shift right)] org-shiftmetaright)
8404 '([(shift up)] org-shiftup)
8405 '([(shift down)] org-shiftdown)
8406 '([(shift left)] org-shiftleft)
8407 '([(shift right)] org-shiftright)
8408 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8409 '("\M-q" fill-paragraph)
8410 '("\C-c^" org-sort)
8411 '("\C-c-" org-cycle-list-bullet)))
8412 elt key fun cmd)
8413 (while (setq elt (pop bindings))
8414 (setq nfunc (1+ nfunc))
8415 (setq key (org-key (car elt))
8416 fun (nth 1 elt)
8417 cmd (orgstruct-make-binding fun nfunc key))
8418 (org-defkey orgstruct-mode-map key cmd))
8420 ;; Special treatment needed for TAB and RET
8421 (org-defkey orgstruct-mode-map [(tab)]
8422 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8423 (org-defkey orgstruct-mode-map "\C-i"
8424 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8426 (org-defkey orgstruct-mode-map "\M-\C-m"
8427 (orgstruct-make-binding 'org-insert-heading 105
8428 "\M-\C-m" [(meta return)]))
8429 (org-defkey orgstruct-mode-map [(meta return)]
8430 (orgstruct-make-binding 'org-insert-heading 106
8431 [(meta return)] "\M-\C-m"))
8433 (org-defkey orgstruct-mode-map [(shift meta return)]
8434 (orgstruct-make-binding 'org-insert-todo-heading 107
8435 [(meta return)] "\M-\C-m"))
8437 (org-defkey orgstruct-mode-map "\e\C-m"
8438 (orgstruct-make-binding 'org-insert-heading 108
8439 "\e\C-m" [?\e (return)]))
8440 (org-defkey orgstruct-mode-map [?\e (return)]
8441 (orgstruct-make-binding 'org-insert-heading 109
8442 [?\e (return)] "\e\C-m"))
8443 (org-defkey orgstruct-mode-map [?\e (shift return)]
8444 (orgstruct-make-binding 'org-insert-todo-heading 110
8445 [?\e (return)] "\e\C-m"))
8447 (unless org-local-vars
8448 (setq org-local-vars (org-get-local-variables)))
8452 (defun orgstruct-make-binding (fun n &rest keys)
8453 "Create a function for binding in the structure minor mode.
8454 FUN is the command to call inside a table. N is used to create a unique
8455 command name. KEYS are keys that should be checked in for a command
8456 to execute outside of tables."
8457 (eval
8458 (list 'defun
8459 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8460 '(arg)
8461 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8462 "Outside of structure, run the binding of `"
8463 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8464 "'.")
8465 '(interactive "p")
8466 (list 'if
8467 `(org-context-p 'headline 'item
8468 (and orgstruct-is-++
8469 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8470 'item-body))
8471 (list 'org-run-like-in-org-mode (list 'quote fun))
8472 (list 'let '(orgstruct-mode)
8473 (list 'call-interactively
8474 (append '(or)
8475 (mapcar (lambda (k)
8476 (list 'key-binding k))
8477 keys)
8478 '('orgstruct-error))))))))
8480 (defun org-context-p (&rest contexts)
8481 "Check if local context is any of CONTEXTS.
8482 Possible values in the list of contexts are `table', `headline', and `item'."
8483 (let ((pos (point)))
8484 (goto-char (point-at-bol))
8485 (prog1 (or (and (memq 'table contexts)
8486 (looking-at "[ \t]*|"))
8487 (and (memq 'headline contexts)
8488 (looking-at org-outline-regexp))
8489 (and (memq 'item contexts)
8490 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8491 (and (memq 'item-body contexts)
8492 (org-in-item-p)))
8493 (goto-char pos))))
8495 (defun org-get-local-variables ()
8496 "Return a list of all local variables in an org-mode buffer."
8497 (let (varlist)
8498 (with-current-buffer (get-buffer-create "*Org tmp*")
8499 (erase-buffer)
8500 (org-mode)
8501 (setq varlist (buffer-local-variables)))
8502 (kill-buffer "*Org tmp*")
8503 (delq nil
8504 (mapcar
8505 (lambda (x)
8506 (setq x
8507 (if (symbolp x)
8508 (list x)
8509 (list (car x) (list 'quote (cdr x)))))
8510 (if (string-match
8511 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8512 (symbol-name (car x)))
8513 x nil))
8514 varlist))))
8516 (defun org-clone-local-variables (from-buffer &optional regexp)
8517 "Clone local variables from FROM-BUFFER.
8518 Optional argument REGEXP selects variables to clone."
8519 (mapc
8520 (lambda (pair)
8521 (and (symbolp (car pair))
8522 (or (null regexp)
8523 (string-match regexp (symbol-name (car pair))))
8524 (set (make-local-variable (car pair))
8525 (cdr pair))))
8526 (buffer-local-variables from-buffer)))
8528 ;;;###autoload
8529 (defun org-run-like-in-org-mode (cmd)
8530 "Run a command, pretending that the current buffer is in Org-mode.
8531 This will temporarily bind local variables that are typically bound in
8532 Org-mode to the values they have in Org-mode, and then interactively
8533 call CMD."
8534 (org-load-modules-maybe)
8535 (unless org-local-vars
8536 (setq org-local-vars (org-get-local-variables)))
8537 (eval (list 'let org-local-vars
8538 (list 'call-interactively (list 'quote cmd)))))
8540 ;;;; Archiving
8542 (defun org-get-category (&optional pos force-refresh)
8543 "Get the category applying to position POS."
8544 (save-match-data
8545 (if force-refresh (org-refresh-category-properties))
8546 (let ((pos (or pos (point))))
8547 (or (get-text-property pos 'org-category)
8548 (progn (org-refresh-category-properties)
8549 (get-text-property pos 'org-category))))))
8551 (defun org-refresh-category-properties ()
8552 "Refresh category text properties in the buffer."
8553 (let ((def-cat (cond
8554 ((null org-category)
8555 (if buffer-file-name
8556 (file-name-sans-extension
8557 (file-name-nondirectory buffer-file-name))
8558 "???"))
8559 ((symbolp org-category) (symbol-name org-category))
8560 (t org-category)))
8561 beg end cat pos optionp)
8562 (org-unmodified
8563 (save-excursion
8564 (save-restriction
8565 (widen)
8566 (goto-char (point-min))
8567 (put-text-property (point) (point-max) 'org-category def-cat)
8568 (while (re-search-forward
8569 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8570 (setq pos (match-end 0)
8571 optionp (equal (char-after (match-beginning 0)) ?#)
8572 cat (org-trim (match-string 2)))
8573 (if optionp
8574 (setq beg (point-at-bol) end (point-max))
8575 (org-back-to-heading t)
8576 (setq beg (point) end (org-end-of-subtree t t)))
8577 (put-text-property beg end 'org-category cat)
8578 (put-text-property beg end 'org-category-position beg)
8579 (goto-char pos)))))))
8582 ;;;; Link Stuff
8584 ;;; Link abbreviations
8586 (defun org-link-expand-abbrev (link)
8587 "Apply replacements as defined in `org-link-abbrev-alist."
8588 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8589 (let* ((key (match-string 1 link))
8590 (as (or (assoc key org-link-abbrev-alist-local)
8591 (assoc key org-link-abbrev-alist)))
8592 (tag (and (match-end 2) (match-string 3 link)))
8593 rpl)
8594 (if (not as)
8595 link
8596 (setq rpl (cdr as))
8597 (cond
8598 ((symbolp rpl) (funcall rpl tag))
8599 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8600 ((string-match "%h" rpl)
8601 (replace-match (url-hexify-string (or tag "")) t t rpl))
8602 (t (concat rpl tag)))))
8603 link))
8605 ;;; Storing and inserting links
8607 (defvar org-insert-link-history nil
8608 "Minibuffer history for links inserted with `org-insert-link'.")
8610 (defvar org-stored-links nil
8611 "Contains the links stored with `org-store-link'.")
8613 (defvar org-store-link-plist nil
8614 "Plist with info about the most recently link created with `org-store-link'.")
8616 (defvar org-link-protocols nil
8617 "Link protocols added to Org-mode using `org-add-link-type'.")
8619 (defvar org-store-link-functions nil
8620 "List of functions that are called to create and store a link.
8621 Each function will be called in turn until one returns a non-nil
8622 value. Each function should check if it is responsible for creating
8623 this link (for example by looking at the major mode).
8624 If not, it must exit and return nil.
8625 If yes, it should return a non-nil value after a calling
8626 `org-store-link-props' with a list of properties and values.
8627 Special properties are:
8629 :type The link prefix, like \"http\". This must be given.
8630 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8631 This is obligatory as well.
8632 :description Optional default description for the second pair
8633 of brackets in an Org-mode link. The user can still change
8634 this when inserting this link into an Org-mode buffer.
8636 In addition to these, any additional properties can be specified
8637 and then used in remember templates.")
8639 (defun org-add-link-type (type &optional follow export)
8640 "Add TYPE to the list of `org-link-types'.
8641 Re-compute all regular expressions depending on `org-link-types'
8643 FOLLOW and EXPORT are two functions.
8645 FOLLOW should take the link path as the single argument and do whatever
8646 is necessary to follow the link, for example find a file or display
8647 a mail message.
8649 EXPORT should format the link path for export to one of the export formats.
8650 It should be a function accepting three arguments:
8652 path the path of the link, the text after the prefix (like \"http:\")
8653 desc the description of the link, if any, or a description added by
8654 org-export-normalize-links if there is none
8655 format the export format, a symbol like `html' or `latex' or `ascii'..
8657 The function may use the FORMAT information to return different values
8658 depending on the format. The return value will be put literally into
8659 the exported file. If the return value is nil, this means Org should
8660 do what it normally does with links which do not have EXPORT defined.
8662 Org-mode has a built-in default for exporting links. If you are happy with
8663 this default, there is no need to define an export function for the link
8664 type. For a simple example of an export function, see `org-bbdb.el'."
8665 (add-to-list 'org-link-types type t)
8666 (org-make-link-regexps)
8667 (if (assoc type org-link-protocols)
8668 (setcdr (assoc type org-link-protocols) (list follow export))
8669 (push (list type follow export) org-link-protocols)))
8671 (defvar org-agenda-buffer-name)
8673 ;;;###autoload
8674 (defun org-store-link (arg)
8675 "\\<org-mode-map>Store an org-link to the current location.
8676 This link is added to `org-stored-links' and can later be inserted
8677 into an org-buffer with \\[org-insert-link].
8679 For some link types, a prefix arg is interpreted:
8680 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8681 For file links, arg negates `org-context-in-file-links'."
8682 (interactive "P")
8683 (org-load-modules-maybe)
8684 (setq org-store-link-plist nil) ; reset
8685 (org-with-limited-levels
8686 (let (link cpltxt desc description search txt custom-id agenda-link)
8687 (cond
8689 ((run-hook-with-args-until-success 'org-store-link-functions)
8690 (setq link (plist-get org-store-link-plist :link)
8691 desc (or (plist-get org-store-link-plist :description) link)))
8693 ((org-src-edit-buffer-p)
8694 (let (label gc)
8695 (while (or (not label)
8696 (save-excursion
8697 (save-restriction
8698 (widen)
8699 (goto-char (point-min))
8700 (re-search-forward
8701 (regexp-quote (format org-coderef-label-format label))
8702 nil t))))
8703 (when label (message "Label exists already") (sit-for 2))
8704 (setq label (read-string "Code line label: " label)))
8705 (end-of-line 1)
8706 (setq link (format org-coderef-label-format label))
8707 (setq gc (- 79 (length link)))
8708 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8709 (insert link)
8710 (setq link (concat "(" label ")") desc nil)))
8712 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8713 ;; We are in the agenda, link to referenced location
8714 (let ((m (or (get-text-property (point) 'org-hd-marker)
8715 (get-text-property (point) 'org-marker))))
8716 (when m
8717 (org-with-point-at m
8718 (setq agenda-link
8719 (if (org-called-interactively-p 'any)
8720 (call-interactively 'org-store-link)
8721 (org-store-link nil)))))))
8723 ((eq major-mode 'calendar-mode)
8724 (let ((cd (calendar-cursor-to-date)))
8725 (setq link
8726 (format-time-string
8727 (car org-time-stamp-formats)
8728 (apply 'encode-time
8729 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8730 nil nil nil))))
8731 (org-store-link-props :type "calendar" :date cd)))
8733 ((eq major-mode 'w3-mode)
8734 (setq cpltxt (if (and (buffer-name)
8735 (not (string-match "Untitled" (buffer-name))))
8736 (buffer-name)
8737 (url-view-url t))
8738 link (org-make-link (url-view-url t)))
8739 (org-store-link-props :type "w3" :url (url-view-url t)))
8741 ((eq major-mode 'w3m-mode)
8742 (setq cpltxt (or w3m-current-title w3m-current-url)
8743 link (org-make-link w3m-current-url))
8744 (org-store-link-props :type "w3m" :url (url-view-url t)))
8746 ((setq search (run-hook-with-args-until-success
8747 'org-create-file-search-functions))
8748 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8749 "::" search))
8750 (setq cpltxt (or description link)))
8752 ((eq major-mode 'image-mode)
8753 (setq cpltxt (concat "file:"
8754 (abbreviate-file-name buffer-file-name))
8755 link (org-make-link cpltxt))
8756 (org-store-link-props :type "image" :file buffer-file-name))
8758 ((eq major-mode 'dired-mode)
8759 ;; link to the file in the current line
8760 (let ((file (dired-get-filename nil t)))
8761 (setq file (if file
8762 (abbreviate-file-name
8763 (expand-file-name (dired-get-filename nil t)))
8764 ;; otherwise, no file so use current directory.
8765 default-directory))
8766 (setq cpltxt (concat "file:" file)
8767 link (org-make-link cpltxt))))
8769 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8770 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8771 (cond
8772 ((org-in-regexp "<<\\(.*?\\)>>")
8773 (setq cpltxt
8774 (concat "file:"
8775 (abbreviate-file-name
8776 (buffer-file-name (buffer-base-buffer)))
8777 "::" (match-string 1))
8778 link (org-make-link cpltxt)))
8779 ((and (featurep 'org-id)
8780 (or (eq org-link-to-org-use-id t)
8781 (and (eq org-link-to-org-use-id 'create-if-interactive)
8782 (org-called-interactively-p 'any))
8783 (and (eq org-link-to-org-use-id
8784 'create-if-interactive-and-no-custom-id)
8785 (org-called-interactively-p 'any)
8786 (not custom-id))
8787 (and org-link-to-org-use-id
8788 (org-entry-get nil "ID"))))
8789 ;; We can make a link using the ID.
8790 (setq link (condition-case nil
8791 (prog1 (org-id-store-link)
8792 (setq desc (plist-get org-store-link-plist
8793 :description)))
8794 (error
8795 ;; probably before first headline, link to file only
8796 (concat "file:"
8797 (abbreviate-file-name
8798 (buffer-file-name (buffer-base-buffer))))))))
8800 ;; Just link to current headline
8801 (setq cpltxt (concat "file:"
8802 (abbreviate-file-name
8803 (buffer-file-name (buffer-base-buffer)))))
8804 ;; Add a context search string
8805 (when (org-xor org-context-in-file-links arg)
8806 (setq txt (cond
8807 ((org-at-heading-p) nil)
8808 ((org-region-active-p)
8809 (buffer-substring (region-beginning) (region-end)))
8810 (t nil)))
8811 (when (or (null txt) (string-match "\\S-" txt))
8812 (setq cpltxt
8813 (concat cpltxt "::"
8814 (condition-case nil
8815 (org-make-org-heading-search-string txt)
8816 (error "")))
8817 desc (or (nth 4 (ignore-errors
8818 (org-heading-components))) "NONE"))))
8819 (if (string-match "::\\'" cpltxt)
8820 (setq cpltxt (substring cpltxt 0 -2)))
8821 (setq link (org-make-link cpltxt)))))
8823 ((buffer-file-name (buffer-base-buffer))
8824 ;; Just link to this file here.
8825 (setq cpltxt (concat "file:"
8826 (abbreviate-file-name
8827 (buffer-file-name (buffer-base-buffer)))))
8828 ;; Add a context string
8829 (when (org-xor org-context-in-file-links arg)
8830 (setq txt (if (org-region-active-p)
8831 (buffer-substring (region-beginning) (region-end))
8832 (buffer-substring (point-at-bol) (point-at-eol))))
8833 ;; Only use search option if there is some text.
8834 (when (string-match "\\S-" txt)
8835 (setq cpltxt
8836 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8837 desc "NONE")))
8838 (setq link (org-make-link cpltxt)))
8840 ((org-called-interactively-p 'interactive)
8841 (error "Cannot link to a buffer which is not visiting a file"))
8843 (t (setq link nil)))
8845 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8846 (setq link (or link cpltxt)
8847 desc (or desc cpltxt))
8848 (if (equal desc "NONE") (setq desc nil))
8850 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8851 (progn
8852 (setq org-stored-links
8853 (cons (list link desc) org-stored-links))
8854 (message "Stored: %s" (or desc link))
8855 (when custom-id
8856 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8857 "::#" custom-id))
8858 (setq org-stored-links
8859 (cons (list link desc) org-stored-links))))
8860 (or agenda-link (and link (org-make-link-string link desc)))))))
8862 (defun org-store-link-props (&rest plist)
8863 "Store link properties, extract names and addresses."
8864 (let (x adr)
8865 (when (setq x (plist-get plist :from))
8866 (setq adr (mail-extract-address-components x))
8867 (setq plist (plist-put plist :fromname (car adr)))
8868 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8869 (when (setq x (plist-get plist :to))
8870 (setq adr (mail-extract-address-components x))
8871 (setq plist (plist-put plist :toname (car adr)))
8872 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8873 (let ((from (plist-get plist :from))
8874 (to (plist-get plist :to)))
8875 (when (and from to org-from-is-user-regexp)
8876 (setq plist
8877 (plist-put plist :fromto
8878 (if (string-match org-from-is-user-regexp from)
8879 (concat "to %t")
8880 (concat "from %f"))))))
8881 (setq org-store-link-plist plist))
8883 (defun org-add-link-props (&rest plist)
8884 "Add these properties to the link property list."
8885 (let (key value)
8886 (while plist
8887 (setq key (pop plist) value (pop plist))
8888 (setq org-store-link-plist
8889 (plist-put org-store-link-plist key value)))))
8891 (defun org-email-link-description (&optional fmt)
8892 "Return the description part of an email link.
8893 This takes information from `org-store-link-plist' and formats it
8894 according to FMT (default from `org-email-link-description-format')."
8895 (setq fmt (or fmt org-email-link-description-format))
8896 (let* ((p org-store-link-plist)
8897 (to (plist-get p :toaddress))
8898 (from (plist-get p :fromaddress))
8899 (table
8900 (list
8901 (cons "%c" (plist-get p :fromto))
8902 (cons "%F" (plist-get p :from))
8903 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8904 (cons "%T" (plist-get p :to))
8905 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8906 (cons "%s" (plist-get p :subject))
8907 (cons "%d" (plist-get p :date))
8908 (cons "%m" (plist-get p :message-id)))))
8909 (when (string-match "%c" fmt)
8910 ;; Check if the user wrote this message
8911 (if (and org-from-is-user-regexp from to
8912 (save-match-data (string-match org-from-is-user-regexp from)))
8913 (setq fmt (replace-match "to %t" t t fmt))
8914 (setq fmt (replace-match "from %f" t t fmt))))
8915 (org-replace-escapes fmt table)))
8917 (defun org-make-org-heading-search-string (&optional string heading)
8918 "Make search string for STRING or current headline."
8919 (interactive)
8920 (let ((s (or string (org-get-heading)))
8921 (lines org-context-in-file-links))
8922 (unless (and string (not heading))
8923 ;; We are using a headline, clean up garbage in there.
8924 (if (string-match org-todo-regexp s)
8925 (setq s (replace-match "" t t s)))
8926 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8927 (setq s (replace-match "" t t s)))
8928 (setq s (org-trim s))
8929 (if (string-match (concat "^\\(" org-quote-string "\\|"
8930 org-comment-string "\\)") s)
8931 (setq s (replace-match "" t t s)))
8932 (while (string-match org-ts-regexp s)
8933 (setq s (replace-match "" t t s))))
8934 (or string (setq s (concat "*" s))) ; Add * for headlines
8935 (when (and string (integerp lines) (> lines 0))
8936 (let ((slines (org-split-string s "\n")))
8937 (when (< lines (length slines))
8938 (setq s (mapconcat
8939 'identity
8940 (reverse (nthcdr (- (length slines) lines)
8941 (reverse slines))) "\n")))))
8942 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8944 (defun org-make-link (&rest strings)
8945 "Concatenate STRINGS."
8946 (apply 'concat strings))
8948 (defun org-make-link-string (link &optional description)
8949 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8950 (unless (string-match "\\S-" link)
8951 (error "Empty link"))
8952 (when (and description
8953 (stringp description)
8954 (not (string-match "\\S-" description)))
8955 (setq description nil))
8956 (when (stringp description)
8957 ;; Remove brackets from the description, they are fatal.
8958 (while (string-match "\\[" description)
8959 (setq description (replace-match "{" t t description)))
8960 (while (string-match "\\]" description)
8961 (setq description (replace-match "}" t t description))))
8962 (when (equal link description)
8963 ;; No description needed, it is identical
8964 (setq description nil))
8965 (when (and (not description)
8966 (not (string-match (org-image-file-name-regexp) link))
8967 (not (equal link (org-link-escape link))))
8968 (setq description (org-extract-attributes link)))
8969 (setq link
8970 (cond ((string-match (org-image-file-name-regexp) link) link)
8971 ((string-match org-link-types-re link)
8972 (concat (match-string 1 link)
8973 (org-link-escape (substring link (match-end 1)))))
8974 (t (org-link-escape link))))
8975 (concat "[[" link "]"
8976 (if description (concat "[" description "]") "")
8977 "]"))
8979 (defconst org-link-escape-chars
8980 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8981 "List of characters that should be escaped in link.
8982 This is the list that is used for internal purposes.")
8984 (defvar org-url-encoding-use-url-hexify nil)
8986 (defconst org-link-escape-chars-browser
8987 '(?\ )
8988 "List of escapes for characters that are problematic in links.
8989 This is the list that is used before handing over to the browser.")
8991 (defun org-link-escape (text &optional table merge)
8992 "Return percent escaped representation of TEXT.
8993 TEXT is a string with the text to escape.
8994 Optional argument TABLE is a list with characters that should be
8995 escaped. When nil, `org-link-escape-chars' is used.
8996 If optional argument MERGE is set, merge TABLE into
8997 `org-link-escape-chars'."
8998 (if (and org-url-encoding-use-url-hexify (not table))
8999 (url-hexify-string text)
9000 (cond
9001 ((and table merge)
9002 (mapc (lambda (defchr)
9003 (unless (member defchr table)
9004 (setq table (cons defchr table)))) org-link-escape-chars))
9005 ((null table)
9006 (setq table org-link-escape-chars)))
9007 (mapconcat
9008 (lambda (char)
9009 (if (or (member char table)
9010 (< char 32) (= char 37) (> char 126))
9011 (mapconcat (lambda (sequence-element)
9012 (format "%%%.2X" sequence-element))
9013 (or (encode-coding-char char 'utf-8)
9014 (error "Unable to percent escape character: %s"
9015 (char-to-string char))) "")
9016 (char-to-string char))) text "")))
9018 (defun org-link-unescape (str)
9019 "Unhex hexified Unicode strings as returned from the JavaScript function
9020 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9021 (unless (and (null str) (string= "" str))
9022 (let ((pos 0) (case-fold-search t) unhexed)
9023 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9024 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9025 (setq str (replace-match unhexed t t str))
9026 (setq pos (+ pos (length unhexed))))))
9027 str)
9029 (defun org-link-unescape-compound (hex)
9030 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9031 Note: this function also decodes single byte encodings like
9032 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9033 (save-match-data
9034 (let* ((bytes (cdr (split-string hex "%")))
9035 (ret "")
9036 (eat 0)
9037 (sum 0))
9038 (while bytes
9039 (let* ((val (string-to-number (pop bytes) 16))
9040 (shift-xor
9041 (if (= 0 eat)
9042 (cond
9043 ((>= val 252) (cons 6 252))
9044 ((>= val 248) (cons 5 248))
9045 ((>= val 240) (cons 4 240))
9046 ((>= val 224) (cons 3 224))
9047 ((>= val 192) (cons 2 192))
9048 (t (cons 0 0)))
9049 (cons 6 128))))
9050 (if (>= val 192) (setq eat (car shift-xor)))
9051 (setq val (logxor val (cdr shift-xor)))
9052 (setq sum (+ (lsh sum (car shift-xor)) val))
9053 (if (> eat 0) (setq eat (- eat 1)))
9054 (cond
9055 ((= 0 eat) ;multi byte
9056 (setq ret (concat ret (org-char-to-string sum)))
9057 (setq sum 0))
9058 ((not bytes) ; single byte(s)
9059 (setq ret (org-link-unescape-single-byte-sequence hex))))
9060 )) ;; end (while bytes
9061 ret )))
9063 (defun org-link-unescape-single-byte-sequence (hex)
9064 "Unhexify hex-encoded single byte character sequences."
9065 (mapconcat (lambda (byte)
9066 (char-to-string (string-to-number byte 16)))
9067 (cdr (split-string hex "%")) ""))
9069 (defun org-xor (a b)
9070 "Exclusive or."
9071 (if a (not b) b))
9073 (defun org-fixup-message-id-for-http (s)
9074 "Replace special characters in a message id, so it can be used in an http query."
9075 (when (string-match "%" s)
9076 (setq s (mapconcat (lambda (c)
9077 (if (eq c ?%)
9078 "%25"
9079 (char-to-string c)))
9080 s "")))
9081 (while (string-match "<" s)
9082 (setq s (replace-match "%3C" t t s)))
9083 (while (string-match ">" s)
9084 (setq s (replace-match "%3E" t t s)))
9085 (while (string-match "@" s)
9086 (setq s (replace-match "%40" t t s)))
9089 ;;;###autoload
9090 (defun org-insert-link-global ()
9091 "Insert a link like Org-mode does.
9092 This command can be called in any mode to insert a link in Org-mode syntax."
9093 (interactive)
9094 (org-load-modules-maybe)
9095 (org-run-like-in-org-mode 'org-insert-link))
9097 (defun org-insert-link (&optional complete-file link-location default-description)
9098 "Insert a link. At the prompt, enter the link.
9100 Completion can be used to insert any of the link protocol prefixes like
9101 http or ftp in use.
9103 The history can be used to select a link previously stored with
9104 `org-store-link'. When the empty string is entered (i.e. if you just
9105 press RET at the prompt), the link defaults to the most recently
9106 stored link. As SPC triggers completion in the minibuffer, you need to
9107 use M-SPC or C-q SPC to force the insertion of a space character.
9109 You will also be prompted for a description, and if one is given, it will
9110 be displayed in the buffer instead of the link.
9112 If there is already a link at point, this command will allow you to edit link
9113 and description parts.
9115 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9116 be selected using completion. The path to the file will be relative to the
9117 current directory if the file is in the current directory or a subdirectory.
9118 Otherwise, the link will be the absolute path as completed in the minibuffer
9119 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9120 option `org-link-file-path-type'.
9122 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9123 the current directory or below.
9125 With three \\[universal-argument] prefixes, negate the meaning of
9126 `org-keep-stored-link-after-insertion'.
9128 If `org-make-link-description-function' is non-nil, this function will be
9129 called with the link target, and the result will be the default
9130 link description.
9132 If the LINK-LOCATION parameter is non-nil, this value will be
9133 used as the link location instead of reading one interactively.
9135 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9136 be used as the default description."
9137 (interactive "P")
9138 (let* ((wcf (current-window-configuration))
9139 (region (if (org-region-active-p)
9140 (buffer-substring (region-beginning) (region-end))))
9141 (remove (and region (list (region-beginning) (region-end))))
9142 (desc region)
9143 tmphist ; byte-compile incorrectly complains about this
9144 (link link-location)
9145 entry file all-prefixes)
9146 (cond
9147 (link-location) ; specified by arg, just use it.
9148 ((org-in-regexp org-bracket-link-regexp 1)
9149 ;; We do have a link at point, and we are going to edit it.
9150 (setq remove (list (match-beginning 0) (match-end 0)))
9151 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9152 (setq link (read-string "Link: "
9153 (org-link-unescape
9154 (org-match-string-no-properties 1)))))
9155 ((or (org-in-regexp org-angle-link-re)
9156 (org-in-regexp org-plain-link-re))
9157 ;; Convert to bracket link
9158 (setq remove (list (match-beginning 0) (match-end 0))
9159 link (read-string "Link: "
9160 (org-remove-angle-brackets (match-string 0)))))
9161 ((member complete-file '((4) (16)))
9162 ;; Completing read for file names.
9163 (setq link (org-file-complete-link complete-file)))
9165 ;; Read link, with completion for stored links.
9166 (with-output-to-temp-buffer "*Org Links*"
9167 (princ "Insert a link.
9168 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9169 (when org-stored-links
9170 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9171 (princ (mapconcat
9172 (lambda (x)
9173 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9174 (reverse org-stored-links) "\n"))))
9175 (let ((cw (selected-window)))
9176 (select-window (get-buffer-window "*Org Links*" 'visible))
9177 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9178 (unless (pos-visible-in-window-p (point-max))
9179 (org-fit-window-to-buffer))
9180 (and (window-live-p cw) (select-window cw)))
9181 ;; Fake a link history, containing the stored links.
9182 (setq tmphist (append (mapcar 'car org-stored-links)
9183 org-insert-link-history))
9184 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9185 (mapcar 'car org-link-abbrev-alist)
9186 org-link-types))
9187 (unwind-protect
9188 (progn
9189 (setq link
9190 (let ((org-completion-use-ido nil)
9191 (org-completion-use-iswitchb nil))
9192 (org-completing-read
9193 "Link: "
9194 (append
9195 (mapcar (lambda (x) (list (concat x ":")))
9196 all-prefixes)
9197 (mapcar 'car org-stored-links))
9198 nil nil nil
9199 'tmphist
9200 (car (car org-stored-links)))))
9201 (if (not (string-match "\\S-" link))
9202 (error "No link selected"))
9203 (if (or (member link all-prefixes)
9204 (and (equal ":" (substring link -1))
9205 (member (substring link 0 -1) all-prefixes)
9206 (setq link (substring link 0 -1))))
9207 (setq link (org-link-try-special-completion link))))
9208 (set-window-configuration wcf)
9209 (kill-buffer "*Org Links*"))
9210 (setq entry (assoc link org-stored-links))
9211 (or entry (push link org-insert-link-history))
9212 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9213 (not org-keep-stored-link-after-insertion))
9214 (setq org-stored-links (delq (assoc link org-stored-links)
9215 org-stored-links)))
9216 (setq desc (or desc (nth 1 entry)))))
9218 (if (string-match org-plain-link-re link)
9219 ;; URL-like link, normalize the use of angular brackets.
9220 (setq link (org-make-link (org-remove-angle-brackets link))))
9222 ;; Check if we are linking to the current file with a search option
9223 ;; If yes, simplify the link by using only the search option.
9224 (when (and buffer-file-name
9225 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9226 (let* ((path (match-string 1 link))
9227 (case-fold-search nil)
9228 (search (match-string 2 link)))
9229 (save-match-data
9230 (if (equal (file-truename buffer-file-name) (file-truename path))
9231 ;; We are linking to this same file, with a search option
9232 (setq link search)))))
9234 ;; Check if we can/should use a relative path. If yes, simplify the link
9235 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9236 (let* ((type (match-string 1 link))
9237 (path (match-string 2 link))
9238 (origpath path)
9239 (case-fold-search nil))
9240 (cond
9241 ((or (eq org-link-file-path-type 'absolute)
9242 (equal complete-file '(16)))
9243 (setq path (abbreviate-file-name (expand-file-name path))))
9244 ((eq org-link-file-path-type 'noabbrev)
9245 (setq path (expand-file-name path)))
9246 ((eq org-link-file-path-type 'relative)
9247 (setq path (file-relative-name path)))
9249 (save-match-data
9250 (if (string-match (concat "^" (regexp-quote
9251 (expand-file-name
9252 (file-name-as-directory
9253 default-directory))))
9254 (expand-file-name path))
9255 ;; We are linking a file with relative path name.
9256 (setq path (substring (expand-file-name path)
9257 (match-end 0)))
9258 (setq path (abbreviate-file-name (expand-file-name path)))))))
9259 (setq link (concat type path))
9260 (if (equal desc origpath)
9261 (setq desc path))))
9263 (if org-make-link-description-function
9264 (setq desc (funcall org-make-link-description-function link desc))
9265 (if default-description (setq desc default-description)))
9267 (setq desc (read-string "Description: " desc))
9268 (unless (string-match "\\S-" desc) (setq desc nil))
9269 (if remove (apply 'delete-region remove))
9270 (insert (org-make-link-string link desc))))
9272 (defun org-link-try-special-completion (type)
9273 "If there is completion support for link type TYPE, offer it."
9274 (let ((fun (intern (concat "org-" type "-complete-link"))))
9275 (if (functionp fun)
9276 (funcall fun)
9277 (read-string "Link (no completion support): " (concat type ":")))))
9279 (defun org-file-complete-link (&optional arg)
9280 "Create a file link using completion."
9281 (let (file link)
9282 (setq file (read-file-name "File: "))
9283 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9284 (pwd1 (file-name-as-directory (abbreviate-file-name
9285 (expand-file-name ".")))))
9286 (cond
9287 ((equal arg '(16))
9288 (setq link (org-make-link
9289 "file:"
9290 (abbreviate-file-name (expand-file-name file)))))
9291 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9292 (setq link (org-make-link "file:" (match-string 1 file))))
9293 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9294 (expand-file-name file))
9295 (setq link (org-make-link
9296 "file:" (match-string 1 (expand-file-name file)))))
9297 (t (setq link (org-make-link "file:" file)))))
9298 link))
9300 (defun org-completing-read (&rest args)
9301 "Completing-read with SPACE being a normal character."
9302 (let ((enable-recursive-minibuffers t)
9303 (minibuffer-local-completion-map
9304 (copy-keymap minibuffer-local-completion-map)))
9305 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9306 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9307 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9308 (apply 'org-icompleting-read args)))
9310 (defun org-completing-read-no-i (&rest args)
9311 (let (org-completion-use-ido org-completion-use-iswitchb)
9312 (apply 'org-completing-read args)))
9314 (defun org-iswitchb-completing-read (prompt choices &rest args)
9315 "Use iswitch as a completing-read replacement to choose from choices.
9316 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9317 from."
9318 (let* ((iswitchb-use-virtual-buffers nil)
9319 (iswitchb-make-buflist-hook
9320 (lambda ()
9321 (setq iswitchb-temp-buflist choices))))
9322 (iswitchb-read-buffer prompt)))
9324 (defun org-icompleting-read (&rest args)
9325 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9326 (org-without-partial-completion
9327 (if (and org-completion-use-ido
9328 (fboundp 'ido-completing-read)
9329 (boundp 'ido-mode) ido-mode
9330 (listp (second args)))
9331 (let ((ido-enter-matching-directory nil))
9332 (apply 'ido-completing-read (concat (car args))
9333 (if (consp (car (nth 1 args)))
9334 (mapcar 'car (nth 1 args))
9335 (nth 1 args))
9336 (cddr args)))
9337 (if (and org-completion-use-iswitchb
9338 (boundp 'iswitchb-mode) iswitchb-mode
9339 (listp (second args)))
9340 (apply 'org-iswitchb-completing-read (concat (car args))
9341 (if (consp (car (nth 1 args)))
9342 (mapcar 'car (nth 1 args))
9343 (nth 1 args))
9344 (cddr args))
9345 (apply 'completing-read args)))))
9347 (defun org-extract-attributes (s)
9348 "Extract the attributes cookie from a string and set as text property."
9349 (let (a attr (start 0) key value)
9350 (save-match-data
9351 (when (string-match "{{\\([^}]+\\)}}$" s)
9352 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9353 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9354 (setq key (match-string 1 a) value (match-string 2 a)
9355 start (match-end 0)
9356 attr (plist-put attr (intern key) value))))
9357 (org-add-props s nil 'org-attr attr))
9360 (defun org-extract-attributes-from-string (tag)
9361 (let (key value attr)
9362 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9363 (setq key (match-string 1 tag) value (match-string 2 tag)
9364 tag (replace-match "" t t tag)
9365 attr (plist-put attr (intern key) value)))
9366 (cons tag attr)))
9368 (defun org-attributes-to-string (plist)
9369 "Format a property list into an HTML attribute list."
9370 (let ((s "") key value)
9371 (while plist
9372 (setq key (pop plist) value (pop plist))
9373 (and value
9374 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9377 ;;; Opening/following a link
9379 (defvar org-link-search-failed nil)
9381 (defvar org-open-link-functions nil
9382 "Hook for functions finding a plain text link.
9383 These functions must take a single argument, the link content.
9384 They will be called for links that look like [[link text][description]]
9385 when LINK TEXT does not have a protocol like \"http:\" and does not look
9386 like a filename (e.g. \"./blue.png\").
9388 These functions will be called *before* Org attempts to resolve the
9389 link by doing text searches in the current buffer - so if you want a
9390 link \"[[target]]\" to still find \"<<target>>\", your function should
9391 handle this as a special case.
9393 When the function does handle the link, it must return a non-nil value.
9394 If it decides that it is not responsible for this link, it must return
9395 nil to indicate that that Org-mode can continue with other options
9396 like exact and fuzzy text search.")
9398 (defun org-next-link ()
9399 "Move forward to the next link.
9400 If the link is in hidden text, expose it."
9401 (interactive)
9402 (when (and org-link-search-failed (eq this-command last-command))
9403 (goto-char (point-min))
9404 (message "Link search wrapped back to beginning of buffer"))
9405 (setq org-link-search-failed nil)
9406 (let* ((pos (point))
9407 (ct (org-context))
9408 (a (assoc :link ct)))
9409 (if a (goto-char (nth 2 a)))
9410 (if (re-search-forward org-any-link-re nil t)
9411 (progn
9412 (goto-char (match-beginning 0))
9413 (if (outline-invisible-p) (org-show-context)))
9414 (goto-char pos)
9415 (setq org-link-search-failed t)
9416 (error "No further link found"))))
9418 (defun org-previous-link ()
9419 "Move backward to the previous link.
9420 If the link is in hidden text, expose it."
9421 (interactive)
9422 (when (and org-link-search-failed (eq this-command last-command))
9423 (goto-char (point-max))
9424 (message "Link search wrapped back to end of buffer"))
9425 (setq org-link-search-failed nil)
9426 (let* ((pos (point))
9427 (ct (org-context))
9428 (a (assoc :link ct)))
9429 (if a (goto-char (nth 1 a)))
9430 (if (re-search-backward org-any-link-re nil t)
9431 (progn
9432 (goto-char (match-beginning 0))
9433 (if (outline-invisible-p) (org-show-context)))
9434 (goto-char pos)
9435 (setq org-link-search-failed t)
9436 (error "No further link found"))))
9438 (defun org-translate-link (s)
9439 "Translate a link string if a translation function has been defined."
9440 (if (and org-link-translation-function
9441 (fboundp org-link-translation-function)
9442 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9443 (progn
9444 (setq s (funcall org-link-translation-function
9445 (match-string 1) (match-string 2)))
9446 (concat (car s) ":" (cdr s)))
9449 (defun org-translate-link-from-planner (type path)
9450 "Translate a link from Emacs Planner syntax so that Org can follow it.
9451 This is still an experimental function, your mileage may vary."
9452 (cond
9453 ((member type '("http" "https" "news" "ftp"))
9454 ;; standard Internet links are the same.
9455 nil)
9456 ((and (equal type "irc") (string-match "^//" path))
9457 ;; Planner has two / at the beginning of an irc link, we have 1.
9458 ;; We should have zero, actually....
9459 (setq path (substring path 1)))
9460 ((and (equal type "lisp") (string-match "^/" path))
9461 ;; Planner has a slash, we do not.
9462 (setq type "elisp" path (substring path 1)))
9463 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9464 ;; A typical message link. Planner has the id after the final slash,
9465 ;; we separate it with a hash mark
9466 (setq path (concat (match-string 1 path) "#"
9467 (org-remove-angle-brackets (match-string 2 path)))))
9469 (cons type path))
9471 (defun org-find-file-at-mouse (ev)
9472 "Open file link or URL at mouse."
9473 (interactive "e")
9474 (mouse-set-point ev)
9475 (org-open-at-point 'in-emacs))
9477 (defun org-open-at-mouse (ev)
9478 "Open file link or URL at mouse.
9479 See the docstring of `org-open-file' for details."
9480 (interactive "e")
9481 (mouse-set-point ev)
9482 (if (eq major-mode 'org-agenda-mode)
9483 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9484 (org-open-at-point))
9486 (defvar org-window-config-before-follow-link nil
9487 "The window configuration before following a link.
9488 This is saved in case the need arises to restore it.")
9490 (defvar org-open-link-marker (make-marker)
9491 "Marker pointing to the location where `org-open-at-point; was called.")
9493 ;;;###autoload
9494 (defun org-open-at-point-global ()
9495 "Follow a link like Org-mode does.
9496 This command can be called in any mode to follow a link that has
9497 Org-mode syntax."
9498 (interactive)
9499 (org-run-like-in-org-mode 'org-open-at-point))
9501 ;;;###autoload
9502 (defun org-open-link-from-string (s &optional arg reference-buffer)
9503 "Open a link in the string S, as if it was in Org-mode."
9504 (interactive "sLink: \nP")
9505 (let ((reference-buffer (or reference-buffer (current-buffer))))
9506 (with-temp-buffer
9507 (let ((org-inhibit-startup (not reference-buffer)))
9508 (org-mode)
9509 (insert s)
9510 (goto-char (point-min))
9511 (when reference-buffer
9512 (setq org-link-abbrev-alist-local
9513 (with-current-buffer reference-buffer
9514 org-link-abbrev-alist-local)))
9515 (org-open-at-point arg reference-buffer)))))
9517 (defvar org-open-at-point-functions nil
9518 "Hook that is run when following a link at point.
9520 Functions in this hook must return t if they identify and follow
9521 a link at point. If they don't find anything interesting at point,
9522 they must return nil.")
9524 (defun org-open-at-point (&optional arg reference-buffer)
9525 "Open link at or after point.
9526 If there is no link at point, this function will search forward up to
9527 the end of the current line.
9528 Normally, files will be opened by an appropriate application. If the
9529 optional prefix argument ARG is non-nil, Emacs will visit the file.
9530 With a double prefix argument, try to open outside of Emacs, in the
9531 application the system uses for this file type."
9532 (interactive "P")
9533 ;; if in a code block, then open the block's results
9534 (unless (call-interactively #'org-babel-open-src-block-result)
9535 (org-load-modules-maybe)
9536 (move-marker org-open-link-marker (point))
9537 (setq org-window-config-before-follow-link (current-window-configuration))
9538 (org-remove-occur-highlights nil nil t)
9539 (cond
9540 ((and (org-at-heading-p)
9541 (not (org-in-regexp
9542 (concat org-plain-link-re "\\|"
9543 org-bracket-link-regexp "\\|"
9544 org-angle-link-re "\\|"
9545 "[ \t]:[^ \t\n]+:[ \t]*$")))
9546 (not (get-text-property (point) 'org-linked-text)))
9547 (or (org-offer-links-in-entry arg)
9548 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9549 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9550 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9551 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9552 (not (org-in-regexp org-bracket-link-regexp)))
9553 (org-footnote-action))
9555 (let (type path link line search (pos (point)))
9556 (catch 'match
9557 (save-excursion
9558 (skip-chars-forward "^]\n\r")
9559 (when (org-in-regexp org-bracket-link-regexp 1)
9560 (setq link (org-extract-attributes
9561 (org-link-unescape (org-match-string-no-properties 1))))
9562 (while (string-match " *\n *" link)
9563 (setq link (replace-match " " t t link)))
9564 (setq link (org-link-expand-abbrev link))
9565 (cond
9566 ((or (file-name-absolute-p link)
9567 (string-match "^\\.\\.?/" link))
9568 (setq type "file" path link))
9569 ((string-match org-link-re-with-space3 link)
9570 (setq type (match-string 1 link) path (match-string 2 link)))
9571 (t (setq type "thisfile" path link)))
9572 (throw 'match t)))
9574 (when (get-text-property (point) 'org-linked-text)
9575 (setq type "thisfile"
9576 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9577 (1+ (point)) (point))
9578 path (buffer-substring
9579 (or (previous-single-property-change pos 'org-linked-text)
9580 (point-min))
9581 (or (next-single-property-change pos 'org-linked-text)
9582 (point-max))))
9583 (throw 'match t))
9585 (save-excursion
9586 (when (or (org-in-regexp org-angle-link-re)
9587 (org-in-regexp org-plain-link-re))
9588 (setq type (match-string 1)
9589 path (org-link-unescape (match-string 2)))
9590 (throw 'match t)))
9591 (save-excursion
9592 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9593 (setq type "tags"
9594 path (match-string 1))
9595 (while (string-match ":" path)
9596 (setq path (replace-match "+" t t path)))
9597 (throw 'match t)))
9598 (when (org-in-regexp "<\\([^><\n]+\\)>")
9599 (setq type "tree-match"
9600 path (match-string 1))
9601 (throw 'match t)))
9602 (unless path
9603 (error "No link found"))
9605 ;; switch back to reference buffer
9606 ;; needed when if called in a temporary buffer through
9607 ;; org-open-link-from-string
9608 (with-current-buffer (or reference-buffer (current-buffer))
9610 ;; Remove any trailing spaces in path
9611 (if (string-match " +\\'" path)
9612 (setq path (replace-match "" t t path)))
9613 (if (and org-link-translation-function
9614 (fboundp org-link-translation-function))
9615 ;; Check if we need to translate the link
9616 (let ((tmp (funcall org-link-translation-function type path)))
9617 (setq type (car tmp) path (cdr tmp))))
9619 (cond
9621 ((assoc type org-link-protocols)
9622 (funcall (nth 1 (assoc type org-link-protocols)) path))
9624 ((equal type "mailto")
9625 (let ((cmd (car org-link-mailto-program))
9626 (args (cdr org-link-mailto-program)) args1
9627 (address path) (subject "") a)
9628 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9629 (setq address (match-string 1 path)
9630 subject (org-link-escape (match-string 2 path))))
9631 (while args
9632 (cond
9633 ((not (stringp (car args))) (push (pop args) args1))
9634 (t (setq a (pop args))
9635 (if (string-match "%a" a)
9636 (setq a (replace-match address t t a)))
9637 (if (string-match "%s" a)
9638 (setq a (replace-match subject t t a)))
9639 (push a args1))))
9640 (apply cmd (nreverse args1))))
9642 ((member type '("http" "https" "ftp" "news"))
9643 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9644 (org-link-escape
9645 path org-link-escape-chars-browser)
9646 path))))
9648 ((string= type "doi")
9649 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9650 (org-link-escape
9651 path org-link-escape-chars-browser)
9652 path))))
9654 ((member type '("message"))
9655 (browse-url (concat type ":" path)))
9657 ((string= type "tags")
9658 (org-tags-view arg path))
9660 ((string= type "tree-match")
9661 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9663 ((string= type "file")
9664 (if (string-match "::\\([0-9]+\\)\\'" path)
9665 (setq line (string-to-number (match-string 1 path))
9666 path (substring path 0 (match-beginning 0)))
9667 (if (string-match "::\\(.+\\)\\'" path)
9668 (setq search (match-string 1 path)
9669 path (substring path 0 (match-beginning 0)))))
9670 (if (string-match "[*?{]" (file-name-nondirectory path))
9671 (dired path)
9672 (org-open-file path arg line search)))
9674 ((string= type "shell")
9675 (let ((cmd path))
9676 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9677 (string-match org-confirm-shell-link-not-regexp cmd))
9678 (not org-confirm-shell-link-function)
9679 (funcall org-confirm-shell-link-function
9680 (format "Execute \"%s\" in shell? "
9681 (org-add-props cmd nil
9682 'face 'org-warning))))
9683 (progn
9684 (message "Executing %s" cmd)
9685 (shell-command cmd))
9686 (error "Abort"))))
9688 ((string= type "elisp")
9689 (let ((cmd path))
9690 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9691 (string-match org-confirm-elisp-link-not-regexp cmd))
9692 (not org-confirm-elisp-link-function)
9693 (funcall org-confirm-elisp-link-function
9694 (format "Execute \"%s\" as elisp? "
9695 (org-add-props cmd nil
9696 'face 'org-warning))))
9697 (message "%s => %s" cmd
9698 (if (equal (string-to-char cmd) ?\()
9699 (eval (read cmd))
9700 (call-interactively (read cmd))))
9701 (error "Abort"))))
9703 ((and (string= type "thisfile")
9704 (run-hook-with-args-until-success
9705 'org-open-link-functions path)))
9707 ((string= type "thisfile")
9708 (if arg
9709 (switch-to-buffer-other-window
9710 (org-get-buffer-for-internal-link (current-buffer)))
9711 (org-mark-ring-push))
9712 (let ((cmd `(org-link-search
9713 ,path
9714 ,(cond ((equal arg '(4)) ''occur)
9715 ((equal arg '(16)) ''org-occur)
9716 (t nil))
9717 ,pos)))
9718 (condition-case nil (let ((org-link-search-inhibit-query t))
9719 (eval cmd))
9720 (error (progn (widen) (eval cmd))))))
9723 (browse-url-at-point)))))))
9724 (move-marker org-open-link-marker nil)
9725 (run-hook-with-args 'org-follow-link-hook)))
9727 (defun org-offer-links-in-entry (&optional nth zero)
9728 "Offer links in the current entry and follow the selected link.
9729 If there is only one link, follow it immediately as well.
9730 If NTH is an integer, immediately pick the NTH link found.
9731 If ZERO is a string, check also this string for a link, and if
9732 there is one, offer it as link number zero."
9733 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9734 "\\(" org-angle-link-re "\\)\\|"
9735 "\\(" org-plain-link-re "\\)"))
9736 (cnt ?0)
9737 (in-emacs (if (integerp nth) nil nth))
9738 have-zero end links link c)
9739 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9740 (push (match-string 0 zero) links)
9741 (setq cnt (1- cnt) have-zero t))
9742 (save-excursion
9743 (org-back-to-heading t)
9744 (setq end (save-excursion (outline-next-heading) (point)))
9745 (while (re-search-forward re end t)
9746 (push (match-string 0) links))
9747 (setq links (org-uniquify (reverse links))))
9749 (cond
9750 ((null links)
9751 (message "No links"))
9752 ((equal (length links) 1)
9753 (setq link (list (car links))))
9754 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9755 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9756 (t ; we have to select a link
9757 (save-excursion
9758 (save-window-excursion
9759 (delete-other-windows)
9760 (with-output-to-temp-buffer "*Select Link*"
9761 (mapc (lambda (l)
9762 (if (not (string-match org-bracket-link-regexp l))
9763 (princ (format "[%c] %s\n" (incf cnt)
9764 (org-remove-angle-brackets l)))
9765 (if (match-end 3)
9766 (princ (format "[%c] %s (%s)\n" (incf cnt)
9767 (match-string 3 l) (match-string 1 l)))
9768 (princ (format "[%c] %s\n" (incf cnt)
9769 (match-string 1 l))))))
9770 links))
9771 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9772 (message "Select link to open, RET to open all:")
9773 (setq c (read-char-exclusive))
9774 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9775 (when (equal c ?q) (error "Abort"))
9776 (if (equal c ?\C-m)
9777 (setq link links)
9778 (setq nth (- c ?0))
9779 (if have-zero (setq nth (1+ nth)))
9780 (unless (and (integerp nth) (>= (length links) nth))
9781 (error "Invalid link selection"))
9782 (setq link (list (nth (1- nth) links))))))
9783 (if link
9784 (let ((buf (current-buffer)))
9785 (dolist (l link)
9786 (org-open-link-from-string l in-emacs buf))
9788 nil)))
9790 ;; Add special file links that specify the way of opening
9792 (org-add-link-type "file+sys" 'org-open-file-with-system)
9793 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9794 (defun org-open-file-with-system (path)
9795 "Open file at PATH using the system way of opening it."
9796 (org-open-file path 'system))
9797 (defun org-open-file-with-emacs (path)
9798 "Open file at PATH in Emacs."
9799 (org-open-file path 'emacs))
9800 (defun org-remove-file-link-modifiers ()
9801 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9802 (goto-char (point-min))
9803 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9804 (org-if-unprotected
9805 (replace-match "file:" t t))))
9806 (eval-after-load "org-exp"
9807 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9808 'org-remove-file-link-modifiers))
9810 ;;;; Time estimates
9812 (defun org-get-effort (&optional pom)
9813 "Get the effort estimate for the current entry."
9814 (org-entry-get pom org-effort-property))
9816 ;;; File search
9818 (defvar org-create-file-search-functions nil
9819 "List of functions to construct the right search string for a file link.
9820 These functions are called in turn with point at the location to
9821 which the link should point.
9823 A function in the hook should first test if it would like to
9824 handle this file type, for example by checking the `major-mode'
9825 or the file extension. If it decides not to handle this file, it
9826 should just return nil to give other functions a chance. If it
9827 does handle the file, it must return the search string to be used
9828 when following the link. The search string will be part of the
9829 file link, given after a double colon, and `org-open-at-point'
9830 will automatically search for it. If special measures must be
9831 taken to make the search successful, another function should be
9832 added to the companion hook `org-execute-file-search-functions',
9833 which see.
9835 A function in this hook may also use `setq' to set the variable
9836 `description' to provide a suggestion for the descriptive text to
9837 be used for this link when it gets inserted into an Org-mode
9838 buffer with \\[org-insert-link].")
9840 (defvar org-execute-file-search-functions nil
9841 "List of functions to execute a file search triggered by a link.
9843 Functions added to this hook must accept a single argument, the
9844 search string that was part of the file link, the part after the
9845 double colon. The function must first check if it would like to
9846 handle this search, for example by checking the `major-mode' or
9847 the file extension. If it decides not to handle this search, it
9848 should just return nil to give other functions a chance. If it
9849 does handle the search, it must return a non-nil value to keep
9850 other functions from trying.
9852 Each function can access the current prefix argument through the
9853 variable `current-prefix-argument'. Note that a single prefix is
9854 used to force opening a link in Emacs, so it may be good to only
9855 use a numeric or double prefix to guide the search function.
9857 In case this is needed, a function in this hook can also restore
9858 the window configuration before `org-open-at-point' was called using:
9860 (set-window-configuration org-window-config-before-follow-link)")
9862 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9863 (defun org-link-search (s &optional type avoid-pos stealth)
9864 "Search for a link search option.
9865 If S is surrounded by forward slashes, it is interpreted as a
9866 regular expression. In org-mode files, this will create an `org-occur'
9867 sparse tree. In ordinary files, `occur' will be used to list matches.
9868 If the current buffer is in `dired-mode', grep will be used to search
9869 in all files. If AVOID-POS is given, ignore matches near that position.
9871 When optional argument STEALTH is non-nil, do not modify
9872 visibility around point, thus ignoring
9873 `org-show-hierarchy-above', `org-show-following-heading' and
9874 `org-show-siblings' variables."
9875 (let ((case-fold-search t)
9876 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9877 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9878 (append '(("") (" ") ("\t") ("\n"))
9879 org-emphasis-alist)
9880 "\\|") "\\)"))
9881 (pos (point))
9882 (pre nil) (post nil)
9883 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9884 (cond
9885 ;; First check if there are any special search functions
9886 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9887 ;; Now try the builtin stuff
9888 ((and (equal (string-to-char s0) ?#)
9889 (> (length s0) 1)
9890 (save-excursion
9891 (goto-char (point-min))
9892 (and
9893 (re-search-forward
9894 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9895 (setq type 'dedicated
9896 pos (match-beginning 0))))
9897 ;; There is an exact target for this
9898 (goto-char pos)
9899 (org-back-to-heading t)))
9900 ((save-excursion
9901 (goto-char (point-min))
9902 (and
9903 (re-search-forward
9904 (concat "<<" (regexp-quote s0) ">>") nil t)
9905 (setq type 'dedicated
9906 pos (match-beginning 0))))
9907 ;; There is an exact target for this
9908 (goto-char pos))
9909 ((save-excursion
9910 (goto-char (point-min))
9911 (and
9912 (re-search-forward
9913 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9914 (setq type 'dedicated pos (match-beginning 0))))
9915 ;; Found an invisible target.
9916 (goto-char pos))
9917 ((save-excursion
9918 (goto-char (point-min))
9919 (and
9920 (re-search-forward
9921 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9922 (setq type 'dedicated pos (match-beginning 0))))
9923 ;; Found an element with a matching #+name affiliated keyword.
9924 (goto-char pos))
9925 ((and (string-match "^(\\(.*\\))$" s0)
9926 (save-excursion
9927 (goto-char (point-min))
9928 (and
9929 (re-search-forward
9930 (concat "[^[]" (regexp-quote
9931 (format org-coderef-label-format
9932 (match-string 1 s0))))
9933 nil t)
9934 (setq type 'dedicated
9935 pos (1+ (match-beginning 0))))))
9936 ;; There is a coderef target for this
9937 (goto-char pos))
9938 ((string-match "^/\\(.*\\)/$" s)
9939 ;; A regular expression
9940 (cond
9941 ((eq major-mode 'org-mode)
9942 (org-occur (match-string 1 s)))
9943 ;;((eq major-mode 'dired-mode)
9944 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9945 (t (org-do-occur (match-string 1 s)))))
9946 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9947 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9948 (goto-char (point-min))
9949 (cond
9950 ((let (case-fold-search)
9951 (re-search-forward (format org-complex-heading-regexp-format
9952 (regexp-quote s))
9953 nil t))
9954 ;; OK, found a match
9955 (setq type 'dedicated)
9956 (goto-char (match-beginning 0)))
9957 ((and (not org-link-search-inhibit-query)
9958 (eq org-link-search-must-match-exact-headline 'query-to-create)
9959 (y-or-n-p "No match - create this as a new heading? "))
9960 (goto-char (point-max))
9961 (or (bolp) (newline))
9962 (insert "* " s "\n")
9963 (beginning-of-line 0))
9965 (goto-char pos)
9966 (error "No match"))))
9968 ;; A normal search string
9969 (when (equal (string-to-char s) ?*)
9970 ;; Anchor on headlines, post may include tags.
9971 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9972 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9973 s (substring s 1)))
9974 (remove-text-properties
9975 0 (length s)
9976 '(face nil mouse-face nil keymap nil fontified nil) s)
9977 ;; Make a series of regular expressions to find a match
9978 (setq words (org-split-string s "[ \n\r\t]+")
9980 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9981 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9982 "\\)" markers)
9983 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9984 re2a (concat "[ \t\r\n]" re2a_)
9985 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9986 re4 (concat "[^a-zA-Z_]" re4_)
9988 re1 (concat pre re2 post)
9989 re3 (concat pre (if pre re4_ re4) post)
9990 re5 (concat pre ".*" re4)
9991 re2 (concat pre re2)
9992 re2a (concat pre (if pre re2a_ re2a))
9993 re4 (concat pre (if pre re4_ re4))
9994 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9995 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9996 re5 "\\)"
9998 (cond
9999 ((eq type 'org-occur) (org-occur reall))
10000 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10001 (t (goto-char (point-min))
10002 (setq type 'fuzzy)
10003 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10004 (org-search-not-self 1 re1 nil t)
10005 (org-search-not-self 1 re2 nil t)
10006 (org-search-not-self 1 re2a nil t)
10007 (org-search-not-self 1 re3 nil t)
10008 (org-search-not-self 1 re4 nil t)
10009 (org-search-not-self 1 re5 nil t)
10011 (goto-char (match-beginning 1))
10012 (goto-char pos)
10013 (error "No match"))))))
10014 (and (eq major-mode 'org-mode)
10015 (not stealth)
10016 (org-show-context 'link-search))
10017 type))
10019 (defun org-search-not-self (group &rest args)
10020 "Execute `re-search-forward', but only accept matches that do not
10021 enclose the position of `org-open-link-marker'."
10022 (let ((m org-open-link-marker))
10023 (catch 'exit
10024 (while (apply 're-search-forward args)
10025 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10026 (goto-char (match-end group))
10027 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10028 (> (match-beginning 0) (marker-position m))
10029 (< (match-end 0) (marker-position m)))
10030 (save-match-data
10031 (or (not (org-in-regexp
10032 org-bracket-link-analytic-regexp 1))
10033 (not (match-end 4)) ; no description
10034 (and (<= (match-beginning 4) (point))
10035 (>= (match-end 4) (point))))))
10036 (throw 'exit (point))))))))
10038 (defun org-get-buffer-for-internal-link (buffer)
10039 "Return a buffer to be used for displaying the link target of internal links."
10040 (cond
10041 ((not org-display-internal-link-with-indirect-buffer)
10042 buffer)
10043 ((string-match "(Clone)$" (buffer-name buffer))
10044 (message "Buffer is already a clone, not making another one")
10045 ;; we also do not modify visibility in this case
10046 buffer)
10047 (t ; make a new indirect buffer for displaying the link
10048 (let* ((bn (buffer-name buffer))
10049 (ibn (concat bn "(Clone)"))
10050 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10051 (with-current-buffer ib (org-overview))
10052 ib))))
10054 (defun org-do-occur (regexp &optional cleanup)
10055 "Call the Emacs command `occur'.
10056 If CLEANUP is non-nil, remove the printout of the regular expression
10057 in the *Occur* buffer. This is useful if the regex is long and not useful
10058 to read."
10059 (occur regexp)
10060 (when cleanup
10061 (let ((cwin (selected-window)) win beg end)
10062 (when (setq win (get-buffer-window "*Occur*"))
10063 (select-window win))
10064 (goto-char (point-min))
10065 (when (re-search-forward "match[a-z]+" nil t)
10066 (setq beg (match-end 0))
10067 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10068 (setq end (1- (match-beginning 0)))))
10069 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10070 (goto-char (point-min))
10071 (select-window cwin))))
10073 ;;; The mark ring for links jumps
10075 (defvar org-mark-ring nil
10076 "Mark ring for positions before jumps in Org-mode.")
10077 (defvar org-mark-ring-last-goto nil
10078 "Last position in the mark ring used to go back.")
10079 ;; Fill and close the ring
10080 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10081 (loop for i from 1 to org-mark-ring-length do
10082 (push (make-marker) org-mark-ring))
10083 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10084 org-mark-ring)
10086 (defun org-mark-ring-push (&optional pos buffer)
10087 "Put the current position or POS into the mark ring and rotate it."
10088 (interactive)
10089 (setq pos (or pos (point)))
10090 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10091 (move-marker (car org-mark-ring)
10092 (or pos (point))
10093 (or buffer (current-buffer)))
10094 (message "%s"
10095 (substitute-command-keys
10096 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10098 (defun org-mark-ring-goto (&optional n)
10099 "Jump to the previous position in the mark ring.
10100 With prefix arg N, jump back that many stored positions. When
10101 called several times in succession, walk through the entire ring.
10102 Org-mode commands jumping to a different position in the current file,
10103 or to another Org-mode file, automatically push the old position
10104 onto the ring."
10105 (interactive "p")
10106 (let (p m)
10107 (if (eq last-command this-command)
10108 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10109 (setq p org-mark-ring))
10110 (setq org-mark-ring-last-goto p)
10111 (setq m (car p))
10112 (org-pop-to-buffer-same-window (marker-buffer m))
10113 (goto-char m)
10114 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10116 (defun org-remove-angle-brackets (s)
10117 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10118 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10120 (defun org-add-angle-brackets (s)
10121 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10122 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10124 (defun org-remove-double-quotes (s)
10125 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10126 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10129 ;;; Following specific links
10131 (defun org-follow-timestamp-link ()
10132 (cond
10133 ((org-at-date-range-p t)
10134 (let ((org-agenda-start-on-weekday)
10135 (t1 (match-string 1))
10136 (t2 (match-string 2)))
10137 (setq t1 (time-to-days (org-time-string-to-time t1))
10138 t2 (time-to-days (org-time-string-to-time t2)))
10139 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10140 ((org-at-timestamp-p t)
10141 (org-agenda-list nil (time-to-days (org-time-string-to-time
10142 (substring (match-string 1) 0 10)))
10144 (t (error "This should not happen"))))
10147 ;;; Following file links
10148 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10149 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10150 (declare-function mailcap-mime-info
10151 "mailcap" (string &optional request no-decode))
10152 (defvar org-wait nil)
10153 (defun org-open-file (path &optional in-emacs line search)
10154 "Open the file at PATH.
10155 First, this expands any special file name abbreviations. Then the
10156 configuration variable `org-file-apps' is checked if it contains an
10157 entry for this file type, and if yes, the corresponding command is launched.
10159 If no application is found, Emacs simply visits the file.
10161 With optional prefix argument IN-EMACS, Emacs will visit the file.
10162 With a double \\[universal-argument] \\[universal-argument] \
10163 prefix arg, Org tries to avoid opening in Emacs
10164 and to use an external application to visit the file.
10166 Optional LINE specifies a line to go to, optional SEARCH a string
10167 to search for. If LINE or SEARCH is given, the file will be
10168 opened in Emacs, unless an entry from org-file-apps that makes
10169 use of groups in a regexp matches.
10171 If you want to change the way frames are used when following a
10172 link, please customize `org-link-frame-setup'.
10174 If the file does not exist, an error is thrown."
10175 (let* ((file (if (equal path "")
10176 buffer-file-name
10177 (substitute-in-file-name (expand-file-name path))))
10178 (file-apps (append org-file-apps (org-default-apps)))
10179 (apps (org-remove-if
10180 'org-file-apps-entry-match-against-dlink-p file-apps))
10181 (apps-dlink (org-remove-if-not
10182 'org-file-apps-entry-match-against-dlink-p file-apps))
10183 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10184 (dirp (if remp nil (file-directory-p file)))
10185 (file (if (and dirp org-open-directory-means-index-dot-org)
10186 (concat (file-name-as-directory file) "index.org")
10187 file))
10188 (a-m-a-p (assq 'auto-mode apps))
10189 (dfile (downcase file))
10190 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10191 (link (cond ((and (eq line nil)
10192 (eq search nil))
10193 file)
10194 (line
10195 (concat file "::" (number-to-string line)))
10196 (search
10197 (concat file "::" search))))
10198 (dlink (downcase link))
10199 (old-buffer (current-buffer))
10200 (old-pos (point))
10201 (old-mode major-mode)
10202 ext cmd link-match-data)
10203 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10204 (setq ext (match-string 1 dfile))
10205 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10206 (setq ext (match-string 1 dfile))))
10207 (cond
10208 ((member in-emacs '((16) system))
10209 (setq cmd (cdr (assoc 'system apps))))
10210 (in-emacs (setq cmd 'emacs))
10212 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10213 (and dirp (cdr (assoc 'directory apps)))
10214 ; first, try matching against apps-dlink
10215 ; if we get a match here, store the match data for later
10216 (let ((match (assoc-default dlink apps-dlink
10217 'string-match)))
10218 (if match
10219 (progn (setq link-match-data (match-data))
10220 match)
10221 (progn (setq in-emacs (or in-emacs line search))
10222 nil))) ; if we have no match in apps-dlink,
10223 ; always open the file in emacs if line or search
10224 ; is given (for backwards compatibility)
10225 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10226 'string-match)
10227 (cdr (assoc ext apps))
10228 (cdr (assoc t apps))))))
10229 (when (eq cmd 'system)
10230 (setq cmd (cdr (assoc 'system apps))))
10231 (when (eq cmd 'default)
10232 (setq cmd (cdr (assoc t apps))))
10233 (when (eq cmd 'mailcap)
10234 (require 'mailcap)
10235 (mailcap-parse-mailcaps)
10236 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10237 (command (mailcap-mime-info mime-type)))
10238 (if (stringp command)
10239 (setq cmd command)
10240 (setq cmd 'emacs))))
10241 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10242 (not (file-exists-p file))
10243 (not org-open-non-existing-files))
10244 (error "No such file: %s" file))
10245 (cond
10246 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10247 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10248 (while (string-match "['\"]%s['\"]" cmd)
10249 (setq cmd (replace-match "%s" t t cmd)))
10250 (while (string-match "%s" cmd)
10251 (setq cmd (replace-match
10252 (save-match-data
10253 (shell-quote-argument
10254 (convert-standard-filename file)))
10255 t t cmd)))
10257 ;; Replace "%1", "%2" etc. in command with group matches from regex
10258 (save-match-data
10259 (let ((match-index 1)
10260 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10261 (set-match-data link-match-data)
10262 (while (<= match-index number-of-groups)
10263 (let ((regex (concat "%" (number-to-string match-index)))
10264 (replace-with (match-string match-index dlink)))
10265 (while (string-match regex cmd)
10266 (setq cmd (replace-match replace-with t t cmd))))
10267 (setq match-index (+ match-index 1)))))
10269 (save-window-excursion
10270 (start-process-shell-command cmd nil cmd)
10271 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10273 ((or (stringp cmd)
10274 (eq cmd 'emacs))
10275 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10276 (widen)
10277 (if line (org-goto-line line)
10278 (if search (org-link-search search))))
10279 ((consp cmd)
10280 (let ((file (convert-standard-filename file)))
10281 (save-match-data
10282 (set-match-data link-match-data)
10283 (eval cmd))))
10284 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10285 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10286 (or (not (equal old-buffer (current-buffer)))
10287 (not (equal old-pos (point))))
10288 (org-mark-ring-push old-pos old-buffer))))
10290 (defun org-file-apps-entry-match-against-dlink-p (entry)
10291 "This function returns non-nil if `entry' uses a regular
10292 expression which should be matched against the whole link by
10293 org-open-file.
10295 It assumes that is the case when the entry uses a regular
10296 expression which has at least one grouping construct and the
10297 action is either a lisp form or a command string containing
10298 '%1', i.e. using at least one subexpression match as a
10299 parameter."
10300 (let ((selector (car entry))
10301 (action (cdr entry)))
10302 (if (stringp selector)
10303 (and (> (regexp-opt-depth selector) 0)
10304 (or (and (stringp action)
10305 (string-match "%[0-9]" action))
10306 (consp action)))
10307 nil)))
10309 (defun org-default-apps ()
10310 "Return the default applications for this operating system."
10311 (cond
10312 ((eq system-type 'darwin)
10313 org-file-apps-defaults-macosx)
10314 ((eq system-type 'windows-nt)
10315 org-file-apps-defaults-windowsnt)
10316 (t org-file-apps-defaults-gnu)))
10318 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10319 "Convert extensions to regular expressions in the cars of LIST.
10320 Also, weed out any non-string entries, because the return value is used
10321 only for regexp matching.
10322 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10323 point to the symbol `emacs', indicating that the file should
10324 be opened in Emacs."
10325 (append
10326 (delq nil
10327 (mapcar (lambda (x)
10328 (if (not (stringp (car x)))
10330 (if (string-match "\\W" (car x))
10332 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10333 list))
10334 (if add-auto-mode
10335 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10337 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10338 (defun org-file-remote-p (file)
10339 "Test whether FILE specifies a location on a remote system.
10340 Return non-nil if the location is indeed remote.
10342 For example, the filename \"/user@host:/foo\" specifies a location
10343 on the system \"/user@host:\"."
10344 (cond ((fboundp 'file-remote-p)
10345 (file-remote-p file))
10346 ((fboundp 'tramp-handle-file-remote-p)
10347 (tramp-handle-file-remote-p file))
10348 ((and (boundp 'ange-ftp-name-format)
10349 (string-match (car ange-ftp-name-format) file))
10351 (t nil)))
10354 ;;;; Refiling
10356 (defun org-get-org-file ()
10357 "Read a filename, with default directory `org-directory'."
10358 (let ((default (or org-default-notes-file remember-data-file)))
10359 (read-file-name (format "File name [%s]: " default)
10360 (file-name-as-directory org-directory)
10361 default)))
10363 (defun org-notes-order-reversed-p ()
10364 "Check if the current file should receive notes in reversed order."
10365 (cond
10366 ((not org-reverse-note-order) nil)
10367 ((eq t org-reverse-note-order) t)
10368 ((not (listp org-reverse-note-order)) nil)
10369 (t (catch 'exit
10370 (let ((all org-reverse-note-order)
10371 entry)
10372 (while (setq entry (pop all))
10373 (if (string-match (car entry) buffer-file-name)
10374 (throw 'exit (cdr entry))))
10375 nil)))))
10377 (defvar org-refile-target-table nil
10378 "The list of refile targets, created by `org-refile'.")
10380 (defvar org-agenda-new-buffers nil
10381 "Buffers created to visit agenda files.")
10383 (defvar org-refile-cache nil
10384 "Cache for refile targets.")
10386 (defvar org-refile-markers nil
10387 "All the markers used for caching refile locations.")
10389 (defun org-refile-marker (pos)
10390 "Get a new refile marker, but only if caching is in use."
10391 (if (not org-refile-use-cache)
10393 (let ((m (make-marker)))
10394 (move-marker m pos)
10395 (push m org-refile-markers)
10396 m)))
10398 (defun org-refile-cache-clear ()
10399 "Clear the refile cache and disable all the markers."
10400 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10401 (setq org-refile-markers nil)
10402 (setq org-refile-cache nil)
10403 (message "Refile cache has been cleared"))
10405 (defun org-refile-cache-check-set (set)
10406 "Check if all the markers in the cache still have live buffers."
10407 (let (marker)
10408 (catch 'exit
10409 (while (and set (setq marker (nth 3 (pop set))))
10410 ;; if org-refile-use-outline-path is 'file, marker may be nil
10411 (when (and marker (null (marker-buffer marker)))
10412 (message "not found") (sit-for 3)
10413 (throw 'exit nil)))
10414 t)))
10416 (defun org-refile-cache-put (set &rest identifiers)
10417 "Push the refile targets SET into the cache, under IDENTIFIERS."
10418 (let* ((key (sha1 (prin1-to-string identifiers)))
10419 (entry (assoc key org-refile-cache)))
10420 (if entry
10421 (setcdr entry set)
10422 (push (cons key set) org-refile-cache))))
10424 (defun org-refile-cache-get (&rest identifiers)
10425 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10426 (cond
10427 ((not org-refile-cache) nil)
10428 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10430 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10431 org-refile-cache))))
10432 (and set (org-refile-cache-check-set set) set)))))
10434 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10435 "Produce a table with refile targets."
10436 (let ((case-fold-search nil)
10437 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10438 (entries (or org-refile-targets '((nil . (:level . 1)))))
10439 targets tgs txt re files f desc descre fast-path-p level pos0)
10440 (message "Getting targets...")
10441 (with-current-buffer (or default-buffer (current-buffer))
10442 (while (setq entry (pop entries))
10443 (setq files (car entry) desc (cdr entry))
10444 (setq fast-path-p nil)
10445 (cond
10446 ((null files) (setq files (list (current-buffer))))
10447 ((eq files 'org-agenda-files)
10448 (setq files (org-agenda-files 'unrestricted)))
10449 ((and (symbolp files) (fboundp files))
10450 (setq files (funcall files)))
10451 ((and (symbolp files) (boundp files))
10452 (setq files (symbol-value files))))
10453 (if (stringp files) (setq files (list files)))
10454 (cond
10455 ((eq (car desc) :tag)
10456 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10457 ((eq (car desc) :todo)
10458 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10459 ((eq (car desc) :regexp)
10460 (setq descre (cdr desc)))
10461 ((eq (car desc) :level)
10462 (setq descre (concat "^\\*\\{" (number-to-string
10463 (if org-odd-levels-only
10464 (1- (* 2 (cdr desc)))
10465 (cdr desc)))
10466 "\\}[ \t]")))
10467 ((eq (car desc) :maxlevel)
10468 (setq fast-path-p t)
10469 (setq descre (concat "^\\*\\{1," (number-to-string
10470 (if org-odd-levels-only
10471 (1- (* 2 (cdr desc)))
10472 (cdr desc)))
10473 "\\}[ \t]")))
10474 (t (error "Bad refiling target description %s" desc)))
10475 (while (setq f (pop files))
10476 (with-current-buffer
10477 (if (bufferp f) f (org-get-agenda-file-buffer f))
10479 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10480 (progn
10481 (if (bufferp f) (setq f (buffer-file-name
10482 (buffer-base-buffer f))))
10483 (setq f (and f (expand-file-name f)))
10484 (if (eq org-refile-use-outline-path 'file)
10485 (push (list (file-name-nondirectory f) f nil nil) tgs))
10486 (save-excursion
10487 (save-restriction
10488 (widen)
10489 (goto-char (point-min))
10490 (while (re-search-forward descre nil t)
10491 (goto-char (setq pos0 (point-at-bol)))
10492 (catch 'next
10493 (when org-refile-target-verify-function
10494 (save-match-data
10495 (or (funcall org-refile-target-verify-function)
10496 (throw 'next t))))
10497 (when (and (looking-at org-complex-heading-regexp)
10498 (not (member (match-string 4) excluded-entries))
10499 (match-string 4))
10500 (setq level (org-reduced-level
10501 (- (match-end 1) (match-beginning 1)))
10502 txt (org-link-display-format (match-string 4))
10503 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10504 re (format org-complex-heading-regexp-format
10505 (regexp-quote (match-string 4))))
10506 (when org-refile-use-outline-path
10507 (setq txt (mapconcat
10508 'org-protect-slash
10509 (append
10510 (if (eq org-refile-use-outline-path
10511 'file)
10512 (list (file-name-nondirectory
10513 (buffer-file-name
10514 (buffer-base-buffer))))
10515 (if (eq org-refile-use-outline-path
10516 'full-file-path)
10517 (list (buffer-file-name
10518 (buffer-base-buffer)))))
10519 (org-get-outline-path fast-path-p
10520 level txt)
10521 (list txt))
10522 "/")))
10523 (push (list txt f re (org-refile-marker (point)))
10524 tgs)))
10525 (when (= (point) pos0)
10526 ;; verification function has not moved point
10527 (goto-char (point-at-eol))))))))
10528 (when org-refile-use-cache
10529 (org-refile-cache-put tgs (buffer-file-name) descre))
10530 (setq targets (append tgs targets))
10531 ))))
10532 (message "Getting targets...done")
10533 (nreverse targets)))
10535 (defun org-protect-slash (s)
10536 (while (string-match "/" s)
10537 (setq s (replace-match "\\" t t s)))
10540 (defvar org-olpa (make-vector 20 nil))
10542 (defun org-get-outline-path (&optional fastp level heading)
10543 "Return the outline path to the current entry, as a list.
10545 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10546 routine which makes outline path derivations for an entire file,
10547 avoiding backtracing. Refile target collection makes use of that."
10548 (if fastp
10549 (progn
10550 (if (> level 19)
10551 (error "Outline path failure, more than 19 levels"))
10552 (loop for i from level upto 19 do
10553 (aset org-olpa i nil))
10554 (prog1
10555 (delq nil (append org-olpa nil))
10556 (aset org-olpa level heading)))
10557 (let (rtn case-fold-search)
10558 (save-excursion
10559 (save-restriction
10560 (widen)
10561 (while (org-up-heading-safe)
10562 (when (looking-at org-complex-heading-regexp)
10563 (push (org-match-string-no-properties 4) rtn)))
10564 rtn)))))
10566 (defun org-format-outline-path (path &optional width prefix)
10567 "Format the outline path PATH for display.
10568 Width is the maximum number of characters that is available.
10569 Prefix is a prefix to be included in the returned string,
10570 such as the file name."
10571 (setq width (or width 79))
10572 (if prefix (setq width (- width (length prefix))))
10573 (if (not path)
10574 (or prefix "")
10575 (let* ((nsteps (length path))
10576 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10577 (maxwidth (if (<= total-width width)
10578 10000 ;; everything fits
10579 ;; we need to shorten the level headings
10580 (/ (- width nsteps) nsteps)))
10581 (org-odd-levels-only nil)
10582 (n 0)
10583 (total (1+ (length prefix))))
10584 (setq maxwidth (max maxwidth 10))
10585 (concat prefix
10586 (mapconcat
10587 (lambda (h)
10588 (setq n (1+ n))
10589 (if (and (= n nsteps) (< maxwidth 10000))
10590 (setq maxwidth (- total-width total)))
10591 (if (< (length h) maxwidth)
10592 (progn (setq total (+ total (length h) 1)) h)
10593 (setq h (substring h 0 (- maxwidth 2))
10594 total (+ total maxwidth 1))
10595 (if (string-match "[ \t]+\\'" h)
10596 (setq h (substring h 0 (match-beginning 0))))
10597 (setq h (concat h "..")))
10598 (org-add-props h nil 'face
10599 (nth (% (1- n) org-n-level-faces)
10600 org-level-faces))
10602 path "/")))))
10604 (defun org-display-outline-path (&optional file current)
10605 "Display the current outline path in the echo area."
10606 (interactive "P")
10607 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10608 (case-fold-search nil)
10609 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10610 (if current (setq path (append path
10611 (save-excursion
10612 (org-back-to-heading t)
10613 (if (looking-at org-complex-heading-regexp)
10614 (list (match-string 4)))))))
10615 (message "%s"
10616 (org-format-outline-path
10617 path
10618 (1- (frame-width))
10619 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10621 (defvar org-refile-history nil
10622 "History for refiling operations.")
10624 (defvar org-after-refile-insert-hook nil
10625 "Hook run after `org-refile' has inserted its stuff at the new location.
10626 Note that this is still *before* the stuff will be removed from
10627 the *old* location.")
10629 (defvar org-capture-last-stored-marker)
10630 (defun org-refile (&optional goto default-buffer rfloc)
10631 "Move the entry or entries at point to another heading.
10632 The list of target headings is compiled using the information in
10633 `org-refile-targets', which see.
10635 At the target location, the entry is filed as a subitem of the target
10636 heading. Depending on `org-reverse-note-order', the new subitem will
10637 either be the first or the last subitem.
10639 If there is an active region, all entries in that region will be moved.
10640 However, the region must fulfill the requirement that the first heading
10641 is the first one sets the top-level of the moved text - at most siblings
10642 below it are allowed.
10644 With prefix arg GOTO, the command will only visit the target location
10645 and not actually move anything.
10647 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10648 go to the location where the last refiling operation has put the subtree.
10649 With a prefix argument of `2', refile to the running clock.
10651 RFLOC can be a refile location obtained in a different way.
10653 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10655 If you are using target caching (see `org-refile-use-cache'),
10656 You have to clear the target cache in order to find new targets.
10657 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10658 prefix argument (`C-u C-u C-u C-c C-w')."
10660 (interactive "P")
10661 (if (member goto '(0 (64)))
10662 (org-refile-cache-clear)
10663 (let* ((cbuf (current-buffer))
10664 (regionp (org-region-active-p))
10665 (region-start (and regionp (region-beginning)))
10666 (region-end (and regionp (region-end)))
10667 (region-length (and regionp (- region-end region-start)))
10668 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10669 pos it nbuf file re level reversed)
10670 (setq last-command nil)
10671 (when regionp
10672 (goto-char region-start)
10673 (or (bolp) (goto-char (point-at-bol)))
10674 (setq region-start (point))
10675 (unless (or (org-kill-is-subtree-p
10676 (buffer-substring region-start region-end))
10677 (prog1 org-refile-active-region-within-subtree
10678 (org-toggle-heading)))
10679 (error "The region is not a (sequence of) subtree(s)")))
10680 (if (equal goto '(16))
10681 (org-refile-goto-last-stored)
10682 (when (or
10683 (and (equal goto 2)
10684 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10685 (prog1
10686 (setq it (list (or org-clock-heading "running clock")
10687 (buffer-file-name
10688 (marker-buffer org-clock-hd-marker))
10690 (marker-position org-clock-hd-marker)))
10691 (setq goto nil)))
10692 (setq it (or rfloc
10693 (let (heading-text)
10694 (save-excursion
10695 (unless goto
10696 (org-back-to-heading t)
10697 (setq heading-text
10698 (nth 4 (org-heading-components))))
10699 (org-refile-get-location
10700 (cond (goto "Goto")
10701 (regionp "Refile region to")
10702 (t (concat "Refile subtree \""
10703 heading-text "\" to")))
10704 default-buffer
10705 (and (not (equal '(4) goto))
10706 org-refile-allow-creating-parent-nodes)
10707 goto))))))
10708 (setq file (nth 1 it)
10709 re (nth 2 it)
10710 pos (nth 3 it))
10711 (if (and (not goto)
10713 (equal (buffer-file-name) file)
10714 (if regionp
10715 (and (>= pos region-start)
10716 (<= pos region-end))
10717 (and (>= pos (point))
10718 (< pos (save-excursion
10719 (org-end-of-subtree t t))))))
10720 (error "Cannot refile to position inside the tree or region"))
10722 (setq nbuf (or (find-buffer-visiting file)
10723 (find-file-noselect file)))
10724 (if goto
10725 (progn
10726 (org-pop-to-buffer-same-window nbuf)
10727 (goto-char pos)
10728 (org-show-context 'org-goto))
10729 (if regionp
10730 (progn
10731 (org-kill-new (buffer-substring region-start region-end))
10732 (org-save-markers-in-region region-start region-end))
10733 (org-copy-subtree 1 nil t))
10734 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10735 (find-file-noselect file)))
10736 (setq reversed (org-notes-order-reversed-p))
10737 (save-excursion
10738 (save-restriction
10739 (widen)
10740 (if pos
10741 (progn
10742 (goto-char pos)
10743 (looking-at org-outline-regexp)
10744 (setq level (org-get-valid-level (funcall outline-level) 1))
10745 (goto-char
10746 (if reversed
10747 (or (outline-next-heading) (point-max))
10748 (or (save-excursion (org-get-next-sibling))
10749 (org-end-of-subtree t t)
10750 (point-max)))))
10751 (setq level 1)
10752 (if (not reversed)
10753 (goto-char (point-max))
10754 (goto-char (point-min))
10755 (or (outline-next-heading) (goto-char (point-max)))))
10756 (if (not (bolp)) (newline))
10757 (org-paste-subtree level)
10758 (when org-log-refile
10759 (org-add-log-setup 'refile nil nil 'findpos
10760 org-log-refile)
10761 (unless (eq org-log-refile 'note)
10762 (save-excursion (org-add-log-note))))
10763 (and org-auto-align-tags (org-set-tags nil t))
10764 (bookmark-set "org-refile-last-stored")
10765 ;; If we are refiling for capture, make sure that the
10766 ;; last-capture pointers point here
10767 (when (org-bound-and-true-p org-refile-for-capture)
10768 (bookmark-set "org-capture-last-stored-marker")
10769 (move-marker org-capture-last-stored-marker (point)))
10770 (if (fboundp 'deactivate-mark) (deactivate-mark))
10771 (run-hooks 'org-after-refile-insert-hook))))
10772 (if regionp
10773 (delete-region (point) (+ (point) region-length))
10774 (org-cut-subtree))
10775 (when (featurep 'org-inlinetask)
10776 (org-inlinetask-remove-END-maybe))
10777 (setq org-markers-to-move nil)
10778 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10780 (defun org-refile-goto-last-stored ()
10781 "Go to the location where the last refile was stored."
10782 (interactive)
10783 (bookmark-jump "org-refile-last-stored")
10784 (message "This is the location of the last refile"))
10786 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10787 no-exclude)
10788 "Prompt the user for a refile location, using PROMPT.
10789 PROMPT should not be suffixed with a colon and a space, because
10790 this function appends the default value from
10791 `org-refile-history' automatically, if that is not empty.
10792 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10793 this is used for the GOTO interface."
10794 (let ((org-refile-targets org-refile-targets)
10795 (org-refile-use-outline-path org-refile-use-outline-path)
10796 excluded-entries)
10797 (when (and (eq major-mode 'org-mode)
10798 (not org-refile-use-cache)
10799 (not no-exclude))
10800 (org-map-tree
10801 (lambda()
10802 (setq excluded-entries
10803 (append excluded-entries (list (org-get-heading t t)))))))
10804 (setq org-refile-target-table
10805 (org-refile-get-targets default-buffer excluded-entries)))
10806 (unless org-refile-target-table
10807 (error "No refile targets"))
10808 (let* ((prompt (concat prompt
10809 (and (car org-refile-history)
10810 (concat " (default " (car org-refile-history) ")"))
10811 ": "))
10812 (cbuf (current-buffer))
10813 (partial-completion-mode nil)
10814 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10815 (cfunc (if (and org-refile-use-outline-path
10816 org-outline-path-complete-in-steps)
10817 'org-olpath-completing-read
10818 'org-icompleting-read))
10819 (extra (if org-refile-use-outline-path "/" ""))
10820 (filename (and cfn (expand-file-name cfn)))
10821 (tbl (mapcar
10822 (lambda (x)
10823 (if (and (not (member org-refile-use-outline-path
10824 '(file full-file-path)))
10825 (not (equal filename (nth 1 x))))
10826 (cons (concat (car x) extra " ("
10827 (file-name-nondirectory (nth 1 x)) ")")
10828 (cdr x))
10829 (cons (concat (car x) extra) (cdr x))))
10830 org-refile-target-table))
10831 (completion-ignore-case t)
10832 pa answ parent-target child parent old-hist)
10833 (setq old-hist org-refile-history)
10834 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10835 nil 'org-refile-history (car org-refile-history)))
10836 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10837 (org-refile-check-position pa)
10838 (if pa
10839 (progn
10840 (when (or (not org-refile-history)
10841 (not (eq old-hist org-refile-history))
10842 (not (equal (car pa) (car org-refile-history))))
10843 (setq org-refile-history
10844 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10845 org-refile-history
10846 (cdr org-refile-history))))
10847 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10848 (pop org-refile-history)))
10850 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10851 (progn
10852 (setq parent (match-string 1 answ)
10853 child (match-string 2 answ))
10854 (setq parent-target (or (assoc parent tbl)
10855 (assoc (concat parent "/") tbl)))
10856 (when (and parent-target
10857 (or (eq new-nodes t)
10858 (and (eq new-nodes 'confirm)
10859 (y-or-n-p (format "Create new node \"%s\"? "
10860 child)))))
10861 (org-refile-new-child parent-target child)))
10862 (error "Invalid target location")))))
10864 (declare-function org-string-nw-p "org-macs.el" (s))
10865 (defun org-refile-check-position (refile-pointer)
10866 "Check if the refile pointer matches the readline to which it points."
10867 (let* ((file (nth 1 refile-pointer))
10868 (re (nth 2 refile-pointer))
10869 (pos (nth 3 refile-pointer))
10870 buffer)
10871 (when (org-string-nw-p re)
10872 (setq buffer (if (markerp pos)
10873 (marker-buffer pos)
10874 (or (find-buffer-visiting file)
10875 (find-file-noselect file))))
10876 (with-current-buffer buffer
10877 (save-excursion
10878 (save-restriction
10879 (widen)
10880 (goto-char pos)
10881 (beginning-of-line 1)
10882 (unless (org-looking-at-p re)
10883 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10885 (defun org-refile-new-child (parent-target child)
10886 "Use refile target PARENT-TARGET to add new CHILD below it."
10887 (unless parent-target
10888 (error "Cannot find parent for new node"))
10889 (let ((file (nth 1 parent-target))
10890 (pos (nth 3 parent-target))
10891 level)
10892 (with-current-buffer (or (find-buffer-visiting file)
10893 (find-file-noselect file))
10894 (save-excursion
10895 (save-restriction
10896 (widen)
10897 (if pos
10898 (goto-char pos)
10899 (goto-char (point-max))
10900 (if (not (bolp)) (newline)))
10901 (when (looking-at org-outline-regexp)
10902 (setq level (funcall outline-level))
10903 (org-end-of-subtree t t))
10904 (org-back-over-empty-lines)
10905 (insert "\n" (make-string
10906 (if pos (org-get-valid-level level 1) 1) ?*)
10907 " " child "\n")
10908 (beginning-of-line 0)
10909 (list (concat (car parent-target) "/" child) file "" (point)))))))
10911 (defun org-olpath-completing-read (prompt collection &rest args)
10912 "Read an outline path like a file name."
10913 (let ((thetable collection)
10914 (org-completion-use-ido nil) ; does not work with ido.
10915 (org-completion-use-iswitchb nil)) ; or iswitchb
10916 (apply
10917 'org-icompleting-read prompt
10918 (lambda (string predicate &optional flag)
10919 (let (rtn r f (l (length string)))
10920 (cond
10921 ((eq flag nil)
10922 ;; try completion
10923 (try-completion string thetable))
10924 ((eq flag t)
10925 ;; all-completions
10926 (setq rtn (all-completions string thetable predicate))
10927 (mapcar
10928 (lambda (x)
10929 (setq r (substring x l))
10930 (if (string-match " ([^)]*)$" x)
10931 (setq f (match-string 0 x))
10932 (setq f ""))
10933 (if (string-match "/" r)
10934 (concat string (substring r 0 (match-end 0)) f)
10936 rtn))
10937 ((eq flag 'lambda)
10938 ;; exact match?
10939 (assoc string thetable)))
10941 args)))
10943 ;;;; Dynamic blocks
10945 (defun org-find-dblock (name)
10946 "Find the first dynamic block with name NAME in the buffer.
10947 If not found, stay at current position and return nil."
10948 (let (pos)
10949 (save-excursion
10950 (goto-char (point-min))
10951 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10952 nil t)
10953 (match-beginning 0))))
10954 (if pos (goto-char pos))
10955 pos))
10957 (defconst org-dblock-start-re
10958 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10959 "Matches the start line of a dynamic block, with parameters.")
10961 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10962 "Matches the end of a dynamic block.")
10964 (defun org-create-dblock (plist)
10965 "Create a dynamic block section, with parameters taken from PLIST.
10966 PLIST must contain a :name entry which is used as name of the block."
10967 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10968 (end-of-line 1)
10969 (newline))
10970 (let ((col (current-column))
10971 (name (plist-get plist :name)))
10972 (insert "#+BEGIN: " name)
10973 (while plist
10974 (if (eq (car plist) :name)
10975 (setq plist (cddr plist))
10976 (insert " " (prin1-to-string (pop plist)))))
10977 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10978 (beginning-of-line -2)))
10980 (defun org-prepare-dblock ()
10981 "Prepare dynamic block for refresh.
10982 This empties the block, puts the cursor at the insert position and returns
10983 the property list including an extra property :name with the block name."
10984 (unless (looking-at org-dblock-start-re)
10985 (error "Not at a dynamic block"))
10986 (let* ((begdel (1+ (match-end 0)))
10987 (name (org-no-properties (match-string 1)))
10988 (params (append (list :name name)
10989 (read (concat "(" (match-string 3) ")")))))
10990 (save-excursion
10991 (beginning-of-line 1)
10992 (skip-chars-forward " \t")
10993 (setq params (plist-put params :indentation-column (current-column))))
10994 (unless (re-search-forward org-dblock-end-re nil t)
10995 (error "Dynamic block not terminated"))
10996 (setq params
10997 (append params
10998 (list :content (buffer-substring
10999 begdel (match-beginning 0)))))
11000 (delete-region begdel (match-beginning 0))
11001 (goto-char begdel)
11002 (open-line 1)
11003 params))
11005 (defun org-map-dblocks (&optional command)
11006 "Apply COMMAND to all dynamic blocks in the current buffer.
11007 If COMMAND is not given, use `org-update-dblock'."
11008 (let ((cmd (or command 'org-update-dblock)))
11009 (save-excursion
11010 (goto-char (point-min))
11011 (while (re-search-forward org-dblock-start-re nil t)
11012 (goto-char (match-beginning 0))
11013 (save-excursion
11014 (condition-case nil
11015 (funcall cmd)
11016 (error (message "Error during update of dynamic block"))))
11017 (unless (re-search-forward org-dblock-end-re nil t)
11018 (error "Dynamic block not terminated"))))))
11020 (defun org-dblock-update (&optional arg)
11021 "User command for updating dynamic blocks.
11022 Update the dynamic block at point. With prefix ARG, update all dynamic
11023 blocks in the buffer."
11024 (interactive "P")
11025 (if arg
11026 (org-update-all-dblocks)
11027 (or (looking-at org-dblock-start-re)
11028 (org-beginning-of-dblock))
11029 (org-update-dblock)))
11031 (defun org-update-dblock ()
11032 "Update the dynamic block at point.
11033 This means to empty the block, parse for parameters and then call
11034 the correct writing function."
11035 (interactive)
11036 (save-window-excursion
11037 (let* ((pos (point))
11038 (line (org-current-line))
11039 (params (org-prepare-dblock))
11040 (name (plist-get params :name))
11041 (indent (plist-get params :indentation-column))
11042 (cmd (intern (concat "org-dblock-write:" name))))
11043 (message "Updating dynamic block `%s' at line %d..." name line)
11044 (funcall cmd params)
11045 (message "Updating dynamic block `%s' at line %d...done" name line)
11046 (goto-char pos)
11047 (when (and indent (> indent 0))
11048 (setq indent (make-string indent ?\ ))
11049 (save-excursion
11050 (org-beginning-of-dblock)
11051 (forward-line 1)
11052 (while (not (looking-at org-dblock-end-re))
11053 (insert indent)
11054 (beginning-of-line 2))
11055 (when (looking-at org-dblock-end-re)
11056 (and (looking-at "[ \t]+")
11057 (replace-match ""))
11058 (insert indent)))))))
11060 (defun org-beginning-of-dblock ()
11061 "Find the beginning of the dynamic block at point.
11062 Error if there is no such block at point."
11063 (let ((pos (point))
11064 beg)
11065 (end-of-line 1)
11066 (if (and (re-search-backward org-dblock-start-re nil t)
11067 (setq beg (match-beginning 0))
11068 (re-search-forward org-dblock-end-re nil t)
11069 (> (match-end 0) pos))
11070 (goto-char beg)
11071 (goto-char pos)
11072 (error "Not in a dynamic block"))))
11074 (defun org-update-all-dblocks ()
11075 "Update all dynamic blocks in the buffer.
11076 This function can be used in a hook."
11077 (interactive)
11078 (when (eq major-mode 'org-mode)
11079 (org-map-dblocks 'org-update-dblock)))
11082 ;;;; Completion
11084 (defconst org-additional-option-like-keywords
11085 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11086 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11087 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11088 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11089 "BEGIN:" "END:"
11090 "ORGTBL" "TBLFM:" "TBLNAME:"
11091 "BEGIN_EXAMPLE" "END_EXAMPLE"
11092 "BEGIN_QUOTE" "END_QUOTE"
11093 "BEGIN_VERSE" "END_VERSE"
11094 "BEGIN_CENTER" "END_CENTER"
11095 "BEGIN_SRC" "END_SRC"
11096 "BEGIN_RESULT" "END_RESULT"
11097 "NAME:" "RESULTS:"
11098 "HEADER:" "HEADERS:"
11099 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11100 "CAPTION:" "LABEL:"
11101 "SETUPFILE:"
11102 "INCLUDE:"
11103 "BIND:"
11104 "MACRO:"))
11106 (defcustom org-structure-template-alist
11108 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11109 "<src lang=\"?\">\n\n</src>")
11110 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11111 "<example>\n?\n</example>")
11112 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11113 "<quote>\n?\n</quote>")
11114 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11115 "<verse>\n?\n</verse>")
11116 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11117 "<center>\n?\n</center>")
11118 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11119 "<literal style=\"latex\">\n?\n</literal>")
11120 ("L" "#+LaTeX: "
11121 "<literal style=\"latex\">?</literal>")
11122 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11123 "<literal style=\"html\">\n?\n</literal>")
11124 ("H" "#+HTML: "
11125 "<literal style=\"html\">?</literal>")
11126 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11127 ("A" "#+ASCII: ")
11128 ("i" "#+INDEX: ?"
11129 "#+INDEX: ?")
11130 ("I" "#+INCLUDE %file ?"
11131 "<include file=%file markup=\"?\">")
11133 "Structure completion elements.
11134 This is a list of abbreviation keys and values. The value gets inserted
11135 if you type `<' followed by the key and then press the completion key,
11136 usually `M-TAB'. %file will be replaced by a file name after prompting
11137 for the file using completion. The cursor will be placed at the position
11138 of the `?` in the template.
11139 There are two templates for each key, the first uses the original Org syntax,
11140 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11141 the default when the /org-mtags.el/ module has been loaded. See also the
11142 variable `org-mtags-prefer-muse-templates'."
11143 :group 'org-completion
11144 :type '(repeat
11145 (string :tag "Key")
11146 (string :tag "Template")
11147 (string :tag "Muse Template")))
11149 (defun org-try-structure-completion ()
11150 "Try to complete a structure template before point.
11151 This looks for strings like \"<e\" on an otherwise empty line and
11152 expands them."
11153 (let ((l (buffer-substring (point-at-bol) (point)))
11155 (when (and (looking-at "[ \t]*$")
11156 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11157 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11158 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11159 (match-beginning 1)) a)
11160 t)))
11162 (defun org-complete-expand-structure-template (start cell)
11163 "Expand a structure template."
11164 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11165 (rpl (nth (if musep 2 1) cell))
11166 (ind ""))
11167 (delete-region start (point))
11168 (when (string-match "\\`#\\+" rpl)
11169 (cond
11170 ((bolp))
11171 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11172 (setq ind (buffer-substring (point-at-bol) (point))))
11173 (t (newline))))
11174 (setq start (point))
11175 (if (string-match "%file" rpl)
11176 (setq rpl (replace-match
11177 (concat
11178 "\""
11179 (save-match-data
11180 (abbreviate-file-name (read-file-name "Include file: ")))
11181 "\"")
11182 t t rpl)))
11183 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11184 (concat "\n" ind)))
11185 (insert rpl)
11186 (if (re-search-backward "\\?" start t) (delete-char 1))))
11188 ;;;; TODO, DEADLINE, Comments
11190 (defun org-toggle-comment ()
11191 "Change the COMMENT state of an entry."
11192 (interactive)
11193 (save-excursion
11194 (org-back-to-heading)
11195 (let (case-fold-search)
11196 (cond
11197 ((looking-at (format org-heading-keyword-regexp-format
11198 org-comment-string))
11199 (goto-char (match-end 1))
11200 (looking-at (concat " +" org-comment-string))
11201 (replace-match "" t t)
11202 (when (eolp) (insert " ")))
11203 ((looking-at org-outline-regexp)
11204 (goto-char (match-end 0))
11205 (insert org-comment-string " "))))))
11207 (defvar org-last-todo-state-is-todo nil
11208 "This is non-nil when the last TODO state change led to a TODO state.
11209 If the last change removed the TODO tag or switched to DONE, then
11210 this is nil.")
11212 (defvar org-setting-tags nil) ; dynamically skipped
11214 (defvar org-todo-setup-filter-hook nil
11215 "Hook for functions that pre-filter todo specs.
11216 Each function takes a todo spec and returns either nil or the spec
11217 transformed into canonical form." )
11219 (defvar org-todo-get-default-hook nil
11220 "Hook for functions that get a default item for todo.
11221 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11222 nil or a string to be used for the todo mark." )
11224 (defvar org-agenda-headline-snapshot-before-repeat)
11226 (defun org-current-effective-time ()
11227 "Return current time adjusted for `org-extend-today-until' variable"
11228 (let* ((ct (org-current-time))
11229 (dct (decode-time ct))
11230 (ct1
11231 (if (and org-use-effective-time
11232 (< (nth 2 dct) org-extend-today-until))
11233 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11234 ct)))
11235 ct1))
11237 (defun org-todo-yesterday (&optional arg)
11238 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11239 (interactive "P")
11240 (if (eq major-mode 'org-agenda-mode)
11241 (apply 'org-agenda-todo-yesterday arg)
11242 (let* ((hour (third (decode-time
11243 (org-current-time))))
11244 (org-extend-today-until (1+ hour)))
11245 (org-todo arg))))
11247 (defun org-todo (&optional arg)
11248 "Change the TODO state of an item.
11249 The state of an item is given by a keyword at the start of the heading,
11250 like
11251 *** TODO Write paper
11252 *** DONE Call mom
11254 The different keywords are specified in the variable `org-todo-keywords'.
11255 By default the available states are \"TODO\" and \"DONE\".
11256 So for this example: when the item starts with TODO, it is changed to DONE.
11257 When it starts with DONE, the DONE is removed. And when neither TODO nor
11258 DONE are present, add TODO at the beginning of the heading.
11260 With \\[universal-argument] prefix arg, use completion to determine the new \
11261 state.
11262 With numeric prefix arg, switch to that state.
11263 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11264 keywords (nextset).
11265 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11266 With a numeric prefix arg of 0, inhibit note taking for the change.
11268 For calling through lisp, arg is also interpreted in the following way:
11269 'none -> empty state
11270 \"\"(empty string) -> switch to empty state
11271 'done -> switch to DONE
11272 'nextset -> switch to the next set of keywords
11273 'previousset -> switch to the previous set of keywords
11274 \"WAITING\" -> switch to the specified keyword, but only if it
11275 really is a member of `org-todo-keywords'."
11276 (interactive "P")
11277 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11278 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11279 'region-start-level 'region))
11280 org-loop-over-headlines-in-active-region)
11281 (org-map-entries
11282 `(org-todo ,arg)
11283 org-loop-over-headlines-in-active-region
11284 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11285 (if (equal arg '(16)) (setq arg 'nextset))
11286 (let ((org-blocker-hook org-blocker-hook)
11287 (case-fold-search nil))
11288 (when (equal arg '(64))
11289 (setq arg nil org-blocker-hook nil))
11290 (when (and org-blocker-hook
11291 (or org-inhibit-blocking
11292 (org-entry-get nil "NOBLOCKING")))
11293 (setq org-blocker-hook nil))
11294 (save-excursion
11295 (catch 'exit
11296 (org-back-to-heading t)
11297 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11298 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11299 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11300 (let* ((match-data (match-data))
11301 (startpos (point-at-bol))
11302 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11303 (org-log-done org-log-done)
11304 (org-log-repeat org-log-repeat)
11305 (org-todo-log-states org-todo-log-states)
11306 (org-inhibit-logging
11307 (if (equal arg 0)
11308 (progn (setq arg nil) 'note) org-inhibit-logging))
11309 (this (match-string 1))
11310 (hl-pos (match-beginning 0))
11311 (head (org-get-todo-sequence-head this))
11312 (ass (assoc head org-todo-kwd-alist))
11313 (interpret (nth 1 ass))
11314 (done-word (nth 3 ass))
11315 (final-done-word (nth 4 ass))
11316 (org-last-state (or this ""))
11317 (completion-ignore-case t)
11318 (member (member this org-todo-keywords-1))
11319 (tail (cdr member))
11320 (org-state (cond
11321 ((and org-todo-key-trigger
11322 (or (and (equal arg '(4))
11323 (eq org-use-fast-todo-selection 'prefix))
11324 (and (not arg) org-use-fast-todo-selection
11325 (not (eq org-use-fast-todo-selection
11326 'prefix)))))
11327 ;; Use fast selection
11328 (org-fast-todo-selection))
11329 ((and (equal arg '(4))
11330 (or (not org-use-fast-todo-selection)
11331 (not org-todo-key-trigger)))
11332 ;; Read a state with completion
11333 (org-icompleting-read
11334 "State: " (mapcar (lambda(x) (list x))
11335 org-todo-keywords-1)
11336 nil t))
11337 ((eq arg 'right)
11338 (if this
11339 (if tail (car tail) nil)
11340 (car org-todo-keywords-1)))
11341 ((eq arg 'left)
11342 (if (equal member org-todo-keywords-1)
11344 (if this
11345 (nth (- (length org-todo-keywords-1)
11346 (length tail) 2)
11347 org-todo-keywords-1)
11348 (org-last org-todo-keywords-1))))
11349 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11350 (setq arg nil))) ; hack to fall back to cycling
11351 (arg
11352 ;; user or caller requests a specific state
11353 (cond
11354 ((equal arg "") nil)
11355 ((eq arg 'none) nil)
11356 ((eq arg 'done) (or done-word (car org-done-keywords)))
11357 ((eq arg 'nextset)
11358 (or (car (cdr (member head org-todo-heads)))
11359 (car org-todo-heads)))
11360 ((eq arg 'previousset)
11361 (let ((org-todo-heads (reverse org-todo-heads)))
11362 (or (car (cdr (member head org-todo-heads)))
11363 (car org-todo-heads))))
11364 ((car (member arg org-todo-keywords-1)))
11365 ((stringp arg)
11366 (error "State `%s' not valid in this file" arg))
11367 ((nth (1- (prefix-numeric-value arg))
11368 org-todo-keywords-1))))
11369 ((null member) (or head (car org-todo-keywords-1)))
11370 ((equal this final-done-word) nil) ;; -> make empty
11371 ((null tail) nil) ;; -> first entry
11372 ((memq interpret '(type priority))
11373 (if (eq this-command last-command)
11374 (car tail)
11375 (if (> (length tail) 0)
11376 (or done-word (car org-done-keywords))
11377 nil)))
11379 (car tail))))
11380 (org-state (or
11381 (run-hook-with-args-until-success
11382 'org-todo-get-default-hook org-state org-last-state)
11383 org-state))
11384 (next (if org-state (concat " " org-state " ") " "))
11385 (change-plist (list :type 'todo-state-change :from this :to org-state
11386 :position startpos))
11387 dolog now-done-p)
11388 (when org-blocker-hook
11389 (setq org-last-todo-state-is-todo
11390 (not (member this org-done-keywords)))
11391 (unless (save-excursion
11392 (save-match-data
11393 (org-with-wide-buffer
11394 (run-hook-with-args-until-failure
11395 'org-blocker-hook change-plist))))
11396 (if (org-called-interactively-p 'interactive)
11397 (error "TODO state change from %s to %s blocked" this org-state)
11398 ;; fail silently
11399 (message "TODO state change from %s to %s blocked" this org-state)
11400 (throw 'exit nil))))
11401 (store-match-data match-data)
11402 (replace-match next t t)
11403 (unless (pos-visible-in-window-p hl-pos)
11404 (message "TODO state changed to %s" (org-trim next)))
11405 (unless head
11406 (setq head (org-get-todo-sequence-head org-state)
11407 ass (assoc head org-todo-kwd-alist)
11408 interpret (nth 1 ass)
11409 done-word (nth 3 ass)
11410 final-done-word (nth 4 ass)))
11411 (when (memq arg '(nextset previousset))
11412 (message "Keyword-Set %d/%d: %s"
11413 (- (length org-todo-sets) -1
11414 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11415 (length org-todo-sets)
11416 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11417 (setq org-last-todo-state-is-todo
11418 (not (member org-state org-done-keywords)))
11419 (setq now-done-p (and (member org-state org-done-keywords)
11420 (not (member this org-done-keywords))))
11421 (and logging (org-local-logging logging))
11422 (when (and (or org-todo-log-states org-log-done)
11423 (not (eq org-inhibit-logging t))
11424 (not (memq arg '(nextset previousset))))
11425 ;; we need to look at recording a time and note
11426 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11427 (nth 2 (assoc this org-todo-log-states))))
11428 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11429 (setq dolog 'time))
11430 (when (and org-state
11431 (member org-state org-not-done-keywords)
11432 (not (member this org-not-done-keywords)))
11433 ;; This is now a todo state and was not one before
11434 ;; If there was a CLOSED time stamp, get rid of it.
11435 (org-add-planning-info nil nil 'closed))
11436 (when (and now-done-p org-log-done)
11437 ;; It is now done, and it was not done before
11438 (org-add-planning-info 'closed (org-current-effective-time))
11439 (if (and (not dolog) (eq 'note org-log-done))
11440 (org-add-log-setup 'done org-state this 'findpos 'note)))
11441 (when (and org-state dolog)
11442 ;; This is a non-nil state, and we need to log it
11443 (org-add-log-setup 'state org-state this 'findpos dolog)))
11444 ;; Fixup tag positioning
11445 (org-todo-trigger-tag-changes org-state)
11446 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11447 (when org-provide-todo-statistics
11448 (org-update-parent-todo-statistics))
11449 (run-hooks 'org-after-todo-state-change-hook)
11450 (if (and arg (not (member org-state org-done-keywords)))
11451 (setq head (org-get-todo-sequence-head org-state)))
11452 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11453 ;; Do we need to trigger a repeat?
11454 (when now-done-p
11455 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11456 ;; This is for the agenda, take a snapshot of the headline.
11457 (save-match-data
11458 (setq org-agenda-headline-snapshot-before-repeat
11459 (org-get-heading))))
11460 (org-auto-repeat-maybe org-state))
11461 ;; Fixup cursor location if close to the keyword
11462 (if (and (outline-on-heading-p)
11463 (not (bolp))
11464 (save-excursion (beginning-of-line 1)
11465 (looking-at org-todo-line-regexp))
11466 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11467 (progn
11468 (goto-char (or (match-end 2) (match-end 1)))
11469 (and (looking-at " ") (just-one-space))))
11470 (when org-trigger-hook
11471 (save-excursion
11472 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11474 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11475 "Block turning an entry into a TODO, using the hierarchy.
11476 This checks whether the current task should be blocked from state
11477 changes. Such blocking occurs when:
11479 1. The task has children which are not all in a completed state.
11481 2. A task has a parent with the property :ORDERED:, and there
11482 are siblings prior to the current task with incomplete
11483 status.
11485 3. The parent of the task is blocked because it has siblings that should
11486 be done first, or is child of a block grandparent TODO entry."
11488 (if (not org-enforce-todo-dependencies)
11489 t ; if locally turned off don't block
11490 (catch 'dont-block
11491 ;; If this is not a todo state change, or if this entry is already DONE,
11492 ;; do not block
11493 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11494 (member (plist-get change-plist :from)
11495 (cons 'done org-done-keywords))
11496 (member (plist-get change-plist :to)
11497 (cons 'todo org-not-done-keywords))
11498 (not (plist-get change-plist :to)))
11499 (throw 'dont-block t))
11500 ;; If this task has children, and any are undone, it's blocked
11501 (save-excursion
11502 (org-back-to-heading t)
11503 (let ((this-level (funcall outline-level)))
11504 (outline-next-heading)
11505 (let ((child-level (funcall outline-level)))
11506 (while (and (not (eobp))
11507 (> child-level this-level))
11508 ;; this todo has children, check whether they are all
11509 ;; completed
11510 (if (and (not (org-entry-is-done-p))
11511 (org-entry-is-todo-p))
11512 (throw 'dont-block nil))
11513 (outline-next-heading)
11514 (setq child-level (funcall outline-level))))))
11515 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11516 ;; any previous siblings are undone, it's blocked
11517 (save-excursion
11518 (org-back-to-heading t)
11519 (let* ((pos (point))
11520 (parent-pos (and (org-up-heading-safe) (point))))
11521 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11522 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11523 (forward-line 1)
11524 (re-search-forward org-not-done-heading-regexp pos t))
11525 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11526 ;; Search further up the hierarchy, to see if an ancestor is blocked
11527 (while t
11528 (goto-char parent-pos)
11529 (if (not (looking-at org-not-done-heading-regexp))
11530 (throw 'dont-block t)) ; do not block, parent is not a TODO
11531 (setq pos (point))
11532 (setq parent-pos (and (org-up-heading-safe) (point)))
11533 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11534 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11535 (forward-line 1)
11536 (re-search-forward org-not-done-heading-regexp pos t))
11537 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11539 (defcustom org-track-ordered-property-with-tag nil
11540 "Should the ORDERED property also be shown as a tag?
11541 The ORDERED property decides if an entry should require subtasks to be
11542 completed in sequence. Since a property is not very visible, setting
11543 this option means that toggling the ORDERED property with the command
11544 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11545 not relevant for the behavior, but it makes things more visible.
11547 Note that toggling the tag with tags commands will not change the property
11548 and therefore not influence behavior!
11550 This can be t, meaning the tag ORDERED should be used, It can also be a
11551 string to select a different tag for this task."
11552 :group 'org-todo
11553 :type '(choice
11554 (const :tag "No tracking" nil)
11555 (const :tag "Track with ORDERED tag" t)
11556 (string :tag "Use other tag")))
11558 (defun org-toggle-ordered-property ()
11559 "Toggle the ORDERED property of the current entry.
11560 For better visibility, you can track the value of this property with a tag.
11561 See variable `org-track-ordered-property-with-tag'."
11562 (interactive)
11563 (let* ((t1 org-track-ordered-property-with-tag)
11564 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11565 (save-excursion
11566 (org-back-to-heading)
11567 (if (org-entry-get nil "ORDERED")
11568 (progn
11569 (org-delete-property "ORDERED")
11570 (and tag (org-toggle-tag tag 'off))
11571 (message "Subtasks can be completed in arbitrary order"))
11572 (org-entry-put nil "ORDERED" "t")
11573 (and tag (org-toggle-tag tag 'on))
11574 (message "Subtasks must be completed in sequence")))))
11576 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11577 (defun org-block-todo-from-checkboxes (change-plist)
11578 "Block turning an entry into a TODO, using checkboxes.
11579 This checks whether the current task should be blocked from state
11580 changes because there are unchecked boxes in this entry."
11581 (if (not org-enforce-todo-checkbox-dependencies)
11582 t ; if locally turned off don't block
11583 (catch 'dont-block
11584 ;; If this is not a todo state change, or if this entry is already DONE,
11585 ;; do not block
11586 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11587 (member (plist-get change-plist :from)
11588 (cons 'done org-done-keywords))
11589 (member (plist-get change-plist :to)
11590 (cons 'todo org-not-done-keywords))
11591 (not (plist-get change-plist :to)))
11592 (throw 'dont-block t))
11593 ;; If this task has checkboxes that are not checked, it's blocked
11594 (save-excursion
11595 (org-back-to-heading t)
11596 (let ((beg (point)) end)
11597 (outline-next-heading)
11598 (setq end (point))
11599 (goto-char beg)
11600 (if (org-list-search-forward
11601 (concat (org-item-beginning-re)
11602 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11603 "\\[[- ]\\]")
11604 end t)
11605 (progn
11606 (if (boundp 'org-blocked-by-checkboxes)
11607 (setq org-blocked-by-checkboxes t))
11608 (throw 'dont-block nil)))))
11609 t))) ; do not block
11611 (defun org-entry-blocked-p ()
11612 "Is the current entry blocked?"
11613 (if (org-entry-get nil "NOBLOCKING")
11614 nil ;; Never block this entry
11615 (not
11616 (run-hook-with-args-until-failure
11617 'org-blocker-hook
11618 (list :type 'todo-state-change
11619 :position (point)
11620 :from 'todo
11621 :to 'done)))))
11623 (defun org-update-statistics-cookies (all)
11624 "Update the statistics cookie, either from TODO or from checkboxes.
11625 This should be called with the cursor in a line with a statistics cookie."
11626 (interactive "P")
11627 (if all
11628 (progn
11629 (org-update-checkbox-count 'all)
11630 (org-map-entries 'org-update-parent-todo-statistics))
11631 (if (not (org-at-heading-p))
11632 (org-update-checkbox-count)
11633 (let ((pos (move-marker (make-marker) (point)))
11634 end l1 l2)
11635 (ignore-errors (org-back-to-heading t))
11636 (if (not (org-at-heading-p))
11637 (org-update-checkbox-count)
11638 (setq l1 (org-outline-level))
11639 (setq end (save-excursion
11640 (outline-next-heading)
11641 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11642 (point)))
11643 (if (and (save-excursion
11644 (re-search-forward
11645 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11646 (not (save-excursion (re-search-forward
11647 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11648 (org-update-checkbox-count)
11649 (if (and l2 (> l2 l1))
11650 (progn
11651 (goto-char end)
11652 (org-update-parent-todo-statistics))
11653 (goto-char pos)
11654 (beginning-of-line 1)
11655 (while (re-search-forward
11656 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11657 (point-at-eol) t)
11658 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11659 (goto-char pos)
11660 (move-marker pos nil)))))
11662 (defvar org-entry-property-inherited-from) ;; defined below
11663 (defun org-update-parent-todo-statistics ()
11664 "Update any statistics cookie in the parent of the current headline.
11665 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11666 the entire subtree and this will travel up the hierarchy and update
11667 statistics everywhere."
11668 (let* ((prop (save-excursion (org-up-heading-safe)
11669 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11670 (recursive (or (not org-hierarchical-todo-statistics)
11671 (and prop (string-match "\\<recursive\\>" prop))))
11672 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11674 (first t)
11675 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11676 level ltoggle l1 new ndel
11677 (cnt-all 0) (cnt-done 0) is-percent kwd
11678 checkbox-beg ov ovs ove cookie-present)
11679 (catch 'exit
11680 (save-excursion
11681 (beginning-of-line 1)
11682 (setq ltoggle (funcall outline-level))
11683 ;; Three situations are to consider:
11685 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11686 ;; to the top-level ancestor on the headline;
11688 ;; 2. If parent has "recursive" property, repeat up to the
11689 ;; headline setting that property, taking inheritance into
11690 ;; account;
11692 ;; 3. Else, move up to direct parent and proceed only once.
11693 (while (and (setq level (org-up-heading-safe))
11694 (or recursive first)
11695 (>= (point) lim))
11696 (setq first nil cookie-present nil)
11697 (unless (and level
11698 (not (string-match
11699 "\\<checkbox\\>"
11700 (downcase (or (org-entry-get nil "COOKIE_DATA")
11701 "")))))
11702 (throw 'exit nil))
11703 (while (re-search-forward box-re (point-at-eol) t)
11704 (setq cnt-all 0 cnt-done 0 cookie-present t)
11705 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11706 (save-match-data
11707 (unless (outline-next-heading) (throw 'exit nil))
11708 (while (and (looking-at org-complex-heading-regexp)
11709 (> (setq l1 (length (match-string 1))) level))
11710 (setq kwd (and (or recursive (= l1 ltoggle))
11711 (match-string 2)))
11712 (if (or (eq org-provide-todo-statistics 'all-headlines)
11713 (and (listp org-provide-todo-statistics)
11714 (or (member kwd org-provide-todo-statistics)
11715 (member kwd org-done-keywords))))
11716 (setq cnt-all (1+ cnt-all))
11717 (if (eq org-provide-todo-statistics t)
11718 (and kwd (setq cnt-all (1+ cnt-all)))))
11719 (and (member kwd org-done-keywords)
11720 (setq cnt-done (1+ cnt-done)))
11721 (outline-next-heading)))
11722 (setq new
11723 (if is-percent
11724 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11725 (format "[%d/%d]" cnt-done cnt-all))
11726 ndel (- (match-end 0) checkbox-beg))
11727 ;; handle overlays when updating cookie from column view
11728 (when (setq ov (car (overlays-at checkbox-beg)))
11729 (setq ovs (overlay-start ov) ove (overlay-end ov))
11730 (delete-overlay ov))
11731 (goto-char checkbox-beg)
11732 (insert new)
11733 (delete-region (point) (+ (point) ndel))
11734 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11735 (when ov (move-overlay ov ovs ove)))
11736 (when cookie-present
11737 (run-hook-with-args 'org-after-todo-statistics-hook
11738 cnt-done (- cnt-all cnt-done))))))
11739 (run-hooks 'org-todo-statistics-hook)))
11741 (defvar org-after-todo-statistics-hook nil
11742 "Hook that is called after a TODO statistics cookie has been updated.
11743 Each function is called with two arguments: the number of not-done entries
11744 and the number of done entries.
11746 For example, the following function, when added to this hook, will switch
11747 an entry to DONE when all children are done, and back to TODO when new
11748 entries are set to a TODO status. Note that this hook is only called
11749 when there is a statistics cookie in the headline!
11751 (defun org-summary-todo (n-done n-not-done)
11752 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11753 (let (org-log-done org-log-states) ; turn off logging
11754 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11757 (defvar org-todo-statistics-hook nil
11758 "Hook that is run whenever Org thinks TODO statistics should be updated.
11759 This hook runs even if there is no statistics cookie present, in which case
11760 `org-after-todo-statistics-hook' would not run.")
11762 (defun org-todo-trigger-tag-changes (state)
11763 "Apply the changes defined in `org-todo-state-tags-triggers'."
11764 (let ((l org-todo-state-tags-triggers)
11765 changes)
11766 (when (or (not state) (equal state ""))
11767 (setq changes (append changes (cdr (assoc "" l)))))
11768 (when (and (stringp state) (> (length state) 0))
11769 (setq changes (append changes (cdr (assoc state l)))))
11770 (when (member state org-not-done-keywords)
11771 (setq changes (append changes (cdr (assoc 'todo l)))))
11772 (when (member state org-done-keywords)
11773 (setq changes (append changes (cdr (assoc 'done l)))))
11774 (dolist (c changes)
11775 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11777 (defun org-local-logging (value)
11778 "Get logging settings from a property VALUE."
11779 (let* (words w a)
11780 ;; directly set the variables, they are already local.
11781 (setq org-log-done nil
11782 org-log-repeat nil
11783 org-todo-log-states nil)
11784 (setq words (org-split-string value))
11785 (while (setq w (pop words))
11786 (cond
11787 ((setq a (assoc w org-startup-options))
11788 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11789 (set (nth 1 a) (nth 2 a))))
11790 ((setq a (org-extract-log-state-settings w))
11791 (and (member (car a) org-todo-keywords-1)
11792 (push a org-todo-log-states)))))))
11794 (defun org-get-todo-sequence-head (kwd)
11795 "Return the head of the TODO sequence to which KWD belongs.
11796 If KWD is not set, check if there is a text property remembering the
11797 right sequence."
11798 (let (p)
11799 (cond
11800 ((not kwd)
11801 (or (get-text-property (point-at-bol) 'org-todo-head)
11802 (progn
11803 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11804 nil (point-at-eol)))
11805 (get-text-property p 'org-todo-head))))
11806 ((not (member kwd org-todo-keywords-1))
11807 (car org-todo-keywords-1))
11808 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11810 (defun org-fast-todo-selection ()
11811 "Fast TODO keyword selection with single keys.
11812 Returns the new TODO keyword, or nil if no state change should occur."
11813 (let* ((fulltable org-todo-key-alist)
11814 (done-keywords org-done-keywords) ;; needed for the faces.
11815 (maxlen (apply 'max (mapcar
11816 (lambda (x)
11817 (if (stringp (car x)) (string-width (car x)) 0))
11818 fulltable)))
11819 (expert nil)
11820 (fwidth (+ maxlen 3 1 3))
11821 (ncol (/ (- (window-width) 4) fwidth))
11822 tg cnt e c tbl
11823 groups ingroup)
11824 (save-excursion
11825 (save-window-excursion
11826 (if expert
11827 (set-buffer (get-buffer-create " *Org todo*"))
11828 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11829 (erase-buffer)
11830 (org-set-local 'org-done-keywords done-keywords)
11831 (setq tbl fulltable cnt 0)
11832 (while (setq e (pop tbl))
11833 (cond
11834 ((equal e '(:startgroup))
11835 (push '() groups) (setq ingroup t)
11836 (when (not (= cnt 0))
11837 (setq cnt 0)
11838 (insert "\n"))
11839 (insert "{ "))
11840 ((equal e '(:endgroup))
11841 (setq ingroup nil cnt 0)
11842 (insert "}\n"))
11843 ((equal e '(:newline))
11844 (when (not (= cnt 0))
11845 (setq cnt 0)
11846 (insert "\n")
11847 (setq e (car tbl))
11848 (while (equal (car tbl) '(:newline))
11849 (insert "\n")
11850 (setq tbl (cdr tbl)))))
11852 (setq tg (car e) c (cdr e))
11853 (if ingroup (push tg (car groups)))
11854 (setq tg (org-add-props tg nil 'face
11855 (org-get-todo-face tg)))
11856 (if (and (= cnt 0) (not ingroup)) (insert " "))
11857 (insert "[" c "] " tg (make-string
11858 (- fwidth 4 (length tg)) ?\ ))
11859 (when (= (setq cnt (1+ cnt)) ncol)
11860 (insert "\n")
11861 (if ingroup (insert " "))
11862 (setq cnt 0)))))
11863 (insert "\n")
11864 (goto-char (point-min))
11865 (if (not expert) (org-fit-window-to-buffer))
11866 (message "[a-z..]:Set [SPC]:clear")
11867 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11868 (cond
11869 ((or (= c ?\C-g)
11870 (and (= c ?q) (not (rassoc c fulltable))))
11871 (setq quit-flag t))
11872 ((= c ?\ ) nil)
11873 ((setq e (rassoc c fulltable) tg (car e))
11875 (t (setq quit-flag t)))))))
11877 (defun org-entry-is-todo-p ()
11878 (member (org-get-todo-state) org-not-done-keywords))
11880 (defun org-entry-is-done-p ()
11881 (member (org-get-todo-state) org-done-keywords))
11883 (defun org-get-todo-state ()
11884 (save-excursion
11885 (org-back-to-heading t)
11886 (and (looking-at org-todo-line-regexp)
11887 (match-end 2)
11888 (match-string 2))))
11890 (defun org-at-date-range-p (&optional inactive-ok)
11891 "Is the cursor inside a date range?"
11892 (interactive)
11893 (save-excursion
11894 (catch 'exit
11895 (let ((pos (point)))
11896 (skip-chars-backward "^[<\r\n")
11897 (skip-chars-backward "<[")
11898 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11899 (>= (match-end 0) pos)
11900 (throw 'exit t))
11901 (skip-chars-backward "^<[\r\n")
11902 (skip-chars-backward "<[")
11903 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11904 (>= (match-end 0) pos)
11905 (throw 'exit t)))
11906 nil)))
11908 (defun org-get-repeat (&optional tagline)
11909 "Check if there is a deadline/schedule with repeater in this entry."
11910 (save-match-data
11911 (save-excursion
11912 (org-back-to-heading t)
11913 (and (re-search-forward (if tagline
11914 (concat tagline "\\s-*" org-repeat-re)
11915 org-repeat-re)
11916 (org-entry-end-position) t)
11917 (match-string-no-properties 1)))))
11919 (defvar org-last-changed-timestamp)
11920 (defvar org-last-inserted-timestamp)
11921 (defvar org-log-post-message)
11922 (defvar org-log-note-purpose)
11923 (defvar org-log-note-how)
11924 (defvar org-log-note-extra)
11925 (defun org-auto-repeat-maybe (done-word)
11926 "Check if the current headline contains a repeated deadline/schedule.
11927 If yes, set TODO state back to what it was and change the base date
11928 of repeating deadline/scheduled time stamps to new date.
11929 This function is run automatically after each state change to a DONE state."
11930 ;; last-state is dynamically scoped into this function
11931 (let* ((repeat (org-get-repeat))
11932 (aa (assoc org-last-state org-todo-kwd-alist))
11933 (interpret (nth 1 aa))
11934 (head (nth 2 aa))
11935 (whata '(("d" . day) ("m" . month) ("y" . year)))
11936 (msg "Entry repeats: ")
11937 (org-log-done nil)
11938 (org-todo-log-states nil)
11939 re type n what ts time to-state)
11940 (when repeat
11941 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11942 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11943 org-todo-repeat-to-state))
11944 (unless (and to-state (member to-state org-todo-keywords-1))
11945 (setq to-state (if (eq interpret 'type) org-last-state head)))
11946 (org-todo to-state)
11947 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11948 (org-entry-put nil "LAST_REPEAT" (format-time-string
11949 (org-time-stamp-format t t))))
11950 (when org-log-repeat
11951 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11952 (memq 'org-add-log-note post-command-hook))
11953 ;; OK, we are already setup for some record
11954 (if (eq org-log-repeat 'note)
11955 ;; make sure we take a note, not only a time stamp
11956 (setq org-log-note-how 'note))
11957 ;; Set up for taking a record
11958 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11959 org-last-state
11960 'findpos org-log-repeat)))
11961 (org-back-to-heading t)
11962 (org-add-planning-info nil nil 'closed)
11963 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11964 org-deadline-time-regexp "\\)\\|\\("
11965 org-ts-regexp "\\)"))
11966 (while (re-search-forward
11967 re (save-excursion (outline-next-heading) (point)) t)
11968 (setq type (if (match-end 1) org-scheduled-string
11969 (if (match-end 3) org-deadline-string "Plain:"))
11970 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11971 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11972 (setq n (string-to-number (match-string 2 ts))
11973 what (match-string 3 ts))
11974 (if (equal what "w") (setq n (* n 7) what "d"))
11975 ;; Preparation, see if we need to modify the start date for the change
11976 (when (match-end 1)
11977 (setq time (save-match-data (org-time-string-to-time ts)))
11978 (cond
11979 ((equal (match-string 1 ts) ".")
11980 ;; Shift starting date to today
11981 (org-timestamp-change
11982 (- (org-today) (time-to-days time))
11983 'day))
11984 ((equal (match-string 1 ts) "+")
11985 (let ((nshiftmax 10) (nshift 0))
11986 (while (or (= nshift 0)
11987 (<= (time-to-days time)
11988 (time-to-days (current-time))))
11989 (when (= (incf nshift) nshiftmax)
11990 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11991 (error "Abort")))
11992 (org-timestamp-change n (cdr (assoc what whata)))
11993 (org-at-timestamp-p t)
11994 (setq ts (match-string 1))
11995 (setq time (save-match-data (org-time-string-to-time ts)))))
11996 (org-timestamp-change (- n) (cdr (assoc what whata)))
11997 ;; rematch, so that we have everything in place for the real shift
11998 (org-at-timestamp-p t)
11999 (setq ts (match-string 1))
12000 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
12001 (org-timestamp-change n (cdr (assoc what whata)))
12002 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12003 (setq org-log-post-message msg)
12004 (message "%s" msg))))
12006 (defun org-show-todo-tree (arg)
12007 "Make a compact tree which shows all headlines marked with TODO.
12008 The tree will show the lines where the regexp matches, and all higher
12009 headlines above the match.
12010 With a \\[universal-argument] prefix, prompt for a regexp to match.
12011 With a numeric prefix N, construct a sparse tree for the Nth element
12012 of `org-todo-keywords-1'."
12013 (interactive "P")
12014 (let ((case-fold-search nil)
12015 (kwd-re
12016 (cond ((null arg) org-not-done-regexp)
12017 ((equal arg '(4))
12018 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12019 (mapcar 'list org-todo-keywords-1))))
12020 (concat "\\("
12021 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12022 "\\)\\>")))
12023 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12024 (regexp-quote (nth (1- (prefix-numeric-value arg))
12025 org-todo-keywords-1)))
12026 (t (error "Invalid prefix argument: %s" arg)))))
12027 (message "%d TODO entries found"
12028 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12030 (defun org-deadline (&optional remove time)
12031 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12032 With argument REMOVE, remove any deadline from the item.
12033 With argument TIME, set the deadline at the corresponding date. TIME
12034 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12035 (interactive "P")
12036 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12037 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12038 'region-start-level 'region))
12039 org-loop-over-headlines-in-active-region)
12040 (org-map-entries
12041 `(org-deadline ',remove ,time)
12042 org-loop-over-headlines-in-active-region
12043 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12044 (let* ((old-date (org-entry-get nil "DEADLINE"))
12045 (repeater (and old-date
12046 (string-match
12047 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12048 old-date)
12049 (match-string 1 old-date))))
12050 (if remove
12051 (progn
12052 (when (and old-date org-log-redeadline)
12053 (org-add-log-setup 'deldeadline nil old-date 'findpos
12054 org-log-redeadline))
12055 (org-remove-timestamp-with-keyword org-deadline-string)
12056 (message "Item no longer has a deadline."))
12057 (org-add-planning-info 'deadline time 'closed)
12058 (when (and old-date org-log-redeadline
12059 (not (equal old-date
12060 (substring org-last-inserted-timestamp 1 -1))))
12061 (org-add-log-setup 'redeadline nil old-date 'findpos
12062 org-log-redeadline))
12063 (when repeater
12064 (save-excursion
12065 (org-back-to-heading t)
12066 (when (re-search-forward (concat org-deadline-string " "
12067 org-last-inserted-timestamp)
12068 (save-excursion
12069 (outline-next-heading) (point)) t)
12070 (goto-char (1- (match-end 0)))
12071 (insert " " repeater)
12072 (setq org-last-inserted-timestamp
12073 (concat (substring org-last-inserted-timestamp 0 -1)
12074 " " repeater
12075 (substring org-last-inserted-timestamp -1))))))
12076 (message "Deadline on %s" org-last-inserted-timestamp)))))
12078 (defun org-schedule (&optional remove time)
12079 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12080 With argument REMOVE, remove any scheduling date from the item.
12081 With argument TIME, scheduled at the corresponding date. TIME can
12082 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12083 (interactive "P")
12084 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12085 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12086 'region-start-level 'region))
12087 org-loop-over-headlines-in-active-region)
12088 (org-map-entries
12089 `(org-schedule ',remove ,time)
12090 org-loop-over-headlines-in-active-region
12091 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12092 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12093 (repeater (and old-date
12094 (string-match
12095 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12096 old-date)
12097 (match-string 1 old-date))))
12098 (if remove
12099 (progn
12100 (when (and old-date org-log-reschedule)
12101 (org-add-log-setup 'delschedule nil old-date 'findpos
12102 org-log-reschedule))
12103 (org-remove-timestamp-with-keyword org-scheduled-string)
12104 (message "Item is no longer scheduled."))
12105 (org-add-planning-info 'scheduled time 'closed)
12106 (when (and old-date org-log-reschedule
12107 (not (equal old-date
12108 (substring org-last-inserted-timestamp 1 -1))))
12109 (org-add-log-setup 'reschedule nil old-date 'findpos
12110 org-log-reschedule))
12111 (when repeater
12112 (save-excursion
12113 (org-back-to-heading t)
12114 (when (re-search-forward (concat org-scheduled-string " "
12115 org-last-inserted-timestamp)
12116 (save-excursion
12117 (outline-next-heading) (point)) t)
12118 (goto-char (1- (match-end 0)))
12119 (insert " " repeater)
12120 (setq org-last-inserted-timestamp
12121 (concat (substring org-last-inserted-timestamp 0 -1)
12122 " " repeater
12123 (substring org-last-inserted-timestamp -1))))))
12124 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12126 (defun org-get-scheduled-time (pom &optional inherit)
12127 "Get the scheduled time as a time tuple, of a format suitable
12128 for calling org-schedule with, or if there is no scheduling,
12129 returns nil."
12130 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12131 (when time
12132 (apply 'encode-time (org-parse-time-string time)))))
12134 (defun org-get-deadline-time (pom &optional inherit)
12135 "Get the deadline as a time tuple, of a format suitable for
12136 calling org-deadline with, or if there is no scheduling, returns
12137 nil."
12138 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12139 (when time
12140 (apply 'encode-time (org-parse-time-string time)))))
12142 (defun org-remove-timestamp-with-keyword (keyword)
12143 "Remove all time stamps with KEYWORD in the current entry."
12144 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12145 beg)
12146 (save-excursion
12147 (org-back-to-heading t)
12148 (setq beg (point))
12149 (outline-next-heading)
12150 (while (re-search-backward re beg t)
12151 (replace-match "")
12152 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12153 (equal (char-before) ?\ ))
12154 (backward-delete-char 1)
12155 (if (string-match "^[ \t]*$" (buffer-substring
12156 (point-at-bol) (point-at-eol)))
12157 (delete-region (point-at-bol)
12158 (min (point-max) (1+ (point-at-eol))))))))))
12160 (defun org-add-planning-info (what &optional time &rest remove)
12161 "Insert new timestamp with keyword in the line directly after the headline.
12162 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12163 If non is given, the user is prompted for a date.
12164 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12165 be removed."
12166 (interactive)
12167 (let (org-time-was-given org-end-time-was-given ts
12168 end default-time default-input)
12170 (catch 'exit
12171 (when (and (memq what '(scheduled deadline))
12172 (or (not time)
12173 (and (stringp time)
12174 (string-match "^[-+]+[0-9]" time))))
12175 ;; Try to get a default date/time from existing timestamp
12176 (save-excursion
12177 (org-back-to-heading t)
12178 (setq end (save-excursion (outline-next-heading) (point)))
12179 (when (re-search-forward (if (eq what 'scheduled)
12180 org-scheduled-time-regexp
12181 org-deadline-time-regexp)
12182 end t)
12183 (setq ts (match-string 1)
12184 default-time
12185 (apply 'encode-time (org-parse-time-string ts))
12186 default-input (and ts (org-get-compact-tod ts))))))
12187 (when what
12188 (setq time
12189 (if (stringp time)
12190 ;; This is a string (relative or absolute), set proper date
12191 (apply 'encode-time
12192 (org-read-date-analyze
12193 time default-time (decode-time default-time)))
12194 ;; If necessary, get the time from the user
12195 (or time (org-read-date nil 'to-time nil nil
12196 default-time default-input)))))
12198 (when (and org-insert-labeled-timestamps-at-point
12199 (member what '(scheduled deadline)))
12200 (insert
12201 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12202 (org-insert-time-stamp time org-time-was-given
12203 nil nil nil (list org-end-time-was-given))
12204 (setq what nil))
12205 (save-excursion
12206 (save-restriction
12207 (let (col list elt ts buffer-invisibility-spec)
12208 (org-back-to-heading t)
12209 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12210 (goto-char (match-end 1))
12211 (setq col (current-column))
12212 (goto-char (match-end 0))
12213 (if (eobp) (insert "\n") (forward-char 1))
12214 (when (and (not what)
12215 (not (looking-at
12216 (concat "[ \t]*"
12217 org-keyword-time-not-clock-regexp))))
12218 ;; Nothing to add, nothing to remove...... :-)
12219 (throw 'exit nil))
12220 (if (and (not (looking-at org-outline-regexp))
12221 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12222 "[^\r\n]*"))
12223 (not (equal (match-string 1) org-clock-string)))
12224 (narrow-to-region (match-beginning 0) (match-end 0))
12225 (insert-before-markers "\n")
12226 (backward-char 1)
12227 (narrow-to-region (point) (point))
12228 (and org-adapt-indentation (org-indent-to-column col)))
12229 ;; Check if we have to remove something.
12230 (setq list (cons what remove))
12231 (while list
12232 (setq elt (pop list))
12233 (when (or (and (eq elt 'scheduled)
12234 (re-search-forward org-scheduled-time-regexp nil t))
12235 (and (eq elt 'deadline)
12236 (re-search-forward org-deadline-time-regexp nil t))
12237 (and (eq elt 'closed)
12238 (re-search-forward org-closed-time-regexp nil t)))
12239 (replace-match "")
12240 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12241 (and (looking-at "[ \t]+") (replace-match ""))
12242 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12243 (when what
12244 (insert
12245 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12246 (cond ((eq what 'scheduled) org-scheduled-string)
12247 ((eq what 'deadline) org-deadline-string)
12248 ((eq what 'closed) org-closed-string))
12249 " ")
12250 (setq ts (org-insert-time-stamp
12251 time
12252 (or org-time-was-given
12253 (and (eq what 'closed) org-log-done-with-time))
12254 (eq what 'closed)
12255 nil nil (list org-end-time-was-given)))
12256 (insert
12257 (if (not (or (bolp) (eq (char-before) ?\ )
12258 (memq (char-after) '(32 10))
12259 (eobp))) " " ""))
12260 (end-of-line 1))
12261 (goto-char (point-min))
12262 (widen)
12263 (if (and (looking-at "[ \t]*\n")
12264 (equal (char-before) ?\n))
12265 (delete-region (1- (point)) (point-at-eol)))
12266 ts))))))
12268 (defvar org-log-note-marker (make-marker))
12269 (defvar org-log-note-purpose nil)
12270 (defvar org-log-note-state nil)
12271 (defvar org-log-note-previous-state nil)
12272 (defvar org-log-note-how nil)
12273 (defvar org-log-note-extra nil)
12274 (defvar org-log-note-window-configuration nil)
12275 (defvar org-log-note-return-to (make-marker))
12276 (defvar org-log-note-effective-time nil
12277 "Remembered current time so that dynamically scoped
12278 `org-extend-today-until' affects tha timestamps in state change
12279 log")
12281 (defvar org-log-post-message nil
12282 "Message to be displayed after a log note has been stored.
12283 The auto-repeater uses this.")
12285 (defun org-add-note ()
12286 "Add a note to the current entry.
12287 This is done in the same way as adding a state change note."
12288 (interactive)
12289 (org-add-log-setup 'note nil nil 'findpos nil))
12291 (defvar org-property-end-re)
12292 (defun org-add-log-setup (&optional purpose state prev-state
12293 findpos how extra)
12294 "Set up the post command hook to take a note.
12295 If this is about to TODO state change, the new state is expected in STATE.
12296 When FINDPOS is non-nil, find the correct position for the note in
12297 the current entry. If not, assume that it can be inserted at point.
12298 HOW is an indicator what kind of note should be created.
12299 EXTRA is additional text that will be inserted into the notes buffer."
12300 (let* ((org-log-into-drawer (org-log-into-drawer))
12301 (drawer (cond ((stringp org-log-into-drawer)
12302 org-log-into-drawer)
12303 (org-log-into-drawer "LOGBOOK")
12304 (t nil))))
12305 (save-restriction
12306 (save-excursion
12307 (when findpos
12308 (org-back-to-heading t)
12309 (narrow-to-region (point) (save-excursion
12310 (outline-next-heading) (point)))
12311 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12312 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12313 "[^\r\n]*\\)?"))
12314 (goto-char (match-end 0))
12315 (cond
12316 (drawer
12317 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12318 nil t)
12319 (progn
12320 (goto-char (match-end 0))
12321 (or org-log-states-order-reversed
12322 (and (re-search-forward org-property-end-re nil t)
12323 (goto-char (1- (match-beginning 0))))))
12324 (insert "\n:" drawer ":\n:END:")
12325 (beginning-of-line 0)
12326 (org-indent-line-function)
12327 (beginning-of-line 2)
12328 (org-indent-line-function)
12329 (end-of-line 0)))
12330 ((and org-log-state-notes-insert-after-drawers
12331 (save-excursion
12332 (forward-line) (looking-at org-drawer-regexp)))
12333 (forward-line)
12334 (while (looking-at org-drawer-regexp)
12335 (goto-char (match-end 0))
12336 (re-search-forward org-property-end-re (point-max) t)
12337 (forward-line))
12338 (forward-line -1)))
12339 (unless org-log-states-order-reversed
12340 (and (= (char-after) ?\n) (forward-char 1))
12341 (org-skip-over-state-notes)
12342 (skip-chars-backward " \t\n\r")))
12343 (move-marker org-log-note-marker (point))
12344 (setq org-log-note-purpose purpose
12345 org-log-note-state state
12346 org-log-note-previous-state prev-state
12347 org-log-note-how how
12348 org-log-note-extra extra
12349 org-log-note-effective-time (org-current-effective-time))
12350 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12352 (defun org-skip-over-state-notes ()
12353 "Skip past the list of State notes in an entry."
12354 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12355 (when (ignore-errors (goto-char (org-in-item-p)))
12356 (let* ((struct (org-list-struct))
12357 (prevs (org-list-prevs-alist struct)))
12358 (while (looking-at "[ \t]*- State")
12359 (goto-char (or (org-list-get-next-item (point) struct prevs)
12360 (org-list-get-item-end (point) struct)))))))
12362 (defun org-add-log-note (&optional purpose)
12363 "Pop up a window for taking a note, and add this note later at point."
12364 (remove-hook 'post-command-hook 'org-add-log-note)
12365 (setq org-log-note-window-configuration (current-window-configuration))
12366 (delete-other-windows)
12367 (move-marker org-log-note-return-to (point))
12368 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12369 (goto-char org-log-note-marker)
12370 (org-switch-to-buffer-other-window "*Org Note*")
12371 (erase-buffer)
12372 (if (memq org-log-note-how '(time state))
12373 (let (current-prefix-arg) (org-store-log-note))
12374 (let ((org-inhibit-startup t)) (org-mode))
12375 (insert (format "# Insert note for %s.
12376 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12377 (cond
12378 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12379 ((eq org-log-note-purpose 'done) "closed todo item")
12380 ((eq org-log-note-purpose 'state)
12381 (format "state change from \"%s\" to \"%s\""
12382 (or org-log-note-previous-state "")
12383 (or org-log-note-state "")))
12384 ((eq org-log-note-purpose 'reschedule)
12385 "rescheduling")
12386 ((eq org-log-note-purpose 'delschedule)
12387 "no longer scheduled")
12388 ((eq org-log-note-purpose 'redeadline)
12389 "changing deadline")
12390 ((eq org-log-note-purpose 'deldeadline)
12391 "removing deadline")
12392 ((eq org-log-note-purpose 'refile)
12393 "refiling")
12394 ((eq org-log-note-purpose 'note)
12395 "this entry")
12396 (t (error "This should not happen")))))
12397 (if org-log-note-extra (insert org-log-note-extra))
12398 (org-set-local 'org-finish-function 'org-store-log-note)
12399 (run-hooks 'org-log-buffer-setup-hook)))
12401 (defvar org-note-abort nil) ; dynamically scoped
12402 (defun org-store-log-note ()
12403 "Finish taking a log note, and insert it to where it belongs."
12404 (let ((txt (buffer-string))
12405 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12406 lines ind bul)
12407 (kill-buffer (current-buffer))
12408 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12409 (setq txt (replace-match "" t t txt)))
12410 (if (string-match "\\s-+\\'" txt)
12411 (setq txt (replace-match "" t t txt)))
12412 (setq lines (org-split-string txt "\n"))
12413 (when (and note (string-match "\\S-" note))
12414 (setq note
12415 (org-replace-escapes
12416 note
12417 (list (cons "%u" (user-login-name))
12418 (cons "%U" user-full-name)
12419 (cons "%t" (format-time-string
12420 (org-time-stamp-format 'long 'inactive)
12421 org-log-note-effective-time))
12422 (cons "%T" (format-time-string
12423 (org-time-stamp-format 'long nil)
12424 org-log-note-effective-time))
12425 (cons "%d" (format-time-string
12426 (org-time-stamp-format nil 'inactive)
12427 org-log-note-effective-time))
12428 (cons "%D" (format-time-string
12429 (org-time-stamp-format nil nil)
12430 org-log-note-effective-time))
12431 (cons "%s" (if org-log-note-state
12432 (concat "\"" org-log-note-state "\"")
12433 ""))
12434 (cons "%S" (if org-log-note-previous-state
12435 (concat "\"" org-log-note-previous-state "\"")
12436 "\"\"")))))
12437 (if lines (setq note (concat note " \\\\")))
12438 (push note lines))
12439 (when (or current-prefix-arg org-note-abort)
12440 (when org-log-into-drawer
12441 (org-remove-empty-drawer-at
12442 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12443 org-log-note-marker))
12444 (setq lines nil))
12445 (when lines
12446 (with-current-buffer (marker-buffer org-log-note-marker)
12447 (save-excursion
12448 (goto-char org-log-note-marker)
12449 (move-marker org-log-note-marker nil)
12450 (end-of-line 1)
12451 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12452 (setq ind (save-excursion
12453 (if (ignore-errors (goto-char (org-in-item-p)))
12454 (let ((struct (org-list-struct)))
12455 (org-list-get-ind
12456 (org-list-get-top-point struct) struct))
12457 (skip-chars-backward " \r\t\n")
12458 (cond
12459 ((and (org-at-heading-p)
12460 org-adapt-indentation)
12461 (1+ (org-current-level)))
12462 ((org-at-heading-p) 0)
12463 (t (org-get-indentation))))))
12464 (setq bul (org-list-bullet-string "-"))
12465 (org-indent-line-to ind)
12466 (insert bul (pop lines))
12467 (let ((ind-body (+ (length bul) ind)))
12468 (while lines
12469 (insert "\n")
12470 (org-indent-line-to ind-body)
12471 (insert (pop lines))))
12472 (message "Note stored")
12473 (org-back-to-heading t)
12474 (org-cycle-hide-drawers 'children)))))
12475 (set-window-configuration org-log-note-window-configuration)
12476 (with-current-buffer (marker-buffer org-log-note-return-to)
12477 (goto-char org-log-note-return-to))
12478 (move-marker org-log-note-return-to nil)
12479 (and org-log-post-message (message "%s" org-log-post-message)))
12481 (defun org-remove-empty-drawer-at (drawer pos)
12482 "Remove an empty drawer DRAWER at position POS.
12483 POS may also be a marker."
12484 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12485 (save-excursion
12486 (save-restriction
12487 (widen)
12488 (goto-char pos)
12489 (if (org-in-regexp
12490 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12491 (replace-match ""))))))
12493 (defun org-sparse-tree (&optional arg)
12494 "Create a sparse tree, prompt for the details.
12495 This command can create sparse trees. You first need to select the type
12496 of match used to create the tree:
12498 t Show all TODO entries.
12499 T Show entries with a specific TODO keyword.
12500 m Show entries selected by a tags/property match.
12501 p Enter a property name and its value (both with completion on existing
12502 names/values) and show entries with that property.
12503 r Show entries matching a regular expression (`/' can be used as well)
12504 d Show deadlines due within `org-deadline-warning-days'.
12505 b Show deadlines and scheduled items before a date.
12506 a Show deadlines and scheduled items after a date."
12507 (interactive "P")
12508 (let (ans kwd value)
12509 (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")
12510 (setq ans (read-char-exclusive))
12511 (cond
12512 ((equal ans ?d)
12513 (call-interactively 'org-check-deadlines))
12514 ((equal ans ?b)
12515 (call-interactively 'org-check-before-date))
12516 ((equal ans ?a)
12517 (call-interactively 'org-check-after-date))
12518 ((equal ans ?D)
12519 (call-interactively 'org-check-dates-range))
12520 ((equal ans ?t)
12521 (org-show-todo-tree nil))
12522 ((equal ans ?T)
12523 (org-show-todo-tree '(4)))
12524 ((member ans '(?T ?m))
12525 (call-interactively 'org-match-sparse-tree))
12526 ((member ans '(?p ?P))
12527 (setq kwd (org-icompleting-read "Property: "
12528 (mapcar 'list (org-buffer-property-keys))))
12529 (setq value (org-icompleting-read "Value: "
12530 (mapcar 'list (org-property-values kwd))))
12531 (unless (string-match "\\`{.*}\\'" value)
12532 (setq value (concat "\"" value "\"")))
12533 (org-match-sparse-tree arg (concat kwd "=" value)))
12534 ((member ans '(?r ?R ?/))
12535 (call-interactively 'org-occur))
12536 (t (error "No such sparse tree command \"%c\"" ans)))))
12538 (defvar org-occur-highlights nil
12539 "List of overlays used for occur matches.")
12540 (make-variable-buffer-local 'org-occur-highlights)
12541 (defvar org-occur-parameters nil
12542 "Parameters of the active org-occur calls.
12543 This is a list, each call to org-occur pushes as cons cell,
12544 containing the regular expression and the callback, onto the list.
12545 The list can contain several entries if `org-occur' has been called
12546 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12547 will only contain one set of parameters. When the highlights are
12548 removed (for example with `C-c C-c', or with the next edit (depending
12549 on `org-remove-highlights-with-change'), this variable is emptied
12550 as well.")
12551 (make-variable-buffer-local 'org-occur-parameters)
12553 (defun org-occur (regexp &optional keep-previous callback)
12554 "Make a compact tree which shows all matches of REGEXP.
12555 The tree will show the lines where the regexp matches, and all higher
12556 headlines above the match. It will also show the heading after the match,
12557 to make sure editing the matching entry is easy.
12558 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12559 call to `org-occur' will be kept, to allow stacking of calls to this
12560 command.
12561 If CALLBACK is non-nil, it is a function which is called to confirm
12562 that the match should indeed be shown."
12563 (interactive "sRegexp: \nP")
12564 (when (equal regexp "")
12565 (error "Regexp cannot be empty"))
12566 (unless keep-previous
12567 (org-remove-occur-highlights nil nil t))
12568 (push (cons regexp callback) org-occur-parameters)
12569 (let ((cnt 0))
12570 (save-excursion
12571 (goto-char (point-min))
12572 (if (or (not keep-previous) ; do not want to keep
12573 (not org-occur-highlights)) ; no previous matches
12574 ;; hide everything
12575 (org-overview))
12576 (while (re-search-forward regexp nil t)
12577 (when (or (not callback)
12578 (save-match-data (funcall callback)))
12579 (setq cnt (1+ cnt))
12580 (when org-highlight-sparse-tree-matches
12581 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12582 (org-show-context 'occur-tree))))
12583 (when org-remove-highlights-with-change
12584 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12585 nil 'local))
12586 (unless org-sparse-tree-open-archived-trees
12587 (org-hide-archived-subtrees (point-min) (point-max)))
12588 (run-hooks 'org-occur-hook)
12589 (if (org-called-interactively-p 'interactive)
12590 (message "%d match(es) for regexp %s" cnt regexp))
12591 cnt))
12593 (defun org-occur-next-match (&optional n reset)
12594 "Function for `next-error-function' to find sparse tree matches.
12595 N is the number of matches to move, when negative move backwards.
12596 RESET is entirely ignored - this function always goes back to the
12597 starting point when no match is found."
12598 (let* ((limit (if (< n 0) (point-min) (point-max)))
12599 (search-func (if (< n 0)
12600 'previous-single-char-property-change
12601 'next-single-char-property-change))
12602 (n (abs n))
12603 (pos (point))
12605 (catch 'exit
12606 (while (setq p1 (funcall search-func (point) 'org-type))
12607 (when (equal p1 limit)
12608 (goto-char pos)
12609 (error "No more matches"))
12610 (when (equal (get-char-property p1 'org-type) 'org-occur)
12611 (setq n (1- n))
12612 (when (= n 0)
12613 (goto-char p1)
12614 (throw 'exit (point))))
12615 (goto-char p1))
12616 (goto-char p1)
12617 (error "No more matches"))))
12619 (defun org-show-context (&optional key)
12620 "Make sure point and context are visible.
12621 How much context is shown depends upon the variables
12622 `org-show-hierarchy-above', `org-show-following-heading',
12623 `org-show-entry-below' and `org-show-siblings'."
12624 (let ((heading-p (org-at-heading-p t))
12625 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12626 (following-p (org-get-alist-option org-show-following-heading key))
12627 (entry-p (org-get-alist-option org-show-entry-below key))
12628 (siblings-p (org-get-alist-option org-show-siblings key)))
12629 (catch 'exit
12630 ;; Show heading or entry text
12631 (if (and heading-p (not entry-p))
12632 (org-flag-heading nil) ; only show the heading
12633 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12634 (org-show-hidden-entry))) ; show entire entry
12635 (when following-p
12636 ;; Show next sibling, or heading below text
12637 (save-excursion
12638 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12639 (org-flag-heading nil))))
12640 (when siblings-p (org-show-siblings))
12641 (when hierarchy-p
12642 ;; show all higher headings, possibly with siblings
12643 (save-excursion
12644 (while (and (condition-case nil
12645 (progn (org-up-heading-all 1) t)
12646 (error nil))
12647 (not (bobp)))
12648 (org-flag-heading nil)
12649 (when siblings-p (org-show-siblings))))))))
12651 (defvar org-reveal-start-hook nil
12652 "Hook run before revealing a location.")
12654 (defun org-reveal (&optional siblings)
12655 "Show current entry, hierarchy above it, and the following headline.
12656 This can be used to show a consistent set of context around locations
12657 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12658 not t for the search context.
12660 With optional argument SIBLINGS, on each level of the hierarchy all
12661 siblings are shown. This repairs the tree structure to what it would
12662 look like when opened with hierarchical calls to `org-cycle'.
12663 With double optional argument \\[universal-argument] \\[universal-argument], \
12664 go to the parent and show the
12665 entire tree."
12666 (interactive "P")
12667 (run-hooks 'org-reveal-start-hook)
12668 (let ((org-show-hierarchy-above t)
12669 (org-show-following-heading t)
12670 (org-show-siblings (if siblings t org-show-siblings)))
12671 (org-show-context nil))
12672 (when (equal siblings '(16))
12673 (save-excursion
12674 (when (org-up-heading-safe)
12675 (org-show-subtree)
12676 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12678 (defun org-highlight-new-match (beg end)
12679 "Highlight from BEG to END and mark the highlight is an occur headline."
12680 (let ((ov (make-overlay beg end)))
12681 (overlay-put ov 'face 'secondary-selection)
12682 (overlay-put ov 'org-type 'org-occur)
12683 (push ov org-occur-highlights)))
12685 (defun org-remove-occur-highlights (&optional beg end noremove)
12686 "Remove the occur highlights from the buffer.
12687 BEG and END are ignored. If NOREMOVE is nil, remove this function
12688 from the `before-change-functions' in the current buffer."
12689 (interactive)
12690 (unless org-inhibit-highlight-removal
12691 (mapc 'delete-overlay org-occur-highlights)
12692 (setq org-occur-highlights nil)
12693 (setq org-occur-parameters nil)
12694 (unless noremove
12695 (remove-hook 'before-change-functions
12696 'org-remove-occur-highlights 'local))))
12698 ;;;; Priorities
12700 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12701 "Regular expression matching the priority indicator.")
12703 (defvar org-remove-priority-next-time nil)
12705 (defun org-priority-up ()
12706 "Increase the priority of the current item."
12707 (interactive)
12708 (org-priority 'up))
12710 (defun org-priority-down ()
12711 "Decrease the priority of the current item."
12712 (interactive)
12713 (org-priority 'down))
12715 (defun org-priority (&optional action)
12716 "Change the priority of an item by ARG.
12717 ACTION can be `set', `up', `down', or a character."
12718 (interactive)
12719 (unless org-enable-priority-commands
12720 (error "Priority commands are disabled"))
12721 (setq action (or action 'set))
12722 (let (current new news have remove)
12723 (save-excursion
12724 (org-back-to-heading t)
12725 (if (looking-at org-priority-regexp)
12726 (setq current (string-to-char (match-string 2))
12727 have t))
12728 (cond
12729 ((eq action 'remove)
12730 (setq remove t new ?\ ))
12731 ((or (eq action 'set)
12732 (if (featurep 'xemacs) (characterp action) (integerp action)))
12733 (if (not (eq action 'set))
12734 (setq new action)
12735 (message "Priority %c-%c, SPC to remove: "
12736 org-highest-priority org-lowest-priority)
12737 (save-match-data
12738 (setq new (read-char-exclusive))))
12739 (if (and (= (upcase org-highest-priority) org-highest-priority)
12740 (= (upcase org-lowest-priority) org-lowest-priority))
12741 (setq new (upcase new)))
12742 (cond ((equal new ?\ ) (setq remove t))
12743 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12744 (error "Priority must be between `%c' and `%c'"
12745 org-highest-priority org-lowest-priority))))
12746 ((eq action 'up)
12747 (setq new (if have
12748 (1- current) ; normal cycling
12749 ;; last priority was empty
12750 (if (eq last-command this-command)
12751 org-lowest-priority ; wrap around empty to lowest
12752 ;; default
12753 (if org-priority-start-cycle-with-default
12754 org-default-priority
12755 (1- org-default-priority))))))
12756 ((eq action 'down)
12757 (setq new (if have
12758 (1+ current) ; normal cycling
12759 ;; last priority was empty
12760 (if (eq last-command this-command)
12761 org-highest-priority ; wrap around empty to highest
12762 ;; default
12763 (if org-priority-start-cycle-with-default
12764 org-default-priority
12765 (1+ org-default-priority))))))
12766 (t (error "Invalid action")))
12767 (if (or (< (upcase new) org-highest-priority)
12768 (> (upcase new) org-lowest-priority))
12769 (if (and (memq action '(up down))
12770 (not have) (not (eq last-command this-command)))
12771 ;; `new' is from default priority
12772 (error
12773 "The default can not be set, see `org-default-priority' why")
12774 ;; normal cycling: `new' is beyond highest/lowest priority
12775 ;; and is wrapped around to the empty priority
12776 (setq remove t)))
12777 (setq news (format "%c" new))
12778 (if have
12779 (if remove
12780 (replace-match "" t t nil 1)
12781 (replace-match news t t nil 2))
12782 (if remove
12783 (error "No priority cookie found in line")
12784 (let ((case-fold-search nil))
12785 (looking-at org-todo-line-regexp))
12786 (if (match-end 2)
12787 (progn
12788 (goto-char (match-end 2))
12789 (insert " [#" news "]"))
12790 (goto-char (match-beginning 3))
12791 (insert "[#" news "] "))))
12792 (org-preserve-lc (org-set-tags nil 'align)))
12793 (if remove
12794 (message "Priority removed")
12795 (message "Priority of current item set to %s" news))))
12797 (defun org-get-priority (s)
12798 "Find priority cookie and return priority."
12799 (if (functionp org-get-priority-function)
12800 (funcall org-get-priority-function)
12801 (save-match-data
12802 (if (not (string-match org-priority-regexp s))
12803 (* 1000 (- org-lowest-priority org-default-priority))
12804 (* 1000 (- org-lowest-priority
12805 (string-to-char (match-string 2 s))))))))
12807 ;;;; Tags
12809 (defvar org-agenda-archives-mode)
12810 (defvar org-map-continue-from nil
12811 "Position from where mapping should continue.
12812 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12814 (defvar org-scanner-tags nil
12815 "The current tag list while the tags scanner is running.")
12816 (defvar org-trust-scanner-tags nil
12817 "Should `org-get-tags-at' use the tags for the scanner.
12818 This is for internal dynamical scoping only.
12819 When this is non-nil, the function `org-get-tags-at' will return the value
12820 of `org-scanner-tags' instead of building the list by itself. This
12821 can lead to large speed-ups when the tags scanner is used in a file with
12822 many entries, and when the list of tags is retrieved, for example to
12823 obtain a list of properties. Building the tags list for each entry in such
12824 a file becomes an N^2 operation - but with this variable set, it scales
12825 as N.")
12827 (defun org-scan-tags (action matcher todo-only &optional start-level)
12828 "Scan headline tags with inheritance and produce output ACTION.
12830 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12831 or `agenda' to produce an entry list for an agenda view. It can also be
12832 a Lisp form or a function that should be called at each matched headline, in
12833 this case the return value is a list of all return values from these calls.
12835 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12836 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12837 only lines with a not-done TODO keyword are included in the output.
12838 This should be the same variable that was scoped into
12839 and set by `org-make-tags-matcher' when it constructed MATCHER.
12841 START-LEVEL can be a string with asterisks, reducing the scope to
12842 headlines matching this string."
12843 (require 'org-agenda)
12844 (let* ((re (concat "^"
12845 (if start-level
12846 ;; Get the correct level to match
12847 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12848 org-outline-regexp)
12849 " *\\(\\<\\("
12850 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12851 (org-re
12852 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12853 (props (list 'face 'default
12854 'done-face 'org-agenda-done
12855 'undone-face 'default
12856 'mouse-face 'highlight
12857 'org-not-done-regexp org-not-done-regexp
12858 'org-todo-regexp org-todo-regexp
12859 'org-complex-heading-regexp org-complex-heading-regexp
12860 'help-echo
12861 (format "mouse-2 or RET jump to org file %s"
12862 (abbreviate-file-name
12863 (or (buffer-file-name (buffer-base-buffer))
12864 (buffer-name (buffer-base-buffer)))))))
12865 (case-fold-search nil)
12866 (org-map-continue-from nil)
12867 lspos tags tags-list
12868 (tags-alist (list (cons 0 org-file-tags)))
12869 (llast 0) rtn rtn1 level category i txt
12870 todo marker entry priority)
12871 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12872 (setq action (list 'lambda nil action)))
12873 (save-excursion
12874 (goto-char (point-min))
12875 (when (eq action 'sparse-tree)
12876 (org-overview)
12877 (org-remove-occur-highlights))
12878 (while (re-search-forward re nil t)
12879 (setq org-map-continue-from nil)
12880 (catch :skip
12881 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12882 tags (if (match-end 4) (org-match-string-no-properties 4)))
12883 (goto-char (setq lspos (match-beginning 0)))
12884 (setq level (org-reduced-level (funcall outline-level))
12885 category (org-get-category))
12886 (setq i llast llast level)
12887 ;; remove tag lists from same and sublevels
12888 (while (>= i level)
12889 (when (setq entry (assoc i tags-alist))
12890 (setq tags-alist (delete entry tags-alist)))
12891 (setq i (1- i)))
12892 ;; add the next tags
12893 (when tags
12894 (setq tags (org-split-string tags ":")
12895 tags-alist
12896 (cons (cons level tags) tags-alist)))
12897 ;; compile tags for current headline
12898 (setq tags-list
12899 (if org-use-tag-inheritance
12900 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12901 tags)
12902 org-scanner-tags tags-list)
12903 (when org-use-tag-inheritance
12904 (setcdr (car tags-alist)
12905 (mapcar (lambda (x)
12906 (setq x (copy-sequence x))
12907 (org-add-prop-inherited x))
12908 (cdar tags-alist))))
12909 (when (and tags org-use-tag-inheritance
12910 (or (not (eq t org-use-tag-inheritance))
12911 org-tags-exclude-from-inheritance))
12912 ;; selective inheritance, remove uninherited ones
12913 (setcdr (car tags-alist)
12914 (org-remove-uninherited-tags (cdar tags-alist))))
12915 (when (and
12917 ;; eval matcher only when the todo condition is OK
12918 (and (or (not todo-only) (member todo org-not-done-keywords))
12919 (let ((case-fold-search t) (org-trust-scanner-tags t))
12920 (eval matcher)))
12922 ;; Call the skipper, but return t if it does not skip,
12923 ;; so that the `and' form continues evaluating
12924 (progn
12925 (unless (eq action 'sparse-tree) (org-agenda-skip))
12928 ;; Check if timestamps are deselecting this entry
12929 (or (not todo-only)
12930 (and (member todo org-not-done-keywords)
12931 (or (not org-agenda-tags-todo-honor-ignore-options)
12932 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12934 ;; Extra check for the archive tag
12935 ;; FIXME: Does the skipper already do this????
12937 (not (member org-archive-tag tags-list))
12938 ;; we have an archive tag, should we use this anyway?
12939 (or (not org-agenda-skip-archived-trees)
12940 (and (eq action 'agenda) org-agenda-archives-mode))))
12942 ;; select this headline
12944 (cond
12945 ((eq action 'sparse-tree)
12946 (and org-highlight-sparse-tree-matches
12947 (org-get-heading) (match-end 0)
12948 (org-highlight-new-match
12949 (match-beginning 1) (match-end 1)))
12950 (org-show-context 'tags-tree))
12951 ((eq action 'agenda)
12952 (setq txt (org-agenda-format-item
12954 (concat
12955 (if (eq org-tags-match-list-sublevels 'indented)
12956 (make-string (1- level) ?.) "")
12957 (org-get-heading))
12958 category
12959 tags-list)
12960 priority (org-get-priority txt))
12961 (goto-char lspos)
12962 (setq marker (org-agenda-new-marker))
12963 (org-add-props txt props
12964 'org-marker marker 'org-hd-marker marker 'org-category category
12965 'todo-state todo
12966 'priority priority 'type "tagsmatch")
12967 (push txt rtn))
12968 ((functionp action)
12969 (setq org-map-continue-from nil)
12970 (save-excursion
12971 (setq rtn1 (funcall action))
12972 (push rtn1 rtn)))
12973 (t (error "Invalid action")))
12975 ;; if we are to skip sublevels, jump to end of subtree
12976 (unless org-tags-match-list-sublevels
12977 (org-end-of-subtree t)
12978 (backward-char 1))))
12979 ;; Get the correct position from where to continue
12980 (if org-map-continue-from
12981 (goto-char org-map-continue-from)
12982 (and (= (point) lspos) (end-of-line 1)))))
12983 (when (and (eq action 'sparse-tree)
12984 (not org-sparse-tree-open-archived-trees))
12985 (org-hide-archived-subtrees (point-min) (point-max)))
12986 (nreverse rtn)))
12988 (defun org-remove-uninherited-tags (tags)
12989 "Remove all tags that are not inherited from the list TAGS."
12990 (cond
12991 ((eq org-use-tag-inheritance t)
12992 (if org-tags-exclude-from-inheritance
12993 (org-delete-all org-tags-exclude-from-inheritance tags)
12994 tags))
12995 ((not org-use-tag-inheritance) nil)
12996 ((stringp org-use-tag-inheritance)
12997 (delq nil (mapcar
12998 (lambda (x)
12999 (if (and (string-match org-use-tag-inheritance x)
13000 (not (member x org-tags-exclude-from-inheritance)))
13001 x nil))
13002 tags)))
13003 ((listp org-use-tag-inheritance)
13004 (delq nil (mapcar
13005 (lambda (x)
13006 (if (member x org-use-tag-inheritance) x nil))
13007 tags)))))
13009 (defun org-match-sparse-tree (&optional todo-only match)
13010 "Create a sparse tree according to tags string MATCH.
13011 MATCH can contain positive and negative selection of tags, like
13012 \"+WORK+URGENT-WITHBOSS\".
13013 If optional argument TODO-ONLY is non-nil, only select lines that are
13014 also TODO lines."
13015 (interactive "P")
13016 (org-prepare-agenda-buffers (list (current-buffer)))
13017 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13019 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13021 (defvar org-cached-props nil)
13022 (defun org-cached-entry-get (pom property)
13023 (if (or (eq t org-use-property-inheritance)
13024 (and (stringp org-use-property-inheritance)
13025 (string-match org-use-property-inheritance property))
13026 (and (listp org-use-property-inheritance)
13027 (member property org-use-property-inheritance)))
13028 ;; Caching is not possible, check it directly
13029 (org-entry-get pom property 'inherit)
13030 ;; Get all properties, so that we can do complicated checks easily
13031 (cdr (assoc property (or org-cached-props
13032 (setq org-cached-props
13033 (org-entry-properties pom)))))))
13035 (defun org-global-tags-completion-table (&optional files)
13036 "Return the list of all tags in all agenda buffer/files.
13037 Optional FILES argument is a list of files to which can be used
13038 instead of the agenda files."
13039 (save-excursion
13040 (org-uniquify
13041 (delq nil
13042 (apply 'append
13043 (mapcar
13044 (lambda (file)
13045 (set-buffer (find-file-noselect file))
13046 (append (org-get-buffer-tags)
13047 (mapcar (lambda (x) (if (stringp (car-safe x))
13048 (list (car-safe x)) nil))
13049 org-tag-alist)))
13050 (if (and files (car files))
13051 files
13052 (org-agenda-files))))))))
13054 (defun org-make-tags-matcher (match)
13055 "Create the TAGS/TODO matcher form for the selection string MATCH.
13057 The variable `todo-only' is scoped dynamically into this function; it will be
13058 set to t if the matcher restricts matching to TODO entries,
13059 otherwise will not be touched.
13061 Returns a cons of the selection string MATCH and the constructed
13062 lisp form implementing the matcher. The matcher is to be
13063 evaluated at an Org entry, with point on the headline,
13064 and returns t if the entry matches the
13065 selection string MATCH. The returned lisp form references
13066 two variables with information about the entry, which must be
13067 bound around the form's evaluation: todo, the TODO keyword at the
13068 entry (or nil of none); and tags-list, the list of all tags at the
13069 entry including inherited ones. Additionally, the category
13070 of the entry (if any) must be specified as the text property
13071 'org-category on the headline.
13073 See also `org-scan-tags'.
13075 (declare (special todo-only))
13076 (unless (boundp 'todo-only)
13077 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13078 (unless match
13079 ;; Get a new match request, with completion
13080 (let ((org-last-tags-completion-table
13081 (org-global-tags-completion-table)))
13082 (setq match (org-completing-read-no-i
13083 "Match: " 'org-tags-completion-function nil nil nil
13084 'org-tags-history))))
13086 ;; Parse the string and create a lisp form
13087 (let ((match0 match)
13088 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13089 minus tag mm
13090 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13091 orterms term orlist re-p str-p level-p level-op time-p
13092 prop-p pn pv po gv rest)
13093 (if (string-match "/+" match)
13094 ;; match contains also a todo-matching request
13095 (progn
13096 (setq tagsmatch (substring match 0 (match-beginning 0))
13097 todomatch (substring match (match-end 0)))
13098 (if (string-match "^!" todomatch)
13099 (setq todo-only t todomatch (substring todomatch 1)))
13100 (if (string-match "^\\s-*$" todomatch)
13101 (setq todomatch nil)))
13102 ;; only matching tags
13103 (setq tagsmatch match todomatch nil))
13105 ;; Make the tags matcher
13106 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13107 (setq tagsmatcher t)
13108 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13109 (while (setq term (pop orterms))
13110 (while (and (equal (substring term -1) "\\") orterms)
13111 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13112 (while (string-match re term)
13113 (setq rest (substring term (match-end 0))
13114 minus (and (match-end 1)
13115 (equal (match-string 1 term) "-"))
13116 tag (save-match-data (replace-regexp-in-string
13117 "\\\\-" "-"
13118 (match-string 2 term)))
13119 re-p (equal (string-to-char tag) ?{)
13120 level-p (match-end 4)
13121 prop-p (match-end 5)
13122 mm (cond
13123 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13124 (level-p
13125 (setq level-op (org-op-to-function (match-string 3 term)))
13126 `(,level-op level ,(string-to-number
13127 (match-string 4 term))))
13128 (prop-p
13129 (setq pn (match-string 5 term)
13130 po (match-string 6 term)
13131 pv (match-string 7 term)
13132 re-p (equal (string-to-char pv) ?{)
13133 str-p (equal (string-to-char pv) ?\")
13134 time-p (save-match-data
13135 (string-match "^\"[[<].*[]>]\"$" pv))
13136 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13137 (if time-p (setq pv (org-matcher-time pv)))
13138 (setq po (org-op-to-function po (if time-p 'time str-p)))
13139 (cond
13140 ((equal pn "CATEGORY")
13141 (setq gv '(get-text-property (point) 'org-category)))
13142 ((equal pn "TODO")
13143 (setq gv 'todo))
13145 (setq gv `(org-cached-entry-get nil ,pn))))
13146 (if re-p
13147 (if (eq po 'org<>)
13148 `(not (string-match ,pv (or ,gv "")))
13149 `(string-match ,pv (or ,gv "")))
13150 (if str-p
13151 `(,po (or ,gv "") ,pv)
13152 `(,po (string-to-number (or ,gv ""))
13153 ,(string-to-number pv) ))))
13154 (t `(member ,tag tags-list)))
13155 mm (if minus (list 'not mm) mm)
13156 term rest)
13157 (push mm tagsmatcher))
13158 (push (if (> (length tagsmatcher) 1)
13159 (cons 'and tagsmatcher)
13160 (car tagsmatcher))
13161 orlist)
13162 (setq tagsmatcher nil))
13163 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13164 (setq tagsmatcher
13165 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13166 ;; Make the todo matcher
13167 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13168 (setq todomatcher t)
13169 (setq orterms (org-split-string todomatch "|") orlist nil)
13170 (while (setq term (pop orterms))
13171 (while (string-match re term)
13172 (setq minus (and (match-end 1)
13173 (equal (match-string 1 term) "-"))
13174 kwd (match-string 2 term)
13175 re-p (equal (string-to-char kwd) ?{)
13176 term (substring term (match-end 0))
13177 mm (if re-p
13178 `(string-match ,(substring kwd 1 -1) todo)
13179 (list 'equal 'todo kwd))
13180 mm (if minus (list 'not mm) mm))
13181 (push mm todomatcher))
13182 (push (if (> (length todomatcher) 1)
13183 (cons 'and todomatcher)
13184 (car todomatcher))
13185 orlist)
13186 (setq todomatcher nil))
13187 (setq todomatcher (if (> (length orlist) 1)
13188 (cons 'or orlist) (car orlist))))
13190 ;; Return the string and lisp forms of the matcher
13191 (setq matcher (if todomatcher
13192 (list 'and tagsmatcher todomatcher)
13193 tagsmatcher))
13194 (when todo-only
13195 (setq matcher (list 'and '(member todo org-not-done-keywords)
13196 matcher)))
13197 (cons match0 matcher)))
13199 (defun org-op-to-function (op &optional stringp)
13200 "Turn an operator into the appropriate function."
13201 (setq op
13202 (cond
13203 ((equal op "<" ) '(< string< org-time<))
13204 ((equal op ">" ) '(> org-string> org-time>))
13205 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13206 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13207 ((member op '("=" "==")) '(= string= org-time=))
13208 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13209 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13211 (defun org<> (a b) (not (= a b)))
13212 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13213 (defun org-string>= (a b) (not (string< a b)))
13214 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13215 (defun org-string<> (a b) (not (string= a b)))
13216 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13217 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13218 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13219 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13220 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13221 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13222 (defun org-2ft (s)
13223 "Convert S to a floating point time.
13224 If S is already a number, just return it. If it is a string, parse
13225 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13226 (cond
13227 ((numberp s) s)
13228 ((stringp s)
13229 (condition-case nil
13230 (float-time (apply 'encode-time (org-parse-time-string s)))
13231 (error 0.)))
13232 (t 0.)))
13234 (defun org-time-today ()
13235 "Time in seconds today at 0:00.
13236 Returns the float number of seconds since the beginning of the
13237 epoch to the beginning of today (00:00)."
13238 (float-time (apply 'encode-time
13239 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13241 (defun org-matcher-time (s)
13242 "Interpret a time comparison value."
13243 (save-match-data
13244 (cond
13245 ((string= s "<now>") (float-time))
13246 ((string= s "<today>") (org-time-today))
13247 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13248 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13249 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13250 (+ (org-time-today)
13251 (* (string-to-number (match-string 1 s))
13252 (cdr (assoc (match-string 2 s)
13253 '(("d" . 86400.0) ("w" . 604800.0)
13254 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13255 (t (org-2ft s)))))
13257 (defun org-match-any-p (re list)
13258 "Does re match any element of list?"
13259 (setq list (mapcar (lambda (x) (string-match re x)) list))
13260 (delq nil list))
13262 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13263 (defvar org-tags-overlay (make-overlay 1 1))
13264 (org-detach-overlay org-tags-overlay)
13266 (defun org-get-local-tags-at (&optional pos)
13267 "Get a list of tags defined in the current headline."
13268 (org-get-tags-at pos 'local))
13270 (defun org-get-local-tags ()
13271 "Get a list of tags defined in the current headline."
13272 (org-get-tags-at nil 'local))
13274 (defun org-get-tags-at (&optional pos local)
13275 "Get a list of all headline tags applicable at POS.
13276 POS defaults to point. If tags are inherited, the list contains
13277 the targets in the same sequence as the headlines appear, i.e.
13278 the tags of the current headline come last.
13279 When LOCAL is non-nil, only return tags from the current headline,
13280 ignore inherited ones."
13281 (interactive)
13282 (if (and org-trust-scanner-tags
13283 (or (not pos) (equal pos (point)))
13284 (not local))
13285 org-scanner-tags
13286 (let (tags ltags lastpos parent)
13287 (save-excursion
13288 (save-restriction
13289 (widen)
13290 (goto-char (or pos (point)))
13291 (save-match-data
13292 (catch 'done
13293 (condition-case nil
13294 (progn
13295 (org-back-to-heading t)
13296 (while (not (equal lastpos (point)))
13297 (setq lastpos (point))
13298 (when (looking-at
13299 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13300 (setq ltags (org-split-string
13301 (org-match-string-no-properties 1) ":"))
13302 (when parent
13303 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13304 (setq tags (append
13305 (if parent
13306 (org-remove-uninherited-tags ltags)
13307 ltags)
13308 tags)))
13309 (or org-use-tag-inheritance (throw 'done t))
13310 (if local (throw 'done t))
13311 (or (org-up-heading-safe) (error nil))
13312 (setq parent t)))
13313 (error nil)))))
13314 (if local
13315 tags
13316 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13318 (defun org-add-prop-inherited (s)
13319 (add-text-properties 0 (length s) '(inherited t) s)
13322 (defun org-toggle-tag (tag &optional onoff)
13323 "Toggle the tag TAG for the current line.
13324 If ONOFF is `on' or `off', don't toggle but set to this state."
13325 (let (res current)
13326 (save-excursion
13327 (org-back-to-heading t)
13328 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13329 (point-at-eol) t)
13330 (progn
13331 (setq current (match-string 1))
13332 (replace-match ""))
13333 (setq current ""))
13334 (setq current (nreverse (org-split-string current ":")))
13335 (cond
13336 ((eq onoff 'on)
13337 (setq res t)
13338 (or (member tag current) (push tag current)))
13339 ((eq onoff 'off)
13340 (or (not (member tag current)) (setq current (delete tag current))))
13341 (t (if (member tag current)
13342 (setq current (delete tag current))
13343 (setq res t)
13344 (push tag current))))
13345 (end-of-line 1)
13346 (if current
13347 (progn
13348 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13349 (org-set-tags nil t))
13350 (delete-horizontal-space))
13351 (run-hooks 'org-after-tags-change-hook))
13352 res))
13354 (defun org-align-tags-here (to-col)
13355 ;; Assumes that this is a headline
13356 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13357 (beginning-of-line 1)
13358 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13359 (< pos (match-beginning 2)))
13360 (progn
13361 (setq tags-l (- (match-end 2) (match-beginning 2)))
13362 (goto-char (match-beginning 1))
13363 (insert " ")
13364 (delete-region (point) (1+ (match-beginning 2)))
13365 (setq ncol (max (current-column)
13366 (1+ col)
13367 (if (> to-col 0)
13368 to-col
13369 (- (abs to-col) tags-l))))
13370 (setq p (point))
13371 (insert (make-string (- ncol (current-column)) ?\ ))
13372 (setq ncol (current-column))
13373 (when indent-tabs-mode (tabify p (point-at-eol)))
13374 (org-move-to-column (min ncol col) t))
13375 (goto-char pos))))
13377 (defun org-set-tags-command (&optional arg just-align)
13378 "Call the set-tags command for the current entry."
13379 (interactive "P")
13380 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13381 (org-set-tags arg just-align)
13382 (save-excursion
13383 (org-back-to-heading t)
13384 (org-set-tags arg just-align))))
13386 (defun org-set-tags-to (data)
13387 "Set the tags of the current entry to DATA, replacing the current tags.
13388 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13389 If DATA is nil or the empty string, any tags will be removed."
13390 (interactive "sTags: ")
13391 (setq data
13392 (cond
13393 ((eq data nil) "")
13394 ((equal data "") "")
13395 ((stringp data)
13396 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13397 ":"))
13398 ((listp data)
13399 (concat ":" (mapconcat 'identity data ":") ":"))
13400 (t nil)))
13401 (when data
13402 (save-excursion
13403 (org-back-to-heading t)
13404 (when (looking-at org-complex-heading-regexp)
13405 (if (match-end 5)
13406 (progn
13407 (goto-char (match-beginning 5))
13408 (insert data)
13409 (delete-region (point) (point-at-eol))
13410 (org-set-tags nil 'align))
13411 (goto-char (point-at-eol))
13412 (insert " " data)
13413 (org-set-tags nil 'align)))
13414 (beginning-of-line 1)
13415 (if (looking-at ".*?\\([ \t]+\\)$")
13416 (delete-region (match-beginning 1) (match-end 1))))))
13418 (defun org-align-all-tags ()
13419 "Align the tags i all headings."
13420 (interactive)
13421 (save-excursion
13422 (or (ignore-errors (org-back-to-heading t))
13423 (outline-next-heading))
13424 (if (org-at-heading-p)
13425 (org-set-tags t)
13426 (message "No headings"))))
13428 (defvar org-indent-indentation-per-level)
13429 (defun org-set-tags (&optional arg just-align)
13430 "Set the tags for the current headline.
13431 With prefix ARG, realign all tags in headings in the current buffer."
13432 (interactive "P")
13433 (let* ((re org-outline-regexp-bol)
13434 (current (unless arg (org-get-tags-string)))
13435 (col (current-column))
13436 (org-setting-tags t)
13437 table current-tags inherited-tags ; computed below when needed
13438 tags p0 c0 c1 rpl di tc level)
13439 (if arg
13440 (save-excursion
13441 (goto-char (point-min))
13442 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13443 (while (re-search-forward re nil t)
13444 (org-set-tags nil t)
13445 (end-of-line 1)))
13446 (message "All tags realigned to column %d" org-tags-column))
13447 (if just-align
13448 (setq tags current)
13449 ;; Get a new set of tags from the user
13450 (save-excursion
13451 (setq table (append org-tag-persistent-alist
13452 org-tag-alist
13453 (org-get-buffer-tags)
13454 (and
13455 org-complete-tags-always-offer-all-agenda-tags
13456 (org-global-tags-completion-table
13457 (org-agenda-files))))
13458 org-last-tags-completion-table table
13459 current-tags (org-split-string current ":")
13460 inherited-tags (nreverse
13461 (nthcdr (length current-tags)
13462 (nreverse (org-get-tags-at))))
13463 tags
13464 (if (or (eq t org-use-fast-tag-selection)
13465 (and org-use-fast-tag-selection
13466 (delq nil (mapcar 'cdr table))))
13467 (org-fast-tag-selection
13468 current-tags inherited-tags table
13469 (if org-fast-tag-selection-include-todo
13470 org-todo-key-alist))
13471 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13472 (org-trim
13473 (org-icompleting-read "Tags: "
13474 'org-tags-completion-function
13475 nil nil current 'org-tags-history))))))
13476 (while (string-match "[-+&]+" tags)
13477 ;; No boolean logic, just a list
13478 (setq tags (replace-match ":" t t tags))))
13480 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13482 (if org-tags-sort-function
13483 (setq tags (mapconcat 'identity
13484 (sort (org-split-string
13485 tags (org-re "[^[:alnum:]_@#%]+"))
13486 org-tags-sort-function) ":")))
13488 (if (string-match "\\`[\t ]*\\'" tags)
13489 (setq tags "")
13490 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13491 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13493 ;; Insert new tags at the correct column
13494 (beginning-of-line 1)
13495 (setq level (or (and (looking-at org-outline-regexp)
13496 (- (match-end 0) (point) 1))
13498 (cond
13499 ((and (equal current "") (equal tags "")))
13500 ((re-search-forward
13501 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13502 (point-at-eol) t)
13503 (if (equal tags "")
13504 (setq rpl "")
13505 (goto-char (match-beginning 0))
13506 (setq c0 (current-column)
13507 ;; compute offset for the case of org-indent-mode active
13508 di (if org-indent-mode
13509 (* (1- org-indent-indentation-per-level) (1- level))
13511 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13512 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13513 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13514 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13515 (replace-match rpl t t)
13516 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13517 tags)
13518 (t (error "Tags alignment failed")))
13519 (org-move-to-column col)
13520 (unless just-align
13521 (run-hooks 'org-after-tags-change-hook)))))
13523 (defun org-change-tag-in-region (beg end tag off)
13524 "Add or remove TAG for each entry in the region.
13525 This works in the agenda, and also in an org-mode buffer."
13526 (interactive
13527 (list (region-beginning) (region-end)
13528 (let ((org-last-tags-completion-table
13529 (if (eq major-mode 'org-mode)
13530 (org-get-buffer-tags)
13531 (org-global-tags-completion-table))))
13532 (org-icompleting-read
13533 "Tag: " 'org-tags-completion-function nil nil nil
13534 'org-tags-history))
13535 (progn
13536 (message "[s]et or [r]emove? ")
13537 (equal (read-char-exclusive) ?r))))
13538 (if (fboundp 'deactivate-mark) (deactivate-mark))
13539 (let ((agendap (equal major-mode 'org-agenda-mode))
13540 l1 l2 m buf pos newhead (cnt 0))
13541 (goto-char end)
13542 (setq l2 (1- (org-current-line)))
13543 (goto-char beg)
13544 (setq l1 (org-current-line))
13545 (loop for l from l1 to l2 do
13546 (org-goto-line l)
13547 (setq m (get-text-property (point) 'org-hd-marker))
13548 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13549 (and agendap m))
13550 (setq buf (if agendap (marker-buffer m) (current-buffer))
13551 pos (if agendap m (point)))
13552 (with-current-buffer buf
13553 (save-excursion
13554 (save-restriction
13555 (goto-char pos)
13556 (setq cnt (1+ cnt))
13557 (org-toggle-tag tag (if off 'off 'on))
13558 (setq newhead (org-get-heading)))))
13559 (and agendap (org-agenda-change-all-lines newhead m))))
13560 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13562 (defun org-tags-completion-function (string predicate &optional flag)
13563 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13564 (confirm (lambda (x) (stringp (car x)))))
13565 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13566 (setq s1 (match-string 1 string)
13567 s2 (match-string 2 string))
13568 (setq s1 "" s2 string))
13569 (cond
13570 ((eq flag nil)
13571 ;; try completion
13572 (setq rtn (try-completion s2 ctable confirm))
13573 (if (stringp rtn)
13574 (setq rtn
13575 (concat s1 s2 (substring rtn (length s2))
13576 (if (and org-add-colon-after-tag-completion
13577 (assoc rtn ctable))
13578 ":" ""))))
13579 rtn)
13580 ((eq flag t)
13581 ;; all-completions
13582 (all-completions s2 ctable confirm)
13584 ((eq flag 'lambda)
13585 ;; exact match?
13586 (assoc s2 ctable)))
13589 (defun org-fast-tag-insert (kwd tags face &optional end)
13590 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13591 (insert (format "%-12s" (concat kwd ":"))
13592 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13593 (or end "")))
13595 (defun org-fast-tag-show-exit (flag)
13596 (save-excursion
13597 (org-goto-line 3)
13598 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13599 (replace-match ""))
13600 (when flag
13601 (end-of-line 1)
13602 (org-move-to-column (- (window-width) 19) t)
13603 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13605 (defun org-set-current-tags-overlay (current prefix)
13606 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13607 (if (featurep 'xemacs)
13608 (org-overlay-display org-tags-overlay (concat prefix s)
13609 'secondary-selection)
13610 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13611 (org-overlay-display org-tags-overlay (concat prefix s)))))
13613 (defvar org-last-tag-selection-key nil)
13614 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13615 "Fast tag selection with single keys.
13616 CURRENT is the current list of tags in the headline, INHERITED is the
13617 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13618 possibly with grouping information. TODO-TABLE is a similar table with
13619 TODO keywords, should these have keys assigned to them.
13620 If the keys are nil, a-z are automatically assigned.
13621 Returns the new tags string, or nil to not change the current settings."
13622 (let* ((fulltable (append table todo-table))
13623 (maxlen (apply 'max (mapcar
13624 (lambda (x)
13625 (if (stringp (car x)) (string-width (car x)) 0))
13626 fulltable)))
13627 (buf (current-buffer))
13628 (expert (eq org-fast-tag-selection-single-key 'expert))
13629 (buffer-tags nil)
13630 (fwidth (+ maxlen 3 1 3))
13631 (ncol (/ (- (window-width) 4) fwidth))
13632 (i-face 'org-done)
13633 (c-face 'org-todo)
13634 tg cnt e c char c1 c2 ntable tbl rtn
13635 ov-start ov-end ov-prefix
13636 (exit-after-next org-fast-tag-selection-single-key)
13637 (done-keywords org-done-keywords)
13638 groups ingroup)
13639 (save-excursion
13640 (beginning-of-line 1)
13641 (if (looking-at
13642 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13643 (setq ov-start (match-beginning 1)
13644 ov-end (match-end 1)
13645 ov-prefix "")
13646 (setq ov-start (1- (point-at-eol))
13647 ov-end (1+ ov-start))
13648 (skip-chars-forward "^\n\r")
13649 (setq ov-prefix
13650 (concat
13651 (buffer-substring (1- (point)) (point))
13652 (if (> (current-column) org-tags-column)
13654 (make-string (- org-tags-column (current-column)) ?\ ))))))
13655 (move-overlay org-tags-overlay ov-start ov-end)
13656 (save-window-excursion
13657 (if expert
13658 (set-buffer (get-buffer-create " *Org tags*"))
13659 (delete-other-windows)
13660 (split-window-vertically)
13661 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13662 (erase-buffer)
13663 (org-set-local 'org-done-keywords done-keywords)
13664 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13665 (org-fast-tag-insert "Current" current c-face "\n\n")
13666 (org-fast-tag-show-exit exit-after-next)
13667 (org-set-current-tags-overlay current ov-prefix)
13668 (setq tbl fulltable char ?a cnt 0)
13669 (while (setq e (pop tbl))
13670 (cond
13671 ((equal (car e) :startgroup)
13672 (push '() groups) (setq ingroup t)
13673 (when (not (= cnt 0))
13674 (setq cnt 0)
13675 (insert "\n"))
13676 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13677 ((equal (car e) :endgroup)
13678 (setq ingroup nil cnt 0)
13679 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13680 ((equal e '(:newline))
13681 (when (not (= cnt 0))
13682 (setq cnt 0)
13683 (insert "\n")
13684 (setq e (car tbl))
13685 (while (equal (car tbl) '(:newline))
13686 (insert "\n")
13687 (setq tbl (cdr tbl)))))
13689 (setq tg (copy-sequence (car e)) c2 nil)
13690 (if (cdr e)
13691 (setq c (cdr e))
13692 ;; automatically assign a character.
13693 (setq c1 (string-to-char
13694 (downcase (substring
13695 tg (if (= (string-to-char tg) ?@) 1 0)))))
13696 (if (or (rassoc c1 ntable) (rassoc c1 table))
13697 (while (or (rassoc char ntable) (rassoc char table))
13698 (setq char (1+ char)))
13699 (setq c2 c1))
13700 (setq c (or c2 char)))
13701 (if ingroup (push tg (car groups)))
13702 (setq tg (org-add-props tg nil 'face
13703 (cond
13704 ((not (assoc tg table))
13705 (org-get-todo-face tg))
13706 ((member tg current) c-face)
13707 ((member tg inherited) i-face)
13708 (t nil))))
13709 (if (and (= cnt 0) (not ingroup)) (insert " "))
13710 (insert "[" c "] " tg (make-string
13711 (- fwidth 4 (length tg)) ?\ ))
13712 (push (cons tg c) ntable)
13713 (when (= (setq cnt (1+ cnt)) ncol)
13714 (insert "\n")
13715 (if ingroup (insert " "))
13716 (setq cnt 0)))))
13717 (setq ntable (nreverse ntable))
13718 (insert "\n")
13719 (goto-char (point-min))
13720 (if (not expert) (org-fit-window-to-buffer))
13721 (setq rtn
13722 (catch 'exit
13723 (while t
13724 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13725 (if (not groups) "no " "")
13726 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13727 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13728 (setq org-last-tag-selection-key c)
13729 (cond
13730 ((= c ?\r) (throw 'exit t))
13731 ((= c ?!)
13732 (setq groups (not groups))
13733 (goto-char (point-min))
13734 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13735 ((= c ?\C-c)
13736 (if (not expert)
13737 (org-fast-tag-show-exit
13738 (setq exit-after-next (not exit-after-next)))
13739 (setq expert nil)
13740 (delete-other-windows)
13741 (set-window-buffer (split-window-vertically) " *Org tags*")
13742 (org-switch-to-buffer-other-window " *Org tags*")
13743 (org-fit-window-to-buffer)))
13744 ((or (= c ?\C-g)
13745 (and (= c ?q) (not (rassoc c ntable))))
13746 (org-detach-overlay org-tags-overlay)
13747 (setq quit-flag t))
13748 ((= c ?\ )
13749 (setq current nil)
13750 (if exit-after-next (setq exit-after-next 'now)))
13751 ((= c ?\t)
13752 (condition-case nil
13753 (setq tg (org-icompleting-read
13754 "Tag: "
13755 (delete-dups
13756 (append (or buffer-tags
13757 (with-current-buffer buf
13758 (mapcar 'car (org-get-buffer-tags))))
13759 (delq nil
13760 (mapcar (lambda (x)
13761 (if (stringp
13762 (car x)) x)) table))))))
13763 (quit (setq tg "")))
13764 (when (string-match "\\S-" tg)
13765 (add-to-list 'buffer-tags (list tg))
13766 (if (member tg current)
13767 (setq current (delete tg current))
13768 (push tg current)))
13769 (if exit-after-next (setq exit-after-next 'now)))
13770 ((setq e (rassoc c todo-table) tg (car e))
13771 (with-current-buffer buf
13772 (save-excursion (org-todo tg)))
13773 (if exit-after-next (setq exit-after-next 'now)))
13774 ((setq e (rassoc c ntable) tg (car e))
13775 (if (member tg current)
13776 (setq current (delete tg current))
13777 (loop for g in groups do
13778 (if (member tg g)
13779 (mapc (lambda (x)
13780 (setq current (delete x current)))
13781 g)))
13782 (push tg current))
13783 (if exit-after-next (setq exit-after-next 'now))))
13785 ;; Create a sorted list
13786 (setq current
13787 (sort current
13788 (lambda (a b)
13789 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13790 (if (eq exit-after-next 'now) (throw 'exit t))
13791 (goto-char (point-min))
13792 (beginning-of-line 2)
13793 (delete-region (point) (point-at-eol))
13794 (org-fast-tag-insert "Current" current c-face)
13795 (org-set-current-tags-overlay current ov-prefix)
13796 (while (re-search-forward
13797 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13798 (setq tg (match-string 1))
13799 (add-text-properties
13800 (match-beginning 1) (match-end 1)
13801 (list 'face
13802 (cond
13803 ((member tg current) c-face)
13804 ((member tg inherited) i-face)
13805 (t (get-text-property (match-beginning 1) 'face))))))
13806 (goto-char (point-min)))))
13807 (org-detach-overlay org-tags-overlay)
13808 (if rtn
13809 (mapconcat 'identity current ":")
13810 nil))))
13812 (defun org-get-tags-string ()
13813 "Get the TAGS string in the current headline."
13814 (unless (org-at-heading-p t)
13815 (error "Not on a heading"))
13816 (save-excursion
13817 (beginning-of-line 1)
13818 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13819 (org-match-string-no-properties 1)
13820 "")))
13822 (defun org-get-tags ()
13823 "Get the list of tags specified in the current headline."
13824 (org-split-string (org-get-tags-string) ":"))
13826 (defun org-get-buffer-tags ()
13827 "Get a table of all tags used in the buffer, for completion."
13828 (let (tags)
13829 (save-excursion
13830 (goto-char (point-min))
13831 (while (re-search-forward
13832 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13833 (when (equal (char-after (point-at-bol 0)) ?*)
13834 (mapc (lambda (x) (add-to-list 'tags x))
13835 (org-split-string (org-match-string-no-properties 1) ":")))))
13836 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13837 (mapcar 'list tags)))
13839 ;;;; The mapping API
13841 ;;;###autoload
13842 (defun org-map-entries (func &optional match scope &rest skip)
13843 "Call FUNC at each headline selected by MATCH in SCOPE.
13845 FUNC is a function or a lisp form. The function will be called without
13846 arguments, with the cursor positioned at the beginning of the headline.
13847 The return values of all calls to the function will be collected and
13848 returned as a list.
13850 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13851 does not need to preserve point. After evaluation, the cursor will be
13852 moved to the end of the line (presumably of the headline of the
13853 processed entry) and search continues from there. Under some
13854 circumstances, this may not produce the wanted results. For example,
13855 if you have removed (e.g. archived) the current (sub)tree it could
13856 mean that the next entry will be skipped entirely. In such cases, you
13857 can specify the position from where search should continue by making
13858 FUNC set the variable `org-map-continue-from' to the desired buffer
13859 position.
13861 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13862 Only headlines that are matched by this query will be considered during
13863 the iteration. When MATCH is nil or t, all headlines will be
13864 visited by the iteration.
13866 SCOPE determines the scope of this command. It can be any of:
13868 nil The current buffer, respecting the restriction if any
13869 tree The subtree started with the entry at point
13870 region The entries within the active region, if any
13871 region-start-level
13872 The entries within the active region, but only those at
13873 the same level than the first one.
13874 file The current buffer, without restriction
13875 file-with-archives
13876 The current buffer, and any archives associated with it
13877 agenda All agenda files
13878 agenda-with-archives
13879 All agenda files with any archive files associated with them
13880 \(file1 file2 ...)
13881 If this is a list, all files in the list will be scanned
13883 The remaining args are treated as settings for the skipping facilities of
13884 the scanner. The following items can be given here:
13886 archive skip trees with the archive tag.
13887 comment skip trees with the COMMENT keyword
13888 function or Emacs Lisp form:
13889 will be used as value for `org-agenda-skip-function', so whenever
13890 the function returns t, FUNC will not be called for that
13891 entry and search will continue from the point where the
13892 function leaves it.
13894 If your function needs to retrieve the tags including inherited tags
13895 at the *current* entry, you can use the value of the variable
13896 `org-scanner-tags' which will be much faster than getting the value
13897 with `org-get-tags-at'. If your function gets properties with
13898 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13899 to t around the call to `org-entry-properties' to get the same speedup.
13900 Note that if your function moves around to retrieve tags and properties at
13901 a *different* entry, you cannot use these techniques."
13902 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13903 (not (org-region-active-p)))
13904 (let* ((org-agenda-archives-mode nil) ; just to make sure
13905 (org-agenda-skip-archived-trees (memq 'archive skip))
13906 (org-agenda-skip-comment-trees (memq 'comment skip))
13907 (org-agenda-skip-function
13908 (car (org-delete-all '(comment archive) skip)))
13909 (org-tags-match-list-sublevels t)
13910 (start-level (eq scope 'region-start-level))
13911 matcher file res
13912 org-todo-keywords-for-agenda
13913 org-done-keywords-for-agenda
13914 org-todo-keyword-alist-for-agenda
13915 org-drawers-for-agenda
13916 org-tag-alist-for-agenda
13917 todo-only)
13919 (cond
13920 ((eq match t) (setq matcher t))
13921 ((eq match nil) (setq matcher t))
13922 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13924 (save-excursion
13925 (save-restriction
13926 (cond ((eq scope 'tree)
13927 (org-back-to-heading t)
13928 (org-narrow-to-subtree)
13929 (setq scope nil))
13930 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13931 (org-region-active-p))
13932 ;; If needed, set start-level to a string like "2"
13933 (when start-level
13934 (save-excursion
13935 (goto-char (region-beginning))
13936 (unless (org-at-heading-p) (outline-next-heading))
13937 (setq start-level (org-current-level))))
13938 (narrow-to-region (region-beginning)
13939 (save-excursion
13940 (goto-char (region-end))
13941 (unless (and (bolp) (org-at-heading-p))
13942 (outline-next-heading))
13943 (point)))
13944 (setq scope nil)))
13946 (if (not scope)
13947 (progn
13948 (org-prepare-agenda-buffers
13949 (list (buffer-file-name (current-buffer))))
13950 (setq res (org-scan-tags func matcher todo-only start-level)))
13951 ;; Get the right scope
13952 (cond
13953 ((and scope (listp scope) (symbolp (car scope)))
13954 (setq scope (eval scope)))
13955 ((eq scope 'agenda)
13956 (setq scope (org-agenda-files t)))
13957 ((eq scope 'agenda-with-archives)
13958 (setq scope (org-agenda-files t))
13959 (setq scope (org-add-archive-files scope)))
13960 ((eq scope 'file)
13961 (setq scope (list (buffer-file-name))))
13962 ((eq scope 'file-with-archives)
13963 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13964 (org-prepare-agenda-buffers scope)
13965 (while (setq file (pop scope))
13966 (with-current-buffer (org-find-base-buffer-visiting file)
13967 (save-excursion
13968 (save-restriction
13969 (widen)
13970 (goto-char (point-min))
13971 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
13972 res)))
13974 ;;;; Properties
13976 ;;; Setting and retrieving properties
13978 (defconst org-special-properties
13979 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13980 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13981 "The special properties valid in Org-mode.
13983 These are properties that are not defined in the property drawer,
13984 but in some other way.")
13986 (defconst org-default-properties
13987 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13988 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13989 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13990 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13991 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13992 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13993 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13994 "Some properties that are used by Org-mode for various purposes.
13995 Being in this list makes sure that they are offered for completion.")
13997 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13998 "Regular expression matching the first line of a property drawer.")
14000 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14001 "Regular expression matching the last line of a property drawer.")
14003 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14004 "Regular expression matching the first line of a property drawer.")
14006 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14007 "Regular expression matching the first line of a property drawer.")
14009 (defconst org-property-drawer-re
14010 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14011 org-property-end-re "\\)\n?")
14012 "Matches an entire property drawer.")
14014 (defconst org-clock-drawer-re
14015 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14016 org-property-end-re "\\)\n?")
14017 "Matches an entire clock drawer.")
14019 (defsubst org-re-property (property)
14020 "Return a regexp matching PROPERTY.
14021 Match group 1 will be set to the value "
14022 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14024 (defun org-property-action ()
14025 "Do an action on properties."
14026 (interactive)
14027 (let (c)
14028 (org-at-property-p)
14029 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14030 (setq c (read-char-exclusive))
14031 (cond
14032 ((equal c ?s)
14033 (call-interactively 'org-set-property))
14034 ((equal c ?d)
14035 (call-interactively 'org-delete-property))
14036 ((equal c ?D)
14037 (call-interactively 'org-delete-property-globally))
14038 ((equal c ?c)
14039 (call-interactively 'org-compute-property-at-point))
14040 (t (error "No such property action %c" c)))))
14042 (defun org-set-effort (&optional value)
14043 "Set the effort property of the current entry.
14044 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14045 allowed value."
14046 (interactive "P")
14047 (if (equal value 0) (setq value 10))
14048 (let* ((completion-ignore-case t)
14049 (prop org-effort-property)
14050 (cur (org-entry-get nil prop))
14051 (allowed (org-property-get-allowed-values nil prop 'table))
14052 (existing (mapcar 'list (org-property-values prop)))
14054 (val (cond
14055 ((stringp value) value)
14056 ((and allowed (integerp value))
14057 (or (car (nth (1- value) allowed))
14058 (car (org-last allowed))))
14059 (allowed
14060 (message "Select 1-9,0, [RET%s]: %s"
14061 (if cur (concat "=" cur) "")
14062 (mapconcat 'car allowed " "))
14063 (setq rpl (read-char-exclusive))
14064 (if (equal rpl ?\r)
14066 (setq rpl (- rpl ?0))
14067 (if (equal rpl 0) (setq rpl 10))
14068 (if (and (> rpl 0) (<= rpl (length allowed)))
14069 (car (nth (1- rpl) allowed))
14070 (org-completing-read "Effort: " allowed nil))))
14072 (let (org-completion-use-ido org-completion-use-iswitchb)
14073 (org-completing-read
14074 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14075 (concat "[" cur "]") "")
14076 ": ")
14077 existing nil nil "" nil cur))))))
14078 (unless (equal (org-entry-get nil prop) val)
14079 (org-entry-put nil prop val))
14080 (message "%s is now %s" prop val)))
14082 (defun org-at-property-p ()
14083 "Is cursor inside a property drawer?"
14084 (save-excursion
14085 (beginning-of-line 1)
14086 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14087 (save-match-data ;; Used by calling procedures
14088 (let ((p (point))
14089 (range (unless (org-before-first-heading-p)
14090 (org-get-property-block))))
14091 (and range (<= (car range) p) (< p (cdr range))))))))
14093 (defun org-get-property-block (&optional beg end force)
14094 "Return the (beg . end) range of the body of the property drawer.
14095 BEG and END can be beginning and end of subtree, if not given
14096 they will be found.
14097 If the drawer does not exist and FORCE is non-nil, create the drawer."
14098 (catch 'exit
14099 (save-excursion
14100 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14101 (end (or end (progn (outline-next-heading) (point)))))
14102 (goto-char beg)
14103 (if (re-search-forward org-property-start-re end t)
14104 (setq beg (1+ (match-end 0)))
14105 (if force
14106 (save-excursion
14107 (org-insert-property-drawer)
14108 (setq end (progn (outline-next-heading) (point))))
14109 (throw 'exit nil))
14110 (goto-char beg)
14111 (if (re-search-forward org-property-start-re end t)
14112 (setq beg (1+ (match-end 0)))))
14113 (if (re-search-forward org-property-end-re end t)
14114 (setq end (match-beginning 0))
14115 (or force (throw 'exit nil))
14116 (goto-char beg)
14117 (setq end beg)
14118 (org-indent-line-function)
14119 (insert ":END:\n"))
14120 (cons beg end)))))
14122 (defun org-entry-properties (&optional pom which specific)
14123 "Get all properties of the entry at point-or-marker POM.
14124 This includes the TODO keyword, the tags, time strings for deadline,
14125 scheduled, and clocking, and any additional properties defined in the
14126 entry. The return value is an alist, keys may occur multiple times
14127 if the property key was used several times.
14128 POM may also be nil, in which case the current entry is used.
14129 If WHICH is nil or `all', get all properties. If WHICH is
14130 `special' or `standard', only get that subclass. If WHICH
14131 is a string only get exactly this property. SPECIFIC can be a string, the
14132 specific property we are interested in. Specifying it can speed
14133 things up because then unnecessary parsing is avoided."
14134 (setq which (or which 'all))
14135 (org-with-point-at pom
14136 (let ((clockstr (substring org-clock-string 0 -1))
14137 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14138 (case-fold-search nil)
14139 beg end range props sum-props key key1 value string clocksum)
14140 (save-excursion
14141 (when (condition-case nil
14142 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14143 (error nil))
14144 (setq beg (point))
14145 (setq sum-props (get-text-property (point) 'org-summaries))
14146 (setq clocksum (get-text-property (point) :org-clock-minutes))
14147 (outline-next-heading)
14148 (setq end (point))
14149 (when (memq which '(all special))
14150 ;; Get the special properties, like TODO and tags
14151 (goto-char beg)
14152 (when (and (or (not specific) (string= specific "TODO"))
14153 (looking-at org-todo-line-regexp) (match-end 2))
14154 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14155 (when (and (or (not specific) (string= specific "PRIORITY"))
14156 (looking-at org-priority-regexp))
14157 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14158 (when (or (not specific) (string= specific "FILE"))
14159 (push (cons "FILE" buffer-file-name) props))
14160 (when (and (or (not specific) (string= specific "TAGS"))
14161 (setq value (org-get-tags-string))
14162 (string-match "\\S-" value))
14163 (push (cons "TAGS" value) props))
14164 (when (and (or (not specific) (string= specific "ALLTAGS"))
14165 (setq value (org-get-tags-at)))
14166 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14167 ":"))
14168 props))
14169 (when (or (not specific) (string= specific "BLOCKED"))
14170 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14171 (when (or (not specific)
14172 (member specific
14173 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14174 "TIMESTAMP" "TIMESTAMP_IA")))
14175 (catch 'match
14176 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14177 (setq key (if (match-end 1)
14178 (substring (org-match-string-no-properties 1)
14179 0 -1))
14180 string (if (equal key clockstr)
14181 (org-no-properties
14182 (org-trim
14183 (buffer-substring
14184 (match-beginning 3) (goto-char
14185 (point-at-eol)))))
14186 (substring (org-match-string-no-properties 3)
14187 1 -1)))
14188 ;; Get the correct property name from the key. This is
14189 ;; necessary if the user has configured time keywords.
14190 (setq key1 (concat key ":"))
14191 (cond
14192 ((not key)
14193 (setq key
14194 (if (= (char-after (match-beginning 3)) ?\[)
14195 "TIMESTAMP_IA" "TIMESTAMP")))
14196 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14197 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14198 ((equal key1 org-closed-string) (setq key "CLOSED"))
14199 ((equal key1 org-clock-string) (setq key "CLOCK")))
14200 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14201 (progn
14202 (push (cons key string) props)
14203 ;; no need to search further if match is found
14204 (throw 'match t))
14205 (when (or (equal key "CLOCK") (not (assoc key props)))
14206 (push (cons key string) props))))))
14209 (when (memq which '(all standard))
14210 ;; Get the standard properties, like :PROP: ...
14211 (setq range (org-get-property-block beg end))
14212 (when range
14213 (goto-char (car range))
14214 (while (re-search-forward
14215 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14216 (cdr range) t)
14217 (setq key (org-match-string-no-properties 1)
14218 value (org-trim (or (org-match-string-no-properties 2) "")))
14219 (unless (member key excluded)
14220 (push (cons key (or value "")) props)))))
14221 (if clocksum
14222 (push (cons "CLOCKSUM"
14223 (org-columns-number-to-string (/ (float clocksum) 60.)
14224 'add_times))
14225 props))
14226 (unless (assoc "CATEGORY" props)
14227 (push (cons "CATEGORY" (org-get-category)) props))
14228 (append sum-props (nreverse props)))))))
14230 (defun org-entry-get (pom property &optional inherit literal-nil)
14231 "Get value of PROPERTY for entry at point-or-marker POM.
14232 If INHERIT is non-nil and the entry does not have the property,
14233 then also check higher levels of the hierarchy.
14234 If INHERIT is the symbol `selective', use inheritance only if the setting
14235 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14236 If the property is present but empty, the return value is the empty string.
14237 If the property is not present at all, nil is returned.
14239 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14240 do not interpret it as the list atom nil. This is used for inheritance
14241 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14242 (org-with-point-at pom
14243 (if (and inherit (if (eq inherit 'selective)
14244 (org-property-inherit-p property)
14246 (org-entry-get-with-inheritance property literal-nil)
14247 (if (member property org-special-properties)
14248 ;; We need a special property. Use `org-entry-properties' to
14249 ;; retrieve it, but specify the wanted property
14250 (cdr (assoc property (org-entry-properties nil 'special property)))
14251 (let ((range (unless (org-before-first-heading-p)
14252 (org-get-property-block)))
14253 (props (list (or (assoc property org-file-properties)
14254 (assoc property org-global-properties)
14255 (assoc property org-global-properties-fixed))))
14256 val)
14257 (flet ((ap (key)
14258 (when (re-search-forward
14259 (org-re-property key) (cdr range) t)
14260 (setq props
14261 (org-update-property-plist
14263 (if (match-end 1)
14264 (org-match-string-no-properties 1) "")
14265 props)))))
14266 (when (and range (goto-char (car range)))
14267 (ap property)
14268 (goto-char (car range))
14269 (while (ap (concat property "+")))
14270 (setq val (cdr (assoc property props)))
14271 (when val (if literal-nil val (org-not-nil val))))))))))
14273 (defun org-property-or-variable-value (var &optional inherit)
14274 "Check if there is a property fixing the value of VAR.
14275 If yes, return this value. If not, return the current value of the variable."
14276 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14277 (if (and prop (stringp prop) (string-match "\\S-" prop))
14278 (read prop)
14279 (symbol-value var))))
14281 (defun org-entry-delete (pom property)
14282 "Delete the property PROPERTY from entry at point-or-marker POM."
14283 (org-with-point-at pom
14284 (if (member property org-special-properties)
14285 nil ; cannot delete these properties.
14286 (let ((range (org-get-property-block)))
14287 (if (and range
14288 (goto-char (car range))
14289 (re-search-forward
14290 (org-re-property property)
14291 (cdr range) t))
14292 (progn
14293 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14295 nil)))))
14297 ;; Multi-values properties are properties that contain multiple values
14298 ;; These values are assumed to be single words, separated by whitespace.
14299 (defun org-entry-add-to-multivalued-property (pom property value)
14300 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14301 (let* ((old (org-entry-get pom property))
14302 (values (and old (org-split-string old "[ \t]"))))
14303 (setq value (org-entry-protect-space value))
14304 (unless (member value values)
14305 (setq values (cons value values))
14306 (org-entry-put pom property
14307 (mapconcat 'identity values " ")))))
14309 (defun org-entry-remove-from-multivalued-property (pom property value)
14310 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14311 (let* ((old (org-entry-get pom property))
14312 (values (and old (org-split-string old "[ \t]"))))
14313 (setq value (org-entry-protect-space value))
14314 (when (member value values)
14315 (setq values (delete value values))
14316 (org-entry-put pom property
14317 (mapconcat 'identity values " ")))))
14319 (defun org-entry-member-in-multivalued-property (pom property value)
14320 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14321 (let* ((old (org-entry-get pom property))
14322 (values (and old (org-split-string old "[ \t]"))))
14323 (setq value (org-entry-protect-space value))
14324 (member value values)))
14326 (defun org-entry-get-multivalued-property (pom property)
14327 "Return a list of values in a multivalued property."
14328 (let* ((value (org-entry-get pom property))
14329 (values (and value (org-split-string value "[ \t]"))))
14330 (mapcar 'org-entry-restore-space values)))
14332 (defun org-entry-put-multivalued-property (pom property &rest values)
14333 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14334 VALUES should be a list of strings. Spaces will be protected."
14335 (org-entry-put pom property
14336 (mapconcat 'org-entry-protect-space values " "))
14337 (let* ((value (org-entry-get pom property))
14338 (values (and value (org-split-string value "[ \t]"))))
14339 (mapcar 'org-entry-restore-space values)))
14341 (defun org-entry-protect-space (s)
14342 "Protect spaces and newline in string S."
14343 (while (string-match " " s)
14344 (setq s (replace-match "%20" t t s)))
14345 (while (string-match "\n" s)
14346 (setq s (replace-match "%0A" t t s)))
14349 (defun org-entry-restore-space (s)
14350 "Restore spaces and newline in string S."
14351 (while (string-match "%20" s)
14352 (setq s (replace-match " " t t s)))
14353 (while (string-match "%0A" s)
14354 (setq s (replace-match "\n" t t s)))
14357 (defvar org-entry-property-inherited-from (make-marker)
14358 "Marker pointing to the entry from where a property was inherited.
14359 Each call to `org-entry-get-with-inheritance' will set this marker to the
14360 location of the entry where the inheritance search matched. If there was
14361 no match, the marker will point nowhere.
14362 Note that also `org-entry-get' calls this function, if the INHERIT flag
14363 is set.")
14365 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14366 "Get entry property, and search higher levels if not present.
14367 The search will stop at the first ancestor which has the property defined.
14368 If the value found is \"nil\", return nil to show that the property
14369 should be considered as undefined (this is the meaning of nil here).
14370 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14371 (move-marker org-entry-property-inherited-from nil)
14372 (let (tmp)
14373 (unless (org-before-first-heading-p)
14374 (save-excursion
14375 (save-restriction
14376 (widen)
14377 (catch 'ex
14378 (while t
14379 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14380 (org-back-to-heading t)
14381 (move-marker org-entry-property-inherited-from (point))
14382 (throw 'ex tmp))
14383 (or (org-up-heading-safe) (throw 'ex nil)))))))
14384 (setq tmp (or tmp
14385 (cdr (assoc property org-file-properties))
14386 (cdr (assoc property org-global-properties))
14387 (cdr (assoc property org-global-properties-fixed))))
14388 (if literal-nil tmp (org-not-nil tmp))))
14390 (defvar org-property-changed-functions nil
14391 "Hook called when the value of a property has changed.
14392 Each hook function should accept two arguments, the name of the property
14393 and the new value.")
14395 (defun org-entry-put (pom property value)
14396 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14397 (org-with-point-at pom
14398 (org-back-to-heading t)
14399 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14400 range)
14401 (cond
14402 ((equal property "TODO")
14403 (when (and (stringp value) (string-match "\\S-" value)
14404 (not (member value org-todo-keywords-1)))
14405 (error "\"%s\" is not a valid TODO state" value))
14406 (if (or (not value)
14407 (not (string-match "\\S-" value)))
14408 (setq value 'none))
14409 (org-todo value)
14410 (org-set-tags nil 'align))
14411 ((equal property "PRIORITY")
14412 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14413 (string-to-char value) ?\ ))
14414 (org-set-tags nil 'align))
14415 ((equal property "SCHEDULED")
14416 (if (re-search-forward org-scheduled-time-regexp end t)
14417 (cond
14418 ((eq value 'earlier) (org-timestamp-change -1 'day))
14419 ((eq value 'later) (org-timestamp-change 1 'day))
14420 (t (call-interactively 'org-schedule)))
14421 (call-interactively 'org-schedule)))
14422 ((equal property "DEADLINE")
14423 (if (re-search-forward org-deadline-time-regexp end t)
14424 (cond
14425 ((eq value 'earlier) (org-timestamp-change -1 'day))
14426 ((eq value 'later) (org-timestamp-change 1 'day))
14427 (t (call-interactively 'org-deadline)))
14428 (call-interactively 'org-deadline)))
14429 ((member property org-special-properties)
14430 (error "The %s property can not yet be set with `org-entry-put'"
14431 property))
14432 (t ; a non-special property
14433 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14434 (setq range (org-get-property-block beg end 'force))
14435 (goto-char (car range))
14436 (if (re-search-forward
14437 (org-re-property property) (cdr range) t)
14438 (progn
14439 (delete-region (match-beginning 0) (match-end 0))
14440 (goto-char (match-beginning 0)))
14441 (goto-char (cdr range))
14442 (insert "\n")
14443 (backward-char 1)
14444 (org-indent-line-function))
14445 (insert ":" property ":")
14446 (and value (insert " " value))
14447 (org-indent-line-function)))))
14448 (run-hook-with-args 'org-property-changed-functions property value)))
14450 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14451 "Get all property keys in the current buffer.
14452 With INCLUDE-SPECIALS, also list the special properties that reflect things
14453 like tags and TODO state.
14454 With INCLUDE-DEFAULTS, also include properties that has special meaning
14455 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14456 and others.
14457 With INCLUDE-COLUMNS, also include property names given in COLUMN
14458 formats in the current buffer."
14459 (let (rtn range cfmt s p)
14460 (save-excursion
14461 (save-restriction
14462 (widen)
14463 (goto-char (point-min))
14464 (while (re-search-forward org-property-start-re nil t)
14465 (setq range (org-get-property-block))
14466 (goto-char (car range))
14467 (while (re-search-forward
14468 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14469 (cdr range) t)
14470 (add-to-list 'rtn (org-match-string-no-properties 1)))
14471 (outline-next-heading))))
14473 (when include-specials
14474 (setq rtn (append org-special-properties rtn)))
14476 (when include-defaults
14477 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14478 (add-to-list 'rtn org-effort-property))
14480 (when include-columns
14481 (save-excursion
14482 (save-restriction
14483 (widen)
14484 (goto-char (point-min))
14485 (while (re-search-forward
14486 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14487 nil t)
14488 (setq cfmt (match-string 2) s 0)
14489 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14490 cfmt s)
14491 (setq s (match-end 0)
14492 p (match-string 1 cfmt))
14493 (unless (or (equal p "ITEM")
14494 (member p org-special-properties))
14495 (add-to-list 'rtn (match-string 1 cfmt))))))))
14497 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14499 (defun org-property-values (key)
14500 "Return a list of all values of property KEY in the current buffer."
14501 (save-excursion
14502 (save-restriction
14503 (widen)
14504 (goto-char (point-min))
14505 (let ((re (org-re-property key))
14506 values)
14507 (while (re-search-forward re nil t)
14508 (add-to-list 'values (org-trim (match-string 1))))
14509 (delete "" values)))))
14511 (defun org-insert-property-drawer ()
14512 "Insert a property drawer into the current entry."
14513 (org-back-to-heading t)
14514 (looking-at org-outline-regexp)
14515 (let ((indent (if org-adapt-indentation
14516 (- (match-end 0) (match-beginning 0))
14518 (beg (point))
14519 (re (concat "^[ \t]*" org-keyword-time-regexp))
14520 end hiddenp)
14521 (outline-next-heading)
14522 (setq end (point))
14523 (goto-char beg)
14524 (while (re-search-forward re end t))
14525 (setq hiddenp (outline-invisible-p))
14526 (end-of-line 1)
14527 (and (equal (char-after) ?\n) (forward-char 1))
14528 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14529 (if (member (match-string 1) '("CLOCK:" ":END:"))
14530 ;; just skip this line
14531 (beginning-of-line 2)
14532 ;; Drawer start, find the end
14533 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14534 (beginning-of-line 1)))
14535 (org-skip-over-state-notes)
14536 (skip-chars-backward " \t\n\r")
14537 (if (eq (char-before) ?*) (forward-char 1))
14538 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14539 (beginning-of-line 0)
14540 (org-indent-to-column indent)
14541 (beginning-of-line 2)
14542 (org-indent-to-column indent)
14543 (beginning-of-line 0)
14544 (if hiddenp
14545 (save-excursion
14546 (org-back-to-heading t)
14547 (hide-entry))
14548 (org-flag-drawer t))))
14550 (defun org-insert-drawer (&optional arg drawer)
14551 "Insert a drawer at point.
14553 Optional argument DRAWER, when non-nil, is a string representing
14554 drawer's name. Otherwise, the user is prompted for a name.
14556 If a region is active, insert the drawer around that region
14557 instead.
14559 Point is left between drawer's boundaries."
14560 (interactive "P")
14561 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14562 "LOGBOOK"))
14563 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14564 ;; internally by Org. They are meant to be inserted
14565 ;; automatically.
14566 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14567 ;; Remove system drawers from list. Note: For some reason,
14568 ;; `org-completing-read' ignores the predicate while
14569 ;; `completing-read' handles it fine.
14570 (drawer (if arg "PROPERTIES"
14571 (or drawer
14572 (completing-read
14573 "Drawer: " org-drawers
14574 (lambda (d) (not (member d system-drawers))))))))
14575 (cond
14576 ;; With C-u, fall back on `org-insert-property-drawer'
14577 (arg (org-insert-property-drawer))
14578 ;; With an active region, insert a drawer at point.
14579 ((not (org-region-active-p))
14580 (progn
14581 (unless (bolp) (insert "\n"))
14582 (insert (format ":%s:\n\n:END:\n" drawer))
14583 (forward-line -2)))
14584 ;; Otherwise, insert the drawer at point
14586 (let ((rbeg (region-beginning))
14587 (rend (copy-marker (region-end))))
14588 (unwind-protect
14589 (progn
14590 (goto-char rbeg)
14591 (beginning-of-line)
14592 (when (save-excursion
14593 (re-search-forward org-outline-regexp-bol rend t))
14594 (error "Drawers cannot contain headlines"))
14595 ;; Position point at the beginning of the first
14596 ;; non-blank line in region. Insert drawer's opening
14597 ;; there, then indent it.
14598 (org-skip-whitespace)
14599 (beginning-of-line)
14600 (insert ":" drawer ":\n")
14601 (forward-line -1)
14602 (indent-for-tab-command)
14603 ;; Move point to the beginning of the first blank line
14604 ;; after the last non-blank line in region. Insert
14605 ;; drawer's closing, then indent it.
14606 (goto-char rend)
14607 (skip-chars-backward " \r\t\n")
14608 (insert "\n:END:")
14609 (indent-for-tab-command)
14610 (unless (eolp) (insert "\n")))
14611 ;; Clear marker, whatever the outcome of insertion is.
14612 (set-marker rend nil)))))))
14614 (defvar org-property-set-functions-alist nil
14615 "Property set function alist.
14616 Each entry should have the following format:
14618 (PROPERTY . READ-FUNCTION)
14620 The read function will be called with the same argument as
14621 `org-completing-read'.")
14623 (defun org-set-property-function (property)
14624 "Get the function that should be used to set PROPERTY.
14625 This is computed according to `org-property-set-functions-alist'."
14626 (or (cdr (assoc property org-property-set-functions-alist))
14627 'org-completing-read))
14629 (defun org-read-property-value (property)
14630 "Read PROPERTY value from user."
14631 (let* ((completion-ignore-case t)
14632 (allowed (org-property-get-allowed-values nil property 'table))
14633 (cur (org-entry-get nil property))
14634 (prompt (concat property " value"
14635 (if (and cur (string-match "\\S-" cur))
14636 (concat " [" cur "]") "") ": "))
14637 (set-function (org-set-property-function property))
14638 (val (if allowed
14639 (funcall set-function prompt allowed nil
14640 (not (get-text-property 0 'org-unrestricted
14641 (caar allowed))))
14642 (let (org-completion-use-ido org-completion-use-iswitchb)
14643 (funcall set-function prompt
14644 (mapcar 'list (org-property-values property))
14645 nil nil "" nil cur)))))
14646 (if (equal val "")
14648 val)))
14650 (defvar org-last-set-property nil)
14651 (defun org-read-property-name ()
14652 "Read a property name."
14653 (let* ((completion-ignore-case t)
14654 (keys (org-buffer-property-keys nil t t))
14655 (default-prop (or (save-excursion
14656 (save-match-data
14657 (beginning-of-line)
14658 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14659 (null (string= (match-string 1) "END"))
14660 (match-string 1))))
14661 org-last-set-property))
14662 (property (org-icompleting-read
14663 (concat "Property"
14664 (if default-prop (concat " [" default-prop "]") "")
14665 ": ")
14666 (mapcar 'list keys)
14667 nil nil nil nil
14668 default-prop
14670 (if (member property keys)
14671 property
14672 (or (cdr (assoc (downcase property)
14673 (mapcar (lambda (x) (cons (downcase x) x))
14674 keys)))
14675 property))))
14677 (defun org-set-property (property value)
14678 "In the current entry, set PROPERTY to VALUE.
14679 When called interactively, this will prompt for a property name, offering
14680 completion on existing and default properties. And then it will prompt
14681 for a value, offering completion either on allowed values (via an inherited
14682 xxx_ALL property) or on existing values in other instances of this property
14683 in the current file."
14684 (interactive (list nil nil))
14685 (let* ((property (or property (org-read-property-name)))
14686 (value (or value (org-read-property-value property)))
14687 (fn (assoc property org-properties-postprocess-alist)))
14688 (setq org-last-set-property property)
14689 ;; Possibly postprocess the inserted value:
14690 (when fn (setq value (funcall (cadr fn) value)))
14691 (unless (equal (org-entry-get nil property) value)
14692 (org-entry-put nil property value))))
14694 (defun org-delete-property (property)
14695 "In the current entry, delete PROPERTY."
14696 (interactive
14697 (let* ((completion-ignore-case t)
14698 (prop (org-icompleting-read "Property: "
14699 (org-entry-properties nil 'standard))))
14700 (list prop)))
14701 (message "Property %s %s" property
14702 (if (org-entry-delete nil property)
14703 "deleted"
14704 "was not present in the entry")))
14706 (defun org-delete-property-globally (property)
14707 "Remove PROPERTY globally, from all entries."
14708 (interactive
14709 (let* ((completion-ignore-case t)
14710 (prop (org-icompleting-read
14711 "Globally remove property: "
14712 (mapcar 'list (org-buffer-property-keys)))))
14713 (list prop)))
14714 (save-excursion
14715 (save-restriction
14716 (widen)
14717 (goto-char (point-min))
14718 (let ((cnt 0))
14719 (while (re-search-forward
14720 (org-re-property property)
14721 nil t)
14722 (setq cnt (1+ cnt))
14723 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14724 (message "Property \"%s\" removed from %d entries" property cnt)))))
14726 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14728 (defun org-compute-property-at-point ()
14729 "Compute the property at point.
14730 This looks for an enclosing column format, extracts the operator and
14731 then applies it to the property in the column format's scope."
14732 (interactive)
14733 (unless (org-at-property-p)
14734 (error "Not at a property"))
14735 (let ((prop (org-match-string-no-properties 2)))
14736 (org-columns-get-format-and-top-level)
14737 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14738 (error "No operator defined for property %s" prop))
14739 (org-columns-compute prop)))
14741 (defvar org-property-allowed-value-functions nil
14742 "Hook for functions supplying allowed values for a specific property.
14743 The functions must take a single argument, the name of the property, and
14744 return a flat list of allowed values. If \":ETC\" is one of
14745 the values, this means that these values are intended as defaults for
14746 completion, but that other values should be allowed too.
14747 The functions must return nil if they are not responsible for this
14748 property.")
14750 (defun org-property-get-allowed-values (pom property &optional table)
14751 "Get allowed values for the property PROPERTY.
14752 When TABLE is non-nil, return an alist that can directly be used for
14753 completion."
14754 (let (vals)
14755 (cond
14756 ((equal property "TODO")
14757 (setq vals (org-with-point-at pom
14758 (append org-todo-keywords-1 '("")))))
14759 ((equal property "PRIORITY")
14760 (let ((n org-lowest-priority))
14761 (while (>= n org-highest-priority)
14762 (push (char-to-string n) vals)
14763 (setq n (1- n)))))
14764 ((member property org-special-properties))
14765 ((setq vals (run-hook-with-args-until-success
14766 'org-property-allowed-value-functions property)))
14768 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14769 (when (and vals (string-match "\\S-" vals))
14770 (setq vals (car (read-from-string (concat "(" vals ")"))))
14771 (setq vals (mapcar (lambda (x)
14772 (cond ((stringp x) x)
14773 ((numberp x) (number-to-string x))
14774 ((symbolp x) (symbol-name x))
14775 (t "???")))
14776 vals)))))
14777 (when (member ":ETC" vals)
14778 (setq vals (remove ":ETC" vals))
14779 (org-add-props (car vals) '(org-unrestricted t)))
14780 (if table (mapcar 'list vals) vals)))
14782 (defun org-property-previous-allowed-value (&optional previous)
14783 "Switch to the next allowed value for this property."
14784 (interactive)
14785 (org-property-next-allowed-value t))
14787 (defun org-property-next-allowed-value (&optional previous)
14788 "Switch to the next allowed value for this property."
14789 (interactive)
14790 (unless (org-at-property-p)
14791 (error "Not at a property"))
14792 (let* ((key (match-string 2))
14793 (value (match-string 3))
14794 (allowed (or (org-property-get-allowed-values (point) key)
14795 (and (member value '("[ ]" "[-]" "[X]"))
14796 '("[ ]" "[X]"))))
14797 nval)
14798 (unless allowed
14799 (error "Allowed values for this property have not been defined"))
14800 (if previous (setq allowed (reverse allowed)))
14801 (if (member value allowed)
14802 (setq nval (car (cdr (member value allowed)))))
14803 (setq nval (or nval (car allowed)))
14804 (if (equal nval value)
14805 (error "Only one allowed value for this property"))
14806 (org-at-property-p)
14807 (replace-match (concat " :" key ": " nval) t t)
14808 (org-indent-line-function)
14809 (beginning-of-line 1)
14810 (skip-chars-forward " \t")
14811 (run-hook-with-args 'org-property-changed-functions key nval)))
14813 (defun org-find-olp (path &optional this-buffer)
14814 "Return a marker pointing to the entry at outline path OLP.
14815 If anything goes wrong, throw an error.
14816 You can wrap this call to catch the error like this:
14818 (condition-case msg
14819 (org-mobile-locate-entry (match-string 4))
14820 (error (nth 1 msg)))
14822 The return value will then be either a string with the error message,
14823 or a marker if everything is OK.
14825 If THIS-BUFFER is set, the outline path does not contain a file,
14826 only headings."
14827 (let* ((file (if this-buffer buffer-file-name (pop path)))
14828 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14829 (level 1)
14830 (lmin 1)
14831 (lmax 1)
14832 limit re end found pos heading cnt flevel)
14833 (unless buffer (error "File not found :%s" file))
14834 (with-current-buffer buffer
14835 (save-excursion
14836 (save-restriction
14837 (widen)
14838 (setq limit (point-max))
14839 (goto-char (point-min))
14840 (while (setq heading (pop path))
14841 (setq re (format org-complex-heading-regexp-format
14842 (regexp-quote heading)))
14843 (setq cnt 0 pos (point))
14844 (while (re-search-forward re end t)
14845 (setq level (- (match-end 1) (match-beginning 1)))
14846 (if (and (>= level lmin) (<= level lmax))
14847 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14848 (when (= cnt 0) (error "Heading not found on level %d: %s"
14849 lmax heading))
14850 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14851 lmax heading))
14852 (goto-char found)
14853 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14854 (setq end (save-excursion (org-end-of-subtree t t))))
14855 (when (org-at-heading-p)
14856 (move-marker (make-marker) (point))))))))
14858 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14859 "Find node HEADING in BUFFER.
14860 Return a marker to the heading if it was found, or nil if not.
14861 If POS-ONLY is set, return just the position instead of a marker.
14863 The heading text must match exact, but it may have a TODO keyword,
14864 a priority cookie and tags in the standard locations."
14865 (with-current-buffer (or buffer (current-buffer))
14866 (save-excursion
14867 (save-restriction
14868 (widen)
14869 (goto-char (point-min))
14870 (let (case-fold-search)
14871 (if (re-search-forward
14872 (format org-complex-heading-regexp-format
14873 (regexp-quote heading)) nil t)
14874 (if pos-only
14875 (match-beginning 0)
14876 (move-marker (make-marker) (match-beginning 0)))))))))
14878 (defun org-find-exact-heading-in-directory (heading &optional dir)
14879 "Find Org node headline HEADING in all .org files in directory DIR.
14880 When the target headline is found, return a marker to this location."
14881 (let ((files (directory-files (or dir default-directory)
14882 nil "\\`[^.#].*\\.org\\'"))
14883 file visiting m buffer)
14884 (catch 'found
14885 (while (setq file (pop files))
14886 (message "trying %s" file)
14887 (setq visiting (org-find-base-buffer-visiting file))
14888 (setq buffer (or visiting (find-file-noselect file)))
14889 (setq m (org-find-exact-headline-in-buffer
14890 heading buffer))
14891 (when (and (not m) (not visiting)) (kill-buffer buffer))
14892 (and m (throw 'found m))))))
14894 (defun org-find-entry-with-id (ident)
14895 "Locate the entry that contains the ID property with exact value IDENT.
14896 IDENT can be a string, a symbol or a number, this function will search for
14897 the string representation of it.
14898 Return the position where this entry starts, or nil if there is no such entry."
14899 (interactive "sID: ")
14900 (let ((id (cond
14901 ((stringp ident) ident)
14902 ((symbol-name ident) (symbol-name ident))
14903 ((numberp ident) (number-to-string ident))
14904 (t (error "IDENT %s must be a string, symbol or number" ident))))
14905 (case-fold-search nil))
14906 (save-excursion
14907 (save-restriction
14908 (widen)
14909 (goto-char (point-min))
14910 (when (re-search-forward
14911 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14912 nil t)
14913 (org-back-to-heading t)
14914 (point))))))
14916 ;;;; Timestamps
14918 (defvar org-last-changed-timestamp nil)
14919 (defvar org-last-inserted-timestamp nil
14920 "The last time stamp inserted with `org-insert-time-stamp'.")
14921 (defvar org-time-was-given) ; dynamically scoped parameter
14922 (defvar org-end-time-was-given) ; dynamically scoped parameter
14923 (defvar org-ts-what) ; dynamically scoped parameter
14925 (defun org-time-stamp (arg &optional inactive)
14926 "Prompt for a date/time and insert a time stamp.
14927 If the user specifies a time like HH:MM, or if this command is called
14928 with a prefix argument, the time stamp will contain date and time.
14929 Otherwise, only the date will be included. All parts of a date not
14930 specified by the user will be filled in from the current date/time.
14931 So if you press just return without typing anything, the time stamp
14932 will represent the current date/time. If there is already a timestamp
14933 at the cursor, it will be modified."
14934 (interactive "P")
14935 (let* ((ts nil)
14936 (default-time
14937 ;; Default time is either today, or, when entering a range,
14938 ;; the range start.
14939 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14940 (save-excursion
14941 (re-search-backward
14942 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14943 (- (point) 20) t)))
14944 (apply 'encode-time (org-parse-time-string (match-string 1)))
14945 (current-time)))
14946 (default-input (and ts (org-get-compact-tod ts)))
14947 (repeater (save-excursion
14948 (save-match-data
14949 (beginning-of-line)
14950 (when (re-search-forward
14951 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14952 (save-excursion (progn (end-of-line) (point))) t)
14953 (match-string 0)))))
14954 org-time-was-given org-end-time-was-given time)
14955 (cond
14956 ((and (org-at-timestamp-p t)
14957 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14958 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14959 (insert "--")
14960 (setq time (let ((this-command this-command))
14961 (org-read-date arg 'totime nil nil
14962 default-time default-input inactive)))
14963 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14964 ((org-at-timestamp-p t)
14965 (setq time (let ((this-command this-command))
14966 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14967 (when (org-at-timestamp-p t) ; just to get the match data
14968 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14969 (replace-match "")
14970 (setq org-last-changed-timestamp
14971 (org-insert-time-stamp
14972 time (or org-time-was-given arg)
14973 inactive nil nil (list org-end-time-was-given)))
14974 (when repeater (goto-char (1- (point))) (insert " " repeater)
14975 (setq org-last-changed-timestamp
14976 (concat (substring org-last-inserted-timestamp 0 -1)
14977 " " repeater ">"))))
14978 (message "Timestamp updated"))
14980 (setq time (let ((this-command this-command))
14981 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14982 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14983 nil nil (list org-end-time-was-given))))))
14985 ;; FIXME: can we use this for something else, like computing time differences?
14986 (defun org-get-compact-tod (s)
14987 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14988 (let* ((t1 (match-string 1 s))
14989 (h1 (string-to-number (match-string 2 s)))
14990 (m1 (string-to-number (match-string 3 s)))
14991 (t2 (and (match-end 4) (match-string 5 s)))
14992 (h2 (and t2 (string-to-number (match-string 6 s))))
14993 (m2 (and t2 (string-to-number (match-string 7 s))))
14994 dh dm)
14995 (if (not t2)
14997 (setq dh (- h2 h1) dm (- m2 m1))
14998 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14999 (concat t1 "+" (number-to-string dh)
15000 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15002 (defun org-time-stamp-inactive (&optional arg)
15003 "Insert an inactive time stamp.
15004 An inactive time stamp is enclosed in square brackets instead of angle
15005 brackets. It is inactive in the sense that it does not trigger agenda entries,
15006 does not link to the calendar and cannot be changed with the S-cursor keys.
15007 So these are more for recording a certain time/date."
15008 (interactive "P")
15009 (org-time-stamp arg 'inactive))
15011 (defvar org-date-ovl (make-overlay 1 1))
15012 (overlay-put org-date-ovl 'face 'org-warning)
15013 (org-detach-overlay org-date-ovl)
15015 (defvar org-ans1) ; dynamically scoped parameter
15016 (defvar org-ans2) ; dynamically scoped parameter
15018 (defvar org-plain-time-of-day-regexp) ; defined below
15020 (defvar org-overriding-default-time nil) ; dynamically scoped
15021 (defvar org-read-date-overlay nil)
15022 (defvar org-dcst nil) ; dynamically scoped
15023 (defvar org-read-date-history nil)
15024 (defvar org-read-date-final-answer nil)
15025 (defvar org-read-date-analyze-futurep nil)
15026 (defvar org-read-date-analyze-forced-year nil)
15027 (defvar org-read-date-inactive)
15029 (defun org-read-date (&optional org-with-time to-time from-string prompt
15030 default-time default-input inactive)
15031 "Read a date, possibly a time, and make things smooth for the user.
15032 The prompt will suggest to enter an ISO date, but you can also enter anything
15033 which will at least partially be understood by `parse-time-string'.
15034 Unrecognized parts of the date will default to the current day, month, year,
15035 hour and minute. If this command is called to replace a timestamp at point,
15036 or to enter the second timestamp of a range, the default time is taken
15037 from the existing stamp. Furthermore, the command prefers the future,
15038 so if you are giving a date where the year is not given, and the day-month
15039 combination is already past in the current year, it will assume you
15040 mean next year. For details, see the manual. A few examples:
15042 3-2-5 --> 2003-02-05
15043 feb 15 --> currentyear-02-15
15044 2/15 --> currentyear-02-15
15045 sep 12 9 --> 2009-09-12
15046 12:45 --> today 12:45
15047 22 sept 0:34 --> currentyear-09-22 0:34
15048 12 --> currentyear-currentmonth-12
15049 Fri --> nearest Friday (today or later)
15050 etc.
15052 Furthermore you can specify a relative date by giving, as the *first* thing
15053 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
15054 change in days weeks, months, years.
15055 With a single plus or minus, the date is relative to today. With a double
15056 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15057 +4d --> four days from today
15058 +4 --> same as above
15059 +2w --> two weeks from today
15060 ++5 --> five days from default date
15062 The function understands only English month and weekday abbreviations.
15064 While prompting, a calendar is popped up - you can also select the
15065 date with the mouse (button 1). The calendar shows a period of three
15066 months. To scroll it to other months, use the keys `>' and `<'.
15067 If you don't like the calendar, turn it off with
15068 \(setq org-read-date-popup-calendar nil)
15070 With optional argument TO-TIME, the date will immediately be converted
15071 to an internal time.
15072 With an optional argument WITH-TIME, the prompt will suggest to also
15073 insert a time. Note that when WITH-TIME is not set, you can still
15074 enter a time, and this function will inform the calling routine about
15075 this change. The calling routine may then choose to change the format
15076 used to insert the time stamp into the buffer to include the time.
15077 With optional argument FROM-STRING, read from this string instead from
15078 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15079 the time/date that is used for everything that is not specified by the
15080 user."
15081 (require 'parse-time)
15082 (let* ((org-time-stamp-rounding-minutes
15083 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15084 (org-dcst org-display-custom-times)
15085 (ct (org-current-time))
15086 (org-def (or org-overriding-default-time default-time ct))
15087 (org-defdecode (decode-time org-def))
15088 (dummy (progn
15089 (when (< (nth 2 org-defdecode) org-extend-today-until)
15090 (setcar (nthcdr 2 org-defdecode) -1)
15091 (setcar (nthcdr 1 org-defdecode) 59)
15092 (setq org-def (apply 'encode-time org-defdecode)
15093 org-defdecode (decode-time org-def)))))
15094 (calendar-frame-setup nil)
15095 (calendar-setup nil)
15096 (calendar-move-hook nil)
15097 (calendar-view-diary-initially-flag nil)
15098 (calendar-view-holidays-initially-flag nil)
15099 (timestr (format-time-string
15100 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15101 (prompt (concat (if prompt (concat prompt " ") "")
15102 (format "Date+time [%s]: " timestr)))
15103 ans (org-ans0 "") org-ans1 org-ans2 final)
15105 (cond
15106 (from-string (setq ans from-string))
15107 (org-read-date-popup-calendar
15108 (save-excursion
15109 (save-window-excursion
15110 (calendar)
15111 (unwind-protect
15112 (progn
15113 (calendar-forward-day (- (time-to-days org-def)
15114 (calendar-absolute-from-gregorian
15115 (calendar-current-date))))
15116 (org-eval-in-calendar nil t)
15117 (let* ((old-map (current-local-map))
15118 (map (copy-keymap calendar-mode-map))
15119 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15120 (org-defkey map (kbd "RET") 'org-calendar-select)
15121 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15122 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15123 (org-defkey minibuffer-local-map [(meta shift left)]
15124 (lambda () (interactive)
15125 (org-eval-in-calendar '(calendar-backward-month 1))))
15126 (org-defkey minibuffer-local-map [(meta shift right)]
15127 (lambda () (interactive)
15128 (org-eval-in-calendar '(calendar-forward-month 1))))
15129 (org-defkey minibuffer-local-map [(meta shift up)]
15130 (lambda () (interactive)
15131 (org-eval-in-calendar '(calendar-backward-year 1))))
15132 (org-defkey minibuffer-local-map [(meta shift down)]
15133 (lambda () (interactive)
15134 (org-eval-in-calendar '(calendar-forward-year 1))))
15135 (org-defkey minibuffer-local-map [?\e (shift left)]
15136 (lambda () (interactive)
15137 (org-eval-in-calendar '(calendar-backward-month 1))))
15138 (org-defkey minibuffer-local-map [?\e (shift right)]
15139 (lambda () (interactive)
15140 (org-eval-in-calendar '(calendar-forward-month 1))))
15141 (org-defkey minibuffer-local-map [?\e (shift up)]
15142 (lambda () (interactive)
15143 (org-eval-in-calendar '(calendar-backward-year 1))))
15144 (org-defkey minibuffer-local-map [?\e (shift down)]
15145 (lambda () (interactive)
15146 (org-eval-in-calendar '(calendar-forward-year 1))))
15147 (org-defkey minibuffer-local-map [(shift up)]
15148 (lambda () (interactive)
15149 (org-eval-in-calendar '(calendar-backward-week 1))))
15150 (org-defkey minibuffer-local-map [(shift down)]
15151 (lambda () (interactive)
15152 (org-eval-in-calendar '(calendar-forward-week 1))))
15153 (org-defkey minibuffer-local-map [(shift left)]
15154 (lambda () (interactive)
15155 (org-eval-in-calendar '(calendar-backward-day 1))))
15156 (org-defkey minibuffer-local-map [(shift right)]
15157 (lambda () (interactive)
15158 (org-eval-in-calendar '(calendar-forward-day 1))))
15159 (org-defkey minibuffer-local-map ">"
15160 (lambda () (interactive)
15161 (org-eval-in-calendar '(scroll-calendar-left 1))))
15162 (org-defkey minibuffer-local-map "<"
15163 (lambda () (interactive)
15164 (org-eval-in-calendar '(scroll-calendar-right 1))))
15165 (org-defkey minibuffer-local-map "\C-v"
15166 (lambda () (interactive)
15167 (org-eval-in-calendar
15168 '(calendar-scroll-left-three-months 1))))
15169 (org-defkey minibuffer-local-map "\M-v"
15170 (lambda () (interactive)
15171 (org-eval-in-calendar
15172 '(calendar-scroll-right-three-months 1))))
15173 (run-hooks 'org-read-date-minibuffer-setup-hook)
15174 (unwind-protect
15175 (progn
15176 (use-local-map map)
15177 (setq org-read-date-inactive inactive)
15178 (add-hook 'post-command-hook 'org-read-date-display)
15179 (setq org-ans0 (read-string prompt default-input
15180 'org-read-date-history nil))
15181 ;; org-ans0: from prompt
15182 ;; org-ans1: from mouse click
15183 ;; org-ans2: from calendar motion
15184 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15185 (remove-hook 'post-command-hook 'org-read-date-display)
15186 (use-local-map old-map)
15187 (when org-read-date-overlay
15188 (delete-overlay org-read-date-overlay)
15189 (setq org-read-date-overlay nil)))))
15190 (bury-buffer "*Calendar*")))))
15192 (t ; Naked prompt only
15193 (unwind-protect
15194 (setq ans (read-string prompt default-input
15195 'org-read-date-history timestr))
15196 (when org-read-date-overlay
15197 (delete-overlay org-read-date-overlay)
15198 (setq org-read-date-overlay nil)))))
15200 (setq final (org-read-date-analyze ans org-def org-defdecode))
15202 (when org-read-date-analyze-forced-year
15203 (message "Year was forced into %s"
15204 (if org-read-date-force-compatible-dates
15205 "compatible range (1970-2037)"
15206 "range representable on this machine"))
15207 (ding))
15209 ;; One round trip to get rid of 34th of August and stuff like that....
15210 (setq final (decode-time (apply 'encode-time final)))
15212 (setq org-read-date-final-answer ans)
15214 (if to-time
15215 (apply 'encode-time final)
15216 (if (and (boundp 'org-time-was-given) org-time-was-given)
15217 (format "%04d-%02d-%02d %02d:%02d"
15218 (nth 5 final) (nth 4 final) (nth 3 final)
15219 (nth 2 final) (nth 1 final))
15220 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15222 (defvar org-def)
15223 (defvar org-defdecode)
15224 (defvar org-with-time)
15225 (defun org-read-date-display ()
15226 "Display the current date prompt interpretation in the minibuffer."
15227 (when org-read-date-display-live
15228 (when org-read-date-overlay
15229 (delete-overlay org-read-date-overlay))
15230 (let ((p (point)))
15231 (end-of-line 1)
15232 (while (not (equal (buffer-substring
15233 (max (point-min) (- (point) 4)) (point))
15234 " "))
15235 (insert " "))
15236 (goto-char p))
15237 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15238 " " (or org-ans1 org-ans2)))
15239 (org-end-time-was-given nil)
15240 (f (org-read-date-analyze ans org-def org-defdecode))
15241 (fmts (if org-dcst
15242 org-time-stamp-custom-formats
15243 org-time-stamp-formats))
15244 (fmt (if (or org-with-time
15245 (and (boundp 'org-time-was-given) org-time-was-given))
15246 (cdr fmts)
15247 (car fmts)))
15248 (txt (format-time-string fmt (apply 'encode-time f)))
15249 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15250 (txt (concat "=> " txt)))
15251 (when (and org-end-time-was-given
15252 (string-match org-plain-time-of-day-regexp txt))
15253 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15254 org-end-time-was-given
15255 (substring txt (match-end 0)))))
15256 (when org-read-date-analyze-futurep
15257 (setq txt (concat txt " (=>F)")))
15258 (setq org-read-date-overlay
15259 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15260 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15262 (defun org-read-date-analyze (ans org-def org-defdecode)
15263 "Analyze the combined answer of the date prompt."
15264 ;; FIXME: cleanup and comment
15265 (let ((nowdecode (decode-time (current-time)))
15266 delta deltan deltaw deltadef year month day
15267 hour minute second wday pm h2 m2 tl wday1
15268 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15269 (setq org-read-date-analyze-futurep nil
15270 org-read-date-analyze-forced-year nil)
15271 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15272 (setq ans "+0"))
15274 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15275 (setq ans (replace-match "" t t ans)
15276 deltan (car delta)
15277 deltaw (nth 1 delta)
15278 deltadef (nth 2 delta)))
15280 ;; Check if there is an iso week date in there
15281 ;; If yes, store the info and postpone interpreting it until the rest
15282 ;; of the parsing is done
15283 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15284 (setq iso-year (if (match-end 1)
15285 (org-small-year-to-year
15286 (string-to-number (match-string 1 ans))))
15287 iso-weekday (if (match-end 3)
15288 (string-to-number (match-string 3 ans)))
15289 iso-week (string-to-number (match-string 2 ans)))
15290 (setq ans (replace-match "" t t ans)))
15292 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15293 (when (string-match
15294 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15295 (setq year (if (match-end 2)
15296 (string-to-number (match-string 2 ans))
15297 (progn (setq kill-year t)
15298 (string-to-number (format-time-string "%Y"))))
15299 month (string-to-number (match-string 3 ans))
15300 day (string-to-number (match-string 4 ans)))
15301 (if (< year 100) (setq year (+ 2000 year)))
15302 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15303 t nil ans)))
15305 ;; Help matching dotted european dates
15306 (when (string-match
15307 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15308 (setq year (if (match-end 3)
15309 (string-to-number (match-string 3 ans))
15310 (progn (setq kill-year t)
15311 (string-to-number (format-time-string "%Y"))))
15312 day (string-to-number (match-string 1 ans))
15313 month (string-to-number (match-string 2 ans))
15314 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15315 t nil ans)))
15317 ;; Help matching american dates, like 5/30 or 5/30/7
15318 (when (string-match
15319 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15320 (setq year (if (match-end 4)
15321 (string-to-number (match-string 4 ans))
15322 (progn (setq kill-year t)
15323 (string-to-number (format-time-string "%Y"))))
15324 month (string-to-number (match-string 1 ans))
15325 day (string-to-number (match-string 2 ans)))
15326 (if (< year 100) (setq year (+ 2000 year)))
15327 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15328 t nil ans)))
15329 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15330 ;; If there is a time with am/pm, and *no* time without it, we convert
15331 ;; so that matching will be successful.
15332 (loop for i from 1 to 2 do ; twice, for end time as well
15333 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15334 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15335 (setq hour (string-to-number (match-string 1 ans))
15336 minute (if (match-end 3)
15337 (string-to-number (match-string 3 ans))
15339 pm (equal ?p
15340 (string-to-char (downcase (match-string 4 ans)))))
15341 (if (and (= hour 12) (not pm))
15342 (setq hour 0)
15343 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15344 (setq ans (replace-match (format "%02d:%02d" hour minute)
15345 t t ans))))
15347 ;; Check if a time range is given as a duration
15348 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15349 (setq hour (string-to-number (match-string 1 ans))
15350 h2 (+ hour (string-to-number (match-string 3 ans)))
15351 minute (string-to-number (match-string 2 ans))
15352 m2 (+ minute (if (match-end 5) (string-to-number
15353 (match-string 5 ans))0)))
15354 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15355 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15356 t t ans)))
15358 ;; Check if there is a time range
15359 (when (boundp 'org-end-time-was-given)
15360 (setq org-time-was-given nil)
15361 (when (and (string-match org-plain-time-of-day-regexp ans)
15362 (match-end 8))
15363 (setq org-end-time-was-given (match-string 8 ans))
15364 (setq ans (concat (substring ans 0 (match-beginning 7))
15365 (substring ans (match-end 7))))))
15367 (setq tl (parse-time-string ans)
15368 day (or (nth 3 tl) (nth 3 org-defdecode))
15369 month (or (nth 4 tl)
15370 (if (and org-read-date-prefer-future
15371 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15372 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15373 (nth 4 org-defdecode)))
15374 year (or (and (not kill-year) (nth 5 tl))
15375 (if (and org-read-date-prefer-future
15376 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15377 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15378 (nth 5 org-defdecode)))
15379 hour (or (nth 2 tl) (nth 2 org-defdecode))
15380 minute (or (nth 1 tl) (nth 1 org-defdecode))
15381 second (or (nth 0 tl) 0)
15382 wday (nth 6 tl))
15384 (when (and (eq org-read-date-prefer-future 'time)
15385 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15386 (equal day (nth 3 nowdecode))
15387 (equal month (nth 4 nowdecode))
15388 (equal year (nth 5 nowdecode))
15389 (nth 2 tl)
15390 (or (< (nth 2 tl) (nth 2 nowdecode))
15391 (and (= (nth 2 tl) (nth 2 nowdecode))
15392 (nth 1 tl)
15393 (< (nth 1 tl) (nth 1 nowdecode)))))
15394 (setq day (1+ day)
15395 futurep t))
15397 ;; Special date definitions below
15398 (cond
15399 (iso-week
15400 ;; There was an iso week
15401 (require 'cal-iso)
15402 (setq futurep nil)
15403 (setq year (or iso-year year)
15404 day (or iso-weekday wday 1)
15405 wday nil ; to make sure that the trigger below does not match
15406 iso-date (calendar-gregorian-from-absolute
15407 (calendar-absolute-from-iso
15408 (list iso-week day year))))
15409 ; FIXME: Should we also push ISO weeks into the future?
15410 ; (when (and org-read-date-prefer-future
15411 ; (not iso-year)
15412 ; (< (calendar-absolute-from-gregorian iso-date)
15413 ; (time-to-days (current-time))))
15414 ; (setq year (1+ year)
15415 ; iso-date (calendar-gregorian-from-absolute
15416 ; (calendar-absolute-from-iso
15417 ; (list iso-week day year)))))
15418 (setq month (car iso-date)
15419 year (nth 2 iso-date)
15420 day (nth 1 iso-date)))
15421 (deltan
15422 (setq futurep nil)
15423 (unless deltadef
15424 (let ((now (decode-time (current-time))))
15425 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15426 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15427 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15428 ((equal deltaw "m") (setq month (+ month deltan)))
15429 ((equal deltaw "y") (setq year (+ year deltan)))))
15430 ((and wday (not (nth 3 tl)))
15431 (setq futurep nil)
15432 ;; Weekday was given, but no day, so pick that day in the week
15433 ;; on or after the derived date.
15434 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15435 (unless (equal wday wday1)
15436 (setq day (+ day (% (- wday wday1 -7) 7))))))
15437 (if (and (boundp 'org-time-was-given)
15438 (nth 2 tl))
15439 (setq org-time-was-given t))
15440 (if (< year 100) (setq year (+ 2000 year)))
15441 ;; Check of the date is representable
15442 (if org-read-date-force-compatible-dates
15443 (progn
15444 (if (< year 1970)
15445 (setq year 1970 org-read-date-analyze-forced-year t))
15446 (if (> year 2037)
15447 (setq year 2037 org-read-date-analyze-forced-year t)))
15448 (condition-case nil
15449 (ignore (encode-time second minute hour day month year))
15450 (error
15451 (setq year (nth 5 org-defdecode))
15452 (setq org-read-date-analyze-forced-year t))))
15453 (setq org-read-date-analyze-futurep futurep)
15454 (list second minute hour day month year)))
15456 (defvar parse-time-weekdays)
15457 (defun org-read-date-get-relative (s today default)
15458 "Check string S for special relative date string.
15459 TODAY and DEFAULT are internal times, for today and for a default.
15460 Return shift list (N what def-flag)
15461 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15462 N is the number of WHATs to shift.
15463 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15464 the DEFAULT date rather than TODAY."
15465 (require 'parse-time)
15466 (when (and
15467 (string-match
15468 (concat
15469 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15470 "\\([0-9]+\\)?"
15471 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15472 "\\([ \t]\\|$\\)") s)
15473 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15474 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15475 (string-to-char (substring (match-string 1 s) -1))
15476 ?+))
15477 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15478 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15479 (what (if (match-end 3) (match-string 3 s) "d"))
15480 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15481 (date (if rel default today))
15482 (wday (nth 6 (decode-time date)))
15483 delta)
15484 (if wday1
15485 (progn
15486 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15487 (if (= dir ?-) (setq delta (- delta 7)))
15488 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15489 (list delta "d" rel))
15490 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15492 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15493 "Turn a user-specified date into the internal representation.
15494 The internal representation needed by the calendar is (month day year).
15495 This is a wrapper to handle the brain-dead convention in calendar that
15496 user function argument order change dependent on argument order."
15497 (if (boundp 'calendar-date-style)
15498 (cond
15499 ((eq calendar-date-style 'american)
15500 (list arg1 arg2 arg3))
15501 ((eq calendar-date-style 'european)
15502 (list arg2 arg1 arg3))
15503 ((eq calendar-date-style 'iso)
15504 (list arg2 arg3 arg1)))
15505 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15506 (if (org-bound-and-true-p european-calendar-style)
15507 (list arg2 arg1 arg3)
15508 (list arg1 arg2 arg3)))))
15510 (defun org-eval-in-calendar (form &optional keepdate)
15511 "Eval FORM in the calendar window and return to current window.
15512 Also, store the cursor date in variable org-ans2."
15513 (let ((sf (selected-frame))
15514 (sw (selected-window)))
15515 (select-window (get-buffer-window "*Calendar*" t))
15516 (eval form)
15517 (when (and (not keepdate) (calendar-cursor-to-date))
15518 (let* ((date (calendar-cursor-to-date))
15519 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15520 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15521 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15522 (select-window sw)
15523 (org-select-frame-set-input-focus sf)))
15525 (defun org-calendar-select ()
15526 "Return to `org-read-date' with the date currently selected.
15527 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15528 (interactive)
15529 (when (calendar-cursor-to-date)
15530 (let* ((date (calendar-cursor-to-date))
15531 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15532 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15533 (if (active-minibuffer-window) (exit-minibuffer))))
15535 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15536 "Insert a date stamp for the date given by the internal TIME.
15537 WITH-HM means use the stamp format that includes the time of the day.
15538 INACTIVE means use square brackets instead of angular ones, so that the
15539 stamp will not contribute to the agenda.
15540 PRE and POST are optional strings to be inserted before and after the
15541 stamp.
15542 The command returns the inserted time stamp."
15543 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15544 stamp)
15545 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15546 (insert-before-markers (or pre ""))
15547 (when (listp extra)
15548 (setq extra (car extra))
15549 (if (and (stringp extra)
15550 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15551 (setq extra (format "-%02d:%02d"
15552 (string-to-number (match-string 1 extra))
15553 (string-to-number (match-string 2 extra))))
15554 (setq extra nil)))
15555 (when extra
15556 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15557 (insert-before-markers (setq stamp (format-time-string fmt time)))
15558 (insert-before-markers (or post ""))
15559 (setq org-last-inserted-timestamp stamp)))
15561 (defun org-toggle-time-stamp-overlays ()
15562 "Toggle the use of custom time stamp formats."
15563 (interactive)
15564 (setq org-display-custom-times (not org-display-custom-times))
15565 (unless org-display-custom-times
15566 (let ((p (point-min)) (bmp (buffer-modified-p)))
15567 (while (setq p (next-single-property-change p 'display))
15568 (if (and (get-text-property p 'display)
15569 (eq (get-text-property p 'face) 'org-date))
15570 (remove-text-properties
15571 p (setq p (next-single-property-change p 'display))
15572 '(display t))))
15573 (set-buffer-modified-p bmp)))
15574 (if (featurep 'xemacs)
15575 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15576 (org-restart-font-lock)
15577 (setq org-table-may-need-update t)
15578 (if org-display-custom-times
15579 (message "Time stamps are overlaid with custom format")
15580 (message "Time stamp overlays removed")))
15582 (defun org-display-custom-time (beg end)
15583 "Overlay modified time stamp format over timestamp between BEG and END."
15584 (let* ((ts (buffer-substring beg end))
15585 t1 w1 with-hm tf time str w2 (off 0))
15586 (save-match-data
15587 (setq t1 (org-parse-time-string ts t))
15588 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15589 (setq off (- (match-end 0) (match-beginning 0)))))
15590 (setq end (- end off))
15591 (setq w1 (- end beg)
15592 with-hm (and (nth 1 t1) (nth 2 t1))
15593 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15594 time (org-fix-decoded-time t1)
15595 str (org-add-props
15596 (format-time-string
15597 (substring tf 1 -1) (apply 'encode-time time))
15598 nil 'mouse-face 'highlight)
15599 w2 (length str))
15600 (if (not (= w2 w1))
15601 (add-text-properties (1+ beg) (+ 2 beg)
15602 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15603 (if (featurep 'xemacs)
15604 (progn
15605 (put-text-property beg end 'invisible t)
15606 (put-text-property beg end 'end-glyph (make-glyph str)))
15607 (put-text-property beg end 'display str))))
15609 (defun org-translate-time (string)
15610 "Translate all timestamps in STRING to custom format.
15611 But do this only if the variable `org-display-custom-times' is set."
15612 (when org-display-custom-times
15613 (save-match-data
15614 (let* ((start 0)
15615 (re org-ts-regexp-both)
15616 t1 with-hm inactive tf time str beg end)
15617 (while (setq start (string-match re string start))
15618 (setq beg (match-beginning 0)
15619 end (match-end 0)
15620 t1 (save-match-data
15621 (org-parse-time-string (substring string beg end) t))
15622 with-hm (and (nth 1 t1) (nth 2 t1))
15623 inactive (equal (substring string beg (1+ beg)) "[")
15624 tf (funcall (if with-hm 'cdr 'car)
15625 org-time-stamp-custom-formats)
15626 time (org-fix-decoded-time t1)
15627 str (format-time-string
15628 (concat
15629 (if inactive "[" "<") (substring tf 1 -1)
15630 (if inactive "]" ">"))
15631 (apply 'encode-time time))
15632 string (replace-match str t t string)
15633 start (+ start (length str)))))))
15634 string)
15636 (defun org-fix-decoded-time (time)
15637 "Set 0 instead of nil for the first 6 elements of time.
15638 Don't touch the rest."
15639 (let ((n 0))
15640 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15642 (defun org-days-to-time (timestamp-string)
15643 "Difference between TIMESTAMP-STRING and now in days."
15644 (- (time-to-days (org-time-string-to-time timestamp-string))
15645 (time-to-days (current-time))))
15647 (defun org-deadline-close (timestamp-string &optional ndays)
15648 "Is the time in TIMESTAMP-STRING close to the current date?"
15649 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15650 (and (< (org-days-to-time timestamp-string) ndays)
15651 (not (org-entry-is-done-p))))
15653 (defun org-get-wdays (ts)
15654 "Get the deadline lead time appropriate for timestring TS."
15655 (cond
15656 ((<= org-deadline-warning-days 0)
15657 ;; 0 or negative, enforce this value no matter what
15658 (- org-deadline-warning-days))
15659 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15660 ;; lead time is specified.
15661 (floor (* (string-to-number (match-string 1 ts))
15662 (cdr (assoc (match-string 2 ts)
15663 '(("d" . 1) ("w" . 7)
15664 ("m" . 30.4) ("y" . 365.25)))))))
15665 ;; go for the default.
15666 (t org-deadline-warning-days)))
15668 (defun org-calendar-select-mouse (ev)
15669 "Return to `org-read-date' with the date currently selected.
15670 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15671 (interactive "e")
15672 (mouse-set-point ev)
15673 (when (calendar-cursor-to-date)
15674 (let* ((date (calendar-cursor-to-date))
15675 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15676 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15677 (if (active-minibuffer-window) (exit-minibuffer))))
15679 (defun org-check-deadlines (ndays)
15680 "Check if there are any deadlines due or past due.
15681 A deadline is considered due if it happens within `org-deadline-warning-days'
15682 days from today's date. If the deadline appears in an entry marked DONE,
15683 it is not shown. The prefix arg NDAYS can be used to test that many
15684 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15685 (interactive "P")
15686 (let* ((org-warn-days
15687 (cond
15688 ((equal ndays '(4)) 100000)
15689 (ndays (prefix-numeric-value ndays))
15690 (t (abs org-deadline-warning-days))))
15691 (case-fold-search nil)
15692 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15693 (callback
15694 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15696 (message "%d deadlines past-due or due within %d days"
15697 (org-occur regexp nil callback)
15698 org-warn-days)))
15700 (defun org-check-before-date (date)
15701 "Check if there are deadlines or scheduled entries before DATE."
15702 (interactive (list (org-read-date)))
15703 (let ((case-fold-search nil)
15704 (regexp (concat "\\<\\(" org-deadline-string
15705 "\\|" org-scheduled-string
15706 "\\) *<\\([^>]+\\)>"))
15707 (callback
15708 (lambda () (time-less-p
15709 (org-time-string-to-time (match-string 2))
15710 (org-time-string-to-time date)))))
15711 (message "%d entries before %s"
15712 (org-occur regexp nil callback) date)))
15714 (defun org-check-after-date (date)
15715 "Check if there are deadlines or scheduled entries after DATE."
15716 (interactive (list (org-read-date)))
15717 (let ((case-fold-search nil)
15718 (regexp (concat "\\<\\(" org-deadline-string
15719 "\\|" org-scheduled-string
15720 "\\) *<\\([^>]+\\)>"))
15721 (callback
15722 (lambda () (not
15723 (time-less-p
15724 (org-time-string-to-time (match-string 2))
15725 (org-time-string-to-time date))))))
15726 (message "%d entries after %s"
15727 (org-occur regexp nil callback) date)))
15729 (defun org-check-dates-range (start-date end-date)
15730 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15731 (interactive (list (org-read-date nil nil nil "Range starts")
15732 (org-read-date nil nil nil "Range end")))
15733 (let ((case-fold-search nil)
15734 (regexp (concat "\\<\\(" org-deadline-string
15735 "\\|" org-scheduled-string
15736 "\\) *<\\([^>]+\\)>"))
15737 (callback
15738 (lambda ()
15739 (let ((match (match-string 2)))
15740 (and
15741 (not (time-less-p
15742 (org-time-string-to-time match)
15743 (org-time-string-to-time start-date)))
15744 (time-less-p
15745 (org-time-string-to-time match)
15746 (org-time-string-to-time end-date)))))))
15747 (message "%d entries between %s and %s"
15748 (org-occur regexp nil callback) start-date end-date)))
15750 (defun org-evaluate-time-range (&optional to-buffer)
15751 "Evaluate a time range by computing the difference between start and end.
15752 Normally the result is just printed in the echo area, but with prefix arg
15753 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15754 If the time range is actually in a table, the result is inserted into the
15755 next column.
15756 For time difference computation, a year is assumed to be exactly 365
15757 days in order to avoid rounding problems."
15758 (interactive "P")
15760 (org-clock-update-time-maybe)
15761 (save-excursion
15762 (unless (org-at-date-range-p t)
15763 (goto-char (point-at-bol))
15764 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15765 (if (not (org-at-date-range-p t))
15766 (error "Not at a time-stamp range, and none found in current line")))
15767 (let* ((ts1 (match-string 1))
15768 (ts2 (match-string 2))
15769 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15770 (match-end (match-end 0))
15771 (time1 (org-time-string-to-time ts1))
15772 (time2 (org-time-string-to-time ts2))
15773 (t1 (org-float-time time1))
15774 (t2 (org-float-time time2))
15775 (diff (abs (- t2 t1)))
15776 (negative (< (- t2 t1) 0))
15777 ;; (ys (floor (* 365 24 60 60)))
15778 (ds (* 24 60 60))
15779 (hs (* 60 60))
15780 (fy "%dy %dd %02d:%02d")
15781 (fy1 "%dy %dd")
15782 (fd "%dd %02d:%02d")
15783 (fd1 "%dd")
15784 (fh "%02d:%02d")
15785 y d h m align)
15786 (if havetime
15787 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15789 d (floor (/ diff ds)) diff (mod diff ds)
15790 h (floor (/ diff hs)) diff (mod diff hs)
15791 m (floor (/ diff 60)))
15792 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15794 d (floor (+ (/ diff ds) 0.5))
15795 h 0 m 0))
15796 (if (not to-buffer)
15797 (message "%s" (org-make-tdiff-string y d h m))
15798 (if (org-at-table-p)
15799 (progn
15800 (goto-char match-end)
15801 (setq align t)
15802 (and (looking-at " *|") (goto-char (match-end 0))))
15803 (goto-char match-end))
15804 (if (looking-at
15805 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15806 (replace-match ""))
15807 (if negative (insert " -"))
15808 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15809 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15810 (insert " " (format fh h m))))
15811 (if align (org-table-align))
15812 (message "Time difference inserted")))))
15814 (defun org-make-tdiff-string (y d h m)
15815 (let ((fmt "")
15816 (l nil))
15817 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15818 l (push y l)))
15819 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15820 l (push d l)))
15821 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15822 l (push h l)))
15823 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15824 l (push m l)))
15825 (apply 'format fmt (nreverse l))))
15827 (defun org-time-string-to-time (s &optional buffer pos)
15828 (condition-case errdata
15829 (apply 'encode-time (org-parse-time-string s))
15830 (error (error "Bad timestamp `%s'%s\nError was: %s"
15831 s (if (not (and buffer pos))
15833 (format " at %d in buffer `%s'" pos buffer))
15834 (cdr errdata)))))
15836 (defun org-time-string-to-seconds (s)
15837 (org-float-time (org-time-string-to-time s)))
15839 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15840 "Convert a time stamp to an absolute day number.
15841 If there is a specifier for a cyclic time stamp, get the closest date to
15842 DAYNR.
15843 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15844 The variable date is bound by the calendar when this is called."
15845 (cond
15846 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15847 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15848 daynr
15849 (+ daynr 1000)))
15850 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15851 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15852 (time-to-days (current-time))) (match-string 0 s)
15853 prefer show-all))
15854 (t (time-to-days
15855 (condition-case errdata
15856 (apply 'encode-time (org-parse-time-string s))
15857 (error (error "Bad timestamp `%s'%s\nError was: %s"
15858 s (if (not (and buffer pos))
15860 (format " at %d in buffer `%s'" pos buffer))
15861 (cdr errdata))))))))
15863 (defun org-days-to-iso-week (days)
15864 "Return the iso week number."
15865 (require 'cal-iso)
15866 (car (calendar-iso-from-absolute days)))
15868 (defun org-small-year-to-year (year)
15869 "Convert 2-digit years into 4-digit years.
15870 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15871 The year 2000 cannot be abbreviated. Any year larger than 99
15872 is returned unchanged."
15873 (if (< year 38)
15874 (setq year (+ 2000 year))
15875 (if (< year 100)
15876 (setq year (+ 1900 year))))
15877 year)
15879 (defun org-time-from-absolute (d)
15880 "Return the time corresponding to date D.
15881 D may be an absolute day number, or a calendar-type list (month day year)."
15882 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15883 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15885 (defun org-calendar-holiday ()
15886 "List of holidays, for Diary display in Org-mode."
15887 (require 'holidays)
15888 (let ((hl (funcall
15889 (if (fboundp 'calendar-check-holidays)
15890 'calendar-check-holidays 'check-calendar-holidays) date)))
15891 (if hl (mapconcat 'identity hl "; "))))
15893 (defun org-diary-sexp-entry (sexp entry date)
15894 "Process a SEXP diary ENTRY for DATE."
15895 (require 'diary-lib)
15896 (let ((result (if calendar-debug-sexp
15897 (let ((stack-trace-on-error t))
15898 (eval (car (read-from-string sexp))))
15899 (condition-case nil
15900 (eval (car (read-from-string sexp)))
15901 (error
15902 (beep)
15903 (message "Bad sexp at line %d in %s: %s"
15904 (org-current-line)
15905 (buffer-file-name) sexp)
15906 (sleep-for 2))))))
15907 (cond ((stringp result) (split-string result "; "))
15908 ((and (consp result)
15909 (not (consp (cdr result)))
15910 (stringp (cdr result))) (cdr result))
15911 ((and (consp result)
15912 (stringp (car result))) result)
15913 (result entry)
15914 (t nil))))
15916 (defun org-diary-to-ical-string (frombuf)
15917 "Get iCalendar entries from diary entries in buffer FROMBUF.
15918 This uses the icalendar.el library."
15919 (let* ((tmpdir (if (featurep 'xemacs)
15920 (temp-directory)
15921 temporary-file-directory))
15922 (tmpfile (make-temp-name
15923 (expand-file-name "orgics" tmpdir)))
15924 buf rtn b e)
15925 (with-current-buffer frombuf
15926 (icalendar-export-region (point-min) (point-max) tmpfile)
15927 (setq buf (find-buffer-visiting tmpfile))
15928 (set-buffer buf)
15929 (goto-char (point-min))
15930 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15931 (setq b (match-beginning 0)))
15932 (goto-char (point-max))
15933 (if (re-search-backward "^END:VEVENT" nil t)
15934 (setq e (match-end 0)))
15935 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15936 (kill-buffer buf)
15937 (delete-file tmpfile)
15938 rtn))
15940 (defun org-closest-date (start current change prefer show-all)
15941 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15942 When PREFER is `past', return a date that is either CURRENT or past.
15943 When PREFER is `future', return a date that is either CURRENT or future.
15944 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15945 ;; Make the proper lists from the dates
15946 (catch 'exit
15947 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15948 dn dw sday cday n1 n2 n0
15949 d m y y1 y2 date1 date2 nmonths nm ny m2)
15951 (setq start (org-date-to-gregorian start)
15952 current (org-date-to-gregorian
15953 (if show-all
15954 current
15955 (time-to-days (current-time))))
15956 sday (calendar-absolute-from-gregorian start)
15957 cday (calendar-absolute-from-gregorian current))
15959 (if (<= cday sday) (throw 'exit sday))
15961 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15962 (setq dn (string-to-number (match-string 1 change))
15963 dw (cdr (assoc (match-string 2 change) a1)))
15964 (error "Invalid change specifier: %s" change))
15965 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15966 (cond
15967 ((eq dw 'day)
15968 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15969 n2 (+ n1 dn)))
15970 ((eq dw 'year)
15971 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15972 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15973 (setq date1 (list m d y1)
15974 n1 (calendar-absolute-from-gregorian date1)
15975 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15976 n2 (calendar-absolute-from-gregorian date2)))
15977 ((eq dw 'month)
15978 ;; approx number of month between the two dates
15979 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15980 ;; How often does dn fit in there?
15981 (setq d (nth 1 start) m (car start) y (nth 2 start)
15982 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15983 m (+ m nm)
15984 ny (floor (/ m 12))
15985 y (+ y ny)
15986 m (- m (* ny 12)))
15987 (while (> m 12) (setq m (- m 12) y (1+ y)))
15988 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15989 (setq m2 (+ m dn) y2 y)
15990 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15991 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15992 (while (<= n2 cday)
15993 (setq n1 n2 m m2 y y2)
15994 (setq m2 (+ m dn) y2 y)
15995 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15996 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15997 ;; Make sure n1 is the earlier date
15998 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15999 (if show-all
16000 (cond
16001 ((eq prefer 'past) (if (= cday n2) n2 n1))
16002 ((eq prefer 'future) (if (= cday n1) n1 n2))
16003 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16004 (cond
16005 ((eq prefer 'past) (if (= cday n2) n2 n1))
16006 ((eq prefer 'future) (if (= cday n1) n1 n2))
16007 (t (if (= cday n1) n1 n2)))))))
16009 (defun org-date-to-gregorian (date)
16010 "Turn any specification of DATE into a Gregorian date for the calendar."
16011 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16012 ((and (listp date) (= (length date) 3)) date)
16013 ((stringp date)
16014 (setq date (org-parse-time-string date))
16015 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16016 ((listp date)
16017 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16019 (defun org-parse-time-string (s &optional nodefault)
16020 "Parse the standard Org-mode time string.
16021 This should be a lot faster than the normal `parse-time-string'.
16022 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16023 hour and minute fields will be nil if not given."
16024 (if (string-match org-ts-regexp0 s)
16025 (list 0
16026 (if (or (match-beginning 8) (not nodefault))
16027 (string-to-number (or (match-string 8 s) "0")))
16028 (if (or (match-beginning 7) (not nodefault))
16029 (string-to-number (or (match-string 7 s) "0")))
16030 (string-to-number (match-string 4 s))
16031 (string-to-number (match-string 3 s))
16032 (string-to-number (match-string 2 s))
16033 nil nil nil)
16034 (error "Not a standard Org-mode time string: %s" s)))
16036 (defun org-timestamp-up (&optional arg)
16037 "Increase the date item at the cursor by one.
16038 If the cursor is on the year, change the year. If it is on the month,
16039 the day or the time, change that.
16040 With prefix ARG, change by that many units."
16041 (interactive "p")
16042 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16044 (defun org-timestamp-down (&optional arg)
16045 "Decrease the date item at the cursor by one.
16046 If the cursor is on the year, change the year. If it is on the month,
16047 the day or the time, change that.
16048 With prefix ARG, change by that many units."
16049 (interactive "p")
16050 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16052 (defun org-timestamp-up-day (&optional arg)
16053 "Increase the date in the time stamp by one day.
16054 With prefix ARG, change that many days."
16055 (interactive "p")
16056 (if (and (not (org-at-timestamp-p t))
16057 (org-at-heading-p))
16058 (org-todo 'up)
16059 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16061 (defun org-timestamp-down-day (&optional arg)
16062 "Decrease the date in the time stamp by one day.
16063 With prefix ARG, change that many days."
16064 (interactive "p")
16065 (if (and (not (org-at-timestamp-p t))
16066 (org-at-heading-p))
16067 (org-todo 'down)
16068 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16070 (defun org-at-timestamp-p (&optional inactive-ok)
16071 "Determine if the cursor is in or at a timestamp."
16072 (interactive)
16073 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16074 (pos (point))
16075 (ans (or (looking-at tsr)
16076 (save-excursion
16077 (skip-chars-backward "^[<\n\r\t")
16078 (if (> (point) (point-min)) (backward-char 1))
16079 (and (looking-at tsr)
16080 (> (- (match-end 0) pos) -1))))))
16081 (and ans
16082 (boundp 'org-ts-what)
16083 (setq org-ts-what
16084 (cond
16085 ((= pos (match-beginning 0)) 'bracket)
16086 ;; Point is considered to be "on the bracket" whether
16087 ;; it's really on it or right after it.
16088 ((or (= pos (1- (match-end 0)))
16089 (= pos (match-end 0))) 'bracket)
16090 ((org-pos-in-match-range pos 2) 'year)
16091 ((org-pos-in-match-range pos 3) 'month)
16092 ((org-pos-in-match-range pos 7) 'hour)
16093 ((org-pos-in-match-range pos 8) 'minute)
16094 ((or (org-pos-in-match-range pos 4)
16095 (org-pos-in-match-range pos 5)) 'day)
16096 ((and (> pos (or (match-end 8) (match-end 5)))
16097 (< pos (match-end 0)))
16098 (- pos (or (match-end 8) (match-end 5))))
16099 (t 'day))))
16100 ans))
16102 (defun org-toggle-timestamp-type ()
16103 "Toggle the type (<active> or [inactive]) of a time stamp."
16104 (interactive)
16105 (when (org-at-timestamp-p t)
16106 (let ((beg (match-beginning 0)) (end (match-end 0))
16107 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16108 (save-excursion
16109 (goto-char beg)
16110 (while (re-search-forward "[][<>]" end t)
16111 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16112 t t)))
16113 (message "Timestamp is now %sactive"
16114 (if (equal (char-after beg) ?<) "" "in")))))
16116 (defun org-timestamp-change (n &optional what updown)
16117 "Change the date in the time stamp at point.
16118 The date will be changed by N times WHAT. WHAT can be `day', `month',
16119 `year', `minute', `second'. If WHAT is not given, the cursor position
16120 in the timestamp determines what will be changed."
16121 (let ((origin (point)) origin-cat
16122 with-hm inactive
16123 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16124 org-ts-what
16125 extra rem
16126 ts time time0)
16127 (if (not (org-at-timestamp-p t))
16128 (error "Not at a timestamp"))
16129 (if (and (not what) (eq org-ts-what 'bracket))
16130 (org-toggle-timestamp-type)
16131 ;; Point isn't on brackets. Remember the part of the time-stamp
16132 ;; the point was in. Indeed, size of time-stamps may change,
16133 ;; but point must be kept in the same category nonetheless.
16134 (setq origin-cat org-ts-what)
16135 (if (and (not what) (not (eq org-ts-what 'day))
16136 org-display-custom-times
16137 (get-text-property (point) 'display)
16138 (not (get-text-property (1- (point)) 'display)))
16139 (setq org-ts-what 'day))
16140 (setq org-ts-what (or what org-ts-what)
16141 inactive (= (char-after (match-beginning 0)) ?\[)
16142 ts (match-string 0))
16143 (replace-match "")
16144 (if (string-match
16145 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16147 (setq extra (match-string 1 ts)))
16148 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16149 (setq with-hm t))
16150 (setq time0 (org-parse-time-string ts))
16151 (when (and updown
16152 (eq org-ts-what 'minute)
16153 (not current-prefix-arg))
16154 ;; This looks like s-up and s-down. Change by one rounding step.
16155 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16156 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16157 (setcar (cdr time0) (+ (nth 1 time0)
16158 (if (> n 0) (- rem) (- dm rem))))))
16159 (setq time
16160 (encode-time (or (car time0) 0)
16161 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16162 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16163 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16164 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16165 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16166 (nthcdr 6 time0)))
16167 (when (and (member org-ts-what '(hour minute))
16168 extra
16169 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16170 (setq extra (org-modify-ts-extra
16171 extra
16172 (if (eq org-ts-what 'hour) 2 5)
16173 n dm)))
16174 (when (integerp org-ts-what)
16175 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16176 (if (eq what 'calendar)
16177 (let ((cal-date (org-get-date-from-calendar)))
16178 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16179 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16180 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16181 (setcar time0 (or (car time0) 0))
16182 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16183 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16184 (setq time (apply 'encode-time time0))))
16185 ;; Insert the new time-stamp, and ensure point stays in the same
16186 ;; category as before (i.e. not after the last position in that
16187 ;; category).
16188 (let ((pos (point)))
16189 ;; Stay before inserted string. `save-excursion' is of no use.
16190 (setq org-last-changed-timestamp
16191 (org-insert-time-stamp time with-hm inactive nil nil extra))
16192 (goto-char pos))
16193 (save-match-data
16194 (looking-at org-ts-regexp3)
16195 (goto-char (cond
16196 ;; `day' category ends before `hour' if any, or at
16197 ;; the end of the day name.
16198 ((eq origin-cat 'day)
16199 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16200 ((eq origin-cat 'hour) (min (match-end 7) origin))
16201 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16202 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16203 ;; `year' and `month' have both fixed size: point
16204 ;; couldn't have moved into another part.
16205 (t origin))))
16206 ;; Update clock if on a CLOCK line.
16207 (org-clock-update-time-maybe)
16208 ;; Try to recenter the calendar window, if any.
16209 (if (and org-calendar-follow-timestamp-change
16210 (get-buffer-window "*Calendar*" t)
16211 (memq org-ts-what '(day month year)))
16212 (org-recenter-calendar (time-to-days time))))))
16214 (defun org-modify-ts-extra (s pos n dm)
16215 "Change the different parts of the lead-time and repeat fields in timestamp."
16216 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16217 ng h m new rem)
16218 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16219 (cond
16220 ((or (org-pos-in-match-range pos 2)
16221 (org-pos-in-match-range pos 3))
16222 (setq m (string-to-number (match-string 3 s))
16223 h (string-to-number (match-string 2 s)))
16224 (if (org-pos-in-match-range pos 2)
16225 (setq h (+ h n))
16226 (setq n (* dm (org-no-warnings (signum n))))
16227 (when (not (= 0 (setq rem (% m dm))))
16228 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16229 (setq m (+ m n)))
16230 (if (< m 0) (setq m (+ m 60) h (1- h)))
16231 (if (> m 59) (setq m (- m 60) h (1+ h)))
16232 (setq h (min 24 (max 0 h)))
16233 (setq ng 1 new (format "-%02d:%02d" h m)))
16234 ((org-pos-in-match-range pos 6)
16235 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16236 ((org-pos-in-match-range pos 5)
16237 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16239 ((org-pos-in-match-range pos 9)
16240 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16241 ((org-pos-in-match-range pos 8)
16242 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16244 (when ng
16245 (setq s (concat
16246 (substring s 0 (match-beginning ng))
16248 (substring s (match-end ng))))))
16251 (defun org-recenter-calendar (date)
16252 "If the calendar is visible, recenter it to DATE."
16253 (let ((cwin (get-buffer-window "*Calendar*" t)))
16254 (when cwin
16255 (let ((calendar-move-hook nil))
16256 (with-selected-window cwin
16257 (calendar-goto-date (if (listp date) date
16258 (calendar-gregorian-from-absolute date))))))))
16260 (defun org-goto-calendar (&optional arg)
16261 "Go to the Emacs calendar at the current date.
16262 If there is a time stamp in the current line, go to that date.
16263 A prefix ARG can be used to force the current date."
16264 (interactive "P")
16265 (let ((tsr org-ts-regexp) diff
16266 (calendar-move-hook nil)
16267 (calendar-view-holidays-initially-flag nil)
16268 (calendar-view-diary-initially-flag nil))
16269 (if (or (org-at-timestamp-p)
16270 (save-excursion
16271 (beginning-of-line 1)
16272 (looking-at (concat ".*" tsr))))
16273 (let ((d1 (time-to-days (current-time)))
16274 (d2 (time-to-days
16275 (org-time-string-to-time (match-string 1)))))
16276 (setq diff (- d2 d1))))
16277 (calendar)
16278 (calendar-goto-today)
16279 (if (and diff (not arg)) (calendar-forward-day diff))))
16281 (defun org-get-date-from-calendar ()
16282 "Return a list (month day year) of date at point in calendar."
16283 (with-current-buffer "*Calendar*"
16284 (save-match-data
16285 (calendar-cursor-to-date))))
16287 (defun org-date-from-calendar ()
16288 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16289 If there is already a time stamp at the cursor position, update it."
16290 (interactive)
16291 (if (org-at-timestamp-p t)
16292 (org-timestamp-change 0 'calendar)
16293 (let ((cal-date (org-get-date-from-calendar)))
16294 (org-insert-time-stamp
16295 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16297 (defun org-minutes-to-hh:mm-string (m)
16298 "Compute H:MM from a number of minutes."
16299 (let ((h (/ m 60)))
16300 (setq m (- m (* 60 h)))
16301 (format org-time-clocksum-format h m)))
16303 (defun org-hh:mm-string-to-minutes (s)
16304 "Convert a string H:MM to a number of minutes.
16305 If the string is just a number, interpret it as minutes.
16306 In fact, the first hh:mm or number in the string will be taken,
16307 there can be extra stuff in the string.
16308 If no number is found, the return value is 0."
16309 (cond
16310 ((integerp s) s)
16311 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16312 (+ (* (string-to-number (match-string 1 s)) 60)
16313 (string-to-number (match-string 2 s))))
16314 ((string-match "\\([0-9]+\\)" s)
16315 (string-to-number (match-string 1 s)))
16316 (t 0)))
16318 (defcustom org-effort-durations
16319 `(("h" . 60)
16320 ("d" . ,(* 60 8))
16321 ("w" . ,(* 60 8 5))
16322 ("m" . ,(* 60 8 5 4))
16323 ("y" . ,(* 60 8 5 40)))
16324 "Conversion factor to minutes for an effort modifier.
16326 Each entry has the form (MODIFIER . MINUTES).
16328 In an effort string, a number followed by MODIFIER is multiplied
16329 by the specified number of MINUTES to obtain an effort in
16330 minutes.
16332 For example, if the value of this variable is ((\"hours\" . 60)), then an
16333 effort string \"2hours\" is equivalent to 120 minutes."
16334 :group 'org-agenda
16335 :version "24.1"
16336 :type '(alist :key-type (string :tag "Modifier")
16337 :value-type (number :tag "Minutes")))
16339 (defun org-duration-string-to-minutes (s)
16340 "Convert a duration string S to minutes.
16342 A bare number is interpreted as minutes, modifiers can be set by
16343 customizing `org-effort-durations' (which see).
16345 Entries containing a colon are interpreted as H:MM by
16346 `org-hh:mm-string-to-minutes'."
16347 (let ((result 0)
16348 (re (concat "\\([0-9]+\\) *\\("
16349 (regexp-opt (mapcar 'car org-effort-durations))
16350 "\\)")))
16351 (while (string-match re s)
16352 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16353 (string-to-number (match-string 1 s))))
16354 (setq s (replace-match "" nil t s)))
16355 (incf result (org-hh:mm-string-to-minutes s))
16356 result))
16358 ;;;; Files
16360 (defun org-save-all-org-buffers ()
16361 "Save all Org-mode buffers without user confirmation."
16362 (interactive)
16363 (message "Saving all Org-mode buffers...")
16364 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16365 (when (featurep 'org-id) (org-id-locations-save))
16366 (message "Saving all Org-mode buffers... done"))
16368 (defun org-revert-all-org-buffers ()
16369 "Revert all Org-mode buffers.
16370 Prompt for confirmation when there are unsaved changes.
16371 Be sure you know what you are doing before letting this function
16372 overwrite your changes.
16374 This function is useful in a setup where one tracks org files
16375 with a version control system, to revert on one machine after pulling
16376 changes from another. I believe the procedure must be like this:
16378 1. M-x org-save-all-org-buffers
16379 2. Pull changes from the other machine, resolve conflicts
16380 3. M-x org-revert-all-org-buffers"
16381 (interactive)
16382 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16383 (error "Abort"))
16384 (save-excursion
16385 (save-window-excursion
16386 (mapc
16387 (lambda (b)
16388 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16389 (with-current-buffer b buffer-file-name))
16390 (org-pop-to-buffer-same-window b)
16391 (revert-buffer t 'no-confirm)))
16392 (buffer-list))
16393 (when (and (featurep 'org-id) org-id-track-globally)
16394 (org-id-locations-load)))))
16396 ;;;; Agenda files
16398 ;;;###autoload
16399 (defun org-switchb (&optional arg)
16400 "Switch between Org buffers.
16401 With one prefix argument, restrict available buffers to files.
16402 With two prefix arguments, restrict available buffers to agenda files.
16404 Defaults to `iswitchb' for buffer name completion.
16405 Set `org-completion-use-ido' to make it use ido instead."
16406 (interactive "P")
16407 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16408 ((equal arg '(16)) (org-buffer-list 'agenda))
16409 (t (org-buffer-list))))
16410 (org-completion-use-iswitchb org-completion-use-iswitchb)
16411 (org-completion-use-ido org-completion-use-ido))
16412 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16413 (setq org-completion-use-iswitchb t))
16414 (org-pop-to-buffer-same-window
16415 (org-icompleting-read "Org buffer: "
16416 (mapcar 'list (mapcar 'buffer-name blist))
16417 nil t))))
16419 ;;; Define some older names previously used for this functionality
16420 ;;;###autoload
16421 (defalias 'org-ido-switchb 'org-switchb)
16422 ;;;###autoload
16423 (defalias 'org-iswitchb 'org-switchb)
16425 (defun org-buffer-list (&optional predicate exclude-tmp)
16426 "Return a list of Org buffers.
16427 PREDICATE can be `export', `files' or `agenda'.
16429 export restrict the list to Export buffers.
16430 files restrict the list to buffers visiting Org files.
16431 agenda restrict the list to buffers visiting agenda files.
16433 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16434 (let* ((bfn nil)
16435 (agenda-files (and (eq predicate 'agenda)
16436 (mapcar 'file-truename (org-agenda-files t))))
16437 (filter
16438 (cond
16439 ((eq predicate 'files)
16440 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16441 ((eq predicate 'export)
16442 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16443 ((eq predicate 'agenda)
16444 (lambda (b)
16445 (with-current-buffer b
16446 (and (eq major-mode 'org-mode)
16447 (setq bfn (buffer-file-name b))
16448 (member (file-truename bfn) agenda-files)))))
16449 (t (lambda (b) (with-current-buffer b
16450 (or (eq major-mode 'org-mode)
16451 (string-match "\*Org .*Export"
16452 (buffer-name b)))))))))
16453 (delq nil
16454 (mapcar
16455 (lambda(b)
16456 (if (and (funcall filter b)
16457 (or (not exclude-tmp)
16458 (not (string-match "tmp" (buffer-name b)))))
16460 nil))
16461 (buffer-list)))))
16463 (defun org-agenda-files (&optional unrestricted archives)
16464 "Get the list of agenda files.
16465 Optional UNRESTRICTED means return the full list even if a restriction
16466 is currently in place.
16467 When ARCHIVES is t, include all archive files that are really being
16468 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16469 `org-agenda-archives-mode' is t."
16470 (let ((files
16471 (cond
16472 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16473 ((stringp org-agenda-files) (org-read-agenda-file-list))
16474 ((listp org-agenda-files) org-agenda-files)
16475 (t (error "Invalid value of `org-agenda-files'")))))
16476 (setq files (apply 'append
16477 (mapcar (lambda (f)
16478 (if (file-directory-p f)
16479 (directory-files
16480 f t org-agenda-file-regexp)
16481 (list f)))
16482 files)))
16483 (when org-agenda-skip-unavailable-files
16484 (setq files (delq nil
16485 (mapcar (function
16486 (lambda (file)
16487 (and (file-readable-p file) file)))
16488 files))))
16489 (when (or (eq archives t)
16490 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16491 (setq files (org-add-archive-files files)))
16492 files))
16494 (defun org-agenda-file-p (&optional file)
16495 "Return non-nil, if FILE is an agenda file.
16496 If FILE is omitted, use the file associated with the current
16497 buffer."
16498 (member (or file (buffer-file-name))
16499 (org-agenda-files t)))
16501 (defun org-edit-agenda-file-list ()
16502 "Edit the list of agenda files.
16503 Depending on setup, this either uses customize to edit the variable
16504 `org-agenda-files', or it visits the file that is holding the list. In the
16505 latter case, the buffer is set up in a way that saving it automatically kills
16506 the buffer and restores the previous window configuration."
16507 (interactive)
16508 (if (stringp org-agenda-files)
16509 (let ((cw (current-window-configuration)))
16510 (find-file org-agenda-files)
16511 (org-set-local 'org-window-configuration cw)
16512 (org-add-hook 'after-save-hook
16513 (lambda ()
16514 (set-window-configuration
16515 (prog1 org-window-configuration
16516 (kill-buffer (current-buffer))))
16517 (org-install-agenda-files-menu)
16518 (message "New agenda file list installed"))
16519 nil 'local)
16520 (message "%s" (substitute-command-keys
16521 "Edit list and finish with \\[save-buffer]")))
16522 (customize-variable 'org-agenda-files)))
16524 (defun org-store-new-agenda-file-list (list)
16525 "Set new value for the agenda file list and save it correctly."
16526 (if (stringp org-agenda-files)
16527 (let ((fe (org-read-agenda-file-list t)) b u)
16528 (while (setq b (find-buffer-visiting org-agenda-files))
16529 (kill-buffer b))
16530 (with-temp-file org-agenda-files
16531 (insert
16532 (mapconcat
16533 (lambda (f) ;; Keep un-expanded entries.
16534 (if (setq u (assoc f fe))
16535 (cdr u)
16537 list "\n")
16538 "\n")))
16539 (let ((org-mode-hook nil) (org-inhibit-startup t)
16540 (org-insert-mode-line-in-empty-file nil))
16541 (setq org-agenda-files list)
16542 (customize-save-variable 'org-agenda-files org-agenda-files))))
16544 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16545 "Read the list of agenda files from a file.
16546 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16547 filenames, used by `org-store-new-agenda-file-list' to write back
16548 un-expanded file names."
16549 (when (file-directory-p org-agenda-files)
16550 (error "`org-agenda-files' cannot be a single directory"))
16551 (when (stringp org-agenda-files)
16552 (with-temp-buffer
16553 (insert-file-contents org-agenda-files)
16554 (mapcar
16555 (lambda (f)
16556 (let ((e (expand-file-name (substitute-in-file-name f)
16557 org-directory)))
16558 (if pair-with-expansion
16559 (cons e f)
16560 e)))
16561 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16563 ;;;###autoload
16564 (defun org-cycle-agenda-files ()
16565 "Cycle through the files in `org-agenda-files'.
16566 If the current buffer visits an agenda file, find the next one in the list.
16567 If the current buffer does not, find the first agenda file."
16568 (interactive)
16569 (let* ((fs (org-agenda-files t))
16570 (files (append fs (list (car fs))))
16571 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16572 file)
16573 (unless files (error "No agenda files"))
16574 (catch 'exit
16575 (while (setq file (pop files))
16576 (if (equal (file-truename file) tcf)
16577 (when (car files)
16578 (find-file (car files))
16579 (throw 'exit t))))
16580 (find-file (car fs)))
16581 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16583 (defun org-agenda-file-to-front (&optional to-end)
16584 "Move/add the current file to the top of the agenda file list.
16585 If the file is not present in the list, it is added to the front. If it is
16586 present, it is moved there. With optional argument TO-END, add/move to the
16587 end of the list."
16588 (interactive "P")
16589 (let ((org-agenda-skip-unavailable-files nil)
16590 (file-alist (mapcar (lambda (x)
16591 (cons (file-truename x) x))
16592 (org-agenda-files t)))
16593 (ctf (file-truename buffer-file-name))
16594 x had)
16595 (setq x (assoc ctf file-alist) had x)
16597 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16598 (if to-end
16599 (setq file-alist (append (delq x file-alist) (list x)))
16600 (setq file-alist (cons x (delq x file-alist))))
16601 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16602 (org-install-agenda-files-menu)
16603 (message "File %s to %s of agenda file list"
16604 (if had "moved" "added") (if to-end "end" "front"))))
16606 (defun org-remove-file (&optional file)
16607 "Remove current file from the list of files in variable `org-agenda-files'.
16608 These are the files which are being checked for agenda entries.
16609 Optional argument FILE means use this file instead of the current."
16610 (interactive)
16611 (let* ((org-agenda-skip-unavailable-files nil)
16612 (file (or file buffer-file-name))
16613 (true-file (file-truename file))
16614 (afile (abbreviate-file-name file))
16615 (files (delq nil (mapcar
16616 (lambda (x)
16617 (if (equal true-file
16618 (file-truename x))
16619 nil x))
16620 (org-agenda-files t)))))
16621 (if (not (= (length files) (length (org-agenda-files t))))
16622 (progn
16623 (org-store-new-agenda-file-list files)
16624 (org-install-agenda-files-menu)
16625 (message "Removed file: %s" afile))
16626 (message "File was not in list: %s (not removed)" afile))))
16628 (defun org-file-menu-entry (file)
16629 (vector file (list 'find-file file) t))
16631 (defun org-check-agenda-file (file)
16632 "Make sure FILE exists. If not, ask user what to do."
16633 (when (not (file-exists-p file))
16634 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16635 (abbreviate-file-name file))
16636 (let ((r (downcase (read-char-exclusive))))
16637 (cond
16638 ((equal r ?r)
16639 (org-remove-file file)
16640 (throw 'nextfile t))
16641 (t (error "Abort"))))))
16643 (defun org-get-agenda-file-buffer (file)
16644 "Get a buffer visiting FILE. If the buffer needs to be created, add
16645 it to the list of buffers which might be released later."
16646 (let ((buf (org-find-base-buffer-visiting file)))
16647 (if buf
16648 buf ; just return it
16649 ;; Make a new buffer and remember it
16650 (setq buf (find-file-noselect file))
16651 (if buf (push buf org-agenda-new-buffers))
16652 buf)))
16654 (defun org-release-buffers (blist)
16655 "Release all buffers in list, asking the user for confirmation when needed.
16656 When a buffer is unmodified, it is just killed. When modified, it is saved
16657 \(if the user agrees) and then killed."
16658 (let (buf file)
16659 (while (setq buf (pop blist))
16660 (setq file (buffer-file-name buf))
16661 (when (and (buffer-modified-p buf)
16662 file
16663 (y-or-n-p (format "Save file %s? " file)))
16664 (with-current-buffer buf (save-buffer)))
16665 (kill-buffer buf))))
16667 (defun org-prepare-agenda-buffers (files)
16668 "Create buffers for all agenda files, protect archived trees and comments."
16669 (interactive)
16670 (let ((pa '(:org-archived t))
16671 (pc '(:org-comment t))
16672 (pall '(:org-archived t :org-comment t))
16673 (inhibit-read-only t)
16674 (rea (concat ":" org-archive-tag ":"))
16675 bmp file re)
16676 (save-excursion
16677 (save-restriction
16678 (while (setq file (pop files))
16679 (catch 'nextfile
16680 (if (bufferp file)
16681 (set-buffer file)
16682 (org-check-agenda-file file)
16683 (set-buffer (org-get-agenda-file-buffer file)))
16684 (widen)
16685 (setq bmp (buffer-modified-p))
16686 (org-refresh-category-properties)
16687 (setq org-todo-keywords-for-agenda
16688 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16689 (setq org-done-keywords-for-agenda
16690 (append org-done-keywords-for-agenda org-done-keywords))
16691 (setq org-todo-keyword-alist-for-agenda
16692 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16693 (setq org-drawers-for-agenda
16694 (append org-drawers-for-agenda org-drawers))
16695 (setq org-tag-alist-for-agenda
16696 (append org-tag-alist-for-agenda org-tag-alist))
16698 (save-excursion
16699 (remove-text-properties (point-min) (point-max) pall)
16700 (when org-agenda-skip-archived-trees
16701 (goto-char (point-min))
16702 (while (re-search-forward rea nil t)
16703 (if (org-at-heading-p t)
16704 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16705 (goto-char (point-min))
16706 (setq re (format org-heading-keyword-regexp-format
16707 org-comment-string))
16708 (while (re-search-forward re nil t)
16709 (add-text-properties
16710 (match-beginning 0) (org-end-of-subtree t) pc)))
16711 (set-buffer-modified-p bmp)))))
16712 (setq org-todo-keywords-for-agenda
16713 (org-uniquify org-todo-keywords-for-agenda))
16714 (setq org-todo-keyword-alist-for-agenda
16715 (org-uniquify org-todo-keyword-alist-for-agenda)
16716 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16718 ;;;; Embedded LaTeX
16720 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16721 "Keymap for the minor `org-cdlatex-mode'.")
16723 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16724 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16725 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16726 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16727 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16729 (defvar org-cdlatex-texmathp-advice-is-done nil
16730 "Flag remembering if we have applied the advice to texmathp already.")
16732 (define-minor-mode org-cdlatex-mode
16733 "Toggle the minor `org-cdlatex-mode'.
16734 This mode supports entering LaTeX environment and math in LaTeX fragments
16735 in Org-mode.
16736 \\{org-cdlatex-mode-map}"
16737 nil " OCDL" nil
16738 (when org-cdlatex-mode
16739 (require 'cdlatex)
16740 (run-hooks 'cdlatex-mode-hook)
16741 (cdlatex-compute-tables))
16742 (unless org-cdlatex-texmathp-advice-is-done
16743 (setq org-cdlatex-texmathp-advice-is-done t)
16744 (defadvice texmathp (around org-math-always-on activate)
16745 "Always return t in org-mode buffers.
16746 This is because we want to insert math symbols without dollars even outside
16747 the LaTeX math segments. If Orgmode thinks that point is actually inside
16748 an embedded LaTeX fragment, let texmathp do its job.
16749 \\[org-cdlatex-mode-map]"
16750 (interactive)
16751 (let (p)
16752 (cond
16753 ((not (eq major-mode 'org-mode)) ad-do-it)
16754 ((eq this-command 'cdlatex-math-symbol)
16755 (setq ad-return-value t
16756 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16758 (let ((p (org-inside-LaTeX-fragment-p)))
16759 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16760 (setq ad-return-value t
16761 texmathp-why '("Org-mode embedded math" . 0))
16762 (if p ad-do-it)))))))))
16764 (defun turn-on-org-cdlatex ()
16765 "Unconditionally turn on `org-cdlatex-mode'."
16766 (org-cdlatex-mode 1))
16768 (defun org-inside-LaTeX-fragment-p ()
16769 "Test if point is inside a LaTeX fragment.
16770 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16771 sequence appearing also before point.
16772 Even though the matchers for math are configurable, this function assumes
16773 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16774 delimiters are skipped when they have been removed by customization.
16775 The return value is nil, or a cons cell with the delimiter and the
16776 position of this delimiter.
16778 This function does a reasonably good job, but can locally be fooled by
16779 for example currency specifications. For example it will assume being in
16780 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16781 fragments that are properly closed, but during editing, we have to live
16782 with the uncertainty caused by missing closing delimiters. This function
16783 looks only before point, not after."
16784 (catch 'exit
16785 (let ((pos (point))
16786 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16787 (lim (progn
16788 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16789 (point)))
16790 dd-on str (start 0) m re)
16791 (goto-char pos)
16792 (when dodollar
16793 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16794 re (nth 1 (assoc "$" org-latex-regexps)))
16795 (while (string-match re str start)
16796 (cond
16797 ((= (match-end 0) (length str))
16798 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16799 ((= (match-end 0) (- (length str) 5))
16800 (throw 'exit nil))
16801 (t (setq start (match-end 0))))))
16802 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16803 (goto-char pos)
16804 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16805 (and (match-beginning 2) (throw 'exit nil))
16806 ;; count $$
16807 (while (re-search-backward "\\$\\$" lim t)
16808 (setq dd-on (not dd-on)))
16809 (goto-char pos)
16810 (if dd-on (cons "$$" m))))))
16812 (defun org-inside-latex-macro-p ()
16813 "Is point inside a LaTeX macro or its arguments?"
16814 (save-match-data
16815 (org-in-regexp
16816 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16818 (defun org-try-cdlatex-tab ()
16819 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16820 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16821 - inside a LaTeX fragment, or
16822 - after the first word in a line, where an abbreviation expansion could
16823 insert a LaTeX environment."
16824 (when org-cdlatex-mode
16825 (cond
16826 ;; Before any word on the line: No expansion possible.
16827 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16828 ;; Just after first word on the line: Expand it. Make sure it
16829 ;; cannot happen on headlines, though.
16830 ((save-excursion
16831 (skip-chars-backward "a-zA-Z0-9*")
16832 (skip-chars-backward " \t")
16833 (and (bolp) (not (org-at-heading-p))))
16834 (cdlatex-tab) t)
16835 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16837 (defun org-cdlatex-underscore-caret (&optional arg)
16838 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16839 Revert to the normal definition outside of these fragments."
16840 (interactive "P")
16841 (if (org-inside-LaTeX-fragment-p)
16842 (call-interactively 'cdlatex-sub-superscript)
16843 (let (org-cdlatex-mode)
16844 (call-interactively (key-binding (vector last-input-event))))))
16846 (defun org-cdlatex-math-modify (&optional arg)
16847 "Execute `cdlatex-math-modify' in LaTeX fragments.
16848 Revert to the normal definition outside of these fragments."
16849 (interactive "P")
16850 (if (org-inside-LaTeX-fragment-p)
16851 (call-interactively 'cdlatex-math-modify)
16852 (let (org-cdlatex-mode)
16853 (call-interactively (key-binding (vector last-input-event))))))
16855 (defvar org-latex-fragment-image-overlays nil
16856 "List of overlays carrying the images of latex fragments.")
16857 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16859 (defun org-remove-latex-fragment-image-overlays ()
16860 "Remove all overlays with LaTeX fragment images in current buffer."
16861 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16862 (setq org-latex-fragment-image-overlays nil))
16864 (defun org-preview-latex-fragment (&optional subtree)
16865 "Preview the LaTeX fragment at point, or all locally or globally.
16866 If the cursor is in a LaTeX fragment, create the image and overlay
16867 it over the source code. If there is no fragment at point, display
16868 all fragments in the current text, from one headline to the next. With
16869 prefix SUBTREE, display all fragments in the current subtree. With a
16870 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16871 the cursor is before the first headline,
16872 display all fragments in the buffer.
16873 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16874 (interactive "P")
16875 (unless buffer-file-name
16876 (error "Can't preview LaTeX fragment in a non-file buffer"))
16877 (org-remove-latex-fragment-image-overlays)
16878 (save-excursion
16879 (save-restriction
16880 (let (beg end at msg)
16881 (cond
16882 ((or (equal subtree '(16))
16883 (not (save-excursion
16884 (re-search-backward org-outline-regexp-bol nil t))))
16885 (setq beg (point-min) end (point-max)
16886 msg "Creating images for buffer...%s"))
16887 ((equal subtree '(4))
16888 (org-back-to-heading)
16889 (setq beg (point) end (org-end-of-subtree t)
16890 msg "Creating images for subtree...%s"))
16892 (if (setq at (org-inside-LaTeX-fragment-p))
16893 (goto-char (max (point-min) (- (cdr at) 2)))
16894 (org-back-to-heading))
16895 (setq beg (point) end (progn (outline-next-heading) (point))
16896 msg (if at "Creating image...%s"
16897 "Creating images for entry...%s"))))
16898 (message msg "")
16899 (narrow-to-region beg end)
16900 (goto-char beg)
16901 (org-format-latex
16902 (concat "ltxpng/" (file-name-sans-extension
16903 (file-name-nondirectory
16904 buffer-file-name)))
16905 default-directory 'overlays msg at 'forbuffer 'dvipng)
16906 (message msg "done. Use `C-c C-c' to remove images.")))))
16908 (defvar org-latex-regexps
16909 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16910 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16911 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16912 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16913 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16914 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16915 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16916 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16917 "Regular expressions for matching embedded LaTeX.")
16919 (defvar org-export-have-math nil) ;; dynamic scoping
16920 (defun org-format-latex (prefix &optional dir overlays msg at
16921 forbuffer processing-type)
16922 "Replace LaTeX fragments with links to an image, and produce images.
16923 Some of the options can be changed using the variable
16924 `org-format-latex-options'."
16925 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16926 (let* ((prefixnodir (file-name-nondirectory prefix))
16927 (absprefix (expand-file-name prefix dir))
16928 (todir (file-name-directory absprefix))
16929 (opt org-format-latex-options)
16930 (matchers (plist-get opt :matchers))
16931 (re-list org-latex-regexps)
16932 (org-format-latex-header-extra
16933 (plist-get (org-infile-export-plist) :latex-header-extra))
16934 (cnt 0) txt hash link beg end re e checkdir
16935 executables-checked string
16936 m n block-type block linkfile movefile ov)
16937 ;; Check the different regular expressions
16938 (while (setq e (pop re-list))
16939 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16940 block (if block-type "\n\n" ""))
16941 (when (member m matchers)
16942 (goto-char (point-min))
16943 (while (re-search-forward re nil t)
16944 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16945 (not (get-text-property (match-beginning n)
16946 'org-protected))
16947 (or (not overlays)
16948 (not (eq (get-char-property (match-beginning n)
16949 'org-overlay-type)
16950 'org-latex-overlay))))
16951 (setq org-export-have-math t)
16952 (cond
16953 ((eq processing-type 'verbatim)
16954 ;; Leave the text verbatim, just protect it
16955 (add-text-properties (match-beginning n) (match-end n)
16956 '(org-protected t)))
16957 ((eq processing-type 'mathjax)
16958 ;; Prepare for MathJax processing
16959 (setq string (match-string n))
16960 (if (member m '("$" "$1"))
16961 (save-excursion
16962 (delete-region (match-beginning n) (match-end n))
16963 (goto-char (match-beginning n))
16964 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16965 "\\)")
16966 '(org-protected t))))
16967 (add-text-properties (match-beginning n) (match-end n)
16968 '(org-protected t))))
16969 ((eq processing-type 'dvipng)
16970 ;; Process to an image
16971 (setq txt (match-string n)
16972 beg (match-beginning n) end (match-end n)
16973 cnt (1+ cnt))
16974 (let (print-length print-level) ; make sure full list is printed
16975 (setq hash (sha1 (prin1-to-string
16976 (list org-format-latex-header
16977 org-format-latex-header-extra
16978 org-export-latex-default-packages-alist
16979 org-export-latex-packages-alist
16980 org-format-latex-options
16981 forbuffer txt)))
16982 linkfile (format "%s_%s.png" prefix hash)
16983 movefile (format "%s_%s.png" absprefix hash)))
16984 (setq link (concat block "[[file:" linkfile "]]" block))
16985 (if msg (message msg cnt))
16986 (goto-char beg)
16987 (unless checkdir ; make sure the directory exists
16988 (setq checkdir t)
16989 (or (file-directory-p todir) (make-directory todir t)))
16991 (unless executables-checked
16992 (org-check-external-command
16993 "latex" "needed to convert LaTeX fragments to images")
16994 (org-check-external-command
16995 "dvipng" "needed to convert LaTeX fragments to images")
16996 (setq executables-checked t))
16998 (unless (file-exists-p movefile)
16999 (org-create-formula-image
17000 txt movefile opt forbuffer))
17001 (if overlays
17002 (progn
17003 (mapc (lambda (o)
17004 (if (eq (overlay-get o 'org-overlay-type)
17005 'org-latex-overlay)
17006 (delete-overlay o)))
17007 (overlays-in beg end))
17008 (setq ov (make-overlay beg end))
17009 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17010 (if (featurep 'xemacs)
17011 (progn
17012 (overlay-put ov 'invisible t)
17013 (overlay-put
17014 ov 'end-glyph
17015 (make-glyph (vector 'png :file movefile))))
17016 (overlay-put
17017 ov 'display
17018 (list 'image :type 'png :file movefile :ascent 'center)))
17019 (push ov org-latex-fragment-image-overlays)
17020 (goto-char end))
17021 (delete-region beg end)
17022 (insert (org-add-props link
17023 (list 'org-latex-src
17024 (replace-regexp-in-string
17025 "\"" "" txt)
17026 'org-latex-src-embed-type
17027 (if block-type 'paragraph 'character))))))
17028 ((eq processing-type 'mathml)
17029 ;; Process to MathML
17030 (unless executables-checked
17031 (unless (save-match-data (org-format-latex-mathml-available-p))
17032 (error "LaTeX to MathML converter not configured"))
17033 (setq executables-checked t))
17034 (setq txt (match-string n)
17035 beg (match-beginning n) end (match-end n)
17036 cnt (1+ cnt))
17037 (if msg (message msg cnt))
17038 (goto-char beg)
17039 (delete-region beg end)
17040 (insert (org-format-latex-as-mathml
17041 txt block-type prefix dir)))
17043 (error "Unknown conversion type %s for latex fragments"
17044 processing-type)))))))))
17046 (defun org-create-math-formula (latex-frag &optional mathml-file)
17047 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17048 Use `org-latex-to-mathml-convert-command'. If the conversion is
17049 sucessful, return the portion between \"<math...> </math>\"
17050 elements otherwise return nil. When MATHML-FILE is specified,
17051 write the results in to that file. When invoked as an
17052 interactive command, prompt for LATEX-FRAG, with initial value
17053 set to the current active region and echo the results for user
17054 inspection."
17055 (interactive (list (let ((frag (when (region-active-p)
17056 (buffer-substring-no-properties
17057 (region-beginning) (region-end)))))
17058 (read-string "LaTeX Fragment: " frag nil frag))))
17059 (unless latex-frag (error "Invalid latex-frag"))
17060 (let* ((tmp-in-file (file-relative-name
17061 (make-temp-name (expand-file-name "ltxmathml-in"))))
17062 (ignore (write-region latex-frag nil tmp-in-file))
17063 (tmp-out-file (file-relative-name
17064 (make-temp-name (expand-file-name "ltxmathml-out"))))
17065 (cmd (format-spec
17066 org-latex-to-mathml-convert-command
17067 `((?j . ,(shell-quote-argument
17068 (expand-file-name org-latex-to-mathml-jar-file)))
17069 (?I . ,(shell-quote-argument tmp-in-file))
17070 (?o . ,(shell-quote-argument tmp-out-file)))))
17071 mathml shell-command-output)
17072 (when (org-called-interactively-p 'any)
17073 (unless (org-format-latex-mathml-available-p)
17074 (error "LaTeX to MathML converter not configured")))
17075 (message "Running %s" cmd)
17076 (setq shell-command-output (shell-command-to-string cmd))
17077 (setq mathml
17078 (when (file-readable-p tmp-out-file)
17079 (with-current-buffer (find-file-noselect tmp-out-file t)
17080 (goto-char (point-min))
17081 (when (re-search-forward
17082 (concat
17083 (regexp-quote
17084 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17085 "\\(.\\|\n\\)*"
17086 (regexp-quote "</math>")) nil t)
17087 (prog1 (match-string 0) (kill-buffer))))))
17088 (cond
17089 (mathml
17090 (setq mathml
17091 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17092 (when mathml-file
17093 (write-region mathml nil mathml-file))
17094 (when (org-called-interactively-p 'any)
17095 (message mathml)))
17096 ((message "LaTeX to MathML conversion failed")
17097 (message shell-command-output)))
17098 (delete-file tmp-in-file)
17099 (when (file-exists-p tmp-out-file)
17100 (delete-file tmp-out-file))
17101 mathml))
17103 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17104 prefix &optional dir)
17105 "Use `org-create-math-formula' but check local cache first."
17106 (let* ((absprefix (expand-file-name prefix dir))
17107 (print-length nil) (print-level nil)
17108 (formula-id (concat
17109 "formula-"
17110 (sha1
17111 (prin1-to-string
17112 (list latex-frag
17113 org-latex-to-mathml-convert-command)))))
17114 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17115 (formula-cache-dir (file-name-directory formula-cache)))
17117 (unless (file-directory-p formula-cache-dir)
17118 (make-directory formula-cache-dir t))
17120 (unless (file-exists-p formula-cache)
17121 (org-create-math-formula latex-frag formula-cache))
17123 (if (file-exists-p formula-cache)
17124 ;; Successful conversion. Return the link to MathML file.
17125 (org-add-props
17126 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17127 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17128 'org-latex-src-embed-type (if latex-frag-type
17129 'paragraph 'character)))
17130 ;; Failed conversion. Return the LaTeX fragment verbatim
17131 (add-text-properties
17132 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17133 latex-frag)))
17135 ;; This function borrows from Ganesh Swami's latex2png.el
17136 (defun org-create-formula-image (string tofile options buffer)
17137 "This calls dvipng."
17138 (require 'org-latex)
17139 (let* ((tmpdir (if (featurep 'xemacs)
17140 (temp-directory)
17141 temporary-file-directory))
17142 (texfilebase (make-temp-name
17143 (expand-file-name "orgtex" tmpdir)))
17144 (texfile (concat texfilebase ".tex"))
17145 (dvifile (concat texfilebase ".dvi"))
17146 (pngfile (concat texfilebase ".png"))
17147 (fnh (if (featurep 'xemacs)
17148 (font-height (face-font 'default))
17149 (face-attribute 'default :height nil)))
17150 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17151 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17152 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17153 "Black"))
17154 (bg (or (plist-get options (if buffer :background :html-background))
17155 "Transparent")))
17156 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17157 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17158 (with-temp-file texfile
17159 (insert (org-splice-latex-header
17160 org-format-latex-header
17161 org-export-latex-default-packages-alist
17162 org-export-latex-packages-alist t
17163 org-format-latex-header-extra))
17164 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17165 (require 'org-latex)
17166 (org-export-latex-fix-inputenc))
17167 (let ((dir default-directory))
17168 (condition-case nil
17169 (progn
17170 (cd tmpdir)
17171 (call-process "latex" nil nil nil texfile))
17172 (error nil))
17173 (cd dir))
17174 (if (not (file-exists-p dvifile))
17175 (progn (message "Failed to create dvi file from %s" texfile) nil)
17176 (condition-case nil
17177 (if (featurep 'xemacs)
17178 (call-process "dvipng" nil nil nil
17179 "-fg" fg "-bg" bg
17180 "-T" "tight"
17181 "-o" pngfile
17182 dvifile)
17183 (call-process "dvipng" nil nil nil
17184 "-fg" fg "-bg" bg
17185 "-D" dpi
17186 ;;"-x" scale "-y" scale
17187 "-T" "tight"
17188 "-o" pngfile
17189 dvifile))
17190 (error nil))
17191 (if (not (file-exists-p pngfile))
17192 (if org-format-latex-signal-error
17193 (error "Failed to create png file from %s" texfile)
17194 (message "Failed to create png file from %s" texfile)
17195 nil)
17196 ;; Use the requested file name and clean up
17197 (copy-file pngfile tofile 'replace)
17198 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17199 (delete-file (concat texfilebase e)))
17200 pngfile))))
17202 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17203 "Fill a LaTeX header template TPL.
17204 In the template, the following place holders will be recognized:
17206 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17207 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17208 [PACKAGES] \\usepackage statements for PKG
17209 [NO-PACKAGES] do not include PKG
17210 [EXTRA] the string EXTRA
17211 [NO-EXTRA] do not include EXTRA
17213 For backward compatibility, if both the positive and the negative place
17214 holder is missing, the positive one (without the \"NO-\") will be
17215 assumed to be present at the end of the template.
17216 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17217 EXTRA is a string.
17218 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17219 (let (rpl (end ""))
17220 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17221 (setq rpl (if (or (match-end 1) (not def-pkg))
17222 "" (org-latex-packages-to-string def-pkg snippets-p t))
17223 tpl (replace-match rpl t t tpl))
17224 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17226 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17227 (setq rpl (if (or (match-end 1) (not pkg))
17228 "" (org-latex-packages-to-string pkg snippets-p t))
17229 tpl (replace-match rpl t t tpl))
17230 (if pkg (setq end
17231 (concat end "\n"
17232 (org-latex-packages-to-string pkg snippets-p)))))
17234 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17235 (setq rpl (if (or (match-end 1) (not extra))
17236 "" (concat extra "\n"))
17237 tpl (replace-match rpl t t tpl))
17238 (if (and extra (string-match "\\S-" extra))
17239 (setq end (concat end "\n" extra))))
17241 (if (string-match "\\S-" end)
17242 (concat tpl "\n" end)
17243 tpl)))
17245 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17246 "Turn an alist of packages into a string with the \\usepackage macros."
17247 (setq pkg (mapconcat (lambda(p)
17248 (cond
17249 ((stringp p) p)
17250 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17251 (format "%% Package %s omitted" (cadr p)))
17252 ((equal "" (car p))
17253 (format "\\usepackage{%s}" (cadr p)))
17255 (format "\\usepackage[%s]{%s}"
17256 (car p) (cadr p)))))
17258 "\n"))
17259 (if newline (concat pkg "\n") pkg))
17261 (defun org-dvipng-color (attr)
17262 "Return an rgb color specification for dvipng."
17263 (apply 'format "rgb %s %s %s"
17264 (mapcar 'org-normalize-color
17265 (if (featurep 'xemacs)
17266 (color-rgb-components
17267 (face-property 'default
17268 (cond ((eq attr :foreground) 'foreground)
17269 ((eq attr :background) 'background))))
17270 (color-values (face-attribute 'default attr nil))))))
17272 (defun org-normalize-color (value)
17273 "Return string to be used as color value for an RGB component."
17274 (format "%g" (/ value 65535.0)))
17276 ;; Image display
17279 (defvar org-inline-image-overlays nil)
17280 (make-variable-buffer-local 'org-inline-image-overlays)
17282 (defun org-toggle-inline-images (&optional include-linked)
17283 "Toggle the display of inline images.
17284 INCLUDE-LINKED is passed to `org-display-inline-images'."
17285 (interactive "P")
17286 (if org-inline-image-overlays
17287 (progn
17288 (org-remove-inline-images)
17289 (message "Inline image display turned off"))
17290 (org-display-inline-images include-linked)
17291 (if org-inline-image-overlays
17292 (message "%d images displayed inline"
17293 (length org-inline-image-overlays))
17294 (message "No images to display inline"))))
17296 (defun org-display-inline-images (&optional include-linked refresh beg end)
17297 "Display inline images.
17298 Normally only links without a description part are inlined, because this
17299 is how it will work for export. When INCLUDE-LINKED is set, also links
17300 with a description part will be inlined. This can be nice for a quick
17301 look at those images, but it does not reflect what exported files will look
17302 like.
17303 When REFRESH is set, refresh existing images between BEG and END.
17304 This will create new image displays only if necessary.
17305 BEG and END default to the buffer boundaries."
17306 (interactive "P")
17307 (unless refresh
17308 (org-remove-inline-images)
17309 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17310 (save-excursion
17311 (save-restriction
17312 (widen)
17313 (setq beg (or beg (point-min)) end (or end (point-max)))
17314 (goto-char beg)
17315 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17316 (substring (org-image-file-name-regexp) 0 -2)
17317 "\\)\\]" (if include-linked "" "\\]")))
17318 old file ov img)
17319 (while (re-search-forward re end t)
17320 (setq old (get-char-property-and-overlay (match-beginning 1)
17321 'org-image-overlay))
17322 (setq file (expand-file-name
17323 (concat (or (match-string 3) "") (match-string 4))))
17324 (when (file-exists-p file)
17325 (if (and (car-safe old) refresh)
17326 (image-refresh (overlay-get (cdr old) 'display))
17327 (setq img (save-match-data (create-image file)))
17328 (when img
17329 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17330 (overlay-put ov 'display img)
17331 (overlay-put ov 'face 'default)
17332 (overlay-put ov 'org-image-overlay t)
17333 (overlay-put ov 'modification-hooks
17334 (list 'org-display-inline-modification-hook))
17335 (push ov org-inline-image-overlays)))))))))
17337 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17338 "Remove inline-display overlay if a corresponding region is modified."
17339 (let ((inhibit-modification-hooks t))
17340 (when (and ov after)
17341 (delete ov org-inline-image-overlays)
17342 (delete-overlay ov))))
17344 (defun org-remove-inline-images ()
17345 "Remove inline display of images."
17346 (interactive)
17347 (mapc 'delete-overlay org-inline-image-overlays)
17348 (setq org-inline-image-overlays nil))
17350 ;;;; Key bindings
17352 ;; Outline functions from `outline-mode-prefix-map'
17353 ;; that can be remapped in Org:
17354 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17355 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17356 (define-key org-mode-map [remap outline-forward-same-level]
17357 'org-forward-same-level)
17358 (define-key org-mode-map [remap outline-backward-same-level]
17359 'org-backward-same-level)
17360 (define-key org-mode-map [remap show-branches]
17361 'org-kill-note-or-show-branches)
17362 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17363 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17364 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17366 ;; Outline functions from `outline-mode-prefix-map'
17367 ;; that can not be remapped in Org:
17368 ;; - the column "key binding" shows whether the Outline function is still
17369 ;; available in Org mode on the same key that it has been bound to in
17370 ;; Outline mode:
17371 ;; - "overridden": key used for a different functionality in Org mode
17372 ;; - else: key still bound to the same Outline function in Org mode
17373 ;; | Outline function | key binding | Org replacement |
17374 ;; |------------------------------------+-------------+-----------------------|
17375 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17376 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17377 ;; | `show-children' | `C-c C-i' | visibility cycling |
17378 ;; | `hide-subtree' | overridden | visibility cycling |
17379 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17380 ;; | `hide-body' | overridden | no replacement |
17381 ;; | `show-all' | overridden | no replacement |
17382 ;; | `hide-entry' | overridden | visibility cycling |
17383 ;; | `show-entry' | overridden | no replacement |
17384 ;; | `hide-leaves' | overridden | no replacement |
17385 ;; | `hide-sublevels' | overridden | no replacement |
17386 ;; | `hide-other' | overridden | no replacement |
17387 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17388 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17390 ;; Make `C-c C-x' a prefix key
17391 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17393 ;; TAB key with modifiers
17394 (org-defkey org-mode-map "\C-i" 'org-cycle)
17395 (org-defkey org-mode-map [(tab)] 'org-cycle)
17396 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17397 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17398 ;; The following line is necessary under Suse GNU/Linux
17399 (unless (featurep 'xemacs)
17400 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17401 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17402 (define-key org-mode-map [backtab] 'org-shifttab)
17404 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17405 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17406 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17408 ;; Cursor keys with modifiers
17409 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17410 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17411 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17412 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17414 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17415 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17416 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17417 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17419 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17420 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17421 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17422 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17424 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17425 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17426 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17427 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17429 ;; Babel keys
17430 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17431 (mapc (lambda (pair)
17432 (define-key org-babel-map (car pair) (cdr pair)))
17433 org-babel-key-bindings)
17435 ;;; Extra keys for tty access.
17436 ;; We only set them when really needed because otherwise the
17437 ;; menus don't show the simple keys
17439 (when (or org-use-extra-keys
17440 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17441 (not window-system))
17442 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17443 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17444 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17445 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17446 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17447 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17448 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17449 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17450 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17451 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17452 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17453 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17454 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17455 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17456 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17457 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17458 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17459 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17460 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17461 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17462 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17463 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17464 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17465 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17466 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17467 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17468 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17469 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17471 ;; All the other keys
17473 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17474 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17475 (if (boundp 'narrow-map)
17476 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17477 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17478 (if (boundp 'narrow-map)
17479 (org-defkey narrow-map "b" 'org-narrow-to-block)
17480 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17481 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17482 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17483 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17484 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17485 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17486 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17487 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17488 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17489 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17490 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17491 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17492 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17493 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17494 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17495 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17496 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17497 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17498 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17499 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17500 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17501 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17502 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17503 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17504 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17505 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17506 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17507 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17508 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17509 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17510 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17511 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17512 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17513 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17514 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17515 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17516 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17517 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17518 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17519 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17520 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17521 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17522 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17523 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17524 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17525 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17526 (org-defkey org-mode-map "\C-c^" 'org-sort)
17527 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17528 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17529 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17530 (org-defkey org-mode-map "\C-m" 'org-return)
17531 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17532 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17533 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17534 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17535 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17536 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17537 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17538 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17539 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17540 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17541 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17542 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17543 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17544 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17545 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17546 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17547 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17548 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17549 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17550 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17551 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17552 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17553 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17555 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17556 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17557 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17558 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17560 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17561 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17562 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17563 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17564 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17565 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17566 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17567 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17568 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17569 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17570 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17571 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17572 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17573 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17574 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17575 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17576 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17577 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17579 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17580 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17581 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17582 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17583 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17585 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17587 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17589 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17590 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17592 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17595 (when (featurep 'xemacs)
17596 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17599 (defconst org-speed-commands-default
17601 ("Outline Navigation")
17602 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17603 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17604 ("f" . (org-speed-move-safe 'org-forward-same-level))
17605 ("b" . (org-speed-move-safe 'org-backward-same-level))
17606 ("u" . (org-speed-move-safe 'outline-up-heading))
17607 ("j" . org-goto)
17608 ("g" . (org-refile t))
17609 ("Outline Visibility")
17610 ("c" . org-cycle)
17611 ("C" . org-shifttab)
17612 (" " . org-display-outline-path)
17613 ("Outline Structure Editing")
17614 ("U" . org-shiftmetaup)
17615 ("D" . org-shiftmetadown)
17616 ("r" . org-metaright)
17617 ("l" . org-metaleft)
17618 ("R" . org-shiftmetaright)
17619 ("L" . org-shiftmetaleft)
17620 ("i" . (progn (forward-char 1) (call-interactively
17621 'org-insert-heading-respect-content)))
17622 ("^" . org-sort)
17623 ("w" . org-refile)
17624 ("a" . org-archive-subtree-default-with-confirmation)
17625 ("." . org-mark-subtree)
17626 ("Clock Commands")
17627 ("I" . org-clock-in)
17628 ("O" . org-clock-out)
17629 ("Meta Data Editing")
17630 ("t" . org-todo)
17631 ("0" . (org-priority ?\ ))
17632 ("1" . (org-priority ?A))
17633 ("2" . (org-priority ?B))
17634 ("3" . (org-priority ?C))
17635 (";" . org-set-tags-command)
17636 ("e" . org-set-effort)
17637 ("Agenda Views etc")
17638 ("v" . org-agenda)
17639 ("/" . org-sparse-tree)
17640 ("Misc")
17641 ("o" . org-open-at-point)
17642 ("?" . org-speed-command-help)
17643 ("<" . (org-agenda-set-restriction-lock 'subtree))
17644 (">" . (org-agenda-remove-restriction-lock))
17646 "The default speed commands.")
17648 (defun org-print-speed-command (e)
17649 (if (> (length (car e)) 1)
17650 (progn
17651 (princ "\n")
17652 (princ (car e))
17653 (princ "\n")
17654 (princ (make-string (length (car e)) ?-))
17655 (princ "\n"))
17656 (princ (car e))
17657 (princ " ")
17658 (if (symbolp (cdr e))
17659 (princ (symbol-name (cdr e)))
17660 (prin1 (cdr e)))
17661 (princ "\n")))
17663 (defun org-speed-command-help ()
17664 "Show the available speed commands."
17665 (interactive)
17666 (if (not org-use-speed-commands)
17667 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17668 (with-output-to-temp-buffer "*Help*"
17669 (princ "User-defined Speed commands\n===========================\n")
17670 (mapc 'org-print-speed-command org-speed-commands-user)
17671 (princ "\n")
17672 (princ "Built-in Speed commands\n=======================\n")
17673 (mapc 'org-print-speed-command org-speed-commands-default))
17674 (with-current-buffer "*Help*"
17675 (setq truncate-lines t))))
17677 (defun org-speed-move-safe (cmd)
17678 "Execute CMD, but make sure that the cursor always ends up in a headline.
17679 If not, return to the original position and throw an error."
17680 (interactive)
17681 (let ((pos (point)))
17682 (call-interactively cmd)
17683 (unless (and (bolp) (org-at-heading-p))
17684 (goto-char pos)
17685 (error "Boundary reached while executing %s" cmd))))
17687 (defvar org-self-insert-command-undo-counter 0)
17689 (defvar org-table-auto-blank-field) ; defined in org-table.el
17690 (defvar org-speed-command nil)
17692 (defun org-speed-command-default-hook (keys)
17693 "Hook for activating single-letter speed commands.
17694 `org-speed-commands-default' specifies a minimal command set.
17695 Use `org-speed-commands-user' for further customization."
17696 (when (or (and (bolp) (looking-at org-outline-regexp))
17697 (and (functionp org-use-speed-commands)
17698 (funcall org-use-speed-commands)))
17699 (cdr (assoc keys (append org-speed-commands-user
17700 org-speed-commands-default)))))
17702 (defun org-babel-speed-command-hook (keys)
17703 "Hook for activating single-letter code block commands."
17704 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17705 (cdr (assoc keys org-babel-key-bindings))))
17707 (defcustom org-speed-command-hook
17708 '(org-speed-command-default-hook org-babel-speed-command-hook)
17709 "Hook for activating speed commands at strategic locations.
17710 Hook functions are called in sequence until a valid handler is
17711 found.
17713 Each hook takes a single argument, a user-pressed command key
17714 which is also a `self-insert-command' from the global map.
17716 Within the hook, examine the cursor position and the command key
17717 and return nil or a valid handler as appropriate. Handler could
17718 be one of an interactive command, a function, or a form.
17720 Set `org-use-speed-commands' to non-nil value to enable this
17721 hook. The default setting is `org-speed-command-default-hook'."
17722 :group 'org-structure
17723 :version "24.1"
17724 :type 'hook)
17726 (defun org-self-insert-command (N)
17727 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17728 If the cursor is in a table looking at whitespace, the whitespace is
17729 overwritten, and the table is not marked as requiring realignment."
17730 (interactive "p")
17731 (org-check-before-invisible-edit 'insert)
17732 (cond
17733 ((and org-use-speed-commands
17734 (setq org-speed-command
17735 (run-hook-with-args-until-success
17736 'org-speed-command-hook (this-command-keys))))
17737 (cond
17738 ((commandp org-speed-command)
17739 (setq this-command org-speed-command)
17740 (call-interactively org-speed-command))
17741 ((functionp org-speed-command)
17742 (funcall org-speed-command))
17743 ((and org-speed-command (listp org-speed-command))
17744 (eval org-speed-command))
17745 (t (let (org-use-speed-commands)
17746 (call-interactively 'org-self-insert-command)))))
17747 ((and
17748 (org-table-p)
17749 (progn
17750 ;; check if we blank the field, and if that triggers align
17751 (and (featurep 'org-table) org-table-auto-blank-field
17752 (member last-command
17753 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17754 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17755 ;; got extra space, this field does not determine column width
17756 (let (org-table-may-need-update) (org-table-blank-field))
17757 ;; no extra space, this field may determine column width
17758 (org-table-blank-field)))
17760 (eq N 1)
17761 (looking-at "[^|\n]* |"))
17762 (let (org-table-may-need-update)
17763 (goto-char (1- (match-end 0)))
17764 (backward-delete-char 1)
17765 (goto-char (match-beginning 0))
17766 (self-insert-command N)))
17768 (setq org-table-may-need-update t)
17769 (self-insert-command N)
17770 (org-fix-tags-on-the-fly)
17771 (if org-self-insert-cluster-for-undo
17772 (if (not (eq last-command 'org-self-insert-command))
17773 (setq org-self-insert-command-undo-counter 1)
17774 (if (>= org-self-insert-command-undo-counter 20)
17775 (setq org-self-insert-command-undo-counter 1)
17776 (and (> org-self-insert-command-undo-counter 0)
17777 buffer-undo-list (listp buffer-undo-list)
17778 (not (cadr buffer-undo-list)) ; remove nil entry
17779 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17780 (setq org-self-insert-command-undo-counter
17781 (1+ org-self-insert-command-undo-counter))))))))
17783 (defun org-check-before-invisible-edit (kind)
17784 "Check is editing if kind KIND would be dangerous with invisible text around.
17785 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17786 ;; First, try to get out of here as quickly as possible, to reduce overhead
17787 (if (and org-catch-invisible-edits
17788 (or (not (boundp 'visible-mode)) (not visible-mode))
17789 (or (get-char-property (point) 'invisible)
17790 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17791 ;; OK, we need to take a closer look
17792 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17793 (invisible-before-point (if (bobp) nil (get-char-property
17794 (1- (point)) 'invisible)))
17795 (border-and-ok-direction
17797 ;; Check if we are acting predictably before invisible text
17798 (and invisible-at-point (not invisible-before-point)
17799 (memq kind '(insert delete-backward)))
17800 ;; Check if we are acting predictably after invisible text
17801 ;; This works not well, and I have turned it off. It seems
17802 ;; better to always show and stop after invisible text.
17803 ;; (and (not invisible-at-point) invisible-before-point
17804 ;; (memq kind '(insert delete)))
17807 (when (or (memq invisible-at-point '(outline org-hide-block))
17808 (memq invisible-before-point '(outline org-hide-block)))
17809 (if (eq org-catch-invisible-edits 'error)
17810 (error "Editing in invisible areas is prohibited - make visible first"))
17811 ;; Make the area visible
17812 (save-excursion
17813 (if invisible-before-point
17814 (goto-char (previous-single-char-property-change
17815 (point) 'invisible)))
17816 (org-cycle))
17817 (cond
17818 ((eq org-catch-invisible-edits 'show)
17819 ;; That's it, we do the edit after showing
17820 (message
17821 "Unfolding invisible region around point before editing")
17822 (sit-for 1))
17823 ((and (eq org-catch-invisible-edits 'smart)
17824 border-and-ok-direction)
17825 (message "Unfolding invisible region around point before editing"))
17827 ;; Don't do the edit, make the user repeat it in full visibility
17828 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17830 (defun org-fix-tags-on-the-fly ()
17831 (when (and (equal (char-after (point-at-bol)) ?*)
17832 (org-at-heading-p))
17833 (org-align-tags-here org-tags-column)))
17835 (defun org-delete-backward-char (N)
17836 "Like `delete-backward-char', insert whitespace at field end in tables.
17837 When deleting backwards, in tables this function will insert whitespace in
17838 front of the next \"|\" separator, to keep the table aligned. The table will
17839 still be marked for re-alignment if the field did fill the entire column,
17840 because, in this case the deletion might narrow the column."
17841 (interactive "p")
17842 (org-check-before-invisible-edit 'delete-backward)
17843 (if (and (org-table-p)
17844 (eq N 1)
17845 (string-match "|" (buffer-substring (point-at-bol) (point)))
17846 (looking-at ".*?|"))
17847 (let ((pos (point))
17848 (noalign (looking-at "[^|\n\r]* |"))
17849 (c org-table-may-need-update))
17850 (backward-delete-char N)
17851 (if (not overwrite-mode)
17852 (progn
17853 (skip-chars-forward "^|")
17854 (insert " ")
17855 (goto-char (1- pos))))
17856 ;; noalign: if there were two spaces at the end, this field
17857 ;; does not determine the width of the column.
17858 (if noalign (setq org-table-may-need-update c)))
17859 (backward-delete-char N)
17860 (org-fix-tags-on-the-fly)))
17862 (defun org-delete-char (N)
17863 "Like `delete-char', but insert whitespace at field end in tables.
17864 When deleting characters, in tables this function will insert whitespace in
17865 front of the next \"|\" separator, to keep the table aligned. The table will
17866 still be marked for re-alignment if the field did fill the entire column,
17867 because, in this case the deletion might narrow the column."
17868 (interactive "p")
17869 (org-check-before-invisible-edit 'delete)
17870 (if (and (org-table-p)
17871 (not (bolp))
17872 (not (= (char-after) ?|))
17873 (eq N 1))
17874 (if (looking-at ".*?|")
17875 (let ((pos (point))
17876 (noalign (looking-at "[^|\n\r]* |"))
17877 (c org-table-may-need-update))
17878 (replace-match (concat
17879 (substring (match-string 0) 1 -1)
17880 " |"))
17881 (goto-char pos)
17882 ;; noalign: if there were two spaces at the end, this field
17883 ;; does not determine the width of the column.
17884 (if noalign (setq org-table-may-need-update c)))
17885 (delete-char N))
17886 (delete-char N)
17887 (org-fix-tags-on-the-fly)))
17889 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17890 (put 'org-self-insert-command 'delete-selection t)
17891 (put 'orgtbl-self-insert-command 'delete-selection t)
17892 (put 'org-delete-char 'delete-selection 'supersede)
17893 (put 'org-delete-backward-char 'delete-selection 'supersede)
17894 (put 'org-yank 'delete-selection 'yank)
17896 ;; Make `flyspell-mode' delay after some commands
17897 (put 'org-self-insert-command 'flyspell-delayed t)
17898 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17899 (put 'org-delete-char 'flyspell-delayed t)
17900 (put 'org-delete-backward-char 'flyspell-delayed t)
17902 ;; Make pabbrev-mode expand after org-mode commands
17903 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17904 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17906 ;; How to do this: Measure non-white length of current string
17907 ;; If equal to column width, we should realign.
17909 (defun org-remap (map &rest commands)
17910 "In MAP, remap the functions given in COMMANDS.
17911 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17912 (let (new old)
17913 (while commands
17914 (setq old (pop commands) new (pop commands))
17915 (if (fboundp 'command-remapping)
17916 (org-defkey map (vector 'remap old) new)
17917 (substitute-key-definition old new map global-map)))))
17919 (when (eq org-enable-table-editor 'optimized)
17920 ;; If the user wants maximum table support, we need to hijack
17921 ;; some standard editing functions
17922 (org-remap org-mode-map
17923 'self-insert-command 'org-self-insert-command
17924 'delete-char 'org-delete-char
17925 'delete-backward-char 'org-delete-backward-char)
17926 (org-defkey org-mode-map "|" 'org-force-self-insert))
17928 (defvar org-ctrl-c-ctrl-c-hook nil
17929 "Hook for functions attaching themselves to `C-c C-c'.
17931 This can be used to add additional functionality to the C-c C-c
17932 key which executes context-dependent commands. This hook is run
17933 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17934 run after the last test.
17936 Each function will be called with no arguments. The function
17937 must check if the context is appropriate for it to act. If yes,
17938 it should do its thing and then return a non-nil value. If the
17939 context is wrong, just do nothing and return nil.")
17941 (defvar org-ctrl-c-ctrl-c-final-hook nil
17942 "Hook for functions attaching themselves to `C-c C-c'.
17944 This can be used to add additional functionality to the C-c C-c
17945 key which executes context-dependent commands. This hook is run
17946 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17947 before the first test.
17949 Each function will be called with no arguments. The function
17950 must check if the context is appropriate for it to act. If yes,
17951 it should do its thing and then return a non-nil value. If the
17952 context is wrong, just do nothing and return nil.")
17954 (defvar org-tab-first-hook nil
17955 "Hook for functions to attach themselves to TAB.
17956 See `org-ctrl-c-ctrl-c-hook' for more information.
17957 This hook runs as the first action when TAB is pressed, even before
17958 `org-cycle' messes around with the `outline-regexp' to cater for
17959 inline tasks and plain list item folding.
17960 If any function in this hook returns t, any other actions that
17961 would have been caused by TAB (such as table field motion or visibility
17962 cycling) will not occur.")
17964 (defvar org-tab-after-check-for-table-hook nil
17965 "Hook for functions to attach themselves to TAB.
17966 See `org-ctrl-c-ctrl-c-hook' for more information.
17967 This hook runs after it has been established that the cursor is not in a
17968 table, but before checking if the cursor is in a headline or if global cycling
17969 should be done.
17970 If any function in this hook returns t, not other actions like visibility
17971 cycling will be done.")
17973 (defvar org-tab-after-check-for-cycling-hook nil
17974 "Hook for functions to attach themselves to TAB.
17975 See `org-ctrl-c-ctrl-c-hook' for more information.
17976 This hook runs after it has been established that not table field motion and
17977 not visibility should be done because of current context. This is probably
17978 the place where a package like yasnippets can hook in.")
17980 (defvar org-tab-before-tab-emulation-hook nil
17981 "Hook for functions to attach themselves to TAB.
17982 See `org-ctrl-c-ctrl-c-hook' for more information.
17983 This hook runs after every other options for TAB have been exhausted, but
17984 before indentation and \t insertion takes place.")
17986 (defvar org-metaleft-hook nil
17987 "Hook for functions attaching themselves to `M-left'.
17988 See `org-ctrl-c-ctrl-c-hook' for more information.")
17989 (defvar org-metaright-hook nil
17990 "Hook for functions attaching themselves to `M-right'.
17991 See `org-ctrl-c-ctrl-c-hook' for more information.")
17992 (defvar org-metaup-hook nil
17993 "Hook for functions attaching themselves to `M-up'.
17994 See `org-ctrl-c-ctrl-c-hook' for more information.")
17995 (defvar org-metadown-hook nil
17996 "Hook for functions attaching themselves to `M-down'.
17997 See `org-ctrl-c-ctrl-c-hook' for more information.")
17998 (defvar org-shiftmetaleft-hook nil
17999 "Hook for functions attaching themselves to `M-S-left'.
18000 See `org-ctrl-c-ctrl-c-hook' for more information.")
18001 (defvar org-shiftmetaright-hook nil
18002 "Hook for functions attaching themselves to `M-S-right'.
18003 See `org-ctrl-c-ctrl-c-hook' for more information.")
18004 (defvar org-shiftmetaup-hook nil
18005 "Hook for functions attaching themselves to `M-S-up'.
18006 See `org-ctrl-c-ctrl-c-hook' for more information.")
18007 (defvar org-shiftmetadown-hook nil
18008 "Hook for functions attaching themselves to `M-S-down'.
18009 See `org-ctrl-c-ctrl-c-hook' for more information.")
18010 (defvar org-metareturn-hook nil
18011 "Hook for functions attaching themselves to `M-RET'.
18012 See `org-ctrl-c-ctrl-c-hook' for more information.")
18013 (defvar org-shiftup-hook nil
18014 "Hook for functions attaching themselves to `S-up'.
18015 See `org-ctrl-c-ctrl-c-hook' for more information.")
18016 (defvar org-shiftup-final-hook nil
18017 "Hook for functions attaching themselves to `S-up'.
18018 This one runs after all other options except shift-select have been excluded.
18019 See `org-ctrl-c-ctrl-c-hook' for more information.")
18020 (defvar org-shiftdown-hook nil
18021 "Hook for functions attaching themselves to `S-down'.
18022 See `org-ctrl-c-ctrl-c-hook' for more information.")
18023 (defvar org-shiftdown-final-hook nil
18024 "Hook for functions attaching themselves to `S-down'.
18025 This one runs after all other options except shift-select have been excluded.
18026 See `org-ctrl-c-ctrl-c-hook' for more information.")
18027 (defvar org-shiftleft-hook nil
18028 "Hook for functions attaching themselves to `S-left'.
18029 See `org-ctrl-c-ctrl-c-hook' for more information.")
18030 (defvar org-shiftleft-final-hook nil
18031 "Hook for functions attaching themselves to `S-left'.
18032 This one runs after all other options except shift-select have been excluded.
18033 See `org-ctrl-c-ctrl-c-hook' for more information.")
18034 (defvar org-shiftright-hook nil
18035 "Hook for functions attaching themselves to `S-right'.
18036 See `org-ctrl-c-ctrl-c-hook' for more information.")
18037 (defvar org-shiftright-final-hook nil
18038 "Hook for functions attaching themselves to `S-right'.
18039 This one runs after all other options except shift-select have been excluded.
18040 See `org-ctrl-c-ctrl-c-hook' for more information.")
18042 (defun org-modifier-cursor-error ()
18043 "Throw an error, a modified cursor command was applied in wrong context."
18044 (error "This command is active in special context like tables, headlines or items"))
18046 (defun org-shiftselect-error ()
18047 "Throw an error because Shift-Cursor command was applied in wrong context."
18048 (if (and (boundp 'shift-select-mode) shift-select-mode)
18049 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18050 (error "This command works only in special context like headlines or timestamps")))
18052 (defun org-call-for-shift-select (cmd)
18053 (let ((this-command-keys-shift-translated t))
18054 (call-interactively cmd)))
18056 (defun org-shifttab (&optional arg)
18057 "Global visibility cycling or move to previous table field.
18058 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18059 on context.
18060 See the individual commands for more information."
18061 (interactive "P")
18062 (cond
18063 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18064 ((integerp arg)
18065 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18066 (message "Content view to level: %d" arg)
18067 (org-content (prefix-numeric-value arg2))
18068 (setq org-cycle-global-status 'overview)))
18069 (t (call-interactively 'org-global-cycle))))
18071 (defun org-shiftmetaleft ()
18072 "Promote subtree or delete table column.
18073 Calls `org-promote-subtree', `org-outdent-item',
18074 or `org-table-delete-column', depending on context.
18075 See the individual commands for more information."
18076 (interactive)
18077 (cond
18078 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18079 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18080 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18081 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
18082 (t (org-modifier-cursor-error))))
18084 (defun org-shiftmetaright ()
18085 "Demote subtree or insert table column.
18086 Calls `org-demote-subtree', `org-indent-item',
18087 or `org-table-insert-column', depending on context.
18088 See the individual commands for more information."
18089 (interactive)
18090 (cond
18091 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18092 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18093 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18094 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
18095 (t (org-modifier-cursor-error))))
18097 (defun org-shiftmetaup (&optional arg)
18098 "Move subtree up or kill table row.
18099 Calls `org-move-subtree-up' or `org-table-kill-row' or
18100 `org-move-item-up' depending on context. See the individual commands
18101 for more information."
18102 (interactive "P")
18103 (cond
18104 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18105 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18106 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18107 ((org-at-item-p) (call-interactively 'org-move-item-up))
18108 (t (org-modifier-cursor-error))))
18110 (defun org-shiftmetadown (&optional arg)
18111 "Move subtree down or insert table row.
18112 Calls `org-move-subtree-down' or `org-table-insert-row' or
18113 `org-move-item-down', depending on context. See the individual
18114 commands for more information."
18115 (interactive "P")
18116 (cond
18117 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18118 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18119 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18120 ((org-at-item-p) (call-interactively 'org-move-item-down))
18121 (t (org-modifier-cursor-error))))
18123 (defsubst org-hidden-tree-error ()
18124 (error
18125 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18127 (defun org-metaleft (&optional arg)
18128 "Promote heading or move table column to left.
18129 Calls `org-do-promote' or `org-table-move-column', depending on context.
18130 With no specific context, calls the Emacs default `backward-word'.
18131 See the individual commands for more information."
18132 (interactive "P")
18133 (cond
18134 ((run-hook-with-args-until-success 'org-metaleft-hook))
18135 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18136 ((org-with-limited-levels
18137 (or (org-at-heading-p)
18138 (and (org-region-active-p)
18139 (save-excursion
18140 (goto-char (region-beginning))
18141 (org-at-heading-p)))))
18142 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18143 (call-interactively 'org-do-promote))
18144 ;; At an inline task.
18145 ((org-at-heading-p)
18146 (call-interactively 'org-inlinetask-promote))
18147 ((or (org-at-item-p)
18148 (and (org-region-active-p)
18149 (save-excursion
18150 (goto-char (region-beginning))
18151 (org-at-item-p))))
18152 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18153 (call-interactively 'org-outdent-item))
18154 (t (call-interactively 'backward-word))))
18156 (defun org-metaright (&optional arg)
18157 "Demote a subtree, a list item or move table column to right.
18158 In front of a drawer or a block keyword, indent it correctly.
18159 With no specific context, calls the Emacs default `forward-word'.
18160 See the individual commands for more information."
18161 (interactive "P")
18162 (cond
18163 ((run-hook-with-args-until-success 'org-metaright-hook))
18164 ((org-at-table-p) (call-interactively 'org-table-move-column))
18165 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18166 ((org-at-block-p) (call-interactively 'org-indent-block))
18167 ((org-with-limited-levels
18168 (or (org-at-heading-p)
18169 (and (org-region-active-p)
18170 (save-excursion
18171 (goto-char (region-beginning))
18172 (org-at-heading-p)))))
18173 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18174 (call-interactively 'org-do-demote))
18175 ;; At an inline task.
18176 ((org-at-heading-p)
18177 (call-interactively 'org-inlinetask-demote))
18178 ((or (org-at-item-p)
18179 (and (org-region-active-p)
18180 (save-excursion
18181 (goto-char (region-beginning))
18182 (org-at-item-p))))
18183 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18184 (call-interactively 'org-indent-item))
18185 (t (call-interactively 'forward-word))))
18187 (defun org-check-for-hidden (what)
18188 "Check if there are hidden headlines/items in the current visual line.
18189 WHAT can be either `headlines' or `items'. If the current line is
18190 an outline or item heading and it has a folded subtree below it,
18191 this function returns t, nil otherwise."
18192 (let ((re (cond
18193 ((eq what 'headlines) org-outline-regexp-bol)
18194 ((eq what 'items) (org-item-beginning-re))
18195 (t (error "This should not happen"))))
18196 beg end)
18197 (save-excursion
18198 (catch 'exit
18199 (unless (org-region-active-p)
18200 (setq beg (point-at-bol))
18201 (beginning-of-line 2)
18202 (while (and (not (eobp)) ;; this is like `next-line'
18203 (get-char-property (1- (point)) 'invisible))
18204 (beginning-of-line 2))
18205 (setq end (point))
18206 (goto-char beg)
18207 (goto-char (point-at-eol))
18208 (setq end (max end (point)))
18209 (while (re-search-forward re end t)
18210 (if (get-char-property (match-beginning 0) 'invisible)
18211 (throw 'exit t))))
18212 nil))))
18214 (defun org-metaup (&optional arg)
18215 "Move subtree up or move table row up.
18216 Calls `org-move-subtree-up' or `org-table-move-row' or
18217 `org-move-item-up', depending on context. See the individual commands
18218 for more information."
18219 (interactive "P")
18220 (cond
18221 ((run-hook-with-args-until-success 'org-metaup-hook))
18222 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18223 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18224 ((org-at-item-p) (call-interactively 'org-move-item-up))
18225 (t (transpose-lines 1) (beginning-of-line -1))))
18227 (defun org-metadown (&optional arg)
18228 "Move subtree down or move table row down.
18229 Calls `org-move-subtree-down' or `org-table-move-row' or
18230 `org-move-item-down', depending on context. See the individual
18231 commands for more information."
18232 (interactive "P")
18233 (cond
18234 ((run-hook-with-args-until-success 'org-metadown-hook))
18235 ((org-at-table-p) (call-interactively 'org-table-move-row))
18236 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18237 ((org-at-item-p) (call-interactively 'org-move-item-down))
18238 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18240 (defun org-shiftup (&optional arg)
18241 "Increase item in timestamp or increase priority of current headline.
18242 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18243 depending on context. See the individual commands for more information."
18244 (interactive "P")
18245 (cond
18246 ((run-hook-with-args-until-success 'org-shiftup-hook))
18247 ((and org-support-shift-select (org-region-active-p))
18248 (org-call-for-shift-select 'previous-line))
18249 ((org-at-timestamp-p t)
18250 (call-interactively (if org-edit-timestamp-down-means-later
18251 'org-timestamp-down 'org-timestamp-up)))
18252 ((and (not (eq org-support-shift-select 'always))
18253 org-enable-priority-commands
18254 (org-at-heading-p))
18255 (call-interactively 'org-priority-up))
18256 ((and (not org-support-shift-select) (org-at-item-p))
18257 (call-interactively 'org-previous-item))
18258 ((org-clocktable-try-shift 'up arg))
18259 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18260 (org-support-shift-select
18261 (org-call-for-shift-select 'previous-line))
18262 (t (org-shiftselect-error))))
18264 (defun org-shiftdown (&optional arg)
18265 "Decrease item in timestamp or decrease priority of current headline.
18266 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18267 depending on context. See the individual commands for more information."
18268 (interactive "P")
18269 (cond
18270 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18271 ((and org-support-shift-select (org-region-active-p))
18272 (org-call-for-shift-select 'next-line))
18273 ((org-at-timestamp-p t)
18274 (call-interactively (if org-edit-timestamp-down-means-later
18275 'org-timestamp-up 'org-timestamp-down)))
18276 ((and (not (eq org-support-shift-select 'always))
18277 org-enable-priority-commands
18278 (org-at-heading-p))
18279 (call-interactively 'org-priority-down))
18280 ((and (not org-support-shift-select) (org-at-item-p))
18281 (call-interactively 'org-next-item))
18282 ((org-clocktable-try-shift 'down arg))
18283 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18284 (org-support-shift-select
18285 (org-call-for-shift-select 'next-line))
18286 (t (org-shiftselect-error))))
18288 (defun org-shiftright (&optional arg)
18289 "Cycle the thing at point or in the current line, depending on context.
18290 Depending on context, this does one of the following:
18292 - switch a timestamp at point one day into the future
18293 - on a headline, switch to the next TODO keyword.
18294 - on an item, switch entire list to the next bullet type
18295 - on a property line, switch to the next allowed value
18296 - on a clocktable definition line, move time block into the future"
18297 (interactive "P")
18298 (cond
18299 ((run-hook-with-args-until-success 'org-shiftright-hook))
18300 ((and org-support-shift-select (org-region-active-p))
18301 (org-call-for-shift-select 'forward-char))
18302 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18303 ((and (not (eq org-support-shift-select 'always))
18304 (org-at-heading-p))
18305 (let ((org-inhibit-logging
18306 (not org-treat-S-cursor-todo-selection-as-state-change))
18307 (org-inhibit-blocking
18308 (not org-treat-S-cursor-todo-selection-as-state-change)))
18309 (org-call-with-arg 'org-todo 'right)))
18310 ((or (and org-support-shift-select
18311 (not (eq org-support-shift-select 'always))
18312 (org-at-item-bullet-p))
18313 (and (not org-support-shift-select) (org-at-item-p)))
18314 (org-call-with-arg 'org-cycle-list-bullet nil))
18315 ((and (not (eq org-support-shift-select 'always))
18316 (org-at-property-p))
18317 (call-interactively 'org-property-next-allowed-value))
18318 ((org-clocktable-try-shift 'right arg))
18319 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18320 (org-support-shift-select
18321 (org-call-for-shift-select 'forward-char))
18322 (t (org-shiftselect-error))))
18324 (defun org-shiftleft (&optional arg)
18325 "Cycle the thing at point or in the current line, depending on context.
18326 Depending on context, this does one of the following:
18328 - switch a timestamp at point one day into the past
18329 - on a headline, switch to the previous TODO keyword.
18330 - on an item, switch entire list to the previous bullet type
18331 - on a property line, switch to the previous allowed value
18332 - on a clocktable definition line, move time block into the past"
18333 (interactive "P")
18334 (cond
18335 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18336 ((and org-support-shift-select (org-region-active-p))
18337 (org-call-for-shift-select 'backward-char))
18338 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18339 ((and (not (eq org-support-shift-select 'always))
18340 (org-at-heading-p))
18341 (let ((org-inhibit-logging
18342 (not org-treat-S-cursor-todo-selection-as-state-change))
18343 (org-inhibit-blocking
18344 (not org-treat-S-cursor-todo-selection-as-state-change)))
18345 (org-call-with-arg 'org-todo 'left)))
18346 ((or (and org-support-shift-select
18347 (not (eq org-support-shift-select 'always))
18348 (org-at-item-bullet-p))
18349 (and (not org-support-shift-select) (org-at-item-p)))
18350 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18351 ((and (not (eq org-support-shift-select 'always))
18352 (org-at-property-p))
18353 (call-interactively 'org-property-previous-allowed-value))
18354 ((org-clocktable-try-shift 'left arg))
18355 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18356 (org-support-shift-select
18357 (org-call-for-shift-select 'backward-char))
18358 (t (org-shiftselect-error))))
18360 (defun org-shiftcontrolright ()
18361 "Switch to next TODO set."
18362 (interactive)
18363 (cond
18364 ((and org-support-shift-select (org-region-active-p))
18365 (org-call-for-shift-select 'forward-word))
18366 ((and (not (eq org-support-shift-select 'always))
18367 (org-at-heading-p))
18368 (org-call-with-arg 'org-todo 'nextset))
18369 (org-support-shift-select
18370 (org-call-for-shift-select 'forward-word))
18371 (t (org-shiftselect-error))))
18373 (defun org-shiftcontrolleft ()
18374 "Switch to previous TODO set."
18375 (interactive)
18376 (cond
18377 ((and org-support-shift-select (org-region-active-p))
18378 (org-call-for-shift-select 'backward-word))
18379 ((and (not (eq org-support-shift-select 'always))
18380 (org-at-heading-p))
18381 (org-call-with-arg 'org-todo 'previousset))
18382 (org-support-shift-select
18383 (org-call-for-shift-select 'backward-word))
18384 (t (org-shiftselect-error))))
18386 (defun org-shiftcontrolup ()
18387 "Change timestamps synchronously up in CLOCK log lines."
18388 (interactive)
18389 (cond ((and (not org-support-shift-select)
18390 (org-at-clock-log-p)
18391 (org-at-timestamp-p t))
18392 (org-clock-timestamps-up))
18393 (t (org-shiftselect-error))))
18395 (defun org-shiftcontroldown ()
18396 "Change timestamps synchronously down in CLOCK log lines."
18397 (interactive)
18398 (cond ((and (not org-support-shift-select)
18399 (org-at-clock-log-p)
18400 (org-at-timestamp-p t))
18401 (org-clock-timestamps-down))
18402 (t (org-shiftselect-error))))
18404 (defun org-ctrl-c-ret ()
18405 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18406 (interactive)
18407 (cond
18408 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18409 (t (call-interactively 'org-insert-heading))))
18411 (defun org-find-visible ()
18412 (let ((s (point)))
18413 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18414 (get-char-property s 'invisible)))
18416 (defun org-find-invisible ()
18417 (let ((s (point)))
18418 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18419 (not (get-char-property s 'invisible))))
18422 (defun org-copy-visible (beg end)
18423 "Copy the visible parts of the region."
18424 (interactive "r")
18425 (let (snippets s)
18426 (save-excursion
18427 (save-restriction
18428 (narrow-to-region beg end)
18429 (setq s (goto-char (point-min)))
18430 (while (not (= (point) (point-max)))
18431 (goto-char (org-find-invisible))
18432 (push (buffer-substring s (point)) snippets)
18433 (setq s (goto-char (org-find-visible))))))
18434 (kill-new (apply 'concat (nreverse snippets)))))
18436 (defun org-copy-special ()
18437 "Copy region in table or copy current subtree.
18438 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18439 See the individual commands for more information."
18440 (interactive)
18441 (call-interactively
18442 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18444 (defun org-cut-special ()
18445 "Cut region in table or cut current subtree.
18446 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18447 See the individual commands for more information."
18448 (interactive)
18449 (call-interactively
18450 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18452 (defun org-paste-special (arg)
18453 "Paste rectangular region into table, or past subtree relative to level.
18454 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18455 See the individual commands for more information."
18456 (interactive "P")
18457 (if (org-at-table-p)
18458 (org-table-paste-rectangle)
18459 (org-paste-subtree arg)))
18461 (defun org-edit-special (&optional arg)
18462 "Call a special editor for the stuff at point.
18463 When at a table, call the formula editor with `org-table-edit-formulas'.
18464 When at the first line of an src example, call `org-edit-src-code'.
18465 When in an #+include line, visit the include file. Otherwise call
18466 `ffap' to visit the file at point."
18467 (interactive)
18468 ;; possibly prep session before editing source
18469 (when arg
18470 (let* ((info (org-babel-get-src-block-info))
18471 (lang (nth 0 info))
18472 (params (nth 2 info))
18473 (session (cdr (assoc :session params))))
18474 (when (and info session) ;; we are in a source-code block with a session
18475 (funcall
18476 (intern (concat "org-babel-prep-session:" lang)) session params))))
18477 (cond ;; proceed with `org-edit-special'
18478 ((save-excursion
18479 (beginning-of-line 1)
18480 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18481 (find-file (org-trim (match-string 1))))
18482 ((org-edit-src-code))
18483 ((org-edit-fixed-width-region))
18484 ((org-at-table.el-p)
18485 (org-edit-src-code))
18486 ((or (org-at-table-p)
18487 (save-excursion
18488 (beginning-of-line 1)
18489 (looking-at "[ \t]*#\\+TBLFM:")))
18490 (call-interactively 'org-table-edit-formulas))
18491 (t (call-interactively 'ffap))))
18493 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18494 (defun org-ctrl-c-ctrl-c (&optional arg)
18495 "Set tags in headline, or update according to changed information at point.
18497 This command does many different things, depending on context:
18499 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18500 this is what we do.
18502 - If the cursor is on a statistics cookie, update it.
18504 - If the cursor is in a headline, prompt for tags and insert them
18505 into the current line, aligned to `org-tags-column'. When called
18506 with prefix arg, realign all tags in the current buffer.
18508 - If the cursor is in one of the special #+KEYWORD lines, this
18509 triggers scanning the buffer for these lines and updating the
18510 information.
18512 - If the cursor is inside a table, realign the table. This command
18513 works even if the automatic table editor has been turned off.
18515 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18516 the entire table.
18518 - If the cursor is at a footnote reference or definition, jump to
18519 the corresponding definition or references, respectively.
18521 - If the cursor is a the beginning of a dynamic block, update it.
18523 - If the current buffer is a capture buffer, close note and file it.
18525 - If the cursor is on a <<<target>>>, update radio targets and
18526 corresponding links in this buffer.
18528 - If the cursor is on a numbered item in a plain list, renumber the
18529 ordered list.
18531 - If the cursor is on a checkbox, toggle it.
18533 - If the cursor is on a code block, evaluate it. The variable
18534 `org-confirm-babel-evaluate' can be used to control prompting
18535 before code block evaluation, by default every code block
18536 evaluation requires confirmation. Code block evaluation can be
18537 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18538 (interactive "P")
18539 (let ((org-enable-table-editor t))
18540 (cond
18541 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18542 org-occur-highlights
18543 org-latex-fragment-image-overlays)
18544 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18545 (org-remove-occur-highlights)
18546 (org-remove-latex-fragment-image-overlays)
18547 (message "Temporary highlights/overlays removed from current buffer"))
18548 ((and (local-variable-p 'org-finish-function (current-buffer))
18549 (fboundp org-finish-function))
18550 (funcall org-finish-function))
18551 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18552 ((org-in-regexp org-ts-regexp-both)
18553 (org-timestamp-change 0 'day))
18554 ((or (looking-at org-property-start-re)
18555 (org-at-property-p))
18556 (call-interactively 'org-property-action))
18557 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18558 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18559 (or (org-at-heading-p) (org-at-item-p)))
18560 (call-interactively 'org-update-statistics-cookies))
18561 ((org-at-heading-p) (call-interactively 'org-set-tags))
18562 ((org-at-table.el-p)
18563 (message "Use C-c ' to edit table.el tables"))
18564 ((org-at-table-p)
18565 (org-table-maybe-eval-formula)
18566 (if arg
18567 (call-interactively 'org-table-recalculate)
18568 (org-table-maybe-recalculate-line))
18569 (call-interactively 'org-table-align)
18570 (orgtbl-send-table 'maybe))
18571 ((or (org-footnote-at-reference-p)
18572 (org-footnote-at-definition-p))
18573 (call-interactively 'org-footnote-action))
18574 ((org-at-item-checkbox-p)
18575 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18576 ;; list only if at top item.
18577 (let* ((cbox (match-string 1))
18578 (struct (org-list-struct))
18579 (old-struct (copy-tree struct))
18580 (parents (org-list-parents-alist struct))
18581 (orderedp (org-entry-get nil "ORDERED"))
18582 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18583 block-item)
18584 ;; Use a light version of `org-toggle-checkbox' to avoid
18585 ;; computing list structure twice.
18586 (let ((new-box (cond
18587 ((equal arg '(16)) "[-]")
18588 ((equal arg '(4)) nil)
18589 ((equal "[X]" cbox) "[ ]")
18590 (t "[X]"))))
18591 (if (and firstp arg)
18592 ;; If at first item of sub-list, remove check-box from
18593 ;; every item at the same level.
18594 (mapc
18595 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18596 (org-list-get-all-items
18597 (point-at-bol) struct (org-list-prevs-alist struct)))
18598 (org-list-set-checkbox (point-at-bol) struct new-box)))
18599 ;; Replicate `org-list-write-struct', while grabbing a return
18600 ;; value from `org-list-struct-fix-box'.
18601 (org-list-struct-fix-ind struct parents 2)
18602 (org-list-struct-fix-item-end struct)
18603 (let ((prevs (org-list-prevs-alist struct)))
18604 (org-list-struct-fix-bul struct prevs)
18605 (org-list-struct-fix-ind struct parents)
18606 (setq block-item
18607 (org-list-struct-fix-box struct parents prevs orderedp)))
18608 (org-list-struct-apply-struct struct old-struct)
18609 (org-update-checkbox-count-maybe)
18610 (when block-item
18611 (message
18612 "Checkboxes were removed due to unchecked box at line %d"
18613 (org-current-line block-item)))
18614 (when firstp (org-list-send-list 'maybe))))
18615 ((org-at-item-p)
18616 ;; Cursor at an item: repair list. Do checkbox related actions
18617 ;; only if function was called with an argument. Send list only
18618 ;; if at top item.
18619 (let* ((struct (org-list-struct))
18620 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18621 old-struct)
18622 (when arg
18623 (setq old-struct (copy-tree struct))
18624 (if firstp
18625 ;; If at first item of sub-list, add check-box to every
18626 ;; item at the same level.
18627 (mapc
18628 (lambda (pos)
18629 (unless (org-list-get-checkbox pos struct)
18630 (org-list-set-checkbox pos struct "[ ]")))
18631 (org-list-get-all-items
18632 (point-at-bol) struct (org-list-prevs-alist struct)))
18633 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18634 (org-list-write-struct
18635 struct (org-list-parents-alist struct) old-struct)
18636 (when arg (org-update-checkbox-count-maybe))
18637 (when firstp (org-list-send-list 'maybe))))
18638 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18639 ;; Dynamic block
18640 (beginning-of-line 1)
18641 (save-excursion (org-update-dblock)))
18642 ((save-excursion
18643 (beginning-of-line 1)
18644 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18645 (cond
18646 ((equal (match-string 1) "TBLFM")
18647 ;; Recalculate the table before this line
18648 (save-excursion
18649 (beginning-of-line 1)
18650 (skip-chars-backward " \r\n\t")
18651 (if (org-at-table-p)
18652 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18654 (let ((org-inhibit-startup-visibility-stuff t)
18655 (org-startup-align-all-tables nil))
18656 (when (boundp 'org-table-coordinate-overlays)
18657 (mapc 'delete-overlay org-table-coordinate-overlays)
18658 (setq org-table-coordinate-overlays nil))
18659 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18660 (message "Local setup has been refreshed"))))
18661 ((org-clock-update-time-maybe))
18663 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18664 (error "C-c C-c can do nothing useful at this location"))))))
18666 (defun org-mode-restart ()
18667 "Restart Org-mode, to scan again for special lines.
18668 Also updates the keyword regular expressions."
18669 (interactive)
18670 (org-mode)
18671 (message "Org-mode restarted"))
18673 (defun org-kill-note-or-show-branches ()
18674 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18675 (interactive)
18676 (if (not org-finish-function)
18677 (progn
18678 (hide-subtree)
18679 (call-interactively 'show-branches))
18680 (let ((org-note-abort t))
18681 (funcall org-finish-function))))
18683 (defun org-return (&optional indent)
18684 "Goto next table row or insert a newline.
18685 Calls `org-table-next-row' or `newline', depending on context.
18686 See the individual commands for more information."
18687 (interactive)
18688 (cond
18689 ((or (bobp) (org-in-src-block-p))
18690 (if indent (newline-and-indent) (newline)))
18691 ((org-at-table-p)
18692 (org-table-justify-field-maybe)
18693 (call-interactively 'org-table-next-row))
18694 ;; when `newline-and-indent' is called within a list, make sure
18695 ;; text moved stays inside the item.
18696 ((and (org-in-item-p) indent)
18697 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18698 (progn
18699 (save-match-data (newline))
18700 (org-indent-line-to (length (match-string 0))))
18701 (let ((ind (org-get-indentation)))
18702 (newline)
18703 (if (org-looking-back org-list-end-re)
18704 (org-indent-line-function)
18705 (org-indent-line-to ind)))))
18706 ((and org-return-follows-link
18707 (let ((tprop (get-text-property (point) 'face)))
18708 (or (eq tprop 'org-link)
18709 (and (listp tprop) (memq 'org-link tprop)))))
18710 (call-interactively 'org-open-at-point))
18711 ((and (org-at-heading-p)
18712 (looking-at
18713 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18714 (org-show-entry)
18715 (end-of-line 1)
18716 (newline))
18717 (t (if indent (newline-and-indent) (newline)))))
18719 (defun org-return-indent ()
18720 "Goto next table row or insert a newline and indent.
18721 Calls `org-table-next-row' or `newline-and-indent', depending on
18722 context. See the individual commands for more information."
18723 (interactive)
18724 (org-return t))
18726 (defun org-ctrl-c-star ()
18727 "Compute table, or change heading status of lines.
18728 Calls `org-table-recalculate' or `org-toggle-heading',
18729 depending on context."
18730 (interactive)
18731 (cond
18732 ((org-at-table-p)
18733 (call-interactively 'org-table-recalculate))
18735 ;; Convert all lines in region to list items
18736 (call-interactively 'org-toggle-heading))))
18738 (defun org-ctrl-c-minus ()
18739 "Insert separator line in table or modify bullet status of line.
18740 Also turns a plain line or a region of lines into list items.
18741 Calls `org-table-insert-hline', `org-toggle-item', or
18742 `org-cycle-list-bullet', depending on context."
18743 (interactive)
18744 (cond
18745 ((org-at-table-p)
18746 (call-interactively 'org-table-insert-hline))
18747 ((org-region-active-p)
18748 (call-interactively 'org-toggle-item))
18749 ((org-in-item-p)
18750 (call-interactively 'org-cycle-list-bullet))
18752 (call-interactively 'org-toggle-item))))
18754 (defun org-toggle-item (arg)
18755 "Convert headings or normal lines to items, items to normal lines.
18756 If there is no active region, only the current line is considered.
18758 If the first non blank line in the region is an headline, convert
18759 all headlines to items, shifting text accordingly.
18761 If it is an item, convert all items to normal lines.
18763 If it is normal text, change region into an item. With a prefix
18764 argument ARG, change each line in region into an item."
18765 (interactive "P")
18766 (let ((shift-text
18767 (function
18768 ;; Shift text in current section to IND, from point to END.
18769 ;; The function leaves point to END line.
18770 (lambda (ind end)
18771 (let ((min-i 1000) (end (copy-marker end)))
18772 ;; First determine the minimum indentation (MIN-I) of
18773 ;; the text.
18774 (save-excursion
18775 (catch 'exit
18776 (while (< (point) end)
18777 (let ((i (org-get-indentation)))
18778 (cond
18779 ;; Skip blank lines and inline tasks.
18780 ((looking-at "^[ \t]*$"))
18781 ((looking-at org-outline-regexp-bol))
18782 ;; We can't find less than 0 indentation.
18783 ((zerop i) (throw 'exit (setq min-i 0)))
18784 ((< i min-i) (setq min-i i))))
18785 (forward-line))))
18786 ;; Then indent each line so that a line indented to
18787 ;; MIN-I becomes indented to IND. Ignore blank lines
18788 ;; and inline tasks in the process.
18789 (let ((delta (- ind min-i)))
18790 (while (< (point) end)
18791 (unless (or (looking-at "^[ \t]*$")
18792 (looking-at org-outline-regexp-bol))
18793 (org-indent-line-to (+ (org-get-indentation) delta)))
18794 (forward-line)))))))
18795 (skip-blanks
18796 (function
18797 ;; Return beginning of first non-blank line, starting from
18798 ;; line at POS.
18799 (lambda (pos)
18800 (save-excursion
18801 (goto-char pos)
18802 (skip-chars-forward " \r\t\n")
18803 (point-at-bol)))))
18804 beg end)
18805 ;; Determine boundaries of changes.
18806 (if (org-region-active-p)
18807 (setq beg (funcall skip-blanks (region-beginning))
18808 end (copy-marker (region-end)))
18809 (setq beg (funcall skip-blanks (point-at-bol))
18810 end (copy-marker (point-at-eol))))
18811 ;; Depending on the starting line, choose an action on the text
18812 ;; between BEG and END.
18813 (org-with-limited-levels
18814 (save-excursion
18815 (goto-char beg)
18816 (cond
18817 ;; Case 1. Start at an item: de-itemize. Note that it only
18818 ;; happens when a region is active: `org-ctrl-c-minus'
18819 ;; would call `org-cycle-list-bullet' otherwise.
18820 ((org-at-item-p)
18821 (while (< (point) end)
18822 (when (org-at-item-p)
18823 (skip-chars-forward " \t")
18824 (delete-region (point) (match-end 0)))
18825 (forward-line)))
18826 ;; Case 2. Start at an heading: convert to items.
18827 ((org-at-heading-p)
18828 (let* ((bul (org-list-bullet-string "-"))
18829 (bul-len (length bul))
18830 ;; Indentation of the first heading. It should be
18831 ;; relative to the indentation of its parent, if any.
18832 (start-ind (save-excursion
18833 (cond
18834 ((not org-adapt-indentation) 0)
18835 ((not (outline-previous-heading)) 0)
18836 (t (length (match-string 0))))))
18837 ;; Level of first heading. Further headings will be
18838 ;; compared to it to determine hierarchy in the list.
18839 (ref-level (org-reduced-level (org-outline-level))))
18840 (while (< (point) end)
18841 (let* ((level (org-reduced-level (org-outline-level)))
18842 (delta (max 0 (- level ref-level))))
18843 ;; If current headline is less indented than the first
18844 ;; one, set it as reference, in order to preserve
18845 ;; subtrees.
18846 (when (< level ref-level) (setq ref-level level))
18847 (replace-match bul t t)
18848 (org-indent-line-to (+ start-ind (* delta bul-len)))
18849 ;; Ensure all text down to END (or SECTION-END) belongs
18850 ;; to the newly created item.
18851 (let ((section-end (save-excursion
18852 (or (outline-next-heading) (point)))))
18853 (forward-line)
18854 (funcall shift-text
18855 (+ start-ind (* (1+ delta) bul-len))
18856 (min end section-end)))))))
18857 ;; Case 3. Normal line with ARG: turn each non-item line into
18858 ;; an item.
18859 (arg
18860 (while (< (point) end)
18861 (unless (or (org-at-heading-p) (org-at-item-p))
18862 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18863 (replace-match
18864 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18865 (forward-line)))
18866 ;; Case 4. Normal line without ARG: make the first line of
18867 ;; region an item, and shift indentation of others
18868 ;; lines to set them as item's body.
18869 (t (let* ((bul (org-list-bullet-string "-"))
18870 (bul-len (length bul))
18871 (ref-ind (org-get-indentation)))
18872 (skip-chars-forward " \t")
18873 (insert bul)
18874 (forward-line)
18875 (while (< (point) end)
18876 ;; Ensure that lines less indented than first one
18877 ;; still get included in item body.
18878 (funcall shift-text
18879 (+ ref-ind bul-len)
18880 (min end (save-excursion (or (outline-next-heading)
18881 (point)))))
18882 (forward-line)))))))))
18884 (defun org-toggle-heading (&optional nstars)
18885 "Convert headings to normal text, or items or text to headings.
18886 If there is no active region, only the current line is considered.
18888 If the first non blank line is an headline, remove the stars from
18889 all headlines in the region.
18891 If it is a plain list item, turn all plain list items into headings.
18893 If it is a normal line, turn each and every normal line (i.e. not
18894 an heading or an item) in the region into a heading.
18896 When converting a line into a heading, the number of stars is chosen
18897 such that the lines become children of the current entry. However,
18898 when a prefix argument is given, its value determines the number of
18899 stars to add."
18900 (interactive "P")
18901 (let ((skip-blanks
18902 (function
18903 ;; Return beginning of first non-blank line, starting from
18904 ;; line at POS.
18905 (lambda (pos)
18906 (save-excursion
18907 (goto-char pos)
18908 (skip-chars-forward " \r\t\n")
18909 (point-at-bol)))))
18910 beg end)
18911 ;; Determine boundaries of changes. If region ends at a bol, do
18912 ;; not consider the last line to be in the region.
18913 (if (org-region-active-p)
18914 (setq beg (funcall skip-blanks (region-beginning))
18915 end (copy-marker (save-excursion
18916 (goto-char (region-end))
18917 (if (bolp) (point) (point-at-eol)))))
18918 (setq beg (funcall skip-blanks (point-at-bol))
18919 end (copy-marker (point-at-eol))))
18920 ;; Ensure inline tasks don't count as headings.
18921 (org-with-limited-levels
18922 (save-excursion
18923 (goto-char beg)
18924 (cond
18925 ;; Case 1. Started at an heading: de-star headings.
18926 ((org-at-heading-p)
18927 (while (< (point) end)
18928 (when (org-at-heading-p t)
18929 (looking-at org-outline-regexp) (replace-match ""))
18930 (forward-line)))
18931 ;; Case 2. Started at an item: change items into headlines.
18932 ;; One star will be added by `org-list-to-subtree'.
18933 ((org-at-item-p)
18934 (let* ((stars (make-string
18935 (if nstars
18936 ;; subtract the star that will be added again by
18937 ;; `org-list-to-subtree'
18938 (1- (prefix-numeric-value current-prefix-arg))
18939 (or (org-current-level) 0))
18940 ?*))
18941 (add-stars
18942 (cond (nstars "") ; stars from prefix only
18943 ((equal stars "") "") ; before first heading
18944 (org-odd-levels-only "*") ; inside heading, odd
18945 (t "")))) ; inside heading, oddeven
18946 (while (< (point) end)
18947 (when (org-at-item-p)
18948 ;; Pay attention to cases when region ends before list.
18949 (let* ((struct (org-list-struct))
18950 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18951 (save-restriction
18952 (narrow-to-region (point) list-end)
18953 (insert
18954 (org-list-to-subtree
18955 (org-list-parse-list t)
18956 '(:istart (concat stars add-stars (funcall get-stars depth))
18957 :icount (concat stars add-stars (funcall get-stars depth))))))))
18958 (forward-line))))
18959 ;; Case 3. Started at normal text: make every line an heading,
18960 ;; skipping headlines and items.
18961 (t (let* ((stars (make-string
18962 (if nstars
18963 (prefix-numeric-value current-prefix-arg)
18964 (or (org-current-level) 0))
18965 ?*))
18966 (add-stars
18967 (cond (nstars "") ; stars from prefix only
18968 ((equal stars "") "*") ; before first heading
18969 (org-odd-levels-only "**") ; inside heading, odd
18970 (t "*"))) ; inside heading, oddeven
18971 (rpl (concat stars add-stars " ")))
18972 (while (< (point) end)
18973 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18974 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18975 (replace-match (concat rpl (match-string 2))))
18976 (forward-line)))))))))
18978 (defun org-meta-return (&optional arg)
18979 "Insert a new heading or wrap a region in a table.
18980 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18981 See the individual commands for more information."
18982 (interactive "P")
18983 (cond
18984 ((run-hook-with-args-until-success 'org-metareturn-hook))
18985 ((or (org-at-drawer-p) (org-at-property-p))
18986 (newline-and-indent))
18987 ((org-at-table-p)
18988 (call-interactively 'org-table-wrap-region))
18989 (t (call-interactively 'org-insert-heading))))
18991 ;;; Menu entries
18993 ;; Define the Org-mode menus
18994 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18995 '("Tbl"
18996 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18997 ["Next Field" org-cycle (org-at-table-p)]
18998 ["Previous Field" org-shifttab (org-at-table-p)]
18999 ["Next Row" org-return (org-at-table-p)]
19000 "--"
19001 ["Blank Field" org-table-blank-field (org-at-table-p)]
19002 ["Edit Field" org-table-edit-field (org-at-table-p)]
19003 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19004 "--"
19005 ("Column"
19006 ["Move Column Left" org-metaleft (org-at-table-p)]
19007 ["Move Column Right" org-metaright (org-at-table-p)]
19008 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19009 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19010 ("Row"
19011 ["Move Row Up" org-metaup (org-at-table-p)]
19012 ["Move Row Down" org-metadown (org-at-table-p)]
19013 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19014 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19015 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19016 "--"
19017 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19018 ("Rectangle"
19019 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19020 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19021 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19022 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19023 "--"
19024 ("Calculate"
19025 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19026 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19027 ["Edit Formulas" org-edit-special (org-at-table-p)]
19028 "--"
19029 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19030 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19031 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19032 "--"
19033 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19034 "--"
19035 ["Sum Column/Rectangle" org-table-sum
19036 (or (org-at-table-p) (org-region-active-p))]
19037 ["Which Column?" org-table-current-column (org-at-table-p)])
19038 ["Debug Formulas"
19039 org-table-toggle-formula-debugger
19040 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19041 ["Show Col/Row Numbers"
19042 org-table-toggle-coordinate-overlays
19043 :style toggle
19044 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19045 "--"
19046 ["Create" org-table-create (and (not (org-at-table-p))
19047 org-enable-table-editor)]
19048 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19049 ["Import from File" org-table-import (not (org-at-table-p))]
19050 ["Export to File" org-table-export (org-at-table-p)]
19051 "--"
19052 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19054 (easy-menu-define org-org-menu org-mode-map "Org menu"
19055 '("Org"
19056 ("Show/Hide"
19057 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19058 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19059 ["Sparse Tree..." org-sparse-tree t]
19060 ["Reveal Context" org-reveal t]
19061 ["Show All" show-all t]
19062 "--"
19063 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19064 "--"
19065 ["New Heading" org-insert-heading t]
19066 ("Navigate Headings"
19067 ["Up" outline-up-heading t]
19068 ["Next" outline-next-visible-heading t]
19069 ["Previous" outline-previous-visible-heading t]
19070 ["Next Same Level" outline-forward-same-level t]
19071 ["Previous Same Level" outline-backward-same-level t]
19072 "--"
19073 ["Jump" org-goto t])
19074 ("Edit Structure"
19075 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19076 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19077 "--"
19078 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19079 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19080 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19081 "--"
19082 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19083 "--"
19084 ["Copy visible text" org-copy-visible t]
19085 "--"
19086 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19087 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19088 ["Demote Heading" org-metaright (not (org-at-table-p))]
19089 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19090 "--"
19091 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19092 "--"
19093 ["Convert to odd levels" org-convert-to-odd-levels t]
19094 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19095 ("Editing"
19096 ["Emphasis..." org-emphasize t]
19097 ["Edit Source Example" org-edit-special t]
19098 "--"
19099 ["Footnote new/jump" org-footnote-action t]
19100 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19101 ("Archive"
19102 ["Archive (default method)" org-archive-subtree-default t]
19103 "--"
19104 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19105 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19106 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19108 "--"
19109 ("Hyperlinks"
19110 ["Store Link (Global)" org-store-link t]
19111 ["Find existing link to here" org-occur-link-in-agenda-files t]
19112 ["Insert Link" org-insert-link t]
19113 ["Follow Link" org-open-at-point t]
19114 "--"
19115 ["Next link" org-next-link t]
19116 ["Previous link" org-previous-link t]
19117 "--"
19118 ["Descriptive Links"
19119 org-toggle-link-display
19120 :style radio
19121 :selected org-descriptive-links
19123 ["Literal Links"
19124 org-toggle-link-display
19125 :style radio
19126 :selected (not org-descriptive-links)])
19127 "--"
19128 ("TODO Lists"
19129 ["TODO/DONE/-" org-todo t]
19130 ("Select keyword"
19131 ["Next keyword" org-shiftright (org-at-heading-p)]
19132 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19133 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19134 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19135 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19136 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19137 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19138 "--"
19139 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19140 :selected org-enforce-todo-dependencies :style toggle :active t]
19141 "Settings for tree at point"
19142 ["Do Children sequentially" org-toggle-ordered-property :style radio
19143 :selected (org-entry-get nil "ORDERED")
19144 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19145 ["Do Children parallel" org-toggle-ordered-property :style radio
19146 :selected (not (org-entry-get nil "ORDERED"))
19147 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19148 "--"
19149 ["Set Priority" org-priority t]
19150 ["Priority Up" org-shiftup t]
19151 ["Priority Down" org-shiftdown t]
19152 "--"
19153 ["Get news from all feeds" org-feed-update-all t]
19154 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19155 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19156 ("TAGS and Properties"
19157 ["Set Tags" org-set-tags-command t]
19158 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19159 "--"
19160 ["Set property" org-set-property t]
19161 ["Column view of properties" org-columns t]
19162 ["Insert Column View DBlock" org-insert-columns-dblock t])
19163 ("Dates and Scheduling"
19164 ["Timestamp" org-time-stamp t]
19165 ["Timestamp (inactive)" org-time-stamp-inactive t]
19166 ("Change Date"
19167 ["1 Day Later" org-shiftright t]
19168 ["1 Day Earlier" org-shiftleft t]
19169 ["1 ... Later" org-shiftup t]
19170 ["1 ... Earlier" org-shiftdown t])
19171 ["Compute Time Range" org-evaluate-time-range t]
19172 ["Schedule Item" org-schedule t]
19173 ["Deadline" org-deadline t]
19174 "--"
19175 ["Custom time format" org-toggle-time-stamp-overlays
19176 :style radio :selected org-display-custom-times]
19177 "--"
19178 ["Goto Calendar" org-goto-calendar t]
19179 ["Date from Calendar" org-date-from-calendar t]
19180 "--"
19181 ["Start/Restart Timer" org-timer-start t]
19182 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19183 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19184 ["Insert Timer String" org-timer t]
19185 ["Insert Timer Item" org-timer-item t])
19186 ("Logging work"
19187 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19188 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19189 ["Clock out" org-clock-out t]
19190 ["Clock cancel" org-clock-cancel t]
19191 "--"
19192 ["Mark as default task" org-clock-mark-default-task t]
19193 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19194 ["Goto running clock" org-clock-goto t]
19195 "--"
19196 ["Display times" org-clock-display t]
19197 ["Create clock table" org-clock-report t]
19198 "--"
19199 ["Record DONE time"
19200 (progn (setq org-log-done (not org-log-done))
19201 (message "Switching to %s will %s record a timestamp"
19202 (car org-done-keywords)
19203 (if org-log-done "automatically" "not")))
19204 :style toggle :selected org-log-done])
19205 "--"
19206 ["Agenda Command..." org-agenda t]
19207 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19208 ("File List for Agenda")
19209 ("Special views current file"
19210 ["TODO Tree" org-show-todo-tree t]
19211 ["Check Deadlines" org-check-deadlines t]
19212 ["Timeline" org-timeline t]
19213 ["Tags/Property tree" org-match-sparse-tree t])
19214 "--"
19215 ["Export/Publish..." org-export t]
19216 ("LaTeX"
19217 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19218 :selected org-cdlatex-mode]
19219 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19220 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19221 ["Modify math symbol" org-cdlatex-math-modify
19222 (org-inside-LaTeX-fragment-p)]
19223 ["Insert citation" org-reftex-citation t]
19224 "--"
19225 ["Template for BEAMER" (progn (require 'org-beamer)
19226 (org-insert-beamer-options-template)) t])
19227 "--"
19228 ("MobileOrg"
19229 ["Push Files and Views" org-mobile-push t]
19230 ["Get Captured and Flagged" org-mobile-pull t]
19231 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19232 "--"
19233 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19234 "--"
19235 ("Documentation"
19236 ["Show Version" org-version t]
19237 ["Info Documentation" org-info t])
19238 ("Customize"
19239 ["Browse Org Group" org-customize t]
19240 "--"
19241 ["Expand This Menu" org-create-customize-menu
19242 (fboundp 'customize-menu-create)])
19243 ["Send bug report" org-submit-bug-report t]
19244 "--"
19245 ("Refresh/Reload"
19246 ["Refresh setup current buffer" org-mode-restart t]
19247 ["Reload Org (after update)" org-reload t]
19248 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19251 (defun org-info (&optional node)
19252 "Read documentation for Org-mode in the info system.
19253 With optional NODE, go directly to that node."
19254 (interactive)
19255 (info (format "(org)%s" (or node ""))))
19257 ;;;###autoload
19258 (defun org-submit-bug-report ()
19259 "Submit a bug report on Org-mode via mail.
19261 Don't hesitate to report any problems or inaccurate documentation.
19263 If you don't have setup sending mail from (X)Emacs, please copy the
19264 output buffer into your mail program, as it gives us important
19265 information about your Org-mode version and configuration."
19266 (interactive)
19267 (require 'reporter)
19268 (org-load-modules-maybe)
19269 (org-require-autoloaded-modules)
19270 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19271 (reporter-submit-bug-report
19272 "emacs-orgmode@gnu.org"
19273 (org-version)
19274 (let (list)
19275 (save-window-excursion
19276 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19277 (delete-other-windows)
19278 (erase-buffer)
19279 (insert "You are about to submit a bug report to the Org-mode mailing list.
19281 We would like to add your full Org-mode and Outline configuration to the
19282 bug report. This greatly simplifies the work of the maintainer and
19283 other experts on the mailing list.
19285 HOWEVER, some variables you have customized may contain private
19286 information. The names of customers, colleagues, or friends, might
19287 appear in the form of file names, tags, todo states, or search strings.
19288 If you answer yes to the prompt, you might want to check and remove
19289 such private information before sending the email.")
19290 (add-text-properties (point-min) (point-max) '(face org-warning))
19291 (when (yes-or-no-p "Include your Org-mode configuration ")
19292 (mapatoms
19293 (lambda (v)
19294 (and (boundp v)
19295 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19296 (or (and (symbol-value v)
19297 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19298 (and
19299 (get v 'custom-type) (get v 'standard-value)
19300 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19301 (push v list)))))
19302 (kill-buffer (get-buffer "*Warn about privacy*"))
19303 list))
19304 nil nil
19305 "Remember to cover the basics, that is, what you expected to happen and
19306 what in fact did happen. You don't know how to make a good report? See
19308 http://orgmode.org/manual/Feedback.html#Feedback
19310 Your bug report will be posted to the Org-mode mailing list.
19311 ------------------------------------------------------------------------")
19312 (save-excursion
19313 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19314 (replace-match "\\1Bug: \\3 [\\2]")))))
19317 (defun org-install-agenda-files-menu ()
19318 (let ((bl (buffer-list)))
19319 (save-excursion
19320 (while bl
19321 (set-buffer (pop bl))
19322 (if (eq major-mode 'org-mode) (setq bl nil)))
19323 (when (eq major-mode 'org-mode)
19324 (easy-menu-change
19325 '("Org") "File List for Agenda"
19326 (append
19327 (list
19328 ["Edit File List" (org-edit-agenda-file-list) t]
19329 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19330 ["Remove Current File from List" org-remove-file t]
19331 ["Cycle through agenda files" org-cycle-agenda-files t]
19332 ["Occur in all agenda files" org-occur-in-agenda-files t]
19333 "--")
19334 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19336 ;;;; Documentation
19338 ;;;###autoload
19339 (defun org-require-autoloaded-modules ()
19340 (interactive)
19341 (mapc 'require
19342 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19343 org-docbook org-exp org-html org-icalendar
19344 org-id org-latex
19345 org-publish org-remember org-table
19346 org-timer org-xoxo)))
19348 ;;;###autoload
19349 (defun org-reload (&optional uncompiled)
19350 "Reload all org lisp files.
19351 With prefix arg UNCOMPILED, load the uncompiled versions."
19352 (interactive "P")
19353 (require 'find-func)
19354 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19355 (dir-org (file-name-directory (org-find-library-name "org")))
19356 (dir-org-contrib (ignore-errors
19357 (file-name-directory
19358 (org-find-library-name "org-contribdir"))))
19359 (babel-files
19360 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19361 (append (list nil "comint" "eval" "exp" "keys"
19362 "lob" "ref" "table" "tangle")
19363 (delq nil
19364 (mapcar
19365 (lambda (lang)
19366 (when (cdr lang) (symbol-name (car lang))))
19367 org-babel-load-languages)))))
19368 (files
19369 (append (directory-files dir-org t file-re)
19370 babel-files
19371 (and dir-org-contrib
19372 (directory-files dir-org-contrib t file-re))))
19373 (remove-re (concat (if (featurep 'xemacs)
19374 "org-colview" "org-colview-xemacs")
19375 "\\'")))
19376 (setq files (mapcar 'file-name-sans-extension files))
19377 (setq files (mapcar
19378 (lambda (x) (if (string-match remove-re x) nil x))
19379 files))
19380 (setq files (delq nil files))
19381 (mapc
19382 (lambda (f)
19383 (when (featurep (intern (file-name-nondirectory f)))
19384 (if (and (not uncompiled)
19385 (file-exists-p (concat f ".elc")))
19386 (load (concat f ".elc") nil nil t)
19387 (load (concat f ".el") nil nil t))))
19388 files))
19389 (org-version))
19391 ;;;###autoload
19392 (defun org-customize ()
19393 "Call the customize function with org as argument."
19394 (interactive)
19395 (org-load-modules-maybe)
19396 (org-require-autoloaded-modules)
19397 (customize-browse 'org))
19399 (defun org-create-customize-menu ()
19400 "Create a full customization menu for Org-mode, insert it into the menu."
19401 (interactive)
19402 (org-load-modules-maybe)
19403 (org-require-autoloaded-modules)
19404 (if (fboundp 'customize-menu-create)
19405 (progn
19406 (easy-menu-change
19407 '("Org") "Customize"
19408 `(["Browse Org group" org-customize t]
19409 "--"
19410 ,(customize-menu-create 'org)
19411 ["Set" Custom-set t]
19412 ["Save" Custom-save t]
19413 ["Reset to Current" Custom-reset-current t]
19414 ["Reset to Saved" Custom-reset-saved t]
19415 ["Reset to Standard Settings" Custom-reset-standard t]))
19416 (message "\"Org\"-menu now contains full customization menu"))
19417 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19419 ;;;; Miscellaneous stuff
19421 ;;; Generally useful functions
19423 (defun org-get-at-bol (property)
19424 "Get text property PROPERTY at beginning of line."
19425 (get-text-property (point-at-bol) property))
19427 (defun org-find-text-property-in-string (prop s)
19428 "Return the first non-nil value of property PROP in string S."
19429 (or (get-text-property 0 prop s)
19430 (get-text-property (or (next-single-property-change 0 prop s) 0)
19431 prop s)))
19433 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19434 "Display the given MESSAGE as a warning."
19435 (if (fboundp 'display-warning)
19436 (display-warning 'org message
19437 (if (featurep 'xemacs) 'warning :warning))
19438 (let ((buf (get-buffer-create "*Org warnings*")))
19439 (with-current-buffer buf
19440 (goto-char (point-max))
19441 (insert "Warning (Org): " message)
19442 (unless (bolp)
19443 (newline)))
19444 (display-buffer buf)
19445 (sit-for 0))))
19447 (defun org-eval (form)
19448 "Eval FORM and return result."
19449 (condition-case error
19450 (eval form)
19451 (error (format "%%![Error: %s]" error))))
19453 (defun org-in-clocktable-p ()
19454 "Check if the cursor is in a clocktable."
19455 (let ((pos (point)) start)
19456 (save-excursion
19457 (end-of-line 1)
19458 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19459 (setq start (match-beginning 0))
19460 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19461 (>= (match-end 0) pos)
19462 start))))
19464 (defun org-in-commented-line ()
19465 "Is point in a line starting with `#'?"
19466 (equal (char-after (point-at-bol)) ?#))
19468 (defun org-in-indented-comment-line ()
19469 "Is point in a line starting with `#' after some white space?"
19470 (save-excursion
19471 (save-match-data
19472 (goto-char (point-at-bol))
19473 (looking-at "[ \t]*#"))))
19475 (defun org-in-verbatim-emphasis ()
19476 (save-match-data
19477 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19479 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19480 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19481 (if (and marker (marker-buffer marker)
19482 (buffer-live-p (marker-buffer marker)))
19483 (progn
19484 (org-pop-to-buffer-same-window (marker-buffer marker))
19485 (if (or (> marker (point-max)) (< marker (point-min)))
19486 (widen))
19487 (goto-char marker)
19488 (org-show-context 'org-goto))
19489 (if bookmark
19490 (bookmark-jump bookmark)
19491 (error "Cannot find location"))))
19493 (defun org-quote-csv-field (s)
19494 "Quote field for inclusion in CSV material."
19495 (if (string-match "[\",]" s)
19496 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19499 (defun org-force-self-insert (N)
19500 "Needed to enforce self-insert under remapping."
19501 (interactive "p")
19502 (self-insert-command N))
19504 (defun org-string-width (s)
19505 "Compute width of string, ignoring invisible characters.
19506 This ignores character with invisibility property `org-link', and also
19507 characters with property `org-cwidth', because these will become invisible
19508 upon the next fontification round."
19509 (let (b l)
19510 (when (or (eq t buffer-invisibility-spec)
19511 (assq 'org-link buffer-invisibility-spec))
19512 (while (setq b (text-property-any 0 (length s)
19513 'invisible 'org-link s))
19514 (setq s (concat (substring s 0 b)
19515 (substring s (or (next-single-property-change
19516 b 'invisible s) (length s)))))))
19517 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19518 (setq s (concat (substring s 0 b)
19519 (substring s (or (next-single-property-change
19520 b 'org-cwidth s) (length s))))))
19521 (setq l (string-width s) b -1)
19522 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19523 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19526 (defun org-shorten-string (s maxlength)
19527 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19528 If the string is shorter or has length MAXLENGTH, just return the
19529 original string. If it is longer, the functions finds a space in the
19530 string, breaks this string off at that locations and adds three dots
19531 as ellipsis. Including the ellipsis, the string will not be longer
19532 than MAXLENGTH. If finding a good breaking point in the string does
19533 not work, the string is just chopped off in the middle of a word
19534 if necessary."
19535 (if (<= (length s) maxlength)
19537 (let* ((n (max (- maxlength 4) 1))
19538 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19539 (if (string-match re s)
19540 (concat (match-string 1 s) "...")
19541 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19543 (defun org-get-indentation (&optional line)
19544 "Get the indentation of the current line, interpreting tabs.
19545 When LINE is given, assume it represents a line and compute its indentation."
19546 (if line
19547 (if (string-match "^ *" (org-remove-tabs line))
19548 (match-end 0))
19549 (save-excursion
19550 (beginning-of-line 1)
19551 (skip-chars-forward " \t")
19552 (current-column))))
19554 (defun org-get-string-indentation (s)
19555 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19556 (let ((n -1) (i 0) (w tab-width) c)
19557 (catch 'exit
19558 (while (< (setq n (1+ n)) (length s))
19559 (setq c (aref s n))
19560 (cond ((= c ?\ ) (setq i (1+ i)))
19561 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19562 (t (throw 'exit t)))))
19565 (defun org-remove-tabs (s &optional width)
19566 "Replace tabulators in S with spaces.
19567 Assumes that s is a single line, starting in column 0."
19568 (setq width (or width tab-width))
19569 (while (string-match "\t" s)
19570 (setq s (replace-match
19571 (make-string
19572 (- (* width (/ (+ (match-beginning 0) width) width))
19573 (match-beginning 0)) ?\ )
19574 t t s)))
19577 (defun org-fix-indentation (line ind)
19578 "Fix indentation in LINE.
19579 IND is a cons cell with target and minimum indentation.
19580 If the current indentation in LINE is smaller than the minimum,
19581 leave it alone. If it is larger than ind, set it to the target."
19582 (let* ((l (org-remove-tabs line))
19583 (i (org-get-indentation l))
19584 (i1 (car ind)) (i2 (cdr ind)))
19585 (if (>= i i2) (setq l (substring line i2)))
19586 (if (> i1 0)
19587 (concat (make-string i1 ?\ ) l)
19588 l)))
19590 (defun org-remove-indentation (code &optional n)
19591 "Remove the maximum common indentation from the lines in CODE.
19592 N may optionally be the number of spaces to remove."
19593 (with-temp-buffer
19594 (insert code)
19595 (org-do-remove-indentation n)
19596 (buffer-string)))
19598 (defun org-do-remove-indentation (&optional n)
19599 "Remove the maximum common indentation from the buffer."
19600 (untabify (point-min) (point-max))
19601 (let ((min 10000) re)
19602 (if n
19603 (setq min n)
19604 (goto-char (point-min))
19605 (while (re-search-forward "^ *[^ \n]" nil t)
19606 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19607 (unless (or (= min 0) (= min 10000))
19608 (setq re (format "^ \\{%d\\}" min))
19609 (goto-char (point-min))
19610 (while (re-search-forward re nil t)
19611 (replace-match "")
19612 (end-of-line 1))
19613 min)))
19615 (defun org-fill-template (template alist)
19616 "Find each %key of ALIST in TEMPLATE and replace it."
19617 (let ((case-fold-search nil)
19618 entry key value)
19619 (setq alist (sort (copy-sequence alist)
19620 (lambda (a b) (< (length (car a)) (length (car b))))))
19621 (while (setq entry (pop alist))
19622 (setq template
19623 (replace-regexp-in-string
19624 (concat "%" (regexp-quote (car entry)))
19625 (cdr entry) template t t)))
19626 template))
19628 (defun org-base-buffer (buffer)
19629 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19630 (if (not buffer)
19631 buffer
19632 (or (buffer-base-buffer buffer)
19633 buffer)))
19635 (defun org-trim (s)
19636 "Remove whitespace at beginning and end of string."
19637 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19638 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19641 (defun org-wrap (string &optional width lines)
19642 "Wrap string to either a number of lines, or a width in characters.
19643 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19644 that costs. If there is a word longer than WIDTH, the text is actually
19645 wrapped to the length of that word.
19646 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19647 many lines, whatever width that takes.
19648 The return value is a list of lines, without newlines at the end."
19649 (let* ((words (org-split-string string "[ \t\n]+"))
19650 (maxword (apply 'max (mapcar 'org-string-width words)))
19651 w ll)
19652 (cond (width
19653 (org-do-wrap words (max maxword width)))
19654 (lines
19655 (setq w maxword)
19656 (setq ll (org-do-wrap words maxword))
19657 (if (<= (length ll) lines)
19659 (setq ll words)
19660 (while (> (length ll) lines)
19661 (setq w (1+ w))
19662 (setq ll (org-do-wrap words w)))
19663 ll))
19664 (t (error "Cannot wrap this")))))
19666 (defun org-do-wrap (words width)
19667 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19668 (let (lines line)
19669 (while words
19670 (setq line (pop words))
19671 (while (and words (< (+ (length line) (length (car words))) width))
19672 (setq line (concat line " " (pop words))))
19673 (setq lines (push line lines)))
19674 (nreverse lines)))
19676 (defun org-split-string (string &optional separators)
19677 "Splits STRING into substrings at SEPARATORS.
19678 No empty strings are returned if there are matches at the beginning
19679 and end of string."
19680 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19681 (start 0)
19682 notfirst
19683 (list nil))
19684 (while (and (string-match rexp string
19685 (if (and notfirst
19686 (= start (match-beginning 0))
19687 (< start (length string)))
19688 (1+ start) start))
19689 (< (match-beginning 0) (length string)))
19690 (setq notfirst t)
19691 (or (eq (match-beginning 0) 0)
19692 (and (eq (match-beginning 0) (match-end 0))
19693 (eq (match-beginning 0) start))
19694 (setq list
19695 (cons (substring string start (match-beginning 0))
19696 list)))
19697 (setq start (match-end 0)))
19698 (or (eq start (length string))
19699 (setq list
19700 (cons (substring string start)
19701 list)))
19702 (nreverse list)))
19704 (defun org-quote-vert (s)
19705 "Replace \"|\" with \"\\vert\"."
19706 (while (string-match "|" s)
19707 (setq s (replace-match "\\vert" t t s)))
19710 (defun org-uuidgen-p (s)
19711 "Is S an ID created by UUIDGEN?"
19712 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19714 (defun org-in-src-block-p nil
19715 "Whether point is in a code source block."
19716 (let (ov)
19717 (when (setq ov (overlays-at (point)))
19718 (memq 'org-block-background
19719 (overlay-properties
19720 (car ov))))))
19722 (defun org-context ()
19723 "Return a list of contexts of the current cursor position.
19724 If several contexts apply, all are returned.
19725 Each context entry is a list with a symbol naming the context, and
19726 two positions indicating start and end of the context. Possible
19727 contexts are:
19729 :headline anywhere in a headline
19730 :headline-stars on the leading stars in a headline
19731 :todo-keyword on a TODO keyword (including DONE) in a headline
19732 :tags on the TAGS in a headline
19733 :priority on the priority cookie in a headline
19734 :item on the first line of a plain list item
19735 :item-bullet on the bullet/number of a plain list item
19736 :checkbox on the checkbox in a plain list item
19737 :table in an org-mode table
19738 :table-special on a special filed in a table
19739 :table-table in a table.el table
19740 :clocktable in a clocktable
19741 :src-block in a source block
19742 :link on a hyperlink
19743 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19744 :target on a <<target>>
19745 :radio-target on a <<<radio-target>>>
19746 :latex-fragment on a LaTeX fragment
19747 :latex-preview on a LaTeX fragment with overlaid preview image
19749 This function expects the position to be visible because it uses font-lock
19750 faces as a help to recognize the following contexts: :table-special, :link,
19751 and :keyword."
19752 (let* ((f (get-text-property (point) 'face))
19753 (faces (if (listp f) f (list f)))
19754 (case-fold-search t)
19755 (p (point)) clist o)
19756 ;; First the large context
19757 (cond
19758 ((org-at-heading-p t)
19759 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19760 (when (progn
19761 (beginning-of-line 1)
19762 (looking-at org-todo-line-tags-regexp))
19763 (push (org-point-in-group p 1 :headline-stars) clist)
19764 (push (org-point-in-group p 2 :todo-keyword) clist)
19765 (push (org-point-in-group p 4 :tags) clist))
19766 (goto-char p)
19767 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19768 (if (looking-at "\\[#[A-Z0-9]\\]")
19769 (push (org-point-in-group p 0 :priority) clist)))
19771 ((org-at-item-p)
19772 (push (org-point-in-group p 2 :item-bullet) clist)
19773 (push (list :item (point-at-bol)
19774 (save-excursion (org-end-of-item) (point)))
19775 clist)
19776 (and (org-at-item-checkbox-p)
19777 (push (org-point-in-group p 0 :checkbox) clist)))
19779 ((org-at-table-p)
19780 (push (list :table (org-table-begin) (org-table-end)) clist)
19781 (if (memq 'org-formula faces)
19782 (push (list :table-special
19783 (previous-single-property-change p 'face)
19784 (next-single-property-change p 'face)) clist)))
19785 ((org-at-table-p 'any)
19786 (push (list :table-table) clist)))
19787 (goto-char p)
19789 ;; New the "medium" contexts: clocktables, source blocks
19790 (cond ((org-in-clocktable-p)
19791 (push (list :clocktable
19792 (and (or (looking-at "#\\+BEGIN: clocktable")
19793 (search-backward "#+BEGIN: clocktable" nil t))
19794 (match-beginning 0))
19795 (and (re-search-forward "#\\+END:?" nil t)
19796 (match-end 0))) clist))
19797 ((org-in-src-block-p)
19798 (push (list :src-block
19799 (and (or (looking-at "#\\+BEGIN_SRC")
19800 (search-backward "#+BEGIN_SRC" nil t))
19801 (match-beginning 0))
19802 (and (search-forward "#+END_SRC" nil t)
19803 (match-beginning 0))) clist)))
19804 (goto-char p)
19806 ;; Now the small context
19807 (cond
19808 ((org-at-timestamp-p)
19809 (push (org-point-in-group p 0 :timestamp) clist))
19810 ((memq 'org-link faces)
19811 (push (list :link
19812 (previous-single-property-change p 'face)
19813 (next-single-property-change p 'face)) clist))
19814 ((memq 'org-special-keyword faces)
19815 (push (list :keyword
19816 (previous-single-property-change p 'face)
19817 (next-single-property-change p 'face)) clist))
19818 ((org-at-target-p)
19819 (push (org-point-in-group p 0 :target) clist)
19820 (goto-char (1- (match-beginning 0)))
19821 (if (looking-at org-radio-target-regexp)
19822 (push (org-point-in-group p 0 :radio-target) clist))
19823 (goto-char p))
19824 ((setq o (car (delq nil
19825 (mapcar
19826 (lambda (x)
19827 (if (memq x org-latex-fragment-image-overlays) x))
19828 (overlays-at (point))))))
19829 (push (list :latex-fragment
19830 (overlay-start o) (overlay-end o)) clist)
19831 (push (list :latex-preview
19832 (overlay-start o) (overlay-end o)) clist))
19833 ((org-inside-LaTeX-fragment-p)
19834 ;; FIXME: positions wrong.
19835 (push (list :latex-fragment (point) (point)) clist)))
19837 (setq clist (nreverse (delq nil clist)))
19838 clist))
19840 ;; FIXME: Compare with at-regexp-p Do we need both?
19841 (defun org-in-regexp (re &optional nlines visually)
19842 "Check if point is inside a match of regexp.
19843 Normally only the current line is checked, but you can include NLINES extra
19844 lines both before and after point into the search.
19845 If VISUALLY is set, require that the cursor is not after the match but
19846 really on, so that the block visually is on the match."
19847 (catch 'exit
19848 (let ((pos (point))
19849 (eol (point-at-eol (+ 1 (or nlines 0))))
19850 (inc (if visually 1 0)))
19851 (save-excursion
19852 (beginning-of-line (- 1 (or nlines 0)))
19853 (while (re-search-forward re eol t)
19854 (if (and (<= (match-beginning 0) pos)
19855 (>= (+ inc (match-end 0)) pos))
19856 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19858 (defun org-at-regexp-p (regexp)
19859 "Is point inside a match of REGEXP in the current line?"
19860 (catch 'exit
19861 (save-excursion
19862 (let ((pos (point)) (end (point-at-eol)))
19863 (beginning-of-line 1)
19864 (while (re-search-forward regexp end t)
19865 (if (and (<= (match-beginning 0) pos)
19866 (>= (match-end 0) pos))
19867 (throw 'exit t)))
19868 nil))))
19870 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19871 "Non-nil when point is between matches of START-RE and END-RE.
19873 Also return a non-nil value when point is on one of the matches.
19875 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19876 buffer positions. Default values are the positions of headlines
19877 surrounding the point.
19879 The functions returns a cons cell whose car (resp. cdr) is the
19880 position before START-RE (resp. after END-RE)."
19881 (save-match-data
19882 (let ((pos (point))
19883 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19884 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19885 beg end)
19886 (save-excursion
19887 ;; Point is on a block when on START-RE or if START-RE can be
19888 ;; found before it...
19889 (and (or (org-at-regexp-p start-re)
19890 (re-search-backward start-re limit-up t))
19891 (setq beg (match-beginning 0))
19892 ;; ... and END-RE after it...
19893 (goto-char (match-end 0))
19894 (re-search-forward end-re limit-down t)
19895 (> (setq end (match-end 0)) pos)
19896 ;; ... without another START-RE in-between.
19897 (goto-char (match-beginning 0))
19898 (not (re-search-backward start-re (1+ beg) t))
19899 ;; Return value.
19900 (cons beg end))))))
19902 (defun org-in-block-p (names)
19903 "Non-nil when point belongs to a block whose name belongs to NAMES.
19905 NAMES is a list of strings containing names of blocks.
19907 Return first block name matched, or nil. Beware that in case of
19908 nested blocks, the returned name may not belong to the closest
19909 block from point."
19910 (save-match-data
19911 (catch 'exit
19912 (let ((case-fold-search t)
19913 (lim-up (save-excursion (outline-previous-heading)))
19914 (lim-down (save-excursion (outline-next-heading))))
19915 (mapc (lambda (name)
19916 (let ((n (regexp-quote name)))
19917 (when (org-between-regexps-p
19918 (concat "^[ \t]*#\\+begin_" n)
19919 (concat "^[ \t]*#\\+end_" n)
19920 lim-up lim-down)
19921 (throw 'exit n))))
19922 names))
19923 nil)))
19925 (defun org-occur-in-agenda-files (regexp &optional nlines)
19926 "Call `multi-occur' with buffers for all agenda files."
19927 (interactive "sOrg-files matching: \np")
19928 (let* ((files (org-agenda-files))
19929 (tnames (mapcar 'file-truename files))
19930 (extra org-agenda-text-search-extra-files)
19932 (when (eq (car extra) 'agenda-archives)
19933 (setq extra (cdr extra))
19934 (setq files (org-add-archive-files files)))
19935 (while (setq f (pop extra))
19936 (unless (member (file-truename f) tnames)
19937 (add-to-list 'files f 'append)
19938 (add-to-list 'tnames (file-truename f) 'append)))
19939 (multi-occur
19940 (mapcar (lambda (x)
19941 (with-current-buffer
19942 (or (get-file-buffer x) (find-file-noselect x))
19943 (widen)
19944 (current-buffer)))
19945 files)
19946 regexp)))
19948 (if (boundp 'occur-mode-find-occurrence-hook)
19949 ;; Emacs 23
19950 (add-hook 'occur-mode-find-occurrence-hook
19951 (lambda ()
19952 (when (eq major-mode 'org-mode)
19953 (org-reveal))))
19954 ;; Emacs 22
19955 (defadvice occur-mode-goto-occurrence
19956 (after org-occur-reveal activate)
19957 (and (eq major-mode 'org-mode) (org-reveal)))
19958 (defadvice occur-mode-goto-occurrence-other-window
19959 (after org-occur-reveal activate)
19960 (and (eq major-mode 'org-mode) (org-reveal)))
19961 (defadvice occur-mode-display-occurrence
19962 (after org-occur-reveal activate)
19963 (when (eq major-mode 'org-mode)
19964 (let ((pos (occur-mode-find-occurrence)))
19965 (with-current-buffer (marker-buffer pos)
19966 (save-excursion
19967 (goto-char pos)
19968 (org-reveal)))))))
19970 (defun org-occur-link-in-agenda-files ()
19971 "Create a link and search for it in the agendas.
19972 The link is not stored in `org-stored-links', it is just created
19973 for the search purpose."
19974 (interactive)
19975 (let ((link (condition-case nil
19976 (org-store-link nil)
19977 (error "Unable to create a link to here"))))
19978 (org-occur-in-agenda-files (regexp-quote link))))
19980 (defun org-uniquify (list)
19981 "Remove duplicate elements from LIST."
19982 (let (res)
19983 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19984 res))
19986 (defun org-delete-all (elts list)
19987 "Remove all elements in ELTS from LIST."
19988 (while elts
19989 (setq list (delete (pop elts) list)))
19990 list)
19992 (defun org-count (cl-item cl-seq)
19993 "Count the number of occurrences of ITEM in SEQ.
19994 Taken from `count' in cl-seq.el with all keyword arguments removed."
19995 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19996 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19997 (while (< cl-start cl-end)
19998 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19999 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20000 (setq cl-start (1+ cl-start)))
20001 cl-count))
20003 (defun org-remove-if (predicate seq)
20004 "Remove everything from SEQ that fulfills PREDICATE."
20005 (let (res e)
20006 (while seq
20007 (setq e (pop seq))
20008 (if (not (funcall predicate e)) (push e res)))
20009 (nreverse res)))
20011 (defun org-remove-if-not (predicate seq)
20012 "Remove everything from SEQ that does not fulfill PREDICATE."
20013 (let (res e)
20014 (while seq
20015 (setq e (pop seq))
20016 (if (funcall predicate e) (push e res)))
20017 (nreverse res)))
20019 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20020 "Reduce two-argument FUNCTION across SEQ.
20021 Taken from `reduce' in cl-seq.el with all keyword arguments but
20022 \":initial-value\" removed."
20023 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20024 (cadr (memq :initial-value cl-keys)))
20025 (cl-seq (pop cl-seq))
20026 (t (funcall cl-func)))))
20027 (while cl-seq
20028 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20029 cl-accum))
20031 (defun org-back-over-empty-lines ()
20032 "Move backwards over whitespace, to the beginning of the first empty line.
20033 Returns the number of empty lines passed."
20034 (let ((pos (point)))
20035 (if (cdr (assoc 'heading org-blank-before-new-entry))
20036 (skip-chars-backward " \t\n\r")
20037 (unless (eobp)
20038 (forward-line -1)))
20039 (beginning-of-line 2)
20040 (goto-char (min (point) pos))
20041 (count-lines (point) pos)))
20043 (defun org-skip-whitespace ()
20044 (skip-chars-forward " \t\n\r"))
20046 (defun org-point-in-group (point group &optional context)
20047 "Check if POINT is in match-group GROUP.
20048 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20049 match. If the match group does not exist or point is not inside it,
20050 return nil."
20051 (and (match-beginning group)
20052 (>= point (match-beginning group))
20053 (<= point (match-end group))
20054 (if context
20055 (list context (match-beginning group) (match-end group))
20056 t)))
20058 (defun org-switch-to-buffer-other-window (&rest args)
20059 "Switch to buffer in a second window on the current frame.
20060 In particular, do not allow pop-up frames.
20061 Returns the newly created buffer."
20062 (let (pop-up-frames special-display-buffer-names special-display-regexps
20063 special-display-function)
20064 (apply 'switch-to-buffer-other-window args)))
20066 (defun org-combine-plists (&rest plists)
20067 "Create a single property list from all plists in PLISTS.
20068 The process starts by copying the first list, and then setting properties
20069 from the other lists. Settings in the last list are the most significant
20070 ones and overrule settings in the other lists."
20071 (let ((rtn (copy-sequence (pop plists)))
20072 p v ls)
20073 (while plists
20074 (setq ls (pop plists))
20075 (while ls
20076 (setq p (pop ls) v (pop ls))
20077 (setq rtn (plist-put rtn p v))))
20078 rtn))
20080 (defun org-move-line-down (arg)
20081 "Move the current line down. With prefix argument, move it past ARG lines."
20082 (interactive "p")
20083 (let ((col (current-column))
20084 beg end pos)
20085 (beginning-of-line 1) (setq beg (point))
20086 (beginning-of-line 2) (setq end (point))
20087 (beginning-of-line (+ 1 arg))
20088 (setq pos (move-marker (make-marker) (point)))
20089 (insert (delete-and-extract-region beg end))
20090 (goto-char pos)
20091 (org-move-to-column col)))
20093 (defun org-move-line-up (arg)
20094 "Move the current line up. With prefix argument, move it past ARG lines."
20095 (interactive "p")
20096 (let ((col (current-column))
20097 beg end pos)
20098 (beginning-of-line 1) (setq beg (point))
20099 (beginning-of-line 2) (setq end (point))
20100 (beginning-of-line (- arg))
20101 (setq pos (move-marker (make-marker) (point)))
20102 (insert (delete-and-extract-region beg end))
20103 (goto-char pos)
20104 (org-move-to-column col)))
20106 (defun org-replace-escapes (string table)
20107 "Replace %-escapes in STRING with values in TABLE.
20108 TABLE is an association list with keys like \"%a\" and string values.
20109 The sequences in STRING may contain normal field width and padding information,
20110 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20111 so values can contain further %-escapes if they are define later in TABLE."
20112 (let ((tbl (copy-alist table))
20113 (case-fold-search nil)
20114 (pchg 0)
20115 e re rpl)
20116 (while (setq e (pop tbl))
20117 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20118 (when (and (cdr e) (string-match re (cdr e)))
20119 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20120 (safe "SREF"))
20121 (add-text-properties 0 3 (list 'sref sref) safe)
20122 (setcdr e (replace-match safe t t (cdr e)))))
20123 (while (string-match re string)
20124 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20125 (cdr e)))
20126 (setq string (replace-match rpl t t string))))
20127 (while (setq pchg (next-property-change pchg string))
20128 (let ((sref (get-text-property pchg 'sref string)))
20129 (when (and sref (string-match "SREF" string pchg))
20130 (setq string (replace-match sref t t string)))))
20131 string))
20133 (defun org-sublist (list start end)
20134 "Return a section of LIST, from START to END.
20135 Counting starts at 1."
20136 (let (rtn (c start))
20137 (setq list (nthcdr (1- start) list))
20138 (while (and list (<= c end))
20139 (push (pop list) rtn)
20140 (setq c (1+ c)))
20141 (nreverse rtn)))
20143 (defun org-find-base-buffer-visiting (file)
20144 "Like `find-buffer-visiting' but always return the base buffer and
20145 not an indirect buffer."
20146 (let ((buf (or (get-file-buffer file)
20147 (find-buffer-visiting file))))
20148 (if buf
20149 (or (buffer-base-buffer buf) buf)
20150 nil)))
20152 (defun org-image-file-name-regexp (&optional extensions)
20153 "Return regexp matching the file names of images.
20154 If EXTENSIONS is given, only match these."
20155 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20156 (image-file-name-regexp)
20157 (let ((image-file-name-extensions
20158 (or extensions
20159 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20160 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20161 (concat "\\."
20162 (regexp-opt (nconc (mapcar 'upcase
20163 image-file-name-extensions)
20164 image-file-name-extensions)
20166 "\\'"))))
20168 (defun org-file-image-p (file &optional extensions)
20169 "Return non-nil if FILE is an image."
20170 (save-match-data
20171 (string-match (org-image-file-name-regexp extensions) file)))
20173 (defun org-get-cursor-date ()
20174 "Return the date at cursor in as a time.
20175 This works in the calendar and in the agenda, anywhere else it just
20176 returns the current time."
20177 (let (date day defd)
20178 (cond
20179 ((eq major-mode 'calendar-mode)
20180 (setq date (calendar-cursor-to-date)
20181 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20182 ((eq major-mode 'org-agenda-mode)
20183 (setq day (get-text-property (point) 'day))
20184 (if day
20185 (setq date (calendar-gregorian-from-absolute day)
20186 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20187 (nth 2 date))))))
20188 (or defd (current-time))))
20190 (defvar org-agenda-action-marker (make-marker)
20191 "Marker pointing to the entry for the next agenda action.")
20193 (defun org-mark-entry-for-agenda-action ()
20194 "Mark the current entry as target of an agenda action.
20195 Agenda actions are actions executed from the agenda with the key `k',
20196 which make use of the date at the cursor."
20197 (interactive)
20198 (move-marker org-agenda-action-marker
20199 (save-excursion (org-back-to-heading t) (point))
20200 (current-buffer))
20201 (message
20202 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20204 (defun org-mark-subtree ()
20205 "Mark the current subtree.
20206 This puts point at the start of the current subtree, and mark at the end.
20208 If point is in an inline task, mark that task instead."
20209 (interactive)
20210 (let ((inline-task-p
20211 (and (featurep 'org-inlinetask)
20212 (org-inlinetask-in-task-p)))
20213 (beg))
20214 ;; Get beginning of subtree
20215 (cond
20216 (inline-task-p (org-inlinetask-goto-beginning))
20217 ((org-at-heading-p) (beginning-of-line))
20218 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20219 (setq beg (point))
20220 ;; Get end of it
20221 (if inline-task-p
20222 (org-inlinetask-goto-end)
20223 (org-end-of-subtree))
20224 ;; Mark zone
20225 (push-mark (point) nil t)
20226 (goto-char beg)))
20228 ;;; Paragraph filling stuff.
20229 ;; We want this to be just right, so use the full arsenal.
20231 (defun org-indent-line-function ()
20232 "Indent line depending on context."
20233 (interactive)
20234 (let* ((pos (point))
20235 (itemp (org-at-item-p))
20236 (case-fold-search t)
20237 (org-drawer-regexp (or org-drawer-regexp "\000"))
20238 (inline-task-p (and (featurep 'org-inlinetask)
20239 (org-inlinetask-in-task-p)))
20240 (inline-re (and inline-task-p
20241 (org-inlinetask-outline-regexp)))
20242 column)
20243 (beginning-of-line 1)
20244 (cond
20245 ;; Comments
20246 ((looking-at "# ") (setq column 0))
20247 ;; Headings
20248 ((looking-at org-outline-regexp) (setq column 0))
20249 ;; Included files
20250 ((looking-at "#\\+include:") (setq column 0))
20251 ;; Footnote definition
20252 ((looking-at org-footnote-definition-re) (setq column 0))
20253 ;; Literal examples
20254 ((looking-at "[ \t]*:\\( \\|$\\)")
20255 (setq column (org-get-indentation))) ; do nothing
20256 ;; Lists
20257 ((ignore-errors (goto-char (org-in-item-p)))
20258 (setq column (if itemp
20259 (org-get-indentation)
20260 (org-list-item-body-column (point))))
20261 (goto-char pos))
20262 ;; Drawers
20263 ((and (looking-at "[ \t]*:END:")
20264 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20265 (save-excursion
20266 (goto-char (1- (match-beginning 1)))
20267 (setq column (current-column))))
20268 ;; Special blocks
20269 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20270 (save-excursion
20271 (re-search-backward
20272 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20273 (setq column (org-get-indentation (match-string 0))))
20274 ((and (not (looking-at "[ \t]*#\\+begin_"))
20275 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20276 (save-excursion
20277 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20278 (setq column
20279 (cond ((equal (downcase (match-string 1)) "src")
20280 ;; src blocks: let `org-edit-src-exit' handle them
20281 (org-get-indentation))
20282 ((equal (downcase (match-string 1)) "example")
20283 (max (org-get-indentation)
20284 (org-get-indentation (match-string 0))))
20286 (org-get-indentation (match-string 0))))))
20287 ;; This line has nothing special, look at the previous relevant
20288 ;; line to compute indentation
20290 (beginning-of-line 0)
20291 (while (and (not (bobp))
20292 (not (looking-at org-drawer-regexp))
20293 ;; When point started in an inline task, do not move
20294 ;; above task starting line.
20295 (not (and inline-task-p (looking-at inline-re)))
20296 ;; Skip drawers, blocks, empty lines, verbatim,
20297 ;; comments, tables, footnotes definitions, lists,
20298 ;; inline tasks.
20299 (or (and (looking-at "[ \t]*:END:")
20300 (re-search-backward org-drawer-regexp nil t))
20301 (and (looking-at "[ \t]*#\\+end_")
20302 (re-search-backward "[ \t]*#\\+begin_"nil t))
20303 (looking-at "[ \t]*[\n:#|]")
20304 (looking-at org-footnote-definition-re)
20305 (and (ignore-errors (goto-char (org-in-item-p)))
20306 (goto-char
20307 (org-list-get-top-point (org-list-struct))))
20308 (and (not inline-task-p)
20309 (featurep 'org-inlinetask)
20310 (org-inlinetask-in-task-p)
20311 (or (org-inlinetask-goto-beginning) t))))
20312 (beginning-of-line 0))
20313 (cond
20314 ;; There was an heading above.
20315 ((looking-at "\\*+[ \t]+")
20316 (if (not org-adapt-indentation)
20317 (setq column 0)
20318 (goto-char (match-end 0))
20319 (setq column (current-column))))
20320 ;; A drawer had started and is unfinished
20321 ((looking-at org-drawer-regexp)
20322 (goto-char (1- (match-beginning 1)))
20323 (setq column (current-column)))
20324 ;; Else, nothing noticeable found: get indentation and go on.
20325 (t (setq column (org-get-indentation))))))
20326 ;; Now apply indentation and move cursor accordingly
20327 (goto-char pos)
20328 (if (<= (current-column) (current-indentation))
20329 (org-indent-line-to column)
20330 (save-excursion (org-indent-line-to column)))
20331 ;; Special polishing for properties, see `org-property-format'
20332 (setq column (current-column))
20333 (beginning-of-line 1)
20334 (if (looking-at
20335 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20336 (replace-match (concat (match-string 1)
20337 (format org-property-format
20338 (match-string 2) (match-string 3)))
20339 t t))
20340 (org-move-to-column column)))
20342 (defun org-indent-drawer ()
20343 "Indent the drawer at point."
20344 (interactive)
20345 (let ((p (point))
20346 (e (and (save-excursion (re-search-forward ":END:" nil t))
20347 (match-end 0)))
20348 (folded
20349 (save-excursion
20350 (end-of-line)
20351 (when (overlays-at (point))
20352 (member 'invisible (overlay-properties
20353 (car (overlays-at (point)))))))))
20354 (when folded (org-cycle))
20355 (indent-for-tab-command)
20356 (while (and (move-beginning-of-line 2) (< (point) e))
20357 (indent-for-tab-command))
20358 (goto-char p)
20359 (when folded (org-cycle)))
20360 (message "Drawer at point indented"))
20362 (defun org-indent-block ()
20363 "Indent the block at point."
20364 (interactive)
20365 (let ((p (point))
20366 (case-fold-search t)
20367 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20368 (match-end 0)))
20369 (folded
20370 (save-excursion
20371 (end-of-line)
20372 (when (overlays-at (point))
20373 (member 'invisible (overlay-properties
20374 (car (overlays-at (point)))))))))
20375 (when folded (org-cycle))
20376 (indent-for-tab-command)
20377 (while (and (move-beginning-of-line 2) (< (point) e))
20378 (indent-for-tab-command))
20379 (goto-char p)
20380 (when folded (org-cycle)))
20381 (message "Block at point indented"))
20383 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20384 "Variable to store copy of `adaptive-fill-regexp'.
20385 Since `adaptive-fill-regexp' is set to never match, we need to
20386 store a backup of its value before entering `org-mode' so that
20387 the functionality can be provided as a fall-back.")
20389 (defun org-set-autofill-regexps ()
20390 (interactive)
20391 ;; In the paragraph separator we include headlines, because filling
20392 ;; text in a line directly attached to a headline would otherwise
20393 ;; fill the headline as well.
20394 (org-set-local 'comment-start-skip "^#+[ \t]*")
20395 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20396 ;; The paragraph starter includes hand-formatted lists.
20397 (org-set-local
20398 'paragraph-start
20399 (concat
20400 "\f" "\\|"
20401 "[ ]*$" "\\|"
20402 org-outline-regexp "\\|"
20403 "[ \t]*#" "\\|"
20404 (org-item-re) "\\|"
20405 "[ \t]*[:|]" "\\|"
20406 "\\$\\$" "\\|"
20407 "\\\\\\(begin\\|end\\|[][]\\)"))
20408 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20409 ;; But only if the user has not turned off tables or fixed-width regions
20410 (org-set-local
20411 'auto-fill-inhibit-regexp
20412 (concat org-outline-regexp
20413 "\\|#\\+"
20414 "\\|[ \t]*" org-keyword-time-regexp
20415 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20416 (concat
20417 "\\|[ \t]*["
20418 (if org-enable-table-editor "|" "")
20419 (if org-enable-fixed-width-editor ":" "")
20420 "]"))))
20421 ;; We use our own fill-paragraph function, to make sure that tables
20422 ;; and fixed-width regions are not wrapped. That function will pass
20423 ;; through to `fill-paragraph' when appropriate.
20424 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20425 ;; Prevent auto-fill from inserting unwanted new items.
20426 (if (boundp 'fill-nobreak-predicate)
20427 (org-set-local
20428 'fill-nobreak-predicate
20429 (org-uniquify
20430 (append fill-nobreak-predicate
20431 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20432 ;; Adaptive filling: To get full control, first make sure that
20433 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20434 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20435 (org-set-local 'org-adaptive-fill-regexp-backup
20436 adaptive-fill-regexp))
20437 (org-set-local 'adaptive-fill-regexp "\000")
20438 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20439 (org-set-local 'adaptive-fill-function
20440 'org-adaptive-fill-function)
20441 (org-set-local
20442 'align-mode-rules-list
20443 '((org-in-buffer-settings
20444 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20445 (modes . '(org-mode))))))
20447 (defun org-fill-item-nobreak-p ()
20448 "Non-nil when a line break at point would insert a new item."
20449 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20451 (defun org-fill-line-break-nobreak-p ()
20452 "Non-nil when a line break at point would create an Org line break."
20453 (save-excursion
20454 (skip-chars-backward "[ \t]")
20455 (skip-chars-backward "\\\\")
20456 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20458 (defun org-fill-paragraph (&optional justify)
20459 "Re-align a table, pass through to fill-paragraph if no table."
20460 (let ((table-p (org-at-table-p))
20461 (table.el-p (org-at-table.el-p))
20462 (itemp (org-in-item-p)))
20463 (cond ((and (equal (char-after (point-at-bol)) ?*)
20464 (save-excursion (goto-char (point-at-bol))
20465 (looking-at org-outline-regexp)))
20466 t) ; skip headlines
20467 (table.el-p t) ; skip table.el tables
20468 (table-p (org-table-align) t) ; align Org tables
20469 (itemp ; align text in items
20470 (let* ((struct (save-excursion (goto-char itemp)
20471 (org-list-struct)))
20472 (parents (org-list-parents-alist struct))
20473 (children (org-list-get-children itemp struct parents))
20474 beg end prev next prefix)
20475 ;; Determine in which part of item point is: before
20476 ;; first child, after last child, between two
20477 ;; sub-lists, or simply in item if there's no child.
20478 (cond
20479 ((not children)
20480 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20481 beg itemp
20482 end (org-list-get-item-end itemp struct)))
20483 ((< (point) (setq next (car children)))
20484 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20485 beg itemp
20486 end next))
20487 ((> (point) (setq prev (car (last children))))
20488 (setq beg (org-list-get-item-end prev struct)
20489 end (org-list-get-item-end itemp struct)
20490 prefix (save-excursion
20491 (goto-char beg)
20492 (skip-chars-forward " \t")
20493 (make-string (current-column) ?\ ))))
20494 (t (catch 'exit
20495 (while (setq next (pop children))
20496 (if (> (point) next)
20497 (setq prev next)
20498 (setq beg (org-list-get-item-end prev struct)
20499 end next
20500 prefix (save-excursion
20501 (goto-char beg)
20502 (skip-chars-forward " \t")
20503 (make-string (current-column) ?\ )))
20504 (throw 'exit nil))))))
20505 ;; Use `fill-paragraph' with buffer narrowed to item
20506 ;; without any child, and with our computed PREFIX.
20507 (flet ((fill-context-prefix (from to &optional flr) prefix))
20508 (save-restriction
20509 (narrow-to-region beg end)
20510 (save-excursion (fill-paragraph justify)))) t))
20511 ;; Special case where point is not in a list but is on
20512 ;; a paragraph adjacent to a list: make sure this paragraph
20513 ;; doesn't get merged with the end of the list by narrowing
20514 ;; buffer first.
20515 ((save-excursion (forward-paragraph -1)
20516 (setq itemp (org-in-item-p)))
20517 (let ((struct (save-excursion (goto-char itemp)
20518 (org-list-struct))))
20519 (save-restriction
20520 (narrow-to-region (org-list-get-bottom-point struct)
20521 (save-excursion (forward-paragraph 1)
20522 (point)))
20523 (fill-paragraph justify) t)))
20524 ;; Don't fill schedule/deadline line before a paragraph
20525 ((save-excursion (forward-paragraph -1)
20526 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20527 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$"))))
20528 (save-restriction
20529 (narrow-to-region (1+ (match-end 0))
20530 (save-excursion (forward-paragraph 1) (point)))
20531 (fill-paragraph justify) t))
20532 ;; Else simply call `fill-paragraph'.
20533 (t nil))))
20535 ;; For reference, this is the default value of adaptive-fill-regexp
20536 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20538 (defun org-adaptive-fill-function ()
20539 "Return a fill prefix for org-mode files."
20540 (let (itemp)
20541 (save-excursion
20542 (cond
20543 ;; Comment line
20544 ((looking-at "#[ \t]+")
20545 (match-string-no-properties 0))
20546 ;; Plain list item
20547 ((org-at-item-p)
20548 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20549 ;; Point is in a list after `backward-paragraph': original
20550 ;; point wasn't in the list, or filling would have been taken
20551 ;; care of by `org-auto-fill-function', but the list and the
20552 ;; real paragraph are not separated by a blank line. Thus, move
20553 ;; point after the list to go back to real paragraph and
20554 ;; determine fill-prefix.
20555 ((setq itemp (org-in-item-p))
20556 (goto-char itemp)
20557 (let* ((struct (org-list-struct))
20558 (bottom (org-list-get-bottom-point struct)))
20559 (goto-char bottom)
20560 (make-string (org-get-indentation) ?\ )))
20561 ;; Other text
20562 ((looking-at org-adaptive-fill-regexp-backup)
20563 (match-string-no-properties 0))))))
20565 (defun org-auto-fill-function ()
20566 "Auto-fill function."
20567 (let (itemp prefix)
20568 ;; When in a list, compute an appropriate fill-prefix and make
20569 ;; sure it will be used by `do-auto-fill'.
20570 (if (setq itemp (org-in-item-p))
20571 (progn
20572 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20573 (flet ((fill-context-prefix (from to &optional flr) prefix))
20574 (do-auto-fill)))
20575 ;; Else just use `do-auto-fill'.
20576 (do-auto-fill))))
20578 ;;; Other stuff.
20580 (defun org-toggle-fixed-width-section (arg)
20581 "Toggle the fixed-width export.
20582 If there is no active region, the QUOTE keyword at the current headline is
20583 inserted or removed. When present, it causes the text between this headline
20584 and the next to be exported as fixed-width text, and unmodified.
20585 If there is an active region, this command adds or removes a colon as the
20586 first character of this line. If the first character of a line is a colon,
20587 this line is also exported in fixed-width font."
20588 (interactive "P")
20589 (let* ((cc 0)
20590 (regionp (org-region-active-p))
20591 (beg (if regionp (region-beginning) (point)))
20592 (end (if regionp (region-end)))
20593 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20594 (case-fold-search nil)
20595 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20596 off)
20597 (if regionp
20598 (save-excursion
20599 (goto-char beg)
20600 (setq cc (current-column))
20601 (beginning-of-line 1)
20602 (setq off (looking-at re))
20603 (while (> nlines 0)
20604 (setq nlines (1- nlines))
20605 (beginning-of-line 1)
20606 (cond
20607 (arg
20608 (org-move-to-column cc t)
20609 (insert ": \n")
20610 (forward-line -1))
20611 ((and off (looking-at re))
20612 (replace-match "" t t nil 1))
20613 ((not off) (org-move-to-column cc t) (insert ": ")))
20614 (forward-line 1)))
20615 (save-excursion
20616 (org-back-to-heading)
20617 (cond
20618 ((looking-at (format org-heading-keyword-regexp-format
20619 org-quote-string))
20620 (goto-char (match-end 1))
20621 (looking-at (concat " +" org-quote-string))
20622 (replace-match "" t t)
20623 (when (eolp) (insert " ")))
20624 ((looking-at org-outline-regexp)
20625 (goto-char (match-end 0))
20626 (insert org-quote-string " ")))))))
20628 (defun org-reftex-citation ()
20629 "Use reftex-citation to insert a citation into the buffer.
20630 This looks for a line like
20632 #+BIBLIOGRAPHY: foo plain option:-d
20634 and derives from it that foo.bib is the bibliography file relevant
20635 for this document. It then installs the necessary environment for RefTeX
20636 to work in this buffer and calls `reftex-citation' to insert a citation
20637 into the buffer.
20639 Export of such citations to both LaTeX and HTML is handled by the contributed
20640 package org-exp-bibtex by Taru Karttunen."
20641 (interactive)
20642 (let ((reftex-docstruct-symbol 'rds)
20643 (reftex-cite-format "\\cite{%l}")
20644 rds bib)
20645 (save-excursion
20646 (save-restriction
20647 (widen)
20648 (let ((case-fold-search t)
20649 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20650 (if (not (save-excursion
20651 (or (re-search-forward re nil t)
20652 (re-search-backward re nil t))))
20653 (error "No bibliography defined in file")
20654 (setq bib (concat (match-string 1) ".bib")
20655 rds (list (list 'bib bib)))))))
20656 (call-interactively 'reftex-citation)))
20658 ;;;; Functions extending outline functionality
20660 (defun org-beginning-of-line (&optional arg)
20661 "Go to the beginning of the current line. If that is invisible, continue
20662 to a visible line beginning. This makes the function of C-a more intuitive.
20663 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20664 first attempt, and only move to after the tags when the cursor is already
20665 beyond the end of the headline."
20666 (interactive "P")
20667 (let ((pos (point))
20668 (special (if (consp org-special-ctrl-a/e)
20669 (car org-special-ctrl-a/e)
20670 org-special-ctrl-a/e))
20671 refpos)
20672 (if (org-bound-and-true-p line-move-visual)
20673 (beginning-of-visual-line 1)
20674 (beginning-of-line 1))
20675 (if (and arg (fboundp 'move-beginning-of-line))
20676 (call-interactively 'move-beginning-of-line)
20677 (if (bobp)
20679 (backward-char 1)
20680 (if (org-truely-invisible-p)
20681 (while (and (not (bobp)) (org-truely-invisible-p))
20682 (backward-char 1)
20683 (beginning-of-line 1))
20684 (forward-char 1))))
20685 (when special
20686 (cond
20687 ((and (looking-at org-complex-heading-regexp)
20688 (= (char-after (match-end 1)) ?\ ))
20689 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20690 (point-at-eol)))
20691 (goto-char
20692 (if (eq special t)
20693 (cond ((> pos refpos) refpos)
20694 ((= pos (point)) refpos)
20695 (t (point)))
20696 (cond ((> pos (point)) (point))
20697 ((not (eq last-command this-command)) (point))
20698 (t refpos)))))
20699 ((org-at-item-p)
20700 ;; Being at an item and not looking at an the item means point
20701 ;; was previously moved to beginning of a visual line, which
20702 ;; doesn't contain the item. Therefore, do nothing special,
20703 ;; just stay here.
20704 (when (looking-at org-list-full-item-re)
20705 ;; Set special position at first white space character after
20706 ;; bullet, and check-box, if any.
20707 (let ((after-bullet
20708 (let ((box (match-end 3)))
20709 (if (not box) (match-end 1)
20710 (let ((after (char-after box)))
20711 (if (and after (= after ? )) (1+ box) box))))))
20712 ;; Special case: Move point to special position when
20713 ;; currently after it or at beginning of line.
20714 (if (eq special t)
20715 (when (or (> pos after-bullet) (= (point) pos))
20716 (goto-char after-bullet))
20717 ;; Reversed case: Move point to special position when
20718 ;; point was already at beginning of line and command is
20719 ;; repeated.
20720 (when (and (= (point) pos) (eq last-command this-command))
20721 (goto-char after-bullet))))))))
20722 (org-no-warnings
20723 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20725 (defun org-end-of-line (&optional arg)
20726 "Go to the end of the line.
20727 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20728 first attempt, and only move to after the tags when the cursor is already
20729 beyond the end of the headline."
20730 (interactive "P")
20731 (let ((special (if (consp org-special-ctrl-a/e)
20732 (cdr org-special-ctrl-a/e)
20733 org-special-ctrl-a/e)))
20734 (cond
20735 ((or (not special) arg
20736 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20737 (call-interactively
20738 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20739 ((fboundp 'move-end-of-line) 'move-end-of-line)
20740 (t 'end-of-line))))
20741 ((org-at-heading-p)
20742 (let ((pos (point)))
20743 (beginning-of-line 1)
20744 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20745 (if (eq special t)
20746 (if (or (< pos (match-beginning 1))
20747 (= pos (match-end 0)))
20748 (goto-char (match-beginning 1))
20749 (goto-char (match-end 0)))
20750 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20751 (goto-char (match-end 0))
20752 (goto-char (match-beginning 1))))
20753 (call-interactively (if (fboundp 'move-end-of-line)
20754 'move-end-of-line
20755 'end-of-line)))))
20756 ((org-at-drawer-p)
20757 (move-end-of-line 1)
20758 (when (overlays-at (1- (point))) (backward-char 1)))
20759 ;; At an item: Move before any hidden text.
20760 (t (call-interactively
20761 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20762 ((fboundp 'move-end-of-line) 'move-end-of-line)
20763 (t 'end-of-line)))))
20764 (org-no-warnings
20765 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20767 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20768 (define-key org-mode-map "\C-e" 'org-end-of-line)
20770 (defun org-backward-sentence (&optional arg)
20771 "Go to beginning of sentence, or beginning of table field.
20772 This will call `backward-sentence' or `org-table-beginning-of-field',
20773 depending on context."
20774 (interactive "P")
20775 (cond
20776 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20777 (t (call-interactively 'backward-sentence))))
20779 (defun org-forward-sentence (&optional arg)
20780 "Go to end of sentence, or end of table field.
20781 This will call `forward-sentence' or `org-table-end-of-field',
20782 depending on context."
20783 (interactive "P")
20784 (cond
20785 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20786 (t (call-interactively 'forward-sentence))))
20788 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20789 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20791 (defun org-kill-line (&optional arg)
20792 "Kill line, to tags or end of line."
20793 (interactive "P")
20794 (cond
20795 ((or (not org-special-ctrl-k)
20796 (bolp)
20797 (not (org-at-heading-p)))
20798 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20799 org-ctrl-k-protect-subtree)
20800 (if (or (eq org-ctrl-k-protect-subtree 'error)
20801 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20802 (error "C-k aborted - would kill hidden subtree")))
20803 (call-interactively
20804 (if visual-line-mode 'kill-visual-line 'kill-line)))
20805 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20806 (kill-region (point) (match-beginning 1))
20807 (org-set-tags nil t))
20808 (t (kill-region (point) (point-at-eol)))))
20810 (define-key org-mode-map "\C-k" 'org-kill-line)
20812 (defun org-yank (&optional arg)
20813 "Yank. If the kill is a subtree, treat it specially.
20814 This command will look at the current kill and check if is a single
20815 subtree, or a series of subtrees[1]. If it passes the test, and if the
20816 cursor is at the beginning of a line or after the stars of a currently
20817 empty headline, then the yank is handled specially. How exactly depends
20818 on the value of the following variables, both set by default.
20820 org-yank-folded-subtrees
20821 When set, the subtree(s) will be folded after insertion, but only
20822 if doing so would now swallow text after the yanked text.
20824 org-yank-adjusted-subtrees
20825 When set, the subtree will be promoted or demoted in order to
20826 fit into the local outline tree structure, which means that the level
20827 will be adjusted so that it becomes the smaller one of the two
20828 *visible* surrounding headings.
20830 Any prefix to this command will cause `yank' to be called directly with
20831 no special treatment. In particular, a simple \\[universal-argument] prefix \
20832 will just
20833 plainly yank the text as it is.
20835 \[1] The test checks if the first non-white line is a heading
20836 and if there are no other headings with fewer stars."
20837 (interactive "P")
20838 (org-yank-generic 'yank arg))
20840 (defun org-yank-generic (command arg)
20841 "Perform some yank-like command.
20843 This function implements the behavior described in the `org-yank'
20844 documentation. However, it has been generalized to work for any
20845 interactive command with similar behavior."
20847 ;; pretend to be command COMMAND
20848 (setq this-command command)
20850 (if arg
20851 (call-interactively command)
20853 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20854 (and (org-kill-is-subtree-p)
20855 (or (bolp)
20856 (and (looking-at "[ \t]*$")
20857 (string-match
20858 "\\`\\*+\\'"
20859 (buffer-substring (point-at-bol) (point)))))))
20860 swallowp)
20861 (cond
20862 ((and subtreep org-yank-folded-subtrees)
20863 (let ((beg (point))
20864 end)
20865 (if (and subtreep org-yank-adjusted-subtrees)
20866 (org-paste-subtree nil nil 'for-yank)
20867 (call-interactively command))
20869 (setq end (point))
20870 (goto-char beg)
20871 (when (and (bolp) subtreep
20872 (not (setq swallowp
20873 (org-yank-folding-would-swallow-text beg end))))
20874 (org-with-limited-levels
20875 (or (looking-at org-outline-regexp)
20876 (re-search-forward org-outline-regexp-bol end t))
20877 (while (and (< (point) end) (looking-at org-outline-regexp))
20878 (hide-subtree)
20879 (org-cycle-show-empty-lines 'folded)
20880 (condition-case nil
20881 (outline-forward-same-level 1)
20882 (error (goto-char end))))))
20883 (when swallowp
20884 (message
20885 "Inserted text not folded because that would swallow text"))
20887 (goto-char end)
20888 (skip-chars-forward " \t\n\r")
20889 (beginning-of-line 1)
20890 (push-mark beg 'nomsg)))
20891 ((and subtreep org-yank-adjusted-subtrees)
20892 (let ((beg (point-at-bol)))
20893 (org-paste-subtree nil nil 'for-yank)
20894 (push-mark beg 'nomsg)))
20896 (call-interactively command))))))
20898 (defun org-yank-folding-would-swallow-text (beg end)
20899 "Would hide-subtree at BEG swallow any text after END?"
20900 (let (level)
20901 (org-with-limited-levels
20902 (save-excursion
20903 (goto-char beg)
20904 (when (or (looking-at org-outline-regexp)
20905 (re-search-forward org-outline-regexp-bol end t))
20906 (setq level (org-outline-level)))
20907 (goto-char end)
20908 (skip-chars-forward " \t\r\n\v\f")
20909 (if (or (eobp)
20910 (and (bolp) (looking-at org-outline-regexp)
20911 (<= (org-outline-level) level)))
20912 nil ; Nothing would be swallowed
20913 t))))) ; something would swallow
20915 (define-key org-mode-map "\C-y" 'org-yank)
20917 (defun org-truely-invisible-p ()
20918 "Check if point is at a character currently not visible.
20919 This version does not only check the character property, but also
20920 `visible-mode'."
20921 ;; Early versions of noutline don't have `outline-invisible-p'.
20922 (if (org-bound-and-true-p visible-mode)
20924 (outline-invisible-p)))
20926 (defun org-invisible-p2 ()
20927 "Check if point is at a character currently not visible."
20928 (save-excursion
20929 (if (and (eolp) (not (bobp))) (backward-char 1))
20930 ;; Early versions of noutline don't have `outline-invisible-p'.
20931 (outline-invisible-p)))
20933 (defun org-back-to-heading (&optional invisible-ok)
20934 "Call `outline-back-to-heading', but provide a better error message."
20935 (condition-case nil
20936 (outline-back-to-heading invisible-ok)
20937 (error (error "Before first headline at position %d in buffer %s"
20938 (point) (current-buffer)))))
20940 (defun org-beginning-of-defun ()
20941 "Go to the beginning of the subtree, i.e. back to the heading."
20942 (org-back-to-heading))
20943 (defun org-end-of-defun ()
20944 "Go to the end of the subtree."
20945 (org-end-of-subtree nil t))
20947 (defun org-before-first-heading-p ()
20948 "Before first heading?"
20949 (save-excursion
20950 (end-of-line)
20951 (null (re-search-backward org-outline-regexp-bol nil t))))
20953 (defun org-at-heading-p (&optional ignored)
20954 (outline-on-heading-p t))
20955 ;; Compatibility alias with Org versions < 7.8.03
20956 (defalias 'org-on-heading-p 'org-at-heading-p)
20958 (defun org-at-drawer-p nil
20959 "Is cursor at a drawer keyword?"
20960 (save-excursion
20961 (move-beginning-of-line 1)
20962 (looking-at org-drawer-regexp)))
20964 (defun org-at-block-p nil
20965 "Is cursor at a block keyword?"
20966 (save-excursion
20967 (move-beginning-of-line 1)
20968 (looking-at org-block-regexp)))
20970 (defun org-point-at-end-of-empty-headline ()
20971 "If point is at the end of an empty headline, return t, else nil.
20972 If the heading only contains a TODO keyword, it is still still considered
20973 empty."
20974 (and (looking-at "[ \t]*$")
20975 (save-excursion
20976 (beginning-of-line 1)
20977 (let ((case-fold-search nil))
20978 (looking-at org-todo-line-regexp)))
20979 (string= (match-string 3) "")))
20981 (defun org-at-heading-or-item-p ()
20982 (or (org-at-heading-p) (org-at-item-p)))
20984 (defun org-at-target-p ()
20985 (or (org-in-regexp org-radio-target-regexp)
20986 (org-in-regexp org-target-regexp)))
20987 ;; Compatibility alias with Org versions < 7.8.03
20988 (defalias 'org-on-target-p 'org-at-target-p)
20990 (defun org-up-heading-all (arg)
20991 "Move to the heading line of which the present line is a subheading.
20992 This function considers both visible and invisible heading lines.
20993 With argument, move up ARG levels."
20994 (if (fboundp 'outline-up-heading-all)
20995 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20996 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20998 (defun org-up-heading-safe ()
20999 "Move to the heading line of which the present line is a subheading.
21000 This version will not throw an error. It will return the level of the
21001 headline found, or nil if no higher level is found.
21003 Also, this function will be a lot faster than `outline-up-heading',
21004 because it relies on stars being the outline starters. This can really
21005 make a significant difference in outlines with very many siblings."
21006 (let (start-level re)
21007 (org-back-to-heading t)
21008 (setq start-level (funcall outline-level))
21009 (if (equal start-level 1)
21011 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21012 (if (re-search-backward re nil t)
21013 (funcall outline-level)))))
21015 (defun org-first-sibling-p ()
21016 "Is this heading the first child of its parents?"
21017 (interactive)
21018 (let ((re org-outline-regexp-bol)
21019 level l)
21020 (unless (org-at-heading-p t)
21021 (error "Not at a heading"))
21022 (setq level (funcall outline-level))
21023 (save-excursion
21024 (if (not (re-search-backward re nil t))
21026 (setq l (funcall outline-level))
21027 (< l level)))))
21029 (defun org-goto-sibling (&optional previous)
21030 "Goto the next sibling, even if it is invisible.
21031 When PREVIOUS is set, go to the previous sibling instead. Returns t
21032 when a sibling was found. When none is found, return nil and don't
21033 move point."
21034 (let ((fun (if previous 're-search-backward 're-search-forward))
21035 (pos (point))
21036 (re org-outline-regexp-bol)
21037 level l)
21038 (when (condition-case nil (org-back-to-heading t) (error nil))
21039 (setq level (funcall outline-level))
21040 (catch 'exit
21041 (or previous (forward-char 1))
21042 (while (funcall fun re nil t)
21043 (setq l (funcall outline-level))
21044 (when (< l level) (goto-char pos) (throw 'exit nil))
21045 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21046 (goto-char pos)
21047 nil))))
21049 (defun org-show-siblings ()
21050 "Show all siblings of the current headline."
21051 (save-excursion
21052 (while (org-goto-sibling) (org-flag-heading nil)))
21053 (save-excursion
21054 (while (org-goto-sibling 'previous)
21055 (org-flag-heading nil))))
21057 (defun org-goto-first-child ()
21058 "Goto the first child, even if it is invisible.
21059 Return t when a child was found. Otherwise don't move point and
21060 return nil."
21061 (let (level (pos (point)) (re org-outline-regexp-bol))
21062 (when (condition-case nil (org-back-to-heading t) (error nil))
21063 (setq level (outline-level))
21064 (forward-char 1)
21065 (if (and (re-search-forward re nil t) (> (outline-level) level))
21066 (progn (goto-char (match-beginning 0)) t)
21067 (goto-char pos) nil))))
21069 (defun org-show-hidden-entry ()
21070 "Show an entry where even the heading is hidden."
21071 (save-excursion
21072 (org-show-entry)))
21074 (defun org-flag-heading (flag &optional entry)
21075 "Flag the current heading. FLAG non-nil means make invisible.
21076 When ENTRY is non-nil, show the entire entry."
21077 (save-excursion
21078 (org-back-to-heading t)
21079 ;; Check if we should show the entire entry
21080 (if entry
21081 (progn
21082 (org-show-entry)
21083 (save-excursion
21084 (and (outline-next-heading)
21085 (org-flag-heading nil))))
21086 (outline-flag-region (max (point-min) (1- (point)))
21087 (save-excursion (outline-end-of-heading) (point))
21088 flag))))
21090 (defun org-get-next-sibling ()
21091 "Move to next heading of the same level, and return point.
21092 If there is no such heading, return nil.
21093 This is like outline-next-sibling, but invisible headings are ok."
21094 (let ((level (funcall outline-level)))
21095 (outline-next-heading)
21096 (while (and (not (eobp)) (> (funcall outline-level) level))
21097 (outline-next-heading))
21098 (if (or (eobp) (< (funcall outline-level) level))
21100 (point))))
21102 (defun org-get-last-sibling ()
21103 "Move to previous heading of the same level, and return point.
21104 If there is no such heading, return nil."
21105 (let ((opoint (point))
21106 (level (funcall outline-level)))
21107 (outline-previous-heading)
21108 (when (and (/= (point) opoint) (outline-on-heading-p t))
21109 (while (and (> (funcall outline-level) level)
21110 (not (bobp)))
21111 (outline-previous-heading))
21112 (if (< (funcall outline-level) level)
21114 (point)))))
21116 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21117 ;; This contains an exact copy of the original function, but it uses
21118 ;; `org-back-to-heading', to make it work also in invisible
21119 ;; trees. And is uses an invisible-OK argument.
21120 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21121 ;; Furthermore, when used inside Org, finding the end of a large subtree
21122 ;; with many children and grandchildren etc, this can be much faster
21123 ;; than the outline version.
21124 (org-back-to-heading invisible-OK)
21125 (let ((first t)
21126 (level (funcall outline-level)))
21127 (if (and (eq major-mode 'org-mode) (< level 1000))
21128 ;; A true heading (not a plain list item), in Org-mode
21129 ;; This means we can easily find the end by looking
21130 ;; only for the right number of stars. Using a regexp to do
21131 ;; this is so much faster than using a Lisp loop.
21132 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21133 (forward-char 1)
21134 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21135 ;; something else, do it the slow way
21136 (while (and (not (eobp))
21137 (or first (> (funcall outline-level) level)))
21138 (setq first nil)
21139 (outline-next-heading)))
21140 (unless to-heading
21141 (if (memq (preceding-char) '(?\n ?\^M))
21142 (progn
21143 ;; Go to end of line before heading
21144 (forward-char -1)
21145 (if (memq (preceding-char) '(?\n ?\^M))
21146 ;; leave blank line before heading
21147 (forward-char -1))))))
21148 (point))
21150 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21151 "Use Org version in org-mode, for dramatic speed-up."
21152 (if (eq major-mode 'org-mode)
21153 (progn
21154 (org-end-of-subtree nil t)
21155 (unless (eobp) (backward-char 1)))
21156 ad-do-it))
21158 (defun org-end-of-meta-data-and-drawers ()
21159 "Jump to the first text after meta data and drawers in the current entry.
21160 This will move over empty lines, lines with planning time stamps,
21161 clocking lines, and drawers."
21162 (org-back-to-heading t)
21163 (let ((end (save-excursion (outline-next-heading) (point)))
21164 (re (concat "\\(" org-drawer-regexp "\\)"
21165 "\\|" "[ \t]*" org-keyword-time-regexp)))
21166 (forward-line 1)
21167 (while (re-search-forward re end t)
21168 (if (not (match-end 1))
21169 ;; empty or planning line
21170 (forward-line 1)
21171 ;; a drawer, find the end
21172 (re-search-forward "^[ \t]*:END:" end 'move)
21173 (forward-line 1)))
21174 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21175 (point)))
21177 (defun org-forward-same-level (arg &optional invisible-ok)
21178 "Move forward to the arg'th subheading at same level as this one.
21179 Stop at the first and last subheadings of a superior heading.
21180 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21181 it wil also look at invisible ones."
21182 (interactive "p")
21183 (org-back-to-heading invisible-ok)
21184 (org-at-heading-p)
21185 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21186 (re (format "^\\*\\{1,%d\\} " level))
21188 (forward-char 1)
21189 (while (> arg 0)
21190 (while (and (re-search-forward re nil 'move)
21191 (setq l (- (match-end 0) (match-beginning 0) 1))
21192 (= l level)
21193 (not invisible-ok)
21194 (progn (backward-char 1) (outline-invisible-p)))
21195 (if (< l level) (setq arg 1)))
21196 (setq arg (1- arg)))
21197 (beginning-of-line 1)))
21199 (defun org-backward-same-level (arg &optional invisible-ok)
21200 "Move backward to the arg'th subheading at same level as this one.
21201 Stop at the first and last subheadings of a superior heading."
21202 (interactive "p")
21203 (org-back-to-heading)
21204 (org-at-heading-p)
21205 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21206 (re (format "^\\*\\{1,%d\\} " level))
21208 (while (> arg 0)
21209 (while (and (re-search-backward re nil 'move)
21210 (setq l (- (match-end 0) (match-beginning 0) 1))
21211 (= l level)
21212 (not invisible-ok)
21213 (outline-invisible-p))
21214 (if (< l level) (setq arg 1)))
21215 (setq arg (1- arg)))))
21217 (defun org-show-subtree ()
21218 "Show everything after this heading at deeper levels."
21219 (interactive)
21220 (outline-flag-region
21221 (point)
21222 (save-excursion
21223 (org-end-of-subtree t t))
21224 nil))
21226 (defun org-show-entry ()
21227 "Show the body directly following this heading.
21228 Show the heading too, if it is currently invisible."
21229 (interactive)
21230 (save-excursion
21231 (condition-case nil
21232 (progn
21233 (org-back-to-heading t)
21234 (outline-flag-region
21235 (max (point-min) (1- (point)))
21236 (save-excursion
21237 (if (re-search-forward
21238 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21239 (match-beginning 1)
21240 (point-max)))
21241 nil)
21242 (org-cycle-hide-drawers 'children))
21243 (error nil))))
21245 (defun org-make-options-regexp (kwds &optional extra)
21246 "Make a regular expression for keyword lines."
21247 (concat
21249 "#?[ \t]*\\+\\("
21250 (mapconcat 'regexp-quote kwds "\\|")
21251 (if extra (concat "\\|" extra))
21252 "\\):[ \t]*"
21253 "\\(.*\\)"))
21255 ;; Make isearch reveal the necessary context
21256 (defun org-isearch-end ()
21257 "Reveal context after isearch exits."
21258 (when isearch-success ; only if search was successful
21259 (if (featurep 'xemacs)
21260 ;; Under XEmacs, the hook is run in the correct place,
21261 ;; we directly show the context.
21262 (org-show-context 'isearch)
21263 ;; In Emacs the hook runs *before* restoring the overlays.
21264 ;; So we have to use a one-time post-command-hook to do this.
21265 ;; (Emacs 22 has a special variable, see function `org-mode')
21266 (unless (and (boundp 'isearch-mode-end-hook-quit)
21267 isearch-mode-end-hook-quit)
21268 ;; Only when the isearch was not quitted.
21269 (org-add-hook 'post-command-hook 'org-isearch-post-command
21270 'append 'local)))))
21272 (defun org-isearch-post-command ()
21273 "Remove self from hook, and show context."
21274 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21275 (org-show-context 'isearch))
21278 ;;;; Integration with and fixes for other packages
21280 ;;; Imenu support
21282 (defvar org-imenu-markers nil
21283 "All markers currently used by Imenu.")
21284 (make-variable-buffer-local 'org-imenu-markers)
21286 (defun org-imenu-new-marker (&optional pos)
21287 "Return a new marker for use by Imenu, and remember the marker."
21288 (let ((m (make-marker)))
21289 (move-marker m (or pos (point)))
21290 (push m org-imenu-markers)
21293 (defun org-imenu-get-tree ()
21294 "Produce the index for Imenu."
21295 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21296 (setq org-imenu-markers nil)
21297 (let* ((n org-imenu-depth)
21298 (re (concat "^" (org-get-limited-outline-regexp)))
21299 (subs (make-vector (1+ n) nil))
21300 (last-level 0)
21301 m level head)
21302 (save-excursion
21303 (save-restriction
21304 (widen)
21305 (goto-char (point-max))
21306 (while (re-search-backward re nil t)
21307 (setq level (org-reduced-level (funcall outline-level)))
21308 (when (and (<= level n)
21309 (looking-at org-complex-heading-regexp))
21310 (setq head (org-link-display-format
21311 (org-match-string-no-properties 4))
21312 m (org-imenu-new-marker))
21313 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21314 (if (>= level last-level)
21315 (push (cons head m) (aref subs level))
21316 (push (cons head (aref subs (1+ level))) (aref subs level))
21317 (loop for i from (1+ level) to n do (aset subs i nil)))
21318 (setq last-level level)))))
21319 (aref subs 1)))
21321 (eval-after-load "imenu"
21322 '(progn
21323 (add-hook 'imenu-after-jump-hook
21324 (lambda ()
21325 (if (eq major-mode 'org-mode)
21326 (org-show-context 'org-goto))))))
21328 (defun org-link-display-format (link)
21329 "Replace a link with either the description, or the link target
21330 if no description is present"
21331 (save-match-data
21332 (if (string-match org-bracket-link-analytic-regexp link)
21333 (replace-match (if (match-end 5)
21334 (match-string 5 link)
21335 (concat (match-string 1 link)
21336 (match-string 3 link)))
21337 nil t link)
21338 link)))
21340 (defun org-toggle-link-display ()
21341 "Toggle the literal or descriptive display of links."
21342 (interactive)
21343 (if org-descriptive-links
21344 (progn (org-remove-from-invisibility-spec '(org-link))
21345 (org-restart-font-lock)
21346 (setq org-descriptive-links nil))
21347 (progn (add-to-invisibility-spec '(org-link))
21348 (org-restart-font-lock)
21349 (setq org-descriptive-links t))))
21351 ;; Speedbar support
21353 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21354 "Overlay marking the agenda restriction line in speedbar.")
21355 (overlay-put org-speedbar-restriction-lock-overlay
21356 'face 'org-agenda-restriction-lock)
21357 (overlay-put org-speedbar-restriction-lock-overlay
21358 'help-echo "Agendas are currently limited to this item.")
21359 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21361 (defun org-speedbar-set-agenda-restriction ()
21362 "Restrict future agenda commands to the location at point in speedbar.
21363 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21364 (interactive)
21365 (require 'org-agenda)
21366 (let (p m tp np dir txt)
21367 (cond
21368 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21369 'org-imenu t))
21370 (setq m (get-text-property p 'org-imenu-marker))
21371 (with-current-buffer (marker-buffer m)
21372 (goto-char m)
21373 (org-agenda-set-restriction-lock 'subtree)))
21374 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21375 'speedbar-function 'speedbar-find-file))
21376 (setq tp (previous-single-property-change
21377 (1+ p) 'speedbar-function)
21378 np (next-single-property-change
21379 tp 'speedbar-function)
21380 dir (speedbar-line-directory)
21381 txt (buffer-substring-no-properties (or tp (point-min))
21382 (or np (point-max))))
21383 (with-current-buffer (find-file-noselect
21384 (let ((default-directory dir))
21385 (expand-file-name txt)))
21386 (unless (eq major-mode 'org-mode)
21387 (error "Cannot restrict to non-Org-mode file"))
21388 (org-agenda-set-restriction-lock 'file)))
21389 (t (error "Don't know how to restrict Org-mode's agenda")))
21390 (move-overlay org-speedbar-restriction-lock-overlay
21391 (point-at-bol) (point-at-eol))
21392 (setq current-prefix-arg nil)
21393 (org-agenda-maybe-redo)))
21395 (eval-after-load "speedbar"
21396 '(progn
21397 (speedbar-add-supported-extension ".org")
21398 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21399 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21400 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21401 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21402 (add-hook 'speedbar-visiting-tag-hook
21403 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21405 ;;; Fixes and Hacks for problems with other packages
21407 ;; Make flyspell not check words in links, to not mess up our keymap
21408 (defun org-mode-flyspell-verify ()
21409 "Don't let flyspell put overlays at active buttons, or on
21410 {todo,all-time,additional-option-like}-keywords."
21411 (let ((pos (max (1- (point)) (point-min)))
21412 (word (thing-at-point 'word)))
21413 (and (not (get-text-property pos 'keymap))
21414 (not (get-text-property pos 'org-no-flyspell))
21415 (not (member word org-todo-keywords-1))
21416 (not (member word org-all-time-keywords))
21417 (not (member word org-additional-option-like-keywords)))))
21419 (defun org-remove-flyspell-overlays-in (beg end)
21420 "Remove flyspell overlays in region."
21421 (and (org-bound-and-true-p flyspell-mode)
21422 (fboundp 'flyspell-delete-region-overlays)
21423 (flyspell-delete-region-overlays beg end))
21424 (add-text-properties beg end '(org-no-flyspell t)))
21426 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21427 (eval-after-load "bookmark"
21428 '(if (boundp 'bookmark-after-jump-hook)
21429 ;; We can use the hook
21430 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21431 ;; Hook not available, use advice
21432 (defadvice bookmark-jump (after org-make-visible activate)
21433 "Make the position visible."
21434 (org-bookmark-jump-unhide))))
21436 ;; Make sure saveplace shows the location if it was hidden
21437 (eval-after-load "saveplace"
21438 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21439 "Make the position visible."
21440 (org-bookmark-jump-unhide)))
21442 ;; Make sure ecb shows the location if it was hidden
21443 (eval-after-load "ecb"
21444 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21445 "Make hierarchy visible when jumping into location from ECB tree buffer."
21446 (if (eq major-mode 'org-mode)
21447 (org-show-context))))
21449 (defun org-bookmark-jump-unhide ()
21450 "Unhide the current position, to show the bookmark location."
21451 (and (eq major-mode 'org-mode)
21452 (or (outline-invisible-p)
21453 (save-excursion (goto-char (max (point-min) (1- (point))))
21454 (outline-invisible-p)))
21455 (org-show-context 'bookmark-jump)))
21457 ;; Make session.el ignore our circular variable
21458 (eval-after-load "session"
21459 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21461 ;;;; Experimental code
21463 (defun org-closed-in-range ()
21464 "Sparse tree of items closed in a certain time range.
21465 Still experimental, may disappear in the future."
21466 (interactive)
21467 ;; Get the time interval from the user.
21468 (let* ((time1 (org-float-time
21469 (org-read-date nil 'to-time nil "Starting date: ")))
21470 (time2 (org-float-time
21471 (org-read-date nil 'to-time nil "End date:")))
21472 ;; callback function
21473 (callback (lambda ()
21474 (let ((time
21475 (org-float-time
21476 (apply 'encode-time
21477 (org-parse-time-string
21478 (match-string 1))))))
21479 ;; check if time in interval
21480 (and (>= time time1) (<= time time2))))))
21481 ;; make tree, check each match with the callback
21482 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21484 ;;;; Finish up
21486 (provide 'org)
21488 (run-hooks 'org-load-hook)
21490 ;;; org.el ends here