Merge branch 'hotfix-7.8.06'
[org-mode.git] / lisp / org.el
blob1782135b5ae713fa811aeb4299e232b4389cc49f
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 'boolean
2845 :version "24.1"
2846 :type 'integer)
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 (1+ (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 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 (mapcar 'car table)))))
13760 (quit (setq tg "")))
13761 (when (string-match "\\S-" tg)
13762 (add-to-list 'buffer-tags (list tg))
13763 (if (member tg current)
13764 (setq current (delete tg current))
13765 (push tg current)))
13766 (if exit-after-next (setq exit-after-next 'now)))
13767 ((setq e (rassoc c todo-table) tg (car e))
13768 (with-current-buffer buf
13769 (save-excursion (org-todo tg)))
13770 (if exit-after-next (setq exit-after-next 'now)))
13771 ((setq e (rassoc c ntable) tg (car e))
13772 (if (member tg current)
13773 (setq current (delete tg current))
13774 (loop for g in groups do
13775 (if (member tg g)
13776 (mapc (lambda (x)
13777 (setq current (delete x current)))
13778 g)))
13779 (push tg current))
13780 (if exit-after-next (setq exit-after-next 'now))))
13782 ;; Create a sorted list
13783 (setq current
13784 (sort current
13785 (lambda (a b)
13786 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13787 (if (eq exit-after-next 'now) (throw 'exit t))
13788 (goto-char (point-min))
13789 (beginning-of-line 2)
13790 (delete-region (point) (point-at-eol))
13791 (org-fast-tag-insert "Current" current c-face)
13792 (org-set-current-tags-overlay current ov-prefix)
13793 (while (re-search-forward
13794 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13795 (setq tg (match-string 1))
13796 (add-text-properties
13797 (match-beginning 1) (match-end 1)
13798 (list 'face
13799 (cond
13800 ((member tg current) c-face)
13801 ((member tg inherited) i-face)
13802 (t (get-text-property (match-beginning 1) 'face))))))
13803 (goto-char (point-min)))))
13804 (org-detach-overlay org-tags-overlay)
13805 (if rtn
13806 (mapconcat 'identity current ":")
13807 nil))))
13809 (defun org-get-tags-string ()
13810 "Get the TAGS string in the current headline."
13811 (unless (org-at-heading-p t)
13812 (error "Not on a heading"))
13813 (save-excursion
13814 (beginning-of-line 1)
13815 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13816 (org-match-string-no-properties 1)
13817 "")))
13819 (defun org-get-tags ()
13820 "Get the list of tags specified in the current headline."
13821 (org-split-string (org-get-tags-string) ":"))
13823 (defun org-get-buffer-tags ()
13824 "Get a table of all tags used in the buffer, for completion."
13825 (let (tags)
13826 (save-excursion
13827 (goto-char (point-min))
13828 (while (re-search-forward
13829 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13830 (when (equal (char-after (point-at-bol 0)) ?*)
13831 (mapc (lambda (x) (add-to-list 'tags x))
13832 (org-split-string (org-match-string-no-properties 1) ":")))))
13833 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13834 (mapcar 'list tags)))
13836 ;;;; The mapping API
13838 ;;;###autoload
13839 (defun org-map-entries (func &optional match scope &rest skip)
13840 "Call FUNC at each headline selected by MATCH in SCOPE.
13842 FUNC is a function or a lisp form. The function will be called without
13843 arguments, with the cursor positioned at the beginning of the headline.
13844 The return values of all calls to the function will be collected and
13845 returned as a list.
13847 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13848 does not need to preserve point. After evaluation, the cursor will be
13849 moved to the end of the line (presumably of the headline of the
13850 processed entry) and search continues from there. Under some
13851 circumstances, this may not produce the wanted results. For example,
13852 if you have removed (e.g. archived) the current (sub)tree it could
13853 mean that the next entry will be skipped entirely. In such cases, you
13854 can specify the position from where search should continue by making
13855 FUNC set the variable `org-map-continue-from' to the desired buffer
13856 position.
13858 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13859 Only headlines that are matched by this query will be considered during
13860 the iteration. When MATCH is nil or t, all headlines will be
13861 visited by the iteration.
13863 SCOPE determines the scope of this command. It can be any of:
13865 nil The current buffer, respecting the restriction if any
13866 tree The subtree started with the entry at point
13867 region The entries within the active region, if any
13868 region-start-level
13869 The entries within the active region, but only those at
13870 the same level than the first one.
13871 file The current buffer, without restriction
13872 file-with-archives
13873 The current buffer, and any archives associated with it
13874 agenda All agenda files
13875 agenda-with-archives
13876 All agenda files with any archive files associated with them
13877 \(file1 file2 ...)
13878 If this is a list, all files in the list will be scanned
13880 The remaining args are treated as settings for the skipping facilities of
13881 the scanner. The following items can be given here:
13883 archive skip trees with the archive tag.
13884 comment skip trees with the COMMENT keyword
13885 function or Emacs Lisp form:
13886 will be used as value for `org-agenda-skip-function', so whenever
13887 the function returns t, FUNC will not be called for that
13888 entry and search will continue from the point where the
13889 function leaves it.
13891 If your function needs to retrieve the tags including inherited tags
13892 at the *current* entry, you can use the value of the variable
13893 `org-scanner-tags' which will be much faster than getting the value
13894 with `org-get-tags-at'. If your function gets properties with
13895 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13896 to t around the call to `org-entry-properties' to get the same speedup.
13897 Note that if your function moves around to retrieve tags and properties at
13898 a *different* entry, you cannot use these techniques."
13899 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13900 (not (org-region-active-p)))
13901 (let* ((org-agenda-archives-mode nil) ; just to make sure
13902 (org-agenda-skip-archived-trees (memq 'archive skip))
13903 (org-agenda-skip-comment-trees (memq 'comment skip))
13904 (org-agenda-skip-function
13905 (car (org-delete-all '(comment archive) skip)))
13906 (org-tags-match-list-sublevels t)
13907 (start-level (eq scope 'region-start-level))
13908 matcher file res
13909 org-todo-keywords-for-agenda
13910 org-done-keywords-for-agenda
13911 org-todo-keyword-alist-for-agenda
13912 org-drawers-for-agenda
13913 org-tag-alist-for-agenda
13914 todo-only)
13916 (cond
13917 ((eq match t) (setq matcher t))
13918 ((eq match nil) (setq matcher t))
13919 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13921 (save-excursion
13922 (save-restriction
13923 (cond ((eq scope 'tree)
13924 (org-back-to-heading t)
13925 (org-narrow-to-subtree)
13926 (setq scope nil))
13927 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13928 (org-region-active-p))
13929 ;; If needed, set start-level to a string like "2"
13930 (when start-level
13931 (save-excursion
13932 (goto-char (region-beginning))
13933 (unless (org-at-heading-p) (outline-next-heading))
13934 (setq start-level (org-current-level))))
13935 (narrow-to-region (region-beginning)
13936 (save-excursion
13937 (goto-char (region-end))
13938 (unless (and (bolp) (org-at-heading-p))
13939 (outline-next-heading))
13940 (point)))
13941 (setq scope nil)))
13943 (if (not scope)
13944 (progn
13945 (org-prepare-agenda-buffers
13946 (list (buffer-file-name (current-buffer))))
13947 (setq res (org-scan-tags func matcher todo-only start-level)))
13948 ;; Get the right scope
13949 (cond
13950 ((and scope (listp scope) (symbolp (car scope)))
13951 (setq scope (eval scope)))
13952 ((eq scope 'agenda)
13953 (setq scope (org-agenda-files t)))
13954 ((eq scope 'agenda-with-archives)
13955 (setq scope (org-agenda-files t))
13956 (setq scope (org-add-archive-files scope)))
13957 ((eq scope 'file)
13958 (setq scope (list (buffer-file-name))))
13959 ((eq scope 'file-with-archives)
13960 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13961 (org-prepare-agenda-buffers scope)
13962 (while (setq file (pop scope))
13963 (with-current-buffer (org-find-base-buffer-visiting file)
13964 (save-excursion
13965 (save-restriction
13966 (widen)
13967 (goto-char (point-min))
13968 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
13969 res)))
13971 ;;;; Properties
13973 ;;; Setting and retrieving properties
13975 (defconst org-special-properties
13976 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13977 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13978 "The special properties valid in Org-mode.
13980 These are properties that are not defined in the property drawer,
13981 but in some other way.")
13983 (defconst org-default-properties
13984 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13985 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13986 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13987 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13988 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13989 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13990 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13991 "Some properties that are used by Org-mode for various purposes.
13992 Being in this list makes sure that they are offered for completion.")
13994 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13995 "Regular expression matching the first line of a property drawer.")
13997 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13998 "Regular expression matching the last line of a property drawer.")
14000 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14001 "Regular expression matching the first line of a property drawer.")
14003 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14004 "Regular expression matching the first line of a property drawer.")
14006 (defconst org-property-drawer-re
14007 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14008 org-property-end-re "\\)\n?")
14009 "Matches an entire property drawer.")
14011 (defconst org-clock-drawer-re
14012 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14013 org-property-end-re "\\)\n?")
14014 "Matches an entire clock drawer.")
14016 (defsubst org-re-property (property)
14017 "Return a regexp matching PROPERTY.
14018 Match group 1 will be set to the value "
14019 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14021 (defun org-property-action ()
14022 "Do an action on properties."
14023 (interactive)
14024 (let (c)
14025 (org-at-property-p)
14026 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14027 (setq c (read-char-exclusive))
14028 (cond
14029 ((equal c ?s)
14030 (call-interactively 'org-set-property))
14031 ((equal c ?d)
14032 (call-interactively 'org-delete-property))
14033 ((equal c ?D)
14034 (call-interactively 'org-delete-property-globally))
14035 ((equal c ?c)
14036 (call-interactively 'org-compute-property-at-point))
14037 (t (error "No such property action %c" c)))))
14039 (defun org-set-effort (&optional value)
14040 "Set the effort property of the current entry.
14041 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14042 allowed value."
14043 (interactive "P")
14044 (if (equal value 0) (setq value 10))
14045 (let* ((completion-ignore-case t)
14046 (prop org-effort-property)
14047 (cur (org-entry-get nil prop))
14048 (allowed (org-property-get-allowed-values nil prop 'table))
14049 (existing (mapcar 'list (org-property-values prop)))
14051 (val (cond
14052 ((stringp value) value)
14053 ((and allowed (integerp value))
14054 (or (car (nth (1- value) allowed))
14055 (car (org-last allowed))))
14056 (allowed
14057 (message "Select 1-9,0, [RET%s]: %s"
14058 (if cur (concat "=" cur) "")
14059 (mapconcat 'car allowed " "))
14060 (setq rpl (read-char-exclusive))
14061 (if (equal rpl ?\r)
14063 (setq rpl (- rpl ?0))
14064 (if (equal rpl 0) (setq rpl 10))
14065 (if (and (> rpl 0) (<= rpl (length allowed)))
14066 (car (nth (1- rpl) allowed))
14067 (org-completing-read "Effort: " allowed nil))))
14069 (let (org-completion-use-ido org-completion-use-iswitchb)
14070 (org-completing-read
14071 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14072 (concat "[" cur "]") "")
14073 ": ")
14074 existing nil nil "" nil cur))))))
14075 (unless (equal (org-entry-get nil prop) val)
14076 (org-entry-put nil prop val))
14077 (message "%s is now %s" prop val)))
14079 (defun org-at-property-p ()
14080 "Is cursor inside a property drawer?"
14081 (save-excursion
14082 (beginning-of-line 1)
14083 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14084 (save-match-data ;; Used by calling procedures
14085 (let ((p (point))
14086 (range (unless (org-before-first-heading-p)
14087 (org-get-property-block))))
14088 (and range (<= (car range) p) (< p (cdr range))))))))
14090 (defun org-get-property-block (&optional beg end force)
14091 "Return the (beg . end) range of the body of the property drawer.
14092 BEG and END can be beginning and end of subtree, if not given
14093 they will be found.
14094 If the drawer does not exist and FORCE is non-nil, create the drawer."
14095 (catch 'exit
14096 (save-excursion
14097 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14098 (end (or end (progn (outline-next-heading) (point)))))
14099 (goto-char beg)
14100 (if (re-search-forward org-property-start-re end t)
14101 (setq beg (1+ (match-end 0)))
14102 (if force
14103 (save-excursion
14104 (org-insert-property-drawer)
14105 (setq end (progn (outline-next-heading) (point))))
14106 (throw 'exit nil))
14107 (goto-char beg)
14108 (if (re-search-forward org-property-start-re end t)
14109 (setq beg (1+ (match-end 0)))))
14110 (if (re-search-forward org-property-end-re end t)
14111 (setq end (match-beginning 0))
14112 (or force (throw 'exit nil))
14113 (goto-char beg)
14114 (setq end beg)
14115 (org-indent-line-function)
14116 (insert ":END:\n"))
14117 (cons beg end)))))
14119 (defun org-entry-properties (&optional pom which specific)
14120 "Get all properties of the entry at point-or-marker POM.
14121 This includes the TODO keyword, the tags, time strings for deadline,
14122 scheduled, and clocking, and any additional properties defined in the
14123 entry. The return value is an alist, keys may occur multiple times
14124 if the property key was used several times.
14125 POM may also be nil, in which case the current entry is used.
14126 If WHICH is nil or `all', get all properties. If WHICH is
14127 `special' or `standard', only get that subclass. If WHICH
14128 is a string only get exactly this property. SPECIFIC can be a string, the
14129 specific property we are interested in. Specifying it can speed
14130 things up because then unnecessary parsing is avoided."
14131 (setq which (or which 'all))
14132 (org-with-point-at pom
14133 (let ((clockstr (substring org-clock-string 0 -1))
14134 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14135 (case-fold-search nil)
14136 beg end range props sum-props key key1 value string clocksum)
14137 (save-excursion
14138 (when (condition-case nil
14139 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14140 (error nil))
14141 (setq beg (point))
14142 (setq sum-props (get-text-property (point) 'org-summaries))
14143 (setq clocksum (get-text-property (point) :org-clock-minutes))
14144 (outline-next-heading)
14145 (setq end (point))
14146 (when (memq which '(all special))
14147 ;; Get the special properties, like TODO and tags
14148 (goto-char beg)
14149 (when (and (or (not specific) (string= specific "TODO"))
14150 (looking-at org-todo-line-regexp) (match-end 2))
14151 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14152 (when (and (or (not specific) (string= specific "PRIORITY"))
14153 (looking-at org-priority-regexp))
14154 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14155 (when (or (not specific) (string= specific "FILE"))
14156 (push (cons "FILE" buffer-file-name) props))
14157 (when (and (or (not specific) (string= specific "TAGS"))
14158 (setq value (org-get-tags-string))
14159 (string-match "\\S-" value))
14160 (push (cons "TAGS" value) props))
14161 (when (and (or (not specific) (string= specific "ALLTAGS"))
14162 (setq value (org-get-tags-at)))
14163 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14164 ":"))
14165 props))
14166 (when (or (not specific) (string= specific "BLOCKED"))
14167 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14168 (when (or (not specific)
14169 (member specific
14170 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14171 "TIMESTAMP" "TIMESTAMP_IA")))
14172 (catch 'match
14173 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14174 (setq key (if (match-end 1)
14175 (substring (org-match-string-no-properties 1)
14176 0 -1))
14177 string (if (equal key clockstr)
14178 (org-no-properties
14179 (org-trim
14180 (buffer-substring
14181 (match-beginning 3) (goto-char
14182 (point-at-eol)))))
14183 (substring (org-match-string-no-properties 3)
14184 1 -1)))
14185 ;; Get the correct property name from the key. This is
14186 ;; necessary if the user has configured time keywords.
14187 (setq key1 (concat key ":"))
14188 (cond
14189 ((not key)
14190 (setq key
14191 (if (= (char-after (match-beginning 3)) ?\[)
14192 "TIMESTAMP_IA" "TIMESTAMP")))
14193 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14194 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14195 ((equal key1 org-closed-string) (setq key "CLOSED"))
14196 ((equal key1 org-clock-string) (setq key "CLOCK")))
14197 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14198 (progn
14199 (push (cons key string) props)
14200 ;; no need to search further if match is found
14201 (throw 'match t))
14202 (when (or (equal key "CLOCK") (not (assoc key props)))
14203 (push (cons key string) props))))))
14206 (when (memq which '(all standard))
14207 ;; Get the standard properties, like :PROP: ...
14208 (setq range (org-get-property-block beg end))
14209 (when range
14210 (goto-char (car range))
14211 (while (re-search-forward
14212 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14213 (cdr range) t)
14214 (setq key (org-match-string-no-properties 1)
14215 value (org-trim (or (org-match-string-no-properties 2) "")))
14216 (unless (member key excluded)
14217 (push (cons key (or value "")) props)))))
14218 (if clocksum
14219 (push (cons "CLOCKSUM"
14220 (org-columns-number-to-string (/ (float clocksum) 60.)
14221 'add_times))
14222 props))
14223 (unless (assoc "CATEGORY" props)
14224 (push (cons "CATEGORY" (org-get-category)) props))
14225 (append sum-props (nreverse props)))))))
14227 (defun org-entry-get (pom property &optional inherit literal-nil)
14228 "Get value of PROPERTY for entry at point-or-marker POM.
14229 If INHERIT is non-nil and the entry does not have the property,
14230 then also check higher levels of the hierarchy.
14231 If INHERIT is the symbol `selective', use inheritance only if the setting
14232 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14233 If the property is present but empty, the return value is the empty string.
14234 If the property is not present at all, nil is returned.
14236 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14237 do not interpret it as the list atom nil. This is used for inheritance
14238 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14239 (org-with-point-at pom
14240 (if (and inherit (if (eq inherit 'selective)
14241 (org-property-inherit-p property)
14243 (org-entry-get-with-inheritance property literal-nil)
14244 (if (member property org-special-properties)
14245 ;; We need a special property. Use `org-entry-properties' to
14246 ;; retrieve it, but specify the wanted property
14247 (cdr (assoc property (org-entry-properties nil 'special property)))
14248 (let ((range (unless (org-before-first-heading-p)
14249 (org-get-property-block)))
14250 (props (list (or (assoc property org-file-properties)
14251 (assoc property org-global-properties)
14252 (assoc property org-global-properties-fixed))))
14253 val)
14254 (flet ((ap (key)
14255 (when (re-search-forward
14256 (org-re-property key) (cdr range) t)
14257 (setq props
14258 (org-update-property-plist
14260 (if (match-end 1)
14261 (org-match-string-no-properties 1) "")
14262 props)))))
14263 (when (and range (goto-char (car range)))
14264 (ap property)
14265 (goto-char (car range))
14266 (while (ap (concat property "+")))
14267 (setq val (cdr (assoc property props)))
14268 (when val (if literal-nil val (org-not-nil val))))))))))
14270 (defun org-property-or-variable-value (var &optional inherit)
14271 "Check if there is a property fixing the value of VAR.
14272 If yes, return this value. If not, return the current value of the variable."
14273 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14274 (if (and prop (stringp prop) (string-match "\\S-" prop))
14275 (read prop)
14276 (symbol-value var))))
14278 (defun org-entry-delete (pom property)
14279 "Delete the property PROPERTY from entry at point-or-marker POM."
14280 (org-with-point-at pom
14281 (if (member property org-special-properties)
14282 nil ; cannot delete these properties.
14283 (let ((range (org-get-property-block)))
14284 (if (and range
14285 (goto-char (car range))
14286 (re-search-forward
14287 (org-re-property property)
14288 (cdr range) t))
14289 (progn
14290 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14292 nil)))))
14294 ;; Multi-values properties are properties that contain multiple values
14295 ;; These values are assumed to be single words, separated by whitespace.
14296 (defun org-entry-add-to-multivalued-property (pom property value)
14297 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14298 (let* ((old (org-entry-get pom property))
14299 (values (and old (org-split-string old "[ \t]"))))
14300 (setq value (org-entry-protect-space value))
14301 (unless (member value values)
14302 (setq values (cons value values))
14303 (org-entry-put pom property
14304 (mapconcat 'identity values " ")))))
14306 (defun org-entry-remove-from-multivalued-property (pom property value)
14307 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14308 (let* ((old (org-entry-get pom property))
14309 (values (and old (org-split-string old "[ \t]"))))
14310 (setq value (org-entry-protect-space value))
14311 (when (member value values)
14312 (setq values (delete value values))
14313 (org-entry-put pom property
14314 (mapconcat 'identity values " ")))))
14316 (defun org-entry-member-in-multivalued-property (pom property value)
14317 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14318 (let* ((old (org-entry-get pom property))
14319 (values (and old (org-split-string old "[ \t]"))))
14320 (setq value (org-entry-protect-space value))
14321 (member value values)))
14323 (defun org-entry-get-multivalued-property (pom property)
14324 "Return a list of values in a multivalued property."
14325 (let* ((value (org-entry-get pom property))
14326 (values (and value (org-split-string value "[ \t]"))))
14327 (mapcar 'org-entry-restore-space values)))
14329 (defun org-entry-put-multivalued-property (pom property &rest values)
14330 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14331 VALUES should be a list of strings. Spaces will be protected."
14332 (org-entry-put pom property
14333 (mapconcat 'org-entry-protect-space values " "))
14334 (let* ((value (org-entry-get pom property))
14335 (values (and value (org-split-string value "[ \t]"))))
14336 (mapcar 'org-entry-restore-space values)))
14338 (defun org-entry-protect-space (s)
14339 "Protect spaces and newline in string S."
14340 (while (string-match " " s)
14341 (setq s (replace-match "%20" t t s)))
14342 (while (string-match "\n" s)
14343 (setq s (replace-match "%0A" t t s)))
14346 (defun org-entry-restore-space (s)
14347 "Restore spaces and newline in string S."
14348 (while (string-match "%20" s)
14349 (setq s (replace-match " " t t s)))
14350 (while (string-match "%0A" s)
14351 (setq s (replace-match "\n" t t s)))
14354 (defvar org-entry-property-inherited-from (make-marker)
14355 "Marker pointing to the entry from where a property was inherited.
14356 Each call to `org-entry-get-with-inheritance' will set this marker to the
14357 location of the entry where the inheritance search matched. If there was
14358 no match, the marker will point nowhere.
14359 Note that also `org-entry-get' calls this function, if the INHERIT flag
14360 is set.")
14362 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14363 "Get entry property, and search higher levels if not present.
14364 The search will stop at the first ancestor which has the property defined.
14365 If the value found is \"nil\", return nil to show that the property
14366 should be considered as undefined (this is the meaning of nil here).
14367 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14368 (move-marker org-entry-property-inherited-from nil)
14369 (let (tmp)
14370 (unless (org-before-first-heading-p)
14371 (save-excursion
14372 (save-restriction
14373 (widen)
14374 (catch 'ex
14375 (while t
14376 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14377 (org-back-to-heading t)
14378 (move-marker org-entry-property-inherited-from (point))
14379 (throw 'ex tmp))
14380 (or (org-up-heading-safe) (throw 'ex nil)))))))
14381 (setq tmp (or tmp
14382 (cdr (assoc property org-file-properties))
14383 (cdr (assoc property org-global-properties))
14384 (cdr (assoc property org-global-properties-fixed))))
14385 (if literal-nil tmp (org-not-nil tmp))))
14387 (defvar org-property-changed-functions nil
14388 "Hook called when the value of a property has changed.
14389 Each hook function should accept two arguments, the name of the property
14390 and the new value.")
14392 (defun org-entry-put (pom property value)
14393 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14394 (org-with-point-at pom
14395 (org-back-to-heading t)
14396 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14397 range)
14398 (cond
14399 ((equal property "TODO")
14400 (when (and (stringp value) (string-match "\\S-" value)
14401 (not (member value org-todo-keywords-1)))
14402 (error "\"%s\" is not a valid TODO state" value))
14403 (if (or (not value)
14404 (not (string-match "\\S-" value)))
14405 (setq value 'none))
14406 (org-todo value)
14407 (org-set-tags nil 'align))
14408 ((equal property "PRIORITY")
14409 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14410 (string-to-char value) ?\ ))
14411 (org-set-tags nil 'align))
14412 ((equal property "SCHEDULED")
14413 (if (re-search-forward org-scheduled-time-regexp end t)
14414 (cond
14415 ((eq value 'earlier) (org-timestamp-change -1 'day))
14416 ((eq value 'later) (org-timestamp-change 1 'day))
14417 (t (call-interactively 'org-schedule)))
14418 (call-interactively 'org-schedule)))
14419 ((equal property "DEADLINE")
14420 (if (re-search-forward org-deadline-time-regexp end t)
14421 (cond
14422 ((eq value 'earlier) (org-timestamp-change -1 'day))
14423 ((eq value 'later) (org-timestamp-change 1 'day))
14424 (t (call-interactively 'org-deadline)))
14425 (call-interactively 'org-deadline)))
14426 ((member property org-special-properties)
14427 (error "The %s property can not yet be set with `org-entry-put'"
14428 property))
14429 (t ; a non-special property
14430 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14431 (setq range (org-get-property-block beg end 'force))
14432 (goto-char (car range))
14433 (if (re-search-forward
14434 (org-re-property property) (cdr range) t)
14435 (progn
14436 (delete-region (match-beginning 0) (match-end 0))
14437 (goto-char (match-beginning 0)))
14438 (goto-char (cdr range))
14439 (insert "\n")
14440 (backward-char 1)
14441 (org-indent-line-function))
14442 (insert ":" property ":")
14443 (and value (insert " " value))
14444 (org-indent-line-function)))))
14445 (run-hook-with-args 'org-property-changed-functions property value)))
14447 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14448 "Get all property keys in the current buffer.
14449 With INCLUDE-SPECIALS, also list the special properties that reflect things
14450 like tags and TODO state.
14451 With INCLUDE-DEFAULTS, also include properties that has special meaning
14452 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14453 and others.
14454 With INCLUDE-COLUMNS, also include property names given in COLUMN
14455 formats in the current buffer."
14456 (let (rtn range cfmt s p)
14457 (save-excursion
14458 (save-restriction
14459 (widen)
14460 (goto-char (point-min))
14461 (while (re-search-forward org-property-start-re nil t)
14462 (setq range (org-get-property-block))
14463 (goto-char (car range))
14464 (while (re-search-forward
14465 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14466 (cdr range) t)
14467 (add-to-list 'rtn (org-match-string-no-properties 1)))
14468 (outline-next-heading))))
14470 (when include-specials
14471 (setq rtn (append org-special-properties rtn)))
14473 (when include-defaults
14474 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14475 (add-to-list 'rtn org-effort-property))
14477 (when include-columns
14478 (save-excursion
14479 (save-restriction
14480 (widen)
14481 (goto-char (point-min))
14482 (while (re-search-forward
14483 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14484 nil t)
14485 (setq cfmt (match-string 2) s 0)
14486 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14487 cfmt s)
14488 (setq s (match-end 0)
14489 p (match-string 1 cfmt))
14490 (unless (or (equal p "ITEM")
14491 (member p org-special-properties))
14492 (add-to-list 'rtn (match-string 1 cfmt))))))))
14494 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14496 (defun org-property-values (key)
14497 "Return a list of all values of property KEY in the current buffer."
14498 (save-excursion
14499 (save-restriction
14500 (widen)
14501 (goto-char (point-min))
14502 (let ((re (org-re-property key))
14503 values)
14504 (while (re-search-forward re nil t)
14505 (add-to-list 'values (org-trim (match-string 1))))
14506 (delete "" values)))))
14508 (defun org-insert-property-drawer ()
14509 "Insert a property drawer into the current entry."
14510 (org-back-to-heading t)
14511 (looking-at org-outline-regexp)
14512 (let ((indent (if org-adapt-indentation
14513 (- (match-end 0) (match-beginning 0))
14515 (beg (point))
14516 (re (concat "^[ \t]*" org-keyword-time-regexp))
14517 end hiddenp)
14518 (outline-next-heading)
14519 (setq end (point))
14520 (goto-char beg)
14521 (while (re-search-forward re end t))
14522 (setq hiddenp (outline-invisible-p))
14523 (end-of-line 1)
14524 (and (equal (char-after) ?\n) (forward-char 1))
14525 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14526 (if (member (match-string 1) '("CLOCK:" ":END:"))
14527 ;; just skip this line
14528 (beginning-of-line 2)
14529 ;; Drawer start, find the end
14530 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14531 (beginning-of-line 1)))
14532 (org-skip-over-state-notes)
14533 (skip-chars-backward " \t\n\r")
14534 (if (eq (char-before) ?*) (forward-char 1))
14535 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14536 (beginning-of-line 0)
14537 (org-indent-to-column indent)
14538 (beginning-of-line 2)
14539 (org-indent-to-column indent)
14540 (beginning-of-line 0)
14541 (if hiddenp
14542 (save-excursion
14543 (org-back-to-heading t)
14544 (hide-entry))
14545 (org-flag-drawer t))))
14547 (defun org-insert-drawer (&optional arg drawer)
14548 "Insert a drawer at point.
14550 Optional argument DRAWER, when non-nil, is a string representing
14551 drawer's name. Otherwise, the user is prompted for a name.
14553 If a region is active, insert the drawer around that region
14554 instead.
14556 Point is left between drawer's boundaries."
14557 (interactive "P")
14558 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14559 "LOGBOOK"))
14560 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14561 ;; internally by Org. They are meant to be inserted
14562 ;; automatically.
14563 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14564 ;; Remove system drawers from list. Note: For some reason,
14565 ;; `org-completing-read' ignores the predicate while
14566 ;; `completing-read' handles it fine.
14567 (drawer (if arg "PROPERTIES"
14568 (or drawer
14569 (completing-read
14570 "Drawer: " org-drawers
14571 (lambda (d) (not (member d system-drawers))))))))
14572 (cond
14573 ;; With C-u, fall back on `org-insert-property-drawer'
14574 (arg (org-insert-property-drawer))
14575 ;; With an active region, insert a drawer at point.
14576 ((not (org-region-active-p))
14577 (progn
14578 (unless (bolp) (insert "\n"))
14579 (insert (format ":%s:\n\n:END:\n" drawer))
14580 (forward-line -2)))
14581 ;; Otherwise, insert the drawer at point
14583 (let ((rbeg (region-beginning))
14584 (rend (copy-marker (region-end))))
14585 (unwind-protect
14586 (progn
14587 (goto-char rbeg)
14588 (beginning-of-line)
14589 (when (save-excursion
14590 (re-search-forward org-outline-regexp-bol rend t))
14591 (error "Drawers cannot contain headlines"))
14592 ;; Position point at the beginning of the first
14593 ;; non-blank line in region. Insert drawer's opening
14594 ;; there, then indent it.
14595 (org-skip-whitespace)
14596 (beginning-of-line)
14597 (insert ":" drawer ":\n")
14598 (forward-line -1)
14599 (indent-for-tab-command)
14600 ;; Move point to the beginning of the first blank line
14601 ;; after the last non-blank line in region. Insert
14602 ;; drawer's closing, then indent it.
14603 (goto-char rend)
14604 (skip-chars-backward " \r\t\n")
14605 (insert "\n:END:")
14606 (indent-for-tab-command)
14607 (unless (eolp) (insert "\n")))
14608 ;; Clear marker, whatever the outcome of insertion is.
14609 (set-marker rend nil)))))))
14611 (defvar org-property-set-functions-alist nil
14612 "Property set function alist.
14613 Each entry should have the following format:
14615 (PROPERTY . READ-FUNCTION)
14617 The read function will be called with the same argument as
14618 `org-completing-read'.")
14620 (defun org-set-property-function (property)
14621 "Get the function that should be used to set PROPERTY.
14622 This is computed according to `org-property-set-functions-alist'."
14623 (or (cdr (assoc property org-property-set-functions-alist))
14624 'org-completing-read))
14626 (defun org-read-property-value (property)
14627 "Read PROPERTY value from user."
14628 (let* ((completion-ignore-case t)
14629 (allowed (org-property-get-allowed-values nil property 'table))
14630 (cur (org-entry-get nil property))
14631 (prompt (concat property " value"
14632 (if (and cur (string-match "\\S-" cur))
14633 (concat " [" cur "]") "") ": "))
14634 (set-function (org-set-property-function property))
14635 (val (if allowed
14636 (funcall set-function prompt allowed nil
14637 (not (get-text-property 0 'org-unrestricted
14638 (caar allowed))))
14639 (let (org-completion-use-ido org-completion-use-iswitchb)
14640 (funcall set-function prompt
14641 (mapcar 'list (org-property-values property))
14642 nil nil "" nil cur)))))
14643 (if (equal val "")
14645 val)))
14647 (defvar org-last-set-property nil)
14648 (defun org-read-property-name ()
14649 "Read a property name."
14650 (let* ((completion-ignore-case t)
14651 (keys (org-buffer-property-keys nil t t))
14652 (default-prop (or (save-excursion
14653 (save-match-data
14654 (beginning-of-line)
14655 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14656 (null (string= (match-string 1) "END"))
14657 (match-string 1))))
14658 org-last-set-property))
14659 (property (org-icompleting-read
14660 (concat "Property"
14661 (if default-prop (concat " [" default-prop "]") "")
14662 ": ")
14663 (mapcar 'list keys)
14664 nil nil nil nil
14665 default-prop
14667 (if (member property keys)
14668 property
14669 (or (cdr (assoc (downcase property)
14670 (mapcar (lambda (x) (cons (downcase x) x))
14671 keys)))
14672 property))))
14674 (defun org-set-property (property value)
14675 "In the current entry, set PROPERTY to VALUE.
14676 When called interactively, this will prompt for a property name, offering
14677 completion on existing and default properties. And then it will prompt
14678 for a value, offering completion either on allowed values (via an inherited
14679 xxx_ALL property) or on existing values in other instances of this property
14680 in the current file."
14681 (interactive (list nil nil))
14682 (let* ((property (or property (org-read-property-name)))
14683 (value (or value (org-read-property-value property)))
14684 (fn (assoc property org-properties-postprocess-alist)))
14685 (setq org-last-set-property property)
14686 ;; Possibly postprocess the inserted value:
14687 (when fn (setq value (funcall (cadr fn) value)))
14688 (unless (equal (org-entry-get nil property) value)
14689 (org-entry-put nil property value))))
14691 (defun org-delete-property (property)
14692 "In the current entry, delete PROPERTY."
14693 (interactive
14694 (let* ((completion-ignore-case t)
14695 (prop (org-icompleting-read "Property: "
14696 (org-entry-properties nil 'standard))))
14697 (list prop)))
14698 (message "Property %s %s" property
14699 (if (org-entry-delete nil property)
14700 "deleted"
14701 "was not present in the entry")))
14703 (defun org-delete-property-globally (property)
14704 "Remove PROPERTY globally, from all entries."
14705 (interactive
14706 (let* ((completion-ignore-case t)
14707 (prop (org-icompleting-read
14708 "Globally remove property: "
14709 (mapcar 'list (org-buffer-property-keys)))))
14710 (list prop)))
14711 (save-excursion
14712 (save-restriction
14713 (widen)
14714 (goto-char (point-min))
14715 (let ((cnt 0))
14716 (while (re-search-forward
14717 (org-re-property property)
14718 nil t)
14719 (setq cnt (1+ cnt))
14720 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14721 (message "Property \"%s\" removed from %d entries" property cnt)))))
14723 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14725 (defun org-compute-property-at-point ()
14726 "Compute the property at point.
14727 This looks for an enclosing column format, extracts the operator and
14728 then applies it to the property in the column format's scope."
14729 (interactive)
14730 (unless (org-at-property-p)
14731 (error "Not at a property"))
14732 (let ((prop (org-match-string-no-properties 2)))
14733 (org-columns-get-format-and-top-level)
14734 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14735 (error "No operator defined for property %s" prop))
14736 (org-columns-compute prop)))
14738 (defvar org-property-allowed-value-functions nil
14739 "Hook for functions supplying allowed values for a specific property.
14740 The functions must take a single argument, the name of the property, and
14741 return a flat list of allowed values. If \":ETC\" is one of
14742 the values, this means that these values are intended as defaults for
14743 completion, but that other values should be allowed too.
14744 The functions must return nil if they are not responsible for this
14745 property.")
14747 (defun org-property-get-allowed-values (pom property &optional table)
14748 "Get allowed values for the property PROPERTY.
14749 When TABLE is non-nil, return an alist that can directly be used for
14750 completion."
14751 (let (vals)
14752 (cond
14753 ((equal property "TODO")
14754 (setq vals (org-with-point-at pom
14755 (append org-todo-keywords-1 '("")))))
14756 ((equal property "PRIORITY")
14757 (let ((n org-lowest-priority))
14758 (while (>= n org-highest-priority)
14759 (push (char-to-string n) vals)
14760 (setq n (1- n)))))
14761 ((member property org-special-properties))
14762 ((setq vals (run-hook-with-args-until-success
14763 'org-property-allowed-value-functions property)))
14765 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14766 (when (and vals (string-match "\\S-" vals))
14767 (setq vals (car (read-from-string (concat "(" vals ")"))))
14768 (setq vals (mapcar (lambda (x)
14769 (cond ((stringp x) x)
14770 ((numberp x) (number-to-string x))
14771 ((symbolp x) (symbol-name x))
14772 (t "???")))
14773 vals)))))
14774 (when (member ":ETC" vals)
14775 (setq vals (remove ":ETC" vals))
14776 (org-add-props (car vals) '(org-unrestricted t)))
14777 (if table (mapcar 'list vals) vals)))
14779 (defun org-property-previous-allowed-value (&optional previous)
14780 "Switch to the next allowed value for this property."
14781 (interactive)
14782 (org-property-next-allowed-value t))
14784 (defun org-property-next-allowed-value (&optional previous)
14785 "Switch to the next allowed value for this property."
14786 (interactive)
14787 (unless (org-at-property-p)
14788 (error "Not at a property"))
14789 (let* ((key (match-string 2))
14790 (value (match-string 3))
14791 (allowed (or (org-property-get-allowed-values (point) key)
14792 (and (member value '("[ ]" "[-]" "[X]"))
14793 '("[ ]" "[X]"))))
14794 nval)
14795 (unless allowed
14796 (error "Allowed values for this property have not been defined"))
14797 (if previous (setq allowed (reverse allowed)))
14798 (if (member value allowed)
14799 (setq nval (car (cdr (member value allowed)))))
14800 (setq nval (or nval (car allowed)))
14801 (if (equal nval value)
14802 (error "Only one allowed value for this property"))
14803 (org-at-property-p)
14804 (replace-match (concat " :" key ": " nval) t t)
14805 (org-indent-line-function)
14806 (beginning-of-line 1)
14807 (skip-chars-forward " \t")
14808 (run-hook-with-args 'org-property-changed-functions key nval)))
14810 (defun org-find-olp (path &optional this-buffer)
14811 "Return a marker pointing to the entry at outline path OLP.
14812 If anything goes wrong, throw an error.
14813 You can wrap this call to catch the error like this:
14815 (condition-case msg
14816 (org-mobile-locate-entry (match-string 4))
14817 (error (nth 1 msg)))
14819 The return value will then be either a string with the error message,
14820 or a marker if everything is OK.
14822 If THIS-BUFFER is set, the outline path does not contain a file,
14823 only headings."
14824 (let* ((file (if this-buffer buffer-file-name (pop path)))
14825 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14826 (level 1)
14827 (lmin 1)
14828 (lmax 1)
14829 limit re end found pos heading cnt flevel)
14830 (unless buffer (error "File not found :%s" file))
14831 (with-current-buffer buffer
14832 (save-excursion
14833 (save-restriction
14834 (widen)
14835 (setq limit (point-max))
14836 (goto-char (point-min))
14837 (while (setq heading (pop path))
14838 (setq re (format org-complex-heading-regexp-format
14839 (regexp-quote heading)))
14840 (setq cnt 0 pos (point))
14841 (while (re-search-forward re end t)
14842 (setq level (- (match-end 1) (match-beginning 1)))
14843 (if (and (>= level lmin) (<= level lmax))
14844 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14845 (when (= cnt 0) (error "Heading not found on level %d: %s"
14846 lmax heading))
14847 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14848 lmax heading))
14849 (goto-char found)
14850 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14851 (setq end (save-excursion (org-end-of-subtree t t))))
14852 (when (org-at-heading-p)
14853 (move-marker (make-marker) (point))))))))
14855 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14856 "Find node HEADING in BUFFER.
14857 Return a marker to the heading if it was found, or nil if not.
14858 If POS-ONLY is set, return just the position instead of a marker.
14860 The heading text must match exact, but it may have a TODO keyword,
14861 a priority cookie and tags in the standard locations."
14862 (with-current-buffer (or buffer (current-buffer))
14863 (save-excursion
14864 (save-restriction
14865 (widen)
14866 (goto-char (point-min))
14867 (let (case-fold-search)
14868 (if (re-search-forward
14869 (format org-complex-heading-regexp-format
14870 (regexp-quote heading)) nil t)
14871 (if pos-only
14872 (match-beginning 0)
14873 (move-marker (make-marker) (match-beginning 0)))))))))
14875 (defun org-find-exact-heading-in-directory (heading &optional dir)
14876 "Find Org node headline HEADING in all .org files in directory DIR.
14877 When the target headline is found, return a marker to this location."
14878 (let ((files (directory-files (or dir default-directory)
14879 nil "\\`[^.#].*\\.org\\'"))
14880 file visiting m buffer)
14881 (catch 'found
14882 (while (setq file (pop files))
14883 (message "trying %s" file)
14884 (setq visiting (org-find-base-buffer-visiting file))
14885 (setq buffer (or visiting (find-file-noselect file)))
14886 (setq m (org-find-exact-headline-in-buffer
14887 heading buffer))
14888 (when (and (not m) (not visiting)) (kill-buffer buffer))
14889 (and m (throw 'found m))))))
14891 (defun org-find-entry-with-id (ident)
14892 "Locate the entry that contains the ID property with exact value IDENT.
14893 IDENT can be a string, a symbol or a number, this function will search for
14894 the string representation of it.
14895 Return the position where this entry starts, or nil if there is no such entry."
14896 (interactive "sID: ")
14897 (let ((id (cond
14898 ((stringp ident) ident)
14899 ((symbol-name ident) (symbol-name ident))
14900 ((numberp ident) (number-to-string ident))
14901 (t (error "IDENT %s must be a string, symbol or number" ident))))
14902 (case-fold-search nil))
14903 (save-excursion
14904 (save-restriction
14905 (widen)
14906 (goto-char (point-min))
14907 (when (re-search-forward
14908 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14909 nil t)
14910 (org-back-to-heading t)
14911 (point))))))
14913 ;;;; Timestamps
14915 (defvar org-last-changed-timestamp nil)
14916 (defvar org-last-inserted-timestamp nil
14917 "The last time stamp inserted with `org-insert-time-stamp'.")
14918 (defvar org-time-was-given) ; dynamically scoped parameter
14919 (defvar org-end-time-was-given) ; dynamically scoped parameter
14920 (defvar org-ts-what) ; dynamically scoped parameter
14922 (defun org-time-stamp (arg &optional inactive)
14923 "Prompt for a date/time and insert a time stamp.
14924 If the user specifies a time like HH:MM, or if this command is called
14925 with a prefix argument, the time stamp will contain date and time.
14926 Otherwise, only the date will be included. All parts of a date not
14927 specified by the user will be filled in from the current date/time.
14928 So if you press just return without typing anything, the time stamp
14929 will represent the current date/time. If there is already a timestamp
14930 at the cursor, it will be modified."
14931 (interactive "P")
14932 (let* ((ts nil)
14933 (default-time
14934 ;; Default time is either today, or, when entering a range,
14935 ;; the range start.
14936 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14937 (save-excursion
14938 (re-search-backward
14939 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14940 (- (point) 20) t)))
14941 (apply 'encode-time (org-parse-time-string (match-string 1)))
14942 (current-time)))
14943 (default-input (and ts (org-get-compact-tod ts)))
14944 (repeater (save-excursion
14945 (save-match-data
14946 (beginning-of-line)
14947 (when (re-search-forward
14948 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14949 (save-excursion (progn (end-of-line) (point))) t)
14950 (match-string 0)))))
14951 org-time-was-given org-end-time-was-given time)
14952 (cond
14953 ((and (org-at-timestamp-p t)
14954 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14955 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14956 (insert "--")
14957 (setq time (let ((this-command this-command))
14958 (org-read-date arg 'totime nil nil
14959 default-time default-input inactive)))
14960 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14961 ((org-at-timestamp-p t)
14962 (setq time (let ((this-command this-command))
14963 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14964 (when (org-at-timestamp-p t) ; just to get the match data
14965 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14966 (replace-match "")
14967 (setq org-last-changed-timestamp
14968 (org-insert-time-stamp
14969 time (or org-time-was-given arg)
14970 inactive nil nil (list org-end-time-was-given)))
14971 (when repeater (goto-char (1- (point))) (insert " " repeater)
14972 (setq org-last-changed-timestamp
14973 (concat (substring org-last-inserted-timestamp 0 -1)
14974 " " repeater ">"))))
14975 (message "Timestamp updated"))
14977 (setq time (let ((this-command this-command))
14978 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14979 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14980 nil nil (list org-end-time-was-given))))))
14982 ;; FIXME: can we use this for something else, like computing time differences?
14983 (defun org-get-compact-tod (s)
14984 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14985 (let* ((t1 (match-string 1 s))
14986 (h1 (string-to-number (match-string 2 s)))
14987 (m1 (string-to-number (match-string 3 s)))
14988 (t2 (and (match-end 4) (match-string 5 s)))
14989 (h2 (and t2 (string-to-number (match-string 6 s))))
14990 (m2 (and t2 (string-to-number (match-string 7 s))))
14991 dh dm)
14992 (if (not t2)
14994 (setq dh (- h2 h1) dm (- m2 m1))
14995 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14996 (concat t1 "+" (number-to-string dh)
14997 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14999 (defun org-time-stamp-inactive (&optional arg)
15000 "Insert an inactive time stamp.
15001 An inactive time stamp is enclosed in square brackets instead of angle
15002 brackets. It is inactive in the sense that it does not trigger agenda entries,
15003 does not link to the calendar and cannot be changed with the S-cursor keys.
15004 So these are more for recording a certain time/date."
15005 (interactive "P")
15006 (org-time-stamp arg 'inactive))
15008 (defvar org-date-ovl (make-overlay 1 1))
15009 (overlay-put org-date-ovl 'face 'org-warning)
15010 (org-detach-overlay org-date-ovl)
15012 (defvar org-ans1) ; dynamically scoped parameter
15013 (defvar org-ans2) ; dynamically scoped parameter
15015 (defvar org-plain-time-of-day-regexp) ; defined below
15017 (defvar org-overriding-default-time nil) ; dynamically scoped
15018 (defvar org-read-date-overlay nil)
15019 (defvar org-dcst nil) ; dynamically scoped
15020 (defvar org-read-date-history nil)
15021 (defvar org-read-date-final-answer nil)
15022 (defvar org-read-date-analyze-futurep nil)
15023 (defvar org-read-date-analyze-forced-year nil)
15024 (defvar org-read-date-inactive)
15026 (defun org-read-date (&optional org-with-time to-time from-string prompt
15027 default-time default-input inactive)
15028 "Read a date, possibly a time, and make things smooth for the user.
15029 The prompt will suggest to enter an ISO date, but you can also enter anything
15030 which will at least partially be understood by `parse-time-string'.
15031 Unrecognized parts of the date will default to the current day, month, year,
15032 hour and minute. If this command is called to replace a timestamp at point,
15033 or to enter the second timestamp of a range, the default time is taken
15034 from the existing stamp. Furthermore, the command prefers the future,
15035 so if you are giving a date where the year is not given, and the day-month
15036 combination is already past in the current year, it will assume you
15037 mean next year. For details, see the manual. A few examples:
15039 3-2-5 --> 2003-02-05
15040 feb 15 --> currentyear-02-15
15041 2/15 --> currentyear-02-15
15042 sep 12 9 --> 2009-09-12
15043 12:45 --> today 12:45
15044 22 sept 0:34 --> currentyear-09-22 0:34
15045 12 --> currentyear-currentmonth-12
15046 Fri --> nearest Friday (today or later)
15047 etc.
15049 Furthermore you can specify a relative date by giving, as the *first* thing
15050 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
15051 change in days weeks, months, years.
15052 With a single plus or minus, the date is relative to today. With a double
15053 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15054 +4d --> four days from today
15055 +4 --> same as above
15056 +2w --> two weeks from today
15057 ++5 --> five days from default date
15059 The function understands only English month and weekday abbreviations.
15061 While prompting, a calendar is popped up - you can also select the
15062 date with the mouse (button 1). The calendar shows a period of three
15063 months. To scroll it to other months, use the keys `>' and `<'.
15064 If you don't like the calendar, turn it off with
15065 \(setq org-read-date-popup-calendar nil)
15067 With optional argument TO-TIME, the date will immediately be converted
15068 to an internal time.
15069 With an optional argument WITH-TIME, the prompt will suggest to also
15070 insert a time. Note that when WITH-TIME is not set, you can still
15071 enter a time, and this function will inform the calling routine about
15072 this change. The calling routine may then choose to change the format
15073 used to insert the time stamp into the buffer to include the time.
15074 With optional argument FROM-STRING, read from this string instead from
15075 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15076 the time/date that is used for everything that is not specified by the
15077 user."
15078 (require 'parse-time)
15079 (let* ((org-time-stamp-rounding-minutes
15080 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15081 (org-dcst org-display-custom-times)
15082 (ct (org-current-time))
15083 (org-def (or org-overriding-default-time default-time ct))
15084 (org-defdecode (decode-time org-def))
15085 (dummy (progn
15086 (when (< (nth 2 org-defdecode) org-extend-today-until)
15087 (setcar (nthcdr 2 org-defdecode) -1)
15088 (setcar (nthcdr 1 org-defdecode) 59)
15089 (setq org-def (apply 'encode-time org-defdecode)
15090 org-defdecode (decode-time org-def)))))
15091 (calendar-frame-setup nil)
15092 (calendar-setup nil)
15093 (calendar-move-hook nil)
15094 (calendar-view-diary-initially-flag nil)
15095 (calendar-view-holidays-initially-flag nil)
15096 (timestr (format-time-string
15097 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15098 (prompt (concat (if prompt (concat prompt " ") "")
15099 (format "Date+time [%s]: " timestr)))
15100 ans (org-ans0 "") org-ans1 org-ans2 final)
15102 (cond
15103 (from-string (setq ans from-string))
15104 (org-read-date-popup-calendar
15105 (save-excursion
15106 (save-window-excursion
15107 (calendar)
15108 (unwind-protect
15109 (progn
15110 (calendar-forward-day (- (time-to-days org-def)
15111 (calendar-absolute-from-gregorian
15112 (calendar-current-date))))
15113 (org-eval-in-calendar nil t)
15114 (let* ((old-map (current-local-map))
15115 (map (copy-keymap calendar-mode-map))
15116 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15117 (org-defkey map (kbd "RET") 'org-calendar-select)
15118 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15119 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15120 (org-defkey minibuffer-local-map [(meta shift left)]
15121 (lambda () (interactive)
15122 (org-eval-in-calendar '(calendar-backward-month 1))))
15123 (org-defkey minibuffer-local-map [(meta shift right)]
15124 (lambda () (interactive)
15125 (org-eval-in-calendar '(calendar-forward-month 1))))
15126 (org-defkey minibuffer-local-map [(meta shift up)]
15127 (lambda () (interactive)
15128 (org-eval-in-calendar '(calendar-backward-year 1))))
15129 (org-defkey minibuffer-local-map [(meta shift down)]
15130 (lambda () (interactive)
15131 (org-eval-in-calendar '(calendar-forward-year 1))))
15132 (org-defkey minibuffer-local-map [?\e (shift left)]
15133 (lambda () (interactive)
15134 (org-eval-in-calendar '(calendar-backward-month 1))))
15135 (org-defkey minibuffer-local-map [?\e (shift right)]
15136 (lambda () (interactive)
15137 (org-eval-in-calendar '(calendar-forward-month 1))))
15138 (org-defkey minibuffer-local-map [?\e (shift up)]
15139 (lambda () (interactive)
15140 (org-eval-in-calendar '(calendar-backward-year 1))))
15141 (org-defkey minibuffer-local-map [?\e (shift down)]
15142 (lambda () (interactive)
15143 (org-eval-in-calendar '(calendar-forward-year 1))))
15144 (org-defkey minibuffer-local-map [(shift up)]
15145 (lambda () (interactive)
15146 (org-eval-in-calendar '(calendar-backward-week 1))))
15147 (org-defkey minibuffer-local-map [(shift down)]
15148 (lambda () (interactive)
15149 (org-eval-in-calendar '(calendar-forward-week 1))))
15150 (org-defkey minibuffer-local-map [(shift left)]
15151 (lambda () (interactive)
15152 (org-eval-in-calendar '(calendar-backward-day 1))))
15153 (org-defkey minibuffer-local-map [(shift right)]
15154 (lambda () (interactive)
15155 (org-eval-in-calendar '(calendar-forward-day 1))))
15156 (org-defkey minibuffer-local-map ">"
15157 (lambda () (interactive)
15158 (org-eval-in-calendar '(scroll-calendar-left 1))))
15159 (org-defkey minibuffer-local-map "<"
15160 (lambda () (interactive)
15161 (org-eval-in-calendar '(scroll-calendar-right 1))))
15162 (org-defkey minibuffer-local-map "\C-v"
15163 (lambda () (interactive)
15164 (org-eval-in-calendar
15165 '(calendar-scroll-left-three-months 1))))
15166 (org-defkey minibuffer-local-map "\M-v"
15167 (lambda () (interactive)
15168 (org-eval-in-calendar
15169 '(calendar-scroll-right-three-months 1))))
15170 (run-hooks 'org-read-date-minibuffer-setup-hook)
15171 (unwind-protect
15172 (progn
15173 (use-local-map map)
15174 (setq org-read-date-inactive inactive)
15175 (add-hook 'post-command-hook 'org-read-date-display)
15176 (setq org-ans0 (read-string prompt default-input
15177 'org-read-date-history nil))
15178 ;; org-ans0: from prompt
15179 ;; org-ans1: from mouse click
15180 ;; org-ans2: from calendar motion
15181 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15182 (remove-hook 'post-command-hook 'org-read-date-display)
15183 (use-local-map old-map)
15184 (when org-read-date-overlay
15185 (delete-overlay org-read-date-overlay)
15186 (setq org-read-date-overlay nil)))))
15187 (bury-buffer "*Calendar*")))))
15189 (t ; Naked prompt only
15190 (unwind-protect
15191 (setq ans (read-string prompt default-input
15192 'org-read-date-history timestr))
15193 (when org-read-date-overlay
15194 (delete-overlay org-read-date-overlay)
15195 (setq org-read-date-overlay nil)))))
15197 (setq final (org-read-date-analyze ans org-def org-defdecode))
15199 (when org-read-date-analyze-forced-year
15200 (message "Year was forced into %s"
15201 (if org-read-date-force-compatible-dates
15202 "compatible range (1970-2037)"
15203 "range representable on this machine"))
15204 (ding))
15206 ;; One round trip to get rid of 34th of August and stuff like that....
15207 (setq final (decode-time (apply 'encode-time final)))
15209 (setq org-read-date-final-answer ans)
15211 (if to-time
15212 (apply 'encode-time final)
15213 (if (and (boundp 'org-time-was-given) org-time-was-given)
15214 (format "%04d-%02d-%02d %02d:%02d"
15215 (nth 5 final) (nth 4 final) (nth 3 final)
15216 (nth 2 final) (nth 1 final))
15217 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15219 (defvar org-def)
15220 (defvar org-defdecode)
15221 (defvar org-with-time)
15222 (defun org-read-date-display ()
15223 "Display the current date prompt interpretation in the minibuffer."
15224 (when org-read-date-display-live
15225 (when org-read-date-overlay
15226 (delete-overlay org-read-date-overlay))
15227 (let ((p (point)))
15228 (end-of-line 1)
15229 (while (not (equal (buffer-substring
15230 (max (point-min) (- (point) 4)) (point))
15231 " "))
15232 (insert " "))
15233 (goto-char p))
15234 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15235 " " (or org-ans1 org-ans2)))
15236 (org-end-time-was-given nil)
15237 (f (org-read-date-analyze ans org-def org-defdecode))
15238 (fmts (if org-dcst
15239 org-time-stamp-custom-formats
15240 org-time-stamp-formats))
15241 (fmt (if (or org-with-time
15242 (and (boundp 'org-time-was-given) org-time-was-given))
15243 (cdr fmts)
15244 (car fmts)))
15245 (txt (format-time-string fmt (apply 'encode-time f)))
15246 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15247 (txt (concat "=> " txt)))
15248 (when (and org-end-time-was-given
15249 (string-match org-plain-time-of-day-regexp txt))
15250 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15251 org-end-time-was-given
15252 (substring txt (match-end 0)))))
15253 (when org-read-date-analyze-futurep
15254 (setq txt (concat txt " (=>F)")))
15255 (setq org-read-date-overlay
15256 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15257 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15259 (defun org-read-date-analyze (ans org-def org-defdecode)
15260 "Analyze the combined answer of the date prompt."
15261 ;; FIXME: cleanup and comment
15262 (let ((nowdecode (decode-time (current-time)))
15263 delta deltan deltaw deltadef year month day
15264 hour minute second wday pm h2 m2 tl wday1
15265 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15266 (setq org-read-date-analyze-futurep nil
15267 org-read-date-analyze-forced-year nil)
15268 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15269 (setq ans "+0"))
15271 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15272 (setq ans (replace-match "" t t ans)
15273 deltan (car delta)
15274 deltaw (nth 1 delta)
15275 deltadef (nth 2 delta)))
15277 ;; Check if there is an iso week date in there
15278 ;; If yes, store the info and postpone interpreting it until the rest
15279 ;; of the parsing is done
15280 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15281 (setq iso-year (if (match-end 1)
15282 (org-small-year-to-year
15283 (string-to-number (match-string 1 ans))))
15284 iso-weekday (if (match-end 3)
15285 (string-to-number (match-string 3 ans)))
15286 iso-week (string-to-number (match-string 2 ans)))
15287 (setq ans (replace-match "" t t ans)))
15289 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15290 (when (string-match
15291 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15292 (setq year (if (match-end 2)
15293 (string-to-number (match-string 2 ans))
15294 (progn (setq kill-year t)
15295 (string-to-number (format-time-string "%Y"))))
15296 month (string-to-number (match-string 3 ans))
15297 day (string-to-number (match-string 4 ans)))
15298 (if (< year 100) (setq year (+ 2000 year)))
15299 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15300 t nil ans)))
15302 ;; Help matching dotted european dates
15303 (when (string-match
15304 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15305 (setq year (if (match-end 3)
15306 (string-to-number (match-string 3 ans))
15307 (progn (setq kill-year t)
15308 (string-to-number (format-time-string "%Y"))))
15309 day (string-to-number (match-string 1 ans))
15310 month (string-to-number (match-string 2 ans))
15311 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15312 t nil ans)))
15314 ;; Help matching american dates, like 5/30 or 5/30/7
15315 (when (string-match
15316 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15317 (setq year (if (match-end 4)
15318 (string-to-number (match-string 4 ans))
15319 (progn (setq kill-year t)
15320 (string-to-number (format-time-string "%Y"))))
15321 month (string-to-number (match-string 1 ans))
15322 day (string-to-number (match-string 2 ans)))
15323 (if (< year 100) (setq year (+ 2000 year)))
15324 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15325 t nil ans)))
15326 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15327 ;; If there is a time with am/pm, and *no* time without it, we convert
15328 ;; so that matching will be successful.
15329 (loop for i from 1 to 2 do ; twice, for end time as well
15330 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15331 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15332 (setq hour (string-to-number (match-string 1 ans))
15333 minute (if (match-end 3)
15334 (string-to-number (match-string 3 ans))
15336 pm (equal ?p
15337 (string-to-char (downcase (match-string 4 ans)))))
15338 (if (and (= hour 12) (not pm))
15339 (setq hour 0)
15340 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15341 (setq ans (replace-match (format "%02d:%02d" hour minute)
15342 t t ans))))
15344 ;; Check if a time range is given as a duration
15345 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15346 (setq hour (string-to-number (match-string 1 ans))
15347 h2 (+ hour (string-to-number (match-string 3 ans)))
15348 minute (string-to-number (match-string 2 ans))
15349 m2 (+ minute (if (match-end 5) (string-to-number
15350 (match-string 5 ans))0)))
15351 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15352 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15353 t t ans)))
15355 ;; Check if there is a time range
15356 (when (boundp 'org-end-time-was-given)
15357 (setq org-time-was-given nil)
15358 (when (and (string-match org-plain-time-of-day-regexp ans)
15359 (match-end 8))
15360 (setq org-end-time-was-given (match-string 8 ans))
15361 (setq ans (concat (substring ans 0 (match-beginning 7))
15362 (substring ans (match-end 7))))))
15364 (setq tl (parse-time-string ans)
15365 day (or (nth 3 tl) (nth 3 org-defdecode))
15366 month (or (nth 4 tl)
15367 (if (and org-read-date-prefer-future
15368 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15369 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15370 (nth 4 org-defdecode)))
15371 year (or (and (not kill-year) (nth 5 tl))
15372 (if (and org-read-date-prefer-future
15373 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15374 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15375 (nth 5 org-defdecode)))
15376 hour (or (nth 2 tl) (nth 2 org-defdecode))
15377 minute (or (nth 1 tl) (nth 1 org-defdecode))
15378 second (or (nth 0 tl) 0)
15379 wday (nth 6 tl))
15381 (when (and (eq org-read-date-prefer-future 'time)
15382 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15383 (equal day (nth 3 nowdecode))
15384 (equal month (nth 4 nowdecode))
15385 (equal year (nth 5 nowdecode))
15386 (nth 2 tl)
15387 (or (< (nth 2 tl) (nth 2 nowdecode))
15388 (and (= (nth 2 tl) (nth 2 nowdecode))
15389 (nth 1 tl)
15390 (< (nth 1 tl) (nth 1 nowdecode)))))
15391 (setq day (1+ day)
15392 futurep t))
15394 ;; Special date definitions below
15395 (cond
15396 (iso-week
15397 ;; There was an iso week
15398 (require 'cal-iso)
15399 (setq futurep nil)
15400 (setq year (or iso-year year)
15401 day (or iso-weekday wday 1)
15402 wday nil ; to make sure that the trigger below does not match
15403 iso-date (calendar-gregorian-from-absolute
15404 (calendar-absolute-from-iso
15405 (list iso-week day year))))
15406 ; FIXME: Should we also push ISO weeks into the future?
15407 ; (when (and org-read-date-prefer-future
15408 ; (not iso-year)
15409 ; (< (calendar-absolute-from-gregorian iso-date)
15410 ; (time-to-days (current-time))))
15411 ; (setq year (1+ year)
15412 ; iso-date (calendar-gregorian-from-absolute
15413 ; (calendar-absolute-from-iso
15414 ; (list iso-week day year)))))
15415 (setq month (car iso-date)
15416 year (nth 2 iso-date)
15417 day (nth 1 iso-date)))
15418 (deltan
15419 (setq futurep nil)
15420 (unless deltadef
15421 (let ((now (decode-time (current-time))))
15422 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15423 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15424 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15425 ((equal deltaw "m") (setq month (+ month deltan)))
15426 ((equal deltaw "y") (setq year (+ year deltan)))))
15427 ((and wday (not (nth 3 tl)))
15428 (setq futurep nil)
15429 ;; Weekday was given, but no day, so pick that day in the week
15430 ;; on or after the derived date.
15431 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15432 (unless (equal wday wday1)
15433 (setq day (+ day (% (- wday wday1 -7) 7))))))
15434 (if (and (boundp 'org-time-was-given)
15435 (nth 2 tl))
15436 (setq org-time-was-given t))
15437 (if (< year 100) (setq year (+ 2000 year)))
15438 ;; Check of the date is representable
15439 (if org-read-date-force-compatible-dates
15440 (progn
15441 (if (< year 1970)
15442 (setq year 1970 org-read-date-analyze-forced-year t))
15443 (if (> year 2037)
15444 (setq year 2037 org-read-date-analyze-forced-year t)))
15445 (condition-case nil
15446 (ignore (encode-time second minute hour day month year))
15447 (error
15448 (setq year (nth 5 org-defdecode))
15449 (setq org-read-date-analyze-forced-year t))))
15450 (setq org-read-date-analyze-futurep futurep)
15451 (list second minute hour day month year)))
15453 (defvar parse-time-weekdays)
15454 (defun org-read-date-get-relative (s today default)
15455 "Check string S for special relative date string.
15456 TODAY and DEFAULT are internal times, for today and for a default.
15457 Return shift list (N what def-flag)
15458 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15459 N is the number of WHATs to shift.
15460 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15461 the DEFAULT date rather than TODAY."
15462 (require 'parse-time)
15463 (when (and
15464 (string-match
15465 (concat
15466 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15467 "\\([0-9]+\\)?"
15468 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15469 "\\([ \t]\\|$\\)") s)
15470 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15471 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15472 (string-to-char (substring (match-string 1 s) -1))
15473 ?+))
15474 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15475 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15476 (what (if (match-end 3) (match-string 3 s) "d"))
15477 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15478 (date (if rel default today))
15479 (wday (nth 6 (decode-time date)))
15480 delta)
15481 (if wday1
15482 (progn
15483 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15484 (if (= dir ?-) (setq delta (- delta 7)))
15485 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15486 (list delta "d" rel))
15487 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15489 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15490 "Turn a user-specified date into the internal representation.
15491 The internal representation needed by the calendar is (month day year).
15492 This is a wrapper to handle the brain-dead convention in calendar that
15493 user function argument order change dependent on argument order."
15494 (if (boundp 'calendar-date-style)
15495 (cond
15496 ((eq calendar-date-style 'american)
15497 (list arg1 arg2 arg3))
15498 ((eq calendar-date-style 'european)
15499 (list arg2 arg1 arg3))
15500 ((eq calendar-date-style 'iso)
15501 (list arg2 arg3 arg1)))
15502 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15503 (if (org-bound-and-true-p european-calendar-style)
15504 (list arg2 arg1 arg3)
15505 (list arg1 arg2 arg3)))))
15507 (defun org-eval-in-calendar (form &optional keepdate)
15508 "Eval FORM in the calendar window and return to current window.
15509 Also, store the cursor date in variable org-ans2."
15510 (let ((sf (selected-frame))
15511 (sw (selected-window)))
15512 (select-window (get-buffer-window "*Calendar*" t))
15513 (eval form)
15514 (when (and (not keepdate) (calendar-cursor-to-date))
15515 (let* ((date (calendar-cursor-to-date))
15516 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15517 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15518 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15519 (select-window sw)
15520 (org-select-frame-set-input-focus sf)))
15522 (defun org-calendar-select ()
15523 "Return to `org-read-date' with the date currently selected.
15524 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15525 (interactive)
15526 (when (calendar-cursor-to-date)
15527 (let* ((date (calendar-cursor-to-date))
15528 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15529 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15530 (if (active-minibuffer-window) (exit-minibuffer))))
15532 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15533 "Insert a date stamp for the date given by the internal TIME.
15534 WITH-HM means use the stamp format that includes the time of the day.
15535 INACTIVE means use square brackets instead of angular ones, so that the
15536 stamp will not contribute to the agenda.
15537 PRE and POST are optional strings to be inserted before and after the
15538 stamp.
15539 The command returns the inserted time stamp."
15540 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15541 stamp)
15542 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15543 (insert-before-markers (or pre ""))
15544 (when (listp extra)
15545 (setq extra (car extra))
15546 (if (and (stringp extra)
15547 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15548 (setq extra (format "-%02d:%02d"
15549 (string-to-number (match-string 1 extra))
15550 (string-to-number (match-string 2 extra))))
15551 (setq extra nil)))
15552 (when extra
15553 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15554 (insert-before-markers (setq stamp (format-time-string fmt time)))
15555 (insert-before-markers (or post ""))
15556 (setq org-last-inserted-timestamp stamp)))
15558 (defun org-toggle-time-stamp-overlays ()
15559 "Toggle the use of custom time stamp formats."
15560 (interactive)
15561 (setq org-display-custom-times (not org-display-custom-times))
15562 (unless org-display-custom-times
15563 (let ((p (point-min)) (bmp (buffer-modified-p)))
15564 (while (setq p (next-single-property-change p 'display))
15565 (if (and (get-text-property p 'display)
15566 (eq (get-text-property p 'face) 'org-date))
15567 (remove-text-properties
15568 p (setq p (next-single-property-change p 'display))
15569 '(display t))))
15570 (set-buffer-modified-p bmp)))
15571 (if (featurep 'xemacs)
15572 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15573 (org-restart-font-lock)
15574 (setq org-table-may-need-update t)
15575 (if org-display-custom-times
15576 (message "Time stamps are overlaid with custom format")
15577 (message "Time stamp overlays removed")))
15579 (defun org-display-custom-time (beg end)
15580 "Overlay modified time stamp format over timestamp between BEG and END."
15581 (let* ((ts (buffer-substring beg end))
15582 t1 w1 with-hm tf time str w2 (off 0))
15583 (save-match-data
15584 (setq t1 (org-parse-time-string ts t))
15585 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15586 (setq off (- (match-end 0) (match-beginning 0)))))
15587 (setq end (- end off))
15588 (setq w1 (- end beg)
15589 with-hm (and (nth 1 t1) (nth 2 t1))
15590 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15591 time (org-fix-decoded-time t1)
15592 str (org-add-props
15593 (format-time-string
15594 (substring tf 1 -1) (apply 'encode-time time))
15595 nil 'mouse-face 'highlight)
15596 w2 (length str))
15597 (if (not (= w2 w1))
15598 (add-text-properties (1+ beg) (+ 2 beg)
15599 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15600 (if (featurep 'xemacs)
15601 (progn
15602 (put-text-property beg end 'invisible t)
15603 (put-text-property beg end 'end-glyph (make-glyph str)))
15604 (put-text-property beg end 'display str))))
15606 (defun org-translate-time (string)
15607 "Translate all timestamps in STRING to custom format.
15608 But do this only if the variable `org-display-custom-times' is set."
15609 (when org-display-custom-times
15610 (save-match-data
15611 (let* ((start 0)
15612 (re org-ts-regexp-both)
15613 t1 with-hm inactive tf time str beg end)
15614 (while (setq start (string-match re string start))
15615 (setq beg (match-beginning 0)
15616 end (match-end 0)
15617 t1 (save-match-data
15618 (org-parse-time-string (substring string beg end) t))
15619 with-hm (and (nth 1 t1) (nth 2 t1))
15620 inactive (equal (substring string beg (1+ beg)) "[")
15621 tf (funcall (if with-hm 'cdr 'car)
15622 org-time-stamp-custom-formats)
15623 time (org-fix-decoded-time t1)
15624 str (format-time-string
15625 (concat
15626 (if inactive "[" "<") (substring tf 1 -1)
15627 (if inactive "]" ">"))
15628 (apply 'encode-time time))
15629 string (replace-match str t t string)
15630 start (+ start (length str)))))))
15631 string)
15633 (defun org-fix-decoded-time (time)
15634 "Set 0 instead of nil for the first 6 elements of time.
15635 Don't touch the rest."
15636 (let ((n 0))
15637 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15639 (defun org-days-to-time (timestamp-string)
15640 "Difference between TIMESTAMP-STRING and now in days."
15641 (- (time-to-days (org-time-string-to-time timestamp-string))
15642 (time-to-days (current-time))))
15644 (defun org-deadline-close (timestamp-string &optional ndays)
15645 "Is the time in TIMESTAMP-STRING close to the current date?"
15646 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15647 (and (< (org-days-to-time timestamp-string) ndays)
15648 (not (org-entry-is-done-p))))
15650 (defun org-get-wdays (ts)
15651 "Get the deadline lead time appropriate for timestring TS."
15652 (cond
15653 ((<= org-deadline-warning-days 0)
15654 ;; 0 or negative, enforce this value no matter what
15655 (- org-deadline-warning-days))
15656 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15657 ;; lead time is specified.
15658 (floor (* (string-to-number (match-string 1 ts))
15659 (cdr (assoc (match-string 2 ts)
15660 '(("d" . 1) ("w" . 7)
15661 ("m" . 30.4) ("y" . 365.25)))))))
15662 ;; go for the default.
15663 (t org-deadline-warning-days)))
15665 (defun org-calendar-select-mouse (ev)
15666 "Return to `org-read-date' with the date currently selected.
15667 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15668 (interactive "e")
15669 (mouse-set-point ev)
15670 (when (calendar-cursor-to-date)
15671 (let* ((date (calendar-cursor-to-date))
15672 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15673 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15674 (if (active-minibuffer-window) (exit-minibuffer))))
15676 (defun org-check-deadlines (ndays)
15677 "Check if there are any deadlines due or past due.
15678 A deadline is considered due if it happens within `org-deadline-warning-days'
15679 days from today's date. If the deadline appears in an entry marked DONE,
15680 it is not shown. The prefix arg NDAYS can be used to test that many
15681 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15682 (interactive "P")
15683 (let* ((org-warn-days
15684 (cond
15685 ((equal ndays '(4)) 100000)
15686 (ndays (prefix-numeric-value ndays))
15687 (t (abs org-deadline-warning-days))))
15688 (case-fold-search nil)
15689 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15690 (callback
15691 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15693 (message "%d deadlines past-due or due within %d days"
15694 (org-occur regexp nil callback)
15695 org-warn-days)))
15697 (defun org-check-before-date (date)
15698 "Check if there are deadlines or scheduled entries before DATE."
15699 (interactive (list (org-read-date)))
15700 (let ((case-fold-search nil)
15701 (regexp (concat "\\<\\(" org-deadline-string
15702 "\\|" org-scheduled-string
15703 "\\) *<\\([^>]+\\)>"))
15704 (callback
15705 (lambda () (time-less-p
15706 (org-time-string-to-time (match-string 2))
15707 (org-time-string-to-time date)))))
15708 (message "%d entries before %s"
15709 (org-occur regexp nil callback) date)))
15711 (defun org-check-after-date (date)
15712 "Check if there are deadlines or scheduled entries after DATE."
15713 (interactive (list (org-read-date)))
15714 (let ((case-fold-search nil)
15715 (regexp (concat "\\<\\(" org-deadline-string
15716 "\\|" org-scheduled-string
15717 "\\) *<\\([^>]+\\)>"))
15718 (callback
15719 (lambda () (not
15720 (time-less-p
15721 (org-time-string-to-time (match-string 2))
15722 (org-time-string-to-time date))))))
15723 (message "%d entries after %s"
15724 (org-occur regexp nil callback) date)))
15726 (defun org-check-dates-range (start-date end-date)
15727 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15728 (interactive (list (org-read-date nil nil nil "Range starts")
15729 (org-read-date nil nil nil "Range end")))
15730 (let ((case-fold-search nil)
15731 (regexp (concat "\\<\\(" org-deadline-string
15732 "\\|" org-scheduled-string
15733 "\\) *<\\([^>]+\\)>"))
15734 (callback
15735 (lambda ()
15736 (let ((match (match-string 2)))
15737 (and
15738 (not (time-less-p
15739 (org-time-string-to-time match)
15740 (org-time-string-to-time start-date)))
15741 (time-less-p
15742 (org-time-string-to-time match)
15743 (org-time-string-to-time end-date)))))))
15744 (message "%d entries between %s and %s"
15745 (org-occur regexp nil callback) start-date end-date)))
15747 (defun org-evaluate-time-range (&optional to-buffer)
15748 "Evaluate a time range by computing the difference between start and end.
15749 Normally the result is just printed in the echo area, but with prefix arg
15750 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15751 If the time range is actually in a table, the result is inserted into the
15752 next column.
15753 For time difference computation, a year is assumed to be exactly 365
15754 days in order to avoid rounding problems."
15755 (interactive "P")
15757 (org-clock-update-time-maybe)
15758 (save-excursion
15759 (unless (org-at-date-range-p t)
15760 (goto-char (point-at-bol))
15761 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15762 (if (not (org-at-date-range-p t))
15763 (error "Not at a time-stamp range, and none found in current line")))
15764 (let* ((ts1 (match-string 1))
15765 (ts2 (match-string 2))
15766 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15767 (match-end (match-end 0))
15768 (time1 (org-time-string-to-time ts1))
15769 (time2 (org-time-string-to-time ts2))
15770 (t1 (org-float-time time1))
15771 (t2 (org-float-time time2))
15772 (diff (abs (- t2 t1)))
15773 (negative (< (- t2 t1) 0))
15774 ;; (ys (floor (* 365 24 60 60)))
15775 (ds (* 24 60 60))
15776 (hs (* 60 60))
15777 (fy "%dy %dd %02d:%02d")
15778 (fy1 "%dy %dd")
15779 (fd "%dd %02d:%02d")
15780 (fd1 "%dd")
15781 (fh "%02d:%02d")
15782 y d h m align)
15783 (if havetime
15784 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15786 d (floor (/ diff ds)) diff (mod diff ds)
15787 h (floor (/ diff hs)) diff (mod diff hs)
15788 m (floor (/ diff 60)))
15789 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15791 d (floor (+ (/ diff ds) 0.5))
15792 h 0 m 0))
15793 (if (not to-buffer)
15794 (message "%s" (org-make-tdiff-string y d h m))
15795 (if (org-at-table-p)
15796 (progn
15797 (goto-char match-end)
15798 (setq align t)
15799 (and (looking-at " *|") (goto-char (match-end 0))))
15800 (goto-char match-end))
15801 (if (looking-at
15802 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15803 (replace-match ""))
15804 (if negative (insert " -"))
15805 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15806 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15807 (insert " " (format fh h m))))
15808 (if align (org-table-align))
15809 (message "Time difference inserted")))))
15811 (defun org-make-tdiff-string (y d h m)
15812 (let ((fmt "")
15813 (l nil))
15814 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15815 l (push y l)))
15816 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15817 l (push d l)))
15818 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15819 l (push h l)))
15820 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15821 l (push m l)))
15822 (apply 'format fmt (nreverse l))))
15824 (defun org-time-string-to-time (s &optional buffer pos)
15825 (condition-case errdata
15826 (apply 'encode-time (org-parse-time-string s))
15827 (error (error "Bad timestamp `%s'%s\nError was: %s"
15828 s (if (not (and buffer pos))
15830 (format " at %d in buffer `%s'" pos buffer))
15831 (cdr errdata)))))
15833 (defun org-time-string-to-seconds (s)
15834 (org-float-time (org-time-string-to-time s)))
15836 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15837 "Convert a time stamp to an absolute day number.
15838 If there is a specifier for a cyclic time stamp, get the closest date to
15839 DAYNR.
15840 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15841 The variable date is bound by the calendar when this is called."
15842 (cond
15843 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15844 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15845 daynr
15846 (+ daynr 1000)))
15847 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15848 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15849 (time-to-days (current-time))) (match-string 0 s)
15850 prefer show-all))
15851 (t (time-to-days
15852 (condition-case errdata
15853 (apply 'encode-time (org-parse-time-string s))
15854 (error (error "Bad timestamp `%s'%s\nError was: %s"
15855 s (if (not (and buffer pos))
15857 (format " at %d in buffer `%s'" pos buffer))
15858 (cdr errdata))))))))
15860 (defun org-days-to-iso-week (days)
15861 "Return the iso week number."
15862 (require 'cal-iso)
15863 (car (calendar-iso-from-absolute days)))
15865 (defun org-small-year-to-year (year)
15866 "Convert 2-digit years into 4-digit years.
15867 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15868 The year 2000 cannot be abbreviated. Any year larger than 99
15869 is returned unchanged."
15870 (if (< year 38)
15871 (setq year (+ 2000 year))
15872 (if (< year 100)
15873 (setq year (+ 1900 year))))
15874 year)
15876 (defun org-time-from-absolute (d)
15877 "Return the time corresponding to date D.
15878 D may be an absolute day number, or a calendar-type list (month day year)."
15879 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15880 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15882 (defun org-calendar-holiday ()
15883 "List of holidays, for Diary display in Org-mode."
15884 (require 'holidays)
15885 (let ((hl (funcall
15886 (if (fboundp 'calendar-check-holidays)
15887 'calendar-check-holidays 'check-calendar-holidays) date)))
15888 (if hl (mapconcat 'identity hl "; "))))
15890 (defun org-diary-sexp-entry (sexp entry date)
15891 "Process a SEXP diary ENTRY for DATE."
15892 (require 'diary-lib)
15893 (let ((result (if calendar-debug-sexp
15894 (let ((stack-trace-on-error t))
15895 (eval (car (read-from-string sexp))))
15896 (condition-case nil
15897 (eval (car (read-from-string sexp)))
15898 (error
15899 (beep)
15900 (message "Bad sexp at line %d in %s: %s"
15901 (org-current-line)
15902 (buffer-file-name) sexp)
15903 (sleep-for 2))))))
15904 (cond ((stringp result) (split-string result "; "))
15905 ((and (consp result)
15906 (not (consp (cdr result)))
15907 (stringp (cdr result))) (cdr result))
15908 ((and (consp result)
15909 (stringp (car result))) result)
15910 (result entry)
15911 (t nil))))
15913 (defun org-diary-to-ical-string (frombuf)
15914 "Get iCalendar entries from diary entries in buffer FROMBUF.
15915 This uses the icalendar.el library."
15916 (let* ((tmpdir (if (featurep 'xemacs)
15917 (temp-directory)
15918 temporary-file-directory))
15919 (tmpfile (make-temp-name
15920 (expand-file-name "orgics" tmpdir)))
15921 buf rtn b e)
15922 (with-current-buffer frombuf
15923 (icalendar-export-region (point-min) (point-max) tmpfile)
15924 (setq buf (find-buffer-visiting tmpfile))
15925 (set-buffer buf)
15926 (goto-char (point-min))
15927 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15928 (setq b (match-beginning 0)))
15929 (goto-char (point-max))
15930 (if (re-search-backward "^END:VEVENT" nil t)
15931 (setq e (match-end 0)))
15932 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15933 (kill-buffer buf)
15934 (delete-file tmpfile)
15935 rtn))
15937 (defun org-closest-date (start current change prefer show-all)
15938 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15939 When PREFER is `past', return a date that is either CURRENT or past.
15940 When PREFER is `future', return a date that is either CURRENT or future.
15941 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15942 ;; Make the proper lists from the dates
15943 (catch 'exit
15944 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15945 dn dw sday cday n1 n2 n0
15946 d m y y1 y2 date1 date2 nmonths nm ny m2)
15948 (setq start (org-date-to-gregorian start)
15949 current (org-date-to-gregorian
15950 (if show-all
15951 current
15952 (time-to-days (current-time))))
15953 sday (calendar-absolute-from-gregorian start)
15954 cday (calendar-absolute-from-gregorian current))
15956 (if (<= cday sday) (throw 'exit sday))
15958 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15959 (setq dn (string-to-number (match-string 1 change))
15960 dw (cdr (assoc (match-string 2 change) a1)))
15961 (error "Invalid change specifier: %s" change))
15962 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15963 (cond
15964 ((eq dw 'day)
15965 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15966 n2 (+ n1 dn)))
15967 ((eq dw 'year)
15968 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15969 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15970 (setq date1 (list m d y1)
15971 n1 (calendar-absolute-from-gregorian date1)
15972 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15973 n2 (calendar-absolute-from-gregorian date2)))
15974 ((eq dw 'month)
15975 ;; approx number of month between the two dates
15976 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15977 ;; How often does dn fit in there?
15978 (setq d (nth 1 start) m (car start) y (nth 2 start)
15979 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15980 m (+ m nm)
15981 ny (floor (/ m 12))
15982 y (+ y ny)
15983 m (- m (* ny 12)))
15984 (while (> m 12) (setq m (- m 12) y (1+ y)))
15985 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15986 (setq m2 (+ m dn) y2 y)
15987 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15988 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15989 (while (<= n2 cday)
15990 (setq n1 n2 m m2 y y2)
15991 (setq m2 (+ m dn) y2 y)
15992 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15993 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15994 ;; Make sure n1 is the earlier date
15995 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15996 (if show-all
15997 (cond
15998 ((eq prefer 'past) (if (= cday n2) n2 n1))
15999 ((eq prefer 'future) (if (= cday n1) n1 n2))
16000 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16001 (cond
16002 ((eq prefer 'past) (if (= cday n2) n2 n1))
16003 ((eq prefer 'future) (if (= cday n1) n1 n2))
16004 (t (if (= cday n1) n1 n2)))))))
16006 (defun org-date-to-gregorian (date)
16007 "Turn any specification of DATE into a Gregorian date for the calendar."
16008 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16009 ((and (listp date) (= (length date) 3)) date)
16010 ((stringp date)
16011 (setq date (org-parse-time-string date))
16012 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16013 ((listp date)
16014 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16016 (defun org-parse-time-string (s &optional nodefault)
16017 "Parse the standard Org-mode time string.
16018 This should be a lot faster than the normal `parse-time-string'.
16019 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16020 hour and minute fields will be nil if not given."
16021 (if (string-match org-ts-regexp0 s)
16022 (list 0
16023 (if (or (match-beginning 8) (not nodefault))
16024 (string-to-number (or (match-string 8 s) "0")))
16025 (if (or (match-beginning 7) (not nodefault))
16026 (string-to-number (or (match-string 7 s) "0")))
16027 (string-to-number (match-string 4 s))
16028 (string-to-number (match-string 3 s))
16029 (string-to-number (match-string 2 s))
16030 nil nil nil)
16031 (error "Not a standard Org-mode time string: %s" s)))
16033 (defun org-timestamp-up (&optional arg)
16034 "Increase the date item at the cursor by one.
16035 If the cursor is on the year, change the year. If it is on the month,
16036 the day or the time, change that.
16037 With prefix ARG, change by that many units."
16038 (interactive "p")
16039 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16041 (defun org-timestamp-down (&optional arg)
16042 "Decrease the date item at the cursor by one.
16043 If the cursor is on the year, change the year. If it is on the month,
16044 the day or the time, change that.
16045 With prefix ARG, change by that many units."
16046 (interactive "p")
16047 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16049 (defun org-timestamp-up-day (&optional arg)
16050 "Increase the date in the time stamp by one day.
16051 With prefix ARG, change that many days."
16052 (interactive "p")
16053 (if (and (not (org-at-timestamp-p t))
16054 (org-at-heading-p))
16055 (org-todo 'up)
16056 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16058 (defun org-timestamp-down-day (&optional arg)
16059 "Decrease the date in the time stamp by one day.
16060 With prefix ARG, change that many days."
16061 (interactive "p")
16062 (if (and (not (org-at-timestamp-p t))
16063 (org-at-heading-p))
16064 (org-todo 'down)
16065 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16067 (defun org-at-timestamp-p (&optional inactive-ok)
16068 "Determine if the cursor is in or at a timestamp."
16069 (interactive)
16070 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16071 (pos (point))
16072 (ans (or (looking-at tsr)
16073 (save-excursion
16074 (skip-chars-backward "^[<\n\r\t")
16075 (if (> (point) (point-min)) (backward-char 1))
16076 (and (looking-at tsr)
16077 (> (- (match-end 0) pos) -1))))))
16078 (and ans
16079 (boundp 'org-ts-what)
16080 (setq org-ts-what
16081 (cond
16082 ((= pos (match-beginning 0)) 'bracket)
16083 ;; Point is considered to be "on the bracket" whether
16084 ;; it's really on it or right after it.
16085 ((or (= pos (1- (match-end 0)))
16086 (= pos (match-end 0))) 'bracket)
16087 ((org-pos-in-match-range pos 2) 'year)
16088 ((org-pos-in-match-range pos 3) 'month)
16089 ((org-pos-in-match-range pos 7) 'hour)
16090 ((org-pos-in-match-range pos 8) 'minute)
16091 ((or (org-pos-in-match-range pos 4)
16092 (org-pos-in-match-range pos 5)) 'day)
16093 ((and (> pos (or (match-end 8) (match-end 5)))
16094 (< pos (match-end 0)))
16095 (- pos (or (match-end 8) (match-end 5))))
16096 (t 'day))))
16097 ans))
16099 (defun org-toggle-timestamp-type ()
16100 "Toggle the type (<active> or [inactive]) of a time stamp."
16101 (interactive)
16102 (when (org-at-timestamp-p t)
16103 (let ((beg (match-beginning 0)) (end (match-end 0))
16104 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16105 (save-excursion
16106 (goto-char beg)
16107 (while (re-search-forward "[][<>]" end t)
16108 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16109 t t)))
16110 (message "Timestamp is now %sactive"
16111 (if (equal (char-after beg) ?<) "" "in")))))
16113 (defun org-timestamp-change (n &optional what updown)
16114 "Change the date in the time stamp at point.
16115 The date will be changed by N times WHAT. WHAT can be `day', `month',
16116 `year', `minute', `second'. If WHAT is not given, the cursor position
16117 in the timestamp determines what will be changed."
16118 (let ((origin (point)) origin-cat
16119 with-hm inactive
16120 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16121 org-ts-what
16122 extra rem
16123 ts time time0)
16124 (if (not (org-at-timestamp-p t))
16125 (error "Not at a timestamp"))
16126 (if (and (not what) (eq org-ts-what 'bracket))
16127 (org-toggle-timestamp-type)
16128 ;; Point isn't on brackets. Remember the part of the time-stamp
16129 ;; the point was in. Indeed, size of time-stamps may change,
16130 ;; but point must be kept in the same category nonetheless.
16131 (setq origin-cat org-ts-what)
16132 (if (and (not what) (not (eq org-ts-what 'day))
16133 org-display-custom-times
16134 (get-text-property (point) 'display)
16135 (not (get-text-property (1- (point)) 'display)))
16136 (setq org-ts-what 'day))
16137 (setq org-ts-what (or what org-ts-what)
16138 inactive (= (char-after (match-beginning 0)) ?\[)
16139 ts (match-string 0))
16140 (replace-match "")
16141 (if (string-match
16142 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16144 (setq extra (match-string 1 ts)))
16145 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16146 (setq with-hm t))
16147 (setq time0 (org-parse-time-string ts))
16148 (when (and updown
16149 (eq org-ts-what 'minute)
16150 (not current-prefix-arg))
16151 ;; This looks like s-up and s-down. Change by one rounding step.
16152 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16153 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16154 (setcar (cdr time0) (+ (nth 1 time0)
16155 (if (> n 0) (- rem) (- dm rem))))))
16156 (setq time
16157 (encode-time (or (car time0) 0)
16158 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16159 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16160 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16161 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16162 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16163 (nthcdr 6 time0)))
16164 (when (and (member org-ts-what '(hour minute))
16165 extra
16166 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16167 (setq extra (org-modify-ts-extra
16168 extra
16169 (if (eq org-ts-what 'hour) 2 5)
16170 n dm)))
16171 (when (integerp org-ts-what)
16172 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16173 (if (eq what 'calendar)
16174 (let ((cal-date (org-get-date-from-calendar)))
16175 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16176 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16177 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16178 (setcar time0 (or (car time0) 0))
16179 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16180 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16181 (setq time (apply 'encode-time time0))))
16182 ;; Insert the new time-stamp, and ensure point stays in the same
16183 ;; category as before (i.e. not after the last position in that
16184 ;; category).
16185 (let ((pos (point)))
16186 ;; Stay before inserted string. `save-excursion' is of no use.
16187 (setq org-last-changed-timestamp
16188 (org-insert-time-stamp time with-hm inactive nil nil extra))
16189 (goto-char pos))
16190 (save-match-data
16191 (looking-at org-ts-regexp3)
16192 (goto-char (cond
16193 ;; `day' category ends before `hour' if any, or at
16194 ;; the end of the day name.
16195 ((eq origin-cat 'day)
16196 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16197 ((eq origin-cat 'hour) (min (match-end 7) origin))
16198 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16199 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16200 ;; `year' and `month' have both fixed size: point
16201 ;; couldn't have moved into another part.
16202 (t origin))))
16203 ;; Update clock if on a CLOCK line.
16204 (org-clock-update-time-maybe)
16205 ;; Try to recenter the calendar window, if any.
16206 (if (and org-calendar-follow-timestamp-change
16207 (get-buffer-window "*Calendar*" t)
16208 (memq org-ts-what '(day month year)))
16209 (org-recenter-calendar (time-to-days time))))))
16211 (defun org-modify-ts-extra (s pos n dm)
16212 "Change the different parts of the lead-time and repeat fields in timestamp."
16213 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16214 ng h m new rem)
16215 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16216 (cond
16217 ((or (org-pos-in-match-range pos 2)
16218 (org-pos-in-match-range pos 3))
16219 (setq m (string-to-number (match-string 3 s))
16220 h (string-to-number (match-string 2 s)))
16221 (if (org-pos-in-match-range pos 2)
16222 (setq h (+ h n))
16223 (setq n (* dm (org-no-warnings (signum n))))
16224 (when (not (= 0 (setq rem (% m dm))))
16225 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16226 (setq m (+ m n)))
16227 (if (< m 0) (setq m (+ m 60) h (1- h)))
16228 (if (> m 59) (setq m (- m 60) h (1+ h)))
16229 (setq h (min 24 (max 0 h)))
16230 (setq ng 1 new (format "-%02d:%02d" h m)))
16231 ((org-pos-in-match-range pos 6)
16232 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16233 ((org-pos-in-match-range pos 5)
16234 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16236 ((org-pos-in-match-range pos 9)
16237 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16238 ((org-pos-in-match-range pos 8)
16239 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16241 (when ng
16242 (setq s (concat
16243 (substring s 0 (match-beginning ng))
16245 (substring s (match-end ng))))))
16248 (defun org-recenter-calendar (date)
16249 "If the calendar is visible, recenter it to DATE."
16250 (let ((cwin (get-buffer-window "*Calendar*" t)))
16251 (when cwin
16252 (let ((calendar-move-hook nil))
16253 (with-selected-window cwin
16254 (calendar-goto-date (if (listp date) date
16255 (calendar-gregorian-from-absolute date))))))))
16257 (defun org-goto-calendar (&optional arg)
16258 "Go to the Emacs calendar at the current date.
16259 If there is a time stamp in the current line, go to that date.
16260 A prefix ARG can be used to force the current date."
16261 (interactive "P")
16262 (let ((tsr org-ts-regexp) diff
16263 (calendar-move-hook nil)
16264 (calendar-view-holidays-initially-flag nil)
16265 (calendar-view-diary-initially-flag nil))
16266 (if (or (org-at-timestamp-p)
16267 (save-excursion
16268 (beginning-of-line 1)
16269 (looking-at (concat ".*" tsr))))
16270 (let ((d1 (time-to-days (current-time)))
16271 (d2 (time-to-days
16272 (org-time-string-to-time (match-string 1)))))
16273 (setq diff (- d2 d1))))
16274 (calendar)
16275 (calendar-goto-today)
16276 (if (and diff (not arg)) (calendar-forward-day diff))))
16278 (defun org-get-date-from-calendar ()
16279 "Return a list (month day year) of date at point in calendar."
16280 (with-current-buffer "*Calendar*"
16281 (save-match-data
16282 (calendar-cursor-to-date))))
16284 (defun org-date-from-calendar ()
16285 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16286 If there is already a time stamp at the cursor position, update it."
16287 (interactive)
16288 (if (org-at-timestamp-p t)
16289 (org-timestamp-change 0 'calendar)
16290 (let ((cal-date (org-get-date-from-calendar)))
16291 (org-insert-time-stamp
16292 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16294 (defun org-minutes-to-hh:mm-string (m)
16295 "Compute H:MM from a number of minutes."
16296 (let ((h (/ m 60)))
16297 (setq m (- m (* 60 h)))
16298 (format org-time-clocksum-format h m)))
16300 (defun org-hh:mm-string-to-minutes (s)
16301 "Convert a string H:MM to a number of minutes.
16302 If the string is just a number, interpret it as minutes.
16303 In fact, the first hh:mm or number in the string will be taken,
16304 there can be extra stuff in the string.
16305 If no number is found, the return value is 0."
16306 (cond
16307 ((integerp s) s)
16308 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16309 (+ (* (string-to-number (match-string 1 s)) 60)
16310 (string-to-number (match-string 2 s))))
16311 ((string-match "\\([0-9]+\\)" s)
16312 (string-to-number (match-string 1 s)))
16313 (t 0)))
16315 (defcustom org-effort-durations
16316 `(("h" . 60)
16317 ("d" . ,(* 60 8))
16318 ("w" . ,(* 60 8 5))
16319 ("m" . ,(* 60 8 5 4))
16320 ("y" . ,(* 60 8 5 40)))
16321 "Conversion factor to minutes for an effort modifier.
16323 Each entry has the form (MODIFIER . MINUTES).
16325 In an effort string, a number followed by MODIFIER is multiplied
16326 by the specified number of MINUTES to obtain an effort in
16327 minutes.
16329 For example, if the value of this variable is ((\"hours\" . 60)), then an
16330 effort string \"2hours\" is equivalent to 120 minutes."
16331 :group 'org-agenda
16332 :version "24.1"
16333 :type '(alist :key-type (string :tag "Modifier")
16334 :value-type (number :tag "Minutes")))
16336 (defun org-duration-string-to-minutes (s)
16337 "Convert a duration string S to minutes.
16339 A bare number is interpreted as minutes, modifiers can be set by
16340 customizing `org-effort-durations' (which see).
16342 Entries containing a colon are interpreted as H:MM by
16343 `org-hh:mm-string-to-minutes'."
16344 (let ((result 0)
16345 (re (concat "\\([0-9]+\\) *\\("
16346 (regexp-opt (mapcar 'car org-effort-durations))
16347 "\\)")))
16348 (while (string-match re s)
16349 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16350 (string-to-number (match-string 1 s))))
16351 (setq s (replace-match "" nil t s)))
16352 (incf result (org-hh:mm-string-to-minutes s))
16353 result))
16355 ;;;; Files
16357 (defun org-save-all-org-buffers ()
16358 "Save all Org-mode buffers without user confirmation."
16359 (interactive)
16360 (message "Saving all Org-mode buffers...")
16361 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16362 (when (featurep 'org-id) (org-id-locations-save))
16363 (message "Saving all Org-mode buffers... done"))
16365 (defun org-revert-all-org-buffers ()
16366 "Revert all Org-mode buffers.
16367 Prompt for confirmation when there are unsaved changes.
16368 Be sure you know what you are doing before letting this function
16369 overwrite your changes.
16371 This function is useful in a setup where one tracks org files
16372 with a version control system, to revert on one machine after pulling
16373 changes from another. I believe the procedure must be like this:
16375 1. M-x org-save-all-org-buffers
16376 2. Pull changes from the other machine, resolve conflicts
16377 3. M-x org-revert-all-org-buffers"
16378 (interactive)
16379 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16380 (error "Abort"))
16381 (save-excursion
16382 (save-window-excursion
16383 (mapc
16384 (lambda (b)
16385 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16386 (with-current-buffer b buffer-file-name))
16387 (org-pop-to-buffer-same-window b)
16388 (revert-buffer t 'no-confirm)))
16389 (buffer-list))
16390 (when (and (featurep 'org-id) org-id-track-globally)
16391 (org-id-locations-load)))))
16393 ;;;; Agenda files
16395 ;;;###autoload
16396 (defun org-switchb (&optional arg)
16397 "Switch between Org buffers.
16398 With one prefix argument, restrict available buffers to files.
16399 With two prefix arguments, restrict available buffers to agenda files.
16401 Defaults to `iswitchb' for buffer name completion.
16402 Set `org-completion-use-ido' to make it use ido instead."
16403 (interactive "P")
16404 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16405 ((equal arg '(16)) (org-buffer-list 'agenda))
16406 (t (org-buffer-list))))
16407 (org-completion-use-iswitchb org-completion-use-iswitchb)
16408 (org-completion-use-ido org-completion-use-ido))
16409 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16410 (setq org-completion-use-iswitchb t))
16411 (org-pop-to-buffer-same-window
16412 (org-icompleting-read "Org buffer: "
16413 (mapcar 'list (mapcar 'buffer-name blist))
16414 nil t))))
16416 ;;; Define some older names previously used for this functionality
16417 ;;;###autoload
16418 (defalias 'org-ido-switchb 'org-switchb)
16419 ;;;###autoload
16420 (defalias 'org-iswitchb 'org-switchb)
16422 (defun org-buffer-list (&optional predicate exclude-tmp)
16423 "Return a list of Org buffers.
16424 PREDICATE can be `export', `files' or `agenda'.
16426 export restrict the list to Export buffers.
16427 files restrict the list to buffers visiting Org files.
16428 agenda restrict the list to buffers visiting agenda files.
16430 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16431 (let* ((bfn nil)
16432 (agenda-files (and (eq predicate 'agenda)
16433 (mapcar 'file-truename (org-agenda-files t))))
16434 (filter
16435 (cond
16436 ((eq predicate 'files)
16437 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16438 ((eq predicate 'export)
16439 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16440 ((eq predicate 'agenda)
16441 (lambda (b)
16442 (with-current-buffer b
16443 (and (eq major-mode 'org-mode)
16444 (setq bfn (buffer-file-name b))
16445 (member (file-truename bfn) agenda-files)))))
16446 (t (lambda (b) (with-current-buffer b
16447 (or (eq major-mode 'org-mode)
16448 (string-match "\*Org .*Export"
16449 (buffer-name b)))))))))
16450 (delq nil
16451 (mapcar
16452 (lambda(b)
16453 (if (and (funcall filter b)
16454 (or (not exclude-tmp)
16455 (not (string-match "tmp" (buffer-name b)))))
16457 nil))
16458 (buffer-list)))))
16460 (defun org-agenda-files (&optional unrestricted archives)
16461 "Get the list of agenda files.
16462 Optional UNRESTRICTED means return the full list even if a restriction
16463 is currently in place.
16464 When ARCHIVES is t, include all archive files that are really being
16465 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16466 `org-agenda-archives-mode' is t."
16467 (let ((files
16468 (cond
16469 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16470 ((stringp org-agenda-files) (org-read-agenda-file-list))
16471 ((listp org-agenda-files) org-agenda-files)
16472 (t (error "Invalid value of `org-agenda-files'")))))
16473 (setq files (apply 'append
16474 (mapcar (lambda (f)
16475 (if (file-directory-p f)
16476 (directory-files
16477 f t org-agenda-file-regexp)
16478 (list f)))
16479 files)))
16480 (when org-agenda-skip-unavailable-files
16481 (setq files (delq nil
16482 (mapcar (function
16483 (lambda (file)
16484 (and (file-readable-p file) file)))
16485 files))))
16486 (when (or (eq archives t)
16487 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16488 (setq files (org-add-archive-files files)))
16489 files))
16491 (defun org-agenda-file-p (&optional file)
16492 "Return non-nil, if FILE is an agenda file.
16493 If FILE is omitted, use the file associated with the current
16494 buffer."
16495 (member (or file (buffer-file-name))
16496 (org-agenda-files t)))
16498 (defun org-edit-agenda-file-list ()
16499 "Edit the list of agenda files.
16500 Depending on setup, this either uses customize to edit the variable
16501 `org-agenda-files', or it visits the file that is holding the list. In the
16502 latter case, the buffer is set up in a way that saving it automatically kills
16503 the buffer and restores the previous window configuration."
16504 (interactive)
16505 (if (stringp org-agenda-files)
16506 (let ((cw (current-window-configuration)))
16507 (find-file org-agenda-files)
16508 (org-set-local 'org-window-configuration cw)
16509 (org-add-hook 'after-save-hook
16510 (lambda ()
16511 (set-window-configuration
16512 (prog1 org-window-configuration
16513 (kill-buffer (current-buffer))))
16514 (org-install-agenda-files-menu)
16515 (message "New agenda file list installed"))
16516 nil 'local)
16517 (message "%s" (substitute-command-keys
16518 "Edit list and finish with \\[save-buffer]")))
16519 (customize-variable 'org-agenda-files)))
16521 (defun org-store-new-agenda-file-list (list)
16522 "Set new value for the agenda file list and save it correctly."
16523 (if (stringp org-agenda-files)
16524 (let ((fe (org-read-agenda-file-list t)) b u)
16525 (while (setq b (find-buffer-visiting org-agenda-files))
16526 (kill-buffer b))
16527 (with-temp-file org-agenda-files
16528 (insert
16529 (mapconcat
16530 (lambda (f) ;; Keep un-expanded entries.
16531 (if (setq u (assoc f fe))
16532 (cdr u)
16534 list "\n")
16535 "\n")))
16536 (let ((org-mode-hook nil) (org-inhibit-startup t)
16537 (org-insert-mode-line-in-empty-file nil))
16538 (setq org-agenda-files list)
16539 (customize-save-variable 'org-agenda-files org-agenda-files))))
16541 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16542 "Read the list of agenda files from a file.
16543 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16544 filenames, used by `org-store-new-agenda-file-list' to write back
16545 un-expanded file names."
16546 (when (file-directory-p org-agenda-files)
16547 (error "`org-agenda-files' cannot be a single directory"))
16548 (when (stringp org-agenda-files)
16549 (with-temp-buffer
16550 (insert-file-contents org-agenda-files)
16551 (mapcar
16552 (lambda (f)
16553 (let ((e (expand-file-name (substitute-in-file-name f)
16554 org-directory)))
16555 (if pair-with-expansion
16556 (cons e f)
16557 e)))
16558 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16560 ;;;###autoload
16561 (defun org-cycle-agenda-files ()
16562 "Cycle through the files in `org-agenda-files'.
16563 If the current buffer visits an agenda file, find the next one in the list.
16564 If the current buffer does not, find the first agenda file."
16565 (interactive)
16566 (let* ((fs (org-agenda-files t))
16567 (files (append fs (list (car fs))))
16568 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16569 file)
16570 (unless files (error "No agenda files"))
16571 (catch 'exit
16572 (while (setq file (pop files))
16573 (if (equal (file-truename file) tcf)
16574 (when (car files)
16575 (find-file (car files))
16576 (throw 'exit t))))
16577 (find-file (car fs)))
16578 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16580 (defun org-agenda-file-to-front (&optional to-end)
16581 "Move/add the current file to the top of the agenda file list.
16582 If the file is not present in the list, it is added to the front. If it is
16583 present, it is moved there. With optional argument TO-END, add/move to the
16584 end of the list."
16585 (interactive "P")
16586 (let ((org-agenda-skip-unavailable-files nil)
16587 (file-alist (mapcar (lambda (x)
16588 (cons (file-truename x) x))
16589 (org-agenda-files t)))
16590 (ctf (file-truename buffer-file-name))
16591 x had)
16592 (setq x (assoc ctf file-alist) had x)
16594 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16595 (if to-end
16596 (setq file-alist (append (delq x file-alist) (list x)))
16597 (setq file-alist (cons x (delq x file-alist))))
16598 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16599 (org-install-agenda-files-menu)
16600 (message "File %s to %s of agenda file list"
16601 (if had "moved" "added") (if to-end "end" "front"))))
16603 (defun org-remove-file (&optional file)
16604 "Remove current file from the list of files in variable `org-agenda-files'.
16605 These are the files which are being checked for agenda entries.
16606 Optional argument FILE means use this file instead of the current."
16607 (interactive)
16608 (let* ((org-agenda-skip-unavailable-files nil)
16609 (file (or file buffer-file-name))
16610 (true-file (file-truename file))
16611 (afile (abbreviate-file-name file))
16612 (files (delq nil (mapcar
16613 (lambda (x)
16614 (if (equal true-file
16615 (file-truename x))
16616 nil x))
16617 (org-agenda-files t)))))
16618 (if (not (= (length files) (length (org-agenda-files t))))
16619 (progn
16620 (org-store-new-agenda-file-list files)
16621 (org-install-agenda-files-menu)
16622 (message "Removed file: %s" afile))
16623 (message "File was not in list: %s (not removed)" afile))))
16625 (defun org-file-menu-entry (file)
16626 (vector file (list 'find-file file) t))
16628 (defun org-check-agenda-file (file)
16629 "Make sure FILE exists. If not, ask user what to do."
16630 (when (not (file-exists-p file))
16631 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16632 (abbreviate-file-name file))
16633 (let ((r (downcase (read-char-exclusive))))
16634 (cond
16635 ((equal r ?r)
16636 (org-remove-file file)
16637 (throw 'nextfile t))
16638 (t (error "Abort"))))))
16640 (defun org-get-agenda-file-buffer (file)
16641 "Get a buffer visiting FILE. If the buffer needs to be created, add
16642 it to the list of buffers which might be released later."
16643 (let ((buf (org-find-base-buffer-visiting file)))
16644 (if buf
16645 buf ; just return it
16646 ;; Make a new buffer and remember it
16647 (setq buf (find-file-noselect file))
16648 (if buf (push buf org-agenda-new-buffers))
16649 buf)))
16651 (defun org-release-buffers (blist)
16652 "Release all buffers in list, asking the user for confirmation when needed.
16653 When a buffer is unmodified, it is just killed. When modified, it is saved
16654 \(if the user agrees) and then killed."
16655 (let (buf file)
16656 (while (setq buf (pop blist))
16657 (setq file (buffer-file-name buf))
16658 (when (and (buffer-modified-p buf)
16659 file
16660 (y-or-n-p (format "Save file %s? " file)))
16661 (with-current-buffer buf (save-buffer)))
16662 (kill-buffer buf))))
16664 (defun org-prepare-agenda-buffers (files)
16665 "Create buffers for all agenda files, protect archived trees and comments."
16666 (interactive)
16667 (let ((pa '(:org-archived t))
16668 (pc '(:org-comment t))
16669 (pall '(:org-archived t :org-comment t))
16670 (inhibit-read-only t)
16671 (rea (concat ":" org-archive-tag ":"))
16672 bmp file re)
16673 (save-excursion
16674 (save-restriction
16675 (while (setq file (pop files))
16676 (catch 'nextfile
16677 (if (bufferp file)
16678 (set-buffer file)
16679 (org-check-agenda-file file)
16680 (set-buffer (org-get-agenda-file-buffer file)))
16681 (widen)
16682 (setq bmp (buffer-modified-p))
16683 (org-refresh-category-properties)
16684 (setq org-todo-keywords-for-agenda
16685 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16686 (setq org-done-keywords-for-agenda
16687 (append org-done-keywords-for-agenda org-done-keywords))
16688 (setq org-todo-keyword-alist-for-agenda
16689 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16690 (setq org-drawers-for-agenda
16691 (append org-drawers-for-agenda org-drawers))
16692 (setq org-tag-alist-for-agenda
16693 (append org-tag-alist-for-agenda org-tag-alist))
16695 (save-excursion
16696 (remove-text-properties (point-min) (point-max) pall)
16697 (when org-agenda-skip-archived-trees
16698 (goto-char (point-min))
16699 (while (re-search-forward rea nil t)
16700 (if (org-at-heading-p t)
16701 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16702 (goto-char (point-min))
16703 (setq re (format org-heading-keyword-regexp-format
16704 org-comment-string))
16705 (while (re-search-forward re nil t)
16706 (add-text-properties
16707 (match-beginning 0) (org-end-of-subtree t) pc)))
16708 (set-buffer-modified-p bmp)))))
16709 (setq org-todo-keywords-for-agenda
16710 (org-uniquify org-todo-keywords-for-agenda))
16711 (setq org-todo-keyword-alist-for-agenda
16712 (org-uniquify org-todo-keyword-alist-for-agenda)
16713 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16715 ;;;; Embedded LaTeX
16717 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16718 "Keymap for the minor `org-cdlatex-mode'.")
16720 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16721 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16722 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16723 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16724 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16726 (defvar org-cdlatex-texmathp-advice-is-done nil
16727 "Flag remembering if we have applied the advice to texmathp already.")
16729 (define-minor-mode org-cdlatex-mode
16730 "Toggle the minor `org-cdlatex-mode'.
16731 This mode supports entering LaTeX environment and math in LaTeX fragments
16732 in Org-mode.
16733 \\{org-cdlatex-mode-map}"
16734 nil " OCDL" nil
16735 (when org-cdlatex-mode
16736 (require 'cdlatex)
16737 (run-hooks 'cdlatex-mode-hook)
16738 (cdlatex-compute-tables))
16739 (unless org-cdlatex-texmathp-advice-is-done
16740 (setq org-cdlatex-texmathp-advice-is-done t)
16741 (defadvice texmathp (around org-math-always-on activate)
16742 "Always return t in org-mode buffers.
16743 This is because we want to insert math symbols without dollars even outside
16744 the LaTeX math segments. If Orgmode thinks that point is actually inside
16745 an embedded LaTeX fragment, let texmathp do its job.
16746 \\[org-cdlatex-mode-map]"
16747 (interactive)
16748 (let (p)
16749 (cond
16750 ((not (eq major-mode 'org-mode)) ad-do-it)
16751 ((eq this-command 'cdlatex-math-symbol)
16752 (setq ad-return-value t
16753 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16755 (let ((p (org-inside-LaTeX-fragment-p)))
16756 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16757 (setq ad-return-value t
16758 texmathp-why '("Org-mode embedded math" . 0))
16759 (if p ad-do-it)))))))))
16761 (defun turn-on-org-cdlatex ()
16762 "Unconditionally turn on `org-cdlatex-mode'."
16763 (org-cdlatex-mode 1))
16765 (defun org-inside-LaTeX-fragment-p ()
16766 "Test if point is inside a LaTeX fragment.
16767 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16768 sequence appearing also before point.
16769 Even though the matchers for math are configurable, this function assumes
16770 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16771 delimiters are skipped when they have been removed by customization.
16772 The return value is nil, or a cons cell with the delimiter and the
16773 position of this delimiter.
16775 This function does a reasonably good job, but can locally be fooled by
16776 for example currency specifications. For example it will assume being in
16777 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16778 fragments that are properly closed, but during editing, we have to live
16779 with the uncertainty caused by missing closing delimiters. This function
16780 looks only before point, not after."
16781 (catch 'exit
16782 (let ((pos (point))
16783 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16784 (lim (progn
16785 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16786 (point)))
16787 dd-on str (start 0) m re)
16788 (goto-char pos)
16789 (when dodollar
16790 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16791 re (nth 1 (assoc "$" org-latex-regexps)))
16792 (while (string-match re str start)
16793 (cond
16794 ((= (match-end 0) (length str))
16795 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16796 ((= (match-end 0) (- (length str) 5))
16797 (throw 'exit nil))
16798 (t (setq start (match-end 0))))))
16799 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16800 (goto-char pos)
16801 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16802 (and (match-beginning 2) (throw 'exit nil))
16803 ;; count $$
16804 (while (re-search-backward "\\$\\$" lim t)
16805 (setq dd-on (not dd-on)))
16806 (goto-char pos)
16807 (if dd-on (cons "$$" m))))))
16809 (defun org-inside-latex-macro-p ()
16810 "Is point inside a LaTeX macro or its arguments?"
16811 (save-match-data
16812 (org-in-regexp
16813 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16815 (defun org-try-cdlatex-tab ()
16816 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16817 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16818 - inside a LaTeX fragment, or
16819 - after the first word in a line, where an abbreviation expansion could
16820 insert a LaTeX environment."
16821 (when org-cdlatex-mode
16822 (cond
16823 ;; Before any word on the line: No expansion possible.
16824 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16825 ;; Just after first word on the line: Expand it. Make sure it
16826 ;; cannot happen on headlines, though.
16827 ((save-excursion
16828 (skip-chars-backward "a-zA-Z0-9*")
16829 (skip-chars-backward " \t")
16830 (and (bolp) (not (org-at-heading-p))))
16831 (cdlatex-tab) t)
16832 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16834 (defun org-cdlatex-underscore-caret (&optional arg)
16835 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16836 Revert to the normal definition outside of these fragments."
16837 (interactive "P")
16838 (if (org-inside-LaTeX-fragment-p)
16839 (call-interactively 'cdlatex-sub-superscript)
16840 (let (org-cdlatex-mode)
16841 (call-interactively (key-binding (vector last-input-event))))))
16843 (defun org-cdlatex-math-modify (&optional arg)
16844 "Execute `cdlatex-math-modify' in LaTeX fragments.
16845 Revert to the normal definition outside of these fragments."
16846 (interactive "P")
16847 (if (org-inside-LaTeX-fragment-p)
16848 (call-interactively 'cdlatex-math-modify)
16849 (let (org-cdlatex-mode)
16850 (call-interactively (key-binding (vector last-input-event))))))
16852 (defvar org-latex-fragment-image-overlays nil
16853 "List of overlays carrying the images of latex fragments.")
16854 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16856 (defun org-remove-latex-fragment-image-overlays ()
16857 "Remove all overlays with LaTeX fragment images in current buffer."
16858 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16859 (setq org-latex-fragment-image-overlays nil))
16861 (defun org-preview-latex-fragment (&optional subtree)
16862 "Preview the LaTeX fragment at point, or all locally or globally.
16863 If the cursor is in a LaTeX fragment, create the image and overlay
16864 it over the source code. If there is no fragment at point, display
16865 all fragments in the current text, from one headline to the next. With
16866 prefix SUBTREE, display all fragments in the current subtree. With a
16867 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16868 the cursor is before the first headline,
16869 display all fragments in the buffer.
16870 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16871 (interactive "P")
16872 (unless buffer-file-name
16873 (error "Can't preview LaTeX fragment in a non-file buffer"))
16874 (org-remove-latex-fragment-image-overlays)
16875 (save-excursion
16876 (save-restriction
16877 (let (beg end at msg)
16878 (cond
16879 ((or (equal subtree '(16))
16880 (not (save-excursion
16881 (re-search-backward org-outline-regexp-bol nil t))))
16882 (setq beg (point-min) end (point-max)
16883 msg "Creating images for buffer...%s"))
16884 ((equal subtree '(4))
16885 (org-back-to-heading)
16886 (setq beg (point) end (org-end-of-subtree t)
16887 msg "Creating images for subtree...%s"))
16889 (if (setq at (org-inside-LaTeX-fragment-p))
16890 (goto-char (max (point-min) (- (cdr at) 2)))
16891 (org-back-to-heading))
16892 (setq beg (point) end (progn (outline-next-heading) (point))
16893 msg (if at "Creating image...%s"
16894 "Creating images for entry...%s"))))
16895 (message msg "")
16896 (narrow-to-region beg end)
16897 (goto-char beg)
16898 (org-format-latex
16899 (concat "ltxpng/" (file-name-sans-extension
16900 (file-name-nondirectory
16901 buffer-file-name)))
16902 default-directory 'overlays msg at 'forbuffer 'dvipng)
16903 (message msg "done. Use `C-c C-c' to remove images.")))))
16905 (defvar org-latex-regexps
16906 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16907 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16908 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16909 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16910 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16911 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16912 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16913 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16914 "Regular expressions for matching embedded LaTeX.")
16916 (defvar org-export-have-math nil) ;; dynamic scoping
16917 (defun org-format-latex (prefix &optional dir overlays msg at
16918 forbuffer processing-type)
16919 "Replace LaTeX fragments with links to an image, and produce images.
16920 Some of the options can be changed using the variable
16921 `org-format-latex-options'."
16922 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16923 (let* ((prefixnodir (file-name-nondirectory prefix))
16924 (absprefix (expand-file-name prefix dir))
16925 (todir (file-name-directory absprefix))
16926 (opt org-format-latex-options)
16927 (matchers (plist-get opt :matchers))
16928 (re-list org-latex-regexps)
16929 (org-format-latex-header-extra
16930 (plist-get (org-infile-export-plist) :latex-header-extra))
16931 (cnt 0) txt hash link beg end re e checkdir
16932 executables-checked string
16933 m n block-type block linkfile movefile ov)
16934 ;; Check the different regular expressions
16935 (while (setq e (pop re-list))
16936 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16937 block (if block-type "\n\n" ""))
16938 (when (member m matchers)
16939 (goto-char (point-min))
16940 (while (re-search-forward re nil t)
16941 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16942 (not (get-text-property (match-beginning n)
16943 'org-protected))
16944 (or (not overlays)
16945 (not (eq (get-char-property (match-beginning n)
16946 'org-overlay-type)
16947 'org-latex-overlay))))
16948 (setq org-export-have-math t)
16949 (cond
16950 ((eq processing-type 'verbatim)
16951 ;; Leave the text verbatim, just protect it
16952 (add-text-properties (match-beginning n) (match-end n)
16953 '(org-protected t)))
16954 ((eq processing-type 'mathjax)
16955 ;; Prepare for MathJax processing
16956 (setq string (match-string n))
16957 (if (member m '("$" "$1"))
16958 (save-excursion
16959 (delete-region (match-beginning n) (match-end n))
16960 (goto-char (match-beginning n))
16961 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16962 "\\)")
16963 '(org-protected t))))
16964 (add-text-properties (match-beginning n) (match-end n)
16965 '(org-protected t))))
16966 ((eq processing-type 'dvipng)
16967 ;; Process to an image
16968 (setq txt (match-string n)
16969 beg (match-beginning n) end (match-end n)
16970 cnt (1+ cnt))
16971 (let (print-length print-level) ; make sure full list is printed
16972 (setq hash (sha1 (prin1-to-string
16973 (list org-format-latex-header
16974 org-format-latex-header-extra
16975 org-export-latex-default-packages-alist
16976 org-export-latex-packages-alist
16977 org-format-latex-options
16978 forbuffer txt)))
16979 linkfile (format "%s_%s.png" prefix hash)
16980 movefile (format "%s_%s.png" absprefix hash)))
16981 (setq link (concat block "[[file:" linkfile "]]" block))
16982 (if msg (message msg cnt))
16983 (goto-char beg)
16984 (unless checkdir ; make sure the directory exists
16985 (setq checkdir t)
16986 (or (file-directory-p todir) (make-directory todir t)))
16988 (unless executables-checked
16989 (org-check-external-command
16990 "latex" "needed to convert LaTeX fragments to images")
16991 (org-check-external-command
16992 "dvipng" "needed to convert LaTeX fragments to images")
16993 (setq executables-checked t))
16995 (unless (file-exists-p movefile)
16996 (org-create-formula-image
16997 txt movefile opt forbuffer))
16998 (if overlays
16999 (progn
17000 (mapc (lambda (o)
17001 (if (eq (overlay-get o 'org-overlay-type)
17002 'org-latex-overlay)
17003 (delete-overlay o)))
17004 (overlays-in beg end))
17005 (setq ov (make-overlay beg end))
17006 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17007 (if (featurep 'xemacs)
17008 (progn
17009 (overlay-put ov 'invisible t)
17010 (overlay-put
17011 ov 'end-glyph
17012 (make-glyph (vector 'png :file movefile))))
17013 (overlay-put
17014 ov 'display
17015 (list 'image :type 'png :file movefile :ascent 'center)))
17016 (push ov org-latex-fragment-image-overlays)
17017 (goto-char end))
17018 (delete-region beg end)
17019 (insert (org-add-props link
17020 (list 'org-latex-src
17021 (replace-regexp-in-string
17022 "\"" "" txt)
17023 'org-latex-src-embed-type
17024 (if block-type 'paragraph 'character))))))
17025 ((eq processing-type 'mathml)
17026 ;; Process to MathML
17027 (unless executables-checked
17028 (unless (save-match-data (org-format-latex-mathml-available-p))
17029 (error "LaTeX to MathML converter not configured"))
17030 (setq executables-checked t))
17031 (setq txt (match-string n)
17032 beg (match-beginning n) end (match-end n)
17033 cnt (1+ cnt))
17034 (if msg (message msg cnt))
17035 (goto-char beg)
17036 (delete-region beg end)
17037 (insert (org-format-latex-as-mathml
17038 txt block-type prefix dir)))
17040 (error "Unknown conversion type %s for latex fragments"
17041 processing-type)))))))))
17043 (defun org-create-math-formula (latex-frag &optional mathml-file)
17044 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17045 Use `org-latex-to-mathml-convert-command'. If the conversion is
17046 sucessful, return the portion between \"<math...> </math>\"
17047 elements otherwise return nil. When MATHML-FILE is specified,
17048 write the results in to that file. When invoked as an
17049 interactive command, prompt for LATEX-FRAG, with initial value
17050 set to the current active region and echo the results for user
17051 inspection."
17052 (interactive (list (let ((frag (when (region-active-p)
17053 (buffer-substring-no-properties
17054 (region-beginning) (region-end)))))
17055 (read-string "LaTeX Fragment: " frag nil frag))))
17056 (unless latex-frag (error "Invalid latex-frag"))
17057 (let* ((tmp-in-file (file-relative-name
17058 (make-temp-name (expand-file-name "ltxmathml-in"))))
17059 (ignore (write-region latex-frag nil tmp-in-file))
17060 (tmp-out-file (file-relative-name
17061 (make-temp-name (expand-file-name "ltxmathml-out"))))
17062 (cmd (format-spec
17063 org-latex-to-mathml-convert-command
17064 `((?j . ,(shell-quote-argument
17065 (expand-file-name org-latex-to-mathml-jar-file)))
17066 (?I . ,(shell-quote-argument tmp-in-file))
17067 (?o . ,(shell-quote-argument tmp-out-file)))))
17068 mathml shell-command-output)
17069 (when (org-called-interactively-p 'any)
17070 (unless (org-format-latex-mathml-available-p)
17071 (error "LaTeX to MathML converter not configured")))
17072 (message "Running %s" cmd)
17073 (setq shell-command-output (shell-command-to-string cmd))
17074 (setq mathml
17075 (when (file-readable-p tmp-out-file)
17076 (with-current-buffer (find-file-noselect tmp-out-file t)
17077 (goto-char (point-min))
17078 (when (re-search-forward
17079 (concat
17080 (regexp-quote
17081 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17082 "\\(.\\|\n\\)*"
17083 (regexp-quote "</math>")) nil t)
17084 (prog1 (match-string 0) (kill-buffer))))))
17085 (cond
17086 (mathml
17087 (setq mathml
17088 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17089 (when mathml-file
17090 (write-region mathml nil mathml-file))
17091 (when (org-called-interactively-p 'any)
17092 (message mathml)))
17093 ((message "LaTeX to MathML conversion failed")
17094 (message shell-command-output)))
17095 (delete-file tmp-in-file)
17096 (when (file-exists-p tmp-out-file)
17097 (delete-file tmp-out-file))
17098 mathml))
17100 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17101 prefix &optional dir)
17102 "Use `org-create-math-formula' but check local cache first."
17103 (let* ((absprefix (expand-file-name prefix dir))
17104 (print-length nil) (print-level nil)
17105 (formula-id (concat
17106 "formula-"
17107 (sha1
17108 (prin1-to-string
17109 (list latex-frag
17110 org-latex-to-mathml-convert-command)))))
17111 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17112 (formula-cache-dir (file-name-directory formula-cache)))
17114 (unless (file-directory-p formula-cache-dir)
17115 (make-directory formula-cache-dir t))
17117 (unless (file-exists-p formula-cache)
17118 (org-create-math-formula latex-frag formula-cache))
17120 (if (file-exists-p formula-cache)
17121 ;; Successful conversion. Return the link to MathML file.
17122 (org-add-props
17123 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17124 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17125 'org-latex-src-embed-type (if latex-frag-type
17126 'paragraph 'character)))
17127 ;; Failed conversion. Return the LaTeX fragment verbatim
17128 (add-text-properties
17129 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17130 latex-frag)))
17132 ;; This function borrows from Ganesh Swami's latex2png.el
17133 (defun org-create-formula-image (string tofile options buffer)
17134 "This calls dvipng."
17135 (require 'org-latex)
17136 (let* ((tmpdir (if (featurep 'xemacs)
17137 (temp-directory)
17138 temporary-file-directory))
17139 (texfilebase (make-temp-name
17140 (expand-file-name "orgtex" tmpdir)))
17141 (texfile (concat texfilebase ".tex"))
17142 (dvifile (concat texfilebase ".dvi"))
17143 (pngfile (concat texfilebase ".png"))
17144 (fnh (if (featurep 'xemacs)
17145 (font-height (face-font 'default))
17146 (face-attribute 'default :height nil)))
17147 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17148 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17149 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17150 "Black"))
17151 (bg (or (plist-get options (if buffer :background :html-background))
17152 "Transparent")))
17153 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17154 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17155 (with-temp-file texfile
17156 (insert (org-splice-latex-header
17157 org-format-latex-header
17158 org-export-latex-default-packages-alist
17159 org-export-latex-packages-alist t
17160 org-format-latex-header-extra))
17161 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17162 (require 'org-latex)
17163 (org-export-latex-fix-inputenc))
17164 (let ((dir default-directory))
17165 (condition-case nil
17166 (progn
17167 (cd tmpdir)
17168 (call-process "latex" nil nil nil texfile))
17169 (error nil))
17170 (cd dir))
17171 (if (not (file-exists-p dvifile))
17172 (progn (message "Failed to create dvi file from %s" texfile) nil)
17173 (condition-case nil
17174 (if (featurep 'xemacs)
17175 (call-process "dvipng" nil nil nil
17176 "-fg" fg "-bg" bg
17177 "-T" "tight"
17178 "-o" pngfile
17179 dvifile)
17180 (call-process "dvipng" nil nil nil
17181 "-fg" fg "-bg" bg
17182 "-D" dpi
17183 ;;"-x" scale "-y" scale
17184 "-T" "tight"
17185 "-o" pngfile
17186 dvifile))
17187 (error nil))
17188 (if (not (file-exists-p pngfile))
17189 (if org-format-latex-signal-error
17190 (error "Failed to create png file from %s" texfile)
17191 (message "Failed to create png file from %s" texfile)
17192 nil)
17193 ;; Use the requested file name and clean up
17194 (copy-file pngfile tofile 'replace)
17195 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17196 (delete-file (concat texfilebase e)))
17197 pngfile))))
17199 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17200 "Fill a LaTeX header template TPL.
17201 In the template, the following place holders will be recognized:
17203 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17204 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17205 [PACKAGES] \\usepackage statements for PKG
17206 [NO-PACKAGES] do not include PKG
17207 [EXTRA] the string EXTRA
17208 [NO-EXTRA] do not include EXTRA
17210 For backward compatibility, if both the positive and the negative place
17211 holder is missing, the positive one (without the \"NO-\") will be
17212 assumed to be present at the end of the template.
17213 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17214 EXTRA is a string.
17215 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17216 (let (rpl (end ""))
17217 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17218 (setq rpl (if (or (match-end 1) (not def-pkg))
17219 "" (org-latex-packages-to-string def-pkg snippets-p t))
17220 tpl (replace-match rpl t t tpl))
17221 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17223 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17224 (setq rpl (if (or (match-end 1) (not pkg))
17225 "" (org-latex-packages-to-string pkg snippets-p t))
17226 tpl (replace-match rpl t t tpl))
17227 (if pkg (setq end
17228 (concat end "\n"
17229 (org-latex-packages-to-string pkg snippets-p)))))
17231 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17232 (setq rpl (if (or (match-end 1) (not extra))
17233 "" (concat extra "\n"))
17234 tpl (replace-match rpl t t tpl))
17235 (if (and extra (string-match "\\S-" extra))
17236 (setq end (concat end "\n" extra))))
17238 (if (string-match "\\S-" end)
17239 (concat tpl "\n" end)
17240 tpl)))
17242 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17243 "Turn an alist of packages into a string with the \\usepackage macros."
17244 (setq pkg (mapconcat (lambda(p)
17245 (cond
17246 ((stringp p) p)
17247 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17248 (format "%% Package %s omitted" (cadr p)))
17249 ((equal "" (car p))
17250 (format "\\usepackage{%s}" (cadr p)))
17252 (format "\\usepackage[%s]{%s}"
17253 (car p) (cadr p)))))
17255 "\n"))
17256 (if newline (concat pkg "\n") pkg))
17258 (defun org-dvipng-color (attr)
17259 "Return an rgb color specification for dvipng."
17260 (apply 'format "rgb %s %s %s"
17261 (mapcar 'org-normalize-color
17262 (if (featurep 'xemacs)
17263 (color-rgb-components
17264 (face-property 'default
17265 (cond ((eq attr :foreground) 'foreground)
17266 ((eq attr :background) 'background))))
17267 (color-values (face-attribute 'default attr nil))))))
17269 (defun org-normalize-color (value)
17270 "Return string to be used as color value for an RGB component."
17271 (format "%g" (/ value 65535.0)))
17273 ;; Image display
17276 (defvar org-inline-image-overlays nil)
17277 (make-variable-buffer-local 'org-inline-image-overlays)
17279 (defun org-toggle-inline-images (&optional include-linked)
17280 "Toggle the display of inline images.
17281 INCLUDE-LINKED is passed to `org-display-inline-images'."
17282 (interactive "P")
17283 (if org-inline-image-overlays
17284 (progn
17285 (org-remove-inline-images)
17286 (message "Inline image display turned off"))
17287 (org-display-inline-images include-linked)
17288 (if org-inline-image-overlays
17289 (message "%d images displayed inline"
17290 (length org-inline-image-overlays))
17291 (message "No images to display inline"))))
17293 (defun org-display-inline-images (&optional include-linked refresh beg end)
17294 "Display inline images.
17295 Normally only links without a description part are inlined, because this
17296 is how it will work for export. When INCLUDE-LINKED is set, also links
17297 with a description part will be inlined. This can be nice for a quick
17298 look at those images, but it does not reflect what exported files will look
17299 like.
17300 When REFRESH is set, refresh existing images between BEG and END.
17301 This will create new image displays only if necessary.
17302 BEG and END default to the buffer boundaries."
17303 (interactive "P")
17304 (unless refresh
17305 (org-remove-inline-images)
17306 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17307 (save-excursion
17308 (save-restriction
17309 (widen)
17310 (setq beg (or beg (point-min)) end (or end (point-max)))
17311 (goto-char beg)
17312 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17313 (substring (org-image-file-name-regexp) 0 -2)
17314 "\\)\\]" (if include-linked "" "\\]")))
17315 old file ov img)
17316 (while (re-search-forward re end t)
17317 (setq old (get-char-property-and-overlay (match-beginning 1)
17318 'org-image-overlay))
17319 (setq file (expand-file-name
17320 (concat (or (match-string 3) "") (match-string 4))))
17321 (when (file-exists-p file)
17322 (if (and (car-safe old) refresh)
17323 (image-refresh (overlay-get (cdr old) 'display))
17324 (setq img (save-match-data (create-image file)))
17325 (when img
17326 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17327 (overlay-put ov 'display img)
17328 (overlay-put ov 'face 'default)
17329 (overlay-put ov 'org-image-overlay t)
17330 (overlay-put ov 'modification-hooks
17331 (list 'org-display-inline-modification-hook))
17332 (push ov org-inline-image-overlays)))))))))
17334 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17335 "Remove inline-display overlay if a corresponding region is modified."
17336 (let ((inhibit-modification-hooks t))
17337 (when (and ov after)
17338 (delete ov org-inline-image-overlays)
17339 (delete-overlay ov))))
17341 (defun org-remove-inline-images ()
17342 "Remove inline display of images."
17343 (interactive)
17344 (mapc 'delete-overlay org-inline-image-overlays)
17345 (setq org-inline-image-overlays nil))
17347 ;;;; Key bindings
17349 ;; Outline functions from `outline-mode-prefix-map'
17350 ;; that can be remapped in Org:
17351 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17352 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17353 (define-key org-mode-map [remap outline-forward-same-level]
17354 'org-forward-same-level)
17355 (define-key org-mode-map [remap outline-backward-same-level]
17356 'org-backward-same-level)
17357 (define-key org-mode-map [remap show-branches]
17358 'org-kill-note-or-show-branches)
17359 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17360 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17361 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17363 ;; Outline functions from `outline-mode-prefix-map'
17364 ;; that can not be remapped in Org:
17365 ;; - the column "key binding" shows whether the Outline function is still
17366 ;; available in Org mode on the same key that it has been bound to in
17367 ;; Outline mode:
17368 ;; - "overridden": key used for a different functionality in Org mode
17369 ;; - else: key still bound to the same Outline function in Org mode
17370 ;; | Outline function | key binding | Org replacement |
17371 ;; |------------------------------------+-------------+-----------------------|
17372 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17373 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17374 ;; | `show-children' | `C-c C-i' | visibility cycling |
17375 ;; | `hide-subtree' | overridden | visibility cycling |
17376 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17377 ;; | `hide-body' | overridden | no replacement |
17378 ;; | `show-all' | overridden | no replacement |
17379 ;; | `hide-entry' | overridden | visibility cycling |
17380 ;; | `show-entry' | overridden | no replacement |
17381 ;; | `hide-leaves' | overridden | no replacement |
17382 ;; | `hide-sublevels' | overridden | no replacement |
17383 ;; | `hide-other' | overridden | no replacement |
17384 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17385 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17387 ;; Make `C-c C-x' a prefix key
17388 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17390 ;; TAB key with modifiers
17391 (org-defkey org-mode-map "\C-i" 'org-cycle)
17392 (org-defkey org-mode-map [(tab)] 'org-cycle)
17393 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17394 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17395 ;; The following line is necessary under Suse GNU/Linux
17396 (unless (featurep 'xemacs)
17397 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17398 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17399 (define-key org-mode-map [backtab] 'org-shifttab)
17401 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17402 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17403 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17405 ;; Cursor keys with modifiers
17406 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17407 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17408 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17409 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17411 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17412 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17413 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17414 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17416 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17417 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17418 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17419 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17421 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17422 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17423 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17424 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17426 ;; Babel keys
17427 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17428 (mapc (lambda (pair)
17429 (define-key org-babel-map (car pair) (cdr pair)))
17430 org-babel-key-bindings)
17432 ;;; Extra keys for tty access.
17433 ;; We only set them when really needed because otherwise the
17434 ;; menus don't show the simple keys
17436 (when (or org-use-extra-keys
17437 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17438 (not window-system))
17439 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17440 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17441 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17442 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17443 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17444 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17445 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17446 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17447 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17448 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17449 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17450 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17451 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17452 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17453 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17454 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17455 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17456 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17457 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17458 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17459 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17460 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17461 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17462 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17463 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17464 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17465 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17466 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17468 ;; All the other keys
17470 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17471 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17472 (if (boundp 'narrow-map)
17473 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17474 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17475 (if (boundp 'narrow-map)
17476 (org-defkey narrow-map "b" 'org-narrow-to-block)
17477 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17478 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17479 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17480 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17481 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17482 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17483 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17484 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17485 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17486 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17487 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17488 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17489 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17490 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17491 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17492 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17493 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17494 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17495 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17496 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17497 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17498 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17499 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17500 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17501 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17502 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17503 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17504 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17505 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17506 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17507 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17508 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17509 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17510 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17511 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17512 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17513 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17514 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17515 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17516 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17517 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17518 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17519 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17520 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17521 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17522 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17523 (org-defkey org-mode-map "\C-c^" 'org-sort)
17524 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17525 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17526 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17527 (org-defkey org-mode-map "\C-m" 'org-return)
17528 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17529 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17530 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17531 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17532 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17533 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17534 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17535 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17536 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17537 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17538 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17539 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17540 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17541 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17542 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17543 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17544 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17545 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17546 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17547 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17548 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17549 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17550 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17552 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17553 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17554 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17555 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17557 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17558 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17559 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17560 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17561 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17562 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17563 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17564 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17565 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17566 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17567 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17568 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17569 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17570 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17571 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17572 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17573 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17574 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17576 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17577 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17578 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17579 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17580 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17582 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17584 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17586 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17587 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17589 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17592 (when (featurep 'xemacs)
17593 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17596 (defconst org-speed-commands-default
17598 ("Outline Navigation")
17599 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17600 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17601 ("f" . (org-speed-move-safe 'org-forward-same-level))
17602 ("b" . (org-speed-move-safe 'org-backward-same-level))
17603 ("u" . (org-speed-move-safe 'outline-up-heading))
17604 ("j" . org-goto)
17605 ("g" . (org-refile t))
17606 ("Outline Visibility")
17607 ("c" . org-cycle)
17608 ("C" . org-shifttab)
17609 (" " . org-display-outline-path)
17610 ("Outline Structure Editing")
17611 ("U" . org-shiftmetaup)
17612 ("D" . org-shiftmetadown)
17613 ("r" . org-metaright)
17614 ("l" . org-metaleft)
17615 ("R" . org-shiftmetaright)
17616 ("L" . org-shiftmetaleft)
17617 ("i" . (progn (forward-char 1) (call-interactively
17618 'org-insert-heading-respect-content)))
17619 ("^" . org-sort)
17620 ("w" . org-refile)
17621 ("a" . org-archive-subtree-default-with-confirmation)
17622 ("." . org-mark-subtree)
17623 ("Clock Commands")
17624 ("I" . org-clock-in)
17625 ("O" . org-clock-out)
17626 ("Meta Data Editing")
17627 ("t" . org-todo)
17628 ("0" . (org-priority ?\ ))
17629 ("1" . (org-priority ?A))
17630 ("2" . (org-priority ?B))
17631 ("3" . (org-priority ?C))
17632 (";" . org-set-tags-command)
17633 ("e" . org-set-effort)
17634 ("Agenda Views etc")
17635 ("v" . org-agenda)
17636 ("/" . org-sparse-tree)
17637 ("Misc")
17638 ("o" . org-open-at-point)
17639 ("?" . org-speed-command-help)
17640 ("<" . (org-agenda-set-restriction-lock 'subtree))
17641 (">" . (org-agenda-remove-restriction-lock))
17643 "The default speed commands.")
17645 (defun org-print-speed-command (e)
17646 (if (> (length (car e)) 1)
17647 (progn
17648 (princ "\n")
17649 (princ (car e))
17650 (princ "\n")
17651 (princ (make-string (length (car e)) ?-))
17652 (princ "\n"))
17653 (princ (car e))
17654 (princ " ")
17655 (if (symbolp (cdr e))
17656 (princ (symbol-name (cdr e)))
17657 (prin1 (cdr e)))
17658 (princ "\n")))
17660 (defun org-speed-command-help ()
17661 "Show the available speed commands."
17662 (interactive)
17663 (if (not org-use-speed-commands)
17664 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17665 (with-output-to-temp-buffer "*Help*"
17666 (princ "User-defined Speed commands\n===========================\n")
17667 (mapc 'org-print-speed-command org-speed-commands-user)
17668 (princ "\n")
17669 (princ "Built-in Speed commands\n=======================\n")
17670 (mapc 'org-print-speed-command org-speed-commands-default))
17671 (with-current-buffer "*Help*"
17672 (setq truncate-lines t))))
17674 (defun org-speed-move-safe (cmd)
17675 "Execute CMD, but make sure that the cursor always ends up in a headline.
17676 If not, return to the original position and throw an error."
17677 (interactive)
17678 (let ((pos (point)))
17679 (call-interactively cmd)
17680 (unless (and (bolp) (org-at-heading-p))
17681 (goto-char pos)
17682 (error "Boundary reached while executing %s" cmd))))
17684 (defvar org-self-insert-command-undo-counter 0)
17686 (defvar org-table-auto-blank-field) ; defined in org-table.el
17687 (defvar org-speed-command nil)
17689 (defun org-speed-command-default-hook (keys)
17690 "Hook for activating single-letter speed commands.
17691 `org-speed-commands-default' specifies a minimal command set.
17692 Use `org-speed-commands-user' for further customization."
17693 (when (or (and (bolp) (looking-at org-outline-regexp))
17694 (and (functionp org-use-speed-commands)
17695 (funcall org-use-speed-commands)))
17696 (cdr (assoc keys (append org-speed-commands-user
17697 org-speed-commands-default)))))
17699 (defun org-babel-speed-command-hook (keys)
17700 "Hook for activating single-letter code block commands."
17701 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17702 (cdr (assoc keys org-babel-key-bindings))))
17704 (defcustom org-speed-command-hook
17705 '(org-speed-command-default-hook org-babel-speed-command-hook)
17706 "Hook for activating speed commands at strategic locations.
17707 Hook functions are called in sequence until a valid handler is
17708 found.
17710 Each hook takes a single argument, a user-pressed command key
17711 which is also a `self-insert-command' from the global map.
17713 Within the hook, examine the cursor position and the command key
17714 and return nil or a valid handler as appropriate. Handler could
17715 be one of an interactive command, a function, or a form.
17717 Set `org-use-speed-commands' to non-nil value to enable this
17718 hook. The default setting is `org-speed-command-default-hook'."
17719 :group 'org-structure
17720 :version "24.1"
17721 :type 'hook)
17723 (defun org-self-insert-command (N)
17724 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17725 If the cursor is in a table looking at whitespace, the whitespace is
17726 overwritten, and the table is not marked as requiring realignment."
17727 (interactive "p")
17728 (org-check-before-invisible-edit 'insert)
17729 (cond
17730 ((and org-use-speed-commands
17731 (setq org-speed-command
17732 (run-hook-with-args-until-success
17733 'org-speed-command-hook (this-command-keys))))
17734 (cond
17735 ((commandp org-speed-command)
17736 (setq this-command org-speed-command)
17737 (call-interactively org-speed-command))
17738 ((functionp org-speed-command)
17739 (funcall org-speed-command))
17740 ((and org-speed-command (listp org-speed-command))
17741 (eval org-speed-command))
17742 (t (let (org-use-speed-commands)
17743 (call-interactively 'org-self-insert-command)))))
17744 ((and
17745 (org-table-p)
17746 (progn
17747 ;; check if we blank the field, and if that triggers align
17748 (and (featurep 'org-table) org-table-auto-blank-field
17749 (member last-command
17750 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17751 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17752 ;; got extra space, this field does not determine column width
17753 (let (org-table-may-need-update) (org-table-blank-field))
17754 ;; no extra space, this field may determine column width
17755 (org-table-blank-field)))
17757 (eq N 1)
17758 (looking-at "[^|\n]* |"))
17759 (let (org-table-may-need-update)
17760 (goto-char (1- (match-end 0)))
17761 (backward-delete-char 1)
17762 (goto-char (match-beginning 0))
17763 (self-insert-command N)))
17765 (setq org-table-may-need-update t)
17766 (self-insert-command N)
17767 (org-fix-tags-on-the-fly)
17768 (if org-self-insert-cluster-for-undo
17769 (if (not (eq last-command 'org-self-insert-command))
17770 (setq org-self-insert-command-undo-counter 1)
17771 (if (>= org-self-insert-command-undo-counter 20)
17772 (setq org-self-insert-command-undo-counter 1)
17773 (and (> org-self-insert-command-undo-counter 0)
17774 buffer-undo-list (listp buffer-undo-list)
17775 (not (cadr buffer-undo-list)) ; remove nil entry
17776 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17777 (setq org-self-insert-command-undo-counter
17778 (1+ org-self-insert-command-undo-counter))))))))
17780 (defun org-check-before-invisible-edit (kind)
17781 "Check is editing if kind KIND would be dangerous with invisible text around.
17782 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17783 ;; First, try to get out of here as quickly as possible, to reduce overhead
17784 (if (and org-catch-invisible-edits
17785 (or (not (boundp 'visible-mode)) (not visible-mode))
17786 (or (get-char-property (point) 'invisible)
17787 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17788 ;; OK, we need to take a closer look
17789 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17790 (invisible-before-point (if (bobp) nil (get-char-property
17791 (1- (point)) 'invisible)))
17792 (border-and-ok-direction
17794 ;; Check if we are acting predictably before invisible text
17795 (and invisible-at-point (not invisible-before-point)
17796 (memq kind '(insert delete-backward)))
17797 ;; Check if we are acting predictably after invisible text
17798 ;; This works not well, and I have turned it off. It seems
17799 ;; better to always show and stop after invisible text.
17800 ;; (and (not invisible-at-point) invisible-before-point
17801 ;; (memq kind '(insert delete)))
17804 (when (or (memq invisible-at-point '(outline org-hide-block))
17805 (memq invisible-before-point '(outline org-hide-block)))
17806 (if (eq org-catch-invisible-edits 'error)
17807 (error "Editing in invisible areas is prohibited - make visible first"))
17808 ;; Make the area visible
17809 (save-excursion
17810 (if invisible-before-point
17811 (goto-char (previous-single-char-property-change
17812 (point) 'invisible)))
17813 (org-cycle))
17814 (cond
17815 ((eq org-catch-invisible-edits 'show)
17816 ;; That's it, we do the edit after showing
17817 (message
17818 "Unfolding invisible region around point before editing")
17819 (sit-for 1))
17820 ((and (eq org-catch-invisible-edits 'smart)
17821 border-and-ok-direction)
17822 (message "Unfolding invisible region around point before editing"))
17824 ;; Don't do the edit, make the user repeat it in full visibility
17825 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17827 (defun org-fix-tags-on-the-fly ()
17828 (when (and (equal (char-after (point-at-bol)) ?*)
17829 (org-at-heading-p))
17830 (org-align-tags-here org-tags-column)))
17832 (defun org-delete-backward-char (N)
17833 "Like `delete-backward-char', insert whitespace at field end in tables.
17834 When deleting backwards, in tables this function will insert whitespace in
17835 front of the next \"|\" separator, to keep the table aligned. The table will
17836 still be marked for re-alignment if the field did fill the entire column,
17837 because, in this case the deletion might narrow the column."
17838 (interactive "p")
17839 (org-check-before-invisible-edit 'delete-backward)
17840 (if (and (org-table-p)
17841 (eq N 1)
17842 (string-match "|" (buffer-substring (point-at-bol) (point)))
17843 (looking-at ".*?|"))
17844 (let ((pos (point))
17845 (noalign (looking-at "[^|\n\r]* |"))
17846 (c org-table-may-need-update))
17847 (backward-delete-char N)
17848 (if (not overwrite-mode)
17849 (progn
17850 (skip-chars-forward "^|")
17851 (insert " ")
17852 (goto-char (1- pos))))
17853 ;; noalign: if there were two spaces at the end, this field
17854 ;; does not determine the width of the column.
17855 (if noalign (setq org-table-may-need-update c)))
17856 (backward-delete-char N)
17857 (org-fix-tags-on-the-fly)))
17859 (defun org-delete-char (N)
17860 "Like `delete-char', but insert whitespace at field end in tables.
17861 When deleting characters, in tables this function will insert whitespace in
17862 front of the next \"|\" separator, to keep the table aligned. The table will
17863 still be marked for re-alignment if the field did fill the entire column,
17864 because, in this case the deletion might narrow the column."
17865 (interactive "p")
17866 (org-check-before-invisible-edit 'delete)
17867 (if (and (org-table-p)
17868 (not (bolp))
17869 (not (= (char-after) ?|))
17870 (eq N 1))
17871 (if (looking-at ".*?|")
17872 (let ((pos (point))
17873 (noalign (looking-at "[^|\n\r]* |"))
17874 (c org-table-may-need-update))
17875 (replace-match (concat
17876 (substring (match-string 0) 1 -1)
17877 " |"))
17878 (goto-char pos)
17879 ;; noalign: if there were two spaces at the end, this field
17880 ;; does not determine the width of the column.
17881 (if noalign (setq org-table-may-need-update c)))
17882 (delete-char N))
17883 (delete-char N)
17884 (org-fix-tags-on-the-fly)))
17886 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17887 (put 'org-self-insert-command 'delete-selection t)
17888 (put 'orgtbl-self-insert-command 'delete-selection t)
17889 (put 'org-delete-char 'delete-selection 'supersede)
17890 (put 'org-delete-backward-char 'delete-selection 'supersede)
17891 (put 'org-yank 'delete-selection 'yank)
17893 ;; Make `flyspell-mode' delay after some commands
17894 (put 'org-self-insert-command 'flyspell-delayed t)
17895 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17896 (put 'org-delete-char 'flyspell-delayed t)
17897 (put 'org-delete-backward-char 'flyspell-delayed t)
17899 ;; Make pabbrev-mode expand after org-mode commands
17900 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17901 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17903 ;; How to do this: Measure non-white length of current string
17904 ;; If equal to column width, we should realign.
17906 (defun org-remap (map &rest commands)
17907 "In MAP, remap the functions given in COMMANDS.
17908 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17909 (let (new old)
17910 (while commands
17911 (setq old (pop commands) new (pop commands))
17912 (if (fboundp 'command-remapping)
17913 (org-defkey map (vector 'remap old) new)
17914 (substitute-key-definition old new map global-map)))))
17916 (when (eq org-enable-table-editor 'optimized)
17917 ;; If the user wants maximum table support, we need to hijack
17918 ;; some standard editing functions
17919 (org-remap org-mode-map
17920 'self-insert-command 'org-self-insert-command
17921 'delete-char 'org-delete-char
17922 'delete-backward-char 'org-delete-backward-char)
17923 (org-defkey org-mode-map "|" 'org-force-self-insert))
17925 (defvar org-ctrl-c-ctrl-c-hook nil
17926 "Hook for functions attaching themselves to `C-c C-c'.
17928 This can be used to add additional functionality to the C-c C-c
17929 key which executes context-dependent commands. This hook is run
17930 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17931 run after the last test.
17933 Each function will be called with no arguments. The function
17934 must check if the context is appropriate for it to act. If yes,
17935 it should do its thing and then return a non-nil value. If the
17936 context is wrong, just do nothing and return nil.")
17938 (defvar org-ctrl-c-ctrl-c-final-hook nil
17939 "Hook for functions attaching themselves to `C-c C-c'.
17941 This can be used to add additional functionality to the C-c C-c
17942 key which executes context-dependent commands. This hook is run
17943 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17944 before the first test.
17946 Each function will be called with no arguments. The function
17947 must check if the context is appropriate for it to act. If yes,
17948 it should do its thing and then return a non-nil value. If the
17949 context is wrong, just do nothing and return nil.")
17951 (defvar org-tab-first-hook nil
17952 "Hook for functions to attach themselves to TAB.
17953 See `org-ctrl-c-ctrl-c-hook' for more information.
17954 This hook runs as the first action when TAB is pressed, even before
17955 `org-cycle' messes around with the `outline-regexp' to cater for
17956 inline tasks and plain list item folding.
17957 If any function in this hook returns t, any other actions that
17958 would have been caused by TAB (such as table field motion or visibility
17959 cycling) will not occur.")
17961 (defvar org-tab-after-check-for-table-hook nil
17962 "Hook for functions to attach themselves to TAB.
17963 See `org-ctrl-c-ctrl-c-hook' for more information.
17964 This hook runs after it has been established that the cursor is not in a
17965 table, but before checking if the cursor is in a headline or if global cycling
17966 should be done.
17967 If any function in this hook returns t, not other actions like visibility
17968 cycling will be done.")
17970 (defvar org-tab-after-check-for-cycling-hook nil
17971 "Hook for functions to attach themselves to TAB.
17972 See `org-ctrl-c-ctrl-c-hook' for more information.
17973 This hook runs after it has been established that not table field motion and
17974 not visibility should be done because of current context. This is probably
17975 the place where a package like yasnippets can hook in.")
17977 (defvar org-tab-before-tab-emulation-hook nil
17978 "Hook for functions to attach themselves to TAB.
17979 See `org-ctrl-c-ctrl-c-hook' for more information.
17980 This hook runs after every other options for TAB have been exhausted, but
17981 before indentation and \t insertion takes place.")
17983 (defvar org-metaleft-hook nil
17984 "Hook for functions attaching themselves to `M-left'.
17985 See `org-ctrl-c-ctrl-c-hook' for more information.")
17986 (defvar org-metaright-hook nil
17987 "Hook for functions attaching themselves to `M-right'.
17988 See `org-ctrl-c-ctrl-c-hook' for more information.")
17989 (defvar org-metaup-hook nil
17990 "Hook for functions attaching themselves to `M-up'.
17991 See `org-ctrl-c-ctrl-c-hook' for more information.")
17992 (defvar org-metadown-hook nil
17993 "Hook for functions attaching themselves to `M-down'.
17994 See `org-ctrl-c-ctrl-c-hook' for more information.")
17995 (defvar org-shiftmetaleft-hook nil
17996 "Hook for functions attaching themselves to `M-S-left'.
17997 See `org-ctrl-c-ctrl-c-hook' for more information.")
17998 (defvar org-shiftmetaright-hook nil
17999 "Hook for functions attaching themselves to `M-S-right'.
18000 See `org-ctrl-c-ctrl-c-hook' for more information.")
18001 (defvar org-shiftmetaup-hook nil
18002 "Hook for functions attaching themselves to `M-S-up'.
18003 See `org-ctrl-c-ctrl-c-hook' for more information.")
18004 (defvar org-shiftmetadown-hook nil
18005 "Hook for functions attaching themselves to `M-S-down'.
18006 See `org-ctrl-c-ctrl-c-hook' for more information.")
18007 (defvar org-metareturn-hook nil
18008 "Hook for functions attaching themselves to `M-RET'.
18009 See `org-ctrl-c-ctrl-c-hook' for more information.")
18010 (defvar org-shiftup-hook nil
18011 "Hook for functions attaching themselves to `S-up'.
18012 See `org-ctrl-c-ctrl-c-hook' for more information.")
18013 (defvar org-shiftup-final-hook nil
18014 "Hook for functions attaching themselves to `S-up'.
18015 This one runs after all other options except shift-select have been excluded.
18016 See `org-ctrl-c-ctrl-c-hook' for more information.")
18017 (defvar org-shiftdown-hook nil
18018 "Hook for functions attaching themselves to `S-down'.
18019 See `org-ctrl-c-ctrl-c-hook' for more information.")
18020 (defvar org-shiftdown-final-hook nil
18021 "Hook for functions attaching themselves to `S-down'.
18022 This one runs after all other options except shift-select have been excluded.
18023 See `org-ctrl-c-ctrl-c-hook' for more information.")
18024 (defvar org-shiftleft-hook nil
18025 "Hook for functions attaching themselves to `S-left'.
18026 See `org-ctrl-c-ctrl-c-hook' for more information.")
18027 (defvar org-shiftleft-final-hook nil
18028 "Hook for functions attaching themselves to `S-left'.
18029 This one runs after all other options except shift-select have been excluded.
18030 See `org-ctrl-c-ctrl-c-hook' for more information.")
18031 (defvar org-shiftright-hook nil
18032 "Hook for functions attaching themselves to `S-right'.
18033 See `org-ctrl-c-ctrl-c-hook' for more information.")
18034 (defvar org-shiftright-final-hook nil
18035 "Hook for functions attaching themselves to `S-right'.
18036 This one runs after all other options except shift-select have been excluded.
18037 See `org-ctrl-c-ctrl-c-hook' for more information.")
18039 (defun org-modifier-cursor-error ()
18040 "Throw an error, a modified cursor command was applied in wrong context."
18041 (error "This command is active in special context like tables, headlines or items"))
18043 (defun org-shiftselect-error ()
18044 "Throw an error because Shift-Cursor command was applied in wrong context."
18045 (if (and (boundp 'shift-select-mode) shift-select-mode)
18046 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18047 (error "This command works only in special context like headlines or timestamps")))
18049 (defun org-call-for-shift-select (cmd)
18050 (let ((this-command-keys-shift-translated t))
18051 (call-interactively cmd)))
18053 (defun org-shifttab (&optional arg)
18054 "Global visibility cycling or move to previous table field.
18055 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18056 on context.
18057 See the individual commands for more information."
18058 (interactive "P")
18059 (cond
18060 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18061 ((integerp arg)
18062 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18063 (message "Content view to level: %d" arg)
18064 (org-content (prefix-numeric-value arg2))
18065 (setq org-cycle-global-status 'overview)))
18066 (t (call-interactively 'org-global-cycle))))
18068 (defun org-shiftmetaleft ()
18069 "Promote subtree or delete table column.
18070 Calls `org-promote-subtree', `org-outdent-item',
18071 or `org-table-delete-column', depending on context.
18072 See the individual commands for more information."
18073 (interactive)
18074 (cond
18075 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18076 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18077 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18078 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
18079 (t (org-modifier-cursor-error))))
18081 (defun org-shiftmetaright ()
18082 "Demote subtree or insert table column.
18083 Calls `org-demote-subtree', `org-indent-item',
18084 or `org-table-insert-column', depending on context.
18085 See the individual commands for more information."
18086 (interactive)
18087 (cond
18088 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18089 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18090 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18091 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
18092 (t (org-modifier-cursor-error))))
18094 (defun org-shiftmetaup (&optional arg)
18095 "Move subtree up or kill table row.
18096 Calls `org-move-subtree-up' or `org-table-kill-row' or
18097 `org-move-item-up' depending on context. See the individual commands
18098 for more information."
18099 (interactive "P")
18100 (cond
18101 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18102 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18103 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18104 ((org-at-item-p) (call-interactively 'org-move-item-up))
18105 (t (org-modifier-cursor-error))))
18107 (defun org-shiftmetadown (&optional arg)
18108 "Move subtree down or insert table row.
18109 Calls `org-move-subtree-down' or `org-table-insert-row' or
18110 `org-move-item-down', depending on context. See the individual
18111 commands for more information."
18112 (interactive "P")
18113 (cond
18114 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18115 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18116 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18117 ((org-at-item-p) (call-interactively 'org-move-item-down))
18118 (t (org-modifier-cursor-error))))
18120 (defsubst org-hidden-tree-error ()
18121 (error
18122 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18124 (defun org-metaleft (&optional arg)
18125 "Promote heading or move table column to left.
18126 Calls `org-do-promote' or `org-table-move-column', depending on context.
18127 With no specific context, calls the Emacs default `backward-word'.
18128 See the individual commands for more information."
18129 (interactive "P")
18130 (cond
18131 ((run-hook-with-args-until-success 'org-metaleft-hook))
18132 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18133 ((org-with-limited-levels
18134 (or (org-at-heading-p)
18135 (and (org-region-active-p)
18136 (save-excursion
18137 (goto-char (region-beginning))
18138 (org-at-heading-p)))))
18139 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18140 (call-interactively 'org-do-promote))
18141 ;; At an inline task.
18142 ((org-at-heading-p)
18143 (call-interactively 'org-inlinetask-promote))
18144 ((or (org-at-item-p)
18145 (and (org-region-active-p)
18146 (save-excursion
18147 (goto-char (region-beginning))
18148 (org-at-item-p))))
18149 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18150 (call-interactively 'org-outdent-item))
18151 (t (call-interactively 'backward-word))))
18153 (defun org-metaright (&optional arg)
18154 "Demote a subtree, a list item or move table column to right.
18155 In front of a drawer or a block keyword, indent it correctly.
18156 With no specific context, calls the Emacs default `forward-word'.
18157 See the individual commands for more information."
18158 (interactive "P")
18159 (cond
18160 ((run-hook-with-args-until-success 'org-metaright-hook))
18161 ((org-at-table-p) (call-interactively 'org-table-move-column))
18162 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18163 ((org-at-block-p) (call-interactively 'org-indent-block))
18164 ((org-with-limited-levels
18165 (or (org-at-heading-p)
18166 (and (org-region-active-p)
18167 (save-excursion
18168 (goto-char (region-beginning))
18169 (org-at-heading-p)))))
18170 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18171 (call-interactively 'org-do-demote))
18172 ;; At an inline task.
18173 ((org-at-heading-p)
18174 (call-interactively 'org-inlinetask-demote))
18175 ((or (org-at-item-p)
18176 (and (org-region-active-p)
18177 (save-excursion
18178 (goto-char (region-beginning))
18179 (org-at-item-p))))
18180 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18181 (call-interactively 'org-indent-item))
18182 (t (call-interactively 'forward-word))))
18184 (defun org-check-for-hidden (what)
18185 "Check if there are hidden headlines/items in the current visual line.
18186 WHAT can be either `headlines' or `items'. If the current line is
18187 an outline or item heading and it has a folded subtree below it,
18188 this function returns t, nil otherwise."
18189 (let ((re (cond
18190 ((eq what 'headlines) org-outline-regexp-bol)
18191 ((eq what 'items) (org-item-beginning-re))
18192 (t (error "This should not happen"))))
18193 beg end)
18194 (save-excursion
18195 (catch 'exit
18196 (unless (org-region-active-p)
18197 (setq beg (point-at-bol))
18198 (beginning-of-line 2)
18199 (while (and (not (eobp)) ;; this is like `next-line'
18200 (get-char-property (1- (point)) 'invisible))
18201 (beginning-of-line 2))
18202 (setq end (point))
18203 (goto-char beg)
18204 (goto-char (point-at-eol))
18205 (setq end (max end (point)))
18206 (while (re-search-forward re end t)
18207 (if (get-char-property (match-beginning 0) 'invisible)
18208 (throw 'exit t))))
18209 nil))))
18211 (defun org-metaup (&optional arg)
18212 "Move subtree up or move table row up.
18213 Calls `org-move-subtree-up' or `org-table-move-row' or
18214 `org-move-item-up', depending on context. See the individual commands
18215 for more information."
18216 (interactive "P")
18217 (cond
18218 ((run-hook-with-args-until-success 'org-metaup-hook))
18219 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18220 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18221 ((org-at-item-p) (call-interactively 'org-move-item-up))
18222 (t (transpose-lines 1) (beginning-of-line -1))))
18224 (defun org-metadown (&optional arg)
18225 "Move subtree down or move table row down.
18226 Calls `org-move-subtree-down' or `org-table-move-row' or
18227 `org-move-item-down', depending on context. See the individual
18228 commands for more information."
18229 (interactive "P")
18230 (cond
18231 ((run-hook-with-args-until-success 'org-metadown-hook))
18232 ((org-at-table-p) (call-interactively 'org-table-move-row))
18233 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18234 ((org-at-item-p) (call-interactively 'org-move-item-down))
18235 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18237 (defun org-shiftup (&optional arg)
18238 "Increase item in timestamp or increase priority of current headline.
18239 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18240 depending on context. See the individual commands for more information."
18241 (interactive "P")
18242 (cond
18243 ((run-hook-with-args-until-success 'org-shiftup-hook))
18244 ((and org-support-shift-select (org-region-active-p))
18245 (org-call-for-shift-select 'previous-line))
18246 ((org-at-timestamp-p t)
18247 (call-interactively (if org-edit-timestamp-down-means-later
18248 'org-timestamp-down 'org-timestamp-up)))
18249 ((and (not (eq org-support-shift-select 'always))
18250 org-enable-priority-commands
18251 (org-at-heading-p))
18252 (call-interactively 'org-priority-up))
18253 ((and (not org-support-shift-select) (org-at-item-p))
18254 (call-interactively 'org-previous-item))
18255 ((org-clocktable-try-shift 'up arg))
18256 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18257 (org-support-shift-select
18258 (org-call-for-shift-select 'previous-line))
18259 (t (org-shiftselect-error))))
18261 (defun org-shiftdown (&optional arg)
18262 "Decrease item in timestamp or decrease priority of current headline.
18263 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18264 depending on context. See the individual commands for more information."
18265 (interactive "P")
18266 (cond
18267 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18268 ((and org-support-shift-select (org-region-active-p))
18269 (org-call-for-shift-select 'next-line))
18270 ((org-at-timestamp-p t)
18271 (call-interactively (if org-edit-timestamp-down-means-later
18272 'org-timestamp-up 'org-timestamp-down)))
18273 ((and (not (eq org-support-shift-select 'always))
18274 org-enable-priority-commands
18275 (org-at-heading-p))
18276 (call-interactively 'org-priority-down))
18277 ((and (not org-support-shift-select) (org-at-item-p))
18278 (call-interactively 'org-next-item))
18279 ((org-clocktable-try-shift 'down arg))
18280 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18281 (org-support-shift-select
18282 (org-call-for-shift-select 'next-line))
18283 (t (org-shiftselect-error))))
18285 (defun org-shiftright (&optional arg)
18286 "Cycle the thing at point or in the current line, depending on context.
18287 Depending on context, this does one of the following:
18289 - switch a timestamp at point one day into the future
18290 - on a headline, switch to the next TODO keyword.
18291 - on an item, switch entire list to the next bullet type
18292 - on a property line, switch to the next allowed value
18293 - on a clocktable definition line, move time block into the future"
18294 (interactive "P")
18295 (cond
18296 ((run-hook-with-args-until-success 'org-shiftright-hook))
18297 ((and org-support-shift-select (org-region-active-p))
18298 (org-call-for-shift-select 'forward-char))
18299 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18300 ((and (not (eq org-support-shift-select 'always))
18301 (org-at-heading-p))
18302 (let ((org-inhibit-logging
18303 (not org-treat-S-cursor-todo-selection-as-state-change))
18304 (org-inhibit-blocking
18305 (not org-treat-S-cursor-todo-selection-as-state-change)))
18306 (org-call-with-arg 'org-todo 'right)))
18307 ((or (and org-support-shift-select
18308 (not (eq org-support-shift-select 'always))
18309 (org-at-item-bullet-p))
18310 (and (not org-support-shift-select) (org-at-item-p)))
18311 (org-call-with-arg 'org-cycle-list-bullet nil))
18312 ((and (not (eq org-support-shift-select 'always))
18313 (org-at-property-p))
18314 (call-interactively 'org-property-next-allowed-value))
18315 ((org-clocktable-try-shift 'right arg))
18316 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18317 (org-support-shift-select
18318 (org-call-for-shift-select 'forward-char))
18319 (t (org-shiftselect-error))))
18321 (defun org-shiftleft (&optional arg)
18322 "Cycle the thing at point or in the current line, depending on context.
18323 Depending on context, this does one of the following:
18325 - switch a timestamp at point one day into the past
18326 - on a headline, switch to the previous TODO keyword.
18327 - on an item, switch entire list to the previous bullet type
18328 - on a property line, switch to the previous allowed value
18329 - on a clocktable definition line, move time block into the past"
18330 (interactive "P")
18331 (cond
18332 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18333 ((and org-support-shift-select (org-region-active-p))
18334 (org-call-for-shift-select 'backward-char))
18335 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18336 ((and (not (eq org-support-shift-select 'always))
18337 (org-at-heading-p))
18338 (let ((org-inhibit-logging
18339 (not org-treat-S-cursor-todo-selection-as-state-change))
18340 (org-inhibit-blocking
18341 (not org-treat-S-cursor-todo-selection-as-state-change)))
18342 (org-call-with-arg 'org-todo 'left)))
18343 ((or (and org-support-shift-select
18344 (not (eq org-support-shift-select 'always))
18345 (org-at-item-bullet-p))
18346 (and (not org-support-shift-select) (org-at-item-p)))
18347 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18348 ((and (not (eq org-support-shift-select 'always))
18349 (org-at-property-p))
18350 (call-interactively 'org-property-previous-allowed-value))
18351 ((org-clocktable-try-shift 'left arg))
18352 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18353 (org-support-shift-select
18354 (org-call-for-shift-select 'backward-char))
18355 (t (org-shiftselect-error))))
18357 (defun org-shiftcontrolright ()
18358 "Switch to next TODO set."
18359 (interactive)
18360 (cond
18361 ((and org-support-shift-select (org-region-active-p))
18362 (org-call-for-shift-select 'forward-word))
18363 ((and (not (eq org-support-shift-select 'always))
18364 (org-at-heading-p))
18365 (org-call-with-arg 'org-todo 'nextset))
18366 (org-support-shift-select
18367 (org-call-for-shift-select 'forward-word))
18368 (t (org-shiftselect-error))))
18370 (defun org-shiftcontrolleft ()
18371 "Switch to previous TODO set."
18372 (interactive)
18373 (cond
18374 ((and org-support-shift-select (org-region-active-p))
18375 (org-call-for-shift-select 'backward-word))
18376 ((and (not (eq org-support-shift-select 'always))
18377 (org-at-heading-p))
18378 (org-call-with-arg 'org-todo 'previousset))
18379 (org-support-shift-select
18380 (org-call-for-shift-select 'backward-word))
18381 (t (org-shiftselect-error))))
18383 (defun org-shiftcontrolup ()
18384 "Change timestamps synchronously up in CLOCK log lines."
18385 (interactive)
18386 (cond ((and (not org-support-shift-select)
18387 (org-at-clock-log-p)
18388 (org-at-timestamp-p t))
18389 (org-clock-timestamps-up))
18390 (t (org-shiftselect-error))))
18392 (defun org-shiftcontroldown ()
18393 "Change timestamps synchronously down in CLOCK log lines."
18394 (interactive)
18395 (cond ((and (not org-support-shift-select)
18396 (org-at-clock-log-p)
18397 (org-at-timestamp-p t))
18398 (org-clock-timestamps-down))
18399 (t (org-shiftselect-error))))
18401 (defun org-ctrl-c-ret ()
18402 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18403 (interactive)
18404 (cond
18405 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18406 (t (call-interactively 'org-insert-heading))))
18408 (defun org-find-visible ()
18409 (let ((s (point)))
18410 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18411 (get-char-property s 'invisible)))
18413 (defun org-find-invisible ()
18414 (let ((s (point)))
18415 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18416 (not (get-char-property s 'invisible))))
18419 (defun org-copy-visible (beg end)
18420 "Copy the visible parts of the region."
18421 (interactive "r")
18422 (let (snippets s)
18423 (save-excursion
18424 (save-restriction
18425 (narrow-to-region beg end)
18426 (setq s (goto-char (point-min)))
18427 (while (not (= (point) (point-max)))
18428 (goto-char (org-find-invisible))
18429 (push (buffer-substring s (point)) snippets)
18430 (setq s (goto-char (org-find-visible))))))
18431 (kill-new (apply 'concat (nreverse snippets)))))
18433 (defun org-copy-special ()
18434 "Copy region in table or copy current subtree.
18435 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18436 See the individual commands for more information."
18437 (interactive)
18438 (call-interactively
18439 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18441 (defun org-cut-special ()
18442 "Cut region in table or cut current subtree.
18443 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18444 See the individual commands for more information."
18445 (interactive)
18446 (call-interactively
18447 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18449 (defun org-paste-special (arg)
18450 "Paste rectangular region into table, or past subtree relative to level.
18451 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18452 See the individual commands for more information."
18453 (interactive "P")
18454 (if (org-at-table-p)
18455 (org-table-paste-rectangle)
18456 (org-paste-subtree arg)))
18458 (defun org-edit-special (&optional arg)
18459 "Call a special editor for the stuff at point.
18460 When at a table, call the formula editor with `org-table-edit-formulas'.
18461 When at the first line of an src example, call `org-edit-src-code'.
18462 When in an #+include line, visit the include file. Otherwise call
18463 `ffap' to visit the file at point."
18464 (interactive)
18465 ;; possibly prep session before editing source
18466 (when arg
18467 (let* ((info (org-babel-get-src-block-info))
18468 (lang (nth 0 info))
18469 (params (nth 2 info))
18470 (session (cdr (assoc :session params))))
18471 (when (and info session) ;; we are in a source-code block with a session
18472 (funcall
18473 (intern (concat "org-babel-prep-session:" lang)) session params))))
18474 (cond ;; proceed with `org-edit-special'
18475 ((save-excursion
18476 (beginning-of-line 1)
18477 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18478 (find-file (org-trim (match-string 1))))
18479 ((org-edit-src-code))
18480 ((org-edit-fixed-width-region))
18481 ((org-at-table.el-p)
18482 (org-edit-src-code))
18483 ((or (org-at-table-p)
18484 (save-excursion
18485 (beginning-of-line 1)
18486 (looking-at "[ \t]*#\\+TBLFM:")))
18487 (call-interactively 'org-table-edit-formulas))
18488 (t (call-interactively 'ffap))))
18490 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18491 (defun org-ctrl-c-ctrl-c (&optional arg)
18492 "Set tags in headline, or update according to changed information at point.
18494 This command does many different things, depending on context:
18496 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18497 this is what we do.
18499 - If the cursor is on a statistics cookie, update it.
18501 - If the cursor is in a headline, prompt for tags and insert them
18502 into the current line, aligned to `org-tags-column'. When called
18503 with prefix arg, realign all tags in the current buffer.
18505 - If the cursor is in one of the special #+KEYWORD lines, this
18506 triggers scanning the buffer for these lines and updating the
18507 information.
18509 - If the cursor is inside a table, realign the table. This command
18510 works even if the automatic table editor has been turned off.
18512 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18513 the entire table.
18515 - If the cursor is at a footnote reference or definition, jump to
18516 the corresponding definition or references, respectively.
18518 - If the cursor is a the beginning of a dynamic block, update it.
18520 - If the current buffer is a capture buffer, close note and file it.
18522 - If the cursor is on a <<<target>>>, update radio targets and
18523 corresponding links in this buffer.
18525 - If the cursor is on a numbered item in a plain list, renumber the
18526 ordered list.
18528 - If the cursor is on a checkbox, toggle it.
18530 - If the cursor is on a code block, evaluate it. The variable
18531 `org-confirm-babel-evaluate' can be used to control prompting
18532 before code block evaluation, by default every code block
18533 evaluation requires confirmation. Code block evaluation can be
18534 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18535 (interactive "P")
18536 (let ((org-enable-table-editor t))
18537 (cond
18538 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18539 org-occur-highlights
18540 org-latex-fragment-image-overlays)
18541 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18542 (org-remove-occur-highlights)
18543 (org-remove-latex-fragment-image-overlays)
18544 (message "Temporary highlights/overlays removed from current buffer"))
18545 ((and (local-variable-p 'org-finish-function (current-buffer))
18546 (fboundp org-finish-function))
18547 (funcall org-finish-function))
18548 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18549 ((org-in-regexp org-ts-regexp-both)
18550 (org-timestamp-change 0 'day))
18551 ((or (looking-at org-property-start-re)
18552 (org-at-property-p))
18553 (call-interactively 'org-property-action))
18554 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18555 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18556 (or (org-at-heading-p) (org-at-item-p)))
18557 (call-interactively 'org-update-statistics-cookies))
18558 ((org-at-heading-p) (call-interactively 'org-set-tags))
18559 ((org-at-table.el-p)
18560 (message "Use C-c ' to edit table.el tables"))
18561 ((org-at-table-p)
18562 (org-table-maybe-eval-formula)
18563 (if arg
18564 (call-interactively 'org-table-recalculate)
18565 (org-table-maybe-recalculate-line))
18566 (call-interactively 'org-table-align)
18567 (orgtbl-send-table 'maybe))
18568 ((or (org-footnote-at-reference-p)
18569 (org-footnote-at-definition-p))
18570 (call-interactively 'org-footnote-action))
18571 ((org-at-item-checkbox-p)
18572 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18573 ;; list only if at top item.
18574 (let* ((cbox (match-string 1))
18575 (struct (org-list-struct))
18576 (old-struct (copy-tree struct))
18577 (parents (org-list-parents-alist struct))
18578 (orderedp (org-entry-get nil "ORDERED"))
18579 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18580 block-item)
18581 ;; Use a light version of `org-toggle-checkbox' to avoid
18582 ;; computing list structure twice.
18583 (let ((new-box (cond
18584 ((equal arg '(16)) "[-]")
18585 ((equal arg '(4)) nil)
18586 ((equal "[X]" cbox) "[ ]")
18587 (t "[X]"))))
18588 (if (and firstp arg)
18589 ;; If at first item of sub-list, remove check-box from
18590 ;; every item at the same level.
18591 (mapc
18592 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18593 (org-list-get-all-items
18594 (point-at-bol) struct (org-list-prevs-alist struct)))
18595 (org-list-set-checkbox (point-at-bol) struct new-box)))
18596 ;; Replicate `org-list-write-struct', while grabbing a return
18597 ;; value from `org-list-struct-fix-box'.
18598 (org-list-struct-fix-ind struct parents 2)
18599 (org-list-struct-fix-item-end struct)
18600 (let ((prevs (org-list-prevs-alist struct)))
18601 (org-list-struct-fix-bul struct prevs)
18602 (org-list-struct-fix-ind struct parents)
18603 (setq block-item
18604 (org-list-struct-fix-box struct parents prevs orderedp)))
18605 (org-list-struct-apply-struct struct old-struct)
18606 (org-update-checkbox-count-maybe)
18607 (when block-item
18608 (message
18609 "Checkboxes were removed due to unchecked box at line %d"
18610 (org-current-line block-item)))
18611 (when firstp (org-list-send-list 'maybe))))
18612 ((org-at-item-p)
18613 ;; Cursor at an item: repair list. Do checkbox related actions
18614 ;; only if function was called with an argument. Send list only
18615 ;; if at top item.
18616 (let* ((struct (org-list-struct))
18617 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18618 old-struct)
18619 (when arg
18620 (setq old-struct (copy-tree struct))
18621 (if firstp
18622 ;; If at first item of sub-list, add check-box to every
18623 ;; item at the same level.
18624 (mapc
18625 (lambda (pos)
18626 (unless (org-list-get-checkbox pos struct)
18627 (org-list-set-checkbox pos struct "[ ]")))
18628 (org-list-get-all-items
18629 (point-at-bol) struct (org-list-prevs-alist struct)))
18630 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18631 (org-list-write-struct
18632 struct (org-list-parents-alist struct) old-struct)
18633 (when arg (org-update-checkbox-count-maybe))
18634 (when firstp (org-list-send-list 'maybe))))
18635 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18636 ;; Dynamic block
18637 (beginning-of-line 1)
18638 (save-excursion (org-update-dblock)))
18639 ((save-excursion
18640 (beginning-of-line 1)
18641 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18642 (cond
18643 ((equal (match-string 1) "TBLFM")
18644 ;; Recalculate the table before this line
18645 (save-excursion
18646 (beginning-of-line 1)
18647 (skip-chars-backward " \r\n\t")
18648 (if (org-at-table-p)
18649 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18651 (let ((org-inhibit-startup-visibility-stuff t)
18652 (org-startup-align-all-tables nil))
18653 (when (boundp 'org-table-coordinate-overlays)
18654 (mapc 'delete-overlay org-table-coordinate-overlays)
18655 (setq org-table-coordinate-overlays nil))
18656 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18657 (message "Local setup has been refreshed"))))
18658 ((org-clock-update-time-maybe))
18660 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18661 (error "C-c C-c can do nothing useful at this location"))))))
18663 (defun org-mode-restart ()
18664 "Restart Org-mode, to scan again for special lines.
18665 Also updates the keyword regular expressions."
18666 (interactive)
18667 (org-mode)
18668 (message "Org-mode restarted"))
18670 (defun org-kill-note-or-show-branches ()
18671 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18672 (interactive)
18673 (if (not org-finish-function)
18674 (progn
18675 (hide-subtree)
18676 (call-interactively 'show-branches))
18677 (let ((org-note-abort t))
18678 (funcall org-finish-function))))
18680 (defun org-return (&optional indent)
18681 "Goto next table row or insert a newline.
18682 Calls `org-table-next-row' or `newline', depending on context.
18683 See the individual commands for more information."
18684 (interactive)
18685 (cond
18686 ((or (bobp) (org-in-src-block-p))
18687 (if indent (newline-and-indent) (newline)))
18688 ((org-at-table-p)
18689 (org-table-justify-field-maybe)
18690 (call-interactively 'org-table-next-row))
18691 ;; when `newline-and-indent' is called within a list, make sure
18692 ;; text moved stays inside the item.
18693 ((and (org-in-item-p) indent)
18694 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18695 (progn
18696 (save-match-data (newline))
18697 (org-indent-line-to (length (match-string 0))))
18698 (let ((ind (org-get-indentation)))
18699 (newline)
18700 (if (org-looking-back org-list-end-re)
18701 (org-indent-line-function)
18702 (org-indent-line-to ind)))))
18703 ((and org-return-follows-link
18704 (let ((tprop (get-text-property (point) 'face)))
18705 (or (eq tprop 'org-link)
18706 (and (listp tprop) (memq 'org-link tprop)))))
18707 (call-interactively 'org-open-at-point))
18708 ((and (org-at-heading-p)
18709 (looking-at
18710 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18711 (org-show-entry)
18712 (end-of-line 1)
18713 (newline))
18714 (t (if indent (newline-and-indent) (newline)))))
18716 (defun org-return-indent ()
18717 "Goto next table row or insert a newline and indent.
18718 Calls `org-table-next-row' or `newline-and-indent', depending on
18719 context. See the individual commands for more information."
18720 (interactive)
18721 (org-return t))
18723 (defun org-ctrl-c-star ()
18724 "Compute table, or change heading status of lines.
18725 Calls `org-table-recalculate' or `org-toggle-heading',
18726 depending on context."
18727 (interactive)
18728 (cond
18729 ((org-at-table-p)
18730 (call-interactively 'org-table-recalculate))
18732 ;; Convert all lines in region to list items
18733 (call-interactively 'org-toggle-heading))))
18735 (defun org-ctrl-c-minus ()
18736 "Insert separator line in table or modify bullet status of line.
18737 Also turns a plain line or a region of lines into list items.
18738 Calls `org-table-insert-hline', `org-toggle-item', or
18739 `org-cycle-list-bullet', depending on context."
18740 (interactive)
18741 (cond
18742 ((org-at-table-p)
18743 (call-interactively 'org-table-insert-hline))
18744 ((org-region-active-p)
18745 (call-interactively 'org-toggle-item))
18746 ((org-in-item-p)
18747 (call-interactively 'org-cycle-list-bullet))
18749 (call-interactively 'org-toggle-item))))
18751 (defun org-toggle-item (arg)
18752 "Convert headings or normal lines to items, items to normal lines.
18753 If there is no active region, only the current line is considered.
18755 If the first non blank line in the region is an headline, convert
18756 all headlines to items, shifting text accordingly.
18758 If it is an item, convert all items to normal lines.
18760 If it is normal text, change region into an item. With a prefix
18761 argument ARG, change each line in region into an item."
18762 (interactive "P")
18763 (let ((shift-text
18764 (function
18765 ;; Shift text in current section to IND, from point to END.
18766 ;; The function leaves point to END line.
18767 (lambda (ind end)
18768 (let ((min-i 1000) (end (copy-marker end)))
18769 ;; First determine the minimum indentation (MIN-I) of
18770 ;; the text.
18771 (save-excursion
18772 (catch 'exit
18773 (while (< (point) end)
18774 (let ((i (org-get-indentation)))
18775 (cond
18776 ;; Skip blank lines and inline tasks.
18777 ((looking-at "^[ \t]*$"))
18778 ((looking-at org-outline-regexp-bol))
18779 ;; We can't find less than 0 indentation.
18780 ((zerop i) (throw 'exit (setq min-i 0)))
18781 ((< i min-i) (setq min-i i))))
18782 (forward-line))))
18783 ;; Then indent each line so that a line indented to
18784 ;; MIN-I becomes indented to IND. Ignore blank lines
18785 ;; and inline tasks in the process.
18786 (let ((delta (- ind min-i)))
18787 (while (< (point) end)
18788 (unless (or (looking-at "^[ \t]*$")
18789 (looking-at org-outline-regexp-bol))
18790 (org-indent-line-to (+ (org-get-indentation) delta)))
18791 (forward-line)))))))
18792 (skip-blanks
18793 (function
18794 ;; Return beginning of first non-blank line, starting from
18795 ;; line at POS.
18796 (lambda (pos)
18797 (save-excursion
18798 (goto-char pos)
18799 (skip-chars-forward " \r\t\n")
18800 (point-at-bol)))))
18801 beg end)
18802 ;; Determine boundaries of changes.
18803 (if (org-region-active-p)
18804 (setq beg (funcall skip-blanks (region-beginning))
18805 end (copy-marker (region-end)))
18806 (setq beg (funcall skip-blanks (point-at-bol))
18807 end (copy-marker (point-at-eol))))
18808 ;; Depending on the starting line, choose an action on the text
18809 ;; between BEG and END.
18810 (org-with-limited-levels
18811 (save-excursion
18812 (goto-char beg)
18813 (cond
18814 ;; Case 1. Start at an item: de-itemize. Note that it only
18815 ;; happens when a region is active: `org-ctrl-c-minus'
18816 ;; would call `org-cycle-list-bullet' otherwise.
18817 ((org-at-item-p)
18818 (while (< (point) end)
18819 (when (org-at-item-p)
18820 (skip-chars-forward " \t")
18821 (delete-region (point) (match-end 0)))
18822 (forward-line)))
18823 ;; Case 2. Start at an heading: convert to items.
18824 ((org-at-heading-p)
18825 (let* ((bul (org-list-bullet-string "-"))
18826 (bul-len (length bul))
18827 ;; Indentation of the first heading. It should be
18828 ;; relative to the indentation of its parent, if any.
18829 (start-ind (save-excursion
18830 (cond
18831 ((not org-adapt-indentation) 0)
18832 ((not (outline-previous-heading)) 0)
18833 (t (length (match-string 0))))))
18834 ;; Level of first heading. Further headings will be
18835 ;; compared to it to determine hierarchy in the list.
18836 (ref-level (org-reduced-level (org-outline-level))))
18837 (while (< (point) end)
18838 (let* ((level (org-reduced-level (org-outline-level)))
18839 (delta (max 0 (- level ref-level))))
18840 ;; If current headline is less indented than the first
18841 ;; one, set it as reference, in order to preserve
18842 ;; subtrees.
18843 (when (< level ref-level) (setq ref-level level))
18844 (replace-match bul t t)
18845 (org-indent-line-to (+ start-ind (* delta bul-len)))
18846 ;; Ensure all text down to END (or SECTION-END) belongs
18847 ;; to the newly created item.
18848 (let ((section-end (save-excursion
18849 (or (outline-next-heading) (point)))))
18850 (forward-line)
18851 (funcall shift-text
18852 (+ start-ind (* (1+ delta) bul-len))
18853 (min end section-end)))))))
18854 ;; Case 3. Normal line with ARG: turn each non-item line into
18855 ;; an item.
18856 (arg
18857 (while (< (point) end)
18858 (unless (or (org-at-heading-p) (org-at-item-p))
18859 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18860 (replace-match
18861 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18862 (forward-line)))
18863 ;; Case 4. Normal line without ARG: make the first line of
18864 ;; region an item, and shift indentation of others
18865 ;; lines to set them as item's body.
18866 (t (let* ((bul (org-list-bullet-string "-"))
18867 (bul-len (length bul))
18868 (ref-ind (org-get-indentation)))
18869 (skip-chars-forward " \t")
18870 (insert bul)
18871 (forward-line)
18872 (while (< (point) end)
18873 ;; Ensure that lines less indented than first one
18874 ;; still get included in item body.
18875 (funcall shift-text
18876 (+ ref-ind bul-len)
18877 (min end (save-excursion (or (outline-next-heading)
18878 (point)))))
18879 (forward-line)))))))))
18881 (defun org-toggle-heading (&optional nstars)
18882 "Convert headings to normal text, or items or text to headings.
18883 If there is no active region, only the current line is considered.
18885 If the first non blank line is an headline, remove the stars from
18886 all headlines in the region.
18888 If it is a plain list item, turn all plain list items into headings.
18890 If it is a normal line, turn each and every normal line (i.e. not
18891 an heading or an item) in the region into a heading.
18893 When converting a line into a heading, the number of stars is chosen
18894 such that the lines become children of the current entry. However,
18895 when a prefix argument is given, its value determines the number of
18896 stars to add."
18897 (interactive "P")
18898 (let ((skip-blanks
18899 (function
18900 ;; Return beginning of first non-blank line, starting from
18901 ;; line at POS.
18902 (lambda (pos)
18903 (save-excursion
18904 (goto-char pos)
18905 (skip-chars-forward " \r\t\n")
18906 (point-at-bol)))))
18907 beg end)
18908 ;; Determine boundaries of changes. If region ends at a bol, do
18909 ;; not consider the last line to be in the region.
18910 (if (org-region-active-p)
18911 (setq beg (funcall skip-blanks (region-beginning))
18912 end (copy-marker (save-excursion
18913 (goto-char (region-end))
18914 (if (bolp) (point) (point-at-eol)))))
18915 (setq beg (funcall skip-blanks (point-at-bol))
18916 end (copy-marker (point-at-eol))))
18917 ;; Ensure inline tasks don't count as headings.
18918 (org-with-limited-levels
18919 (save-excursion
18920 (goto-char beg)
18921 (cond
18922 ;; Case 1. Started at an heading: de-star headings.
18923 ((org-at-heading-p)
18924 (while (< (point) end)
18925 (when (org-at-heading-p t)
18926 (looking-at org-outline-regexp) (replace-match ""))
18927 (forward-line)))
18928 ;; Case 2. Started at an item: change items into headlines.
18929 ;; One star will be added by `org-list-to-subtree'.
18930 ((org-at-item-p)
18931 (let* ((stars (make-string
18932 (if nstars
18933 ;; subtract the star that will be added again by
18934 ;; `org-list-to-subtree'
18935 (1- (prefix-numeric-value current-prefix-arg))
18936 (or (org-current-level) 0))
18937 ?*))
18938 (add-stars
18939 (cond (nstars "") ; stars from prefix only
18940 ((equal stars "") "") ; before first heading
18941 (org-odd-levels-only "*") ; inside heading, odd
18942 (t "")))) ; inside heading, oddeven
18943 (while (< (point) end)
18944 (when (org-at-item-p)
18945 ;; Pay attention to cases when region ends before list.
18946 (let* ((struct (org-list-struct))
18947 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18948 (save-restriction
18949 (narrow-to-region (point) list-end)
18950 (insert
18951 (org-list-to-subtree
18952 (org-list-parse-list t)
18953 '(:istart (concat stars add-stars (funcall get-stars depth))
18954 :icount (concat stars add-stars (funcall get-stars depth))))))))
18955 (forward-line))))
18956 ;; Case 3. Started at normal text: make every line an heading,
18957 ;; skipping headlines and items.
18958 (t (let* ((stars (make-string
18959 (if nstars
18960 (prefix-numeric-value current-prefix-arg)
18961 (or (org-current-level) 0))
18962 ?*))
18963 (add-stars
18964 (cond (nstars "") ; stars from prefix only
18965 ((equal stars "") "*") ; before first heading
18966 (org-odd-levels-only "**") ; inside heading, odd
18967 (t "*"))) ; inside heading, oddeven
18968 (rpl (concat stars add-stars " ")))
18969 (while (< (point) end)
18970 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18971 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18972 (replace-match (concat rpl (match-string 2))))
18973 (forward-line)))))))))
18975 (defun org-meta-return (&optional arg)
18976 "Insert a new heading or wrap a region in a table.
18977 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18978 See the individual commands for more information."
18979 (interactive "P")
18980 (cond
18981 ((run-hook-with-args-until-success 'org-metareturn-hook))
18982 ((or (org-at-drawer-p) (org-at-property-p))
18983 (newline-and-indent))
18984 ((org-at-table-p)
18985 (call-interactively 'org-table-wrap-region))
18986 (t (call-interactively 'org-insert-heading))))
18988 ;;; Menu entries
18990 ;; Define the Org-mode menus
18991 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18992 '("Tbl"
18993 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18994 ["Next Field" org-cycle (org-at-table-p)]
18995 ["Previous Field" org-shifttab (org-at-table-p)]
18996 ["Next Row" org-return (org-at-table-p)]
18997 "--"
18998 ["Blank Field" org-table-blank-field (org-at-table-p)]
18999 ["Edit Field" org-table-edit-field (org-at-table-p)]
19000 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19001 "--"
19002 ("Column"
19003 ["Move Column Left" org-metaleft (org-at-table-p)]
19004 ["Move Column Right" org-metaright (org-at-table-p)]
19005 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19006 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19007 ("Row"
19008 ["Move Row Up" org-metaup (org-at-table-p)]
19009 ["Move Row Down" org-metadown (org-at-table-p)]
19010 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19011 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19012 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19013 "--"
19014 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19015 ("Rectangle"
19016 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19017 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19018 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19019 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19020 "--"
19021 ("Calculate"
19022 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19023 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19024 ["Edit Formulas" org-edit-special (org-at-table-p)]
19025 "--"
19026 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19027 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19028 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19029 "--"
19030 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19031 "--"
19032 ["Sum Column/Rectangle" org-table-sum
19033 (or (org-at-table-p) (org-region-active-p))]
19034 ["Which Column?" org-table-current-column (org-at-table-p)])
19035 ["Debug Formulas"
19036 org-table-toggle-formula-debugger
19037 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19038 ["Show Col/Row Numbers"
19039 org-table-toggle-coordinate-overlays
19040 :style toggle
19041 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19042 "--"
19043 ["Create" org-table-create (and (not (org-at-table-p))
19044 org-enable-table-editor)]
19045 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19046 ["Import from File" org-table-import (not (org-at-table-p))]
19047 ["Export to File" org-table-export (org-at-table-p)]
19048 "--"
19049 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19051 (easy-menu-define org-org-menu org-mode-map "Org menu"
19052 '("Org"
19053 ("Show/Hide"
19054 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19055 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19056 ["Sparse Tree..." org-sparse-tree t]
19057 ["Reveal Context" org-reveal t]
19058 ["Show All" show-all t]
19059 "--"
19060 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19061 "--"
19062 ["New Heading" org-insert-heading t]
19063 ("Navigate Headings"
19064 ["Up" outline-up-heading t]
19065 ["Next" outline-next-visible-heading t]
19066 ["Previous" outline-previous-visible-heading t]
19067 ["Next Same Level" outline-forward-same-level t]
19068 ["Previous Same Level" outline-backward-same-level t]
19069 "--"
19070 ["Jump" org-goto t])
19071 ("Edit Structure"
19072 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19073 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19074 "--"
19075 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19076 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19077 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19078 "--"
19079 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19080 "--"
19081 ["Copy visible text" org-copy-visible t]
19082 "--"
19083 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19084 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19085 ["Demote Heading" org-metaright (not (org-at-table-p))]
19086 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19087 "--"
19088 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19089 "--"
19090 ["Convert to odd levels" org-convert-to-odd-levels t]
19091 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19092 ("Editing"
19093 ["Emphasis..." org-emphasize t]
19094 ["Edit Source Example" org-edit-special t]
19095 "--"
19096 ["Footnote new/jump" org-footnote-action t]
19097 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19098 ("Archive"
19099 ["Archive (default method)" org-archive-subtree-default t]
19100 "--"
19101 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19102 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19103 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19105 "--"
19106 ("Hyperlinks"
19107 ["Store Link (Global)" org-store-link t]
19108 ["Find existing link to here" org-occur-link-in-agenda-files t]
19109 ["Insert Link" org-insert-link t]
19110 ["Follow Link" org-open-at-point t]
19111 "--"
19112 ["Next link" org-next-link t]
19113 ["Previous link" org-previous-link t]
19114 "--"
19115 ["Descriptive Links"
19116 org-toggle-link-display
19117 :style radio
19118 :selected org-descriptive-links
19120 ["Literal Links"
19121 org-toggle-link-display
19122 :style radio
19123 :selected (not org-descriptive-links)])
19124 "--"
19125 ("TODO Lists"
19126 ["TODO/DONE/-" org-todo t]
19127 ("Select keyword"
19128 ["Next keyword" org-shiftright (org-at-heading-p)]
19129 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19130 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19131 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19132 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19133 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19134 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19135 "--"
19136 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19137 :selected org-enforce-todo-dependencies :style toggle :active t]
19138 "Settings for tree at point"
19139 ["Do Children sequentially" org-toggle-ordered-property :style radio
19140 :selected (org-entry-get nil "ORDERED")
19141 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19142 ["Do Children parallel" org-toggle-ordered-property :style radio
19143 :selected (not (org-entry-get nil "ORDERED"))
19144 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19145 "--"
19146 ["Set Priority" org-priority t]
19147 ["Priority Up" org-shiftup t]
19148 ["Priority Down" org-shiftdown t]
19149 "--"
19150 ["Get news from all feeds" org-feed-update-all t]
19151 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19152 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19153 ("TAGS and Properties"
19154 ["Set Tags" org-set-tags-command t]
19155 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19156 "--"
19157 ["Set property" org-set-property t]
19158 ["Column view of properties" org-columns t]
19159 ["Insert Column View DBlock" org-insert-columns-dblock t])
19160 ("Dates and Scheduling"
19161 ["Timestamp" org-time-stamp t]
19162 ["Timestamp (inactive)" org-time-stamp-inactive t]
19163 ("Change Date"
19164 ["1 Day Later" org-shiftright t]
19165 ["1 Day Earlier" org-shiftleft t]
19166 ["1 ... Later" org-shiftup t]
19167 ["1 ... Earlier" org-shiftdown t])
19168 ["Compute Time Range" org-evaluate-time-range t]
19169 ["Schedule Item" org-schedule t]
19170 ["Deadline" org-deadline t]
19171 "--"
19172 ["Custom time format" org-toggle-time-stamp-overlays
19173 :style radio :selected org-display-custom-times]
19174 "--"
19175 ["Goto Calendar" org-goto-calendar t]
19176 ["Date from Calendar" org-date-from-calendar t]
19177 "--"
19178 ["Start/Restart Timer" org-timer-start t]
19179 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19180 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19181 ["Insert Timer String" org-timer t]
19182 ["Insert Timer Item" org-timer-item t])
19183 ("Logging work"
19184 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19185 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19186 ["Clock out" org-clock-out t]
19187 ["Clock cancel" org-clock-cancel t]
19188 "--"
19189 ["Mark as default task" org-clock-mark-default-task t]
19190 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19191 ["Goto running clock" org-clock-goto t]
19192 "--"
19193 ["Display times" org-clock-display t]
19194 ["Create clock table" org-clock-report t]
19195 "--"
19196 ["Record DONE time"
19197 (progn (setq org-log-done (not org-log-done))
19198 (message "Switching to %s will %s record a timestamp"
19199 (car org-done-keywords)
19200 (if org-log-done "automatically" "not")))
19201 :style toggle :selected org-log-done])
19202 "--"
19203 ["Agenda Command..." org-agenda t]
19204 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19205 ("File List for Agenda")
19206 ("Special views current file"
19207 ["TODO Tree" org-show-todo-tree t]
19208 ["Check Deadlines" org-check-deadlines t]
19209 ["Timeline" org-timeline t]
19210 ["Tags/Property tree" org-match-sparse-tree t])
19211 "--"
19212 ["Export/Publish..." org-export t]
19213 ("LaTeX"
19214 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19215 :selected org-cdlatex-mode]
19216 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19217 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19218 ["Modify math symbol" org-cdlatex-math-modify
19219 (org-inside-LaTeX-fragment-p)]
19220 ["Insert citation" org-reftex-citation t]
19221 "--"
19222 ["Template for BEAMER" (progn (require 'org-beamer)
19223 (org-insert-beamer-options-template)) t])
19224 "--"
19225 ("MobileOrg"
19226 ["Push Files and Views" org-mobile-push t]
19227 ["Get Captured and Flagged" org-mobile-pull t]
19228 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19229 "--"
19230 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19231 "--"
19232 ("Documentation"
19233 ["Show Version" org-version t]
19234 ["Info Documentation" org-info t])
19235 ("Customize"
19236 ["Browse Org Group" org-customize t]
19237 "--"
19238 ["Expand This Menu" org-create-customize-menu
19239 (fboundp 'customize-menu-create)])
19240 ["Send bug report" org-submit-bug-report t]
19241 "--"
19242 ("Refresh/Reload"
19243 ["Refresh setup current buffer" org-mode-restart t]
19244 ["Reload Org (after update)" org-reload t]
19245 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19248 (defun org-info (&optional node)
19249 "Read documentation for Org-mode in the info system.
19250 With optional NODE, go directly to that node."
19251 (interactive)
19252 (info (format "(org)%s" (or node ""))))
19254 ;;;###autoload
19255 (defun org-submit-bug-report ()
19256 "Submit a bug report on Org-mode via mail.
19258 Don't hesitate to report any problems or inaccurate documentation.
19260 If you don't have setup sending mail from (X)Emacs, please copy the
19261 output buffer into your mail program, as it gives us important
19262 information about your Org-mode version and configuration."
19263 (interactive)
19264 (require 'reporter)
19265 (org-load-modules-maybe)
19266 (org-require-autoloaded-modules)
19267 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19268 (reporter-submit-bug-report
19269 "emacs-orgmode@gnu.org"
19270 (org-version)
19271 (let (list)
19272 (save-window-excursion
19273 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19274 (delete-other-windows)
19275 (erase-buffer)
19276 (insert "You are about to submit a bug report to the Org-mode mailing list.
19278 We would like to add your full Org-mode and Outline configuration to the
19279 bug report. This greatly simplifies the work of the maintainer and
19280 other experts on the mailing list.
19282 HOWEVER, some variables you have customized may contain private
19283 information. The names of customers, colleagues, or friends, might
19284 appear in the form of file names, tags, todo states, or search strings.
19285 If you answer yes to the prompt, you might want to check and remove
19286 such private information before sending the email.")
19287 (add-text-properties (point-min) (point-max) '(face org-warning))
19288 (when (yes-or-no-p "Include your Org-mode configuration ")
19289 (mapatoms
19290 (lambda (v)
19291 (and (boundp v)
19292 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19293 (or (and (symbol-value v)
19294 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19295 (and
19296 (get v 'custom-type) (get v 'standard-value)
19297 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19298 (push v list)))))
19299 (kill-buffer (get-buffer "*Warn about privacy*"))
19300 list))
19301 nil nil
19302 "Remember to cover the basics, that is, what you expected to happen and
19303 what in fact did happen. You don't know how to make a good report? See
19305 http://orgmode.org/manual/Feedback.html#Feedback
19307 Your bug report will be posted to the Org-mode mailing list.
19308 ------------------------------------------------------------------------")
19309 (save-excursion
19310 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19311 (replace-match "\\1Bug: \\3 [\\2]")))))
19314 (defun org-install-agenda-files-menu ()
19315 (let ((bl (buffer-list)))
19316 (save-excursion
19317 (while bl
19318 (set-buffer (pop bl))
19319 (if (eq major-mode 'org-mode) (setq bl nil)))
19320 (when (eq major-mode 'org-mode)
19321 (easy-menu-change
19322 '("Org") "File List for Agenda"
19323 (append
19324 (list
19325 ["Edit File List" (org-edit-agenda-file-list) t]
19326 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19327 ["Remove Current File from List" org-remove-file t]
19328 ["Cycle through agenda files" org-cycle-agenda-files t]
19329 ["Occur in all agenda files" org-occur-in-agenda-files t]
19330 "--")
19331 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19333 ;;;; Documentation
19335 ;;;###autoload
19336 (defun org-require-autoloaded-modules ()
19337 (interactive)
19338 (mapc 'require
19339 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19340 org-docbook org-exp org-html org-icalendar
19341 org-id org-latex
19342 org-publish org-remember org-table
19343 org-timer org-xoxo)))
19345 ;;;###autoload
19346 (defun org-reload (&optional uncompiled)
19347 "Reload all org lisp files.
19348 With prefix arg UNCOMPILED, load the uncompiled versions."
19349 (interactive "P")
19350 (require 'find-func)
19351 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19352 (dir-org (file-name-directory (org-find-library-name "org")))
19353 (dir-org-contrib (ignore-errors
19354 (file-name-directory
19355 (org-find-library-name "org-contribdir"))))
19356 (babel-files
19357 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19358 (append (list nil "comint" "eval" "exp" "keys"
19359 "lob" "ref" "table" "tangle")
19360 (delq nil
19361 (mapcar
19362 (lambda (lang)
19363 (when (cdr lang) (symbol-name (car lang))))
19364 org-babel-load-languages)))))
19365 (files
19366 (append (directory-files dir-org t file-re)
19367 babel-files
19368 (and dir-org-contrib
19369 (directory-files dir-org-contrib t file-re))))
19370 (remove-re (concat (if (featurep 'xemacs)
19371 "org-colview" "org-colview-xemacs")
19372 "\\'")))
19373 (setq files (mapcar 'file-name-sans-extension files))
19374 (setq files (mapcar
19375 (lambda (x) (if (string-match remove-re x) nil x))
19376 files))
19377 (setq files (delq nil files))
19378 (mapc
19379 (lambda (f)
19380 (when (featurep (intern (file-name-nondirectory f)))
19381 (if (and (not uncompiled)
19382 (file-exists-p (concat f ".elc")))
19383 (load (concat f ".elc") nil nil t)
19384 (load (concat f ".el") nil nil t))))
19385 files))
19386 (org-version))
19388 ;;;###autoload
19389 (defun org-customize ()
19390 "Call the customize function with org as argument."
19391 (interactive)
19392 (org-load-modules-maybe)
19393 (org-require-autoloaded-modules)
19394 (customize-browse 'org))
19396 (defun org-create-customize-menu ()
19397 "Create a full customization menu for Org-mode, insert it into the menu."
19398 (interactive)
19399 (org-load-modules-maybe)
19400 (org-require-autoloaded-modules)
19401 (if (fboundp 'customize-menu-create)
19402 (progn
19403 (easy-menu-change
19404 '("Org") "Customize"
19405 `(["Browse Org group" org-customize t]
19406 "--"
19407 ,(customize-menu-create 'org)
19408 ["Set" Custom-set t]
19409 ["Save" Custom-save t]
19410 ["Reset to Current" Custom-reset-current t]
19411 ["Reset to Saved" Custom-reset-saved t]
19412 ["Reset to Standard Settings" Custom-reset-standard t]))
19413 (message "\"Org\"-menu now contains full customization menu"))
19414 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19416 ;;;; Miscellaneous stuff
19418 ;;; Generally useful functions
19420 (defun org-get-at-bol (property)
19421 "Get text property PROPERTY at beginning of line."
19422 (get-text-property (point-at-bol) property))
19424 (defun org-find-text-property-in-string (prop s)
19425 "Return the first non-nil value of property PROP in string S."
19426 (or (get-text-property 0 prop s)
19427 (get-text-property (or (next-single-property-change 0 prop s) 0)
19428 prop s)))
19430 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19431 "Display the given MESSAGE as a warning."
19432 (if (fboundp 'display-warning)
19433 (display-warning 'org message
19434 (if (featurep 'xemacs) 'warning :warning))
19435 (let ((buf (get-buffer-create "*Org warnings*")))
19436 (with-current-buffer buf
19437 (goto-char (point-max))
19438 (insert "Warning (Org): " message)
19439 (unless (bolp)
19440 (newline)))
19441 (display-buffer buf)
19442 (sit-for 0))))
19444 (defun org-eval (form)
19445 "Eval FORM and return result."
19446 (condition-case error
19447 (eval form)
19448 (error (format "%%![Error: %s]" error))))
19450 (defun org-in-clocktable-p ()
19451 "Check if the cursor is in a clocktable."
19452 (let ((pos (point)) start)
19453 (save-excursion
19454 (end-of-line 1)
19455 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19456 (setq start (match-beginning 0))
19457 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19458 (>= (match-end 0) pos)
19459 start))))
19461 (defun org-in-commented-line ()
19462 "Is point in a line starting with `#'?"
19463 (equal (char-after (point-at-bol)) ?#))
19465 (defun org-in-indented-comment-line ()
19466 "Is point in a line starting with `#' after some white space?"
19467 (save-excursion
19468 (save-match-data
19469 (goto-char (point-at-bol))
19470 (looking-at "[ \t]*#"))))
19472 (defun org-in-verbatim-emphasis ()
19473 (save-match-data
19474 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19476 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19477 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19478 (if (and marker (marker-buffer marker)
19479 (buffer-live-p (marker-buffer marker)))
19480 (progn
19481 (org-pop-to-buffer-same-window (marker-buffer marker))
19482 (if (or (> marker (point-max)) (< marker (point-min)))
19483 (widen))
19484 (goto-char marker)
19485 (org-show-context 'org-goto))
19486 (if bookmark
19487 (bookmark-jump bookmark)
19488 (error "Cannot find location"))))
19490 (defun org-quote-csv-field (s)
19491 "Quote field for inclusion in CSV material."
19492 (if (string-match "[\",]" s)
19493 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19496 (defun org-force-self-insert (N)
19497 "Needed to enforce self-insert under remapping."
19498 (interactive "p")
19499 (self-insert-command N))
19501 (defun org-string-width (s)
19502 "Compute width of string, ignoring invisible characters.
19503 This ignores character with invisibility property `org-link', and also
19504 characters with property `org-cwidth', because these will become invisible
19505 upon the next fontification round."
19506 (let (b l)
19507 (when (or (eq t buffer-invisibility-spec)
19508 (assq 'org-link buffer-invisibility-spec))
19509 (while (setq b (text-property-any 0 (length s)
19510 'invisible 'org-link s))
19511 (setq s (concat (substring s 0 b)
19512 (substring s (or (next-single-property-change
19513 b 'invisible s) (length s)))))))
19514 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19515 (setq s (concat (substring s 0 b)
19516 (substring s (or (next-single-property-change
19517 b 'org-cwidth s) (length s))))))
19518 (setq l (string-width s) b -1)
19519 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19520 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19523 (defun org-shorten-string (s maxlength)
19524 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19525 If the string is shorter or has length MAXLENGTH, just return the
19526 original string. If it is longer, the functions finds a space in the
19527 string, breaks this string off at that locations and adds three dots
19528 as ellipsis. Including the ellipsis, the string will not be longer
19529 than MAXLENGTH. If finding a good breaking point in the string does
19530 not work, the string is just chopped off in the middle of a word
19531 if necessary."
19532 (if (<= (length s) maxlength)
19534 (let* ((n (max (- maxlength 4) 1))
19535 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19536 (if (string-match re s)
19537 (concat (match-string 1 s) "...")
19538 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19540 (defun org-get-indentation (&optional line)
19541 "Get the indentation of the current line, interpreting tabs.
19542 When LINE is given, assume it represents a line and compute its indentation."
19543 (if line
19544 (if (string-match "^ *" (org-remove-tabs line))
19545 (match-end 0))
19546 (save-excursion
19547 (beginning-of-line 1)
19548 (skip-chars-forward " \t")
19549 (current-column))))
19551 (defun org-get-string-indentation (s)
19552 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19553 (let ((n -1) (i 0) (w tab-width) c)
19554 (catch 'exit
19555 (while (< (setq n (1+ n)) (length s))
19556 (setq c (aref s n))
19557 (cond ((= c ?\ ) (setq i (1+ i)))
19558 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19559 (t (throw 'exit t)))))
19562 (defun org-remove-tabs (s &optional width)
19563 "Replace tabulators in S with spaces.
19564 Assumes that s is a single line, starting in column 0."
19565 (setq width (or width tab-width))
19566 (while (string-match "\t" s)
19567 (setq s (replace-match
19568 (make-string
19569 (- (* width (/ (+ (match-beginning 0) width) width))
19570 (match-beginning 0)) ?\ )
19571 t t s)))
19574 (defun org-fix-indentation (line ind)
19575 "Fix indentation in LINE.
19576 IND is a cons cell with target and minimum indentation.
19577 If the current indentation in LINE is smaller than the minimum,
19578 leave it alone. If it is larger than ind, set it to the target."
19579 (let* ((l (org-remove-tabs line))
19580 (i (org-get-indentation l))
19581 (i1 (car ind)) (i2 (cdr ind)))
19582 (if (>= i i2) (setq l (substring line i2)))
19583 (if (> i1 0)
19584 (concat (make-string i1 ?\ ) l)
19585 l)))
19587 (defun org-remove-indentation (code &optional n)
19588 "Remove the maximum common indentation from the lines in CODE.
19589 N may optionally be the number of spaces to remove."
19590 (with-temp-buffer
19591 (insert code)
19592 (org-do-remove-indentation n)
19593 (buffer-string)))
19595 (defun org-do-remove-indentation (&optional n)
19596 "Remove the maximum common indentation from the buffer."
19597 (untabify (point-min) (point-max))
19598 (let ((min 10000) re)
19599 (if n
19600 (setq min n)
19601 (goto-char (point-min))
19602 (while (re-search-forward "^ *[^ \n]" nil t)
19603 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19604 (unless (or (= min 0) (= min 10000))
19605 (setq re (format "^ \\{%d\\}" min))
19606 (goto-char (point-min))
19607 (while (re-search-forward re nil t)
19608 (replace-match "")
19609 (end-of-line 1))
19610 min)))
19612 (defun org-fill-template (template alist)
19613 "Find each %key of ALIST in TEMPLATE and replace it."
19614 (let ((case-fold-search nil)
19615 entry key value)
19616 (setq alist (sort (copy-sequence alist)
19617 (lambda (a b) (< (length (car a)) (length (car b))))))
19618 (while (setq entry (pop alist))
19619 (setq template
19620 (replace-regexp-in-string
19621 (concat "%" (regexp-quote (car entry)))
19622 (cdr entry) template t t)))
19623 template))
19625 (defun org-base-buffer (buffer)
19626 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19627 (if (not buffer)
19628 buffer
19629 (or (buffer-base-buffer buffer)
19630 buffer)))
19632 (defun org-trim (s)
19633 "Remove whitespace at beginning and end of string."
19634 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19635 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19638 (defun org-wrap (string &optional width lines)
19639 "Wrap string to either a number of lines, or a width in characters.
19640 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19641 that costs. If there is a word longer than WIDTH, the text is actually
19642 wrapped to the length of that word.
19643 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19644 many lines, whatever width that takes.
19645 The return value is a list of lines, without newlines at the end."
19646 (let* ((words (org-split-string string "[ \t\n]+"))
19647 (maxword (apply 'max (mapcar 'org-string-width words)))
19648 w ll)
19649 (cond (width
19650 (org-do-wrap words (max maxword width)))
19651 (lines
19652 (setq w maxword)
19653 (setq ll (org-do-wrap words maxword))
19654 (if (<= (length ll) lines)
19656 (setq ll words)
19657 (while (> (length ll) lines)
19658 (setq w (1+ w))
19659 (setq ll (org-do-wrap words w)))
19660 ll))
19661 (t (error "Cannot wrap this")))))
19663 (defun org-do-wrap (words width)
19664 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19665 (let (lines line)
19666 (while words
19667 (setq line (pop words))
19668 (while (and words (< (+ (length line) (length (car words))) width))
19669 (setq line (concat line " " (pop words))))
19670 (setq lines (push line lines)))
19671 (nreverse lines)))
19673 (defun org-split-string (string &optional separators)
19674 "Splits STRING into substrings at SEPARATORS.
19675 No empty strings are returned if there are matches at the beginning
19676 and end of string."
19677 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19678 (start 0)
19679 notfirst
19680 (list nil))
19681 (while (and (string-match rexp string
19682 (if (and notfirst
19683 (= start (match-beginning 0))
19684 (< start (length string)))
19685 (1+ start) start))
19686 (< (match-beginning 0) (length string)))
19687 (setq notfirst t)
19688 (or (eq (match-beginning 0) 0)
19689 (and (eq (match-beginning 0) (match-end 0))
19690 (eq (match-beginning 0) start))
19691 (setq list
19692 (cons (substring string start (match-beginning 0))
19693 list)))
19694 (setq start (match-end 0)))
19695 (or (eq start (length string))
19696 (setq list
19697 (cons (substring string start)
19698 list)))
19699 (nreverse list)))
19701 (defun org-quote-vert (s)
19702 "Replace \"|\" with \"\\vert\"."
19703 (while (string-match "|" s)
19704 (setq s (replace-match "\\vert" t t s)))
19707 (defun org-uuidgen-p (s)
19708 "Is S an ID created by UUIDGEN?"
19709 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19711 (defun org-in-src-block-p nil
19712 "Whether point is in a code source block."
19713 (let (ov)
19714 (when (setq ov (overlays-at (point)))
19715 (memq 'org-block-background
19716 (overlay-properties
19717 (car ov))))))
19719 (defun org-context ()
19720 "Return a list of contexts of the current cursor position.
19721 If several contexts apply, all are returned.
19722 Each context entry is a list with a symbol naming the context, and
19723 two positions indicating start and end of the context. Possible
19724 contexts are:
19726 :headline anywhere in a headline
19727 :headline-stars on the leading stars in a headline
19728 :todo-keyword on a TODO keyword (including DONE) in a headline
19729 :tags on the TAGS in a headline
19730 :priority on the priority cookie in a headline
19731 :item on the first line of a plain list item
19732 :item-bullet on the bullet/number of a plain list item
19733 :checkbox on the checkbox in a plain list item
19734 :table in an org-mode table
19735 :table-special on a special filed in a table
19736 :table-table in a table.el table
19737 :clocktable in a clocktable
19738 :src-block in a source block
19739 :link on a hyperlink
19740 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19741 :target on a <<target>>
19742 :radio-target on a <<<radio-target>>>
19743 :latex-fragment on a LaTeX fragment
19744 :latex-preview on a LaTeX fragment with overlaid preview image
19746 This function expects the position to be visible because it uses font-lock
19747 faces as a help to recognize the following contexts: :table-special, :link,
19748 and :keyword."
19749 (let* ((f (get-text-property (point) 'face))
19750 (faces (if (listp f) f (list f)))
19751 (case-fold-search t)
19752 (p (point)) clist o)
19753 ;; First the large context
19754 (cond
19755 ((org-at-heading-p t)
19756 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19757 (when (progn
19758 (beginning-of-line 1)
19759 (looking-at org-todo-line-tags-regexp))
19760 (push (org-point-in-group p 1 :headline-stars) clist)
19761 (push (org-point-in-group p 2 :todo-keyword) clist)
19762 (push (org-point-in-group p 4 :tags) clist))
19763 (goto-char p)
19764 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19765 (if (looking-at "\\[#[A-Z0-9]\\]")
19766 (push (org-point-in-group p 0 :priority) clist)))
19768 ((org-at-item-p)
19769 (push (org-point-in-group p 2 :item-bullet) clist)
19770 (push (list :item (point-at-bol)
19771 (save-excursion (org-end-of-item) (point)))
19772 clist)
19773 (and (org-at-item-checkbox-p)
19774 (push (org-point-in-group p 0 :checkbox) clist)))
19776 ((org-at-table-p)
19777 (push (list :table (org-table-begin) (org-table-end)) clist)
19778 (if (memq 'org-formula faces)
19779 (push (list :table-special
19780 (previous-single-property-change p 'face)
19781 (next-single-property-change p 'face)) clist)))
19782 ((org-at-table-p 'any)
19783 (push (list :table-table) clist)))
19784 (goto-char p)
19786 ;; New the "medium" contexts: clocktables, source blocks
19787 (cond ((org-in-clocktable-p)
19788 (push (list :clocktable
19789 (and (or (looking-at "#\\+BEGIN: clocktable")
19790 (search-backward "#+BEGIN: clocktable" nil t))
19791 (match-beginning 0))
19792 (and (re-search-forward "#\\+END:?" nil t)
19793 (match-end 0))) clist))
19794 ((org-in-src-block-p)
19795 (push (list :src-block
19796 (and (or (looking-at "#\\+BEGIN_SRC")
19797 (search-backward "#+BEGIN_SRC" nil t))
19798 (match-beginning 0))
19799 (and (search-forward "#+END_SRC" nil t)
19800 (match-beginning 0))) clist)))
19801 (goto-char p)
19803 ;; Now the small context
19804 (cond
19805 ((org-at-timestamp-p)
19806 (push (org-point-in-group p 0 :timestamp) clist))
19807 ((memq 'org-link faces)
19808 (push (list :link
19809 (previous-single-property-change p 'face)
19810 (next-single-property-change p 'face)) clist))
19811 ((memq 'org-special-keyword faces)
19812 (push (list :keyword
19813 (previous-single-property-change p 'face)
19814 (next-single-property-change p 'face)) clist))
19815 ((org-at-target-p)
19816 (push (org-point-in-group p 0 :target) clist)
19817 (goto-char (1- (match-beginning 0)))
19818 (if (looking-at org-radio-target-regexp)
19819 (push (org-point-in-group p 0 :radio-target) clist))
19820 (goto-char p))
19821 ((setq o (car (delq nil
19822 (mapcar
19823 (lambda (x)
19824 (if (memq x org-latex-fragment-image-overlays) x))
19825 (overlays-at (point))))))
19826 (push (list :latex-fragment
19827 (overlay-start o) (overlay-end o)) clist)
19828 (push (list :latex-preview
19829 (overlay-start o) (overlay-end o)) clist))
19830 ((org-inside-LaTeX-fragment-p)
19831 ;; FIXME: positions wrong.
19832 (push (list :latex-fragment (point) (point)) clist)))
19834 (setq clist (nreverse (delq nil clist)))
19835 clist))
19837 ;; FIXME: Compare with at-regexp-p Do we need both?
19838 (defun org-in-regexp (re &optional nlines visually)
19839 "Check if point is inside a match of regexp.
19840 Normally only the current line is checked, but you can include NLINES extra
19841 lines both before and after point into the search.
19842 If VISUALLY is set, require that the cursor is not after the match but
19843 really on, so that the block visually is on the match."
19844 (catch 'exit
19845 (let ((pos (point))
19846 (eol (point-at-eol (+ 1 (or nlines 0))))
19847 (inc (if visually 1 0)))
19848 (save-excursion
19849 (beginning-of-line (- 1 (or nlines 0)))
19850 (while (re-search-forward re eol t)
19851 (if (and (<= (match-beginning 0) pos)
19852 (>= (+ inc (match-end 0)) pos))
19853 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19855 (defun org-at-regexp-p (regexp)
19856 "Is point inside a match of REGEXP in the current line?"
19857 (catch 'exit
19858 (save-excursion
19859 (let ((pos (point)) (end (point-at-eol)))
19860 (beginning-of-line 1)
19861 (while (re-search-forward regexp end t)
19862 (if (and (<= (match-beginning 0) pos)
19863 (>= (match-end 0) pos))
19864 (throw 'exit t)))
19865 nil))))
19867 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19868 "Non-nil when point is between matches of START-RE and END-RE.
19870 Also return a non-nil value when point is on one of the matches.
19872 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19873 buffer positions. Default values are the positions of headlines
19874 surrounding the point.
19876 The functions returns a cons cell whose car (resp. cdr) is the
19877 position before START-RE (resp. after END-RE)."
19878 (save-match-data
19879 (let ((pos (point))
19880 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19881 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19882 beg end)
19883 (save-excursion
19884 ;; Point is on a block when on START-RE or if START-RE can be
19885 ;; found before it...
19886 (and (or (org-at-regexp-p start-re)
19887 (re-search-backward start-re limit-up t))
19888 (setq beg (match-beginning 0))
19889 ;; ... and END-RE after it...
19890 (goto-char (match-end 0))
19891 (re-search-forward end-re limit-down t)
19892 (> (setq end (match-end 0)) pos)
19893 ;; ... without another START-RE in-between.
19894 (goto-char (match-beginning 0))
19895 (not (re-search-backward start-re (1+ beg) t))
19896 ;; Return value.
19897 (cons beg end))))))
19899 (defun org-in-block-p (names)
19900 "Non-nil when point belongs to a block whose name belongs to NAMES.
19902 NAMES is a list of strings containing names of blocks.
19904 Return first block name matched, or nil. Beware that in case of
19905 nested blocks, the returned name may not belong to the closest
19906 block from point."
19907 (save-match-data
19908 (catch 'exit
19909 (let ((case-fold-search t)
19910 (lim-up (save-excursion (outline-previous-heading)))
19911 (lim-down (save-excursion (outline-next-heading))))
19912 (mapc (lambda (name)
19913 (let ((n (regexp-quote name)))
19914 (when (org-between-regexps-p
19915 (concat "^[ \t]*#\\+begin_" n)
19916 (concat "^[ \t]*#\\+end_" n)
19917 lim-up lim-down)
19918 (throw 'exit n))))
19919 names))
19920 nil)))
19922 (defun org-occur-in-agenda-files (regexp &optional nlines)
19923 "Call `multi-occur' with buffers for all agenda files."
19924 (interactive "sOrg-files matching: \np")
19925 (let* ((files (org-agenda-files))
19926 (tnames (mapcar 'file-truename files))
19927 (extra org-agenda-text-search-extra-files)
19929 (when (eq (car extra) 'agenda-archives)
19930 (setq extra (cdr extra))
19931 (setq files (org-add-archive-files files)))
19932 (while (setq f (pop extra))
19933 (unless (member (file-truename f) tnames)
19934 (add-to-list 'files f 'append)
19935 (add-to-list 'tnames (file-truename f) 'append)))
19936 (multi-occur
19937 (mapcar (lambda (x)
19938 (with-current-buffer
19939 (or (get-file-buffer x) (find-file-noselect x))
19940 (widen)
19941 (current-buffer)))
19942 files)
19943 regexp)))
19945 (if (boundp 'occur-mode-find-occurrence-hook)
19946 ;; Emacs 23
19947 (add-hook 'occur-mode-find-occurrence-hook
19948 (lambda ()
19949 (when (eq major-mode 'org-mode)
19950 (org-reveal))))
19951 ;; Emacs 22
19952 (defadvice occur-mode-goto-occurrence
19953 (after org-occur-reveal activate)
19954 (and (eq major-mode 'org-mode) (org-reveal)))
19955 (defadvice occur-mode-goto-occurrence-other-window
19956 (after org-occur-reveal activate)
19957 (and (eq major-mode 'org-mode) (org-reveal)))
19958 (defadvice occur-mode-display-occurrence
19959 (after org-occur-reveal activate)
19960 (when (eq major-mode 'org-mode)
19961 (let ((pos (occur-mode-find-occurrence)))
19962 (with-current-buffer (marker-buffer pos)
19963 (save-excursion
19964 (goto-char pos)
19965 (org-reveal)))))))
19967 (defun org-occur-link-in-agenda-files ()
19968 "Create a link and search for it in the agendas.
19969 The link is not stored in `org-stored-links', it is just created
19970 for the search purpose."
19971 (interactive)
19972 (let ((link (condition-case nil
19973 (org-store-link nil)
19974 (error "Unable to create a link to here"))))
19975 (org-occur-in-agenda-files (regexp-quote link))))
19977 (defun org-uniquify (list)
19978 "Remove duplicate elements from LIST."
19979 (let (res)
19980 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19981 res))
19983 (defun org-delete-all (elts list)
19984 "Remove all elements in ELTS from LIST."
19985 (while elts
19986 (setq list (delete (pop elts) list)))
19987 list)
19989 (defun org-count (cl-item cl-seq)
19990 "Count the number of occurrences of ITEM in SEQ.
19991 Taken from `count' in cl-seq.el with all keyword arguments removed."
19992 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19993 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19994 (while (< cl-start cl-end)
19995 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19996 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19997 (setq cl-start (1+ cl-start)))
19998 cl-count))
20000 (defun org-remove-if (predicate seq)
20001 "Remove everything from SEQ that fulfills PREDICATE."
20002 (let (res e)
20003 (while seq
20004 (setq e (pop seq))
20005 (if (not (funcall predicate e)) (push e res)))
20006 (nreverse res)))
20008 (defun org-remove-if-not (predicate seq)
20009 "Remove everything from SEQ that does not fulfill PREDICATE."
20010 (let (res e)
20011 (while seq
20012 (setq e (pop seq))
20013 (if (funcall predicate e) (push e res)))
20014 (nreverse res)))
20016 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20017 "Reduce two-argument FUNCTION across SEQ.
20018 Taken from `reduce' in cl-seq.el with all keyword arguments but
20019 \":initial-value\" removed."
20020 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20021 (cadr (memq :initial-value cl-keys)))
20022 (cl-seq (pop cl-seq))
20023 (t (funcall cl-func)))))
20024 (while cl-seq
20025 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20026 cl-accum))
20028 (defun org-back-over-empty-lines ()
20029 "Move backwards over whitespace, to the beginning of the first empty line.
20030 Returns the number of empty lines passed."
20031 (let ((pos (point)))
20032 (if (cdr (assoc 'heading org-blank-before-new-entry))
20033 (skip-chars-backward " \t\n\r")
20034 (unless (eobp)
20035 (forward-line -1)))
20036 (beginning-of-line 2)
20037 (goto-char (min (point) pos))
20038 (count-lines (point) pos)))
20040 (defun org-skip-whitespace ()
20041 (skip-chars-forward " \t\n\r"))
20043 (defun org-point-in-group (point group &optional context)
20044 "Check if POINT is in match-group GROUP.
20045 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20046 match. If the match group does not exist or point is not inside it,
20047 return nil."
20048 (and (match-beginning group)
20049 (>= point (match-beginning group))
20050 (<= point (match-end group))
20051 (if context
20052 (list context (match-beginning group) (match-end group))
20053 t)))
20055 (defun org-switch-to-buffer-other-window (&rest args)
20056 "Switch to buffer in a second window on the current frame.
20057 In particular, do not allow pop-up frames.
20058 Returns the newly created buffer."
20059 (let (pop-up-frames special-display-buffer-names special-display-regexps
20060 special-display-function)
20061 (apply 'switch-to-buffer-other-window args)))
20063 (defun org-combine-plists (&rest plists)
20064 "Create a single property list from all plists in PLISTS.
20065 The process starts by copying the first list, and then setting properties
20066 from the other lists. Settings in the last list are the most significant
20067 ones and overrule settings in the other lists."
20068 (let ((rtn (copy-sequence (pop plists)))
20069 p v ls)
20070 (while plists
20071 (setq ls (pop plists))
20072 (while ls
20073 (setq p (pop ls) v (pop ls))
20074 (setq rtn (plist-put rtn p v))))
20075 rtn))
20077 (defun org-move-line-down (arg)
20078 "Move the current line down. With prefix argument, move it past ARG lines."
20079 (interactive "p")
20080 (let ((col (current-column))
20081 beg end pos)
20082 (beginning-of-line 1) (setq beg (point))
20083 (beginning-of-line 2) (setq end (point))
20084 (beginning-of-line (+ 1 arg))
20085 (setq pos (move-marker (make-marker) (point)))
20086 (insert (delete-and-extract-region beg end))
20087 (goto-char pos)
20088 (org-move-to-column col)))
20090 (defun org-move-line-up (arg)
20091 "Move the current line up. With prefix argument, move it past ARG lines."
20092 (interactive "p")
20093 (let ((col (current-column))
20094 beg end pos)
20095 (beginning-of-line 1) (setq beg (point))
20096 (beginning-of-line 2) (setq end (point))
20097 (beginning-of-line (- arg))
20098 (setq pos (move-marker (make-marker) (point)))
20099 (insert (delete-and-extract-region beg end))
20100 (goto-char pos)
20101 (org-move-to-column col)))
20103 (defun org-replace-escapes (string table)
20104 "Replace %-escapes in STRING with values in TABLE.
20105 TABLE is an association list with keys like \"%a\" and string values.
20106 The sequences in STRING may contain normal field width and padding information,
20107 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20108 so values can contain further %-escapes if they are define later in TABLE."
20109 (let ((tbl (copy-alist table))
20110 (case-fold-search nil)
20111 (pchg 0)
20112 e re rpl)
20113 (while (setq e (pop tbl))
20114 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20115 (when (and (cdr e) (string-match re (cdr e)))
20116 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20117 (safe "SREF"))
20118 (add-text-properties 0 3 (list 'sref sref) safe)
20119 (setcdr e (replace-match safe t t (cdr e)))))
20120 (while (string-match re string)
20121 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20122 (cdr e)))
20123 (setq string (replace-match rpl t t string))))
20124 (while (setq pchg (next-property-change pchg string))
20125 (let ((sref (get-text-property pchg 'sref string)))
20126 (when (and sref (string-match "SREF" string pchg))
20127 (setq string (replace-match sref t t string)))))
20128 string))
20130 (defun org-sublist (list start end)
20131 "Return a section of LIST, from START to END.
20132 Counting starts at 1."
20133 (let (rtn (c start))
20134 (setq list (nthcdr (1- start) list))
20135 (while (and list (<= c end))
20136 (push (pop list) rtn)
20137 (setq c (1+ c)))
20138 (nreverse rtn)))
20140 (defun org-find-base-buffer-visiting (file)
20141 "Like `find-buffer-visiting' but always return the base buffer and
20142 not an indirect buffer."
20143 (let ((buf (or (get-file-buffer file)
20144 (find-buffer-visiting file))))
20145 (if buf
20146 (or (buffer-base-buffer buf) buf)
20147 nil)))
20149 (defun org-image-file-name-regexp (&optional extensions)
20150 "Return regexp matching the file names of images.
20151 If EXTENSIONS is given, only match these."
20152 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20153 (image-file-name-regexp)
20154 (let ((image-file-name-extensions
20155 (or extensions
20156 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20157 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20158 (concat "\\."
20159 (regexp-opt (nconc (mapcar 'upcase
20160 image-file-name-extensions)
20161 image-file-name-extensions)
20163 "\\'"))))
20165 (defun org-file-image-p (file &optional extensions)
20166 "Return non-nil if FILE is an image."
20167 (save-match-data
20168 (string-match (org-image-file-name-regexp extensions) file)))
20170 (defun org-get-cursor-date ()
20171 "Return the date at cursor in as a time.
20172 This works in the calendar and in the agenda, anywhere else it just
20173 returns the current time."
20174 (let (date day defd)
20175 (cond
20176 ((eq major-mode 'calendar-mode)
20177 (setq date (calendar-cursor-to-date)
20178 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20179 ((eq major-mode 'org-agenda-mode)
20180 (setq day (get-text-property (point) 'day))
20181 (if day
20182 (setq date (calendar-gregorian-from-absolute day)
20183 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20184 (nth 2 date))))))
20185 (or defd (current-time))))
20187 (defvar org-agenda-action-marker (make-marker)
20188 "Marker pointing to the entry for the next agenda action.")
20190 (defun org-mark-entry-for-agenda-action ()
20191 "Mark the current entry as target of an agenda action.
20192 Agenda actions are actions executed from the agenda with the key `k',
20193 which make use of the date at the cursor."
20194 (interactive)
20195 (move-marker org-agenda-action-marker
20196 (save-excursion (org-back-to-heading t) (point))
20197 (current-buffer))
20198 (message
20199 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20201 (defun org-mark-subtree ()
20202 "Mark the current subtree.
20203 This puts point at the start of the current subtree, and mark at the end.
20205 If point is in an inline task, mark that task instead."
20206 (interactive)
20207 (let ((inline-task-p
20208 (and (featurep 'org-inlinetask)
20209 (org-inlinetask-in-task-p)))
20210 (beg))
20211 ;; Get beginning of subtree
20212 (cond
20213 (inline-task-p (org-inlinetask-goto-beginning))
20214 ((org-at-heading-p) (beginning-of-line))
20215 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20216 (setq beg (point))
20217 ;; Get end of it
20218 (if inline-task-p
20219 (org-inlinetask-goto-end)
20220 (org-end-of-subtree))
20221 ;; Mark zone
20222 (push-mark (point) nil t)
20223 (goto-char beg)))
20225 ;;; Paragraph filling stuff.
20226 ;; We want this to be just right, so use the full arsenal.
20228 (defun org-indent-line-function ()
20229 "Indent line depending on context."
20230 (interactive)
20231 (let* ((pos (point))
20232 (itemp (org-at-item-p))
20233 (case-fold-search t)
20234 (org-drawer-regexp (or org-drawer-regexp "\000"))
20235 (inline-task-p (and (featurep 'org-inlinetask)
20236 (org-inlinetask-in-task-p)))
20237 (inline-re (and inline-task-p
20238 (org-inlinetask-outline-regexp)))
20239 column)
20240 (beginning-of-line 1)
20241 (cond
20242 ;; Comments
20243 ((looking-at "# ") (setq column 0))
20244 ;; Headings
20245 ((looking-at org-outline-regexp) (setq column 0))
20246 ;; Included files
20247 ((looking-at "#\\+include:") (setq column 0))
20248 ;; Footnote definition
20249 ((looking-at org-footnote-definition-re) (setq column 0))
20250 ;; Literal examples
20251 ((looking-at "[ \t]*:\\( \\|$\\)")
20252 (setq column (org-get-indentation))) ; do nothing
20253 ;; Lists
20254 ((ignore-errors (goto-char (org-in-item-p)))
20255 (setq column (if itemp
20256 (org-get-indentation)
20257 (org-list-item-body-column (point))))
20258 (goto-char pos))
20259 ;; Drawers
20260 ((and (looking-at "[ \t]*:END:")
20261 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20262 (save-excursion
20263 (goto-char (1- (match-beginning 1)))
20264 (setq column (current-column))))
20265 ;; Special blocks
20266 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20267 (save-excursion
20268 (re-search-backward
20269 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20270 (setq column (org-get-indentation (match-string 0))))
20271 ((and (not (looking-at "[ \t]*#\\+begin_"))
20272 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20273 (save-excursion
20274 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20275 (setq column
20276 (cond ((equal (downcase (match-string 1)) "src")
20277 ;; src blocks: let `org-edit-src-exit' handle them
20278 (org-get-indentation))
20279 ((equal (downcase (match-string 1)) "example")
20280 (max (org-get-indentation)
20281 (org-get-indentation (match-string 0))))
20283 (org-get-indentation (match-string 0))))))
20284 ;; This line has nothing special, look at the previous relevant
20285 ;; line to compute indentation
20287 (beginning-of-line 0)
20288 (while (and (not (bobp))
20289 (not (looking-at org-drawer-regexp))
20290 ;; When point started in an inline task, do not move
20291 ;; above task starting line.
20292 (not (and inline-task-p (looking-at inline-re)))
20293 ;; Skip drawers, blocks, empty lines, verbatim,
20294 ;; comments, tables, footnotes definitions, lists,
20295 ;; inline tasks.
20296 (or (and (looking-at "[ \t]*:END:")
20297 (re-search-backward org-drawer-regexp nil t))
20298 (and (looking-at "[ \t]*#\\+end_")
20299 (re-search-backward "[ \t]*#\\+begin_"nil t))
20300 (looking-at "[ \t]*[\n:#|]")
20301 (looking-at org-footnote-definition-re)
20302 (and (ignore-errors (goto-char (org-in-item-p)))
20303 (goto-char
20304 (org-list-get-top-point (org-list-struct))))
20305 (and (not inline-task-p)
20306 (featurep 'org-inlinetask)
20307 (org-inlinetask-in-task-p)
20308 (or (org-inlinetask-goto-beginning) t))))
20309 (beginning-of-line 0))
20310 (cond
20311 ;; There was an heading above.
20312 ((looking-at "\\*+[ \t]+")
20313 (if (not org-adapt-indentation)
20314 (setq column 0)
20315 (goto-char (match-end 0))
20316 (setq column (current-column))))
20317 ;; A drawer had started and is unfinished
20318 ((looking-at org-drawer-regexp)
20319 (goto-char (1- (match-beginning 1)))
20320 (setq column (current-column)))
20321 ;; Else, nothing noticeable found: get indentation and go on.
20322 (t (setq column (org-get-indentation))))))
20323 ;; Now apply indentation and move cursor accordingly
20324 (goto-char pos)
20325 (if (<= (current-column) (current-indentation))
20326 (org-indent-line-to column)
20327 (save-excursion (org-indent-line-to column)))
20328 ;; Special polishing for properties, see `org-property-format'
20329 (setq column (current-column))
20330 (beginning-of-line 1)
20331 (if (looking-at
20332 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20333 (replace-match (concat (match-string 1)
20334 (format org-property-format
20335 (match-string 2) (match-string 3)))
20336 t t))
20337 (org-move-to-column column)))
20339 (defun org-indent-drawer ()
20340 "Indent the drawer at point."
20341 (interactive)
20342 (let ((p (point))
20343 (e (and (save-excursion (re-search-forward ":END:" nil t))
20344 (match-end 0)))
20345 (folded
20346 (save-excursion
20347 (end-of-line)
20348 (when (overlays-at (point))
20349 (member 'invisible (overlay-properties
20350 (car (overlays-at (point)))))))))
20351 (when folded (org-cycle))
20352 (indent-for-tab-command)
20353 (while (and (move-beginning-of-line 2) (< (point) e))
20354 (indent-for-tab-command))
20355 (goto-char p)
20356 (when folded (org-cycle)))
20357 (message "Drawer at point indented"))
20359 (defun org-indent-block ()
20360 "Indent the block at point."
20361 (interactive)
20362 (let ((p (point))
20363 (case-fold-search t)
20364 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20365 (match-end 0)))
20366 (folded
20367 (save-excursion
20368 (end-of-line)
20369 (when (overlays-at (point))
20370 (member 'invisible (overlay-properties
20371 (car (overlays-at (point)))))))))
20372 (when folded (org-cycle))
20373 (indent-for-tab-command)
20374 (while (and (move-beginning-of-line 2) (< (point) e))
20375 (indent-for-tab-command))
20376 (goto-char p)
20377 (when folded (org-cycle)))
20378 (message "Block at point indented"))
20380 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20381 "Variable to store copy of `adaptive-fill-regexp'.
20382 Since `adaptive-fill-regexp' is set to never match, we need to
20383 store a backup of its value before entering `org-mode' so that
20384 the functionality can be provided as a fall-back.")
20386 (defun org-set-autofill-regexps ()
20387 (interactive)
20388 ;; In the paragraph separator we include headlines, because filling
20389 ;; text in a line directly attached to a headline would otherwise
20390 ;; fill the headline as well.
20391 (org-set-local 'comment-start-skip "^#+[ \t]*")
20392 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20393 ;; The paragraph starter includes hand-formatted lists.
20394 (org-set-local
20395 'paragraph-start
20396 (concat
20397 "\f" "\\|"
20398 "[ ]*$" "\\|"
20399 org-outline-regexp "\\|"
20400 "[ \t]*#" "\\|"
20401 (org-item-re) "\\|"
20402 "[ \t]*[:|]" "\\|"
20403 "\\$\\$" "\\|"
20404 "\\\\\\(begin\\|end\\|[][]\\)"))
20405 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20406 ;; But only if the user has not turned off tables or fixed-width regions
20407 (org-set-local
20408 'auto-fill-inhibit-regexp
20409 (concat org-outline-regexp
20410 "\\|#\\+"
20411 "\\|[ \t]*" org-keyword-time-regexp
20412 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20413 (concat
20414 "\\|[ \t]*["
20415 (if org-enable-table-editor "|" "")
20416 (if org-enable-fixed-width-editor ":" "")
20417 "]"))))
20418 ;; We use our own fill-paragraph function, to make sure that tables
20419 ;; and fixed-width regions are not wrapped. That function will pass
20420 ;; through to `fill-paragraph' when appropriate.
20421 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20422 ;; Prevent auto-fill from inserting unwanted new items.
20423 (if (boundp 'fill-nobreak-predicate)
20424 (org-set-local
20425 'fill-nobreak-predicate
20426 (org-uniquify
20427 (append fill-nobreak-predicate
20428 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20429 ;; Adaptive filling: To get full control, first make sure that
20430 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20431 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20432 (org-set-local 'org-adaptive-fill-regexp-backup
20433 adaptive-fill-regexp))
20434 (org-set-local 'adaptive-fill-regexp "\000")
20435 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20436 (org-set-local 'adaptive-fill-function
20437 'org-adaptive-fill-function)
20438 (org-set-local
20439 'align-mode-rules-list
20440 '((org-in-buffer-settings
20441 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20442 (modes . '(org-mode))))))
20444 (defun org-fill-item-nobreak-p ()
20445 "Non-nil when a line break at point would insert a new item."
20446 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20448 (defun org-fill-line-break-nobreak-p ()
20449 "Non-nil when a line break at point would create an Org line break."
20450 (save-excursion
20451 (skip-chars-backward "[ \t]")
20452 (skip-chars-backward "\\\\")
20453 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20455 (defun org-fill-paragraph (&optional justify)
20456 "Re-align a table, pass through to fill-paragraph if no table."
20457 (let ((table-p (org-at-table-p))
20458 (table.el-p (org-at-table.el-p))
20459 (itemp (org-in-item-p)))
20460 (cond ((and (equal (char-after (point-at-bol)) ?*)
20461 (save-excursion (goto-char (point-at-bol))
20462 (looking-at org-outline-regexp)))
20463 t) ; skip headlines
20464 (table.el-p t) ; skip table.el tables
20465 (table-p (org-table-align) t) ; align Org tables
20466 (itemp ; align text in items
20467 (let* ((struct (save-excursion (goto-char itemp)
20468 (org-list-struct)))
20469 (parents (org-list-parents-alist struct))
20470 (children (org-list-get-children itemp struct parents))
20471 beg end prev next prefix)
20472 ;; Determine in which part of item point is: before
20473 ;; first child, after last child, between two
20474 ;; sub-lists, or simply in item if there's no child.
20475 (cond
20476 ((not children)
20477 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20478 beg itemp
20479 end (org-list-get-item-end itemp struct)))
20480 ((< (point) (setq next (car children)))
20481 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20482 beg itemp
20483 end next))
20484 ((> (point) (setq prev (car (last children))))
20485 (setq beg (org-list-get-item-end prev struct)
20486 end (org-list-get-item-end itemp struct)
20487 prefix (save-excursion
20488 (goto-char beg)
20489 (skip-chars-forward " \t")
20490 (make-string (current-column) ?\ ))))
20491 (t (catch 'exit
20492 (while (setq next (pop children))
20493 (if (> (point) next)
20494 (setq prev next)
20495 (setq beg (org-list-get-item-end prev struct)
20496 end next
20497 prefix (save-excursion
20498 (goto-char beg)
20499 (skip-chars-forward " \t")
20500 (make-string (current-column) ?\ )))
20501 (throw 'exit nil))))))
20502 ;; Use `fill-paragraph' with buffer narrowed to item
20503 ;; without any child, and with our computed PREFIX.
20504 (flet ((fill-context-prefix (from to &optional flr) prefix))
20505 (save-restriction
20506 (narrow-to-region beg end)
20507 (save-excursion (fill-paragraph justify)))) t))
20508 ;; Special case where point is not in a list but is on
20509 ;; a paragraph adjacent to a list: make sure this paragraph
20510 ;; doesn't get merged with the end of the list by narrowing
20511 ;; buffer first.
20512 ((save-excursion (forward-paragraph -1)
20513 (setq itemp (org-in-item-p)))
20514 (let ((struct (save-excursion (goto-char itemp)
20515 (org-list-struct))))
20516 (save-restriction
20517 (narrow-to-region (org-list-get-bottom-point struct)
20518 (save-excursion (forward-paragraph 1)
20519 (point)))
20520 (fill-paragraph justify) t)))
20521 ;; Else simply call `fill-paragraph'.
20522 (t nil))))
20524 ;; For reference, this is the default value of adaptive-fill-regexp
20525 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20527 (defun org-adaptive-fill-function ()
20528 "Return a fill prefix for org-mode files."
20529 (let (itemp)
20530 (save-excursion
20531 (cond
20532 ;; Comment line
20533 ((looking-at "#[ \t]+")
20534 (match-string-no-properties 0))
20535 ;; Plain list item
20536 ((org-at-item-p)
20537 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20538 ;; Point is in a list after `backward-paragraph': original
20539 ;; point wasn't in the list, or filling would have been taken
20540 ;; care of by `org-auto-fill-function', but the list and the
20541 ;; real paragraph are not separated by a blank line. Thus, move
20542 ;; point after the list to go back to real paragraph and
20543 ;; determine fill-prefix.
20544 ((setq itemp (org-in-item-p))
20545 (goto-char itemp)
20546 (let* ((struct (org-list-struct))
20547 (bottom (org-list-get-bottom-point struct)))
20548 (goto-char bottom)
20549 (make-string (org-get-indentation) ?\ )))
20550 ;; Other text
20551 ((looking-at org-adaptive-fill-regexp-backup)
20552 (match-string-no-properties 0))))))
20554 (defun org-auto-fill-function ()
20555 "Auto-fill function."
20556 (let (itemp prefix)
20557 ;; When in a list, compute an appropriate fill-prefix and make
20558 ;; sure it will be used by `do-auto-fill'.
20559 (if (setq itemp (org-in-item-p))
20560 (progn
20561 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20562 (flet ((fill-context-prefix (from to &optional flr) prefix))
20563 (do-auto-fill)))
20564 ;; Else just use `do-auto-fill'.
20565 (do-auto-fill))))
20567 ;;; Other stuff.
20569 (defun org-toggle-fixed-width-section (arg)
20570 "Toggle the fixed-width export.
20571 If there is no active region, the QUOTE keyword at the current headline is
20572 inserted or removed. When present, it causes the text between this headline
20573 and the next to be exported as fixed-width text, and unmodified.
20574 If there is an active region, this command adds or removes a colon as the
20575 first character of this line. If the first character of a line is a colon,
20576 this line is also exported in fixed-width font."
20577 (interactive "P")
20578 (let* ((cc 0)
20579 (regionp (org-region-active-p))
20580 (beg (if regionp (region-beginning) (point)))
20581 (end (if regionp (region-end)))
20582 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20583 (case-fold-search nil)
20584 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20585 off)
20586 (if regionp
20587 (save-excursion
20588 (goto-char beg)
20589 (setq cc (current-column))
20590 (beginning-of-line 1)
20591 (setq off (looking-at re))
20592 (while (> nlines 0)
20593 (setq nlines (1- nlines))
20594 (beginning-of-line 1)
20595 (cond
20596 (arg
20597 (org-move-to-column cc t)
20598 (insert ": \n")
20599 (forward-line -1))
20600 ((and off (looking-at re))
20601 (replace-match "" t t nil 1))
20602 ((not off) (org-move-to-column cc t) (insert ": ")))
20603 (forward-line 1)))
20604 (save-excursion
20605 (org-back-to-heading)
20606 (cond
20607 ((looking-at (format org-heading-keyword-regexp-format
20608 org-quote-string))
20609 (goto-char (match-end 1))
20610 (looking-at (concat " +" org-quote-string))
20611 (replace-match "" t t)
20612 (when (eolp) (insert " ")))
20613 ((looking-at org-outline-regexp)
20614 (goto-char (match-end 0))
20615 (insert org-quote-string " ")))))))
20617 (defun org-reftex-citation ()
20618 "Use reftex-citation to insert a citation into the buffer.
20619 This looks for a line like
20621 #+BIBLIOGRAPHY: foo plain option:-d
20623 and derives from it that foo.bib is the bibliography file relevant
20624 for this document. It then installs the necessary environment for RefTeX
20625 to work in this buffer and calls `reftex-citation' to insert a citation
20626 into the buffer.
20628 Export of such citations to both LaTeX and HTML is handled by the contributed
20629 package org-exp-bibtex by Taru Karttunen."
20630 (interactive)
20631 (let ((reftex-docstruct-symbol 'rds)
20632 (reftex-cite-format "\\cite{%l}")
20633 rds bib)
20634 (save-excursion
20635 (save-restriction
20636 (widen)
20637 (let ((case-fold-search t)
20638 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20639 (if (not (save-excursion
20640 (or (re-search-forward re nil t)
20641 (re-search-backward re nil t))))
20642 (error "No bibliography defined in file")
20643 (setq bib (concat (match-string 1) ".bib")
20644 rds (list (list 'bib bib)))))))
20645 (call-interactively 'reftex-citation)))
20647 ;;;; Functions extending outline functionality
20649 (defun org-beginning-of-line (&optional arg)
20650 "Go to the beginning of the current line. If that is invisible, continue
20651 to a visible line beginning. This makes the function of C-a more intuitive.
20652 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20653 first attempt, and only move to after the tags when the cursor is already
20654 beyond the end of the headline."
20655 (interactive "P")
20656 (let ((pos (point))
20657 (special (if (consp org-special-ctrl-a/e)
20658 (car org-special-ctrl-a/e)
20659 org-special-ctrl-a/e))
20660 refpos)
20661 (if (org-bound-and-true-p line-move-visual)
20662 (beginning-of-visual-line 1)
20663 (beginning-of-line 1))
20664 (if (and arg (fboundp 'move-beginning-of-line))
20665 (call-interactively 'move-beginning-of-line)
20666 (if (bobp)
20668 (backward-char 1)
20669 (if (org-truely-invisible-p)
20670 (while (and (not (bobp)) (org-truely-invisible-p))
20671 (backward-char 1)
20672 (beginning-of-line 1))
20673 (forward-char 1))))
20674 (when special
20675 (cond
20676 ((and (looking-at org-complex-heading-regexp)
20677 (= (char-after (match-end 1)) ?\ ))
20678 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20679 (point-at-eol)))
20680 (goto-char
20681 (if (eq special t)
20682 (cond ((> pos refpos) refpos)
20683 ((= pos (point)) refpos)
20684 (t (point)))
20685 (cond ((> pos (point)) (point))
20686 ((not (eq last-command this-command)) (point))
20687 (t refpos)))))
20688 ((org-at-item-p)
20689 ;; Being at an item and not looking at an the item means point
20690 ;; was previously moved to beginning of a visual line, which
20691 ;; doesn't contain the item. Therefore, do nothing special,
20692 ;; just stay here.
20693 (when (looking-at org-list-full-item-re)
20694 ;; Set special position at first white space character after
20695 ;; bullet, and check-box, if any.
20696 (let ((after-bullet
20697 (let ((box (match-end 3)))
20698 (if (not box) (match-end 1)
20699 (let ((after (char-after box)))
20700 (if (and after (= after ? )) (1+ box) box))))))
20701 ;; Special case: Move point to special position when
20702 ;; currently after it or at beginning of line.
20703 (if (eq special t)
20704 (when (or (> pos after-bullet) (= (point) pos))
20705 (goto-char after-bullet))
20706 ;; Reversed case: Move point to special position when
20707 ;; point was already at beginning of line and command is
20708 ;; repeated.
20709 (when (and (= (point) pos) (eq last-command this-command))
20710 (goto-char after-bullet))))))))
20711 (org-no-warnings
20712 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20714 (defun org-end-of-line (&optional arg)
20715 "Go to the end of the line.
20716 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20717 first attempt, and only move to after the tags when the cursor is already
20718 beyond the end of the headline."
20719 (interactive "P")
20720 (let ((special (if (consp org-special-ctrl-a/e)
20721 (cdr org-special-ctrl-a/e)
20722 org-special-ctrl-a/e)))
20723 (cond
20724 ((or (not special) arg
20725 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20726 (call-interactively
20727 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20728 ((fboundp 'move-end-of-line) 'move-end-of-line)
20729 (t 'end-of-line))))
20730 ((org-at-heading-p)
20731 (let ((pos (point)))
20732 (beginning-of-line 1)
20733 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20734 (if (eq special t)
20735 (if (or (< pos (match-beginning 1))
20736 (= pos (match-end 0)))
20737 (goto-char (match-beginning 1))
20738 (goto-char (match-end 0)))
20739 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20740 (goto-char (match-end 0))
20741 (goto-char (match-beginning 1))))
20742 (call-interactively (if (fboundp 'move-end-of-line)
20743 'move-end-of-line
20744 'end-of-line)))))
20745 ((org-at-drawer-p)
20746 (move-end-of-line 1)
20747 (when (overlays-at (1- (point))) (backward-char 1)))
20748 ;; At an item: Move before any hidden text.
20749 (t (call-interactively
20750 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20751 ((fboundp 'move-end-of-line) 'move-end-of-line)
20752 (t 'end-of-line)))))
20753 (org-no-warnings
20754 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20756 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20757 (define-key org-mode-map "\C-e" 'org-end-of-line)
20759 (defun org-backward-sentence (&optional arg)
20760 "Go to beginning of sentence, or beginning of table field.
20761 This will call `backward-sentence' or `org-table-beginning-of-field',
20762 depending on context."
20763 (interactive "P")
20764 (cond
20765 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20766 (t (call-interactively 'backward-sentence))))
20768 (defun org-forward-sentence (&optional arg)
20769 "Go to end of sentence, or end of table field.
20770 This will call `forward-sentence' or `org-table-end-of-field',
20771 depending on context."
20772 (interactive "P")
20773 (cond
20774 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20775 (t (call-interactively 'forward-sentence))))
20777 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20778 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20780 (defun org-kill-line (&optional arg)
20781 "Kill line, to tags or end of line."
20782 (interactive "P")
20783 (cond
20784 ((or (not org-special-ctrl-k)
20785 (bolp)
20786 (not (org-at-heading-p)))
20787 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20788 org-ctrl-k-protect-subtree)
20789 (if (or (eq org-ctrl-k-protect-subtree 'error)
20790 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20791 (error "C-k aborted - would kill hidden subtree")))
20792 (call-interactively
20793 (if visual-line-mode 'kill-visual-line 'kill-line)))
20794 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20795 (kill-region (point) (match-beginning 1))
20796 (org-set-tags nil t))
20797 (t (kill-region (point) (point-at-eol)))))
20799 (define-key org-mode-map "\C-k" 'org-kill-line)
20801 (defun org-yank (&optional arg)
20802 "Yank. If the kill is a subtree, treat it specially.
20803 This command will look at the current kill and check if is a single
20804 subtree, or a series of subtrees[1]. If it passes the test, and if the
20805 cursor is at the beginning of a line or after the stars of a currently
20806 empty headline, then the yank is handled specially. How exactly depends
20807 on the value of the following variables, both set by default.
20809 org-yank-folded-subtrees
20810 When set, the subtree(s) will be folded after insertion, but only
20811 if doing so would now swallow text after the yanked text.
20813 org-yank-adjusted-subtrees
20814 When set, the subtree will be promoted or demoted in order to
20815 fit into the local outline tree structure, which means that the level
20816 will be adjusted so that it becomes the smaller one of the two
20817 *visible* surrounding headings.
20819 Any prefix to this command will cause `yank' to be called directly with
20820 no special treatment. In particular, a simple \\[universal-argument] prefix \
20821 will just
20822 plainly yank the text as it is.
20824 \[1] The test checks if the first non-white line is a heading
20825 and if there are no other headings with fewer stars."
20826 (interactive "P")
20827 (org-yank-generic 'yank arg))
20829 (defun org-yank-generic (command arg)
20830 "Perform some yank-like command.
20832 This function implements the behavior described in the `org-yank'
20833 documentation. However, it has been generalized to work for any
20834 interactive command with similar behavior."
20836 ;; pretend to be command COMMAND
20837 (setq this-command command)
20839 (if arg
20840 (call-interactively command)
20842 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20843 (and (org-kill-is-subtree-p)
20844 (or (bolp)
20845 (and (looking-at "[ \t]*$")
20846 (string-match
20847 "\\`\\*+\\'"
20848 (buffer-substring (point-at-bol) (point)))))))
20849 swallowp)
20850 (cond
20851 ((and subtreep org-yank-folded-subtrees)
20852 (let ((beg (point))
20853 end)
20854 (if (and subtreep org-yank-adjusted-subtrees)
20855 (org-paste-subtree nil nil 'for-yank)
20856 (call-interactively command))
20858 (setq end (point))
20859 (goto-char beg)
20860 (when (and (bolp) subtreep
20861 (not (setq swallowp
20862 (org-yank-folding-would-swallow-text beg end))))
20863 (org-with-limited-levels
20864 (or (looking-at org-outline-regexp)
20865 (re-search-forward org-outline-regexp-bol end t))
20866 (while (and (< (point) end) (looking-at org-outline-regexp))
20867 (hide-subtree)
20868 (org-cycle-show-empty-lines 'folded)
20869 (condition-case nil
20870 (outline-forward-same-level 1)
20871 (error (goto-char end))))))
20872 (when swallowp
20873 (message
20874 "Inserted text not folded because that would swallow text"))
20876 (goto-char end)
20877 (skip-chars-forward " \t\n\r")
20878 (beginning-of-line 1)
20879 (push-mark beg 'nomsg)))
20880 ((and subtreep org-yank-adjusted-subtrees)
20881 (let ((beg (point-at-bol)))
20882 (org-paste-subtree nil nil 'for-yank)
20883 (push-mark beg 'nomsg)))
20885 (call-interactively command))))))
20887 (defun org-yank-folding-would-swallow-text (beg end)
20888 "Would hide-subtree at BEG swallow any text after END?"
20889 (let (level)
20890 (org-with-limited-levels
20891 (save-excursion
20892 (goto-char beg)
20893 (when (or (looking-at org-outline-regexp)
20894 (re-search-forward org-outline-regexp-bol end t))
20895 (setq level (org-outline-level)))
20896 (goto-char end)
20897 (skip-chars-forward " \t\r\n\v\f")
20898 (if (or (eobp)
20899 (and (bolp) (looking-at org-outline-regexp)
20900 (<= (org-outline-level) level)))
20901 nil ; Nothing would be swallowed
20902 t))))) ; something would swallow
20904 (define-key org-mode-map "\C-y" 'org-yank)
20906 (defun org-truely-invisible-p ()
20907 "Check if point is at a character currently not visible.
20908 This version does not only check the character property, but also
20909 `visible-mode'."
20910 ;; Early versions of noutline don't have `outline-invisible-p'.
20911 (if (org-bound-and-true-p visible-mode)
20913 (outline-invisible-p)))
20915 (defun org-invisible-p2 ()
20916 "Check if point is at a character currently not visible."
20917 (save-excursion
20918 (if (and (eolp) (not (bobp))) (backward-char 1))
20919 ;; Early versions of noutline don't have `outline-invisible-p'.
20920 (outline-invisible-p)))
20922 (defun org-back-to-heading (&optional invisible-ok)
20923 "Call `outline-back-to-heading', but provide a better error message."
20924 (condition-case nil
20925 (outline-back-to-heading invisible-ok)
20926 (error (error "Before first headline at position %d in buffer %s"
20927 (point) (current-buffer)))))
20929 (defun org-beginning-of-defun ()
20930 "Go to the beginning of the subtree, i.e. back to the heading."
20931 (org-back-to-heading))
20932 (defun org-end-of-defun ()
20933 "Go to the end of the subtree."
20934 (org-end-of-subtree nil t))
20936 (defun org-before-first-heading-p ()
20937 "Before first heading?"
20938 (save-excursion
20939 (end-of-line)
20940 (null (re-search-backward org-outline-regexp-bol nil t))))
20942 (defun org-at-heading-p (&optional ignored)
20943 (outline-on-heading-p t))
20944 ;; Compatibility alias with Org versions < 7.8.03
20945 (defalias 'org-on-heading-p 'org-at-heading-p)
20947 (defun org-at-drawer-p nil
20948 "Is cursor at a drawer keyword?"
20949 (save-excursion
20950 (move-beginning-of-line 1)
20951 (looking-at org-drawer-regexp)))
20953 (defun org-at-block-p nil
20954 "Is cursor at a block keyword?"
20955 (save-excursion
20956 (move-beginning-of-line 1)
20957 (looking-at org-block-regexp)))
20959 (defun org-point-at-end-of-empty-headline ()
20960 "If point is at the end of an empty headline, return t, else nil.
20961 If the heading only contains a TODO keyword, it is still still considered
20962 empty."
20963 (and (looking-at "[ \t]*$")
20964 (save-excursion
20965 (beginning-of-line 1)
20966 (let ((case-fold-search nil))
20967 (looking-at org-todo-line-regexp)))
20968 (string= (match-string 3) "")))
20970 (defun org-at-heading-or-item-p ()
20971 (or (org-at-heading-p) (org-at-item-p)))
20973 (defun org-at-target-p ()
20974 (or (org-in-regexp org-radio-target-regexp)
20975 (org-in-regexp org-target-regexp)))
20976 ;; Compatibility alias with Org versions < 7.8.03
20977 (defalias 'org-on-target-p 'org-at-target-p)
20979 (defun org-up-heading-all (arg)
20980 "Move to the heading line of which the present line is a subheading.
20981 This function considers both visible and invisible heading lines.
20982 With argument, move up ARG levels."
20983 (if (fboundp 'outline-up-heading-all)
20984 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20985 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20987 (defun org-up-heading-safe ()
20988 "Move to the heading line of which the present line is a subheading.
20989 This version will not throw an error. It will return the level of the
20990 headline found, or nil if no higher level is found.
20992 Also, this function will be a lot faster than `outline-up-heading',
20993 because it relies on stars being the outline starters. This can really
20994 make a significant difference in outlines with very many siblings."
20995 (let (start-level re)
20996 (org-back-to-heading t)
20997 (setq start-level (funcall outline-level))
20998 (if (equal start-level 1)
21000 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21001 (if (re-search-backward re nil t)
21002 (funcall outline-level)))))
21004 (defun org-first-sibling-p ()
21005 "Is this heading the first child of its parents?"
21006 (interactive)
21007 (let ((re org-outline-regexp-bol)
21008 level l)
21009 (unless (org-at-heading-p t)
21010 (error "Not at a heading"))
21011 (setq level (funcall outline-level))
21012 (save-excursion
21013 (if (not (re-search-backward re nil t))
21015 (setq l (funcall outline-level))
21016 (< l level)))))
21018 (defun org-goto-sibling (&optional previous)
21019 "Goto the next sibling, even if it is invisible.
21020 When PREVIOUS is set, go to the previous sibling instead. Returns t
21021 when a sibling was found. When none is found, return nil and don't
21022 move point."
21023 (let ((fun (if previous 're-search-backward 're-search-forward))
21024 (pos (point))
21025 (re org-outline-regexp-bol)
21026 level l)
21027 (when (condition-case nil (org-back-to-heading t) (error nil))
21028 (setq level (funcall outline-level))
21029 (catch 'exit
21030 (or previous (forward-char 1))
21031 (while (funcall fun re nil t)
21032 (setq l (funcall outline-level))
21033 (when (< l level) (goto-char pos) (throw 'exit nil))
21034 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21035 (goto-char pos)
21036 nil))))
21038 (defun org-show-siblings ()
21039 "Show all siblings of the current headline."
21040 (save-excursion
21041 (while (org-goto-sibling) (org-flag-heading nil)))
21042 (save-excursion
21043 (while (org-goto-sibling 'previous)
21044 (org-flag-heading nil))))
21046 (defun org-goto-first-child ()
21047 "Goto the first child, even if it is invisible.
21048 Return t when a child was found. Otherwise don't move point and
21049 return nil."
21050 (let (level (pos (point)) (re org-outline-regexp-bol))
21051 (when (condition-case nil (org-back-to-heading t) (error nil))
21052 (setq level (outline-level))
21053 (forward-char 1)
21054 (if (and (re-search-forward re nil t) (> (outline-level) level))
21055 (progn (goto-char (match-beginning 0)) t)
21056 (goto-char pos) nil))))
21058 (defun org-show-hidden-entry ()
21059 "Show an entry where even the heading is hidden."
21060 (save-excursion
21061 (org-show-entry)))
21063 (defun org-flag-heading (flag &optional entry)
21064 "Flag the current heading. FLAG non-nil means make invisible.
21065 When ENTRY is non-nil, show the entire entry."
21066 (save-excursion
21067 (org-back-to-heading t)
21068 ;; Check if we should show the entire entry
21069 (if entry
21070 (progn
21071 (org-show-entry)
21072 (save-excursion
21073 (and (outline-next-heading)
21074 (org-flag-heading nil))))
21075 (outline-flag-region (max (point-min) (1- (point)))
21076 (save-excursion (outline-end-of-heading) (point))
21077 flag))))
21079 (defun org-get-next-sibling ()
21080 "Move to next heading of the same level, and return point.
21081 If there is no such heading, return nil.
21082 This is like outline-next-sibling, but invisible headings are ok."
21083 (let ((level (funcall outline-level)))
21084 (outline-next-heading)
21085 (while (and (not (eobp)) (> (funcall outline-level) level))
21086 (outline-next-heading))
21087 (if (or (eobp) (< (funcall outline-level) level))
21089 (point))))
21091 (defun org-get-last-sibling ()
21092 "Move to previous heading of the same level, and return point.
21093 If there is no such heading, return nil."
21094 (let ((opoint (point))
21095 (level (funcall outline-level)))
21096 (outline-previous-heading)
21097 (when (and (/= (point) opoint) (outline-on-heading-p t))
21098 (while (and (> (funcall outline-level) level)
21099 (not (bobp)))
21100 (outline-previous-heading))
21101 (if (< (funcall outline-level) level)
21103 (point)))))
21105 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21106 ;; This contains an exact copy of the original function, but it uses
21107 ;; `org-back-to-heading', to make it work also in invisible
21108 ;; trees. And is uses an invisible-OK argument.
21109 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21110 ;; Furthermore, when used inside Org, finding the end of a large subtree
21111 ;; with many children and grandchildren etc, this can be much faster
21112 ;; than the outline version.
21113 (org-back-to-heading invisible-OK)
21114 (let ((first t)
21115 (level (funcall outline-level)))
21116 (if (and (eq major-mode 'org-mode) (< level 1000))
21117 ;; A true heading (not a plain list item), in Org-mode
21118 ;; This means we can easily find the end by looking
21119 ;; only for the right number of stars. Using a regexp to do
21120 ;; this is so much faster than using a Lisp loop.
21121 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21122 (forward-char 1)
21123 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21124 ;; something else, do it the slow way
21125 (while (and (not (eobp))
21126 (or first (> (funcall outline-level) level)))
21127 (setq first nil)
21128 (outline-next-heading)))
21129 (unless to-heading
21130 (if (memq (preceding-char) '(?\n ?\^M))
21131 (progn
21132 ;; Go to end of line before heading
21133 (forward-char -1)
21134 (if (memq (preceding-char) '(?\n ?\^M))
21135 ;; leave blank line before heading
21136 (forward-char -1))))))
21137 (point))
21139 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21140 "Use Org version in org-mode, for dramatic speed-up."
21141 (if (eq major-mode 'org-mode)
21142 (progn
21143 (org-end-of-subtree nil t)
21144 (unless (eobp) (backward-char 1)))
21145 ad-do-it))
21147 (defun org-end-of-meta-data-and-drawers ()
21148 "Jump to the first text after meta data and drawers in the current entry.
21149 This will move over empty lines, lines with planning time stamps,
21150 clocking lines, and drawers."
21151 (org-back-to-heading t)
21152 (let ((end (save-excursion (outline-next-heading) (point)))
21153 (re (concat "\\(" org-drawer-regexp "\\)"
21154 "\\|" "[ \t]*" org-keyword-time-regexp)))
21155 (forward-line 1)
21156 (while (re-search-forward re end t)
21157 (if (not (match-end 1))
21158 ;; empty or planning line
21159 (forward-line 1)
21160 ;; a drawer, find the end
21161 (re-search-forward "^[ \t]*:END:" end 'move)
21162 (forward-line 1)))
21163 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21164 (point)))
21166 (defun org-forward-same-level (arg &optional invisible-ok)
21167 "Move forward to the arg'th subheading at same level as this one.
21168 Stop at the first and last subheadings of a superior heading.
21169 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21170 it wil also look at invisible ones."
21171 (interactive "p")
21172 (org-back-to-heading invisible-ok)
21173 (org-at-heading-p)
21174 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21175 (re (format "^\\*\\{1,%d\\} " level))
21177 (forward-char 1)
21178 (while (> arg 0)
21179 (while (and (re-search-forward re nil 'move)
21180 (setq l (- (match-end 0) (match-beginning 0) 1))
21181 (= l level)
21182 (not invisible-ok)
21183 (progn (backward-char 1) (outline-invisible-p)))
21184 (if (< l level) (setq arg 1)))
21185 (setq arg (1- arg)))
21186 (beginning-of-line 1)))
21188 (defun org-backward-same-level (arg &optional invisible-ok)
21189 "Move backward to the arg'th subheading at same level as this one.
21190 Stop at the first and last subheadings of a superior heading."
21191 (interactive "p")
21192 (org-back-to-heading)
21193 (org-at-heading-p)
21194 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21195 (re (format "^\\*\\{1,%d\\} " level))
21197 (while (> arg 0)
21198 (while (and (re-search-backward re nil 'move)
21199 (setq l (- (match-end 0) (match-beginning 0) 1))
21200 (= l level)
21201 (not invisible-ok)
21202 (outline-invisible-p))
21203 (if (< l level) (setq arg 1)))
21204 (setq arg (1- arg)))))
21206 (defun org-show-subtree ()
21207 "Show everything after this heading at deeper levels."
21208 (interactive)
21209 (outline-flag-region
21210 (point)
21211 (save-excursion
21212 (org-end-of-subtree t t))
21213 nil))
21215 (defun org-show-entry ()
21216 "Show the body directly following this heading.
21217 Show the heading too, if it is currently invisible."
21218 (interactive)
21219 (save-excursion
21220 (condition-case nil
21221 (progn
21222 (org-back-to-heading t)
21223 (outline-flag-region
21224 (max (point-min) (1- (point)))
21225 (save-excursion
21226 (if (re-search-forward
21227 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21228 (match-beginning 1)
21229 (point-max)))
21230 nil)
21231 (org-cycle-hide-drawers 'children))
21232 (error nil))))
21234 (defun org-make-options-regexp (kwds &optional extra)
21235 "Make a regular expression for keyword lines."
21236 (concat
21238 "#?[ \t]*\\+\\("
21239 (mapconcat 'regexp-quote kwds "\\|")
21240 (if extra (concat "\\|" extra))
21241 "\\):[ \t]*"
21242 "\\(.*\\)"))
21244 ;; Make isearch reveal the necessary context
21245 (defun org-isearch-end ()
21246 "Reveal context after isearch exits."
21247 (when isearch-success ; only if search was successful
21248 (if (featurep 'xemacs)
21249 ;; Under XEmacs, the hook is run in the correct place,
21250 ;; we directly show the context.
21251 (org-show-context 'isearch)
21252 ;; In Emacs the hook runs *before* restoring the overlays.
21253 ;; So we have to use a one-time post-command-hook to do this.
21254 ;; (Emacs 22 has a special variable, see function `org-mode')
21255 (unless (and (boundp 'isearch-mode-end-hook-quit)
21256 isearch-mode-end-hook-quit)
21257 ;; Only when the isearch was not quitted.
21258 (org-add-hook 'post-command-hook 'org-isearch-post-command
21259 'append 'local)))))
21261 (defun org-isearch-post-command ()
21262 "Remove self from hook, and show context."
21263 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21264 (org-show-context 'isearch))
21267 ;;;; Integration with and fixes for other packages
21269 ;;; Imenu support
21271 (defvar org-imenu-markers nil
21272 "All markers currently used by Imenu.")
21273 (make-variable-buffer-local 'org-imenu-markers)
21275 (defun org-imenu-new-marker (&optional pos)
21276 "Return a new marker for use by Imenu, and remember the marker."
21277 (let ((m (make-marker)))
21278 (move-marker m (or pos (point)))
21279 (push m org-imenu-markers)
21282 (defun org-imenu-get-tree ()
21283 "Produce the index for Imenu."
21284 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21285 (setq org-imenu-markers nil)
21286 (let* ((n org-imenu-depth)
21287 (re (concat "^" (org-get-limited-outline-regexp)))
21288 (subs (make-vector (1+ n) nil))
21289 (last-level 0)
21290 m level head)
21291 (save-excursion
21292 (save-restriction
21293 (widen)
21294 (goto-char (point-max))
21295 (while (re-search-backward re nil t)
21296 (setq level (org-reduced-level (funcall outline-level)))
21297 (when (and (<= level n)
21298 (looking-at org-complex-heading-regexp))
21299 (setq head (org-link-display-format
21300 (org-match-string-no-properties 4))
21301 m (org-imenu-new-marker))
21302 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21303 (if (>= level last-level)
21304 (push (cons head m) (aref subs level))
21305 (push (cons head (aref subs (1+ level))) (aref subs level))
21306 (loop for i from (1+ level) to n do (aset subs i nil)))
21307 (setq last-level level)))))
21308 (aref subs 1)))
21310 (eval-after-load "imenu"
21311 '(progn
21312 (add-hook 'imenu-after-jump-hook
21313 (lambda ()
21314 (if (eq major-mode 'org-mode)
21315 (org-show-context 'org-goto))))))
21317 (defun org-link-display-format (link)
21318 "Replace a link with either the description, or the link target
21319 if no description is present"
21320 (save-match-data
21321 (if (string-match org-bracket-link-analytic-regexp link)
21322 (replace-match (if (match-end 5)
21323 (match-string 5 link)
21324 (concat (match-string 1 link)
21325 (match-string 3 link)))
21326 nil t link)
21327 link)))
21329 (defun org-toggle-link-display ()
21330 "Toggle the literal or descriptive display of links."
21331 (interactive)
21332 (if org-descriptive-links
21333 (progn (org-remove-from-invisibility-spec '(org-link))
21334 (org-restart-font-lock)
21335 (setq org-descriptive-links nil))
21336 (progn (add-to-invisibility-spec '(org-link))
21337 (org-restart-font-lock)
21338 (setq org-descriptive-links t))))
21340 ;; Speedbar support
21342 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21343 "Overlay marking the agenda restriction line in speedbar.")
21344 (overlay-put org-speedbar-restriction-lock-overlay
21345 'face 'org-agenda-restriction-lock)
21346 (overlay-put org-speedbar-restriction-lock-overlay
21347 'help-echo "Agendas are currently limited to this item.")
21348 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21350 (defun org-speedbar-set-agenda-restriction ()
21351 "Restrict future agenda commands to the location at point in speedbar.
21352 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21353 (interactive)
21354 (require 'org-agenda)
21355 (let (p m tp np dir txt)
21356 (cond
21357 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21358 'org-imenu t))
21359 (setq m (get-text-property p 'org-imenu-marker))
21360 (with-current-buffer (marker-buffer m)
21361 (goto-char m)
21362 (org-agenda-set-restriction-lock 'subtree)))
21363 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21364 'speedbar-function 'speedbar-find-file))
21365 (setq tp (previous-single-property-change
21366 (1+ p) 'speedbar-function)
21367 np (next-single-property-change
21368 tp 'speedbar-function)
21369 dir (speedbar-line-directory)
21370 txt (buffer-substring-no-properties (or tp (point-min))
21371 (or np (point-max))))
21372 (with-current-buffer (find-file-noselect
21373 (let ((default-directory dir))
21374 (expand-file-name txt)))
21375 (unless (eq major-mode 'org-mode)
21376 (error "Cannot restrict to non-Org-mode file"))
21377 (org-agenda-set-restriction-lock 'file)))
21378 (t (error "Don't know how to restrict Org-mode's agenda")))
21379 (move-overlay org-speedbar-restriction-lock-overlay
21380 (point-at-bol) (point-at-eol))
21381 (setq current-prefix-arg nil)
21382 (org-agenda-maybe-redo)))
21384 (eval-after-load "speedbar"
21385 '(progn
21386 (speedbar-add-supported-extension ".org")
21387 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21388 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21389 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21390 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21391 (add-hook 'speedbar-visiting-tag-hook
21392 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21394 ;;; Fixes and Hacks for problems with other packages
21396 ;; Make flyspell not check words in links, to not mess up our keymap
21397 (defun org-mode-flyspell-verify ()
21398 "Don't let flyspell put overlays at active buttons, or on
21399 {todo,all-time,additional-option-like}-keywords."
21400 (let ((pos (max (1- (point)) (point-min)))
21401 (word (thing-at-point 'word)))
21402 (and (not (get-text-property pos 'keymap))
21403 (not (get-text-property pos 'org-no-flyspell))
21404 (not (member word org-todo-keywords-1))
21405 (not (member word org-all-time-keywords))
21406 (not (member word org-additional-option-like-keywords)))))
21408 (defun org-remove-flyspell-overlays-in (beg end)
21409 "Remove flyspell overlays in region."
21410 (and (org-bound-and-true-p flyspell-mode)
21411 (fboundp 'flyspell-delete-region-overlays)
21412 (flyspell-delete-region-overlays beg end))
21413 (add-text-properties beg end '(org-no-flyspell t)))
21415 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21416 (eval-after-load "bookmark"
21417 '(if (boundp 'bookmark-after-jump-hook)
21418 ;; We can use the hook
21419 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21420 ;; Hook not available, use advice
21421 (defadvice bookmark-jump (after org-make-visible activate)
21422 "Make the position visible."
21423 (org-bookmark-jump-unhide))))
21425 ;; Make sure saveplace shows the location if it was hidden
21426 (eval-after-load "saveplace"
21427 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21428 "Make the position visible."
21429 (org-bookmark-jump-unhide)))
21431 ;; Make sure ecb shows the location if it was hidden
21432 (eval-after-load "ecb"
21433 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21434 "Make hierarchy visible when jumping into location from ECB tree buffer."
21435 (if (eq major-mode 'org-mode)
21436 (org-show-context))))
21438 (defun org-bookmark-jump-unhide ()
21439 "Unhide the current position, to show the bookmark location."
21440 (and (eq major-mode 'org-mode)
21441 (or (outline-invisible-p)
21442 (save-excursion (goto-char (max (point-min) (1- (point))))
21443 (outline-invisible-p)))
21444 (org-show-context 'bookmark-jump)))
21446 ;; Make session.el ignore our circular variable
21447 (eval-after-load "session"
21448 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21450 ;;;; Experimental code
21452 (defun org-closed-in-range ()
21453 "Sparse tree of items closed in a certain time range.
21454 Still experimental, may disappear in the future."
21455 (interactive)
21456 ;; Get the time interval from the user.
21457 (let* ((time1 (org-float-time
21458 (org-read-date nil 'to-time nil "Starting date: ")))
21459 (time2 (org-float-time
21460 (org-read-date nil 'to-time nil "End date:")))
21461 ;; callback function
21462 (callback (lambda ()
21463 (let ((time
21464 (org-float-time
21465 (apply 'encode-time
21466 (org-parse-time-string
21467 (match-string 1))))))
21468 ;; check if time in interval
21469 (and (>= time time1) (<= time time2))))))
21470 ;; make tree, check each match with the callback
21471 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21473 ;;;; Finish up
21475 (provide 'org)
21477 (run-hooks 'org-load-hook)
21479 ;;; org.el ends here