Merge branch 'hotfix-7.8.06'
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob1f2ac3db1b737f96d37b18b8e9b12ec969c1c8f5
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.06
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.06"
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 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)
4933 ;;;###autoload
4934 (define-derived-mode org-mode outline-mode "Org"
4935 "Outline-based notes management and organizer, alias
4936 \"Carsten's outline-mode for keeping track of everything.\"
4938 Org-mode develops organizational tasks around a NOTES file which
4939 contains information about projects as plain text. Org-mode is
4940 implemented on top of outline-mode, which is ideal to keep the content
4941 of large files well structured. It supports ToDo items, deadlines and
4942 time stamps, which magically appear in the diary listing of the Emacs
4943 calendar. Tables are easily created with a built-in table editor.
4944 Plain text URL-like links connect to websites, emails (VM), Usenet
4945 messages (Gnus), BBDB entries, and any files related to the project.
4946 For printing and sharing of notes, an Org-mode file (or a part of it)
4947 can be exported as a structured ASCII or HTML file.
4949 The following commands are available:
4951 \\{org-mode-map}"
4953 ;; Get rid of Outline menus, they are not needed
4954 ;; Need to do this here because define-derived-mode sets up
4955 ;; the keymap so late. Still, it is a waste to call this each time
4956 ;; we switch another buffer into org-mode.
4957 (if (featurep 'xemacs)
4958 (when (boundp 'outline-mode-menu-heading)
4959 ;; Assume this is Greg's port, it uses easymenu
4960 (easy-menu-remove outline-mode-menu-heading)
4961 (easy-menu-remove outline-mode-menu-show)
4962 (easy-menu-remove outline-mode-menu-hide))
4963 (define-key org-mode-map [menu-bar headings] 'undefined)
4964 (define-key org-mode-map [menu-bar hide] 'undefined)
4965 (define-key org-mode-map [menu-bar show] 'undefined))
4967 (org-load-modules-maybe)
4968 (easy-menu-add org-org-menu)
4969 (easy-menu-add org-tbl-menu)
4970 (org-install-agenda-files-menu)
4971 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4972 (add-to-invisibility-spec '(org-cwidth))
4973 (add-to-invisibility-spec '(org-hide-block . t))
4974 (when (featurep 'xemacs)
4975 (org-set-local 'line-move-ignore-invisible t))
4976 (org-set-local 'outline-regexp org-outline-regexp)
4977 (org-set-local 'outline-level 'org-outline-level)
4978 (setq bidi-paragraph-direction 'left-to-right)
4979 (when (and org-ellipsis
4980 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4981 (fboundp 'make-glyph-code))
4982 (unless org-display-table
4983 (setq org-display-table (make-display-table)))
4984 (set-display-table-slot
4985 org-display-table 4
4986 (vconcat (mapcar
4987 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4988 org-ellipsis)))
4989 (if (stringp org-ellipsis) org-ellipsis "..."))))
4990 (setq buffer-display-table org-display-table))
4991 (org-set-regexps-and-options)
4992 (when (and org-tag-faces (not org-tags-special-faces-re))
4993 ;; tag faces set outside customize.... force initialization.
4994 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4995 ;; Calc embedded
4996 (org-set-local 'calc-embedded-open-mode "# ")
4997 (modify-syntax-entry ?@ "w")
4998 (if org-startup-truncated (setq truncate-lines t))
4999 (org-set-local 'font-lock-unfontify-region-function
5000 'org-unfontify-region)
5001 ;; Activate before-change-function
5002 (org-set-local 'org-table-may-need-update t)
5003 (org-add-hook 'before-change-functions 'org-before-change-function nil
5004 'local)
5005 ;; Check for running clock before killing a buffer
5006 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5007 ;; Paragraphs and auto-filling
5008 (org-set-autofill-regexps)
5009 (setq indent-line-function 'org-indent-line-function)
5010 (org-update-radio-target-regexp)
5011 ;; Beginning/end of defun
5012 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5013 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5014 ;; Next error for sparse trees
5015 (org-set-local 'next-error-function 'org-occur-next-match)
5016 ;; Make sure dependence stuff works reliably, even for users who set it
5017 ;; too late :-(
5018 (if org-enforce-todo-dependencies
5019 (add-hook 'org-blocker-hook
5020 'org-block-todo-from-children-or-siblings-or-parent)
5021 (remove-hook 'org-blocker-hook
5022 'org-block-todo-from-children-or-siblings-or-parent))
5023 (if org-enforce-todo-checkbox-dependencies
5024 (add-hook 'org-blocker-hook
5025 'org-block-todo-from-checkboxes)
5026 (remove-hook 'org-blocker-hook
5027 'org-block-todo-from-checkboxes))
5029 ;; Comment characters
5030 (org-set-local 'comment-start "#")
5031 (org-set-local 'comment-padding " ")
5033 ;; Align options lines
5034 (org-set-local
5035 'align-mode-rules-list
5036 '((org-in-buffer-settings
5037 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5038 (modes . '(org-mode)))))
5040 ;; Imenu
5041 (org-set-local 'imenu-create-index-function
5042 'org-imenu-get-tree)
5044 ;; Make isearch reveal context
5045 (if (or (featurep 'xemacs)
5046 (not (boundp 'outline-isearch-open-invisible-function)))
5047 ;; Emacs 21 and XEmacs make use of the hook
5048 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5049 ;; Emacs 22 deals with this through a special variable
5050 (org-set-local 'outline-isearch-open-invisible-function
5051 (lambda (&rest ignore) (org-show-context 'isearch))))
5053 ;; Turn on org-beamer-mode?
5054 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5056 ;; Setup the pcomplete hooks
5057 (set (make-local-variable 'pcomplete-command-completion-function)
5058 'org-pcomplete-initial)
5059 (set (make-local-variable 'pcomplete-command-name-function)
5060 'org-command-at-point)
5061 (set (make-local-variable 'pcomplete-default-completion-function)
5062 'ignore)
5063 (set (make-local-variable 'pcomplete-parse-arguments-function)
5064 'org-parse-arguments)
5065 (set (make-local-variable 'pcomplete-termination-string) "")
5066 (set (make-local-variable 'face-remapping-alist)
5067 '((default org-default)))
5069 ;; If empty file that did not turn on org-mode automatically, make it to.
5070 (if (and org-insert-mode-line-in-empty-file
5071 (org-called-interactively-p 'any)
5072 (= (point-min) (point-max)))
5073 (insert "# -*- mode: org -*-\n\n"))
5074 (unless org-inhibit-startup
5075 (when org-startup-align-all-tables
5076 (let ((bmp (buffer-modified-p)))
5077 (org-table-map-tables 'org-table-align 'quietly)
5078 (set-buffer-modified-p bmp)))
5079 (when org-startup-with-inline-images
5080 (org-display-inline-images))
5081 (when org-startup-indented
5082 (require 'org-indent)
5083 (org-indent-mode 1))
5084 (unless org-inhibit-startup-visibility-stuff
5085 (org-set-startup-visibility))))
5087 (when (fboundp 'abbrev-table-put)
5088 (abbrev-table-put org-mode-abbrev-table
5089 :parents (list text-mode-abbrev-table)))
5091 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5093 (defun org-current-time ()
5094 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5095 (if (> (car org-time-stamp-rounding-minutes) 1)
5096 (let ((r (car org-time-stamp-rounding-minutes))
5097 (time (decode-time)))
5098 (apply 'encode-time
5099 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5100 (nthcdr 2 time))))
5101 (current-time)))
5103 (defun org-today ()
5104 "Return today date, considering `org-extend-today-until'."
5105 (time-to-days
5106 (time-subtract (current-time)
5107 (list 0 (* 3600 org-extend-today-until) 0))))
5109 ;;;; Font-Lock stuff, including the activators
5111 (defvar org-mouse-map (make-sparse-keymap))
5112 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5113 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5114 (when org-mouse-1-follows-link
5115 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5116 (when org-tab-follows-link
5117 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5118 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5120 (require 'font-lock)
5122 (defconst org-non-link-chars "]\t\n\r<>")
5123 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5124 "shell" "elisp" "doi" "message"))
5125 (defvar org-link-types-re nil
5126 "Matches a link that has a url-like prefix like \"http:\"")
5127 (defvar org-link-re-with-space nil
5128 "Matches a link with spaces, optional angular brackets around it.")
5129 (defvar org-link-re-with-space2 nil
5130 "Matches a link with spaces, optional angular brackets around it.")
5131 (defvar org-link-re-with-space3 nil
5132 "Matches a link with spaces, only for internal part in bracket links.")
5133 (defvar org-angle-link-re nil
5134 "Matches link with angular brackets, spaces are allowed.")
5135 (defvar org-plain-link-re nil
5136 "Matches plain link, without spaces.")
5137 (defvar org-bracket-link-regexp nil
5138 "Matches a link in double brackets.")
5139 (defvar org-bracket-link-analytic-regexp nil
5140 "Regular expression used to analyze links.
5141 Here is what the match groups contain after a match:
5142 1: http:
5143 2: http
5144 3: path
5145 4: [desc]
5146 5: desc")
5147 (defvar org-bracket-link-analytic-regexp++ nil
5148 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5149 (defvar org-any-link-re nil
5150 "Regular expression matching any link.")
5152 (defcustom org-match-sexp-depth 3
5153 "Number of stacked braces for sub/superscript matching.
5154 This has to be set before loading org.el to be effective."
5155 :group 'org-export-translation ; ??????????????????????????/
5156 :type 'integer)
5158 (defun org-create-multibrace-regexp (left right n)
5159 "Create a regular expression which will match a balanced sexp.
5160 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5161 as single character strings.
5162 The regexp returned will match the entire expression including the
5163 delimiters. It will also define a single group which contains the
5164 match except for the outermost delimiters. The maximum depth of
5165 stacked delimiters is N. Escaping delimiters is not possible."
5166 (let* ((nothing (concat "[^" left right "]*?"))
5167 (or "\\|")
5168 (re nothing)
5169 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5170 (while (> n 1)
5171 (setq n (1- n)
5172 re (concat re or next)
5173 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5174 (concat left "\\(" re "\\)" right)))
5176 (defvar org-match-substring-regexp
5177 (concat
5178 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5179 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5180 "\\|"
5181 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5182 "\\|"
5183 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5184 "The regular expression matching a sub- or superscript.")
5186 (defvar org-match-substring-with-braces-regexp
5187 (concat
5188 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5189 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5190 "\\)")
5191 "The regular expression matching a sub- or superscript, forcing braces.")
5193 (defun org-make-link-regexps ()
5194 "Update the link regular expressions.
5195 This should be called after the variable `org-link-types' has changed."
5196 (setq org-link-types-re
5197 (concat
5198 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5199 org-link-re-with-space
5200 (concat
5201 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5202 "\\([^" org-non-link-chars " ]"
5203 "[^" org-non-link-chars "]*"
5204 "[^" org-non-link-chars " ]\\)>?")
5205 org-link-re-with-space2
5206 (concat
5207 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5208 "\\([^" org-non-link-chars " ]"
5209 "[^\t\n\r]*"
5210 "[^" org-non-link-chars " ]\\)>?")
5211 org-link-re-with-space3
5212 (concat
5213 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5214 "\\([^" org-non-link-chars " ]"
5215 "[^\t\n\r]*\\)")
5216 org-angle-link-re
5217 (concat
5218 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5219 "\\([^" org-non-link-chars " ]"
5220 "[^" org-non-link-chars "]*"
5221 "\\)>")
5222 org-plain-link-re
5223 (concat
5224 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5225 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5226 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5227 org-bracket-link-regexp
5228 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5229 org-bracket-link-analytic-regexp
5230 (concat
5231 "\\[\\["
5232 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5233 "\\([^]]+\\)"
5234 "\\]"
5235 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5236 "\\]")
5237 org-bracket-link-analytic-regexp++
5238 (concat
5239 "\\[\\["
5240 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5241 "\\([^]]+\\)"
5242 "\\]"
5243 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5244 "\\]")
5245 org-any-link-re
5246 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5247 org-angle-link-re "\\)\\|\\("
5248 org-plain-link-re "\\)")))
5250 (org-make-link-regexps)
5252 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5253 "Regular expression for fast time stamp matching.")
5254 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5255 "Regular expression for fast time stamp matching.")
5256 (defconst org-ts-regexp0
5257 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5258 "Regular expression matching time strings for analysis.
5259 This one does not require the space after the date, so it can be used
5260 on a string that terminates immediately after the date.")
5261 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5262 "Regular expression matching time strings for analysis.")
5263 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5264 "Regular expression matching time stamps, with groups.")
5265 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5266 "Regular expression matching time stamps (also [..]), with groups.")
5267 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5268 "Regular expression matching a time stamp range.")
5269 (defconst org-tr-regexp-both
5270 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5271 "Regular expression matching a time stamp range.")
5272 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5273 org-ts-regexp "\\)?")
5274 "Regular expression matching a time stamp or time stamp range.")
5275 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5276 org-ts-regexp-both "\\)?")
5277 "Regular expression matching a time stamp or time stamp range.
5278 The time stamps may be either active or inactive.")
5280 (defvar org-emph-face nil)
5282 (defun org-do-emphasis-faces (limit)
5283 "Run through the buffer and add overlays to emphasized strings."
5284 (let (rtn a)
5285 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5286 (if (not (= (char-after (match-beginning 3))
5287 (char-after (match-beginning 4))))
5288 (progn
5289 (setq rtn t)
5290 (setq a (assoc (match-string 3) org-emphasis-alist))
5291 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5292 'face
5293 (nth 1 a))
5294 (and (nth 4 a)
5295 (org-remove-flyspell-overlays-in
5296 (match-beginning 0) (match-end 0)))
5297 (add-text-properties (match-beginning 2) (match-end 2)
5298 '(font-lock-multiline t org-emphasis t))
5299 (when org-hide-emphasis-markers
5300 (add-text-properties (match-end 4) (match-beginning 5)
5301 '(invisible org-link))
5302 (add-text-properties (match-beginning 3) (match-end 3)
5303 '(invisible org-link)))))
5304 (backward-char 1))
5305 rtn))
5307 (defun org-emphasize (&optional char)
5308 "Insert or change an emphasis, i.e. a font like bold or italic.
5309 If there is an active region, change that region to a new emphasis.
5310 If there is no region, just insert the marker characters and position
5311 the cursor between them.
5312 CHAR should be either the marker character, or the first character of the
5313 HTML tag associated with that emphasis. If CHAR is a space, the means
5314 to remove the emphasis of the selected region.
5315 If char is not given (for example in an interactive call) it
5316 will be prompted for."
5317 (interactive)
5318 (let ((eal org-emphasis-alist) e det
5319 (erc org-emphasis-regexp-components)
5320 (prompt "")
5321 (string "") beg end move tag c s)
5322 (if (org-region-active-p)
5323 (setq beg (region-beginning) end (region-end)
5324 string (buffer-substring beg end))
5325 (setq move t))
5327 (while (setq e (pop eal))
5328 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5329 c (aref tag 0))
5330 (push (cons c (string-to-char (car e))) det)
5331 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5332 (substring tag 1)))))
5333 (setq det (nreverse det))
5334 (unless char
5335 (message "%s" (concat "Emphasis marker or tag:" prompt))
5336 (setq char (read-char-exclusive)))
5337 (setq char (or (cdr (assoc char det)) char))
5338 (if (equal char ?\ )
5339 (setq s "" move nil)
5340 (unless (assoc (char-to-string char) org-emphasis-alist)
5341 (error "No such emphasis marker: \"%c\"" char))
5342 (setq s (char-to-string char)))
5343 (while (and (> (length string) 1)
5344 (equal (substring string 0 1) (substring string -1))
5345 (assoc (substring string 0 1) org-emphasis-alist))
5346 (setq string (substring string 1 -1)))
5347 (setq string (concat s string s))
5348 (if beg (delete-region beg end))
5349 (unless (or (bolp)
5350 (string-match (concat "[" (nth 0 erc) "\n]")
5351 (char-to-string (char-before (point)))))
5352 (insert " "))
5353 (unless (or (eobp)
5354 (string-match (concat "[" (nth 1 erc) "\n]")
5355 (char-to-string (char-after (point)))))
5356 (insert " ") (backward-char 1))
5357 (insert string)
5358 (and move (backward-char 1))))
5360 (defconst org-nonsticky-props
5361 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5363 (defsubst org-rear-nonsticky-at (pos)
5364 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5366 (defun org-activate-plain-links (limit)
5367 "Run through the buffer and add overlays to links."
5368 (catch 'exit
5369 (let (f)
5370 (if (re-search-forward org-plain-link-re limit t)
5371 (progn
5372 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5373 (setq f (get-text-property (match-beginning 0) 'face))
5374 (if (or (eq f 'org-tag)
5375 (and (listp f) (memq 'org-tag f)))
5377 (add-text-properties (match-beginning 0) (match-end 0)
5378 (list 'mouse-face 'highlight
5379 'face 'org-link
5380 'keymap org-mouse-map))
5381 (org-rear-nonsticky-at (match-end 0)))
5382 t)))))
5384 (defun org-activate-code (limit)
5385 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5386 (progn
5387 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5388 (remove-text-properties (match-beginning 0) (match-end 0)
5389 '(display t invisible t intangible t))
5390 t)))
5392 (defcustom org-src-fontify-natively nil
5393 "When non-nil, fontify code in code blocks."
5394 :type 'boolean
5395 :version "24.1"
5396 :group 'org-appearance
5397 :group 'org-babel)
5399 (defun org-fontify-meta-lines-and-blocks (limit)
5400 (condition-case nil
5401 (org-fontify-meta-lines-and-blocks-1 limit)
5402 (error (message "org-mode fontification error"))))
5404 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5405 "Fontify #+ lines and blocks, in the correct ways."
5406 (let ((case-fold-search t))
5407 (if (re-search-forward
5408 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5409 limit t)
5410 (let ((beg (match-beginning 0))
5411 (block-start (match-end 0))
5412 (block-end nil)
5413 (lang (match-string 7))
5414 (beg1 (line-beginning-position 2))
5415 (dc1 (downcase (match-string 2)))
5416 (dc3 (downcase (match-string 3)))
5417 end end1 quoting block-type ovl)
5418 (cond
5419 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5420 ;; a single line of backend-specific content
5421 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5422 (remove-text-properties (match-beginning 0) (match-end 0)
5423 '(display t invisible t intangible t))
5424 (add-text-properties (match-beginning 1) (match-end 3)
5425 '(font-lock-fontified t face org-meta-line))
5426 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5427 '(font-lock-fontified t face org-block))
5428 ; for backend-specific code
5430 ((and (match-end 4) (equal dc3 "begin"))
5431 ;; Truly a block
5432 (setq block-type (downcase (match-string 5))
5433 quoting (member block-type org-protecting-blocks))
5434 (when (re-search-forward
5435 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5436 nil t) ;; on purpose, we look further than LIMIT
5437 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5438 (setq block-end (match-beginning 0))
5439 (when quoting
5440 (remove-text-properties beg end
5441 '(display t invisible t intangible t)))
5442 (add-text-properties
5443 beg end
5444 '(font-lock-fontified t font-lock-multiline t))
5445 (add-text-properties beg beg1 '(face org-meta-line))
5446 (add-text-properties end1 (min (point-max) (1+ end))
5447 '(face org-meta-line)) ; for end_src
5448 (cond
5449 ((and lang (not (string= lang "")) org-src-fontify-natively)
5450 (org-src-font-lock-fontify-block lang block-start block-end)
5451 ;; remove old background overlays
5452 (mapc (lambda (ov)
5453 (if (eq (overlay-get ov 'face) 'org-block-background)
5454 (delete-overlay ov)))
5455 (overlays-at (/ (+ beg1 block-end) 2)))
5456 ;; add a background overlay
5457 (setq ovl (make-overlay beg1 block-end))
5458 (overlay-put ovl 'face 'org-block-background)
5459 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5460 (quoting
5461 (add-text-properties beg1 (min (point-max) (1+ end1))
5462 '(face org-block))) ; end of source block
5463 ((not org-fontify-quote-and-verse-blocks))
5464 ((string= block-type "quote")
5465 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5466 ((string= block-type "verse")
5467 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5468 (add-text-properties beg beg1 '(face org-block-begin-line))
5469 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5471 ((member dc1 '("title:" "author:" "email:" "date:"))
5472 (add-text-properties
5473 beg (match-end 3)
5474 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5475 '(font-lock-fontified t invisible t)
5476 '(font-lock-fontified t face org-document-info-keyword)))
5477 (add-text-properties
5478 (match-beginning 6) (match-end 6)
5479 (if (string-equal dc1 "title:")
5480 '(font-lock-fontified t face org-document-title)
5481 '(font-lock-fontified t face org-document-info))))
5482 ((not (member (char-after beg) '(?\ ?\t)))
5483 ;; just any other in-buffer setting, but not indented
5484 (add-text-properties
5485 beg (1+ (match-end 0))
5486 '(font-lock-fontified t face org-meta-line))
5488 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5489 "orgtbl:" "tblfm:" "tblname:" "results:"
5490 "call:" "header:" "headers:" "name:"))
5491 (and (match-end 4) (equal dc3 "attr")))
5492 (add-text-properties
5493 beg (match-end 0)
5494 '(font-lock-fontified t face org-meta-line))
5496 ((member dc3 '(" " ""))
5497 (add-text-properties
5498 beg (match-end 0)
5499 '(font-lock-fontified t face font-lock-comment-face)))
5500 (t nil))))))
5502 (defun org-strip-protective-commas (beg end)
5503 "Strip protective commas between BEG and END in the current buffer."
5504 (interactive "r")
5505 (save-excursion
5506 (save-match-data
5507 (goto-char beg)
5508 (let ((front-line (save-excursion
5509 (re-search-forward
5510 "[^[:space:]]" end t)
5511 (goto-char (match-beginning 0))
5512 (current-column))))
5513 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5514 (goto-char (match-beginning 1))
5515 (when (= (current-column) front-line)
5516 (replace-match "" nil nil nil 1)))))))
5518 (defun org-activate-angle-links (limit)
5519 "Run through the buffer and add overlays to links."
5520 (if (re-search-forward org-angle-link-re limit t)
5521 (progn
5522 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5523 (add-text-properties (match-beginning 0) (match-end 0)
5524 (list 'mouse-face 'highlight
5525 'keymap org-mouse-map))
5526 (org-rear-nonsticky-at (match-end 0))
5527 t)))
5529 (defun org-activate-footnote-links (limit)
5530 "Run through the buffer and add overlays to footnotes."
5531 (let ((fn (org-footnote-next-reference-or-definition limit)))
5532 (when fn
5533 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5534 (org-remove-flyspell-overlays-in beg end)
5535 (add-text-properties beg end
5536 (list 'mouse-face 'highlight
5537 'keymap org-mouse-map
5538 'help-echo
5539 (if (= (point-at-bol) beg)
5540 "Footnote definition"
5541 "Footnote reference")
5542 'font-lock-fontified t
5543 'font-lock-multiline t
5544 'face 'org-footnote))))))
5546 (defun org-activate-bracket-links (limit)
5547 "Run through the buffer and add overlays to bracketed links."
5548 (if (re-search-forward org-bracket-link-regexp limit t)
5549 (let* ((help (concat "LINK: "
5550 (org-match-string-no-properties 1)))
5551 ;; FIXME: above we should remove the escapes.
5552 ;; but that requires another match, protecting match data,
5553 ;; a lot of overhead for font-lock.
5554 (ip (org-maybe-intangible
5555 (list 'invisible 'org-link
5556 'keymap org-mouse-map 'mouse-face 'highlight
5557 'font-lock-multiline t 'help-echo help)))
5558 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5559 'font-lock-multiline t 'help-echo help)))
5560 ;; We need to remove the invisible property here. Table narrowing
5561 ;; may have made some of this invisible.
5562 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5563 (remove-text-properties (match-beginning 0) (match-end 0)
5564 '(invisible nil))
5565 (if (match-end 3)
5566 (progn
5567 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5568 (org-rear-nonsticky-at (match-beginning 3))
5569 (add-text-properties (match-beginning 3) (match-end 3) vp)
5570 (org-rear-nonsticky-at (match-end 3))
5571 (add-text-properties (match-end 3) (match-end 0) ip)
5572 (org-rear-nonsticky-at (match-end 0)))
5573 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5574 (org-rear-nonsticky-at (match-beginning 1))
5575 (add-text-properties (match-beginning 1) (match-end 1) vp)
5576 (org-rear-nonsticky-at (match-end 1))
5577 (add-text-properties (match-end 1) (match-end 0) ip)
5578 (org-rear-nonsticky-at (match-end 0)))
5579 t)))
5581 (defun org-activate-dates (limit)
5582 "Run through the buffer and add overlays to dates."
5583 (if (re-search-forward org-tsr-regexp-both limit t)
5584 (progn
5585 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5586 (add-text-properties (match-beginning 0) (match-end 0)
5587 (list 'mouse-face 'highlight
5588 'keymap org-mouse-map))
5589 (org-rear-nonsticky-at (match-end 0))
5590 (when org-display-custom-times
5591 (if (match-end 3)
5592 (org-display-custom-time (match-beginning 3) (match-end 3)))
5593 (org-display-custom-time (match-beginning 1) (match-end 1)))
5594 t)))
5596 (defvar org-target-link-regexp nil
5597 "Regular expression matching radio targets in plain text.")
5598 (make-variable-buffer-local 'org-target-link-regexp)
5599 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5600 "Regular expression matching a link target.")
5601 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5602 "Regular expression matching a radio target.")
5603 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5604 "Regular expression matching any target.")
5606 (defun org-activate-target-links (limit)
5607 "Run through the buffer and add overlays to target matches."
5608 (when org-target-link-regexp
5609 (let ((case-fold-search t))
5610 (if (re-search-forward org-target-link-regexp limit t)
5611 (progn
5612 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5613 (add-text-properties (match-beginning 0) (match-end 0)
5614 (list 'mouse-face 'highlight
5615 'keymap org-mouse-map
5616 'help-echo "Radio target link"
5617 'org-linked-text t))
5618 (org-rear-nonsticky-at (match-end 0))
5619 t)))))
5621 (defun org-update-radio-target-regexp ()
5622 "Find all radio targets in this file and update the regular expression."
5623 (interactive)
5624 (when (memq 'radio org-activate-links)
5625 (setq org-target-link-regexp
5626 (org-make-target-link-regexp (org-all-targets 'radio)))
5627 (org-restart-font-lock)))
5629 (defun org-hide-wide-columns (limit)
5630 (let (s e)
5631 (setq s (text-property-any (point) (or limit (point-max))
5632 'org-cwidth t))
5633 (when s
5634 (setq e (next-single-property-change s 'org-cwidth))
5635 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5636 (goto-char e)
5637 t)))
5639 (defvar org-latex-and-specials-regexp nil
5640 "Regular expression for highlighting export special stuff.")
5641 (defvar org-match-substring-regexp)
5642 (defvar org-match-substring-with-braces-regexp)
5644 ;; This should be with the exporter code, but we also use if for font-locking
5645 (defconst org-export-html-special-string-regexps
5646 '(("\\\\-" . "&shy;")
5647 ("---\\([^-]\\)" . "&mdash;\\1")
5648 ("--\\([^-]\\)" . "&ndash;\\1")
5649 ("\\.\\.\\." . "&hellip;"))
5650 "Regular expressions for special string conversion.")
5653 (defun org-compute-latex-and-specials-regexp ()
5654 "Compute regular expression for stuff treated specially by exporters."
5655 (if (not org-highlight-latex-fragments-and-specials)
5656 (org-set-local 'org-latex-and-specials-regexp nil)
5657 (require 'org-exp)
5658 (let*
5659 ((matchers (plist-get org-format-latex-options :matchers))
5660 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5661 org-latex-regexps)))
5662 (org-export-allow-BIND nil)
5663 (options (org-combine-plists (org-default-export-plist)
5664 (org-infile-export-plist)))
5665 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5666 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5667 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5668 (org-export-html-expand (plist-get options :expand-quoted-html))
5669 (org-export-with-special-strings (plist-get options :special-strings))
5670 (re-sub
5671 (cond
5672 ((equal org-export-with-sub-superscripts '{})
5673 (list org-match-substring-with-braces-regexp))
5674 (org-export-with-sub-superscripts
5675 (list org-match-substring-regexp))
5676 (t nil)))
5677 (re-latex
5678 (if org-export-with-LaTeX-fragments
5679 (mapcar (lambda (x) (nth 1 x)) latexs)))
5680 (re-macros
5681 (if org-export-with-TeX-macros
5682 (list (concat "\\\\"
5683 (regexp-opt
5684 (append
5686 (delq nil
5687 (mapcar 'car-safe
5688 (append org-entities-user
5689 org-entities)))
5690 (if (boundp 'org-latex-entities)
5691 (mapcar (lambda (x)
5692 (or (car-safe x) x))
5693 org-latex-entities)
5694 nil))
5695 'words))) ; FIXME
5697 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5698 (re-special (if org-export-with-special-strings
5699 (mapcar (lambda (x) (car x))
5700 org-export-html-special-string-regexps)))
5701 (re-rest
5702 (delq nil
5703 (list
5704 (if org-export-html-expand "@<[^>\n]+>")
5705 ))))
5706 (org-set-local
5707 'org-latex-and-specials-regexp
5708 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5709 re-rest) "\\|")))))
5711 (defun org-do-latex-and-special-faces (limit)
5712 "Run through the buffer and add overlays to links."
5713 (when org-latex-and-specials-regexp
5714 (let (rtn d)
5715 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5716 limit t))
5717 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5718 'face))
5719 '(org-code org-verbatim underline)))
5720 (progn
5721 (setq rtn t
5722 d (cond ((member (char-after (1+ (match-beginning 0)))
5723 '(?_ ?^)) 1)
5724 (t 0)))
5725 (font-lock-prepend-text-property
5726 (+ d (match-beginning 0)) (match-end 0)
5727 'face 'org-latex-and-export-specials)
5728 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5729 '(font-lock-multiline t)))))
5730 rtn)))
5732 (defun org-restart-font-lock ()
5733 "Restart `font-lock-mode', to force refontification."
5734 (when (and (boundp 'font-lock-mode) font-lock-mode)
5735 (font-lock-mode -1)
5736 (font-lock-mode 1)))
5738 (defun org-all-targets (&optional radio)
5739 "Return a list of all targets in this file.
5740 With optional argument RADIO, only find radio targets."
5741 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5742 rtn)
5743 (save-excursion
5744 (goto-char (point-min))
5745 (while (re-search-forward re nil t)
5746 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5747 rtn)))
5749 (defun org-make-target-link-regexp (targets)
5750 "Make regular expression matching all strings in TARGETS.
5751 The regular expression finds the targets also if there is a line break
5752 between words."
5753 (and targets
5754 (concat
5755 "\\<\\("
5756 (mapconcat
5757 (lambda (x)
5758 (setq x (regexp-quote x))
5759 (while (string-match " +" x)
5760 (setq x (replace-match "\\s-+" t t x)))
5762 targets
5763 "\\|")
5764 "\\)\\>")))
5766 (defun org-activate-tags (limit)
5767 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5768 (progn
5769 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5770 (add-text-properties (match-beginning 1) (match-end 1)
5771 (list 'mouse-face 'highlight
5772 'keymap org-mouse-map))
5773 (org-rear-nonsticky-at (match-end 1))
5774 t)))
5776 (defun org-outline-level ()
5777 "Compute the outline level of the heading at point.
5778 This function assumes that the cursor is at the beginning of a line matched
5779 by `outline-regexp'. Otherwise it returns garbage.
5780 If this is called at a normal headline, the level is the number of stars.
5781 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5782 (save-excursion
5783 (looking-at org-outline-regexp)
5784 (1- (- (match-end 0) (match-beginning 0)))))
5786 (defvar org-font-lock-keywords nil)
5788 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5789 "Regular expression matching a property line.")
5791 (defvar org-font-lock-hook nil
5792 "Functions to be called for special font lock stuff.")
5794 (defvar org-font-lock-set-keywords-hook nil
5795 "Functions that can manipulate `org-font-lock-extra-keywords'.
5796 This is called after `org-font-lock-extra-keywords' is defined, but before
5797 it is installed to be used by font lock. This can be useful if something
5798 needs to be inserted at a specific position in the font-lock sequence.")
5800 (defun org-font-lock-hook (limit)
5801 (run-hook-with-args 'org-font-lock-hook limit))
5803 (defun org-set-font-lock-defaults ()
5804 (let* ((em org-fontify-emphasized-text)
5805 (lk org-activate-links)
5806 (org-font-lock-extra-keywords
5807 (list
5808 ;; Call the hook
5809 '(org-font-lock-hook)
5810 ;; Headlines
5811 `(,(if org-fontify-whole-heading-line
5812 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5813 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5814 (1 (org-get-level-face 1))
5815 (2 (org-get-level-face 2))
5816 (3 (org-get-level-face 3)))
5817 ;; Table lines
5818 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5819 (1 'org-table t))
5820 ;; Table internals
5821 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5822 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5823 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5824 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5825 ;; Drawers
5826 (list org-drawer-regexp '(0 'org-special-keyword t))
5827 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5828 ;; Properties
5829 (list org-property-re
5830 '(1 'org-special-keyword t)
5831 '(3 'org-property-value t))
5832 ;; Links
5833 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5834 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5835 (if (memq 'plain lk) '(org-activate-plain-links))
5836 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5837 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5838 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5839 (if (memq 'footnote lk) '(org-activate-footnote-links))
5840 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5841 '(org-hide-wide-columns (0 nil append))
5842 ;; TODO keyword
5843 (list (format org-heading-keyword-regexp-format
5844 org-todo-regexp)
5845 '(2 (org-get-todo-face 2) t))
5846 ;; DONE
5847 (if org-fontify-done-headline
5848 (list (format org-heading-keyword-regexp-format
5849 (concat
5850 "\\(?:"
5851 (mapconcat 'regexp-quote org-done-keywords "\\|")
5852 "\\)"))
5853 '(2 'org-headline-done t))
5854 nil)
5855 ;; Priorities
5856 '(org-font-lock-add-priority-faces)
5857 ;; Tags
5858 '(org-font-lock-add-tag-faces)
5859 ;; Special keywords
5860 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5861 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5862 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5863 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5864 ;; Emphasis
5865 (if em
5866 (if (featurep 'xemacs)
5867 '(org-do-emphasis-faces (0 nil append))
5868 '(org-do-emphasis-faces)))
5869 ;; Checkboxes
5870 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5871 1 'org-checkbox prepend)
5872 (if (cdr (assq 'checkbox org-list-automatic-rules))
5873 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5874 (0 (org-get-checkbox-statistics-face) t)))
5875 ;; Description list items
5876 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5877 1 'bold prepend)
5878 ;; ARCHIVEd headings
5879 (list (concat
5880 org-outline-regexp-bol
5881 "\\(.*:" org-archive-tag ":.*\\)")
5882 '(1 'org-archived prepend))
5883 ;; Specials
5884 '(org-do-latex-and-special-faces)
5885 '(org-fontify-entities)
5886 '(org-raise-scripts)
5887 ;; Code
5888 '(org-activate-code (1 'org-code t))
5889 ;; COMMENT
5890 (list (format org-heading-keyword-regexp-format
5891 (concat "\\("
5892 org-comment-string "\\|" org-quote-string
5893 "\\)"))
5894 '(2 'org-special-keyword t))
5895 '("^#.*" (0 'font-lock-comment-face t))
5896 ;; Blocks and meta lines
5897 '(org-fontify-meta-lines-and-blocks)
5899 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5900 (run-hooks 'org-font-lock-set-keywords-hook)
5901 ;; Now set the full font-lock-keywords
5902 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5903 (org-set-local 'font-lock-defaults
5904 '(org-font-lock-keywords t nil nil backward-paragraph))
5905 (kill-local-variable 'font-lock-keywords) nil))
5907 (defun org-toggle-pretty-entities ()
5908 "Toggle the composition display of entities as UTF8 characters."
5909 (interactive)
5910 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5911 (org-restart-font-lock)
5912 (if org-pretty-entities
5913 (message "Entities are displayed as UTF8 characters")
5914 (save-restriction
5915 (widen)
5916 (org-decompose-region (point-min) (point-max))
5917 (message "Entities are displayed plain"))))
5919 (defun org-fontify-entities (limit)
5920 "Find an entity to fontify."
5921 (let (ee)
5922 (when org-pretty-entities
5923 (catch 'match
5924 (while (re-search-forward
5925 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5926 limit t)
5927 (if (and (not (org-in-indented-comment-line))
5928 (setq ee (org-entity-get (match-string 1)))
5929 (= (length (nth 6 ee)) 1))
5930 (progn
5931 (add-text-properties
5932 (match-beginning 0) (match-end 1)
5933 (list 'font-lock-fontified t))
5934 (compose-region (match-beginning 0) (match-end 1)
5935 (nth 6 ee) nil)
5936 (backward-char 1)
5937 (throw 'match t))))
5938 nil))))
5940 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5941 "Fontify string S like in Org-mode."
5942 (with-temp-buffer
5943 (insert s)
5944 (let ((org-odd-levels-only odd-levels))
5945 (org-mode)
5946 (font-lock-fontify-buffer)
5947 (buffer-string))))
5949 (defvar org-m nil)
5950 (defvar org-l nil)
5951 (defvar org-f nil)
5952 (defun org-get-level-face (n)
5953 "Get the right face for match N in font-lock matching of headlines."
5954 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5955 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5956 (if org-cycle-level-faces
5957 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5958 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5959 (cond
5960 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5961 ((eq n 2) org-f)
5962 (t (if org-level-color-stars-only nil org-f))))
5965 (defun org-get-todo-face (kwd)
5966 "Get the right face for a TODO keyword KWD.
5967 If KWD is a number, get the corresponding match group."
5968 (if (numberp kwd) (setq kwd (match-string kwd)))
5969 (or (org-face-from-face-or-color
5970 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5971 (and (member kwd org-done-keywords) 'org-done)
5972 'org-todo))
5974 (defun org-face-from-face-or-color (context inherit face-or-color)
5975 "Create a face list that inherits INHERIT, but sets the foreground color.
5976 When FACE-OR-COLOR is not a string, just return it."
5977 (if (stringp face-or-color)
5978 (list :inherit inherit
5979 (cdr (assoc context org-faces-easy-properties))
5980 face-or-color)
5981 face-or-color))
5983 (defun org-font-lock-add-tag-faces (limit)
5984 "Add the special tag faces."
5985 (when (and org-tag-faces org-tags-special-faces-re)
5986 (while (re-search-forward org-tags-special-faces-re limit t)
5987 (add-text-properties (match-beginning 1) (match-end 1)
5988 (list 'face (org-get-tag-face 1)
5989 'font-lock-fontified t))
5990 (backward-char 1))))
5992 (defun org-font-lock-add-priority-faces (limit)
5993 "Add the special priority faces."
5994 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5995 (add-text-properties
5996 (match-beginning 0) (match-end 0)
5997 (list 'face (or (org-face-from-face-or-color
5998 'priority 'org-special-keyword
5999 (cdr (assoc (char-after (match-beginning 1))
6000 org-priority-faces)))
6001 'org-special-keyword)
6002 'font-lock-fontified t))))
6004 (defun org-get-tag-face (kwd)
6005 "Get the right face for a TODO keyword KWD.
6006 If KWD is a number, get the corresponding match group."
6007 (if (numberp kwd) (setq kwd (match-string kwd)))
6008 (or (org-face-from-face-or-color
6009 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6010 'org-tag))
6012 (defun org-unfontify-region (beg end &optional maybe_loudly)
6013 "Remove fontification and activation overlays from links."
6014 (font-lock-default-unfontify-region beg end)
6015 (let* ((buffer-undo-list t)
6016 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6017 (inhibit-modification-hooks t)
6018 deactivate-mark buffer-file-name buffer-file-truename)
6019 (org-decompose-region beg end)
6020 (remove-text-properties beg end
6021 '(mouse-face t keymap t org-linked-text t
6022 invisible t intangible t
6023 org-no-flyspell t org-emphasis t))
6024 (org-remove-font-lock-display-properties beg end)))
6026 (defconst org-script-display '(((raise -0.3) (height 0.7))
6027 ((raise 0.3) (height 0.7))
6028 ((raise -0.5))
6029 ((raise 0.5)))
6030 "Display properties for showing superscripts and subscripts.")
6032 (defun org-remove-font-lock-display-properties (beg end)
6033 "Remove specific display properties that have been added by font lock.
6034 The will remove the raise properties that are used to show superscripts
6035 and subscripts."
6036 (let (next prop)
6037 (while (< beg end)
6038 (setq next (next-single-property-change beg 'display nil end)
6039 prop (get-text-property beg 'display))
6040 (if (member prop org-script-display)
6041 (put-text-property beg next 'display nil))
6042 (setq beg next))))
6044 (defun org-raise-scripts (limit)
6045 "Add raise properties to sub/superscripts."
6046 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6047 (if (re-search-forward
6048 (if (eq org-use-sub-superscripts t)
6049 org-match-substring-regexp
6050 org-match-substring-with-braces-regexp)
6051 limit t)
6052 (let* ((pos (point)) table-p comment-p
6053 (mpos (match-beginning 3))
6054 (emph-p (get-text-property mpos 'org-emphasis))
6055 (link-p (get-text-property mpos 'mouse-face))
6056 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6057 (goto-char (point-at-bol))
6058 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6059 comment-p (org-looking-at-p "[ \t]*#"))
6060 (goto-char pos)
6061 ;; FIXME: Should we go back one character here, for a_b^c
6062 ;; (goto-char (1- pos)) ;????????????????????
6063 (if (or comment-p emph-p link-p keyw-p)
6065 (put-text-property (match-beginning 3) (match-end 0)
6066 'display
6067 (if (equal (char-after (match-beginning 2)) ?^)
6068 (nth (if table-p 3 1) org-script-display)
6069 (nth (if table-p 2 0) org-script-display)))
6070 (add-text-properties (match-beginning 2) (match-end 2)
6071 (list 'invisible t
6072 'org-dwidth t 'org-dwidth-n 1))
6073 (if (and (eq (char-after (match-beginning 3)) ?{)
6074 (eq (char-before (match-end 3)) ?}))
6075 (progn
6076 (add-text-properties
6077 (match-beginning 3) (1+ (match-beginning 3))
6078 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6079 (add-text-properties
6080 (1- (match-end 3)) (match-end 3)
6081 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6082 t)))))
6084 ;;;; Visibility cycling, including org-goto and indirect buffer
6086 ;;; Cycling
6088 (defvar org-cycle-global-status nil)
6089 (make-variable-buffer-local 'org-cycle-global-status)
6090 (defvar org-cycle-subtree-status nil)
6091 (make-variable-buffer-local 'org-cycle-subtree-status)
6093 ;;;###autoload
6095 (defvar org-inlinetask-min-level)
6097 (defun org-cycle (&optional arg)
6098 "TAB-action and visibility cycling for Org-mode.
6100 This is the command invoked in Org-mode by the TAB key. Its main purpose
6101 is outline visibility cycling, but it also invokes other actions
6102 in special contexts.
6104 - When this function is called with a prefix argument, rotate the entire
6105 buffer through 3 states (global cycling)
6106 1. OVERVIEW: Show only top-level headlines.
6107 2. CONTENTS: Show all headlines of all levels, but no body text.
6108 3. SHOW ALL: Show everything.
6109 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6110 determined by the variable `org-startup-folded', and by any VISIBILITY
6111 properties in the buffer.
6112 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6113 including any drawers.
6115 - When inside a table, re-align the table and move to the next field.
6117 - When point is at the beginning of a headline, rotate the subtree started
6118 by this line through 3 different states (local cycling)
6119 1. FOLDED: Only the main headline is shown.
6120 2. CHILDREN: The main headline and the direct children are shown.
6121 From this state, you can move to one of the children
6122 and zoom in further.
6123 3. SUBTREE: Show the entire subtree, including body text.
6124 If there is no subtree, switch directly from CHILDREN to FOLDED.
6126 - When point is at the beginning of an empty headline and the variable
6127 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6128 of the headline by demoting and promoting it to likely levels. This
6129 speeds up creation document structure by pressing TAB once or several
6130 times right after creating a new headline.
6132 - When there is a numeric prefix, go up to a heading with level ARG, do
6133 a `show-subtree' and return to the previous cursor position. If ARG
6134 is negative, go up that many levels.
6136 - When point is not at the beginning of a headline, execute the global
6137 binding for TAB, which is re-indenting the line. See the option
6138 `org-cycle-emulate-tab' for details.
6140 - Special case: if point is at the beginning of the buffer and there is
6141 no headline in line 1, this function will act as if called with prefix arg
6142 (C-u TAB, same as S-TAB) also when called without prefix arg.
6143 But only if also the variable `org-cycle-global-at-bob' is t."
6144 (interactive "P")
6145 (org-load-modules-maybe)
6146 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6147 (and org-cycle-level-after-item/entry-creation
6148 (or (org-cycle-level)
6149 (org-cycle-item-indentation))))
6150 (let* ((limit-level
6151 (or org-cycle-max-level
6152 (and (boundp 'org-inlinetask-min-level)
6153 org-inlinetask-min-level
6154 (1- org-inlinetask-min-level))))
6155 (nstars (and limit-level
6156 (if org-odd-levels-only
6157 (and limit-level (1- (* limit-level 2)))
6158 limit-level)))
6159 (org-outline-regexp
6160 (if (not (eq major-mode 'org-mode))
6161 outline-regexp
6162 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6163 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6164 (not (looking-at org-outline-regexp))))
6165 (org-cycle-hook
6166 (if bob-special
6167 (delq 'org-optimize-window-after-visibility-change
6168 (copy-sequence org-cycle-hook))
6169 org-cycle-hook))
6170 (pos (point)))
6172 (if (or bob-special (equal arg '(4)))
6173 ;; special case: use global cycling
6174 (setq arg t))
6176 (cond
6178 ((equal arg '(16))
6179 (setq last-command 'dummy)
6180 (org-set-startup-visibility)
6181 (message "Startup visibility, plus VISIBILITY properties"))
6183 ((equal arg '(64))
6184 (show-all)
6185 (message "Entire buffer visible, including drawers"))
6187 ;; Table: enter it or move to the next field.
6188 ((org-at-table-p 'any)
6189 (if (org-at-table.el-p)
6190 (message "Use C-c ' to edit table.el tables")
6191 (if arg (org-table-edit-field t)
6192 (org-table-justify-field-maybe)
6193 (call-interactively 'org-table-next-field))))
6195 ((run-hook-with-args-until-success
6196 'org-tab-after-check-for-table-hook))
6198 ;; Global cycling: delegate to `org-cycle-internal-global'.
6199 ((eq arg t) (org-cycle-internal-global))
6201 ;; Drawers: delegate to `org-flag-drawer'.
6202 ((and org-drawers org-drawer-regexp
6203 (save-excursion
6204 (beginning-of-line 1)
6205 (looking-at org-drawer-regexp)))
6206 (org-flag-drawer ; toggle block visibility
6207 (not (get-char-property (match-end 0) 'invisible))))
6209 ;; Show-subtree, ARG levels up from here.
6210 ((integerp arg)
6211 (save-excursion
6212 (org-back-to-heading)
6213 (outline-up-heading (if (< arg 0) (- arg)
6214 (- (funcall outline-level) arg)))
6215 (org-show-subtree)))
6217 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6218 ((and (featurep 'org-inlinetask)
6219 (org-inlinetask-at-task-p)
6220 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6221 (org-inlinetask-toggle-visibility))
6223 ((org-try-cdlatex-tab))
6225 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6226 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6227 (save-excursion (beginning-of-line 1)
6228 (looking-at org-outline-regexp)))
6229 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6230 (org-cycle-internal-local))
6232 ;; From there: TAB emulation and template completion.
6233 (buffer-read-only (org-back-to-heading))
6235 ((run-hook-with-args-until-success
6236 'org-tab-after-check-for-cycling-hook))
6238 ((org-try-structure-completion))
6240 ((run-hook-with-args-until-success
6241 'org-tab-before-tab-emulation-hook))
6243 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6244 (or (not (bolp))
6245 (not (looking-at org-outline-regexp))))
6246 (call-interactively (global-key-binding "\t")))
6248 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6249 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6250 (or (and (eq org-cycle-emulate-tab 'white)
6251 (= (match-end 0) (point-at-eol)))
6252 (and (eq org-cycle-emulate-tab 'whitestart)
6253 (>= (match-end 0) pos))))
6255 (eq org-cycle-emulate-tab t))
6256 (call-interactively (global-key-binding "\t")))
6258 (t (save-excursion
6259 (org-back-to-heading)
6260 (org-cycle)))))))
6262 (defun org-cycle-internal-global ()
6263 "Do the global cycling action."
6264 ;; Hack to avoid display of messages for .org attachments in Gnus
6265 (let ((ga (string-match "\\*fontification" (buffer-name))))
6266 (cond
6267 ((and (eq last-command this-command)
6268 (eq org-cycle-global-status 'overview))
6269 ;; We just created the overview - now do table of contents
6270 ;; This can be slow in very large buffers, so indicate action
6271 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6272 (unless ga (message "CONTENTS..."))
6273 (org-content)
6274 (unless ga (message "CONTENTS...done"))
6275 (setq org-cycle-global-status 'contents)
6276 (run-hook-with-args 'org-cycle-hook 'contents))
6278 ((and (eq last-command this-command)
6279 (eq org-cycle-global-status 'contents))
6280 ;; We just showed the table of contents - now show everything
6281 (run-hook-with-args 'org-pre-cycle-hook 'all)
6282 (show-all)
6283 (unless ga (message "SHOW ALL"))
6284 (setq org-cycle-global-status 'all)
6285 (run-hook-with-args 'org-cycle-hook 'all))
6288 ;; Default action: go to overview
6289 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6290 (org-overview)
6291 (unless ga (message "OVERVIEW"))
6292 (setq org-cycle-global-status 'overview)
6293 (run-hook-with-args 'org-cycle-hook 'overview)))))
6295 (defun org-cycle-internal-local ()
6296 "Do the local cycling action."
6297 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6298 ;; First, determine end of headline (EOH), end of subtree or item
6299 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6300 (save-excursion
6301 (if (org-at-item-p)
6302 (progn
6303 (beginning-of-line)
6304 (setq struct (org-list-struct))
6305 (setq eoh (point-at-eol))
6306 (setq eos (org-list-get-item-end-before-blank (point) struct))
6307 (setq has-children (org-list-has-child-p (point) struct)))
6308 (org-back-to-heading)
6309 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6310 (setq eos (save-excursion
6311 (org-end-of-subtree t)
6312 (unless (eobp)
6313 (skip-chars-forward " \t\n"))
6314 (if (eobp) (point) (1- (point)))))
6315 (setq has-children
6316 (or (save-excursion
6317 (let ((level (funcall outline-level)))
6318 (outline-next-heading)
6319 (and (org-at-heading-p t)
6320 (> (funcall outline-level) level))))
6321 (save-excursion
6322 (org-list-search-forward (org-item-beginning-re) eos t)))))
6323 ;; Determine end invisible part of buffer (EOL)
6324 (beginning-of-line 2)
6325 ;; XEmacs doesn't have `next-single-char-property-change'
6326 (if (featurep 'xemacs)
6327 (while (and (not (eobp)) ;; this is like `next-line'
6328 (get-char-property (1- (point)) 'invisible))
6329 (beginning-of-line 2))
6330 (while (and (not (eobp)) ;; this is like `next-line'
6331 (get-char-property (1- (point)) 'invisible))
6332 (goto-char (next-single-char-property-change (point) 'invisible))
6333 (and (eolp) (beginning-of-line 2))))
6334 (setq eol (point)))
6335 ;; Find out what to do next and set `this-command'
6336 (cond
6337 ((= eos eoh)
6338 ;; Nothing is hidden behind this heading
6339 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6340 (message "EMPTY ENTRY")
6341 (setq org-cycle-subtree-status nil)
6342 (save-excursion
6343 (goto-char eos)
6344 (outline-next-heading)
6345 (if (outline-invisible-p) (org-flag-heading nil))))
6346 ((and (or (>= eol eos)
6347 (not (string-match "\\S-" (buffer-substring eol eos))))
6348 (or has-children
6349 (not (setq children-skipped
6350 org-cycle-skip-children-state-if-no-children))))
6351 ;; Entire subtree is hidden in one line: children view
6352 (run-hook-with-args 'org-pre-cycle-hook 'children)
6353 (if (org-at-item-p)
6354 (org-list-set-item-visibility (point-at-bol) struct 'children)
6355 (org-show-entry)
6356 (org-with-limited-levels (show-children))
6357 ;; FIXME: This slows down the func way too much.
6358 ;; How keep drawers hidden in subtree anyway?
6359 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6360 ;; (org-cycle-hide-drawers 'subtree))
6362 ;; Fold every list in subtree to top-level items.
6363 (when (eq org-cycle-include-plain-lists 'integrate)
6364 (save-excursion
6365 (org-back-to-heading)
6366 (while (org-list-search-forward (org-item-beginning-re) eos t)
6367 (beginning-of-line 1)
6368 (let* ((struct (org-list-struct))
6369 (prevs (org-list-prevs-alist struct))
6370 (end (org-list-get-bottom-point struct)))
6371 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6372 (org-list-get-all-items (point) struct prevs))
6373 (goto-char end))))))
6374 (message "CHILDREN")
6375 (save-excursion
6376 (goto-char eos)
6377 (outline-next-heading)
6378 (if (outline-invisible-p) (org-flag-heading nil)))
6379 (setq org-cycle-subtree-status 'children)
6380 (run-hook-with-args 'org-cycle-hook 'children))
6381 ((or children-skipped
6382 (and (eq last-command this-command)
6383 (eq org-cycle-subtree-status 'children)))
6384 ;; We just showed the children, or no children are there,
6385 ;; now show everything.
6386 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6387 (outline-flag-region eoh eos nil)
6388 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6389 (setq org-cycle-subtree-status 'subtree)
6390 (run-hook-with-args 'org-cycle-hook 'subtree))
6392 ;; Default action: hide the subtree.
6393 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6394 (outline-flag-region eoh eos t)
6395 (message "FOLDED")
6396 (setq org-cycle-subtree-status 'folded)
6397 (run-hook-with-args 'org-cycle-hook 'folded)))))
6399 ;;;###autoload
6400 (defun org-global-cycle (&optional arg)
6401 "Cycle the global visibility. For details see `org-cycle'.
6402 With \\[universal-argument] prefix arg, switch to startup visibility.
6403 With a numeric prefix, show all headlines up to that level."
6404 (interactive "P")
6405 (let ((org-cycle-include-plain-lists
6406 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6407 (cond
6408 ((integerp arg)
6409 (show-all)
6410 (hide-sublevels arg)
6411 (setq org-cycle-global-status 'contents))
6412 ((equal arg '(4))
6413 (org-set-startup-visibility)
6414 (message "Startup visibility, plus VISIBILITY properties."))
6416 (org-cycle '(4))))))
6418 (defun org-set-startup-visibility ()
6419 "Set the visibility required by startup options and properties."
6420 (cond
6421 ((eq org-startup-folded t)
6422 (org-cycle '(4)))
6423 ((eq org-startup-folded 'content)
6424 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6425 (org-cycle '(4)) (org-cycle '(4)))))
6426 (unless (eq org-startup-folded 'showeverything)
6427 (if org-hide-block-startup (org-hide-block-all))
6428 (org-set-visibility-according-to-property 'no-cleanup)
6429 (org-cycle-hide-archived-subtrees 'all)
6430 (org-cycle-hide-drawers 'all)
6431 (org-cycle-show-empty-lines t)))
6433 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6434 "Switch subtree visibilities according to :VISIBILITY: property."
6435 (interactive)
6436 (let (org-show-entry-below state)
6437 (save-excursion
6438 (goto-char (point-min))
6439 (while (re-search-forward
6440 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6441 nil t)
6442 (setq state (match-string 1))
6443 (save-excursion
6444 (org-back-to-heading t)
6445 (hide-subtree)
6446 (org-reveal)
6447 (cond
6448 ((equal state '("fold" "folded"))
6449 (hide-subtree))
6450 ((equal state "children")
6451 (org-show-hidden-entry)
6452 (show-children))
6453 ((equal state "content")
6454 (save-excursion
6455 (save-restriction
6456 (org-narrow-to-subtree)
6457 (org-content))))
6458 ((member state '("all" "showall"))
6459 (show-subtree)))))
6460 (unless no-cleanup
6461 (org-cycle-hide-archived-subtrees 'all)
6462 (org-cycle-hide-drawers 'all)
6463 (org-cycle-show-empty-lines 'all)))))
6465 ;; This function uses outline-regexp instead of the more fundamental
6466 ;; org-outline-regexp so that org-cycle-global works outside of Org
6467 ;; buffers, where outline-regexp is needed.
6468 (defun org-overview ()
6469 "Switch to overview mode, showing only top-level headlines.
6470 Really, this shows all headlines with level equal or greater than the level
6471 of the first headline in the buffer. This is important, because if the
6472 first headline is not level one, then (hide-sublevels 1) gives confusing
6473 results."
6474 (interactive)
6475 (let ((level (save-excursion
6476 (goto-char (point-min))
6477 (if (re-search-forward (concat "^" outline-regexp) nil t)
6478 (progn
6479 (goto-char (match-beginning 0))
6480 (funcall outline-level))))))
6481 (and level (hide-sublevels level))))
6483 (defun org-content (&optional arg)
6484 "Show all headlines in the buffer, like a table of contents.
6485 With numerical argument N, show content up to level N."
6486 (interactive "P")
6487 (save-excursion
6488 ;; Visit all headings and show their offspring
6489 (and (integerp arg) (org-overview))
6490 (goto-char (point-max))
6491 (catch 'exit
6492 (while (and (progn (condition-case nil
6493 (outline-previous-visible-heading 1)
6494 (error (goto-char (point-min))))
6496 (looking-at org-outline-regexp))
6497 (if (integerp arg)
6498 (show-children (1- arg))
6499 (show-branches))
6500 (if (bobp) (throw 'exit nil))))))
6503 (defun org-optimize-window-after-visibility-change (state)
6504 "Adjust the window after a change in outline visibility.
6505 This function is the default value of the hook `org-cycle-hook'."
6506 (when (get-buffer-window (current-buffer))
6507 (cond
6508 ((eq state 'content) nil)
6509 ((eq state 'all) nil)
6510 ((eq state 'folded) nil)
6511 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6512 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6514 (defun org-remove-empty-overlays-at (pos)
6515 "Remove outline overlays that do not contain non-white stuff."
6516 (mapc
6517 (lambda (o)
6518 (and (eq 'outline (overlay-get o 'invisible))
6519 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6520 (overlay-end o))))
6521 (delete-overlay o)))
6522 (overlays-at pos)))
6524 (defun org-clean-visibility-after-subtree-move ()
6525 "Fix visibility issues after moving a subtree."
6526 ;; First, find a reasonable region to look at:
6527 ;; Start two siblings above, end three below
6528 (let* ((beg (save-excursion
6529 (and (org-get-last-sibling)
6530 (org-get-last-sibling))
6531 (point)))
6532 (end (save-excursion
6533 (and (org-get-next-sibling)
6534 (org-get-next-sibling)
6535 (org-get-next-sibling))
6536 (if (org-at-heading-p)
6537 (point-at-eol)
6538 (point))))
6539 (level (looking-at "\\*+"))
6540 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6541 (save-excursion
6542 (save-restriction
6543 (narrow-to-region beg end)
6544 (when re
6545 ;; Properly fold already folded siblings
6546 (goto-char (point-min))
6547 (while (re-search-forward re nil t)
6548 (if (and (not (outline-invisible-p))
6549 (save-excursion
6550 (goto-char (point-at-eol)) (outline-invisible-p)))
6551 (hide-entry))))
6552 (org-cycle-show-empty-lines 'overview)
6553 (org-cycle-hide-drawers 'overview)))))
6555 (defun org-cycle-show-empty-lines (state)
6556 "Show empty lines above all visible headlines.
6557 The region to be covered depends on STATE when called through
6558 `org-cycle-hook'. Lisp program can use t for STATE to get the
6559 entire buffer covered. Note that an empty line is only shown if there
6560 are at least `org-cycle-separator-lines' empty lines before the headline."
6561 (when (not (= org-cycle-separator-lines 0))
6562 (save-excursion
6563 (let* ((n (abs org-cycle-separator-lines))
6564 (re (cond
6565 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6566 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6567 (t (let ((ns (number-to-string (- n 2))))
6568 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6569 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6570 beg end b e)
6571 (cond
6572 ((memq state '(overview contents t))
6573 (setq beg (point-min) end (point-max)))
6574 ((memq state '(children folded))
6575 (setq beg (point) end (progn (org-end-of-subtree t t)
6576 (beginning-of-line 2)
6577 (point)))))
6578 (when beg
6579 (goto-char beg)
6580 (while (re-search-forward re end t)
6581 (unless (get-char-property (match-end 1) 'invisible)
6582 (setq e (match-end 1))
6583 (if (< org-cycle-separator-lines 0)
6584 (setq b (save-excursion
6585 (goto-char (match-beginning 0))
6586 (org-back-over-empty-lines)
6587 (if (save-excursion
6588 (goto-char (max (point-min) (1- (point))))
6589 (org-at-heading-p))
6590 (1- (point))
6591 (point))))
6592 (setq b (match-beginning 1)))
6593 (outline-flag-region b e nil)))))))
6594 ;; Never hide empty lines at the end of the file.
6595 (save-excursion
6596 (goto-char (point-max))
6597 (outline-previous-heading)
6598 (outline-end-of-heading)
6599 (if (and (looking-at "[ \t\n]+")
6600 (= (match-end 0) (point-max)))
6601 (outline-flag-region (point) (match-end 0) nil))))
6603 (defun org-show-empty-lines-in-parent ()
6604 "Move to the parent and re-show empty lines before visible headlines."
6605 (save-excursion
6606 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6607 (org-cycle-show-empty-lines context))))
6609 (defun org-files-list ()
6610 "Return `org-agenda-files' list, plus all open org-mode files.
6611 This is useful for operations that need to scan all of a user's
6612 open and agenda-wise Org files."
6613 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6614 (dolist (buf (buffer-list))
6615 (with-current-buffer buf
6616 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6617 (let ((file (expand-file-name (buffer-file-name))))
6618 (unless (member file files)
6619 (push file files))))))
6620 files))
6622 (defsubst org-entry-beginning-position ()
6623 "Return the beginning position of the current entry."
6624 (save-excursion (outline-back-to-heading t) (point)))
6626 (defsubst org-entry-end-position ()
6627 "Return the end position of the current entry."
6628 (save-excursion (outline-next-heading) (point)))
6630 (defun org-cycle-hide-drawers (state)
6631 "Re-hide all drawers after a visibility state change."
6632 (when (and (eq major-mode 'org-mode)
6633 (not (memq state '(overview folded contents))))
6634 (save-excursion
6635 (let* ((globalp (memq state '(contents all)))
6636 (beg (if globalp (point-min) (point)))
6637 (end (if globalp (point-max)
6638 (if (eq state 'children)
6639 (save-excursion (outline-next-heading) (point))
6640 (org-end-of-subtree t)))))
6641 (goto-char beg)
6642 (while (re-search-forward org-drawer-regexp end t)
6643 (org-flag-drawer t))))))
6645 (defun org-flag-drawer (flag)
6646 (save-excursion
6647 (beginning-of-line 1)
6648 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6649 (let ((b (match-end 0)))
6650 (if (re-search-forward
6651 "^[ \t]*:END:"
6652 (save-excursion (outline-next-heading) (point)) t)
6653 (outline-flag-region b (point-at-eol) flag)
6654 (error ":END: line missing at position %s" b))))))
6656 (defun org-subtree-end-visible-p ()
6657 "Is the end of the current subtree visible?"
6658 (pos-visible-in-window-p
6659 (save-excursion (org-end-of-subtree t) (point))))
6661 (defun org-first-headline-recenter (&optional N)
6662 "Move cursor to the first headline and recenter the headline.
6663 Optional argument N means put the headline into the Nth line of the window."
6664 (goto-char (point-min))
6665 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6666 (beginning-of-line)
6667 (recenter (prefix-numeric-value N))))
6669 ;;; Saving and restoring visibility
6671 (defun org-outline-overlay-data (&optional use-markers)
6672 "Return a list of the locations of all outline overlays.
6673 These are overlays with the `invisible' property value `outline'.
6674 The return value is a list of cons cells, with start and stop
6675 positions for each overlay.
6676 If USE-MARKERS is set, return the positions as markers."
6677 (let (beg end)
6678 (save-excursion
6679 (save-restriction
6680 (widen)
6681 (delq nil
6682 (mapcar (lambda (o)
6683 (when (eq (overlay-get o 'invisible) 'outline)
6684 (setq beg (overlay-start o)
6685 end (overlay-end o))
6686 (and beg end (> end beg)
6687 (if use-markers
6688 (cons (move-marker (make-marker) beg)
6689 (move-marker (make-marker) end))
6690 (cons beg end)))))
6691 (overlays-in (point-min) (point-max))))))))
6693 (defun org-set-outline-overlay-data (data)
6694 "Create visibility overlays for all positions in DATA.
6695 DATA should have been made by `org-outline-overlay-data'."
6696 (let (o)
6697 (save-excursion
6698 (save-restriction
6699 (widen)
6700 (show-all)
6701 (mapc (lambda (c)
6702 (outline-flag-region (car c) (cdr c) t))
6703 data)))))
6705 ;;; Folding of blocks
6707 (defvar org-hide-block-overlays nil
6708 "Overlays hiding blocks.")
6709 (make-variable-buffer-local 'org-hide-block-overlays)
6711 (defun org-block-map (function &optional start end)
6712 "Call FUNCTION at the head of all source blocks in the current buffer.
6713 Optional arguments START and END can be used to limit the range."
6714 (let ((start (or start (point-min)))
6715 (end (or end (point-max))))
6716 (save-excursion
6717 (goto-char start)
6718 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6719 (save-excursion
6720 (save-match-data
6721 (goto-char (match-beginning 0))
6722 (funcall function)))))))
6724 (defun org-hide-block-toggle-all ()
6725 "Toggle the visibility of all blocks in the current buffer."
6726 (org-block-map #'org-hide-block-toggle))
6728 (defun org-hide-block-all ()
6729 "Fold all blocks in the current buffer."
6730 (interactive)
6731 (org-show-block-all)
6732 (org-block-map #'org-hide-block-toggle-maybe))
6734 (defun org-show-block-all ()
6735 "Unfold all blocks in the current buffer."
6736 (interactive)
6737 (mapc 'delete-overlay org-hide-block-overlays)
6738 (setq org-hide-block-overlays nil))
6740 (defun org-hide-block-toggle-maybe ()
6741 "Toggle visibility of block at point."
6742 (interactive)
6743 (let ((case-fold-search t))
6744 (if (save-excursion
6745 (beginning-of-line 1)
6746 (looking-at org-block-regexp))
6747 (progn (org-hide-block-toggle)
6748 t) ;; to signal that we took action
6749 nil))) ;; to signal that we did not
6751 (defun org-hide-block-toggle (&optional force)
6752 "Toggle the visibility of the current block."
6753 (interactive)
6754 (save-excursion
6755 (beginning-of-line)
6756 (if (re-search-forward org-block-regexp nil t)
6757 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6758 (end (match-end 0)) ;; end of entire body
6760 (if (memq t (mapcar (lambda (overlay)
6761 (eq (overlay-get overlay 'invisible)
6762 'org-hide-block))
6763 (overlays-at start)))
6764 (if (or (not force) (eq force 'off))
6765 (mapc (lambda (ov)
6766 (when (member ov org-hide-block-overlays)
6767 (setq org-hide-block-overlays
6768 (delq ov org-hide-block-overlays)))
6769 (when (eq (overlay-get ov 'invisible)
6770 'org-hide-block)
6771 (delete-overlay ov)))
6772 (overlays-at start)))
6773 (setq ov (make-overlay start end))
6774 (overlay-put ov 'invisible 'org-hide-block)
6775 ;; make the block accessible to isearch
6776 (overlay-put
6777 ov 'isearch-open-invisible
6778 (lambda (ov)
6779 (when (member ov org-hide-block-overlays)
6780 (setq org-hide-block-overlays
6781 (delq ov org-hide-block-overlays)))
6782 (when (eq (overlay-get ov 'invisible)
6783 'org-hide-block)
6784 (delete-overlay ov))))
6785 (push ov org-hide-block-overlays)))
6786 (error "Not looking at a source block"))))
6788 ;; org-tab-after-check-for-cycling-hook
6789 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6790 ;; Remove overlays when changing major mode
6791 (add-hook 'org-mode-hook
6792 (lambda () (org-add-hook 'change-major-mode-hook
6793 'org-show-block-all 'append 'local)))
6795 ;;; Org-goto
6797 (defvar org-goto-window-configuration nil)
6798 (defvar org-goto-marker nil)
6799 (defvar org-goto-map
6800 (let ((map (make-sparse-keymap)))
6801 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6802 (while (setq cmd (pop cmds))
6803 (substitute-key-definition cmd cmd map global-map)))
6804 (suppress-keymap map)
6805 (org-defkey map "\C-m" 'org-goto-ret)
6806 (org-defkey map [(return)] 'org-goto-ret)
6807 (org-defkey map [(left)] 'org-goto-left)
6808 (org-defkey map [(right)] 'org-goto-right)
6809 (org-defkey map [(control ?g)] 'org-goto-quit)
6810 (org-defkey map "\C-i" 'org-cycle)
6811 (org-defkey map [(tab)] 'org-cycle)
6812 (org-defkey map [(down)] 'outline-next-visible-heading)
6813 (org-defkey map [(up)] 'outline-previous-visible-heading)
6814 (if org-goto-auto-isearch
6815 (if (fboundp 'define-key-after)
6816 (define-key-after map [t] 'org-goto-local-auto-isearch)
6817 nil)
6818 (org-defkey map "q" 'org-goto-quit)
6819 (org-defkey map "n" 'outline-next-visible-heading)
6820 (org-defkey map "p" 'outline-previous-visible-heading)
6821 (org-defkey map "f" 'outline-forward-same-level)
6822 (org-defkey map "b" 'outline-backward-same-level)
6823 (org-defkey map "u" 'outline-up-heading))
6824 (org-defkey map "/" 'org-occur)
6825 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6826 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6827 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6828 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6829 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6830 map))
6832 (defconst org-goto-help
6833 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6834 RET=jump to location [Q]uit and return to previous location
6835 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6837 (defvar org-goto-start-pos) ; dynamically scoped parameter
6839 ;; FIXME: Docstring does not mention both interfaces
6840 (defun org-goto (&optional alternative-interface)
6841 "Look up a different location in the current file, keeping current visibility.
6843 When you want look-up or go to a different location in a document, the
6844 fastest way is often to fold the entire buffer and then dive into the tree.
6845 This method has the disadvantage, that the previous location will be folded,
6846 which may not be what you want.
6848 This command works around this by showing a copy of the current buffer
6849 in an indirect buffer, in overview mode. You can dive into the tree in
6850 that copy, use org-occur and incremental search to find a location.
6851 When pressing RET or `Q', the command returns to the original buffer in
6852 which the visibility is still unchanged. After RET it will also jump to
6853 the location selected in the indirect buffer and expose the headline
6854 hierarchy above."
6855 (interactive "P")
6856 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6857 (org-refile-use-outline-path t)
6858 (org-refile-target-verify-function nil)
6859 (interface
6860 (if (not alternative-interface)
6861 org-goto-interface
6862 (if (eq org-goto-interface 'outline)
6863 'outline-path-completion
6864 'outline)))
6865 (org-goto-start-pos (point))
6866 (selected-point
6867 (if (eq interface 'outline)
6868 (car (org-get-location (current-buffer) org-goto-help))
6869 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6870 (org-refile-check-position pa)
6871 (nth 3 pa)))))
6872 (if selected-point
6873 (progn
6874 (org-mark-ring-push org-goto-start-pos)
6875 (goto-char selected-point)
6876 (if (or (outline-invisible-p) (org-invisible-p2))
6877 (org-show-context 'org-goto)))
6878 (message "Quit"))))
6880 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6881 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6882 (defvar org-goto-local-auto-isearch-map) ; defined below
6884 (defun org-get-location (buf help)
6885 "Let the user select a location in the Org-mode buffer BUF.
6886 This function uses a recursive edit. It returns the selected position
6887 or nil."
6888 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6889 (isearch-hide-immediately nil)
6890 (isearch-search-fun-function
6891 (lambda () 'org-goto-local-search-headings))
6892 (org-goto-selected-point org-goto-exit-command)
6893 (pop-up-frames nil)
6894 (special-display-buffer-names nil)
6895 (special-display-regexps nil)
6896 (special-display-function nil))
6897 (save-excursion
6898 (save-window-excursion
6899 (delete-other-windows)
6900 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6901 (org-pop-to-buffer-same-window
6902 (condition-case nil
6903 (make-indirect-buffer (current-buffer) "*org-goto*")
6904 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6905 (with-output-to-temp-buffer "*Help*"
6906 (princ help))
6907 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6908 (setq buffer-read-only nil)
6909 (let ((org-startup-truncated t)
6910 (org-startup-folded nil)
6911 (org-startup-align-all-tables nil))
6912 (org-mode)
6913 (org-overview))
6914 (setq buffer-read-only t)
6915 (if (and (boundp 'org-goto-start-pos)
6916 (integer-or-marker-p org-goto-start-pos))
6917 (let ((org-show-hierarchy-above t)
6918 (org-show-siblings t)
6919 (org-show-following-heading t))
6920 (goto-char org-goto-start-pos)
6921 (and (outline-invisible-p) (org-show-context)))
6922 (goto-char (point-min)))
6923 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6924 (message "Select location and press RET")
6925 (use-local-map org-goto-map)
6926 (recursive-edit)
6928 (kill-buffer "*org-goto*")
6929 (cons org-goto-selected-point org-goto-exit-command)))
6931 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6932 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6933 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6934 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6936 (defun org-goto-local-search-headings (string bound noerror)
6937 "Search and make sure that any matches are in headlines."
6938 (catch 'return
6939 (while (if isearch-forward
6940 (search-forward string bound noerror)
6941 (search-backward string bound noerror))
6942 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6943 (and (member :headline context)
6944 (not (member :tags context))))
6945 (throw 'return (point))))))
6947 (defun org-goto-local-auto-isearch ()
6948 "Start isearch."
6949 (interactive)
6950 (goto-char (point-min))
6951 (let ((keys (this-command-keys)))
6952 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6953 (isearch-mode t)
6954 (isearch-process-search-char (string-to-char keys)))))
6956 (defun org-goto-ret (&optional arg)
6957 "Finish `org-goto' by going to the new location."
6958 (interactive "P")
6959 (setq org-goto-selected-point (point)
6960 org-goto-exit-command 'return)
6961 (throw 'exit nil))
6963 (defun org-goto-left ()
6964 "Finish `org-goto' by going to the new location."
6965 (interactive)
6966 (if (org-at-heading-p)
6967 (progn
6968 (beginning-of-line 1)
6969 (setq org-goto-selected-point (point)
6970 org-goto-exit-command 'left)
6971 (throw 'exit nil))
6972 (error "Not on a heading")))
6974 (defun org-goto-right ()
6975 "Finish `org-goto' by going to the new location."
6976 (interactive)
6977 (if (org-at-heading-p)
6978 (progn
6979 (setq org-goto-selected-point (point)
6980 org-goto-exit-command 'right)
6981 (throw 'exit nil))
6982 (error "Not on a heading")))
6984 (defun org-goto-quit ()
6985 "Finish `org-goto' without cursor motion."
6986 (interactive)
6987 (setq org-goto-selected-point nil)
6988 (setq org-goto-exit-command 'quit)
6989 (throw 'exit nil))
6991 ;;; Indirect buffer display of subtrees
6993 (defvar org-indirect-dedicated-frame nil
6994 "This is the frame being used for indirect tree display.")
6995 (defvar org-last-indirect-buffer nil)
6997 (defun org-tree-to-indirect-buffer (&optional arg)
6998 "Create indirect buffer and narrow it to current subtree.
6999 With numerical prefix ARG, go up to this level and then take that tree.
7000 If ARG is negative, go up that many levels.
7001 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7002 indirect buffer previously made with this command, to avoid proliferation of
7003 indirect buffers. However, when you call the command with a \
7004 \\[universal-argument] prefix, or
7005 when `org-indirect-buffer-display' is `new-frame', the last buffer
7006 is kept so that you can work with several indirect buffers at the same time.
7007 If `org-indirect-buffer-display' is `dedicated-frame', the \
7008 \\[universal-argument] prefix also
7009 requests that a new frame be made for the new buffer, so that the dedicated
7010 frame is not changed."
7011 (interactive "P")
7012 (let ((cbuf (current-buffer))
7013 (cwin (selected-window))
7014 (pos (point))
7015 beg end level heading ibuf)
7016 (save-excursion
7017 (org-back-to-heading t)
7018 (when (numberp arg)
7019 (setq level (org-outline-level))
7020 (if (< arg 0) (setq arg (+ level arg)))
7021 (while (> (setq level (org-outline-level)) arg)
7022 (outline-up-heading 1 t)))
7023 (setq beg (point)
7024 heading (org-get-heading))
7025 (org-end-of-subtree t t)
7026 (if (org-at-heading-p) (backward-char 1))
7027 (setq end (point)))
7028 (if (and (buffer-live-p org-last-indirect-buffer)
7029 (not (eq org-indirect-buffer-display 'new-frame))
7030 (not arg))
7031 (kill-buffer org-last-indirect-buffer))
7032 (setq ibuf (org-get-indirect-buffer cbuf)
7033 org-last-indirect-buffer ibuf)
7034 (cond
7035 ((or (eq org-indirect-buffer-display 'new-frame)
7036 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7037 (select-frame (make-frame))
7038 (delete-other-windows)
7039 (org-pop-to-buffer-same-window ibuf)
7040 (org-set-frame-title heading))
7041 ((eq org-indirect-buffer-display 'dedicated-frame)
7042 (raise-frame
7043 (select-frame (or (and org-indirect-dedicated-frame
7044 (frame-live-p org-indirect-dedicated-frame)
7045 org-indirect-dedicated-frame)
7046 (setq org-indirect-dedicated-frame (make-frame)))))
7047 (delete-other-windows)
7048 (org-pop-to-buffer-same-window ibuf)
7049 (org-set-frame-title (concat "Indirect: " heading)))
7050 ((eq org-indirect-buffer-display 'current-window)
7051 (org-pop-to-buffer-same-window ibuf))
7052 ((eq org-indirect-buffer-display 'other-window)
7053 (pop-to-buffer ibuf))
7054 (t (error "Invalid value")))
7055 (if (featurep 'xemacs)
7056 (save-excursion (org-mode) (turn-on-font-lock)))
7057 (narrow-to-region beg end)
7058 (show-all)
7059 (goto-char pos)
7060 (run-hook-with-args 'org-cycle-hook 'all)
7061 (and (window-live-p cwin) (select-window cwin))))
7063 (defun org-get-indirect-buffer (&optional buffer)
7064 (setq buffer (or buffer (current-buffer)))
7065 (let ((n 1) (base (buffer-name buffer)) bname)
7066 (while (buffer-live-p
7067 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7068 (setq n (1+ n)))
7069 (condition-case nil
7070 (make-indirect-buffer buffer bname 'clone)
7071 (error (make-indirect-buffer buffer bname)))))
7073 (defun org-set-frame-title (title)
7074 "Set the title of the current frame to the string TITLE."
7075 ;; FIXME: how to name a single frame in XEmacs???
7076 (unless (featurep 'xemacs)
7077 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7079 ;;;; Structure editing
7081 ;;; Inserting headlines
7083 (defun org-previous-line-empty-p ()
7084 (save-excursion
7085 (and (not (bobp))
7086 (or (beginning-of-line 0) t)
7087 (save-match-data
7088 (looking-at "[ \t]*$")))))
7090 (defun org-insert-heading (&optional force-heading invisible-ok)
7091 "Insert a new heading or item with same depth at point.
7092 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7093 If point is at the beginning of a headline, insert a sibling before the
7094 current headline. If point is not at the beginning, split the line,
7095 create the new headline with the text in the current line after point
7096 \(but see also the variable `org-M-RET-may-split-line').
7098 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7099 This is important for non-interactive uses of the command."
7100 (interactive "P")
7101 (if (or (= (buffer-size) 0)
7102 (and (not (save-excursion
7103 (and (ignore-errors (org-back-to-heading invisible-ok))
7104 (org-at-heading-p))))
7105 (or force-heading (not (org-in-item-p)))))
7106 (progn
7107 (insert "\n* ")
7108 (run-hooks 'org-insert-heading-hook))
7109 (when (or force-heading (not (org-insert-item)))
7110 (let* ((empty-line-p nil)
7111 (level nil)
7112 (on-heading (org-at-heading-p))
7113 (head (save-excursion
7114 (condition-case nil
7115 (progn
7116 (org-back-to-heading invisible-ok)
7117 (when (and (not on-heading)
7118 (featurep 'org-inlinetask)
7119 (integerp org-inlinetask-min-level)
7120 (>= (length (match-string 0))
7121 org-inlinetask-min-level))
7122 ;; Find a heading level before the inline task
7123 (while (and (setq level (org-up-heading-safe))
7124 (>= level org-inlinetask-min-level)))
7125 (if (org-at-heading-p)
7126 (org-back-to-heading invisible-ok)
7127 (error "This should not happen")))
7128 (setq empty-line-p (org-previous-line-empty-p))
7129 (match-string 0))
7130 (error "*"))))
7131 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7132 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7133 pos hide-previous previous-pos)
7134 (cond
7135 ((and (org-at-heading-p) (bolp)
7136 (or (bobp)
7137 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7138 ;; insert before the current line
7139 (open-line (if blank 2 1)))
7140 ((and (bolp)
7141 (not org-insert-heading-respect-content)
7142 (or (bobp)
7143 (save-excursion
7144 (backward-char 1) (not (outline-invisible-p)))))
7145 ;; insert right here
7146 nil)
7148 ;; somewhere in the line
7149 (save-excursion
7150 (setq previous-pos (point-at-bol))
7151 (end-of-line)
7152 (setq hide-previous (outline-invisible-p)))
7153 (and org-insert-heading-respect-content (org-show-subtree))
7154 (let ((split
7155 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7156 (save-excursion
7157 (let ((p (point)))
7158 (goto-char (point-at-bol))
7159 (and (looking-at org-complex-heading-regexp)
7160 (match-beginning 4)
7161 (> p (match-beginning 4)))))))
7162 tags pos)
7163 (cond
7164 (org-insert-heading-respect-content
7165 (org-end-of-subtree nil t)
7166 (when (featurep 'org-inlinetask)
7167 (while (and (not (eobp))
7168 (looking-at "\\(\\*+\\)[ \t]+")
7169 (>= (length (match-string 1))
7170 org-inlinetask-min-level))
7171 (org-end-of-subtree nil t)))
7172 (or (bolp) (newline))
7173 (or (org-previous-line-empty-p)
7174 (and blank (newline)))
7175 (open-line 1))
7176 ((org-at-heading-p)
7177 (when hide-previous
7178 (show-children)
7179 (org-show-entry))
7180 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7181 (setq tags (and (match-end 2) (match-string 2)))
7182 (and (match-end 1)
7183 (delete-region (match-beginning 1) (match-end 1)))
7184 (setq pos (point-at-bol))
7185 (or split (end-of-line 1))
7186 (delete-horizontal-space)
7187 (if (string-match "\\`\\*+\\'"
7188 (buffer-substring (point-at-bol) (point)))
7189 (insert " "))
7190 (newline (if blank 2 1))
7191 (when tags
7192 (save-excursion
7193 (goto-char pos)
7194 (end-of-line 1)
7195 (insert " " tags)
7196 (org-set-tags nil 'align))))
7198 (or split (end-of-line 1))
7199 (newline (if blank 2 1)))))))
7200 (insert head) (just-one-space)
7201 (setq pos (point))
7202 (end-of-line 1)
7203 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7204 (when (and org-insert-heading-respect-content hide-previous)
7205 (save-excursion
7206 (goto-char previous-pos)
7207 (hide-subtree)))
7208 (run-hooks 'org-insert-heading-hook)))))
7210 (defun org-get-heading (&optional no-tags no-todo)
7211 "Return the heading of the current entry, without the stars.
7212 When NO-TAGS is non-nil, don't include tags.
7213 When NO-TODO is non-nil, don't include TODO keywords."
7214 (save-excursion
7215 (org-back-to-heading t)
7216 (cond
7217 ((and no-tags no-todo)
7218 (looking-at org-complex-heading-regexp)
7219 (match-string 4))
7220 (no-tags
7221 (looking-at (concat org-outline-regexp
7222 "\\(.*?\\)"
7223 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7224 (match-string 1))
7225 (no-todo
7226 (looking-at org-todo-line-regexp)
7227 (match-string 3))
7228 (t (looking-at org-heading-regexp)
7229 (match-string 2)))))
7231 (defun org-heading-components ()
7232 "Return the components of the current heading.
7233 This is a list with the following elements:
7234 - the level as an integer
7235 - the reduced level, different if `org-odd-levels-only' is set.
7236 - the TODO keyword, or nil
7237 - the priority character, like ?A, or nil if no priority is given
7238 - the headline text itself, or the tags string if no headline text
7239 - the tags string, or nil."
7240 (save-excursion
7241 (org-back-to-heading t)
7242 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7243 (list (length (match-string 1))
7244 (org-reduced-level (length (match-string 1)))
7245 (org-match-string-no-properties 2)
7246 (and (match-end 3) (aref (match-string 3) 2))
7247 (org-match-string-no-properties 4)
7248 (org-match-string-no-properties 5)))))
7250 (defun org-get-entry ()
7251 "Get the entry text, after heading, entire subtree."
7252 (save-excursion
7253 (org-back-to-heading t)
7254 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7256 (defun org-insert-heading-after-current ()
7257 "Insert a new heading with same level as current, after current subtree."
7258 (interactive)
7259 (org-back-to-heading)
7260 (org-insert-heading)
7261 (org-move-subtree-down)
7262 (end-of-line 1))
7264 (defun org-insert-heading-respect-content ()
7265 (interactive)
7266 (let ((org-insert-heading-respect-content t))
7267 (org-insert-heading t)))
7269 (defun org-insert-todo-heading-respect-content (&optional force-state)
7270 (interactive "P")
7271 (let ((org-insert-heading-respect-content t))
7272 (org-insert-todo-heading force-state t)))
7274 (defun org-insert-todo-heading (arg &optional force-heading)
7275 "Insert a new heading with the same level and TODO state as current heading.
7276 If the heading has no TODO state, or if the state is DONE, use the first
7277 state (TODO by default). Also with prefix arg, force first state."
7278 (interactive "P")
7279 (when (or force-heading (not (org-insert-item 'checkbox)))
7280 (org-insert-heading force-heading)
7281 (save-excursion
7282 (org-back-to-heading)
7283 (outline-previous-heading)
7284 (looking-at org-todo-line-regexp))
7285 (let*
7286 ((new-mark-x
7287 (if (or arg
7288 (not (match-beginning 2))
7289 (member (match-string 2) org-done-keywords))
7290 (car org-todo-keywords-1)
7291 (match-string 2)))
7292 (new-mark
7294 (run-hook-with-args-until-success
7295 'org-todo-get-default-hook new-mark-x nil)
7296 new-mark-x)))
7297 (beginning-of-line 1)
7298 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7299 (if org-treat-insert-todo-heading-as-state-change
7300 (org-todo new-mark)
7301 (insert new-mark " "))))
7302 (when org-provide-todo-statistics
7303 (org-update-parent-todo-statistics))))
7305 (defun org-insert-subheading (arg)
7306 "Insert a new subheading and demote it.
7307 Works for outline headings and for plain lists alike."
7308 (interactive "P")
7309 (org-insert-heading arg)
7310 (cond
7311 ((org-at-heading-p) (org-do-demote))
7312 ((org-at-item-p) (org-indent-item))))
7314 (defun org-insert-todo-subheading (arg)
7315 "Insert a new subheading with TODO keyword or checkbox and demote it.
7316 Works for outline headings and for plain lists alike."
7317 (interactive "P")
7318 (org-insert-todo-heading arg)
7319 (cond
7320 ((org-at-heading-p) (org-do-demote))
7321 ((org-at-item-p) (org-indent-item))))
7323 ;;; Promotion and Demotion
7325 (defvar org-after-demote-entry-hook nil
7326 "Hook run after an entry has been demoted.
7327 The cursor will be at the beginning of the entry.
7328 When a subtree is being demoted, the hook will be called for each node.")
7330 (defvar org-after-promote-entry-hook nil
7331 "Hook run after an entry has been promoted.
7332 The cursor will be at the beginning of the entry.
7333 When a subtree is being promoted, the hook will be called for each node.")
7335 (defun org-promote-subtree ()
7336 "Promote the entire subtree.
7337 See also `org-promote'."
7338 (interactive)
7339 (save-excursion
7340 (org-with-limited-levels (org-map-tree 'org-promote)))
7341 (org-fix-position-after-promote))
7343 (defun org-demote-subtree ()
7344 "Demote the entire subtree. See `org-demote'.
7345 See also `org-promote'."
7346 (interactive)
7347 (save-excursion
7348 (org-with-limited-levels (org-map-tree 'org-demote)))
7349 (org-fix-position-after-promote))
7352 (defun org-do-promote ()
7353 "Promote the current heading higher up the tree.
7354 If the region is active in `transient-mark-mode', promote all headings
7355 in the region."
7356 (interactive)
7357 (save-excursion
7358 (if (org-region-active-p)
7359 (org-map-region 'org-promote (region-beginning) (region-end))
7360 (org-promote)))
7361 (org-fix-position-after-promote))
7363 (defun org-do-demote ()
7364 "Demote the current heading lower down the tree.
7365 If the region is active in `transient-mark-mode', demote all headings
7366 in the region."
7367 (interactive)
7368 (save-excursion
7369 (if (org-region-active-p)
7370 (org-map-region 'org-demote (region-beginning) (region-end))
7371 (org-demote)))
7372 (org-fix-position-after-promote))
7374 (defun org-fix-position-after-promote ()
7375 "Make sure that after pro/demotion cursor position is right."
7376 (let ((pos (point)))
7377 (when (save-excursion
7378 (beginning-of-line 1)
7379 (looking-at org-todo-line-regexp)
7380 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7381 (cond ((eobp) (insert " "))
7382 ((eolp) (insert " "))
7383 ((equal (char-after) ?\ ) (forward-char 1))))))
7385 (defun org-current-level ()
7386 "Return the level of the current entry, or nil if before the first headline.
7387 The level is the number of stars at the beginning of the headline."
7388 (save-excursion
7389 (org-with-limited-levels
7390 (if (ignore-errors (org-back-to-heading t))
7391 (funcall outline-level)))))
7393 (defun org-get-previous-line-level ()
7394 "Return the outline depth of the last headline before the current line.
7395 Returns 0 for the first headline in the buffer, and nil if before the
7396 first headline."
7397 (let ((current-level (org-current-level))
7398 (prev-level (when (> (line-number-at-pos) 1)
7399 (save-excursion
7400 (beginning-of-line 0)
7401 (org-current-level)))))
7402 (cond ((null current-level) nil) ; Before first headline
7403 ((null prev-level) 0) ; At first headline
7404 (prev-level))))
7406 (defun org-reduced-level (l)
7407 "Compute the effective level of a heading.
7408 This takes into account the setting of `org-odd-levels-only'."
7409 (cond
7410 ((zerop l) 0)
7411 (org-odd-levels-only (1+ (floor (/ l 2))))
7412 (t l)))
7414 (defun org-level-increment ()
7415 "Return the number of stars that will be added or removed at a
7416 time to headlines when structure editing, based on the value of
7417 `org-odd-levels-only'."
7418 (if org-odd-levels-only 2 1))
7420 (defun org-get-valid-level (level &optional change)
7421 "Rectify a level change under the influence of `org-odd-levels-only'
7422 LEVEL is a current level, CHANGE is by how much the level should be
7423 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7424 even level numbers will become the next higher odd number."
7425 (if org-odd-levels-only
7426 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7427 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7428 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7429 (max 1 (+ level (or change 0)))))
7431 (if (boundp 'define-obsolete-function-alias)
7432 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7433 (define-obsolete-function-alias 'org-get-legal-level
7434 'org-get-valid-level)
7435 (define-obsolete-function-alias 'org-get-legal-level
7436 'org-get-valid-level "23.1")))
7438 (defun org-promote ()
7439 "Promote the current heading higher up the tree.
7440 If the region is active in `transient-mark-mode', promote all headings
7441 in the region."
7442 (org-back-to-heading t)
7443 (let* ((level (save-match-data (funcall outline-level)))
7444 (after-change-functions (remove 'flyspell-after-change-function
7445 after-change-functions))
7446 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7447 (diff (abs (- level (length up-head) -1))))
7448 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7449 (replace-match up-head nil t)
7450 ;; Fixup tag positioning
7451 (and org-auto-align-tags (org-set-tags nil t))
7452 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7453 (run-hooks 'org-after-promote-entry-hook)))
7455 (defun org-demote ()
7456 "Demote the current heading lower down the tree.
7457 If the region is active in `transient-mark-mode', demote all headings
7458 in the region."
7459 (org-back-to-heading t)
7460 (let* ((level (save-match-data (funcall outline-level)))
7461 (after-change-functions (remove 'flyspell-after-change-function
7462 after-change-functions))
7463 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7464 (diff (abs (- level (length down-head) -1))))
7465 (replace-match down-head nil t)
7466 ;; Fixup tag positioning
7467 (and org-auto-align-tags (org-set-tags nil t))
7468 (if org-adapt-indentation (org-fixup-indentation diff))
7469 (run-hooks 'org-after-demote-entry-hook)))
7471 (defun org-cycle-level ()
7472 "Cycle the level of an empty headline through possible states.
7473 This goes first to child, then to parent, level, then up the hierarchy.
7474 After top level, it switches back to sibling level."
7475 (interactive)
7476 (let ((org-adapt-indentation nil))
7477 (when (org-point-at-end-of-empty-headline)
7478 (setq this-command 'org-cycle-level) ; Only needed for caching
7479 (let ((cur-level (org-current-level))
7480 (prev-level (org-get-previous-line-level)))
7481 (cond
7482 ;; If first headline in file, promote to top-level.
7483 ((= prev-level 0)
7484 (loop repeat (/ (- cur-level 1) (org-level-increment))
7485 do (org-do-promote)))
7486 ;; If same level as prev, demote one.
7487 ((= prev-level cur-level)
7488 (org-do-demote))
7489 ;; If parent is top-level, promote to top level if not already.
7490 ((= prev-level 1)
7491 (loop repeat (/ (- cur-level 1) (org-level-increment))
7492 do (org-do-promote)))
7493 ;; If top-level, return to prev-level.
7494 ((= cur-level 1)
7495 (loop repeat (/ (- prev-level 1) (org-level-increment))
7496 do (org-do-demote)))
7497 ;; If less than prev-level, promote one.
7498 ((< cur-level prev-level)
7499 (org-do-promote))
7500 ;; If deeper than prev-level, promote until higher than
7501 ;; prev-level.
7502 ((> cur-level prev-level)
7503 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7504 do (org-do-promote))))
7505 t))))
7507 (defun org-map-tree (fun)
7508 "Call FUN for every heading underneath the current one."
7509 (org-back-to-heading)
7510 (let ((level (funcall outline-level)))
7511 (save-excursion
7512 (funcall fun)
7513 (while (and (progn
7514 (outline-next-heading)
7515 (> (funcall outline-level) level))
7516 (not (eobp)))
7517 (funcall fun)))))
7519 (defun org-map-region (fun beg end)
7520 "Call FUN for every heading between BEG and END."
7521 (let ((org-ignore-region t))
7522 (save-excursion
7523 (setq end (copy-marker end))
7524 (goto-char beg)
7525 (if (and (re-search-forward org-outline-regexp-bol nil t)
7526 (< (point) end))
7527 (funcall fun))
7528 (while (and (progn
7529 (outline-next-heading)
7530 (< (point) end))
7531 (not (eobp)))
7532 (funcall fun)))))
7534 (defvar org-property-end-re) ; silence byte-compiler
7535 (defun org-fixup-indentation (diff)
7536 "Change the indentation in the current entry by DIFF.
7537 However, if any line in the current entry has no indentation, or if it
7538 would end up with no indentation after the change, nothing at all is done."
7539 (save-excursion
7540 (let ((end (save-excursion (outline-next-heading)
7541 (point-marker)))
7542 (prohibit (if (> diff 0)
7543 "^\\S-"
7544 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7545 col)
7546 (unless (save-excursion (end-of-line 1)
7547 (re-search-forward prohibit end t))
7548 (while (and (< (point) end)
7549 (re-search-forward "^[ \t]+" end t))
7550 (goto-char (match-end 0))
7551 (setq col (current-column))
7552 (if (< diff 0) (replace-match ""))
7553 (org-indent-to-column (+ diff col))))
7554 (move-marker end nil))))
7556 (defun org-convert-to-odd-levels ()
7557 "Convert an org-mode file with all levels allowed to one with odd levels.
7558 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7559 level 5 etc."
7560 (interactive)
7561 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7562 (let ((outline-level 'org-outline-level)
7563 (org-odd-levels-only nil) n)
7564 (save-excursion
7565 (goto-char (point-min))
7566 (while (re-search-forward "^\\*\\*+ " nil t)
7567 (setq n (- (length (match-string 0)) 2))
7568 (while (>= (setq n (1- n)) 0)
7569 (org-demote))
7570 (end-of-line 1))))))
7572 (defun org-convert-to-oddeven-levels ()
7573 "Convert an org-mode file with only odd levels to one with odd/even levels.
7574 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7575 file contains a section with an even level, conversion would
7576 destroy the structure of the file. An error is signaled in this
7577 case."
7578 (interactive)
7579 (goto-char (point-min))
7580 ;; First check if there are no even levels
7581 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7582 (org-show-context t)
7583 (error "Not all levels are odd in this file. Conversion not possible"))
7584 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7585 (let ((outline-regexp org-outline-regexp)
7586 (outline-level 'org-outline-level)
7587 (org-odd-levels-only nil) n)
7588 (save-excursion
7589 (goto-char (point-min))
7590 (while (re-search-forward "^\\*\\*+ " nil t)
7591 (setq n (/ (1- (length (match-string 0))) 2))
7592 (while (>= (setq n (1- n)) 0)
7593 (org-promote))
7594 (end-of-line 1))))))
7596 (defun org-tr-level (n)
7597 "Make N odd if required."
7598 (if org-odd-levels-only (1+ (/ n 2)) n))
7600 ;;; Vertical tree motion, cutting and pasting of subtrees
7602 (defun org-move-subtree-up (&optional arg)
7603 "Move the current subtree up past ARG headlines of the same level."
7604 (interactive "p")
7605 (org-move-subtree-down (- (prefix-numeric-value arg))))
7607 (defun org-move-subtree-down (&optional arg)
7608 "Move the current subtree down past ARG headlines of the same level."
7609 (interactive "p")
7610 (setq arg (prefix-numeric-value arg))
7611 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7612 'org-get-last-sibling))
7613 (ins-point (make-marker))
7614 (cnt (abs arg))
7615 (col (current-column))
7616 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7617 ;; Select the tree
7618 (org-back-to-heading)
7619 (setq beg0 (point))
7620 (save-excursion
7621 (setq ne-beg (org-back-over-empty-lines))
7622 (setq beg (point)))
7623 (save-match-data
7624 (save-excursion (outline-end-of-heading)
7625 (setq folded (outline-invisible-p)))
7626 (outline-end-of-subtree))
7627 (outline-next-heading)
7628 (setq ne-end (org-back-over-empty-lines))
7629 (setq end (point))
7630 (goto-char beg0)
7631 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7632 ;; include less whitespace
7633 (save-excursion
7634 (goto-char beg)
7635 (forward-line (- ne-beg ne-end))
7636 (setq beg (point))))
7637 ;; Find insertion point, with error handling
7638 (while (> cnt 0)
7639 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7640 (progn (goto-char beg0)
7641 (error "Cannot move past superior level or buffer limit")))
7642 (setq cnt (1- cnt)))
7643 (if (> arg 0)
7644 ;; Moving forward - still need to move over subtree
7645 (progn (org-end-of-subtree t t)
7646 (save-excursion
7647 (org-back-over-empty-lines)
7648 (or (bolp) (newline)))))
7649 (setq ne-ins (org-back-over-empty-lines))
7650 (move-marker ins-point (point))
7651 (setq txt (buffer-substring beg end))
7652 (org-save-markers-in-region beg end)
7653 (delete-region beg end)
7654 (org-remove-empty-overlays-at beg)
7655 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7656 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7657 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7658 (let ((bbb (point)))
7659 (insert-before-markers txt)
7660 (org-reinstall-markers-in-region bbb)
7661 (move-marker ins-point bbb))
7662 (or (bolp) (insert "\n"))
7663 (setq ins-end (point))
7664 (goto-char ins-point)
7665 (org-skip-whitespace)
7666 (when (and (< arg 0)
7667 (org-first-sibling-p)
7668 (> ne-ins ne-beg))
7669 ;; Move whitespace back to beginning
7670 (save-excursion
7671 (goto-char ins-end)
7672 (let ((kill-whole-line t))
7673 (kill-line (- ne-ins ne-beg)) (point)))
7674 (insert (make-string (- ne-ins ne-beg) ?\n)))
7675 (move-marker ins-point nil)
7676 (if folded
7677 (hide-subtree)
7678 (org-show-entry)
7679 (show-children)
7680 (org-cycle-hide-drawers 'children))
7681 (org-clean-visibility-after-subtree-move)
7682 ;; move back to the initial column we were at
7683 (move-to-column col)))
7685 (defvar org-subtree-clip ""
7686 "Clipboard for cut and paste of subtrees.
7687 This is actually only a copy of the kill, because we use the normal kill
7688 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7690 (defvar org-subtree-clip-folded nil
7691 "Was the last copied subtree folded?
7692 This is used to fold the tree back after pasting.")
7694 (defun org-cut-subtree (&optional n)
7695 "Cut the current subtree into the clipboard.
7696 With prefix arg N, cut this many sequential subtrees.
7697 This is a short-hand for marking the subtree and then cutting it."
7698 (interactive "p")
7699 (org-copy-subtree n 'cut))
7701 (defun org-copy-subtree (&optional n cut force-store-markers)
7702 "Cut the current subtree into the clipboard.
7703 With prefix arg N, cut this many sequential subtrees.
7704 This is a short-hand for marking the subtree and then copying it.
7705 If CUT is non-nil, actually cut the subtree.
7706 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7707 of some markers in the region, even if CUT is non-nil. This is
7708 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7709 (interactive "p")
7710 (let (beg end folded (beg0 (point)))
7711 (if (org-called-interactively-p 'any)
7712 (org-back-to-heading nil) ; take what looks like a subtree
7713 (org-back-to-heading t)) ; take what is really there
7714 (org-back-over-empty-lines)
7715 (setq beg (point))
7716 (skip-chars-forward " \t\r\n")
7717 (save-match-data
7718 (save-excursion (outline-end-of-heading)
7719 (setq folded (outline-invisible-p)))
7720 (condition-case nil
7721 (org-forward-same-level (1- n) t)
7722 (error nil))
7723 (org-end-of-subtree t t))
7724 (org-back-over-empty-lines)
7725 (setq end (point))
7726 (goto-char beg0)
7727 (when (> end beg)
7728 (setq org-subtree-clip-folded folded)
7729 (when (or cut force-store-markers)
7730 (org-save-markers-in-region beg end))
7731 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7732 (setq org-subtree-clip (current-kill 0))
7733 (message "%s: Subtree(s) with %d characters"
7734 (if cut "Cut" "Copied")
7735 (length org-subtree-clip)))))
7737 (defun org-paste-subtree (&optional level tree for-yank)
7738 "Paste the clipboard as a subtree, with modification of headline level.
7739 The entire subtree is promoted or demoted in order to match a new headline
7740 level.
7742 If the cursor is at the beginning of a headline, the same level as
7743 that headline is used to paste the tree
7745 If not, the new level is derived from the *visible* headings
7746 before and after the insertion point, and taken to be the inferior headline
7747 level of the two. So if the previous visible heading is level 3 and the
7748 next is level 4 (or vice versa), level 4 will be used for insertion.
7749 This makes sure that the subtree remains an independent subtree and does
7750 not swallow low level entries.
7752 You can also force a different level, either by using a numeric prefix
7753 argument, or by inserting the heading marker by hand. For example, if the
7754 cursor is after \"*****\", then the tree will be shifted to level 5.
7756 If optional TREE is given, use this text instead of the kill ring.
7758 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7759 move back over whitespace before inserting, and move point to the end of
7760 the inserted text when done."
7761 (interactive "P")
7762 (setq tree (or tree (and kill-ring (current-kill 0))))
7763 (unless (org-kill-is-subtree-p tree)
7764 (error "%s"
7765 (substitute-command-keys
7766 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7767 (org-with-limited-levels
7768 (let* ((visp (not (outline-invisible-p)))
7769 (txt tree)
7770 (^re_ "\\(\\*+\\)[ \t]*")
7771 (old-level (if (string-match org-outline-regexp-bol txt)
7772 (- (match-end 0) (match-beginning 0) 1)
7773 -1))
7774 (force-level (cond (level (prefix-numeric-value level))
7775 ((and (looking-at "[ \t]*$")
7776 (string-match
7777 "^\\*+$" (buffer-substring
7778 (point-at-bol) (point))))
7779 (- (match-end 1) (match-beginning 1)))
7780 ((and (bolp)
7781 (looking-at org-outline-regexp))
7782 (- (match-end 0) (point) 1))
7783 (t nil)))
7784 (previous-level (save-excursion
7785 (condition-case nil
7786 (progn
7787 (outline-previous-visible-heading 1)
7788 (if (looking-at ^re_)
7789 (- (match-end 0) (match-beginning 0) 1)
7791 (error 1))))
7792 (next-level (save-excursion
7793 (condition-case nil
7794 (progn
7795 (or (looking-at org-outline-regexp)
7796 (outline-next-visible-heading 1))
7797 (if (looking-at ^re_)
7798 (- (match-end 0) (match-beginning 0) 1)
7800 (error 1))))
7801 (new-level (or force-level (max previous-level next-level)))
7802 (shift (if (or (= old-level -1)
7803 (= new-level -1)
7804 (= old-level new-level))
7806 (- new-level old-level)))
7807 (delta (if (> shift 0) -1 1))
7808 (func (if (> shift 0) 'org-demote 'org-promote))
7809 (org-odd-levels-only nil)
7810 beg end newend)
7811 ;; Remove the forced level indicator
7812 (if force-level
7813 (delete-region (point-at-bol) (point)))
7814 ;; Paste
7815 (beginning-of-line (if (bolp) 1 2))
7816 (unless for-yank (org-back-over-empty-lines))
7817 (setq beg (point))
7818 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7819 (insert-before-markers txt)
7820 (unless (string-match "\n\\'" txt) (insert "\n"))
7821 (setq newend (point))
7822 (org-reinstall-markers-in-region beg)
7823 (setq end (point))
7824 (goto-char beg)
7825 (skip-chars-forward " \t\n\r")
7826 (setq beg (point))
7827 (if (and (outline-invisible-p) visp)
7828 (save-excursion (outline-show-heading)))
7829 ;; Shift if necessary
7830 (unless (= shift 0)
7831 (save-restriction
7832 (narrow-to-region beg end)
7833 (while (not (= shift 0))
7834 (org-map-region func (point-min) (point-max))
7835 (setq shift (+ delta shift)))
7836 (goto-char (point-min))
7837 (setq newend (point-max))))
7838 (when (or (org-called-interactively-p 'interactive) for-yank)
7839 (message "Clipboard pasted as level %d subtree" new-level))
7840 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7841 kill-ring
7842 (eq org-subtree-clip (current-kill 0))
7843 org-subtree-clip-folded)
7844 ;; The tree was folded before it was killed/copied
7845 (hide-subtree))
7846 (and for-yank (goto-char newend)))))
7848 (defun org-kill-is-subtree-p (&optional txt)
7849 "Check if the current kill is an outline subtree, or a set of trees.
7850 Returns nil if kill does not start with a headline, or if the first
7851 headline level is not the largest headline level in the tree.
7852 So this will actually accept several entries of equal levels as well,
7853 which is OK for `org-paste-subtree'.
7854 If optional TXT is given, check this string instead of the current kill."
7855 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7856 (re (org-get-limited-outline-regexp))
7857 (^re (concat "^" re))
7858 (start-level (and kill
7859 (string-match
7860 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7861 kill)
7862 (- (match-end 2) (match-beginning 2) 1)))
7863 (start (1+ (or (match-beginning 2) -1))))
7864 (if (not start-level)
7865 (progn
7866 nil) ;; does not even start with a heading
7867 (catch 'exit
7868 (while (setq start (string-match ^re kill (1+ start)))
7869 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7870 (throw 'exit nil)))
7871 t))))
7873 (defvar org-markers-to-move nil
7874 "Markers that should be moved with a cut-and-paste operation.
7875 Those markers are stored together with their positions relative to
7876 the start of the region.")
7878 (defun org-save-markers-in-region (beg end)
7879 "Check markers in region.
7880 If these markers are between BEG and END, record their position relative
7881 to BEG, so that after moving the block of text, we can put the markers back
7882 into place.
7883 This function gets called just before an entry or tree gets cut from the
7884 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7885 called immediately, to move the markers with the entries."
7886 (setq org-markers-to-move nil)
7887 (when (featurep 'org-clock)
7888 (org-clock-save-markers-for-cut-and-paste beg end))
7889 (when (featurep 'org-agenda)
7890 (org-agenda-save-markers-for-cut-and-paste beg end)))
7892 (defun org-check-and-save-marker (marker beg end)
7893 "Check if MARKER is between BEG and END.
7894 If yes, remember the marker and the distance to BEG."
7895 (when (and (marker-buffer marker)
7896 (equal (marker-buffer marker) (current-buffer)))
7897 (if (and (>= marker beg) (< marker end))
7898 (push (cons marker (- marker beg)) org-markers-to-move))))
7900 (defun org-reinstall-markers-in-region (beg)
7901 "Move all remembered markers to their position relative to BEG."
7902 (mapc (lambda (x)
7903 (move-marker (car x) (+ beg (cdr x))))
7904 org-markers-to-move)
7905 (setq org-markers-to-move nil))
7907 (defun org-narrow-to-subtree ()
7908 "Narrow buffer to the current subtree."
7909 (interactive)
7910 (save-excursion
7911 (save-match-data
7912 (org-with-limited-levels
7913 (narrow-to-region
7914 (progn (org-back-to-heading t) (point))
7915 (progn (org-end-of-subtree t t)
7916 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7917 (point)))))))
7919 (defun org-narrow-to-block ()
7920 "Narrow buffer to the current block."
7921 (interactive)
7922 (let* ((case-fold-search t)
7923 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7924 "^[ \t]*#\\+end_.*")))
7925 (if blockp
7926 (narrow-to-region (car blockp) (cdr blockp))
7927 (error "Not in a block"))))
7929 (eval-when-compile
7930 (defvar org-property-drawer-re))
7932 (defvar org-property-start-re) ;; defined below
7933 (defun org-clone-subtree-with-time-shift (n &optional shift)
7934 "Clone the task (subtree) at point N times.
7935 The clones will be inserted as siblings.
7937 In interactive use, the user will be prompted for the number of
7938 clones to be produced, and for a time SHIFT, which may be a
7939 repeater as used in time stamps, for example `+3d'.
7941 When a valid repeater is given and the entry contains any time
7942 stamps, the clones will become a sequence in time, with time
7943 stamps in the subtree shifted for each clone produced. If SHIFT
7944 is nil or the empty string, time stamps will be left alone. The
7945 ID property of the original subtree is removed.
7947 If the original subtree did contain time stamps with a repeater,
7948 the following will happen:
7949 - the repeater will be removed in each clone
7950 - an additional clone will be produced, with the current, unshifted
7951 date(s) in the entry.
7952 - the original entry will be placed *after* all the clones, with
7953 repeater intact.
7954 - the start days in the repeater in the original entry will be shifted
7955 to past the last clone.
7956 In this way you can spell out a number of instances of a repeating task,
7957 and still retain the repeater to cover future instances of the task."
7958 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7959 (let (beg end template task idprop
7960 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7961 (drawer-re org-drawer-regexp))
7962 (if (not (and (integerp n) (> n 0)))
7963 (error "Invalid number of replications %s" n))
7964 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7965 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7966 shift)))
7967 (error "Invalid shift specification %s" shift))
7968 (when doshift
7969 (setq shift-n (string-to-number (match-string 1 shift))
7970 shift-what (cdr (assoc (match-string 2 shift)
7971 '(("d" . day) ("w" . week)
7972 ("m" . month) ("y" . year))))))
7973 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7974 (setq nmin 1 nmax n)
7975 (org-back-to-heading t)
7976 (setq beg (point))
7977 (setq idprop (org-entry-get nil "ID"))
7978 (org-end-of-subtree t t)
7979 (or (bolp) (insert "\n"))
7980 (setq end (point))
7981 (setq template (buffer-substring beg end))
7982 (when (and doshift
7983 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7984 (delete-region beg end)
7985 (setq end beg)
7986 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7987 (goto-char end)
7988 (loop for n from nmin to nmax do
7989 ;; prepare clone
7990 (with-temp-buffer
7991 (insert template)
7992 (org-mode)
7993 (goto-char (point-min))
7994 (org-show-subtree)
7995 (and idprop (if org-clone-delete-id
7996 (org-entry-delete nil "ID")
7997 (org-id-get-create t)))
7998 (unless (= n 0)
7999 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8000 (kill-whole-line))
8001 (goto-char (point-min))
8002 (while (re-search-forward drawer-re nil t)
8003 (mapc (lambda (d)
8004 (org-remove-empty-drawer-at d (point))) org-drawers)))
8005 (goto-char (point-min))
8006 (when doshift
8007 (while (re-search-forward org-ts-regexp-both nil t)
8008 (org-timestamp-change (* n shift-n) shift-what))
8009 (unless (= n n-no-remove)
8010 (goto-char (point-min))
8011 (while (re-search-forward org-ts-regexp nil t)
8012 (save-excursion
8013 (goto-char (match-beginning 0))
8014 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8015 (delete-region (match-beginning 1) (match-end 1)))))))
8016 (setq task (buffer-string)))
8017 (insert task))
8018 (goto-char beg)))
8020 ;;; Outline Sorting
8022 (defun org-sort (with-case)
8023 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8024 Optional argument WITH-CASE means sort case-sensitively."
8025 (interactive "P")
8026 (cond
8027 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8028 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8030 (org-call-with-arg 'org-sort-entries with-case))))
8032 (defun org-sort-remove-invisible (s)
8033 (remove-text-properties 0 (length s) org-rm-props s)
8034 (while (string-match org-bracket-link-regexp s)
8035 (setq s (replace-match (if (match-end 2)
8036 (match-string 3 s)
8037 (match-string 1 s)) t t s)))
8040 (defvar org-priority-regexp) ; defined later in the file
8042 (defvar org-after-sorting-entries-or-items-hook nil
8043 "Hook that is run after a bunch of entries or items have been sorted.
8044 When children are sorted, the cursor is in the parent line when this
8045 hook gets called. When a region or a plain list is sorted, the cursor
8046 will be in the first entry of the sorted region/list.")
8048 (defun org-sort-entries
8049 (&optional with-case sorting-type getkey-func compare-func property)
8050 "Sort entries on a certain level of an outline tree.
8051 If there is an active region, the entries in the region are sorted.
8052 Else, if the cursor is before the first entry, sort the top-level items.
8053 Else, the children of the entry at point are sorted.
8055 Sorting can be alphabetically, numerically, by date/time as given by
8056 a time stamp, by a property or by priority.
8058 The command prompts for the sorting type unless it has been given to the
8059 function through the SORTING-TYPE argument, which needs to be a character,
8060 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8061 precise meaning of each character:
8063 n Numerically, by converting the beginning of the entry/item to a number.
8064 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8065 t By date/time, either the first active time stamp in the entry, or, if
8066 none exist, by the first inactive one.
8067 s By the scheduled date/time.
8068 d By deadline date/time.
8069 c By creation time, which is assumed to be the first inactive time stamp
8070 at the beginning of a line.
8071 p By priority according to the cookie.
8072 r By the value of a property.
8074 Capital letters will reverse the sort order.
8076 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8077 called with point at the beginning of the record. It must return either
8078 a string or a number that should serve as the sorting key for that record.
8080 Comparing entries ignores case by default. However, with an optional argument
8081 WITH-CASE, the sorting considers case as well."
8082 (interactive "P")
8083 (let ((case-func (if with-case 'identity 'downcase))
8084 start beg end stars re re2
8085 txt what tmp)
8086 ;; Find beginning and end of region to sort
8087 (cond
8088 ((org-region-active-p)
8089 ;; we will sort the region
8090 (setq end (region-end)
8091 what "region")
8092 (goto-char (region-beginning))
8093 (if (not (org-at-heading-p)) (outline-next-heading))
8094 (setq start (point)))
8095 ((or (org-at-heading-p)
8096 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8097 ;; we will sort the children of the current headline
8098 (org-back-to-heading)
8099 (setq start (point)
8100 end (progn (org-end-of-subtree t t)
8101 (or (bolp) (insert "\n"))
8102 (org-back-over-empty-lines)
8103 (point))
8104 what "children")
8105 (goto-char start)
8106 (show-subtree)
8107 (outline-next-heading))
8109 ;; we will sort the top-level entries in this file
8110 (goto-char (point-min))
8111 (or (org-at-heading-p) (outline-next-heading))
8112 (setq start (point))
8113 (goto-char (point-max))
8114 (beginning-of-line 1)
8115 (when (looking-at ".*?\\S-")
8116 ;; File ends in a non-white line
8117 (end-of-line 1)
8118 (insert "\n"))
8119 (setq end (point-max))
8120 (setq what "top-level")
8121 (goto-char start)
8122 (show-all)))
8124 (setq beg (point))
8125 (if (>= beg end) (error "Nothing to sort"))
8127 (looking-at "\\(\\*+\\)")
8128 (setq stars (match-string 1)
8129 re (concat "^" (regexp-quote stars) " +")
8130 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8131 txt (buffer-substring beg end))
8132 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8133 (if (and (not (equal stars "*")) (string-match re2 txt))
8134 (error "Region to sort contains a level above the first entry"))
8136 (unless sorting-type
8137 (message
8138 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8139 [t]ime [s]cheduled [d]eadline [c]reated
8140 A/N/T/S/D/C/P/O/F means reversed:"
8141 what)
8142 (setq sorting-type (read-char-exclusive))
8144 (and (= (downcase sorting-type) ?f)
8145 (setq getkey-func
8146 (org-icompleting-read "Sort using function: "
8147 obarray 'fboundp t nil nil))
8148 (setq getkey-func (intern getkey-func)))
8150 (and (= (downcase sorting-type) ?r)
8151 (setq property
8152 (org-icompleting-read "Property: "
8153 (mapcar 'list (org-buffer-property-keys t))
8154 nil t))))
8156 (message "Sorting entries...")
8158 (save-restriction
8159 (narrow-to-region start end)
8160 (let ((dcst (downcase sorting-type))
8161 (case-fold-search nil)
8162 (now (current-time)))
8163 (sort-subr
8164 (/= dcst sorting-type)
8165 ;; This function moves to the beginning character of the "record" to
8166 ;; be sorted.
8167 (lambda nil
8168 (if (re-search-forward re nil t)
8169 (goto-char (match-beginning 0))
8170 (goto-char (point-max))))
8171 ;; This function moves to the last character of the "record" being
8172 ;; sorted.
8173 (lambda nil
8174 (save-match-data
8175 (condition-case nil
8176 (outline-forward-same-level 1)
8177 (error
8178 (goto-char (point-max))))))
8179 ;; This function returns the value that gets sorted against.
8180 (lambda nil
8181 (cond
8182 ((= dcst ?n)
8183 (if (looking-at org-complex-heading-regexp)
8184 (string-to-number (match-string 4))
8185 nil))
8186 ((= dcst ?a)
8187 (if (looking-at org-complex-heading-regexp)
8188 (funcall case-func (match-string 4))
8189 nil))
8190 ((= dcst ?t)
8191 (let ((end (save-excursion (outline-next-heading) (point))))
8192 (if (or (re-search-forward org-ts-regexp end t)
8193 (re-search-forward org-ts-regexp-both end t))
8194 (org-time-string-to-seconds (match-string 0))
8195 (org-float-time now))))
8196 ((= dcst ?c)
8197 (let ((end (save-excursion (outline-next-heading) (point))))
8198 (if (re-search-forward
8199 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8200 end t)
8201 (org-time-string-to-seconds (match-string 0))
8202 (org-float-time now))))
8203 ((= dcst ?s)
8204 (let ((end (save-excursion (outline-next-heading) (point))))
8205 (if (re-search-forward org-scheduled-time-regexp end t)
8206 (org-time-string-to-seconds (match-string 1))
8207 (org-float-time now))))
8208 ((= dcst ?d)
8209 (let ((end (save-excursion (outline-next-heading) (point))))
8210 (if (re-search-forward org-deadline-time-regexp end t)
8211 (org-time-string-to-seconds (match-string 1))
8212 (org-float-time now))))
8213 ((= dcst ?p)
8214 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8215 (string-to-char (match-string 2))
8216 org-default-priority))
8217 ((= dcst ?r)
8218 (or (org-entry-get nil property) ""))
8219 ((= dcst ?o)
8220 (if (looking-at org-complex-heading-regexp)
8221 (- 9999 (length (member (match-string 2)
8222 org-todo-keywords-1)))))
8223 ((= dcst ?f)
8224 (if getkey-func
8225 (progn
8226 (setq tmp (funcall getkey-func))
8227 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8228 tmp)
8229 (error "Invalid key function `%s'" getkey-func)))
8230 (t (error "Invalid sorting type `%c'" sorting-type))))
8232 (cond
8233 ((= dcst ?a) 'string<)
8234 ((= dcst ?f) compare-func)
8235 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8236 (t nil)))))
8237 (run-hooks 'org-after-sorting-entries-or-items-hook)
8238 (message "Sorting entries...done")))
8240 (defun org-do-sort (table what &optional with-case sorting-type)
8241 "Sort TABLE of WHAT according to SORTING-TYPE.
8242 The user will be prompted for the SORTING-TYPE if the call to this
8243 function does not specify it. WHAT is only for the prompt, to indicate
8244 what is being sorted. The sorting key will be extracted from
8245 the car of the elements of the table.
8246 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8247 (unless sorting-type
8248 (message
8249 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8250 what)
8251 (setq sorting-type (read-char-exclusive)))
8252 (let ((dcst (downcase sorting-type))
8253 extractfun comparefun)
8254 ;; Define the appropriate functions
8255 (cond
8256 ((= dcst ?n)
8257 (setq extractfun 'string-to-number
8258 comparefun (if (= dcst sorting-type) '< '>)))
8259 ((= dcst ?a)
8260 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8261 (lambda(x) (downcase (org-sort-remove-invisible x))))
8262 comparefun (if (= dcst sorting-type)
8263 'string<
8264 (lambda (a b) (and (not (string< a b))
8265 (not (string= a b)))))))
8266 ((= dcst ?t)
8267 (setq extractfun
8268 (lambda (x)
8269 (if (or (string-match org-ts-regexp x)
8270 (string-match org-ts-regexp-both x))
8271 (org-float-time
8272 (org-time-string-to-time (match-string 0 x)))
8274 comparefun (if (= dcst sorting-type) '< '>)))
8275 (t (error "Invalid sorting type `%c'" sorting-type)))
8277 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8278 table)
8279 (lambda (a b) (funcall comparefun (car a) (car b))))))
8282 ;;; The orgstruct minor mode
8284 ;; Define a minor mode which can be used in other modes in order to
8285 ;; integrate the org-mode structure editing commands.
8287 ;; This is really a hack, because the org-mode structure commands use
8288 ;; keys which normally belong to the major mode. Here is how it
8289 ;; works: The minor mode defines all the keys necessary to operate the
8290 ;; structure commands, but wraps the commands into a function which
8291 ;; tests if the cursor is currently at a headline or a plain list
8292 ;; item. If that is the case, the structure command is used,
8293 ;; temporarily setting many Org-mode variables like regular
8294 ;; expressions for filling etc. However, when any of those keys is
8295 ;; used at a different location, function uses `key-binding' to look
8296 ;; up if the key has an associated command in another currently active
8297 ;; keymap (minor modes, major mode, global), and executes that
8298 ;; command. There might be problems if any of the keys is otherwise
8299 ;; used as a prefix key.
8301 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8302 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8303 ;; addresses this by checking explicitly for both bindings.
8305 (defvar orgstruct-mode-map (make-sparse-keymap)
8306 "Keymap for the minor `orgstruct-mode'.")
8308 (defvar org-local-vars nil
8309 "List of local variables, for use by `orgstruct-mode'.")
8311 ;;;###autoload
8312 (define-minor-mode orgstruct-mode
8313 "Toggle the minor mode `orgstruct-mode'.
8314 This mode is for using Org-mode structure commands in other
8315 modes. The following keys behave as if Org-mode were active, if
8316 the cursor is on a headline, or on a plain list item (both as
8317 defined by Org-mode).
8319 M-up Move entry/item up
8320 M-down Move entry/item down
8321 M-left Promote
8322 M-right Demote
8323 M-S-up Move entry/item up
8324 M-S-down Move entry/item down
8325 M-S-left Promote subtree
8326 M-S-right Demote subtree
8327 M-q Fill paragraph and items like in Org-mode
8328 C-c ^ Sort entries
8329 C-c - Cycle list bullet
8330 TAB Cycle item visibility
8331 M-RET Insert new heading/item
8332 S-M-RET Insert new TODO heading / Checkbox item
8333 C-c C-c Set tags / toggle checkbox"
8334 nil " OrgStruct" nil
8335 (org-load-modules-maybe)
8336 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8338 ;;;###autoload
8339 (defun turn-on-orgstruct ()
8340 "Unconditionally turn on `orgstruct-mode'."
8341 (orgstruct-mode 1))
8343 (defun orgstruct++-mode (&optional arg)
8344 "Toggle `orgstruct-mode', the enhanced version of it.
8345 In addition to setting orgstruct-mode, this also exports all indentation
8346 and autofilling variables from org-mode into the buffer. It will also
8347 recognize item context in multiline items.
8348 Note that turning off orgstruct-mode will *not* remove the
8349 indentation/paragraph settings. This can only be done by refreshing the
8350 major mode, for example with \\[normal-mode]."
8351 (interactive "P")
8352 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8353 (if (< arg 1)
8354 (orgstruct-mode -1)
8355 (orgstruct-mode 1)
8356 (let (var val)
8357 (mapc
8358 (lambda (x)
8359 (when (string-match
8360 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8361 (symbol-name (car x)))
8362 (setq var (car x) val (nth 1 x))
8363 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8364 org-local-vars)
8365 (org-set-local 'orgstruct-is-++ t))))
8367 (defvar orgstruct-is-++ nil
8368 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8369 (make-variable-buffer-local 'orgstruct-is-++)
8371 ;;;###autoload
8372 (defun turn-on-orgstruct++ ()
8373 "Unconditionally turn on `orgstruct++-mode'."
8374 (orgstruct++-mode 1))
8376 (defun orgstruct-error ()
8377 "Error when there is no default binding for a structure key."
8378 (interactive)
8379 (error "This key has no function outside structure elements"))
8381 (defun orgstruct-setup ()
8382 "Setup orgstruct keymaps."
8383 (let ((nfunc 0)
8384 (bindings
8385 (list
8386 '([(meta up)] org-metaup)
8387 '([(meta down)] org-metadown)
8388 '([(meta left)] org-metaleft)
8389 '([(meta right)] org-metaright)
8390 '([(meta shift up)] org-shiftmetaup)
8391 '([(meta shift down)] org-shiftmetadown)
8392 '([(meta shift left)] org-shiftmetaleft)
8393 '([(meta shift right)] org-shiftmetaright)
8394 '([?\e (up)] org-metaup)
8395 '([?\e (down)] org-metadown)
8396 '([?\e (left)] org-metaleft)
8397 '([?\e (right)] org-metaright)
8398 '([?\e (shift up)] org-shiftmetaup)
8399 '([?\e (shift down)] org-shiftmetadown)
8400 '([?\e (shift left)] org-shiftmetaleft)
8401 '([?\e (shift right)] org-shiftmetaright)
8402 '([(shift up)] org-shiftup)
8403 '([(shift down)] org-shiftdown)
8404 '([(shift left)] org-shiftleft)
8405 '([(shift right)] org-shiftright)
8406 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8407 '("\M-q" fill-paragraph)
8408 '("\C-c^" org-sort)
8409 '("\C-c-" org-cycle-list-bullet)))
8410 elt key fun cmd)
8411 (while (setq elt (pop bindings))
8412 (setq nfunc (1+ nfunc))
8413 (setq key (org-key (car elt))
8414 fun (nth 1 elt)
8415 cmd (orgstruct-make-binding fun nfunc key))
8416 (org-defkey orgstruct-mode-map key cmd))
8418 ;; Special treatment needed for TAB and RET
8419 (org-defkey orgstruct-mode-map [(tab)]
8420 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8421 (org-defkey orgstruct-mode-map "\C-i"
8422 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8424 (org-defkey orgstruct-mode-map "\M-\C-m"
8425 (orgstruct-make-binding 'org-insert-heading 105
8426 "\M-\C-m" [(meta return)]))
8427 (org-defkey orgstruct-mode-map [(meta return)]
8428 (orgstruct-make-binding 'org-insert-heading 106
8429 [(meta return)] "\M-\C-m"))
8431 (org-defkey orgstruct-mode-map [(shift meta return)]
8432 (orgstruct-make-binding 'org-insert-todo-heading 107
8433 [(meta return)] "\M-\C-m"))
8435 (org-defkey orgstruct-mode-map "\e\C-m"
8436 (orgstruct-make-binding 'org-insert-heading 108
8437 "\e\C-m" [?\e (return)]))
8438 (org-defkey orgstruct-mode-map [?\e (return)]
8439 (orgstruct-make-binding 'org-insert-heading 109
8440 [?\e (return)] "\e\C-m"))
8441 (org-defkey orgstruct-mode-map [?\e (shift return)]
8442 (orgstruct-make-binding 'org-insert-todo-heading 110
8443 [?\e (return)] "\e\C-m"))
8445 (unless org-local-vars
8446 (setq org-local-vars (org-get-local-variables)))
8450 (defun orgstruct-make-binding (fun n &rest keys)
8451 "Create a function for binding in the structure minor mode.
8452 FUN is the command to call inside a table. N is used to create a unique
8453 command name. KEYS are keys that should be checked in for a command
8454 to execute outside of tables."
8455 (eval
8456 (list 'defun
8457 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8458 '(arg)
8459 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8460 "Outside of structure, run the binding of `"
8461 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8462 "'.")
8463 '(interactive "p")
8464 (list 'if
8465 `(org-context-p 'headline 'item
8466 (and orgstruct-is-++
8467 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8468 'item-body))
8469 (list 'org-run-like-in-org-mode (list 'quote fun))
8470 (list 'let '(orgstruct-mode)
8471 (list 'call-interactively
8472 (append '(or)
8473 (mapcar (lambda (k)
8474 (list 'key-binding k))
8475 keys)
8476 '('orgstruct-error))))))))
8478 (defun org-context-p (&rest contexts)
8479 "Check if local context is any of CONTEXTS.
8480 Possible values in the list of contexts are `table', `headline', and `item'."
8481 (let ((pos (point)))
8482 (goto-char (point-at-bol))
8483 (prog1 (or (and (memq 'table contexts)
8484 (looking-at "[ \t]*|"))
8485 (and (memq 'headline contexts)
8486 (looking-at org-outline-regexp))
8487 (and (memq 'item contexts)
8488 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8489 (and (memq 'item-body contexts)
8490 (org-in-item-p)))
8491 (goto-char pos))))
8493 (defun org-get-local-variables ()
8494 "Return a list of all local variables in an org-mode buffer."
8495 (let (varlist)
8496 (with-current-buffer (get-buffer-create "*Org tmp*")
8497 (erase-buffer)
8498 (org-mode)
8499 (setq varlist (buffer-local-variables)))
8500 (kill-buffer "*Org tmp*")
8501 (delq nil
8502 (mapcar
8503 (lambda (x)
8504 (setq x
8505 (if (symbolp x)
8506 (list x)
8507 (list (car x) (list 'quote (cdr x)))))
8508 (if (string-match
8509 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8510 (symbol-name (car x)))
8511 x nil))
8512 varlist))))
8514 (defun org-clone-local-variables (from-buffer &optional regexp)
8515 "Clone local variables from FROM-BUFFER.
8516 Optional argument REGEXP selects variables to clone."
8517 (mapc
8518 (lambda (pair)
8519 (and (symbolp (car pair))
8520 (or (null regexp)
8521 (string-match regexp (symbol-name (car pair))))
8522 (set (make-local-variable (car pair))
8523 (cdr pair))))
8524 (buffer-local-variables from-buffer)))
8526 ;;;###autoload
8527 (defun org-run-like-in-org-mode (cmd)
8528 "Run a command, pretending that the current buffer is in Org-mode.
8529 This will temporarily bind local variables that are typically bound in
8530 Org-mode to the values they have in Org-mode, and then interactively
8531 call CMD."
8532 (org-load-modules-maybe)
8533 (unless org-local-vars
8534 (setq org-local-vars (org-get-local-variables)))
8535 (eval (list 'let org-local-vars
8536 (list 'call-interactively (list 'quote cmd)))))
8538 ;;;; Archiving
8540 (defun org-get-category (&optional pos force-refresh)
8541 "Get the category applying to position POS."
8542 (save-match-data
8543 (if force-refresh (org-refresh-category-properties))
8544 (let ((pos (or pos (point))))
8545 (or (get-text-property pos 'org-category)
8546 (progn (org-refresh-category-properties)
8547 (get-text-property pos 'org-category))))))
8549 (defun org-refresh-category-properties ()
8550 "Refresh category text properties in the buffer."
8551 (let ((def-cat (cond
8552 ((null org-category)
8553 (if buffer-file-name
8554 (file-name-sans-extension
8555 (file-name-nondirectory buffer-file-name))
8556 "???"))
8557 ((symbolp org-category) (symbol-name org-category))
8558 (t org-category)))
8559 beg end cat pos optionp)
8560 (org-unmodified
8561 (save-excursion
8562 (save-restriction
8563 (widen)
8564 (goto-char (point-min))
8565 (put-text-property (point) (point-max) 'org-category def-cat)
8566 (while (re-search-forward
8567 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8568 (setq pos (match-end 0)
8569 optionp (equal (char-after (match-beginning 0)) ?#)
8570 cat (org-trim (match-string 2)))
8571 (if optionp
8572 (setq beg (point-at-bol) end (point-max))
8573 (org-back-to-heading t)
8574 (setq beg (point) end (org-end-of-subtree t t)))
8575 (put-text-property beg end 'org-category cat)
8576 (put-text-property beg end 'org-category-position beg)
8577 (goto-char pos)))))))
8580 ;;;; Link Stuff
8582 ;;; Link abbreviations
8584 (defun org-link-expand-abbrev (link)
8585 "Apply replacements as defined in `org-link-abbrev-alist."
8586 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8587 (let* ((key (match-string 1 link))
8588 (as (or (assoc key org-link-abbrev-alist-local)
8589 (assoc key org-link-abbrev-alist)))
8590 (tag (and (match-end 2) (match-string 3 link)))
8591 rpl)
8592 (if (not as)
8593 link
8594 (setq rpl (cdr as))
8595 (cond
8596 ((symbolp rpl) (funcall rpl tag))
8597 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8598 ((string-match "%h" rpl)
8599 (replace-match (url-hexify-string (or tag "")) t t rpl))
8600 (t (concat rpl tag)))))
8601 link))
8603 ;;; Storing and inserting links
8605 (defvar org-insert-link-history nil
8606 "Minibuffer history for links inserted with `org-insert-link'.")
8608 (defvar org-stored-links nil
8609 "Contains the links stored with `org-store-link'.")
8611 (defvar org-store-link-plist nil
8612 "Plist with info about the most recently link created with `org-store-link'.")
8614 (defvar org-link-protocols nil
8615 "Link protocols added to Org-mode using `org-add-link-type'.")
8617 (defvar org-store-link-functions nil
8618 "List of functions that are called to create and store a link.
8619 Each function will be called in turn until one returns a non-nil
8620 value. Each function should check if it is responsible for creating
8621 this link (for example by looking at the major mode).
8622 If not, it must exit and return nil.
8623 If yes, it should return a non-nil value after a calling
8624 `org-store-link-props' with a list of properties and values.
8625 Special properties are:
8627 :type The link prefix, like \"http\". This must be given.
8628 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8629 This is obligatory as well.
8630 :description Optional default description for the second pair
8631 of brackets in an Org-mode link. The user can still change
8632 this when inserting this link into an Org-mode buffer.
8634 In addition to these, any additional properties can be specified
8635 and then used in remember templates.")
8637 (defun org-add-link-type (type &optional follow export)
8638 "Add TYPE to the list of `org-link-types'.
8639 Re-compute all regular expressions depending on `org-link-types'
8641 FOLLOW and EXPORT are two functions.
8643 FOLLOW should take the link path as the single argument and do whatever
8644 is necessary to follow the link, for example find a file or display
8645 a mail message.
8647 EXPORT should format the link path for export to one of the export formats.
8648 It should be a function accepting three arguments:
8650 path the path of the link, the text after the prefix (like \"http:\")
8651 desc the description of the link, if any, or a description added by
8652 org-export-normalize-links if there is none
8653 format the export format, a symbol like `html' or `latex' or `ascii'..
8655 The function may use the FORMAT information to return different values
8656 depending on the format. The return value will be put literally into
8657 the exported file. If the return value is nil, this means Org should
8658 do what it normally does with links which do not have EXPORT defined.
8660 Org-mode has a built-in default for exporting links. If you are happy with
8661 this default, there is no need to define an export function for the link
8662 type. For a simple example of an export function, see `org-bbdb.el'."
8663 (add-to-list 'org-link-types type t)
8664 (org-make-link-regexps)
8665 (if (assoc type org-link-protocols)
8666 (setcdr (assoc type org-link-protocols) (list follow export))
8667 (push (list type follow export) org-link-protocols)))
8669 (defvar org-agenda-buffer-name)
8671 ;;;###autoload
8672 (defun org-store-link (arg)
8673 "\\<org-mode-map>Store an org-link to the current location.
8674 This link is added to `org-stored-links' and can later be inserted
8675 into an org-buffer with \\[org-insert-link].
8677 For some link types, a prefix arg is interpreted:
8678 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8679 For file links, arg negates `org-context-in-file-links'."
8680 (interactive "P")
8681 (org-load-modules-maybe)
8682 (setq org-store-link-plist nil) ; reset
8683 (org-with-limited-levels
8684 (let (link cpltxt desc description search txt custom-id agenda-link)
8685 (cond
8687 ((run-hook-with-args-until-success 'org-store-link-functions)
8688 (setq link (plist-get org-store-link-plist :link)
8689 desc (or (plist-get org-store-link-plist :description) link)))
8691 ((org-src-edit-buffer-p)
8692 (let (label gc)
8693 (while (or (not label)
8694 (save-excursion
8695 (save-restriction
8696 (widen)
8697 (goto-char (point-min))
8698 (re-search-forward
8699 (regexp-quote (format org-coderef-label-format label))
8700 nil t))))
8701 (when label (message "Label exists already") (sit-for 2))
8702 (setq label (read-string "Code line label: " label)))
8703 (end-of-line 1)
8704 (setq link (format org-coderef-label-format label))
8705 (setq gc (- 79 (length link)))
8706 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8707 (insert link)
8708 (setq link (concat "(" label ")") desc nil)))
8710 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8711 ;; We are in the agenda, link to referenced location
8712 (let ((m (or (get-text-property (point) 'org-hd-marker)
8713 (get-text-property (point) 'org-marker))))
8714 (when m
8715 (org-with-point-at m
8716 (setq agenda-link
8717 (if (org-called-interactively-p 'any)
8718 (call-interactively 'org-store-link)
8719 (org-store-link nil)))))))
8721 ((eq major-mode 'calendar-mode)
8722 (let ((cd (calendar-cursor-to-date)))
8723 (setq link
8724 (format-time-string
8725 (car org-time-stamp-formats)
8726 (apply 'encode-time
8727 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8728 nil nil nil))))
8729 (org-store-link-props :type "calendar" :date cd)))
8731 ((eq major-mode 'w3-mode)
8732 (setq cpltxt (if (and (buffer-name)
8733 (not (string-match "Untitled" (buffer-name))))
8734 (buffer-name)
8735 (url-view-url t))
8736 link (org-make-link (url-view-url t)))
8737 (org-store-link-props :type "w3" :url (url-view-url t)))
8739 ((eq major-mode 'w3m-mode)
8740 (setq cpltxt (or w3m-current-title w3m-current-url)
8741 link (org-make-link w3m-current-url))
8742 (org-store-link-props :type "w3m" :url (url-view-url t)))
8744 ((setq search (run-hook-with-args-until-success
8745 'org-create-file-search-functions))
8746 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8747 "::" search))
8748 (setq cpltxt (or description link)))
8750 ((eq major-mode 'image-mode)
8751 (setq cpltxt (concat "file:"
8752 (abbreviate-file-name buffer-file-name))
8753 link (org-make-link cpltxt))
8754 (org-store-link-props :type "image" :file buffer-file-name))
8756 ((eq major-mode 'dired-mode)
8757 ;; link to the file in the current line
8758 (let ((file (dired-get-filename nil t)))
8759 (setq file (if file
8760 (abbreviate-file-name
8761 (expand-file-name (dired-get-filename nil t)))
8762 ;; otherwise, no file so use current directory.
8763 default-directory))
8764 (setq cpltxt (concat "file:" file)
8765 link (org-make-link cpltxt))))
8767 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8768 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8769 (cond
8770 ((org-in-regexp "<<\\(.*?\\)>>")
8771 (setq cpltxt
8772 (concat "file:"
8773 (abbreviate-file-name
8774 (buffer-file-name (buffer-base-buffer)))
8775 "::" (match-string 1))
8776 link (org-make-link cpltxt)))
8777 ((and (featurep 'org-id)
8778 (or (eq org-link-to-org-use-id t)
8779 (and (eq org-link-to-org-use-id 'create-if-interactive)
8780 (org-called-interactively-p 'any))
8781 (and (eq org-link-to-org-use-id
8782 'create-if-interactive-and-no-custom-id)
8783 (org-called-interactively-p 'any)
8784 (not custom-id))
8785 (and org-link-to-org-use-id
8786 (org-entry-get nil "ID"))))
8787 ;; We can make a link using the ID.
8788 (setq link (condition-case nil
8789 (prog1 (org-id-store-link)
8790 (setq desc (plist-get org-store-link-plist
8791 :description)))
8792 (error
8793 ;; probably before first headline, link to file only
8794 (concat "file:"
8795 (abbreviate-file-name
8796 (buffer-file-name (buffer-base-buffer))))))))
8798 ;; Just link to current headline
8799 (setq cpltxt (concat "file:"
8800 (abbreviate-file-name
8801 (buffer-file-name (buffer-base-buffer)))))
8802 ;; Add a context search string
8803 (when (org-xor org-context-in-file-links arg)
8804 (setq txt (cond
8805 ((org-at-heading-p) nil)
8806 ((org-region-active-p)
8807 (buffer-substring (region-beginning) (region-end)))
8808 (t nil)))
8809 (when (or (null txt) (string-match "\\S-" txt))
8810 (setq cpltxt
8811 (concat cpltxt "::"
8812 (condition-case nil
8813 (org-make-org-heading-search-string txt)
8814 (error "")))
8815 desc (or (nth 4 (ignore-errors
8816 (org-heading-components))) "NONE"))))
8817 (if (string-match "::\\'" cpltxt)
8818 (setq cpltxt (substring cpltxt 0 -2)))
8819 (setq link (org-make-link cpltxt)))))
8821 ((buffer-file-name (buffer-base-buffer))
8822 ;; Just link to this file here.
8823 (setq cpltxt (concat "file:"
8824 (abbreviate-file-name
8825 (buffer-file-name (buffer-base-buffer)))))
8826 ;; Add a context string
8827 (when (org-xor org-context-in-file-links arg)
8828 (setq txt (if (org-region-active-p)
8829 (buffer-substring (region-beginning) (region-end))
8830 (buffer-substring (point-at-bol) (point-at-eol))))
8831 ;; Only use search option if there is some text.
8832 (when (string-match "\\S-" txt)
8833 (setq cpltxt
8834 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8835 desc "NONE")))
8836 (setq link (org-make-link cpltxt)))
8838 ((org-called-interactively-p 'interactive)
8839 (error "Cannot link to a buffer which is not visiting a file"))
8841 (t (setq link nil)))
8843 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8844 (setq link (or link cpltxt)
8845 desc (or desc cpltxt))
8846 (if (equal desc "NONE") (setq desc nil))
8848 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8849 (progn
8850 (setq org-stored-links
8851 (cons (list link desc) org-stored-links))
8852 (message "Stored: %s" (or desc link))
8853 (when custom-id
8854 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8855 "::#" custom-id))
8856 (setq org-stored-links
8857 (cons (list link desc) org-stored-links))))
8858 (or agenda-link (and link (org-make-link-string link desc)))))))
8860 (defun org-store-link-props (&rest plist)
8861 "Store link properties, extract names and addresses."
8862 (let (x adr)
8863 (when (setq x (plist-get plist :from))
8864 (setq adr (mail-extract-address-components x))
8865 (setq plist (plist-put plist :fromname (car adr)))
8866 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8867 (when (setq x (plist-get plist :to))
8868 (setq adr (mail-extract-address-components x))
8869 (setq plist (plist-put plist :toname (car adr)))
8870 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8871 (let ((from (plist-get plist :from))
8872 (to (plist-get plist :to)))
8873 (when (and from to org-from-is-user-regexp)
8874 (setq plist
8875 (plist-put plist :fromto
8876 (if (string-match org-from-is-user-regexp from)
8877 (concat "to %t")
8878 (concat "from %f"))))))
8879 (setq org-store-link-plist plist))
8881 (defun org-add-link-props (&rest plist)
8882 "Add these properties to the link property list."
8883 (let (key value)
8884 (while plist
8885 (setq key (pop plist) value (pop plist))
8886 (setq org-store-link-plist
8887 (plist-put org-store-link-plist key value)))))
8889 (defun org-email-link-description (&optional fmt)
8890 "Return the description part of an email link.
8891 This takes information from `org-store-link-plist' and formats it
8892 according to FMT (default from `org-email-link-description-format')."
8893 (setq fmt (or fmt org-email-link-description-format))
8894 (let* ((p org-store-link-plist)
8895 (to (plist-get p :toaddress))
8896 (from (plist-get p :fromaddress))
8897 (table
8898 (list
8899 (cons "%c" (plist-get p :fromto))
8900 (cons "%F" (plist-get p :from))
8901 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8902 (cons "%T" (plist-get p :to))
8903 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8904 (cons "%s" (plist-get p :subject))
8905 (cons "%d" (plist-get p :date))
8906 (cons "%m" (plist-get p :message-id)))))
8907 (when (string-match "%c" fmt)
8908 ;; Check if the user wrote this message
8909 (if (and org-from-is-user-regexp from to
8910 (save-match-data (string-match org-from-is-user-regexp from)))
8911 (setq fmt (replace-match "to %t" t t fmt))
8912 (setq fmt (replace-match "from %f" t t fmt))))
8913 (org-replace-escapes fmt table)))
8915 (defun org-make-org-heading-search-string (&optional string heading)
8916 "Make search string for STRING or current headline."
8917 (interactive)
8918 (let ((s (or string (org-get-heading)))
8919 (lines org-context-in-file-links))
8920 (unless (and string (not heading))
8921 ;; We are using a headline, clean up garbage in there.
8922 (if (string-match org-todo-regexp s)
8923 (setq s (replace-match "" t t s)))
8924 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8925 (setq s (replace-match "" t t s)))
8926 (setq s (org-trim s))
8927 (if (string-match (concat "^\\(" org-quote-string "\\|"
8928 org-comment-string "\\)") s)
8929 (setq s (replace-match "" t t s)))
8930 (while (string-match org-ts-regexp s)
8931 (setq s (replace-match "" t t s))))
8932 (or string (setq s (concat "*" s))) ; Add * for headlines
8933 (when (and string (integerp lines) (> lines 0))
8934 (let ((slines (org-split-string s "\n")))
8935 (when (< lines (length slines))
8936 (setq s (mapconcat
8937 'identity
8938 (reverse (nthcdr (- (length slines) lines)
8939 (reverse slines))) "\n")))))
8940 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8942 (defun org-make-link (&rest strings)
8943 "Concatenate STRINGS."
8944 (apply 'concat strings))
8946 (defun org-make-link-string (link &optional description)
8947 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8948 (unless (string-match "\\S-" link)
8949 (error "Empty link"))
8950 (when (and description
8951 (stringp description)
8952 (not (string-match "\\S-" description)))
8953 (setq description nil))
8954 (when (stringp description)
8955 ;; Remove brackets from the description, they are fatal.
8956 (while (string-match "\\[" description)
8957 (setq description (replace-match "{" t t description)))
8958 (while (string-match "\\]" description)
8959 (setq description (replace-match "}" t t description))))
8960 (when (equal link description)
8961 ;; No description needed, it is identical
8962 (setq description nil))
8963 (when (and (not description)
8964 (not (string-match (org-image-file-name-regexp) link))
8965 (not (equal link (org-link-escape link))))
8966 (setq description (org-extract-attributes link)))
8967 (setq link
8968 (cond ((string-match (org-image-file-name-regexp) link) link)
8969 ((string-match org-link-types-re link)
8970 (concat (match-string 1 link)
8971 (org-link-escape (substring link (match-end 1)))))
8972 (t (org-link-escape link))))
8973 (concat "[[" link "]"
8974 (if description (concat "[" description "]") "")
8975 "]"))
8977 (defconst org-link-escape-chars
8978 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8979 "List of characters that should be escaped in link.
8980 This is the list that is used for internal purposes.")
8982 (defvar org-url-encoding-use-url-hexify nil)
8984 (defconst org-link-escape-chars-browser
8985 '(?\ )
8986 "List of escapes for characters that are problematic in links.
8987 This is the list that is used before handing over to the browser.")
8989 (defun org-link-escape (text &optional table merge)
8990 "Return percent escaped representation of TEXT.
8991 TEXT is a string with the text to escape.
8992 Optional argument TABLE is a list with characters that should be
8993 escaped. When nil, `org-link-escape-chars' is used.
8994 If optional argument MERGE is set, merge TABLE into
8995 `org-link-escape-chars'."
8996 (if (and org-url-encoding-use-url-hexify (not table))
8997 (url-hexify-string text)
8998 (cond
8999 ((and table merge)
9000 (mapc (lambda (defchr)
9001 (unless (member defchr table)
9002 (setq table (cons defchr table)))) org-link-escape-chars))
9003 ((null table)
9004 (setq table org-link-escape-chars)))
9005 (mapconcat
9006 (lambda (char)
9007 (if (or (member char table)
9008 (< char 32) (= char 37) (> char 126))
9009 (mapconcat (lambda (sequence-element)
9010 (format "%%%.2X" sequence-element))
9011 (or (encode-coding-char char 'utf-8)
9012 (error "Unable to percent escape character: %s"
9013 (char-to-string char))) "")
9014 (char-to-string char))) text "")))
9016 (defun org-link-unescape (str)
9017 "Unhex hexified Unicode strings as returned from the JavaScript function
9018 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9019 (unless (and (null str) (string= "" str))
9020 (let ((pos 0) (case-fold-search t) unhexed)
9021 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9022 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9023 (setq str (replace-match unhexed t t str))
9024 (setq pos (+ pos (length unhexed))))))
9025 str)
9027 (defun org-link-unescape-compound (hex)
9028 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9029 Note: this function also decodes single byte encodings like
9030 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9031 (save-match-data
9032 (let* ((bytes (cdr (split-string hex "%")))
9033 (ret "")
9034 (eat 0)
9035 (sum 0))
9036 (while bytes
9037 (let* ((val (string-to-number (pop bytes) 16))
9038 (shift-xor
9039 (if (= 0 eat)
9040 (cond
9041 ((>= val 252) (cons 6 252))
9042 ((>= val 248) (cons 5 248))
9043 ((>= val 240) (cons 4 240))
9044 ((>= val 224) (cons 3 224))
9045 ((>= val 192) (cons 2 192))
9046 (t (cons 0 0)))
9047 (cons 6 128))))
9048 (if (>= val 192) (setq eat (car shift-xor)))
9049 (setq val (logxor val (cdr shift-xor)))
9050 (setq sum (+ (lsh sum (car shift-xor)) val))
9051 (if (> eat 0) (setq eat (- eat 1)))
9052 (cond
9053 ((= 0 eat) ;multi byte
9054 (setq ret (concat ret (org-char-to-string sum)))
9055 (setq sum 0))
9056 ((not bytes) ; single byte(s)
9057 (setq ret (org-link-unescape-single-byte-sequence hex))))
9058 )) ;; end (while bytes
9059 ret )))
9061 (defun org-link-unescape-single-byte-sequence (hex)
9062 "Unhexify hex-encoded single byte character sequences."
9063 (mapconcat (lambda (byte)
9064 (char-to-string (string-to-number byte 16)))
9065 (cdr (split-string hex "%")) ""))
9067 (defun org-xor (a b)
9068 "Exclusive or."
9069 (if a (not b) b))
9071 (defun org-fixup-message-id-for-http (s)
9072 "Replace special characters in a message id, so it can be used in an http query."
9073 (when (string-match "%" s)
9074 (setq s (mapconcat (lambda (c)
9075 (if (eq c ?%)
9076 "%25"
9077 (char-to-string c)))
9078 s "")))
9079 (while (string-match "<" s)
9080 (setq s (replace-match "%3C" t t s)))
9081 (while (string-match ">" s)
9082 (setq s (replace-match "%3E" t t s)))
9083 (while (string-match "@" s)
9084 (setq s (replace-match "%40" t t s)))
9087 ;;;###autoload
9088 (defun org-insert-link-global ()
9089 "Insert a link like Org-mode does.
9090 This command can be called in any mode to insert a link in Org-mode syntax."
9091 (interactive)
9092 (org-load-modules-maybe)
9093 (org-run-like-in-org-mode 'org-insert-link))
9095 (defun org-insert-link (&optional complete-file link-location default-description)
9096 "Insert a link. At the prompt, enter the link.
9098 Completion can be used to insert any of the link protocol prefixes like
9099 http or ftp in use.
9101 The history can be used to select a link previously stored with
9102 `org-store-link'. When the empty string is entered (i.e. if you just
9103 press RET at the prompt), the link defaults to the most recently
9104 stored link. As SPC triggers completion in the minibuffer, you need to
9105 use M-SPC or C-q SPC to force the insertion of a space character.
9107 You will also be prompted for a description, and if one is given, it will
9108 be displayed in the buffer instead of the link.
9110 If there is already a link at point, this command will allow you to edit link
9111 and description parts.
9113 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9114 be selected using completion. The path to the file will be relative to the
9115 current directory if the file is in the current directory or a subdirectory.
9116 Otherwise, the link will be the absolute path as completed in the minibuffer
9117 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9118 option `org-link-file-path-type'.
9120 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9121 the current directory or below.
9123 With three \\[universal-argument] prefixes, negate the meaning of
9124 `org-keep-stored-link-after-insertion'.
9126 If `org-make-link-description-function' is non-nil, this function will be
9127 called with the link target, and the result will be the default
9128 link description.
9130 If the LINK-LOCATION parameter is non-nil, this value will be
9131 used as the link location instead of reading one interactively.
9133 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9134 be used as the default description."
9135 (interactive "P")
9136 (let* ((wcf (current-window-configuration))
9137 (region (if (org-region-active-p)
9138 (buffer-substring (region-beginning) (region-end))))
9139 (remove (and region (list (region-beginning) (region-end))))
9140 (desc region)
9141 tmphist ; byte-compile incorrectly complains about this
9142 (link link-location)
9143 entry file all-prefixes)
9144 (cond
9145 (link-location) ; specified by arg, just use it.
9146 ((org-in-regexp org-bracket-link-regexp 1)
9147 ;; We do have a link at point, and we are going to edit it.
9148 (setq remove (list (match-beginning 0) (match-end 0)))
9149 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9150 (setq link (read-string "Link: "
9151 (org-link-unescape
9152 (org-match-string-no-properties 1)))))
9153 ((or (org-in-regexp org-angle-link-re)
9154 (org-in-regexp org-plain-link-re))
9155 ;; Convert to bracket link
9156 (setq remove (list (match-beginning 0) (match-end 0))
9157 link (read-string "Link: "
9158 (org-remove-angle-brackets (match-string 0)))))
9159 ((member complete-file '((4) (16)))
9160 ;; Completing read for file names.
9161 (setq link (org-file-complete-link complete-file)))
9163 ;; Read link, with completion for stored links.
9164 (with-output-to-temp-buffer "*Org Links*"
9165 (princ "Insert a link.
9166 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9167 (when org-stored-links
9168 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9169 (princ (mapconcat
9170 (lambda (x)
9171 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9172 (reverse org-stored-links) "\n"))))
9173 (let ((cw (selected-window)))
9174 (select-window (get-buffer-window "*Org Links*" 'visible))
9175 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9176 (unless (pos-visible-in-window-p (point-max))
9177 (org-fit-window-to-buffer))
9178 (and (window-live-p cw) (select-window cw)))
9179 ;; Fake a link history, containing the stored links.
9180 (setq tmphist (append (mapcar 'car org-stored-links)
9181 org-insert-link-history))
9182 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9183 (mapcar 'car org-link-abbrev-alist)
9184 org-link-types))
9185 (unwind-protect
9186 (progn
9187 (setq link
9188 (let ((org-completion-use-ido nil)
9189 (org-completion-use-iswitchb nil))
9190 (org-completing-read
9191 "Link: "
9192 (append
9193 (mapcar (lambda (x) (list (concat x ":")))
9194 all-prefixes)
9195 (mapcar 'car org-stored-links))
9196 nil nil nil
9197 'tmphist
9198 (car (car org-stored-links)))))
9199 (if (not (string-match "\\S-" link))
9200 (error "No link selected"))
9201 (if (or (member link all-prefixes)
9202 (and (equal ":" (substring link -1))
9203 (member (substring link 0 -1) all-prefixes)
9204 (setq link (substring link 0 -1))))
9205 (setq link (org-link-try-special-completion link))))
9206 (set-window-configuration wcf)
9207 (kill-buffer "*Org Links*"))
9208 (setq entry (assoc link org-stored-links))
9209 (or entry (push link org-insert-link-history))
9210 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9211 (not org-keep-stored-link-after-insertion))
9212 (setq org-stored-links (delq (assoc link org-stored-links)
9213 org-stored-links)))
9214 (setq desc (or desc (nth 1 entry)))))
9216 (if (string-match org-plain-link-re link)
9217 ;; URL-like link, normalize the use of angular brackets.
9218 (setq link (org-make-link (org-remove-angle-brackets link))))
9220 ;; Check if we are linking to the current file with a search option
9221 ;; If yes, simplify the link by using only the search option.
9222 (when (and buffer-file-name
9223 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9224 (let* ((path (match-string 1 link))
9225 (case-fold-search nil)
9226 (search (match-string 2 link)))
9227 (save-match-data
9228 (if (equal (file-truename buffer-file-name) (file-truename path))
9229 ;; We are linking to this same file, with a search option
9230 (setq link search)))))
9232 ;; Check if we can/should use a relative path. If yes, simplify the link
9233 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9234 (let* ((type (match-string 1 link))
9235 (path (match-string 2 link))
9236 (origpath path)
9237 (case-fold-search nil))
9238 (cond
9239 ((or (eq org-link-file-path-type 'absolute)
9240 (equal complete-file '(16)))
9241 (setq path (abbreviate-file-name (expand-file-name path))))
9242 ((eq org-link-file-path-type 'noabbrev)
9243 (setq path (expand-file-name path)))
9244 ((eq org-link-file-path-type 'relative)
9245 (setq path (file-relative-name path)))
9247 (save-match-data
9248 (if (string-match (concat "^" (regexp-quote
9249 (expand-file-name
9250 (file-name-as-directory
9251 default-directory))))
9252 (expand-file-name path))
9253 ;; We are linking a file with relative path name.
9254 (setq path (substring (expand-file-name path)
9255 (match-end 0)))
9256 (setq path (abbreviate-file-name (expand-file-name path)))))))
9257 (setq link (concat type path))
9258 (if (equal desc origpath)
9259 (setq desc path))))
9261 (if org-make-link-description-function
9262 (setq desc (funcall org-make-link-description-function link desc))
9263 (if default-description (setq desc default-description)))
9265 (setq desc (read-string "Description: " desc))
9266 (unless (string-match "\\S-" desc) (setq desc nil))
9267 (if remove (apply 'delete-region remove))
9268 (insert (org-make-link-string link desc))))
9270 (defun org-link-try-special-completion (type)
9271 "If there is completion support for link type TYPE, offer it."
9272 (let ((fun (intern (concat "org-" type "-complete-link"))))
9273 (if (functionp fun)
9274 (funcall fun)
9275 (read-string "Link (no completion support): " (concat type ":")))))
9277 (defun org-file-complete-link (&optional arg)
9278 "Create a file link using completion."
9279 (let (file link)
9280 (setq file (read-file-name "File: "))
9281 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9282 (pwd1 (file-name-as-directory (abbreviate-file-name
9283 (expand-file-name ".")))))
9284 (cond
9285 ((equal arg '(16))
9286 (setq link (org-make-link
9287 "file:"
9288 (abbreviate-file-name (expand-file-name file)))))
9289 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9290 (setq link (org-make-link "file:" (match-string 1 file))))
9291 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9292 (expand-file-name file))
9293 (setq link (org-make-link
9294 "file:" (match-string 1 (expand-file-name file)))))
9295 (t (setq link (org-make-link "file:" file)))))
9296 link))
9298 (defun org-completing-read (&rest args)
9299 "Completing-read with SPACE being a normal character."
9300 (let ((enable-recursive-minibuffers t)
9301 (minibuffer-local-completion-map
9302 (copy-keymap minibuffer-local-completion-map)))
9303 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9304 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9305 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9306 (apply 'org-icompleting-read args)))
9308 (defun org-completing-read-no-i (&rest args)
9309 (let (org-completion-use-ido org-completion-use-iswitchb)
9310 (apply 'org-completing-read args)))
9312 (defun org-iswitchb-completing-read (prompt choices &rest args)
9313 "Use iswitch as a completing-read replacement to choose from choices.
9314 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9315 from."
9316 (let* ((iswitchb-use-virtual-buffers nil)
9317 (iswitchb-make-buflist-hook
9318 (lambda ()
9319 (setq iswitchb-temp-buflist choices))))
9320 (iswitchb-read-buffer prompt)))
9322 (defun org-icompleting-read (&rest args)
9323 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9324 (org-without-partial-completion
9325 (if (and org-completion-use-ido
9326 (fboundp 'ido-completing-read)
9327 (boundp 'ido-mode) ido-mode
9328 (listp (second args)))
9329 (let ((ido-enter-matching-directory nil))
9330 (apply 'ido-completing-read (concat (car args))
9331 (if (consp (car (nth 1 args)))
9332 (mapcar 'car (nth 1 args))
9333 (nth 1 args))
9334 (cddr args)))
9335 (if (and org-completion-use-iswitchb
9336 (boundp 'iswitchb-mode) iswitchb-mode
9337 (listp (second args)))
9338 (apply 'org-iswitchb-completing-read (concat (car args))
9339 (if (consp (car (nth 1 args)))
9340 (mapcar 'car (nth 1 args))
9341 (nth 1 args))
9342 (cddr args))
9343 (apply 'completing-read args)))))
9345 (defun org-extract-attributes (s)
9346 "Extract the attributes cookie from a string and set as text property."
9347 (let (a attr (start 0) key value)
9348 (save-match-data
9349 (when (string-match "{{\\([^}]+\\)}}$" s)
9350 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9351 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9352 (setq key (match-string 1 a) value (match-string 2 a)
9353 start (match-end 0)
9354 attr (plist-put attr (intern key) value))))
9355 (org-add-props s nil 'org-attr attr))
9358 (defun org-extract-attributes-from-string (tag)
9359 (let (key value attr)
9360 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9361 (setq key (match-string 1 tag) value (match-string 2 tag)
9362 tag (replace-match "" t t tag)
9363 attr (plist-put attr (intern key) value)))
9364 (cons tag attr)))
9366 (defun org-attributes-to-string (plist)
9367 "Format a property list into an HTML attribute list."
9368 (let ((s "") key value)
9369 (while plist
9370 (setq key (pop plist) value (pop plist))
9371 (and value
9372 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9375 ;;; Opening/following a link
9377 (defvar org-link-search-failed nil)
9379 (defvar org-open-link-functions nil
9380 "Hook for functions finding a plain text link.
9381 These functions must take a single argument, the link content.
9382 They will be called for links that look like [[link text][description]]
9383 when LINK TEXT does not have a protocol like \"http:\" and does not look
9384 like a filename (e.g. \"./blue.png\").
9386 These functions will be called *before* Org attempts to resolve the
9387 link by doing text searches in the current buffer - so if you want a
9388 link \"[[target]]\" to still find \"<<target>>\", your function should
9389 handle this as a special case.
9391 When the function does handle the link, it must return a non-nil value.
9392 If it decides that it is not responsible for this link, it must return
9393 nil to indicate that that Org-mode can continue with other options
9394 like exact and fuzzy text search.")
9396 (defun org-next-link ()
9397 "Move forward to the next link.
9398 If the link is in hidden text, expose it."
9399 (interactive)
9400 (when (and org-link-search-failed (eq this-command last-command))
9401 (goto-char (point-min))
9402 (message "Link search wrapped back to beginning of buffer"))
9403 (setq org-link-search-failed nil)
9404 (let* ((pos (point))
9405 (ct (org-context))
9406 (a (assoc :link ct)))
9407 (if a (goto-char (nth 2 a)))
9408 (if (re-search-forward org-any-link-re nil t)
9409 (progn
9410 (goto-char (match-beginning 0))
9411 (if (outline-invisible-p) (org-show-context)))
9412 (goto-char pos)
9413 (setq org-link-search-failed t)
9414 (error "No further link found"))))
9416 (defun org-previous-link ()
9417 "Move backward to the previous link.
9418 If the link is in hidden text, expose it."
9419 (interactive)
9420 (when (and org-link-search-failed (eq this-command last-command))
9421 (goto-char (point-max))
9422 (message "Link search wrapped back to end of buffer"))
9423 (setq org-link-search-failed nil)
9424 (let* ((pos (point))
9425 (ct (org-context))
9426 (a (assoc :link ct)))
9427 (if a (goto-char (nth 1 a)))
9428 (if (re-search-backward org-any-link-re nil t)
9429 (progn
9430 (goto-char (match-beginning 0))
9431 (if (outline-invisible-p) (org-show-context)))
9432 (goto-char pos)
9433 (setq org-link-search-failed t)
9434 (error "No further link found"))))
9436 (defun org-translate-link (s)
9437 "Translate a link string if a translation function has been defined."
9438 (if (and org-link-translation-function
9439 (fboundp org-link-translation-function)
9440 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9441 (progn
9442 (setq s (funcall org-link-translation-function
9443 (match-string 1) (match-string 2)))
9444 (concat (car s) ":" (cdr s)))
9447 (defun org-translate-link-from-planner (type path)
9448 "Translate a link from Emacs Planner syntax so that Org can follow it.
9449 This is still an experimental function, your mileage may vary."
9450 (cond
9451 ((member type '("http" "https" "news" "ftp"))
9452 ;; standard Internet links are the same.
9453 nil)
9454 ((and (equal type "irc") (string-match "^//" path))
9455 ;; Planner has two / at the beginning of an irc link, we have 1.
9456 ;; We should have zero, actually....
9457 (setq path (substring path 1)))
9458 ((and (equal type "lisp") (string-match "^/" path))
9459 ;; Planner has a slash, we do not.
9460 (setq type "elisp" path (substring path 1)))
9461 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9462 ;; A typical message link. Planner has the id after the final slash,
9463 ;; we separate it with a hash mark
9464 (setq path (concat (match-string 1 path) "#"
9465 (org-remove-angle-brackets (match-string 2 path)))))
9467 (cons type path))
9469 (defun org-find-file-at-mouse (ev)
9470 "Open file link or URL at mouse."
9471 (interactive "e")
9472 (mouse-set-point ev)
9473 (org-open-at-point 'in-emacs))
9475 (defun org-open-at-mouse (ev)
9476 "Open file link or URL at mouse.
9477 See the docstring of `org-open-file' for details."
9478 (interactive "e")
9479 (mouse-set-point ev)
9480 (if (eq major-mode 'org-agenda-mode)
9481 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9482 (org-open-at-point))
9484 (defvar org-window-config-before-follow-link nil
9485 "The window configuration before following a link.
9486 This is saved in case the need arises to restore it.")
9488 (defvar org-open-link-marker (make-marker)
9489 "Marker pointing to the location where `org-open-at-point; was called.")
9491 ;;;###autoload
9492 (defun org-open-at-point-global ()
9493 "Follow a link like Org-mode does.
9494 This command can be called in any mode to follow a link that has
9495 Org-mode syntax."
9496 (interactive)
9497 (org-run-like-in-org-mode 'org-open-at-point))
9499 ;;;###autoload
9500 (defun org-open-link-from-string (s &optional arg reference-buffer)
9501 "Open a link in the string S, as if it was in Org-mode."
9502 (interactive "sLink: \nP")
9503 (let ((reference-buffer (or reference-buffer (current-buffer))))
9504 (with-temp-buffer
9505 (let ((org-inhibit-startup (not reference-buffer)))
9506 (org-mode)
9507 (insert s)
9508 (goto-char (point-min))
9509 (when reference-buffer
9510 (setq org-link-abbrev-alist-local
9511 (with-current-buffer reference-buffer
9512 org-link-abbrev-alist-local)))
9513 (org-open-at-point arg reference-buffer)))))
9515 (defvar org-open-at-point-functions nil
9516 "Hook that is run when following a link at point.
9518 Functions in this hook must return t if they identify and follow
9519 a link at point. If they don't find anything interesting at point,
9520 they must return nil.")
9522 (defun org-open-at-point (&optional arg reference-buffer)
9523 "Open link at or after point.
9524 If there is no link at point, this function will search forward up to
9525 the end of the current line.
9526 Normally, files will be opened by an appropriate application. If the
9527 optional prefix argument ARG is non-nil, Emacs will visit the file.
9528 With a double prefix argument, try to open outside of Emacs, in the
9529 application the system uses for this file type."
9530 (interactive "P")
9531 ;; if in a code block, then open the block's results
9532 (unless (call-interactively #'org-babel-open-src-block-result)
9533 (org-load-modules-maybe)
9534 (move-marker org-open-link-marker (point))
9535 (setq org-window-config-before-follow-link (current-window-configuration))
9536 (org-remove-occur-highlights nil nil t)
9537 (cond
9538 ((and (org-at-heading-p)
9539 (not (org-in-regexp
9540 (concat org-plain-link-re "\\|"
9541 org-bracket-link-regexp "\\|"
9542 org-angle-link-re "\\|"
9543 "[ \t]:[^ \t\n]+:[ \t]*$")))
9544 (not (get-text-property (point) 'org-linked-text)))
9545 (or (org-offer-links-in-entry arg)
9546 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9547 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9548 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9549 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9550 (not (org-in-regexp org-bracket-link-regexp)))
9551 (org-footnote-action))
9553 (let (type path link line search (pos (point)))
9554 (catch 'match
9555 (save-excursion
9556 (skip-chars-forward "^]\n\r")
9557 (when (org-in-regexp org-bracket-link-regexp 1)
9558 (setq link (org-extract-attributes
9559 (org-link-unescape (org-match-string-no-properties 1))))
9560 (while (string-match " *\n *" link)
9561 (setq link (replace-match " " t t link)))
9562 (setq link (org-link-expand-abbrev link))
9563 (cond
9564 ((or (file-name-absolute-p link)
9565 (string-match "^\\.\\.?/" link))
9566 (setq type "file" path link))
9567 ((string-match org-link-re-with-space3 link)
9568 (setq type (match-string 1 link) path (match-string 2 link)))
9569 (t (setq type "thisfile" path link)))
9570 (throw 'match t)))
9572 (when (get-text-property (point) 'org-linked-text)
9573 (setq type "thisfile"
9574 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9575 (1+ (point)) (point))
9576 path (buffer-substring
9577 (or (previous-single-property-change pos 'org-linked-text)
9578 (point-min))
9579 (or (next-single-property-change pos 'org-linked-text)
9580 (point-max))))
9581 (throw 'match t))
9583 (save-excursion
9584 (when (or (org-in-regexp org-angle-link-re)
9585 (org-in-regexp org-plain-link-re))
9586 (setq type (match-string 1)
9587 path (org-link-unescape (match-string 2)))
9588 (throw 'match t)))
9589 (save-excursion
9590 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9591 (setq type "tags"
9592 path (match-string 1))
9593 (while (string-match ":" path)
9594 (setq path (replace-match "+" t t path)))
9595 (throw 'match t)))
9596 (when (org-in-regexp "<\\([^><\n]+\\)>")
9597 (setq type "tree-match"
9598 path (match-string 1))
9599 (throw 'match t)))
9600 (unless path
9601 (error "No link found"))
9603 ;; switch back to reference buffer
9604 ;; needed when if called in a temporary buffer through
9605 ;; org-open-link-from-string
9606 (with-current-buffer (or reference-buffer (current-buffer))
9608 ;; Remove any trailing spaces in path
9609 (if (string-match " +\\'" path)
9610 (setq path (replace-match "" t t path)))
9611 (if (and org-link-translation-function
9612 (fboundp org-link-translation-function))
9613 ;; Check if we need to translate the link
9614 (let ((tmp (funcall org-link-translation-function type path)))
9615 (setq type (car tmp) path (cdr tmp))))
9617 (cond
9619 ((assoc type org-link-protocols)
9620 (funcall (nth 1 (assoc type org-link-protocols)) path))
9622 ((equal type "mailto")
9623 (let ((cmd (car org-link-mailto-program))
9624 (args (cdr org-link-mailto-program)) args1
9625 (address path) (subject "") a)
9626 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9627 (setq address (match-string 1 path)
9628 subject (org-link-escape (match-string 2 path))))
9629 (while args
9630 (cond
9631 ((not (stringp (car args))) (push (pop args) args1))
9632 (t (setq a (pop args))
9633 (if (string-match "%a" a)
9634 (setq a (replace-match address t t a)))
9635 (if (string-match "%s" a)
9636 (setq a (replace-match subject t t a)))
9637 (push a args1))))
9638 (apply cmd (nreverse args1))))
9640 ((member type '("http" "https" "ftp" "news"))
9641 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9642 (org-link-escape
9643 path org-link-escape-chars-browser)
9644 path))))
9646 ((string= type "doi")
9647 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9648 (org-link-escape
9649 path org-link-escape-chars-browser)
9650 path))))
9652 ((member type '("message"))
9653 (browse-url (concat type ":" path)))
9655 ((string= type "tags")
9656 (org-tags-view arg path))
9658 ((string= type "tree-match")
9659 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9661 ((string= type "file")
9662 (if (string-match "::\\([0-9]+\\)\\'" path)
9663 (setq line (string-to-number (match-string 1 path))
9664 path (substring path 0 (match-beginning 0)))
9665 (if (string-match "::\\(.+\\)\\'" path)
9666 (setq search (match-string 1 path)
9667 path (substring path 0 (match-beginning 0)))))
9668 (if (string-match "[*?{]" (file-name-nondirectory path))
9669 (dired path)
9670 (org-open-file path arg line search)))
9672 ((string= type "shell")
9673 (let ((cmd path))
9674 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9675 (string-match org-confirm-shell-link-not-regexp cmd))
9676 (not org-confirm-shell-link-function)
9677 (funcall org-confirm-shell-link-function
9678 (format "Execute \"%s\" in shell? "
9679 (org-add-props cmd nil
9680 'face 'org-warning))))
9681 (progn
9682 (message "Executing %s" cmd)
9683 (shell-command cmd))
9684 (error "Abort"))))
9686 ((string= type "elisp")
9687 (let ((cmd path))
9688 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9689 (string-match org-confirm-elisp-link-not-regexp cmd))
9690 (not org-confirm-elisp-link-function)
9691 (funcall org-confirm-elisp-link-function
9692 (format "Execute \"%s\" as elisp? "
9693 (org-add-props cmd nil
9694 'face 'org-warning))))
9695 (message "%s => %s" cmd
9696 (if (equal (string-to-char cmd) ?\()
9697 (eval (read cmd))
9698 (call-interactively (read cmd))))
9699 (error "Abort"))))
9701 ((and (string= type "thisfile")
9702 (run-hook-with-args-until-success
9703 'org-open-link-functions path)))
9705 ((string= type "thisfile")
9706 (if arg
9707 (switch-to-buffer-other-window
9708 (org-get-buffer-for-internal-link (current-buffer)))
9709 (org-mark-ring-push))
9710 (let ((cmd `(org-link-search
9711 ,path
9712 ,(cond ((equal arg '(4)) ''occur)
9713 ((equal arg '(16)) ''org-occur)
9714 (t nil))
9715 ,pos)))
9716 (condition-case nil (let ((org-link-search-inhibit-query t))
9717 (eval cmd))
9718 (error (progn (widen) (eval cmd))))))
9721 (browse-url-at-point)))))))
9722 (move-marker org-open-link-marker nil)
9723 (run-hook-with-args 'org-follow-link-hook)))
9725 (defun org-offer-links-in-entry (&optional nth zero)
9726 "Offer links in the current entry and follow the selected link.
9727 If there is only one link, follow it immediately as well.
9728 If NTH is an integer, immediately pick the NTH link found.
9729 If ZERO is a string, check also this string for a link, and if
9730 there is one, offer it as link number zero."
9731 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9732 "\\(" org-angle-link-re "\\)\\|"
9733 "\\(" org-plain-link-re "\\)"))
9734 (cnt ?0)
9735 (in-emacs (if (integerp nth) nil nth))
9736 have-zero end links link c)
9737 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9738 (push (match-string 0 zero) links)
9739 (setq cnt (1- cnt) have-zero t))
9740 (save-excursion
9741 (org-back-to-heading t)
9742 (setq end (save-excursion (outline-next-heading) (point)))
9743 (while (re-search-forward re end t)
9744 (push (match-string 0) links))
9745 (setq links (org-uniquify (reverse links))))
9747 (cond
9748 ((null links)
9749 (message "No links"))
9750 ((equal (length links) 1)
9751 (setq link (list (car links))))
9752 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9753 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9754 (t ; we have to select a link
9755 (save-excursion
9756 (save-window-excursion
9757 (delete-other-windows)
9758 (with-output-to-temp-buffer "*Select Link*"
9759 (mapc (lambda (l)
9760 (if (not (string-match org-bracket-link-regexp l))
9761 (princ (format "[%c] %s\n" (incf cnt)
9762 (org-remove-angle-brackets l)))
9763 (if (match-end 3)
9764 (princ (format "[%c] %s (%s)\n" (incf cnt)
9765 (match-string 3 l) (match-string 1 l)))
9766 (princ (format "[%c] %s\n" (incf cnt)
9767 (match-string 1 l))))))
9768 links))
9769 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9770 (message "Select link to open, RET to open all:")
9771 (setq c (read-char-exclusive))
9772 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9773 (when (equal c ?q) (error "Abort"))
9774 (if (equal c ?\C-m)
9775 (setq link links)
9776 (setq nth (- c ?0))
9777 (if have-zero (setq nth (1+ nth)))
9778 (unless (and (integerp nth) (>= (length links) nth))
9779 (error "Invalid link selection"))
9780 (setq link (list (nth (1- nth) links))))))
9781 (if link
9782 (let ((buf (current-buffer)))
9783 (dolist (l link)
9784 (org-open-link-from-string l in-emacs buf))
9786 nil)))
9788 ;; Add special file links that specify the way of opening
9790 (org-add-link-type "file+sys" 'org-open-file-with-system)
9791 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9792 (defun org-open-file-with-system (path)
9793 "Open file at PATH using the system way of opening it."
9794 (org-open-file path 'system))
9795 (defun org-open-file-with-emacs (path)
9796 "Open file at PATH in Emacs."
9797 (org-open-file path 'emacs))
9798 (defun org-remove-file-link-modifiers ()
9799 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9800 (goto-char (point-min))
9801 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9802 (org-if-unprotected
9803 (replace-match "file:" t t))))
9804 (eval-after-load "org-exp"
9805 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9806 'org-remove-file-link-modifiers))
9808 ;;;; Time estimates
9810 (defun org-get-effort (&optional pom)
9811 "Get the effort estimate for the current entry."
9812 (org-entry-get pom org-effort-property))
9814 ;;; File search
9816 (defvar org-create-file-search-functions nil
9817 "List of functions to construct the right search string for a file link.
9818 These functions are called in turn with point at the location to
9819 which the link should point.
9821 A function in the hook should first test if it would like to
9822 handle this file type, for example by checking the `major-mode'
9823 or the file extension. If it decides not to handle this file, it
9824 should just return nil to give other functions a chance. If it
9825 does handle the file, it must return the search string to be used
9826 when following the link. The search string will be part of the
9827 file link, given after a double colon, and `org-open-at-point'
9828 will automatically search for it. If special measures must be
9829 taken to make the search successful, another function should be
9830 added to the companion hook `org-execute-file-search-functions',
9831 which see.
9833 A function in this hook may also use `setq' to set the variable
9834 `description' to provide a suggestion for the descriptive text to
9835 be used for this link when it gets inserted into an Org-mode
9836 buffer with \\[org-insert-link].")
9838 (defvar org-execute-file-search-functions nil
9839 "List of functions to execute a file search triggered by a link.
9841 Functions added to this hook must accept a single argument, the
9842 search string that was part of the file link, the part after the
9843 double colon. The function must first check if it would like to
9844 handle this search, for example by checking the `major-mode' or
9845 the file extension. If it decides not to handle this search, it
9846 should just return nil to give other functions a chance. If it
9847 does handle the search, it must return a non-nil value to keep
9848 other functions from trying.
9850 Each function can access the current prefix argument through the
9851 variable `current-prefix-argument'. Note that a single prefix is
9852 used to force opening a link in Emacs, so it may be good to only
9853 use a numeric or double prefix to guide the search function.
9855 In case this is needed, a function in this hook can also restore
9856 the window configuration before `org-open-at-point' was called using:
9858 (set-window-configuration org-window-config-before-follow-link)")
9860 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9861 (defun org-link-search (s &optional type avoid-pos stealth)
9862 "Search for a link search option.
9863 If S is surrounded by forward slashes, it is interpreted as a
9864 regular expression. In org-mode files, this will create an `org-occur'
9865 sparse tree. In ordinary files, `occur' will be used to list matches.
9866 If the current buffer is in `dired-mode', grep will be used to search
9867 in all files. If AVOID-POS is given, ignore matches near that position.
9869 When optional argument STEALTH is non-nil, do not modify
9870 visibility around point, thus ignoring
9871 `org-show-hierarchy-above', `org-show-following-heading' and
9872 `org-show-siblings' variables."
9873 (let ((case-fold-search t)
9874 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9875 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9876 (append '(("") (" ") ("\t") ("\n"))
9877 org-emphasis-alist)
9878 "\\|") "\\)"))
9879 (pos (point))
9880 (pre nil) (post nil)
9881 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9882 (cond
9883 ;; First check if there are any special search functions
9884 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9885 ;; Now try the builtin stuff
9886 ((and (equal (string-to-char s0) ?#)
9887 (> (length s0) 1)
9888 (save-excursion
9889 (goto-char (point-min))
9890 (and
9891 (re-search-forward
9892 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9893 (setq type 'dedicated
9894 pos (match-beginning 0))))
9895 ;; There is an exact target for this
9896 (goto-char pos)
9897 (org-back-to-heading t)))
9898 ((save-excursion
9899 (goto-char (point-min))
9900 (and
9901 (re-search-forward
9902 (concat "<<" (regexp-quote s0) ">>") nil t)
9903 (setq type 'dedicated
9904 pos (match-beginning 0))))
9905 ;; There is an exact target for this
9906 (goto-char pos))
9907 ((save-excursion
9908 (goto-char (point-min))
9909 (and
9910 (re-search-forward
9911 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9912 (setq type 'dedicated pos (match-beginning 0))))
9913 ;; Found an invisible target.
9914 (goto-char pos))
9915 ((save-excursion
9916 (goto-char (point-min))
9917 (and
9918 (re-search-forward
9919 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9920 (setq type 'dedicated pos (match-beginning 0))))
9921 ;; Found an element with a matching #+name affiliated keyword.
9922 (goto-char pos))
9923 ((and (string-match "^(\\(.*\\))$" s0)
9924 (save-excursion
9925 (goto-char (point-min))
9926 (and
9927 (re-search-forward
9928 (concat "[^[]" (regexp-quote
9929 (format org-coderef-label-format
9930 (match-string 1 s0))))
9931 nil t)
9932 (setq type 'dedicated
9933 pos (1+ (match-beginning 0))))))
9934 ;; There is a coderef target for this
9935 (goto-char pos))
9936 ((string-match "^/\\(.*\\)/$" s)
9937 ;; A regular expression
9938 (cond
9939 ((eq major-mode 'org-mode)
9940 (org-occur (match-string 1 s)))
9941 ;;((eq major-mode 'dired-mode)
9942 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9943 (t (org-do-occur (match-string 1 s)))))
9944 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9945 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9946 (goto-char (point-min))
9947 (cond
9948 ((let (case-fold-search)
9949 (re-search-forward (format org-complex-heading-regexp-format
9950 (regexp-quote s))
9951 nil t))
9952 ;; OK, found a match
9953 (setq type 'dedicated)
9954 (goto-char (match-beginning 0)))
9955 ((and (not org-link-search-inhibit-query)
9956 (eq org-link-search-must-match-exact-headline 'query-to-create)
9957 (y-or-n-p "No match - create this as a new heading? "))
9958 (goto-char (point-max))
9959 (or (bolp) (newline))
9960 (insert "* " s "\n")
9961 (beginning-of-line 0))
9963 (goto-char pos)
9964 (error "No match"))))
9966 ;; A normal search string
9967 (when (equal (string-to-char s) ?*)
9968 ;; Anchor on headlines, post may include tags.
9969 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9970 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9971 s (substring s 1)))
9972 (remove-text-properties
9973 0 (length s)
9974 '(face nil mouse-face nil keymap nil fontified nil) s)
9975 ;; Make a series of regular expressions to find a match
9976 (setq words (org-split-string s "[ \n\r\t]+")
9978 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9979 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9980 "\\)" markers)
9981 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9982 re2a (concat "[ \t\r\n]" re2a_)
9983 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9984 re4 (concat "[^a-zA-Z_]" re4_)
9986 re1 (concat pre re2 post)
9987 re3 (concat pre (if pre re4_ re4) post)
9988 re5 (concat pre ".*" re4)
9989 re2 (concat pre re2)
9990 re2a (concat pre (if pre re2a_ re2a))
9991 re4 (concat pre (if pre re4_ re4))
9992 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9993 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9994 re5 "\\)"
9996 (cond
9997 ((eq type 'org-occur) (org-occur reall))
9998 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9999 (t (goto-char (point-min))
10000 (setq type 'fuzzy)
10001 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10002 (org-search-not-self 1 re1 nil t)
10003 (org-search-not-self 1 re2 nil t)
10004 (org-search-not-self 1 re2a nil t)
10005 (org-search-not-self 1 re3 nil t)
10006 (org-search-not-self 1 re4 nil t)
10007 (org-search-not-self 1 re5 nil t)
10009 (goto-char (match-beginning 1))
10010 (goto-char pos)
10011 (error "No match"))))))
10012 (and (eq major-mode 'org-mode)
10013 (not stealth)
10014 (org-show-context 'link-search))
10015 type))
10017 (defun org-search-not-self (group &rest args)
10018 "Execute `re-search-forward', but only accept matches that do not
10019 enclose the position of `org-open-link-marker'."
10020 (let ((m org-open-link-marker))
10021 (catch 'exit
10022 (while (apply 're-search-forward args)
10023 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10024 (goto-char (match-end group))
10025 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10026 (> (match-beginning 0) (marker-position m))
10027 (< (match-end 0) (marker-position m)))
10028 (save-match-data
10029 (or (not (org-in-regexp
10030 org-bracket-link-analytic-regexp 1))
10031 (not (match-end 4)) ; no description
10032 (and (<= (match-beginning 4) (point))
10033 (>= (match-end 4) (point))))))
10034 (throw 'exit (point))))))))
10036 (defun org-get-buffer-for-internal-link (buffer)
10037 "Return a buffer to be used for displaying the link target of internal links."
10038 (cond
10039 ((not org-display-internal-link-with-indirect-buffer)
10040 buffer)
10041 ((string-match "(Clone)$" (buffer-name buffer))
10042 (message "Buffer is already a clone, not making another one")
10043 ;; we also do not modify visibility in this case
10044 buffer)
10045 (t ; make a new indirect buffer for displaying the link
10046 (let* ((bn (buffer-name buffer))
10047 (ibn (concat bn "(Clone)"))
10048 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10049 (with-current-buffer ib (org-overview))
10050 ib))))
10052 (defun org-do-occur (regexp &optional cleanup)
10053 "Call the Emacs command `occur'.
10054 If CLEANUP is non-nil, remove the printout of the regular expression
10055 in the *Occur* buffer. This is useful if the regex is long and not useful
10056 to read."
10057 (occur regexp)
10058 (when cleanup
10059 (let ((cwin (selected-window)) win beg end)
10060 (when (setq win (get-buffer-window "*Occur*"))
10061 (select-window win))
10062 (goto-char (point-min))
10063 (when (re-search-forward "match[a-z]+" nil t)
10064 (setq beg (match-end 0))
10065 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10066 (setq end (1- (match-beginning 0)))))
10067 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10068 (goto-char (point-min))
10069 (select-window cwin))))
10071 ;;; The mark ring for links jumps
10073 (defvar org-mark-ring nil
10074 "Mark ring for positions before jumps in Org-mode.")
10075 (defvar org-mark-ring-last-goto nil
10076 "Last position in the mark ring used to go back.")
10077 ;; Fill and close the ring
10078 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10079 (loop for i from 1 to org-mark-ring-length do
10080 (push (make-marker) org-mark-ring))
10081 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10082 org-mark-ring)
10084 (defun org-mark-ring-push (&optional pos buffer)
10085 "Put the current position or POS into the mark ring and rotate it."
10086 (interactive)
10087 (setq pos (or pos (point)))
10088 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10089 (move-marker (car org-mark-ring)
10090 (or pos (point))
10091 (or buffer (current-buffer)))
10092 (message "%s"
10093 (substitute-command-keys
10094 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10096 (defun org-mark-ring-goto (&optional n)
10097 "Jump to the previous position in the mark ring.
10098 With prefix arg N, jump back that many stored positions. When
10099 called several times in succession, walk through the entire ring.
10100 Org-mode commands jumping to a different position in the current file,
10101 or to another Org-mode file, automatically push the old position
10102 onto the ring."
10103 (interactive "p")
10104 (let (p m)
10105 (if (eq last-command this-command)
10106 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10107 (setq p org-mark-ring))
10108 (setq org-mark-ring-last-goto p)
10109 (setq m (car p))
10110 (org-pop-to-buffer-same-window (marker-buffer m))
10111 (goto-char m)
10112 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10114 (defun org-remove-angle-brackets (s)
10115 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10116 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10118 (defun org-add-angle-brackets (s)
10119 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10120 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10122 (defun org-remove-double-quotes (s)
10123 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10124 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10127 ;;; Following specific links
10129 (defun org-follow-timestamp-link ()
10130 (cond
10131 ((org-at-date-range-p t)
10132 (let ((org-agenda-start-on-weekday)
10133 (t1 (match-string 1))
10134 (t2 (match-string 2)))
10135 (setq t1 (time-to-days (org-time-string-to-time t1))
10136 t2 (time-to-days (org-time-string-to-time t2)))
10137 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10138 ((org-at-timestamp-p t)
10139 (org-agenda-list nil (time-to-days (org-time-string-to-time
10140 (substring (match-string 1) 0 10)))
10142 (t (error "This should not happen"))))
10145 ;;; Following file links
10146 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10147 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10148 (declare-function mailcap-mime-info
10149 "mailcap" (string &optional request no-decode))
10150 (defvar org-wait nil)
10151 (defun org-open-file (path &optional in-emacs line search)
10152 "Open the file at PATH.
10153 First, this expands any special file name abbreviations. Then the
10154 configuration variable `org-file-apps' is checked if it contains an
10155 entry for this file type, and if yes, the corresponding command is launched.
10157 If no application is found, Emacs simply visits the file.
10159 With optional prefix argument IN-EMACS, Emacs will visit the file.
10160 With a double \\[universal-argument] \\[universal-argument] \
10161 prefix arg, Org tries to avoid opening in Emacs
10162 and to use an external application to visit the file.
10164 Optional LINE specifies a line to go to, optional SEARCH a string
10165 to search for. If LINE or SEARCH is given, the file will be
10166 opened in Emacs, unless an entry from org-file-apps that makes
10167 use of groups in a regexp matches.
10169 If you want to change the way frames are used when following a
10170 link, please customize `org-link-frame-setup'.
10172 If the file does not exist, an error is thrown."
10173 (let* ((file (if (equal path "")
10174 buffer-file-name
10175 (substitute-in-file-name (expand-file-name path))))
10176 (file-apps (append org-file-apps (org-default-apps)))
10177 (apps (org-remove-if
10178 'org-file-apps-entry-match-against-dlink-p file-apps))
10179 (apps-dlink (org-remove-if-not
10180 'org-file-apps-entry-match-against-dlink-p file-apps))
10181 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10182 (dirp (if remp nil (file-directory-p file)))
10183 (file (if (and dirp org-open-directory-means-index-dot-org)
10184 (concat (file-name-as-directory file) "index.org")
10185 file))
10186 (a-m-a-p (assq 'auto-mode apps))
10187 (dfile (downcase file))
10188 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10189 (link (cond ((and (eq line nil)
10190 (eq search nil))
10191 file)
10192 (line
10193 (concat file "::" (number-to-string line)))
10194 (search
10195 (concat file "::" search))))
10196 (dlink (downcase link))
10197 (old-buffer (current-buffer))
10198 (old-pos (point))
10199 (old-mode major-mode)
10200 ext cmd link-match-data)
10201 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10202 (setq ext (match-string 1 dfile))
10203 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10204 (setq ext (match-string 1 dfile))))
10205 (cond
10206 ((member in-emacs '((16) system))
10207 (setq cmd (cdr (assoc 'system apps))))
10208 (in-emacs (setq cmd 'emacs))
10210 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10211 (and dirp (cdr (assoc 'directory apps)))
10212 ; first, try matching against apps-dlink
10213 ; if we get a match here, store the match data for later
10214 (let ((match (assoc-default dlink apps-dlink
10215 'string-match)))
10216 (if match
10217 (progn (setq link-match-data (match-data))
10218 match)
10219 (progn (setq in-emacs (or in-emacs line search))
10220 nil))) ; if we have no match in apps-dlink,
10221 ; always open the file in emacs if line or search
10222 ; is given (for backwards compatibility)
10223 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10224 'string-match)
10225 (cdr (assoc ext apps))
10226 (cdr (assoc t apps))))))
10227 (when (eq cmd 'system)
10228 (setq cmd (cdr (assoc 'system apps))))
10229 (when (eq cmd 'default)
10230 (setq cmd (cdr (assoc t apps))))
10231 (when (eq cmd 'mailcap)
10232 (require 'mailcap)
10233 (mailcap-parse-mailcaps)
10234 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10235 (command (mailcap-mime-info mime-type)))
10236 (if (stringp command)
10237 (setq cmd command)
10238 (setq cmd 'emacs))))
10239 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10240 (not (file-exists-p file))
10241 (not org-open-non-existing-files))
10242 (error "No such file: %s" file))
10243 (cond
10244 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10245 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10246 (while (string-match "['\"]%s['\"]" cmd)
10247 (setq cmd (replace-match "%s" t t cmd)))
10248 (while (string-match "%s" cmd)
10249 (setq cmd (replace-match
10250 (save-match-data
10251 (shell-quote-argument
10252 (convert-standard-filename file)))
10253 t t cmd)))
10255 ;; Replace "%1", "%2" etc. in command with group matches from regex
10256 (save-match-data
10257 (let ((match-index 1)
10258 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10259 (set-match-data link-match-data)
10260 (while (<= match-index number-of-groups)
10261 (let ((regex (concat "%" (number-to-string match-index)))
10262 (replace-with (match-string match-index dlink)))
10263 (while (string-match regex cmd)
10264 (setq cmd (replace-match replace-with t t cmd))))
10265 (setq match-index (+ match-index 1)))))
10267 (save-window-excursion
10268 (start-process-shell-command cmd nil cmd)
10269 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10271 ((or (stringp cmd)
10272 (eq cmd 'emacs))
10273 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10274 (widen)
10275 (if line (org-goto-line line)
10276 (if search (org-link-search search))))
10277 ((consp cmd)
10278 (let ((file (convert-standard-filename file)))
10279 (save-match-data
10280 (set-match-data link-match-data)
10281 (eval cmd))))
10282 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10283 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10284 (or (not (equal old-buffer (current-buffer)))
10285 (not (equal old-pos (point))))
10286 (org-mark-ring-push old-pos old-buffer))))
10288 (defun org-file-apps-entry-match-against-dlink-p (entry)
10289 "This function returns non-nil if `entry' uses a regular
10290 expression which should be matched against the whole link by
10291 org-open-file.
10293 It assumes that is the case when the entry uses a regular
10294 expression which has at least one grouping construct and the
10295 action is either a lisp form or a command string containing
10296 '%1', i.e. using at least one subexpression match as a
10297 parameter."
10298 (let ((selector (car entry))
10299 (action (cdr entry)))
10300 (if (stringp selector)
10301 (and (> (regexp-opt-depth selector) 0)
10302 (or (and (stringp action)
10303 (string-match "%[0-9]" action))
10304 (consp action)))
10305 nil)))
10307 (defun org-default-apps ()
10308 "Return the default applications for this operating system."
10309 (cond
10310 ((eq system-type 'darwin)
10311 org-file-apps-defaults-macosx)
10312 ((eq system-type 'windows-nt)
10313 org-file-apps-defaults-windowsnt)
10314 (t org-file-apps-defaults-gnu)))
10316 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10317 "Convert extensions to regular expressions in the cars of LIST.
10318 Also, weed out any non-string entries, because the return value is used
10319 only for regexp matching.
10320 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10321 point to the symbol `emacs', indicating that the file should
10322 be opened in Emacs."
10323 (append
10324 (delq nil
10325 (mapcar (lambda (x)
10326 (if (not (stringp (car x)))
10328 (if (string-match "\\W" (car x))
10330 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10331 list))
10332 (if add-auto-mode
10333 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10335 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10336 (defun org-file-remote-p (file)
10337 "Test whether FILE specifies a location on a remote system.
10338 Return non-nil if the location is indeed remote.
10340 For example, the filename \"/user@host:/foo\" specifies a location
10341 on the system \"/user@host:\"."
10342 (cond ((fboundp 'file-remote-p)
10343 (file-remote-p file))
10344 ((fboundp 'tramp-handle-file-remote-p)
10345 (tramp-handle-file-remote-p file))
10346 ((and (boundp 'ange-ftp-name-format)
10347 (string-match (car ange-ftp-name-format) file))
10349 (t nil)))
10352 ;;;; Refiling
10354 (defun org-get-org-file ()
10355 "Read a filename, with default directory `org-directory'."
10356 (let ((default (or org-default-notes-file remember-data-file)))
10357 (read-file-name (format "File name [%s]: " default)
10358 (file-name-as-directory org-directory)
10359 default)))
10361 (defun org-notes-order-reversed-p ()
10362 "Check if the current file should receive notes in reversed order."
10363 (cond
10364 ((not org-reverse-note-order) nil)
10365 ((eq t org-reverse-note-order) t)
10366 ((not (listp org-reverse-note-order)) nil)
10367 (t (catch 'exit
10368 (let ((all org-reverse-note-order)
10369 entry)
10370 (while (setq entry (pop all))
10371 (if (string-match (car entry) buffer-file-name)
10372 (throw 'exit (cdr entry))))
10373 nil)))))
10375 (defvar org-refile-target-table nil
10376 "The list of refile targets, created by `org-refile'.")
10378 (defvar org-agenda-new-buffers nil
10379 "Buffers created to visit agenda files.")
10381 (defvar org-refile-cache nil
10382 "Cache for refile targets.")
10384 (defvar org-refile-markers nil
10385 "All the markers used for caching refile locations.")
10387 (defun org-refile-marker (pos)
10388 "Get a new refile marker, but only if caching is in use."
10389 (if (not org-refile-use-cache)
10391 (let ((m (make-marker)))
10392 (move-marker m pos)
10393 (push m org-refile-markers)
10394 m)))
10396 (defun org-refile-cache-clear ()
10397 "Clear the refile cache and disable all the markers."
10398 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10399 (setq org-refile-markers nil)
10400 (setq org-refile-cache nil)
10401 (message "Refile cache has been cleared"))
10403 (defun org-refile-cache-check-set (set)
10404 "Check if all the markers in the cache still have live buffers."
10405 (let (marker)
10406 (catch 'exit
10407 (while (and set (setq marker (nth 3 (pop set))))
10408 ;; if org-refile-use-outline-path is 'file, marker may be nil
10409 (when (and marker (null (marker-buffer marker)))
10410 (message "not found") (sit-for 3)
10411 (throw 'exit nil)))
10412 t)))
10414 (defun org-refile-cache-put (set &rest identifiers)
10415 "Push the refile targets SET into the cache, under IDENTIFIERS."
10416 (let* ((key (sha1 (prin1-to-string identifiers)))
10417 (entry (assoc key org-refile-cache)))
10418 (if entry
10419 (setcdr entry set)
10420 (push (cons key set) org-refile-cache))))
10422 (defun org-refile-cache-get (&rest identifiers)
10423 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10424 (cond
10425 ((not org-refile-cache) nil)
10426 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10428 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10429 org-refile-cache))))
10430 (and set (org-refile-cache-check-set set) set)))))
10432 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10433 "Produce a table with refile targets."
10434 (let ((case-fold-search nil)
10435 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10436 (entries (or org-refile-targets '((nil . (:level . 1)))))
10437 targets tgs txt re files f desc descre fast-path-p level pos0)
10438 (message "Getting targets...")
10439 (with-current-buffer (or default-buffer (current-buffer))
10440 (while (setq entry (pop entries))
10441 (setq files (car entry) desc (cdr entry))
10442 (setq fast-path-p nil)
10443 (cond
10444 ((null files) (setq files (list (current-buffer))))
10445 ((eq files 'org-agenda-files)
10446 (setq files (org-agenda-files 'unrestricted)))
10447 ((and (symbolp files) (fboundp files))
10448 (setq files (funcall files)))
10449 ((and (symbolp files) (boundp files))
10450 (setq files (symbol-value files))))
10451 (if (stringp files) (setq files (list files)))
10452 (cond
10453 ((eq (car desc) :tag)
10454 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10455 ((eq (car desc) :todo)
10456 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10457 ((eq (car desc) :regexp)
10458 (setq descre (cdr desc)))
10459 ((eq (car desc) :level)
10460 (setq descre (concat "^\\*\\{" (number-to-string
10461 (if org-odd-levels-only
10462 (1- (* 2 (cdr desc)))
10463 (cdr desc)))
10464 "\\}[ \t]")))
10465 ((eq (car desc) :maxlevel)
10466 (setq fast-path-p t)
10467 (setq descre (concat "^\\*\\{1," (number-to-string
10468 (if org-odd-levels-only
10469 (1- (* 2 (cdr desc)))
10470 (cdr desc)))
10471 "\\}[ \t]")))
10472 (t (error "Bad refiling target description %s" desc)))
10473 (while (setq f (pop files))
10474 (with-current-buffer
10475 (if (bufferp f) f (org-get-agenda-file-buffer f))
10477 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10478 (progn
10479 (if (bufferp f) (setq f (buffer-file-name
10480 (buffer-base-buffer f))))
10481 (setq f (and f (expand-file-name f)))
10482 (if (eq org-refile-use-outline-path 'file)
10483 (push (list (file-name-nondirectory f) f nil nil) tgs))
10484 (save-excursion
10485 (save-restriction
10486 (widen)
10487 (goto-char (point-min))
10488 (while (re-search-forward descre nil t)
10489 (goto-char (setq pos0 (point-at-bol)))
10490 (catch 'next
10491 (when org-refile-target-verify-function
10492 (save-match-data
10493 (or (funcall org-refile-target-verify-function)
10494 (throw 'next t))))
10495 (when (and (looking-at org-complex-heading-regexp)
10496 (not (member (match-string 4) excluded-entries))
10497 (match-string 4))
10498 (setq level (org-reduced-level
10499 (- (match-end 1) (match-beginning 1)))
10500 txt (org-link-display-format (match-string 4))
10501 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10502 re (format org-complex-heading-regexp-format
10503 (regexp-quote (match-string 4))))
10504 (when org-refile-use-outline-path
10505 (setq txt (mapconcat
10506 'org-protect-slash
10507 (append
10508 (if (eq org-refile-use-outline-path
10509 'file)
10510 (list (file-name-nondirectory
10511 (buffer-file-name
10512 (buffer-base-buffer))))
10513 (if (eq org-refile-use-outline-path
10514 'full-file-path)
10515 (list (buffer-file-name
10516 (buffer-base-buffer)))))
10517 (org-get-outline-path fast-path-p
10518 level txt)
10519 (list txt))
10520 "/")))
10521 (push (list txt f re (org-refile-marker (point)))
10522 tgs)))
10523 (when (= (point) pos0)
10524 ;; verification function has not moved point
10525 (goto-char (point-at-eol))))))))
10526 (when org-refile-use-cache
10527 (org-refile-cache-put tgs (buffer-file-name) descre))
10528 (setq targets (append tgs targets))
10529 ))))
10530 (message "Getting targets...done")
10531 (nreverse targets)))
10533 (defun org-protect-slash (s)
10534 (while (string-match "/" s)
10535 (setq s (replace-match "\\" t t s)))
10538 (defvar org-olpa (make-vector 20 nil))
10540 (defun org-get-outline-path (&optional fastp level heading)
10541 "Return the outline path to the current entry, as a list.
10543 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10544 routine which makes outline path derivations for an entire file,
10545 avoiding backtracing. Refile target collection makes use of that."
10546 (if fastp
10547 (progn
10548 (if (> level 19)
10549 (error "Outline path failure, more than 19 levels"))
10550 (loop for i from level upto 19 do
10551 (aset org-olpa i nil))
10552 (prog1
10553 (delq nil (append org-olpa nil))
10554 (aset org-olpa level heading)))
10555 (let (rtn case-fold-search)
10556 (save-excursion
10557 (save-restriction
10558 (widen)
10559 (while (org-up-heading-safe)
10560 (when (looking-at org-complex-heading-regexp)
10561 (push (org-match-string-no-properties 4) rtn)))
10562 rtn)))))
10564 (defun org-format-outline-path (path &optional width prefix)
10565 "Format the outline path PATH for display.
10566 Width is the maximum number of characters that is available.
10567 Prefix is a prefix to be included in the returned string,
10568 such as the file name."
10569 (setq width (or width 79))
10570 (if prefix (setq width (- width (length prefix))))
10571 (if (not path)
10572 (or prefix "")
10573 (let* ((nsteps (length path))
10574 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10575 (maxwidth (if (<= total-width width)
10576 10000 ;; everything fits
10577 ;; we need to shorten the level headings
10578 (/ (- width nsteps) nsteps)))
10579 (org-odd-levels-only nil)
10580 (n 0)
10581 (total (1+ (length prefix))))
10582 (setq maxwidth (max maxwidth 10))
10583 (concat prefix
10584 (mapconcat
10585 (lambda (h)
10586 (setq n (1+ n))
10587 (if (and (= n nsteps) (< maxwidth 10000))
10588 (setq maxwidth (- total-width total)))
10589 (if (< (length h) maxwidth)
10590 (progn (setq total (+ total (length h) 1)) h)
10591 (setq h (substring h 0 (- maxwidth 2))
10592 total (+ total maxwidth 1))
10593 (if (string-match "[ \t]+\\'" h)
10594 (setq h (substring h 0 (match-beginning 0))))
10595 (setq h (concat h "..")))
10596 (org-add-props h nil 'face
10597 (nth (% (1- n) org-n-level-faces)
10598 org-level-faces))
10600 path "/")))))
10602 (defun org-display-outline-path (&optional file current)
10603 "Display the current outline path in the echo area."
10604 (interactive "P")
10605 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10606 (case-fold-search nil)
10607 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10608 (if current (setq path (append path
10609 (save-excursion
10610 (org-back-to-heading t)
10611 (if (looking-at org-complex-heading-regexp)
10612 (list (match-string 4)))))))
10613 (message "%s"
10614 (org-format-outline-path
10615 path
10616 (1- (frame-width))
10617 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10619 (defvar org-refile-history nil
10620 "History for refiling operations.")
10622 (defvar org-after-refile-insert-hook nil
10623 "Hook run after `org-refile' has inserted its stuff at the new location.
10624 Note that this is still *before* the stuff will be removed from
10625 the *old* location.")
10627 (defvar org-capture-last-stored-marker)
10628 (defun org-refile (&optional goto default-buffer rfloc)
10629 "Move the entry or entries at point to another heading.
10630 The list of target headings is compiled using the information in
10631 `org-refile-targets', which see.
10633 At the target location, the entry is filed as a subitem of the target
10634 heading. Depending on `org-reverse-note-order', the new subitem will
10635 either be the first or the last subitem.
10637 If there is an active region, all entries in that region will be moved.
10638 However, the region must fulfill the requirement that the first heading
10639 is the first one sets the top-level of the moved text - at most siblings
10640 below it are allowed.
10642 With prefix arg GOTO, the command will only visit the target location
10643 and not actually move anything.
10645 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10646 go to the location where the last refiling operation has put the subtree.
10647 With a prefix argument of `2', refile to the running clock.
10649 RFLOC can be a refile location obtained in a different way.
10651 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10653 If you are using target caching (see `org-refile-use-cache'),
10654 You have to clear the target cache in order to find new targets.
10655 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10656 prefix argument (`C-u C-u C-u C-c C-w')."
10658 (interactive "P")
10659 (if (member goto '(0 (64)))
10660 (org-refile-cache-clear)
10661 (let* ((cbuf (current-buffer))
10662 (regionp (org-region-active-p))
10663 (region-start (and regionp (region-beginning)))
10664 (region-end (and regionp (region-end)))
10665 (region-length (and regionp (- region-end region-start)))
10666 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10667 pos it nbuf file re level reversed)
10668 (setq last-command nil)
10669 (when regionp
10670 (goto-char region-start)
10671 (or (bolp) (goto-char (point-at-bol)))
10672 (setq region-start (point))
10673 (unless (or (org-kill-is-subtree-p
10674 (buffer-substring region-start region-end))
10675 (prog1 org-refile-active-region-within-subtree
10676 (org-toggle-heading)))
10677 (error "The region is not a (sequence of) subtree(s)")))
10678 (if (equal goto '(16))
10679 (org-refile-goto-last-stored)
10680 (when (or
10681 (and (equal goto 2)
10682 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10683 (prog1
10684 (setq it (list (or org-clock-heading "running clock")
10685 (buffer-file-name
10686 (marker-buffer org-clock-hd-marker))
10688 (marker-position org-clock-hd-marker)))
10689 (setq goto nil)))
10690 (setq it (or rfloc
10691 (let (heading-text)
10692 (save-excursion
10693 (unless goto
10694 (org-back-to-heading t)
10695 (setq heading-text
10696 (nth 4 (org-heading-components))))
10697 (org-refile-get-location
10698 (cond (goto "Goto")
10699 (regionp "Refile region to")
10700 (t (concat "Refile subtree \""
10701 heading-text "\" to")))
10702 default-buffer
10703 (and (not (equal '(4) goto))
10704 org-refile-allow-creating-parent-nodes)
10705 goto))))))
10706 (setq file (nth 1 it)
10707 re (nth 2 it)
10708 pos (nth 3 it))
10709 (if (and (not goto)
10711 (equal (buffer-file-name) file)
10712 (if regionp
10713 (and (>= pos region-start)
10714 (<= pos region-end))
10715 (and (>= pos (point))
10716 (< pos (save-excursion
10717 (org-end-of-subtree t t))))))
10718 (error "Cannot refile to position inside the tree or region"))
10720 (setq nbuf (or (find-buffer-visiting file)
10721 (find-file-noselect file)))
10722 (if goto
10723 (progn
10724 (org-pop-to-buffer-same-window nbuf)
10725 (goto-char pos)
10726 (org-show-context 'org-goto))
10727 (if regionp
10728 (progn
10729 (org-kill-new (buffer-substring region-start region-end))
10730 (org-save-markers-in-region region-start region-end))
10731 (org-copy-subtree 1 nil t))
10732 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10733 (find-file-noselect file)))
10734 (setq reversed (org-notes-order-reversed-p))
10735 (save-excursion
10736 (save-restriction
10737 (widen)
10738 (if pos
10739 (progn
10740 (goto-char pos)
10741 (looking-at org-outline-regexp)
10742 (setq level (org-get-valid-level (funcall outline-level) 1))
10743 (goto-char
10744 (if reversed
10745 (or (outline-next-heading) (point-max))
10746 (or (save-excursion (org-get-next-sibling))
10747 (org-end-of-subtree t t)
10748 (point-max)))))
10749 (setq level 1)
10750 (if (not reversed)
10751 (goto-char (point-max))
10752 (goto-char (point-min))
10753 (or (outline-next-heading) (goto-char (point-max)))))
10754 (if (not (bolp)) (newline))
10755 (org-paste-subtree level)
10756 (when org-log-refile
10757 (org-add-log-setup 'refile nil nil 'findpos
10758 org-log-refile)
10759 (unless (eq org-log-refile 'note)
10760 (save-excursion (org-add-log-note))))
10761 (and org-auto-align-tags (org-set-tags nil t))
10762 (bookmark-set "org-refile-last-stored")
10763 ;; If we are refiling for capture, make sure that the
10764 ;; last-capture pointers point here
10765 (when (org-bound-and-true-p org-refile-for-capture)
10766 (bookmark-set "org-capture-last-stored-marker")
10767 (move-marker org-capture-last-stored-marker (point)))
10768 (if (fboundp 'deactivate-mark) (deactivate-mark))
10769 (run-hooks 'org-after-refile-insert-hook))))
10770 (if regionp
10771 (delete-region (point) (+ (point) region-length))
10772 (org-cut-subtree))
10773 (when (featurep 'org-inlinetask)
10774 (org-inlinetask-remove-END-maybe))
10775 (setq org-markers-to-move nil)
10776 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10778 (defun org-refile-goto-last-stored ()
10779 "Go to the location where the last refile was stored."
10780 (interactive)
10781 (bookmark-jump "org-refile-last-stored")
10782 (message "This is the location of the last refile"))
10784 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10785 no-exclude)
10786 "Prompt the user for a refile location, using PROMPT.
10787 PROMPT should not be suffixed with a colon and a space, because
10788 this function appends the default value from
10789 `org-refile-history' automatically, if that is not empty.
10790 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10791 this is used for the GOTO interface."
10792 (let ((org-refile-targets org-refile-targets)
10793 (org-refile-use-outline-path org-refile-use-outline-path)
10794 excluded-entries)
10795 (when (and (eq major-mode 'org-mode)
10796 (not org-refile-use-cache)
10797 (not no-exclude))
10798 (org-map-tree
10799 (lambda()
10800 (setq excluded-entries
10801 (append excluded-entries (list (org-get-heading t t)))))))
10802 (setq org-refile-target-table
10803 (org-refile-get-targets default-buffer excluded-entries)))
10804 (unless org-refile-target-table
10805 (error "No refile targets"))
10806 (let* ((prompt (concat prompt
10807 (and (car org-refile-history)
10808 (concat " (default " (car org-refile-history) ")"))
10809 ": "))
10810 (cbuf (current-buffer))
10811 (partial-completion-mode nil)
10812 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10813 (cfunc (if (and org-refile-use-outline-path
10814 org-outline-path-complete-in-steps)
10815 'org-olpath-completing-read
10816 'org-icompleting-read))
10817 (extra (if org-refile-use-outline-path "/" ""))
10818 (filename (and cfn (expand-file-name cfn)))
10819 (tbl (mapcar
10820 (lambda (x)
10821 (if (and (not (member org-refile-use-outline-path
10822 '(file full-file-path)))
10823 (not (equal filename (nth 1 x))))
10824 (cons (concat (car x) extra " ("
10825 (file-name-nondirectory (nth 1 x)) ")")
10826 (cdr x))
10827 (cons (concat (car x) extra) (cdr x))))
10828 org-refile-target-table))
10829 (completion-ignore-case t)
10830 pa answ parent-target child parent old-hist)
10831 (setq old-hist org-refile-history)
10832 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10833 nil 'org-refile-history (car org-refile-history)))
10834 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10835 (org-refile-check-position pa)
10836 (if pa
10837 (progn
10838 (when (or (not org-refile-history)
10839 (not (eq old-hist org-refile-history))
10840 (not (equal (car pa) (car org-refile-history))))
10841 (setq org-refile-history
10842 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10843 org-refile-history
10844 (cdr org-refile-history))))
10845 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10846 (pop org-refile-history)))
10848 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10849 (progn
10850 (setq parent (match-string 1 answ)
10851 child (match-string 2 answ))
10852 (setq parent-target (or (assoc parent tbl)
10853 (assoc (concat parent "/") tbl)))
10854 (when (and parent-target
10855 (or (eq new-nodes t)
10856 (and (eq new-nodes 'confirm)
10857 (y-or-n-p (format "Create new node \"%s\"? "
10858 child)))))
10859 (org-refile-new-child parent-target child)))
10860 (error "Invalid target location")))))
10862 (declare-function org-string-nw-p "org-macs.el" (s))
10863 (defun org-refile-check-position (refile-pointer)
10864 "Check if the refile pointer matches the readline to which it points."
10865 (let* ((file (nth 1 refile-pointer))
10866 (re (nth 2 refile-pointer))
10867 (pos (nth 3 refile-pointer))
10868 buffer)
10869 (when (org-string-nw-p re)
10870 (setq buffer (if (markerp pos)
10871 (marker-buffer pos)
10872 (or (find-buffer-visiting file)
10873 (find-file-noselect file))))
10874 (with-current-buffer buffer
10875 (save-excursion
10876 (save-restriction
10877 (widen)
10878 (goto-char pos)
10879 (beginning-of-line 1)
10880 (unless (org-looking-at-p re)
10881 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10883 (defun org-refile-new-child (parent-target child)
10884 "Use refile target PARENT-TARGET to add new CHILD below it."
10885 (unless parent-target
10886 (error "Cannot find parent for new node"))
10887 (let ((file (nth 1 parent-target))
10888 (pos (nth 3 parent-target))
10889 level)
10890 (with-current-buffer (or (find-buffer-visiting file)
10891 (find-file-noselect file))
10892 (save-excursion
10893 (save-restriction
10894 (widen)
10895 (if pos
10896 (goto-char pos)
10897 (goto-char (point-max))
10898 (if (not (bolp)) (newline)))
10899 (when (looking-at org-outline-regexp)
10900 (setq level (funcall outline-level))
10901 (org-end-of-subtree t t))
10902 (org-back-over-empty-lines)
10903 (insert "\n" (make-string
10904 (if pos (org-get-valid-level level 1) 1) ?*)
10905 " " child "\n")
10906 (beginning-of-line 0)
10907 (list (concat (car parent-target) "/" child) file "" (point)))))))
10909 (defun org-olpath-completing-read (prompt collection &rest args)
10910 "Read an outline path like a file name."
10911 (let ((thetable collection)
10912 (org-completion-use-ido nil) ; does not work with ido.
10913 (org-completion-use-iswitchb nil)) ; or iswitchb
10914 (apply
10915 'org-icompleting-read prompt
10916 (lambda (string predicate &optional flag)
10917 (let (rtn r f (l (length string)))
10918 (cond
10919 ((eq flag nil)
10920 ;; try completion
10921 (try-completion string thetable))
10922 ((eq flag t)
10923 ;; all-completions
10924 (setq rtn (all-completions string thetable predicate))
10925 (mapcar
10926 (lambda (x)
10927 (setq r (substring x l))
10928 (if (string-match " ([^)]*)$" x)
10929 (setq f (match-string 0 x))
10930 (setq f ""))
10931 (if (string-match "/" r)
10932 (concat string (substring r 0 (match-end 0)) f)
10934 rtn))
10935 ((eq flag 'lambda)
10936 ;; exact match?
10937 (assoc string thetable)))
10939 args)))
10941 ;;;; Dynamic blocks
10943 (defun org-find-dblock (name)
10944 "Find the first dynamic block with name NAME in the buffer.
10945 If not found, stay at current position and return nil."
10946 (let (pos)
10947 (save-excursion
10948 (goto-char (point-min))
10949 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10950 nil t)
10951 (match-beginning 0))))
10952 (if pos (goto-char pos))
10953 pos))
10955 (defconst org-dblock-start-re
10956 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10957 "Matches the start line of a dynamic block, with parameters.")
10959 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10960 "Matches the end of a dynamic block.")
10962 (defun org-create-dblock (plist)
10963 "Create a dynamic block section, with parameters taken from PLIST.
10964 PLIST must contain a :name entry which is used as name of the block."
10965 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10966 (end-of-line 1)
10967 (newline))
10968 (let ((col (current-column))
10969 (name (plist-get plist :name)))
10970 (insert "#+BEGIN: " name)
10971 (while plist
10972 (if (eq (car plist) :name)
10973 (setq plist (cddr plist))
10974 (insert " " (prin1-to-string (pop plist)))))
10975 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10976 (beginning-of-line -2)))
10978 (defun org-prepare-dblock ()
10979 "Prepare dynamic block for refresh.
10980 This empties the block, puts the cursor at the insert position and returns
10981 the property list including an extra property :name with the block name."
10982 (unless (looking-at org-dblock-start-re)
10983 (error "Not at a dynamic block"))
10984 (let* ((begdel (1+ (match-end 0)))
10985 (name (org-no-properties (match-string 1)))
10986 (params (append (list :name name)
10987 (read (concat "(" (match-string 3) ")")))))
10988 (save-excursion
10989 (beginning-of-line 1)
10990 (skip-chars-forward " \t")
10991 (setq params (plist-put params :indentation-column (current-column))))
10992 (unless (re-search-forward org-dblock-end-re nil t)
10993 (error "Dynamic block not terminated"))
10994 (setq params
10995 (append params
10996 (list :content (buffer-substring
10997 begdel (match-beginning 0)))))
10998 (delete-region begdel (match-beginning 0))
10999 (goto-char begdel)
11000 (open-line 1)
11001 params))
11003 (defun org-map-dblocks (&optional command)
11004 "Apply COMMAND to all dynamic blocks in the current buffer.
11005 If COMMAND is not given, use `org-update-dblock'."
11006 (let ((cmd (or command 'org-update-dblock)))
11007 (save-excursion
11008 (goto-char (point-min))
11009 (while (re-search-forward org-dblock-start-re nil t)
11010 (goto-char (match-beginning 0))
11011 (save-excursion
11012 (condition-case nil
11013 (funcall cmd)
11014 (error (message "Error during update of dynamic block"))))
11015 (unless (re-search-forward org-dblock-end-re nil t)
11016 (error "Dynamic block not terminated"))))))
11018 (defun org-dblock-update (&optional arg)
11019 "User command for updating dynamic blocks.
11020 Update the dynamic block at point. With prefix ARG, update all dynamic
11021 blocks in the buffer."
11022 (interactive "P")
11023 (if arg
11024 (org-update-all-dblocks)
11025 (or (looking-at org-dblock-start-re)
11026 (org-beginning-of-dblock))
11027 (org-update-dblock)))
11029 (defun org-update-dblock ()
11030 "Update the dynamic block at point.
11031 This means to empty the block, parse for parameters and then call
11032 the correct writing function."
11033 (interactive)
11034 (save-window-excursion
11035 (let* ((pos (point))
11036 (line (org-current-line))
11037 (params (org-prepare-dblock))
11038 (name (plist-get params :name))
11039 (indent (plist-get params :indentation-column))
11040 (cmd (intern (concat "org-dblock-write:" name))))
11041 (message "Updating dynamic block `%s' at line %d..." name line)
11042 (funcall cmd params)
11043 (message "Updating dynamic block `%s' at line %d...done" name line)
11044 (goto-char pos)
11045 (when (and indent (> indent 0))
11046 (setq indent (make-string indent ?\ ))
11047 (save-excursion
11048 (org-beginning-of-dblock)
11049 (forward-line 1)
11050 (while (not (looking-at org-dblock-end-re))
11051 (insert indent)
11052 (beginning-of-line 2))
11053 (when (looking-at org-dblock-end-re)
11054 (and (looking-at "[ \t]+")
11055 (replace-match ""))
11056 (insert indent)))))))
11058 (defun org-beginning-of-dblock ()
11059 "Find the beginning of the dynamic block at point.
11060 Error if there is no such block at point."
11061 (let ((pos (point))
11062 beg)
11063 (end-of-line 1)
11064 (if (and (re-search-backward org-dblock-start-re nil t)
11065 (setq beg (match-beginning 0))
11066 (re-search-forward org-dblock-end-re nil t)
11067 (> (match-end 0) pos))
11068 (goto-char beg)
11069 (goto-char pos)
11070 (error "Not in a dynamic block"))))
11072 (defun org-update-all-dblocks ()
11073 "Update all dynamic blocks in the buffer.
11074 This function can be used in a hook."
11075 (interactive)
11076 (when (eq major-mode 'org-mode)
11077 (org-map-dblocks 'org-update-dblock)))
11080 ;;;; Completion
11082 (defconst org-additional-option-like-keywords
11083 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11084 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11085 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11086 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11087 "BEGIN:" "END:"
11088 "ORGTBL" "TBLFM:" "TBLNAME:"
11089 "BEGIN_EXAMPLE" "END_EXAMPLE"
11090 "BEGIN_QUOTE" "END_QUOTE"
11091 "BEGIN_VERSE" "END_VERSE"
11092 "BEGIN_CENTER" "END_CENTER"
11093 "BEGIN_SRC" "END_SRC"
11094 "BEGIN_RESULT" "END_RESULT"
11095 "NAME:" "RESULTS:"
11096 "HEADER:" "HEADERS:"
11097 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11098 "CAPTION:" "LABEL:"
11099 "SETUPFILE:"
11100 "INCLUDE:"
11101 "BIND:"
11102 "MACRO:"))
11104 (defcustom org-structure-template-alist
11106 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11107 "<src lang=\"?\">\n\n</src>")
11108 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11109 "<example>\n?\n</example>")
11110 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11111 "<quote>\n?\n</quote>")
11112 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11113 "<verse>\n?\n</verse>")
11114 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11115 "<center>\n?\n</center>")
11116 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11117 "<literal style=\"latex\">\n?\n</literal>")
11118 ("L" "#+LaTeX: "
11119 "<literal style=\"latex\">?</literal>")
11120 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11121 "<literal style=\"html\">\n?\n</literal>")
11122 ("H" "#+HTML: "
11123 "<literal style=\"html\">?</literal>")
11124 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11125 ("A" "#+ASCII: ")
11126 ("i" "#+INDEX: ?"
11127 "#+INDEX: ?")
11128 ("I" "#+INCLUDE %file ?"
11129 "<include file=%file markup=\"?\">")
11131 "Structure completion elements.
11132 This is a list of abbreviation keys and values. The value gets inserted
11133 if you type `<' followed by the key and then press the completion key,
11134 usually `M-TAB'. %file will be replaced by a file name after prompting
11135 for the file using completion. The cursor will be placed at the position
11136 of the `?` in the template.
11137 There are two templates for each key, the first uses the original Org syntax,
11138 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11139 the default when the /org-mtags.el/ module has been loaded. See also the
11140 variable `org-mtags-prefer-muse-templates'."
11141 :group 'org-completion
11142 :type '(repeat
11143 (string :tag "Key")
11144 (string :tag "Template")
11145 (string :tag "Muse Template")))
11147 (defun org-try-structure-completion ()
11148 "Try to complete a structure template before point.
11149 This looks for strings like \"<e\" on an otherwise empty line and
11150 expands them."
11151 (let ((l (buffer-substring (point-at-bol) (point)))
11153 (when (and (looking-at "[ \t]*$")
11154 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11155 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11156 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11157 (match-beginning 1)) a)
11158 t)))
11160 (defun org-complete-expand-structure-template (start cell)
11161 "Expand a structure template."
11162 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11163 (rpl (nth (if musep 2 1) cell))
11164 (ind ""))
11165 (delete-region start (point))
11166 (when (string-match "\\`#\\+" rpl)
11167 (cond
11168 ((bolp))
11169 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11170 (setq ind (buffer-substring (point-at-bol) (point))))
11171 (t (newline))))
11172 (setq start (point))
11173 (if (string-match "%file" rpl)
11174 (setq rpl (replace-match
11175 (concat
11176 "\""
11177 (save-match-data
11178 (abbreviate-file-name (read-file-name "Include file: ")))
11179 "\"")
11180 t t rpl)))
11181 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11182 (concat "\n" ind)))
11183 (insert rpl)
11184 (if (re-search-backward "\\?" start t) (delete-char 1))))
11186 ;;;; TODO, DEADLINE, Comments
11188 (defun org-toggle-comment ()
11189 "Change the COMMENT state of an entry."
11190 (interactive)
11191 (save-excursion
11192 (org-back-to-heading)
11193 (let (case-fold-search)
11194 (cond
11195 ((looking-at (format org-heading-keyword-regexp-format
11196 org-comment-string))
11197 (goto-char (match-end 1))
11198 (looking-at (concat " +" org-comment-string))
11199 (replace-match "" t t)
11200 (when (eolp) (insert " ")))
11201 ((looking-at org-outline-regexp)
11202 (goto-char (match-end 0))
11203 (insert org-comment-string " "))))))
11205 (defvar org-last-todo-state-is-todo nil
11206 "This is non-nil when the last TODO state change led to a TODO state.
11207 If the last change removed the TODO tag or switched to DONE, then
11208 this is nil.")
11210 (defvar org-setting-tags nil) ; dynamically skipped
11212 (defvar org-todo-setup-filter-hook nil
11213 "Hook for functions that pre-filter todo specs.
11214 Each function takes a todo spec and returns either nil or the spec
11215 transformed into canonical form." )
11217 (defvar org-todo-get-default-hook nil
11218 "Hook for functions that get a default item for todo.
11219 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11220 nil or a string to be used for the todo mark." )
11222 (defvar org-agenda-headline-snapshot-before-repeat)
11224 (defun org-current-effective-time ()
11225 "Return current time adjusted for `org-extend-today-until' variable"
11226 (let* ((ct (org-current-time))
11227 (dct (decode-time ct))
11228 (ct1
11229 (if (and org-use-effective-time
11230 (< (nth 2 dct) org-extend-today-until))
11231 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11232 ct)))
11233 ct1))
11235 (defun org-todo-yesterday (&optional arg)
11236 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11237 (interactive "P")
11238 (if (eq major-mode 'org-agenda-mode)
11239 (apply 'org-agenda-todo-yesterday arg)
11240 (let* ((hour (third (decode-time
11241 (org-current-time))))
11242 (org-extend-today-until (1+ hour)))
11243 (org-todo arg))))
11245 (defun org-todo (&optional arg)
11246 "Change the TODO state of an item.
11247 The state of an item is given by a keyword at the start of the heading,
11248 like
11249 *** TODO Write paper
11250 *** DONE Call mom
11252 The different keywords are specified in the variable `org-todo-keywords'.
11253 By default the available states are \"TODO\" and \"DONE\".
11254 So for this example: when the item starts with TODO, it is changed to DONE.
11255 When it starts with DONE, the DONE is removed. And when neither TODO nor
11256 DONE are present, add TODO at the beginning of the heading.
11258 With \\[universal-argument] prefix arg, use completion to determine the new \
11259 state.
11260 With numeric prefix arg, switch to that state.
11261 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11262 keywords (nextset).
11263 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11264 With a numeric prefix arg of 0, inhibit note taking for the change.
11266 For calling through lisp, arg is also interpreted in the following way:
11267 'none -> empty state
11268 \"\"(empty string) -> switch to empty state
11269 'done -> switch to DONE
11270 'nextset -> switch to the next set of keywords
11271 'previousset -> switch to the previous set of keywords
11272 \"WAITING\" -> switch to the specified keyword, but only if it
11273 really is a member of `org-todo-keywords'."
11274 (interactive "P")
11275 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11276 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11277 'region-start-level 'region))
11278 org-loop-over-headlines-in-active-region)
11279 (org-map-entries
11280 `(org-todo ,arg)
11281 org-loop-over-headlines-in-active-region
11282 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11283 (if (equal arg '(16)) (setq arg 'nextset))
11284 (let ((org-blocker-hook org-blocker-hook)
11285 (case-fold-search nil))
11286 (when (equal arg '(64))
11287 (setq arg nil org-blocker-hook nil))
11288 (when (and org-blocker-hook
11289 (or org-inhibit-blocking
11290 (org-entry-get nil "NOBLOCKING")))
11291 (setq org-blocker-hook nil))
11292 (save-excursion
11293 (catch 'exit
11294 (org-back-to-heading t)
11295 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11296 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11297 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11298 (let* ((match-data (match-data))
11299 (startpos (point-at-bol))
11300 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11301 (org-log-done org-log-done)
11302 (org-log-repeat org-log-repeat)
11303 (org-todo-log-states org-todo-log-states)
11304 (org-inhibit-logging
11305 (if (equal arg 0)
11306 (progn (setq arg nil) 'note) org-inhibit-logging))
11307 (this (match-string 1))
11308 (hl-pos (match-beginning 0))
11309 (head (org-get-todo-sequence-head this))
11310 (ass (assoc head org-todo-kwd-alist))
11311 (interpret (nth 1 ass))
11312 (done-word (nth 3 ass))
11313 (final-done-word (nth 4 ass))
11314 (last-state (or this ""))
11315 (completion-ignore-case t)
11316 (member (member this org-todo-keywords-1))
11317 (tail (cdr member))
11318 (state (cond
11319 ((and org-todo-key-trigger
11320 (or (and (equal arg '(4))
11321 (eq org-use-fast-todo-selection 'prefix))
11322 (and (not arg) org-use-fast-todo-selection
11323 (not (eq org-use-fast-todo-selection
11324 'prefix)))))
11325 ;; Use fast selection
11326 (org-fast-todo-selection))
11327 ((and (equal arg '(4))
11328 (or (not org-use-fast-todo-selection)
11329 (not org-todo-key-trigger)))
11330 ;; Read a state with completion
11331 (org-icompleting-read
11332 "State: " (mapcar (lambda(x) (list x))
11333 org-todo-keywords-1)
11334 nil t))
11335 ((eq arg 'right)
11336 (if this
11337 (if tail (car tail) nil)
11338 (car org-todo-keywords-1)))
11339 ((eq arg 'left)
11340 (if (equal member org-todo-keywords-1)
11342 (if this
11343 (nth (- (length org-todo-keywords-1)
11344 (length tail) 2)
11345 org-todo-keywords-1)
11346 (org-last org-todo-keywords-1))))
11347 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11348 (setq arg nil))) ; hack to fall back to cycling
11349 (arg
11350 ;; user or caller requests a specific state
11351 (cond
11352 ((equal arg "") nil)
11353 ((eq arg 'none) nil)
11354 ((eq arg 'done) (or done-word (car org-done-keywords)))
11355 ((eq arg 'nextset)
11356 (or (car (cdr (member head org-todo-heads)))
11357 (car org-todo-heads)))
11358 ((eq arg 'previousset)
11359 (let ((org-todo-heads (reverse org-todo-heads)))
11360 (or (car (cdr (member head org-todo-heads)))
11361 (car org-todo-heads))))
11362 ((car (member arg org-todo-keywords-1)))
11363 ((stringp arg)
11364 (error "State `%s' not valid in this file" arg))
11365 ((nth (1- (prefix-numeric-value arg))
11366 org-todo-keywords-1))))
11367 ((null member) (or head (car org-todo-keywords-1)))
11368 ((equal this final-done-word) nil) ;; -> make empty
11369 ((null tail) nil) ;; -> first entry
11370 ((memq interpret '(type priority))
11371 (if (eq this-command last-command)
11372 (car tail)
11373 (if (> (length tail) 0)
11374 (or done-word (car org-done-keywords))
11375 nil)))
11377 (car tail))))
11378 (state (or
11379 (run-hook-with-args-until-success
11380 'org-todo-get-default-hook state last-state)
11381 state))
11382 (next (if state (concat " " state " ") " "))
11383 (change-plist (list :type 'todo-state-change :from this :to state
11384 :position startpos))
11385 dolog now-done-p)
11386 (when org-blocker-hook
11387 (setq org-last-todo-state-is-todo
11388 (not (member this org-done-keywords)))
11389 (unless (save-excursion
11390 (save-match-data
11391 (org-with-wide-buffer
11392 (run-hook-with-args-until-failure
11393 'org-blocker-hook change-plist))))
11394 (if (org-called-interactively-p 'interactive)
11395 (error "TODO state change from %s to %s blocked" this state)
11396 ;; fail silently
11397 (message "TODO state change from %s to %s blocked" this state)
11398 (throw 'exit nil))))
11399 (store-match-data match-data)
11400 (replace-match next t t)
11401 (unless (pos-visible-in-window-p hl-pos)
11402 (message "TODO state changed to %s" (org-trim next)))
11403 (unless head
11404 (setq head (org-get-todo-sequence-head state)
11405 ass (assoc head org-todo-kwd-alist)
11406 interpret (nth 1 ass)
11407 done-word (nth 3 ass)
11408 final-done-word (nth 4 ass)))
11409 (when (memq arg '(nextset previousset))
11410 (message "Keyword-Set %d/%d: %s"
11411 (- (length org-todo-sets) -1
11412 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11413 (length org-todo-sets)
11414 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11415 (setq org-last-todo-state-is-todo
11416 (not (member state org-done-keywords)))
11417 (setq now-done-p (and (member state org-done-keywords)
11418 (not (member this org-done-keywords))))
11419 (and logging (org-local-logging logging))
11420 (when (and (or org-todo-log-states org-log-done)
11421 (not (eq org-inhibit-logging t))
11422 (not (memq arg '(nextset previousset))))
11423 ;; we need to look at recording a time and note
11424 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11425 (nth 2 (assoc this org-todo-log-states))))
11426 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11427 (setq dolog 'time))
11428 (when (and state
11429 (member state org-not-done-keywords)
11430 (not (member this org-not-done-keywords)))
11431 ;; This is now a todo state and was not one before
11432 ;; If there was a CLOSED time stamp, get rid of it.
11433 (org-add-planning-info nil nil 'closed))
11434 (when (and now-done-p org-log-done)
11435 ;; It is now done, and it was not done before
11436 (org-add-planning-info 'closed (org-current-effective-time))
11437 (if (and (not dolog) (eq 'note org-log-done))
11438 (org-add-log-setup 'done state this 'findpos 'note)))
11439 (when (and state dolog)
11440 ;; This is a non-nil state, and we need to log it
11441 (org-add-log-setup 'state state this 'findpos dolog)))
11442 ;; Fixup tag positioning
11443 (org-todo-trigger-tag-changes state)
11444 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11445 (when org-provide-todo-statistics
11446 (org-update-parent-todo-statistics))
11447 (run-hooks 'org-after-todo-state-change-hook)
11448 (if (and arg (not (member state org-done-keywords)))
11449 (setq head (org-get-todo-sequence-head state)))
11450 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11451 ;; Do we need to trigger a repeat?
11452 (when now-done-p
11453 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11454 ;; This is for the agenda, take a snapshot of the headline.
11455 (save-match-data
11456 (setq org-agenda-headline-snapshot-before-repeat
11457 (org-get-heading))))
11458 (org-auto-repeat-maybe state))
11459 ;; Fixup cursor location if close to the keyword
11460 (if (and (outline-on-heading-p)
11461 (not (bolp))
11462 (save-excursion (beginning-of-line 1)
11463 (looking-at org-todo-line-regexp))
11464 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11465 (progn
11466 (goto-char (or (match-end 2) (match-end 1)))
11467 (and (looking-at " ") (just-one-space))))
11468 (when org-trigger-hook
11469 (save-excursion
11470 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11472 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11473 "Block turning an entry into a TODO, using the hierarchy.
11474 This checks whether the current task should be blocked from state
11475 changes. Such blocking occurs when:
11477 1. The task has children which are not all in a completed state.
11479 2. A task has a parent with the property :ORDERED:, and there
11480 are siblings prior to the current task with incomplete
11481 status.
11483 3. The parent of the task is blocked because it has siblings that should
11484 be done first, or is child of a block grandparent TODO entry."
11486 (if (not org-enforce-todo-dependencies)
11487 t ; if locally turned off don't block
11488 (catch 'dont-block
11489 ;; If this is not a todo state change, or if this entry is already DONE,
11490 ;; do not block
11491 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11492 (member (plist-get change-plist :from)
11493 (cons 'done org-done-keywords))
11494 (member (plist-get change-plist :to)
11495 (cons 'todo org-not-done-keywords))
11496 (not (plist-get change-plist :to)))
11497 (throw 'dont-block t))
11498 ;; If this task has children, and any are undone, it's blocked
11499 (save-excursion
11500 (org-back-to-heading t)
11501 (let ((this-level (funcall outline-level)))
11502 (outline-next-heading)
11503 (let ((child-level (funcall outline-level)))
11504 (while (and (not (eobp))
11505 (> child-level this-level))
11506 ;; this todo has children, check whether they are all
11507 ;; completed
11508 (if (and (not (org-entry-is-done-p))
11509 (org-entry-is-todo-p))
11510 (throw 'dont-block nil))
11511 (outline-next-heading)
11512 (setq child-level (funcall outline-level))))))
11513 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11514 ;; any previous siblings are undone, it's blocked
11515 (save-excursion
11516 (org-back-to-heading t)
11517 (let* ((pos (point))
11518 (parent-pos (and (org-up-heading-safe) (point))))
11519 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11520 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11521 (forward-line 1)
11522 (re-search-forward org-not-done-heading-regexp pos t))
11523 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11524 ;; Search further up the hierarchy, to see if an ancestor is blocked
11525 (while t
11526 (goto-char parent-pos)
11527 (if (not (looking-at org-not-done-heading-regexp))
11528 (throw 'dont-block t)) ; do not block, parent is not a TODO
11529 (setq pos (point))
11530 (setq parent-pos (and (org-up-heading-safe) (point)))
11531 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11532 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11533 (forward-line 1)
11534 (re-search-forward org-not-done-heading-regexp pos t))
11535 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11537 (defcustom org-track-ordered-property-with-tag nil
11538 "Should the ORDERED property also be shown as a tag?
11539 The ORDERED property decides if an entry should require subtasks to be
11540 completed in sequence. Since a property is not very visible, setting
11541 this option means that toggling the ORDERED property with the command
11542 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11543 not relevant for the behavior, but it makes things more visible.
11545 Note that toggling the tag with tags commands will not change the property
11546 and therefore not influence behavior!
11548 This can be t, meaning the tag ORDERED should be used, It can also be a
11549 string to select a different tag for this task."
11550 :group 'org-todo
11551 :type '(choice
11552 (const :tag "No tracking" nil)
11553 (const :tag "Track with ORDERED tag" t)
11554 (string :tag "Use other tag")))
11556 (defun org-toggle-ordered-property ()
11557 "Toggle the ORDERED property of the current entry.
11558 For better visibility, you can track the value of this property with a tag.
11559 See variable `org-track-ordered-property-with-tag'."
11560 (interactive)
11561 (let* ((t1 org-track-ordered-property-with-tag)
11562 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11563 (save-excursion
11564 (org-back-to-heading)
11565 (if (org-entry-get nil "ORDERED")
11566 (progn
11567 (org-delete-property "ORDERED")
11568 (and tag (org-toggle-tag tag 'off))
11569 (message "Subtasks can be completed in arbitrary order"))
11570 (org-entry-put nil "ORDERED" "t")
11571 (and tag (org-toggle-tag tag 'on))
11572 (message "Subtasks must be completed in sequence")))))
11574 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11575 (defun org-block-todo-from-checkboxes (change-plist)
11576 "Block turning an entry into a TODO, using checkboxes.
11577 This checks whether the current task should be blocked from state
11578 changes because there are unchecked boxes in this entry."
11579 (if (not org-enforce-todo-checkbox-dependencies)
11580 t ; if locally turned off don't block
11581 (catch 'dont-block
11582 ;; If this is not a todo state change, or if this entry is already DONE,
11583 ;; do not block
11584 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11585 (member (plist-get change-plist :from)
11586 (cons 'done org-done-keywords))
11587 (member (plist-get change-plist :to)
11588 (cons 'todo org-not-done-keywords))
11589 (not (plist-get change-plist :to)))
11590 (throw 'dont-block t))
11591 ;; If this task has checkboxes that are not checked, it's blocked
11592 (save-excursion
11593 (org-back-to-heading t)
11594 (let ((beg (point)) end)
11595 (outline-next-heading)
11596 (setq end (point))
11597 (goto-char beg)
11598 (if (org-list-search-forward
11599 (concat (org-item-beginning-re)
11600 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11601 "\\[[- ]\\]")
11602 end t)
11603 (progn
11604 (if (boundp 'org-blocked-by-checkboxes)
11605 (setq org-blocked-by-checkboxes t))
11606 (throw 'dont-block nil)))))
11607 t))) ; do not block
11609 (defun org-entry-blocked-p ()
11610 "Is the current entry blocked?"
11611 (if (org-entry-get nil "NOBLOCKING")
11612 nil ;; Never block this entry
11613 (not
11614 (run-hook-with-args-until-failure
11615 'org-blocker-hook
11616 (list :type 'todo-state-change
11617 :position (point)
11618 :from 'todo
11619 :to 'done)))))
11621 (defun org-update-statistics-cookies (all)
11622 "Update the statistics cookie, either from TODO or from checkboxes.
11623 This should be called with the cursor in a line with a statistics cookie."
11624 (interactive "P")
11625 (if all
11626 (progn
11627 (org-update-checkbox-count 'all)
11628 (org-map-entries 'org-update-parent-todo-statistics))
11629 (if (not (org-at-heading-p))
11630 (org-update-checkbox-count)
11631 (let ((pos (move-marker (make-marker) (point)))
11632 end l1 l2)
11633 (ignore-errors (org-back-to-heading t))
11634 (if (not (org-at-heading-p))
11635 (org-update-checkbox-count)
11636 (setq l1 (org-outline-level))
11637 (setq end (save-excursion
11638 (outline-next-heading)
11639 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11640 (point)))
11641 (if (and (save-excursion
11642 (re-search-forward
11643 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11644 (not (save-excursion (re-search-forward
11645 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11646 (org-update-checkbox-count)
11647 (if (and l2 (> l2 l1))
11648 (progn
11649 (goto-char end)
11650 (org-update-parent-todo-statistics))
11651 (goto-char pos)
11652 (beginning-of-line 1)
11653 (while (re-search-forward
11654 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11655 (point-at-eol) t)
11656 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11657 (goto-char pos)
11658 (move-marker pos nil)))))
11660 (defvar org-entry-property-inherited-from) ;; defined below
11661 (defun org-update-parent-todo-statistics ()
11662 "Update any statistics cookie in the parent of the current headline.
11663 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11664 the entire subtree and this will travel up the hierarchy and update
11665 statistics everywhere."
11666 (let* ((prop (save-excursion (org-up-heading-safe)
11667 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11668 (recursive (or (not org-hierarchical-todo-statistics)
11669 (and prop (string-match "\\<recursive\\>" prop))))
11670 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11672 (first t)
11673 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11674 level ltoggle l1 new ndel
11675 (cnt-all 0) (cnt-done 0) is-percent kwd
11676 checkbox-beg ov ovs ove cookie-present)
11677 (catch 'exit
11678 (save-excursion
11679 (beginning-of-line 1)
11680 (setq ltoggle (funcall outline-level))
11681 ;; Three situations are to consider:
11683 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11684 ;; to the top-level ancestor on the headline;
11686 ;; 2. If parent has "recursive" property, repeat up to the
11687 ;; headline setting that property, taking inheritance into
11688 ;; account;
11690 ;; 3. Else, move up to direct parent and proceed only once.
11691 (while (and (setq level (org-up-heading-safe))
11692 (or recursive first)
11693 (>= (point) lim))
11694 (setq first nil cookie-present nil)
11695 (unless (and level
11696 (not (string-match
11697 "\\<checkbox\\>"
11698 (downcase (or (org-entry-get nil "COOKIE_DATA")
11699 "")))))
11700 (throw 'exit nil))
11701 (while (re-search-forward box-re (point-at-eol) t)
11702 (setq cnt-all 0 cnt-done 0 cookie-present t)
11703 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11704 (save-match-data
11705 (unless (outline-next-heading) (throw 'exit nil))
11706 (while (and (looking-at org-complex-heading-regexp)
11707 (> (setq l1 (length (match-string 1))) level))
11708 (setq kwd (and (or recursive (= l1 ltoggle))
11709 (match-string 2)))
11710 (if (or (eq org-provide-todo-statistics 'all-headlines)
11711 (and (listp org-provide-todo-statistics)
11712 (or (member kwd org-provide-todo-statistics)
11713 (member kwd org-done-keywords))))
11714 (setq cnt-all (1+ cnt-all))
11715 (if (eq org-provide-todo-statistics t)
11716 (and kwd (setq cnt-all (1+ cnt-all)))))
11717 (and (member kwd org-done-keywords)
11718 (setq cnt-done (1+ cnt-done)))
11719 (outline-next-heading)))
11720 (setq new
11721 (if is-percent
11722 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11723 (format "[%d/%d]" cnt-done cnt-all))
11724 ndel (- (match-end 0) checkbox-beg))
11725 ;; handle overlays when updating cookie from column view
11726 (when (setq ov (car (overlays-at checkbox-beg)))
11727 (setq ovs (overlay-start ov) ove (overlay-end ov))
11728 (delete-overlay ov))
11729 (goto-char checkbox-beg)
11730 (insert new)
11731 (delete-region (point) (+ (point) ndel))
11732 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11733 (when ov (move-overlay ov ovs ove)))
11734 (when cookie-present
11735 (run-hook-with-args 'org-after-todo-statistics-hook
11736 cnt-done (- cnt-all cnt-done))))))
11737 (run-hooks 'org-todo-statistics-hook)))
11739 (defvar org-after-todo-statistics-hook nil
11740 "Hook that is called after a TODO statistics cookie has been updated.
11741 Each function is called with two arguments: the number of not-done entries
11742 and the number of done entries.
11744 For example, the following function, when added to this hook, will switch
11745 an entry to DONE when all children are done, and back to TODO when new
11746 entries are set to a TODO status. Note that this hook is only called
11747 when there is a statistics cookie in the headline!
11749 (defun org-summary-todo (n-done n-not-done)
11750 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11751 (let (org-log-done org-log-states) ; turn off logging
11752 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11755 (defvar org-todo-statistics-hook nil
11756 "Hook that is run whenever Org thinks TODO statistics should be updated.
11757 This hook runs even if there is no statistics cookie present, in which case
11758 `org-after-todo-statistics-hook' would not run.")
11760 (defun org-todo-trigger-tag-changes (state)
11761 "Apply the changes defined in `org-todo-state-tags-triggers'."
11762 (let ((l org-todo-state-tags-triggers)
11763 changes)
11764 (when (or (not state) (equal state ""))
11765 (setq changes (append changes (cdr (assoc "" l)))))
11766 (when (and (stringp state) (> (length state) 0))
11767 (setq changes (append changes (cdr (assoc state l)))))
11768 (when (member state org-not-done-keywords)
11769 (setq changes (append changes (cdr (assoc 'todo l)))))
11770 (when (member state org-done-keywords)
11771 (setq changes (append changes (cdr (assoc 'done l)))))
11772 (dolist (c changes)
11773 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11775 (defun org-local-logging (value)
11776 "Get logging settings from a property VALUE."
11777 (let* (words w a)
11778 ;; directly set the variables, they are already local.
11779 (setq org-log-done nil
11780 org-log-repeat nil
11781 org-todo-log-states nil)
11782 (setq words (org-split-string value))
11783 (while (setq w (pop words))
11784 (cond
11785 ((setq a (assoc w org-startup-options))
11786 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11787 (set (nth 1 a) (nth 2 a))))
11788 ((setq a (org-extract-log-state-settings w))
11789 (and (member (car a) org-todo-keywords-1)
11790 (push a org-todo-log-states)))))))
11792 (defun org-get-todo-sequence-head (kwd)
11793 "Return the head of the TODO sequence to which KWD belongs.
11794 If KWD is not set, check if there is a text property remembering the
11795 right sequence."
11796 (let (p)
11797 (cond
11798 ((not kwd)
11799 (or (get-text-property (point-at-bol) 'org-todo-head)
11800 (progn
11801 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11802 nil (point-at-eol)))
11803 (get-text-property p 'org-todo-head))))
11804 ((not (member kwd org-todo-keywords-1))
11805 (car org-todo-keywords-1))
11806 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11808 (defun org-fast-todo-selection ()
11809 "Fast TODO keyword selection with single keys.
11810 Returns the new TODO keyword, or nil if no state change should occur."
11811 (let* ((fulltable org-todo-key-alist)
11812 (done-keywords org-done-keywords) ;; needed for the faces.
11813 (maxlen (apply 'max (mapcar
11814 (lambda (x)
11815 (if (stringp (car x)) (string-width (car x)) 0))
11816 fulltable)))
11817 (expert nil)
11818 (fwidth (+ maxlen 3 1 3))
11819 (ncol (/ (- (window-width) 4) fwidth))
11820 tg cnt e c tbl
11821 groups ingroup)
11822 (save-excursion
11823 (save-window-excursion
11824 (if expert
11825 (set-buffer (get-buffer-create " *Org todo*"))
11826 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11827 (erase-buffer)
11828 (org-set-local 'org-done-keywords done-keywords)
11829 (setq tbl fulltable cnt 0)
11830 (while (setq e (pop tbl))
11831 (cond
11832 ((equal e '(:startgroup))
11833 (push '() groups) (setq ingroup t)
11834 (when (not (= cnt 0))
11835 (setq cnt 0)
11836 (insert "\n"))
11837 (insert "{ "))
11838 ((equal e '(:endgroup))
11839 (setq ingroup nil cnt 0)
11840 (insert "}\n"))
11841 ((equal e '(:newline))
11842 (when (not (= cnt 0))
11843 (setq cnt 0)
11844 (insert "\n")
11845 (setq e (car tbl))
11846 (while (equal (car tbl) '(:newline))
11847 (insert "\n")
11848 (setq tbl (cdr tbl)))))
11850 (setq tg (car e) c (cdr e))
11851 (if ingroup (push tg (car groups)))
11852 (setq tg (org-add-props tg nil 'face
11853 (org-get-todo-face tg)))
11854 (if (and (= cnt 0) (not ingroup)) (insert " "))
11855 (insert "[" c "] " tg (make-string
11856 (- fwidth 4 (length tg)) ?\ ))
11857 (when (= (setq cnt (1+ cnt)) ncol)
11858 (insert "\n")
11859 (if ingroup (insert " "))
11860 (setq cnt 0)))))
11861 (insert "\n")
11862 (goto-char (point-min))
11863 (if (not expert) (org-fit-window-to-buffer))
11864 (message "[a-z..]:Set [SPC]:clear")
11865 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11866 (cond
11867 ((or (= c ?\C-g)
11868 (and (= c ?q) (not (rassoc c fulltable))))
11869 (setq quit-flag t))
11870 ((= c ?\ ) nil)
11871 ((setq e (rassoc c fulltable) tg (car e))
11873 (t (setq quit-flag t)))))))
11875 (defun org-entry-is-todo-p ()
11876 (member (org-get-todo-state) org-not-done-keywords))
11878 (defun org-entry-is-done-p ()
11879 (member (org-get-todo-state) org-done-keywords))
11881 (defun org-get-todo-state ()
11882 (save-excursion
11883 (org-back-to-heading t)
11884 (and (looking-at org-todo-line-regexp)
11885 (match-end 2)
11886 (match-string 2))))
11888 (defun org-at-date-range-p (&optional inactive-ok)
11889 "Is the cursor inside a date range?"
11890 (interactive)
11891 (save-excursion
11892 (catch 'exit
11893 (let ((pos (point)))
11894 (skip-chars-backward "^[<\r\n")
11895 (skip-chars-backward "<[")
11896 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11897 (>= (match-end 0) pos)
11898 (throw 'exit t))
11899 (skip-chars-backward "^<[\r\n")
11900 (skip-chars-backward "<[")
11901 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11902 (>= (match-end 0) pos)
11903 (throw 'exit t)))
11904 nil)))
11906 (defun org-get-repeat (&optional tagline)
11907 "Check if there is a deadline/schedule with repeater in this entry."
11908 (save-match-data
11909 (save-excursion
11910 (org-back-to-heading t)
11911 (and (re-search-forward (if tagline
11912 (concat tagline "\\s-*" org-repeat-re)
11913 org-repeat-re)
11914 (org-entry-end-position) t)
11915 (match-string-no-properties 1)))))
11917 (defvar org-last-changed-timestamp)
11918 (defvar org-last-inserted-timestamp)
11919 (defvar org-log-post-message)
11920 (defvar org-log-note-purpose)
11921 (defvar org-log-note-how)
11922 (defvar org-log-note-extra)
11923 (defun org-auto-repeat-maybe (done-word)
11924 "Check if the current headline contains a repeated deadline/schedule.
11925 If yes, set TODO state back to what it was and change the base date
11926 of repeating deadline/scheduled time stamps to new date.
11927 This function is run automatically after each state change to a DONE state."
11928 ;; last-state is dynamically scoped into this function
11929 (let* ((repeat (org-get-repeat))
11930 (aa (assoc last-state org-todo-kwd-alist))
11931 (interpret (nth 1 aa))
11932 (head (nth 2 aa))
11933 (whata '(("d" . day) ("m" . month) ("y" . year)))
11934 (msg "Entry repeats: ")
11935 (org-log-done nil)
11936 (org-todo-log-states nil)
11937 re type n what ts time to-state)
11938 (when repeat
11939 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11940 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11941 org-todo-repeat-to-state))
11942 (unless (and to-state (member to-state org-todo-keywords-1))
11943 (setq to-state (if (eq interpret 'type) last-state head)))
11944 (org-todo to-state)
11945 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11946 (org-entry-put nil "LAST_REPEAT" (format-time-string
11947 (org-time-stamp-format t t))))
11948 (when org-log-repeat
11949 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11950 (memq 'org-add-log-note post-command-hook))
11951 ;; OK, we are already setup for some record
11952 (if (eq org-log-repeat 'note)
11953 ;; make sure we take a note, not only a time stamp
11954 (setq org-log-note-how 'note))
11955 ;; Set up for taking a record
11956 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11957 last-state
11958 'findpos org-log-repeat)))
11959 (org-back-to-heading t)
11960 (org-add-planning-info nil nil 'closed)
11961 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11962 org-deadline-time-regexp "\\)\\|\\("
11963 org-ts-regexp "\\)"))
11964 (while (re-search-forward
11965 re (save-excursion (outline-next-heading) (point)) t)
11966 (setq type (if (match-end 1) org-scheduled-string
11967 (if (match-end 3) org-deadline-string "Plain:"))
11968 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11969 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11970 (setq n (string-to-number (match-string 2 ts))
11971 what (match-string 3 ts))
11972 (if (equal what "w") (setq n (* n 7) what "d"))
11973 ;; Preparation, see if we need to modify the start date for the change
11974 (when (match-end 1)
11975 (setq time (save-match-data (org-time-string-to-time ts)))
11976 (cond
11977 ((equal (match-string 1 ts) ".")
11978 ;; Shift starting date to today
11979 (org-timestamp-change
11980 (- (org-today) (time-to-days time))
11981 'day))
11982 ((equal (match-string 1 ts) "+")
11983 (let ((nshiftmax 10) (nshift 0))
11984 (while (or (= nshift 0)
11985 (<= (time-to-days time)
11986 (time-to-days (current-time))))
11987 (when (= (incf nshift) nshiftmax)
11988 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11989 (error "Abort")))
11990 (org-timestamp-change n (cdr (assoc what whata)))
11991 (org-at-timestamp-p t)
11992 (setq ts (match-string 1))
11993 (setq time (save-match-data (org-time-string-to-time ts)))))
11994 (org-timestamp-change (- n) (cdr (assoc what whata)))
11995 ;; rematch, so that we have everything in place for the real shift
11996 (org-at-timestamp-p t)
11997 (setq ts (match-string 1))
11998 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11999 (org-timestamp-change n (cdr (assoc what whata)))
12000 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12001 (setq org-log-post-message msg)
12002 (message "%s" msg))))
12004 (defun org-show-todo-tree (arg)
12005 "Make a compact tree which shows all headlines marked with TODO.
12006 The tree will show the lines where the regexp matches, and all higher
12007 headlines above the match.
12008 With a \\[universal-argument] prefix, prompt for a regexp to match.
12009 With a numeric prefix N, construct a sparse tree for the Nth element
12010 of `org-todo-keywords-1'."
12011 (interactive "P")
12012 (let ((case-fold-search nil)
12013 (kwd-re
12014 (cond ((null arg) org-not-done-regexp)
12015 ((equal arg '(4))
12016 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12017 (mapcar 'list org-todo-keywords-1))))
12018 (concat "\\("
12019 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12020 "\\)\\>")))
12021 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12022 (regexp-quote (nth (1- (prefix-numeric-value arg))
12023 org-todo-keywords-1)))
12024 (t (error "Invalid prefix argument: %s" arg)))))
12025 (message "%d TODO entries found"
12026 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12028 (defun org-deadline (&optional remove time)
12029 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12030 With argument REMOVE, remove any deadline from the item.
12031 With argument TIME, set the deadline at the corresponding date. TIME
12032 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12033 (interactive "P")
12034 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12035 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12036 'region-start-level 'region))
12037 org-loop-over-headlines-in-active-region)
12038 (org-map-entries
12039 `(org-deadline ',remove ,time)
12040 org-loop-over-headlines-in-active-region
12041 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12042 (let* ((old-date (org-entry-get nil "DEADLINE"))
12043 (repeater (and old-date
12044 (string-match
12045 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12046 old-date)
12047 (match-string 1 old-date))))
12048 (if remove
12049 (progn
12050 (when (and old-date org-log-redeadline)
12051 (org-add-log-setup 'deldeadline nil old-date 'findpos
12052 org-log-redeadline))
12053 (org-remove-timestamp-with-keyword org-deadline-string)
12054 (message "Item no longer has a deadline."))
12055 (org-add-planning-info 'deadline time 'closed)
12056 (when (and old-date org-log-redeadline
12057 (not (equal old-date
12058 (substring org-last-inserted-timestamp 1 -1))))
12059 (org-add-log-setup 'redeadline nil old-date 'findpos
12060 org-log-redeadline))
12061 (when repeater
12062 (save-excursion
12063 (org-back-to-heading t)
12064 (when (re-search-forward (concat org-deadline-string " "
12065 org-last-inserted-timestamp)
12066 (save-excursion
12067 (outline-next-heading) (point)) t)
12068 (goto-char (1- (match-end 0)))
12069 (insert " " repeater)
12070 (setq org-last-inserted-timestamp
12071 (concat (substring org-last-inserted-timestamp 0 -1)
12072 " " repeater
12073 (substring org-last-inserted-timestamp -1))))))
12074 (message "Deadline on %s" org-last-inserted-timestamp)))))
12076 (defun org-schedule (&optional remove time)
12077 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12078 With argument REMOVE, remove any scheduling date from the item.
12079 With argument TIME, scheduled at the corresponding date. TIME can
12080 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12081 (interactive "P")
12082 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12083 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12084 'region-start-level 'region))
12085 org-loop-over-headlines-in-active-region)
12086 (org-map-entries
12087 `(org-schedule ',remove ,time)
12088 org-loop-over-headlines-in-active-region
12089 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12090 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12091 (repeater (and old-date
12092 (string-match
12093 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12094 old-date)
12095 (match-string 1 old-date))))
12096 (if remove
12097 (progn
12098 (when (and old-date org-log-reschedule)
12099 (org-add-log-setup 'delschedule nil old-date 'findpos
12100 org-log-reschedule))
12101 (org-remove-timestamp-with-keyword org-scheduled-string)
12102 (message "Item is no longer scheduled."))
12103 (org-add-planning-info 'scheduled time 'closed)
12104 (when (and old-date org-log-reschedule
12105 (not (equal old-date
12106 (substring org-last-inserted-timestamp 1 -1))))
12107 (org-add-log-setup 'reschedule nil old-date 'findpos
12108 org-log-reschedule))
12109 (when repeater
12110 (save-excursion
12111 (org-back-to-heading t)
12112 (when (re-search-forward (concat org-scheduled-string " "
12113 org-last-inserted-timestamp)
12114 (save-excursion
12115 (outline-next-heading) (point)) t)
12116 (goto-char (1- (match-end 0)))
12117 (insert " " repeater)
12118 (setq org-last-inserted-timestamp
12119 (concat (substring org-last-inserted-timestamp 0 -1)
12120 " " repeater
12121 (substring org-last-inserted-timestamp -1))))))
12122 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12124 (defun org-get-scheduled-time (pom &optional inherit)
12125 "Get the scheduled time as a time tuple, of a format suitable
12126 for calling org-schedule with, or if there is no scheduling,
12127 returns nil."
12128 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12129 (when time
12130 (apply 'encode-time (org-parse-time-string time)))))
12132 (defun org-get-deadline-time (pom &optional inherit)
12133 "Get the deadline as a time tuple, of a format suitable for
12134 calling org-deadline with, or if there is no scheduling, returns
12135 nil."
12136 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12137 (when time
12138 (apply 'encode-time (org-parse-time-string time)))))
12140 (defun org-remove-timestamp-with-keyword (keyword)
12141 "Remove all time stamps with KEYWORD in the current entry."
12142 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12143 beg)
12144 (save-excursion
12145 (org-back-to-heading t)
12146 (setq beg (point))
12147 (outline-next-heading)
12148 (while (re-search-backward re beg t)
12149 (replace-match "")
12150 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12151 (equal (char-before) ?\ ))
12152 (backward-delete-char 1)
12153 (if (string-match "^[ \t]*$" (buffer-substring
12154 (point-at-bol) (point-at-eol)))
12155 (delete-region (point-at-bol)
12156 (min (point-max) (1+ (point-at-eol))))))))))
12158 (defun org-add-planning-info (what &optional time &rest remove)
12159 "Insert new timestamp with keyword in the line directly after the headline.
12160 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12161 If non is given, the user is prompted for a date.
12162 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12163 be removed."
12164 (interactive)
12165 (let (org-time-was-given org-end-time-was-given ts
12166 end default-time default-input)
12168 (catch 'exit
12169 (when (and (memq what '(scheduled deadline))
12170 (or (not time)
12171 (and (stringp time)
12172 (string-match "^[-+]+[0-9]" time))))
12173 ;; Try to get a default date/time from existing timestamp
12174 (save-excursion
12175 (org-back-to-heading t)
12176 (setq end (save-excursion (outline-next-heading) (point)))
12177 (when (re-search-forward (if (eq what 'scheduled)
12178 org-scheduled-time-regexp
12179 org-deadline-time-regexp)
12180 end t)
12181 (setq ts (match-string 1)
12182 default-time
12183 (apply 'encode-time (org-parse-time-string ts))
12184 default-input (and ts (org-get-compact-tod ts))))))
12185 (when what
12186 (setq time
12187 (if (stringp time)
12188 ;; This is a string (relative or absolute), set proper date
12189 (apply 'encode-time
12190 (org-read-date-analyze
12191 time default-time (decode-time default-time)))
12192 ;; If necessary, get the time from the user
12193 (or time (org-read-date nil 'to-time nil nil
12194 default-time default-input)))))
12196 (when (and org-insert-labeled-timestamps-at-point
12197 (member what '(scheduled deadline)))
12198 (insert
12199 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12200 (org-insert-time-stamp time org-time-was-given
12201 nil nil nil (list org-end-time-was-given))
12202 (setq what nil))
12203 (save-excursion
12204 (save-restriction
12205 (let (col list elt ts buffer-invisibility-spec)
12206 (org-back-to-heading t)
12207 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12208 (goto-char (match-end 1))
12209 (setq col (current-column))
12210 (goto-char (match-end 0))
12211 (if (eobp) (insert "\n") (forward-char 1))
12212 (when (and (not what)
12213 (not (looking-at
12214 (concat "[ \t]*"
12215 org-keyword-time-not-clock-regexp))))
12216 ;; Nothing to add, nothing to remove...... :-)
12217 (throw 'exit nil))
12218 (if (and (not (looking-at org-outline-regexp))
12219 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12220 "[^\r\n]*"))
12221 (not (equal (match-string 1) org-clock-string)))
12222 (narrow-to-region (match-beginning 0) (match-end 0))
12223 (insert-before-markers "\n")
12224 (backward-char 1)
12225 (narrow-to-region (point) (point))
12226 (and org-adapt-indentation (org-indent-to-column col)))
12227 ;; Check if we have to remove something.
12228 (setq list (cons what remove))
12229 (while list
12230 (setq elt (pop list))
12231 (when (or (and (eq elt 'scheduled)
12232 (re-search-forward org-scheduled-time-regexp nil t))
12233 (and (eq elt 'deadline)
12234 (re-search-forward org-deadline-time-regexp nil t))
12235 (and (eq elt 'closed)
12236 (re-search-forward org-closed-time-regexp nil t)))
12237 (replace-match "")
12238 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12239 (and (looking-at "[ \t]+") (replace-match ""))
12240 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12241 (when what
12242 (insert
12243 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12244 (cond ((eq what 'scheduled) org-scheduled-string)
12245 ((eq what 'deadline) org-deadline-string)
12246 ((eq what 'closed) org-closed-string))
12247 " ")
12248 (setq ts (org-insert-time-stamp
12249 time
12250 (or org-time-was-given
12251 (and (eq what 'closed) org-log-done-with-time))
12252 (eq what 'closed)
12253 nil nil (list org-end-time-was-given)))
12254 (insert
12255 (if (not (or (bolp) (eq (char-before) ?\ )
12256 (memq (char-after) '(32 10))
12257 (eobp))) " " ""))
12258 (end-of-line 1))
12259 (goto-char (point-min))
12260 (widen)
12261 (if (and (looking-at "[ \t]*\n")
12262 (equal (char-before) ?\n))
12263 (delete-region (1- (point)) (point-at-eol)))
12264 ts))))))
12266 (defvar org-log-note-marker (make-marker))
12267 (defvar org-log-note-purpose nil)
12268 (defvar org-log-note-state nil)
12269 (defvar org-log-note-previous-state nil)
12270 (defvar org-log-note-how nil)
12271 (defvar org-log-note-extra nil)
12272 (defvar org-log-note-window-configuration nil)
12273 (defvar org-log-note-return-to (make-marker))
12274 (defvar org-log-note-effective-time nil
12275 "Remembered current time so that dynamically scoped
12276 `org-extend-today-until' affects tha timestamps in state change
12277 log")
12279 (defvar org-log-post-message nil
12280 "Message to be displayed after a log note has been stored.
12281 The auto-repeater uses this.")
12283 (defun org-add-note ()
12284 "Add a note to the current entry.
12285 This is done in the same way as adding a state change note."
12286 (interactive)
12287 (org-add-log-setup 'note nil nil 'findpos nil))
12289 (defvar org-property-end-re)
12290 (defun org-add-log-setup (&optional purpose state prev-state
12291 findpos how extra)
12292 "Set up the post command hook to take a note.
12293 If this is about to TODO state change, the new state is expected in STATE.
12294 When FINDPOS is non-nil, find the correct position for the note in
12295 the current entry. If not, assume that it can be inserted at point.
12296 HOW is an indicator what kind of note should be created.
12297 EXTRA is additional text that will be inserted into the notes buffer."
12298 (let* ((org-log-into-drawer (org-log-into-drawer))
12299 (drawer (cond ((stringp org-log-into-drawer)
12300 org-log-into-drawer)
12301 (org-log-into-drawer "LOGBOOK")
12302 (t nil))))
12303 (save-restriction
12304 (save-excursion
12305 (when findpos
12306 (org-back-to-heading t)
12307 (narrow-to-region (point) (save-excursion
12308 (outline-next-heading) (point)))
12309 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12310 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12311 "[^\r\n]*\\)?"))
12312 (goto-char (match-end 0))
12313 (cond
12314 (drawer
12315 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12316 nil t)
12317 (progn
12318 (goto-char (match-end 0))
12319 (or org-log-states-order-reversed
12320 (and (re-search-forward org-property-end-re nil t)
12321 (goto-char (1- (match-beginning 0))))))
12322 (insert "\n:" drawer ":\n:END:")
12323 (beginning-of-line 0)
12324 (org-indent-line-function)
12325 (beginning-of-line 2)
12326 (org-indent-line-function)
12327 (end-of-line 0)))
12328 ((and org-log-state-notes-insert-after-drawers
12329 (save-excursion
12330 (forward-line) (looking-at org-drawer-regexp)))
12331 (forward-line)
12332 (while (looking-at org-drawer-regexp)
12333 (goto-char (match-end 0))
12334 (re-search-forward org-property-end-re (point-max) t)
12335 (forward-line))
12336 (forward-line -1)))
12337 (unless org-log-states-order-reversed
12338 (and (= (char-after) ?\n) (forward-char 1))
12339 (org-skip-over-state-notes)
12340 (skip-chars-backward " \t\n\r")))
12341 (move-marker org-log-note-marker (point))
12342 (setq org-log-note-purpose purpose
12343 org-log-note-state state
12344 org-log-note-previous-state prev-state
12345 org-log-note-how how
12346 org-log-note-extra extra
12347 org-log-note-effective-time (org-current-effective-time))
12348 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12350 (defun org-skip-over-state-notes ()
12351 "Skip past the list of State notes in an entry."
12352 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12353 (when (ignore-errors (goto-char (org-in-item-p)))
12354 (let* ((struct (org-list-struct))
12355 (prevs (org-list-prevs-alist struct)))
12356 (while (looking-at "[ \t]*- State")
12357 (goto-char (or (org-list-get-next-item (point) struct prevs)
12358 (org-list-get-item-end (point) struct)))))))
12360 (defun org-add-log-note (&optional purpose)
12361 "Pop up a window for taking a note, and add this note later at point."
12362 (remove-hook 'post-command-hook 'org-add-log-note)
12363 (setq org-log-note-window-configuration (current-window-configuration))
12364 (delete-other-windows)
12365 (move-marker org-log-note-return-to (point))
12366 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12367 (goto-char org-log-note-marker)
12368 (org-switch-to-buffer-other-window "*Org Note*")
12369 (erase-buffer)
12370 (if (memq org-log-note-how '(time state))
12371 (let (current-prefix-arg) (org-store-log-note))
12372 (let ((org-inhibit-startup t)) (org-mode))
12373 (insert (format "# Insert note for %s.
12374 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12375 (cond
12376 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12377 ((eq org-log-note-purpose 'done) "closed todo item")
12378 ((eq org-log-note-purpose 'state)
12379 (format "state change from \"%s\" to \"%s\""
12380 (or org-log-note-previous-state "")
12381 (or org-log-note-state "")))
12382 ((eq org-log-note-purpose 'reschedule)
12383 "rescheduling")
12384 ((eq org-log-note-purpose 'delschedule)
12385 "no longer scheduled")
12386 ((eq org-log-note-purpose 'redeadline)
12387 "changing deadline")
12388 ((eq org-log-note-purpose 'deldeadline)
12389 "removing deadline")
12390 ((eq org-log-note-purpose 'refile)
12391 "refiling")
12392 ((eq org-log-note-purpose 'note)
12393 "this entry")
12394 (t (error "This should not happen")))))
12395 (if org-log-note-extra (insert org-log-note-extra))
12396 (org-set-local 'org-finish-function 'org-store-log-note)
12397 (run-hooks 'org-log-buffer-setup-hook)))
12399 (defvar org-note-abort nil) ; dynamically scoped
12400 (defun org-store-log-note ()
12401 "Finish taking a log note, and insert it to where it belongs."
12402 (let ((txt (buffer-string))
12403 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12404 lines ind bul)
12405 (kill-buffer (current-buffer))
12406 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12407 (setq txt (replace-match "" t t txt)))
12408 (if (string-match "\\s-+\\'" txt)
12409 (setq txt (replace-match "" t t txt)))
12410 (setq lines (org-split-string txt "\n"))
12411 (when (and note (string-match "\\S-" note))
12412 (setq note
12413 (org-replace-escapes
12414 note
12415 (list (cons "%u" (user-login-name))
12416 (cons "%U" user-full-name)
12417 (cons "%t" (format-time-string
12418 (org-time-stamp-format 'long 'inactive)
12419 org-log-note-effective-time))
12420 (cons "%T" (format-time-string
12421 (org-time-stamp-format 'long nil)
12422 org-log-note-effective-time))
12423 (cons "%d" (format-time-string
12424 (org-time-stamp-format nil 'inactive)
12425 org-log-note-effective-time))
12426 (cons "%D" (format-time-string
12427 (org-time-stamp-format nil nil)
12428 org-log-note-effective-time))
12429 (cons "%s" (if org-log-note-state
12430 (concat "\"" org-log-note-state "\"")
12431 ""))
12432 (cons "%S" (if org-log-note-previous-state
12433 (concat "\"" org-log-note-previous-state "\"")
12434 "\"\"")))))
12435 (if lines (setq note (concat note " \\\\")))
12436 (push note lines))
12437 (when (or current-prefix-arg org-note-abort)
12438 (when org-log-into-drawer
12439 (org-remove-empty-drawer-at
12440 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12441 org-log-note-marker))
12442 (setq lines nil))
12443 (when lines
12444 (with-current-buffer (marker-buffer org-log-note-marker)
12445 (save-excursion
12446 (goto-char org-log-note-marker)
12447 (move-marker org-log-note-marker nil)
12448 (end-of-line 1)
12449 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12450 (setq ind (save-excursion
12451 (if (ignore-errors (goto-char (org-in-item-p)))
12452 (let ((struct (org-list-struct)))
12453 (org-list-get-ind
12454 (org-list-get-top-point struct) struct))
12455 (skip-chars-backward " \r\t\n")
12456 (cond
12457 ((and (org-at-heading-p)
12458 org-adapt-indentation)
12459 (1+ (org-current-level)))
12460 ((org-at-heading-p) 0)
12461 (t (org-get-indentation))))))
12462 (setq bul (org-list-bullet-string "-"))
12463 (org-indent-line-to ind)
12464 (insert bul (pop lines))
12465 (let ((ind-body (+ (length bul) ind)))
12466 (while lines
12467 (insert "\n")
12468 (org-indent-line-to ind-body)
12469 (insert (pop lines))))
12470 (message "Note stored")
12471 (org-back-to-heading t)
12472 (org-cycle-hide-drawers 'children)))))
12473 (set-window-configuration org-log-note-window-configuration)
12474 (with-current-buffer (marker-buffer org-log-note-return-to)
12475 (goto-char org-log-note-return-to))
12476 (move-marker org-log-note-return-to nil)
12477 (and org-log-post-message (message "%s" org-log-post-message)))
12479 (defun org-remove-empty-drawer-at (drawer pos)
12480 "Remove an empty drawer DRAWER at position POS.
12481 POS may also be a marker."
12482 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12483 (save-excursion
12484 (save-restriction
12485 (widen)
12486 (goto-char pos)
12487 (if (org-in-regexp
12488 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12489 (replace-match ""))))))
12491 (defun org-sparse-tree (&optional arg)
12492 "Create a sparse tree, prompt for the details.
12493 This command can create sparse trees. You first need to select the type
12494 of match used to create the tree:
12496 t Show all TODO entries.
12497 T Show entries with a specific TODO keyword.
12498 m Show entries selected by a tags/property match.
12499 p Enter a property name and its value (both with completion on existing
12500 names/values) and show entries with that property.
12501 r Show entries matching a regular expression (`/' can be used as well)
12502 d Show deadlines due within `org-deadline-warning-days'.
12503 b Show deadlines and scheduled items before a date.
12504 a Show deadlines and scheduled items after a date."
12505 (interactive "P")
12506 (let (ans kwd value)
12507 (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")
12508 (setq ans (read-char-exclusive))
12509 (cond
12510 ((equal ans ?d)
12511 (call-interactively 'org-check-deadlines))
12512 ((equal ans ?b)
12513 (call-interactively 'org-check-before-date))
12514 ((equal ans ?a)
12515 (call-interactively 'org-check-after-date))
12516 ((equal ans ?D)
12517 (call-interactively 'org-check-dates-range))
12518 ((equal ans ?t)
12519 (org-show-todo-tree nil))
12520 ((equal ans ?T)
12521 (org-show-todo-tree '(4)))
12522 ((member ans '(?T ?m))
12523 (call-interactively 'org-match-sparse-tree))
12524 ((member ans '(?p ?P))
12525 (setq kwd (org-icompleting-read "Property: "
12526 (mapcar 'list (org-buffer-property-keys))))
12527 (setq value (org-icompleting-read "Value: "
12528 (mapcar 'list (org-property-values kwd))))
12529 (unless (string-match "\\`{.*}\\'" value)
12530 (setq value (concat "\"" value "\"")))
12531 (org-match-sparse-tree arg (concat kwd "=" value)))
12532 ((member ans '(?r ?R ?/))
12533 (call-interactively 'org-occur))
12534 (t (error "No such sparse tree command \"%c\"" ans)))))
12536 (defvar org-occur-highlights nil
12537 "List of overlays used for occur matches.")
12538 (make-variable-buffer-local 'org-occur-highlights)
12539 (defvar org-occur-parameters nil
12540 "Parameters of the active org-occur calls.
12541 This is a list, each call to org-occur pushes as cons cell,
12542 containing the regular expression and the callback, onto the list.
12543 The list can contain several entries if `org-occur' has been called
12544 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12545 will only contain one set of parameters. When the highlights are
12546 removed (for example with `C-c C-c', or with the next edit (depending
12547 on `org-remove-highlights-with-change'), this variable is emptied
12548 as well.")
12549 (make-variable-buffer-local 'org-occur-parameters)
12551 (defun org-occur (regexp &optional keep-previous callback)
12552 "Make a compact tree which shows all matches of REGEXP.
12553 The tree will show the lines where the regexp matches, and all higher
12554 headlines above the match. It will also show the heading after the match,
12555 to make sure editing the matching entry is easy.
12556 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12557 call to `org-occur' will be kept, to allow stacking of calls to this
12558 command.
12559 If CALLBACK is non-nil, it is a function which is called to confirm
12560 that the match should indeed be shown."
12561 (interactive "sRegexp: \nP")
12562 (when (equal regexp "")
12563 (error "Regexp cannot be empty"))
12564 (unless keep-previous
12565 (org-remove-occur-highlights nil nil t))
12566 (push (cons regexp callback) org-occur-parameters)
12567 (let ((cnt 0))
12568 (save-excursion
12569 (goto-char (point-min))
12570 (if (or (not keep-previous) ; do not want to keep
12571 (not org-occur-highlights)) ; no previous matches
12572 ;; hide everything
12573 (org-overview))
12574 (while (re-search-forward regexp nil t)
12575 (when (or (not callback)
12576 (save-match-data (funcall callback)))
12577 (setq cnt (1+ cnt))
12578 (when org-highlight-sparse-tree-matches
12579 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12580 (org-show-context 'occur-tree))))
12581 (when org-remove-highlights-with-change
12582 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12583 nil 'local))
12584 (unless org-sparse-tree-open-archived-trees
12585 (org-hide-archived-subtrees (point-min) (point-max)))
12586 (run-hooks 'org-occur-hook)
12587 (if (org-called-interactively-p 'interactive)
12588 (message "%d match(es) for regexp %s" cnt regexp))
12589 cnt))
12591 (defun org-occur-next-match (&optional n reset)
12592 "Function for `next-error-function' to find sparse tree matches.
12593 N is the number of matches to move, when negative move backwards.
12594 RESET is entirely ignored - this function always goes back to the
12595 starting point when no match is found."
12596 (let* ((limit (if (< n 0) (point-min) (point-max)))
12597 (search-func (if (< n 0)
12598 'previous-single-char-property-change
12599 'next-single-char-property-change))
12600 (n (abs n))
12601 (pos (point))
12603 (catch 'exit
12604 (while (setq p1 (funcall search-func (point) 'org-type))
12605 (when (equal p1 limit)
12606 (goto-char pos)
12607 (error "No more matches"))
12608 (when (equal (get-char-property p1 'org-type) 'org-occur)
12609 (setq n (1- n))
12610 (when (= n 0)
12611 (goto-char p1)
12612 (throw 'exit (point))))
12613 (goto-char p1))
12614 (goto-char p1)
12615 (error "No more matches"))))
12617 (defun org-show-context (&optional key)
12618 "Make sure point and context are visible.
12619 How much context is shown depends upon the variables
12620 `org-show-hierarchy-above', `org-show-following-heading',
12621 `org-show-entry-below' and `org-show-siblings'."
12622 (let ((heading-p (org-at-heading-p t))
12623 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12624 (following-p (org-get-alist-option org-show-following-heading key))
12625 (entry-p (org-get-alist-option org-show-entry-below key))
12626 (siblings-p (org-get-alist-option org-show-siblings key)))
12627 (catch 'exit
12628 ;; Show heading or entry text
12629 (if (and heading-p (not entry-p))
12630 (org-flag-heading nil) ; only show the heading
12631 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12632 (org-show-hidden-entry))) ; show entire entry
12633 (when following-p
12634 ;; Show next sibling, or heading below text
12635 (save-excursion
12636 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12637 (org-flag-heading nil))))
12638 (when siblings-p (org-show-siblings))
12639 (when hierarchy-p
12640 ;; show all higher headings, possibly with siblings
12641 (save-excursion
12642 (while (and (condition-case nil
12643 (progn (org-up-heading-all 1) t)
12644 (error nil))
12645 (not (bobp)))
12646 (org-flag-heading nil)
12647 (when siblings-p (org-show-siblings))))))))
12649 (defvar org-reveal-start-hook nil
12650 "Hook run before revealing a location.")
12652 (defun org-reveal (&optional siblings)
12653 "Show current entry, hierarchy above it, and the following headline.
12654 This can be used to show a consistent set of context around locations
12655 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12656 not t for the search context.
12658 With optional argument SIBLINGS, on each level of the hierarchy all
12659 siblings are shown. This repairs the tree structure to what it would
12660 look like when opened with hierarchical calls to `org-cycle'.
12661 With double optional argument \\[universal-argument] \\[universal-argument], \
12662 go to the parent and show the
12663 entire tree."
12664 (interactive "P")
12665 (run-hooks 'org-reveal-start-hook)
12666 (let ((org-show-hierarchy-above t)
12667 (org-show-following-heading t)
12668 (org-show-siblings (if siblings t org-show-siblings)))
12669 (org-show-context nil))
12670 (when (equal siblings '(16))
12671 (save-excursion
12672 (when (org-up-heading-safe)
12673 (org-show-subtree)
12674 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12676 (defun org-highlight-new-match (beg end)
12677 "Highlight from BEG to END and mark the highlight is an occur headline."
12678 (let ((ov (make-overlay beg end)))
12679 (overlay-put ov 'face 'secondary-selection)
12680 (overlay-put ov 'org-type 'org-occur)
12681 (push ov org-occur-highlights)))
12683 (defun org-remove-occur-highlights (&optional beg end noremove)
12684 "Remove the occur highlights from the buffer.
12685 BEG and END are ignored. If NOREMOVE is nil, remove this function
12686 from the `before-change-functions' in the current buffer."
12687 (interactive)
12688 (unless org-inhibit-highlight-removal
12689 (mapc 'delete-overlay org-occur-highlights)
12690 (setq org-occur-highlights nil)
12691 (setq org-occur-parameters nil)
12692 (unless noremove
12693 (remove-hook 'before-change-functions
12694 'org-remove-occur-highlights 'local))))
12696 ;;;; Priorities
12698 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12699 "Regular expression matching the priority indicator.")
12701 (defvar org-remove-priority-next-time nil)
12703 (defun org-priority-up ()
12704 "Increase the priority of the current item."
12705 (interactive)
12706 (org-priority 'up))
12708 (defun org-priority-down ()
12709 "Decrease the priority of the current item."
12710 (interactive)
12711 (org-priority 'down))
12713 (defun org-priority (&optional action)
12714 "Change the priority of an item by ARG.
12715 ACTION can be `set', `up', `down', or a character."
12716 (interactive)
12717 (unless org-enable-priority-commands
12718 (error "Priority commands are disabled"))
12719 (setq action (or action 'set))
12720 (let (current new news have remove)
12721 (save-excursion
12722 (org-back-to-heading t)
12723 (if (looking-at org-priority-regexp)
12724 (setq current (string-to-char (match-string 2))
12725 have t))
12726 (cond
12727 ((eq action 'remove)
12728 (setq remove t new ?\ ))
12729 ((or (eq action 'set)
12730 (if (featurep 'xemacs) (characterp action) (integerp action)))
12731 (if (not (eq action 'set))
12732 (setq new action)
12733 (message "Priority %c-%c, SPC to remove: "
12734 org-highest-priority org-lowest-priority)
12735 (save-match-data
12736 (setq new (read-char-exclusive))))
12737 (if (and (= (upcase org-highest-priority) org-highest-priority)
12738 (= (upcase org-lowest-priority) org-lowest-priority))
12739 (setq new (upcase new)))
12740 (cond ((equal new ?\ ) (setq remove t))
12741 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12742 (error "Priority must be between `%c' and `%c'"
12743 org-highest-priority org-lowest-priority))))
12744 ((eq action 'up)
12745 (setq new (if have
12746 (1- current) ; normal cycling
12747 ;; last priority was empty
12748 (if (eq last-command this-command)
12749 org-lowest-priority ; wrap around empty to lowest
12750 ;; default
12751 (if org-priority-start-cycle-with-default
12752 org-default-priority
12753 (1- org-default-priority))))))
12754 ((eq action 'down)
12755 (setq new (if have
12756 (1+ current) ; normal cycling
12757 ;; last priority was empty
12758 (if (eq last-command this-command)
12759 org-highest-priority ; wrap around empty to highest
12760 ;; default
12761 (if org-priority-start-cycle-with-default
12762 org-default-priority
12763 (1+ org-default-priority))))))
12764 (t (error "Invalid action")))
12765 (if (or (< (upcase new) org-highest-priority)
12766 (> (upcase new) org-lowest-priority))
12767 (if (and (memq action '(up down))
12768 (not have) (not (eq last-command this-command)))
12769 ;; `new' is from default priority
12770 (error
12771 "The default can not be set, see `org-default-priority' why")
12772 ;; normal cycling: `new' is beyond highest/lowest priority
12773 ;; and is wrapped around to the empty priority
12774 (setq remove t)))
12775 (setq news (format "%c" new))
12776 (if have
12777 (if remove
12778 (replace-match "" t t nil 1)
12779 (replace-match news t t nil 2))
12780 (if remove
12781 (error "No priority cookie found in line")
12782 (let ((case-fold-search nil))
12783 (looking-at org-todo-line-regexp))
12784 (if (match-end 2)
12785 (progn
12786 (goto-char (match-end 2))
12787 (insert " [#" news "]"))
12788 (goto-char (match-beginning 3))
12789 (insert "[#" news "] "))))
12790 (org-preserve-lc (org-set-tags nil 'align)))
12791 (if remove
12792 (message "Priority removed")
12793 (message "Priority of current item set to %s" news))))
12795 (defun org-get-priority (s)
12796 "Find priority cookie and return priority."
12797 (if (functionp org-get-priority-function)
12798 (funcall org-get-priority-function)
12799 (save-match-data
12800 (if (not (string-match org-priority-regexp s))
12801 (* 1000 (- org-lowest-priority org-default-priority))
12802 (* 1000 (- org-lowest-priority
12803 (string-to-char (match-string 2 s))))))))
12805 ;;;; Tags
12807 (defvar org-agenda-archives-mode)
12808 (defvar org-map-continue-from nil
12809 "Position from where mapping should continue.
12810 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12812 (defvar org-scanner-tags nil
12813 "The current tag list while the tags scanner is running.")
12814 (defvar org-trust-scanner-tags nil
12815 "Should `org-get-tags-at' use the tags for the scanner.
12816 This is for internal dynamical scoping only.
12817 When this is non-nil, the function `org-get-tags-at' will return the value
12818 of `org-scanner-tags' instead of building the list by itself. This
12819 can lead to large speed-ups when the tags scanner is used in a file with
12820 many entries, and when the list of tags is retrieved, for example to
12821 obtain a list of properties. Building the tags list for each entry in such
12822 a file becomes an N^2 operation - but with this variable set, it scales
12823 as N.")
12825 (defun org-scan-tags (action matcher todo-only &optional start-level)
12826 "Scan headline tags with inheritance and produce output ACTION.
12828 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12829 or `agenda' to produce an entry list for an agenda view. It can also be
12830 a Lisp form or a function that should be called at each matched headline, in
12831 this case the return value is a list of all return values from these calls.
12833 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12834 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12835 only lines with a not-done TODO keyword are included in the output.
12836 This should be the same variable that was scoped into
12837 and set by `org-make-tags-matcher' when it constructed MATCHER.
12839 START-LEVEL can be a string with asterisks, reducing the scope to
12840 headlines matching this string."
12841 (require 'org-agenda)
12842 (let* ((re (concat "^"
12843 (if start-level
12844 ;; Get the correct level to match
12845 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12846 org-outline-regexp)
12847 " *\\(\\<\\("
12848 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12849 (org-re
12850 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12851 (props (list 'face 'default
12852 'done-face 'org-agenda-done
12853 'undone-face 'default
12854 'mouse-face 'highlight
12855 'org-not-done-regexp org-not-done-regexp
12856 'org-todo-regexp org-todo-regexp
12857 'org-complex-heading-regexp org-complex-heading-regexp
12858 'help-echo
12859 (format "mouse-2 or RET jump to org file %s"
12860 (abbreviate-file-name
12861 (or (buffer-file-name (buffer-base-buffer))
12862 (buffer-name (buffer-base-buffer)))))))
12863 (case-fold-search nil)
12864 (org-map-continue-from nil)
12865 lspos tags tags-list
12866 (tags-alist (list (cons 0 org-file-tags)))
12867 (llast 0) rtn rtn1 level category i txt
12868 todo marker entry priority)
12869 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12870 (setq action (list 'lambda nil action)))
12871 (save-excursion
12872 (goto-char (point-min))
12873 (when (eq action 'sparse-tree)
12874 (org-overview)
12875 (org-remove-occur-highlights))
12876 (while (re-search-forward re nil t)
12877 (setq org-map-continue-from nil)
12878 (catch :skip
12879 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12880 tags (if (match-end 4) (org-match-string-no-properties 4)))
12881 (goto-char (setq lspos (match-beginning 0)))
12882 (setq level (org-reduced-level (funcall outline-level))
12883 category (org-get-category))
12884 (setq i llast llast level)
12885 ;; remove tag lists from same and sublevels
12886 (while (>= i level)
12887 (when (setq entry (assoc i tags-alist))
12888 (setq tags-alist (delete entry tags-alist)))
12889 (setq i (1- i)))
12890 ;; add the next tags
12891 (when tags
12892 (setq tags (org-split-string tags ":")
12893 tags-alist
12894 (cons (cons level tags) tags-alist)))
12895 ;; compile tags for current headline
12896 (setq tags-list
12897 (if org-use-tag-inheritance
12898 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12899 tags)
12900 org-scanner-tags tags-list)
12901 (when org-use-tag-inheritance
12902 (setcdr (car tags-alist)
12903 (mapcar (lambda (x)
12904 (setq x (copy-sequence x))
12905 (org-add-prop-inherited x))
12906 (cdar tags-alist))))
12907 (when (and tags org-use-tag-inheritance
12908 (or (not (eq t org-use-tag-inheritance))
12909 org-tags-exclude-from-inheritance))
12910 ;; selective inheritance, remove uninherited ones
12911 (setcdr (car tags-alist)
12912 (org-remove-uninherited-tags (cdar tags-alist))))
12913 (when (and
12915 ;; eval matcher only when the todo condition is OK
12916 (and (or (not todo-only) (member todo org-not-done-keywords))
12917 (let ((case-fold-search t) (org-trust-scanner-tags t))
12918 (eval matcher)))
12920 ;; Call the skipper, but return t if it does not skip,
12921 ;; so that the `and' form continues evaluating
12922 (progn
12923 (unless (eq action 'sparse-tree) (org-agenda-skip))
12926 ;; Check if timestamps are deselecting this entry
12927 (or (not todo-only)
12928 (and (member todo org-not-done-keywords)
12929 (or (not org-agenda-tags-todo-honor-ignore-options)
12930 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12932 ;; Extra check for the archive tag
12933 ;; FIXME: Does the skipper already do this????
12935 (not (member org-archive-tag tags-list))
12936 ;; we have an archive tag, should we use this anyway?
12937 (or (not org-agenda-skip-archived-trees)
12938 (and (eq action 'agenda) org-agenda-archives-mode))))
12940 ;; select this headline
12942 (cond
12943 ((eq action 'sparse-tree)
12944 (and org-highlight-sparse-tree-matches
12945 (org-get-heading) (match-end 0)
12946 (org-highlight-new-match
12947 (match-beginning 1) (match-end 1)))
12948 (org-show-context 'tags-tree))
12949 ((eq action 'agenda)
12950 (setq txt (org-agenda-format-item
12952 (concat
12953 (if (eq org-tags-match-list-sublevels 'indented)
12954 (make-string (1- level) ?.) "")
12955 (org-get-heading))
12956 category
12957 tags-list)
12958 priority (org-get-priority txt))
12959 (goto-char lspos)
12960 (setq marker (org-agenda-new-marker))
12961 (org-add-props txt props
12962 'org-marker marker 'org-hd-marker marker 'org-category category
12963 'todo-state todo
12964 'priority priority 'type "tagsmatch")
12965 (push txt rtn))
12966 ((functionp action)
12967 (setq org-map-continue-from nil)
12968 (save-excursion
12969 (setq rtn1 (funcall action))
12970 (push rtn1 rtn)))
12971 (t (error "Invalid action")))
12973 ;; if we are to skip sublevels, jump to end of subtree
12974 (unless org-tags-match-list-sublevels
12975 (org-end-of-subtree t)
12976 (backward-char 1))))
12977 ;; Get the correct position from where to continue
12978 (if org-map-continue-from
12979 (goto-char org-map-continue-from)
12980 (and (= (point) lspos) (end-of-line 1)))))
12981 (when (and (eq action 'sparse-tree)
12982 (not org-sparse-tree-open-archived-trees))
12983 (org-hide-archived-subtrees (point-min) (point-max)))
12984 (nreverse rtn)))
12986 (defun org-remove-uninherited-tags (tags)
12987 "Remove all tags that are not inherited from the list TAGS."
12988 (cond
12989 ((eq org-use-tag-inheritance t)
12990 (if org-tags-exclude-from-inheritance
12991 (org-delete-all org-tags-exclude-from-inheritance tags)
12992 tags))
12993 ((not org-use-tag-inheritance) nil)
12994 ((stringp org-use-tag-inheritance)
12995 (delq nil (mapcar
12996 (lambda (x)
12997 (if (and (string-match org-use-tag-inheritance x)
12998 (not (member x org-tags-exclude-from-inheritance)))
12999 x nil))
13000 tags)))
13001 ((listp org-use-tag-inheritance)
13002 (delq nil (mapcar
13003 (lambda (x)
13004 (if (member x org-use-tag-inheritance) x nil))
13005 tags)))))
13007 (defun org-match-sparse-tree (&optional todo-only match)
13008 "Create a sparse tree according to tags string MATCH.
13009 MATCH can contain positive and negative selection of tags, like
13010 \"+WORK+URGENT-WITHBOSS\".
13011 If optional argument TODO-ONLY is non-nil, only select lines that are
13012 also TODO lines."
13013 (interactive "P")
13014 (org-prepare-agenda-buffers (list (current-buffer)))
13015 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13017 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13019 (defvar org-cached-props nil)
13020 (defun org-cached-entry-get (pom property)
13021 (if (or (eq t org-use-property-inheritance)
13022 (and (stringp org-use-property-inheritance)
13023 (string-match org-use-property-inheritance property))
13024 (and (listp org-use-property-inheritance)
13025 (member property org-use-property-inheritance)))
13026 ;; Caching is not possible, check it directly
13027 (org-entry-get pom property 'inherit)
13028 ;; Get all properties, so that we can do complicated checks easily
13029 (cdr (assoc property (or org-cached-props
13030 (setq org-cached-props
13031 (org-entry-properties pom)))))))
13033 (defun org-global-tags-completion-table (&optional files)
13034 "Return the list of all tags in all agenda buffer/files.
13035 Optional FILES argument is a list of files to which can be used
13036 instead of the agenda files."
13037 (save-excursion
13038 (org-uniquify
13039 (delq nil
13040 (apply 'append
13041 (mapcar
13042 (lambda (file)
13043 (set-buffer (find-file-noselect file))
13044 (append (org-get-buffer-tags)
13045 (mapcar (lambda (x) (if (stringp (car-safe x))
13046 (list (car-safe x)) nil))
13047 org-tag-alist)))
13048 (if (and files (car files))
13049 files
13050 (org-agenda-files))))))))
13052 (defun org-make-tags-matcher (match)
13053 "Create the TAGS/TODO matcher form for the selection string MATCH.
13055 The variable `todo-only' is scoped dynamically into this function; it will be
13056 set to t if the matcher restricts matching to TODO entries,
13057 otherwise will not be touched.
13059 Returns a cons of the selection string MATCH and the constructed
13060 lisp form implementing the matcher. The matcher is to be
13061 evaluated at an Org entry, with point on the headline,
13062 and returns t if the entry matches the
13063 selection string MATCH. The returned lisp form references
13064 two variables with information about the entry, which must be
13065 bound around the form's evaluation: todo, the TODO keyword at the
13066 entry (or nil of none); and tags-list, the list of all tags at the
13067 entry including inherited ones. Additionally, the category
13068 of the entry (if any) must be specified as the text property
13069 'org-category on the headline.
13071 See also `org-scan-tags'.
13073 (declare (special todo-only))
13074 (unless (boundp 'todo-only)
13075 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13076 (unless match
13077 ;; Get a new match request, with completion
13078 (let ((org-last-tags-completion-table
13079 (org-global-tags-completion-table)))
13080 (setq match (org-completing-read-no-i
13081 "Match: " 'org-tags-completion-function nil nil nil
13082 'org-tags-history))))
13084 ;; Parse the string and create a lisp form
13085 (let ((match0 match)
13086 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13087 minus tag mm
13088 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13089 orterms term orlist re-p str-p level-p level-op time-p
13090 prop-p pn pv po gv rest)
13091 (if (string-match "/+" match)
13092 ;; match contains also a todo-matching request
13093 (progn
13094 (setq tagsmatch (substring match 0 (match-beginning 0))
13095 todomatch (substring match (match-end 0)))
13096 (if (string-match "^!" todomatch)
13097 (setq todo-only t todomatch (substring todomatch 1)))
13098 (if (string-match "^\\s-*$" todomatch)
13099 (setq todomatch nil)))
13100 ;; only matching tags
13101 (setq tagsmatch match todomatch nil))
13103 ;; Make the tags matcher
13104 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13105 (setq tagsmatcher t)
13106 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13107 (while (setq term (pop orterms))
13108 (while (and (equal (substring term -1) "\\") orterms)
13109 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13110 (while (string-match re term)
13111 (setq rest (substring term (match-end 0))
13112 minus (and (match-end 1)
13113 (equal (match-string 1 term) "-"))
13114 tag (save-match-data (replace-regexp-in-string
13115 "\\\\-" "-"
13116 (match-string 2 term)))
13117 re-p (equal (string-to-char tag) ?{)
13118 level-p (match-end 4)
13119 prop-p (match-end 5)
13120 mm (cond
13121 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13122 (level-p
13123 (setq level-op (org-op-to-function (match-string 3 term)))
13124 `(,level-op level ,(string-to-number
13125 (match-string 4 term))))
13126 (prop-p
13127 (setq pn (match-string 5 term)
13128 po (match-string 6 term)
13129 pv (match-string 7 term)
13130 re-p (equal (string-to-char pv) ?{)
13131 str-p (equal (string-to-char pv) ?\")
13132 time-p (save-match-data
13133 (string-match "^\"[[<].*[]>]\"$" pv))
13134 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13135 (if time-p (setq pv (org-matcher-time pv)))
13136 (setq po (org-op-to-function po (if time-p 'time str-p)))
13137 (cond
13138 ((equal pn "CATEGORY")
13139 (setq gv '(get-text-property (point) 'org-category)))
13140 ((equal pn "TODO")
13141 (setq gv 'todo))
13143 (setq gv `(org-cached-entry-get nil ,pn))))
13144 (if re-p
13145 (if (eq po 'org<>)
13146 `(not (string-match ,pv (or ,gv "")))
13147 `(string-match ,pv (or ,gv "")))
13148 (if str-p
13149 `(,po (or ,gv "") ,pv)
13150 `(,po (string-to-number (or ,gv ""))
13151 ,(string-to-number pv) ))))
13152 (t `(member ,tag tags-list)))
13153 mm (if minus (list 'not mm) mm)
13154 term rest)
13155 (push mm tagsmatcher))
13156 (push (if (> (length tagsmatcher) 1)
13157 (cons 'and tagsmatcher)
13158 (car tagsmatcher))
13159 orlist)
13160 (setq tagsmatcher nil))
13161 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13162 (setq tagsmatcher
13163 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13164 ;; Make the todo matcher
13165 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13166 (setq todomatcher t)
13167 (setq orterms (org-split-string todomatch "|") orlist nil)
13168 (while (setq term (pop orterms))
13169 (while (string-match re term)
13170 (setq minus (and (match-end 1)
13171 (equal (match-string 1 term) "-"))
13172 kwd (match-string 2 term)
13173 re-p (equal (string-to-char kwd) ?{)
13174 term (substring term (match-end 0))
13175 mm (if re-p
13176 `(string-match ,(substring kwd 1 -1) todo)
13177 (list 'equal 'todo kwd))
13178 mm (if minus (list 'not mm) mm))
13179 (push mm todomatcher))
13180 (push (if (> (length todomatcher) 1)
13181 (cons 'and todomatcher)
13182 (car todomatcher))
13183 orlist)
13184 (setq todomatcher nil))
13185 (setq todomatcher (if (> (length orlist) 1)
13186 (cons 'or orlist) (car orlist))))
13188 ;; Return the string and lisp forms of the matcher
13189 (setq matcher (if todomatcher
13190 (list 'and tagsmatcher todomatcher)
13191 tagsmatcher))
13192 (when todo-only
13193 (setq matcher (list 'and '(member todo org-not-done-keywords)
13194 matcher)))
13195 (cons match0 matcher)))
13197 (defun org-op-to-function (op &optional stringp)
13198 "Turn an operator into the appropriate function."
13199 (setq op
13200 (cond
13201 ((equal op "<" ) '(< string< org-time<))
13202 ((equal op ">" ) '(> org-string> org-time>))
13203 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13204 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13205 ((member op '("=" "==")) '(= string= org-time=))
13206 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13207 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13209 (defun org<> (a b) (not (= a b)))
13210 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13211 (defun org-string>= (a b) (not (string< a b)))
13212 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13213 (defun org-string<> (a b) (not (string= a b)))
13214 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13215 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< 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) (org<> a b)))
13220 (defun org-2ft (s)
13221 "Convert S to a floating point time.
13222 If S is already a number, just return it. If it is a string, parse
13223 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13224 (cond
13225 ((numberp s) s)
13226 ((stringp s)
13227 (condition-case nil
13228 (float-time (apply 'encode-time (org-parse-time-string s)))
13229 (error 0.)))
13230 (t 0.)))
13232 (defun org-time-today ()
13233 "Time in seconds today at 0:00.
13234 Returns the float number of seconds since the beginning of the
13235 epoch to the beginning of today (00:00)."
13236 (float-time (apply 'encode-time
13237 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13239 (defun org-matcher-time (s)
13240 "Interpret a time comparison value."
13241 (save-match-data
13242 (cond
13243 ((string= s "<now>") (float-time))
13244 ((string= s "<today>") (org-time-today))
13245 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13246 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13247 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13248 (+ (org-time-today)
13249 (* (string-to-number (match-string 1 s))
13250 (cdr (assoc (match-string 2 s)
13251 '(("d" . 86400.0) ("w" . 604800.0)
13252 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13253 (t (org-2ft s)))))
13255 (defun org-match-any-p (re list)
13256 "Does re match any element of list?"
13257 (setq list (mapcar (lambda (x) (string-match re x)) list))
13258 (delq nil list))
13260 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13261 (defvar org-tags-overlay (make-overlay 1 1))
13262 (org-detach-overlay org-tags-overlay)
13264 (defun org-get-local-tags-at (&optional pos)
13265 "Get a list of tags defined in the current headline."
13266 (org-get-tags-at pos 'local))
13268 (defun org-get-local-tags ()
13269 "Get a list of tags defined in the current headline."
13270 (org-get-tags-at nil 'local))
13272 (defun org-get-tags-at (&optional pos local)
13273 "Get a list of all headline tags applicable at POS.
13274 POS defaults to point. If tags are inherited, the list contains
13275 the targets in the same sequence as the headlines appear, i.e.
13276 the tags of the current headline come last.
13277 When LOCAL is non-nil, only return tags from the current headline,
13278 ignore inherited ones."
13279 (interactive)
13280 (if (and org-trust-scanner-tags
13281 (or (not pos) (equal pos (point)))
13282 (not local))
13283 org-scanner-tags
13284 (let (tags ltags lastpos parent)
13285 (save-excursion
13286 (save-restriction
13287 (widen)
13288 (goto-char (or pos (point)))
13289 (save-match-data
13290 (catch 'done
13291 (condition-case nil
13292 (progn
13293 (org-back-to-heading t)
13294 (while (not (equal lastpos (point)))
13295 (setq lastpos (point))
13296 (when (looking-at
13297 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13298 (setq ltags (org-split-string
13299 (org-match-string-no-properties 1) ":"))
13300 (when parent
13301 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13302 (setq tags (append
13303 (if parent
13304 (org-remove-uninherited-tags ltags)
13305 ltags)
13306 tags)))
13307 (or org-use-tag-inheritance (throw 'done t))
13308 (if local (throw 'done t))
13309 (or (org-up-heading-safe) (error nil))
13310 (setq parent t)))
13311 (error nil)))))
13312 (if local
13313 tags
13314 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13316 (defun org-add-prop-inherited (s)
13317 (add-text-properties 0 (length s) '(inherited t) s)
13320 (defun org-toggle-tag (tag &optional onoff)
13321 "Toggle the tag TAG for the current line.
13322 If ONOFF is `on' or `off', don't toggle but set to this state."
13323 (let (res current)
13324 (save-excursion
13325 (org-back-to-heading t)
13326 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13327 (point-at-eol) t)
13328 (progn
13329 (setq current (match-string 1))
13330 (replace-match ""))
13331 (setq current ""))
13332 (setq current (nreverse (org-split-string current ":")))
13333 (cond
13334 ((eq onoff 'on)
13335 (setq res t)
13336 (or (member tag current) (push tag current)))
13337 ((eq onoff 'off)
13338 (or (not (member tag current)) (setq current (delete tag current))))
13339 (t (if (member tag current)
13340 (setq current (delete tag current))
13341 (setq res t)
13342 (push tag current))))
13343 (end-of-line 1)
13344 (if current
13345 (progn
13346 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13347 (org-set-tags nil t))
13348 (delete-horizontal-space))
13349 (run-hooks 'org-after-tags-change-hook))
13350 res))
13352 (defun org-align-tags-here (to-col)
13353 ;; Assumes that this is a headline
13354 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13355 (beginning-of-line 1)
13356 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13357 (< pos (match-beginning 2)))
13358 (progn
13359 (setq tags-l (- (match-end 2) (match-beginning 2)))
13360 (goto-char (match-beginning 1))
13361 (insert " ")
13362 (delete-region (point) (1+ (match-beginning 2)))
13363 (setq ncol (max (current-column)
13364 (1+ col)
13365 (if (> to-col 0)
13366 to-col
13367 (- (abs to-col) tags-l))))
13368 (setq p (point))
13369 (insert (make-string (- ncol (current-column)) ?\ ))
13370 (setq ncol (current-column))
13371 (when indent-tabs-mode (tabify p (point-at-eol)))
13372 (org-move-to-column (min ncol col) t))
13373 (goto-char pos))))
13375 (defun org-set-tags-command (&optional arg just-align)
13376 "Call the set-tags command for the current entry."
13377 (interactive "P")
13378 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13379 (org-set-tags arg just-align)
13380 (save-excursion
13381 (org-back-to-heading t)
13382 (org-set-tags arg just-align))))
13384 (defun org-set-tags-to (data)
13385 "Set the tags of the current entry to DATA, replacing the current tags.
13386 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13387 If DATA is nil or the empty string, any tags will be removed."
13388 (interactive "sTags: ")
13389 (setq data
13390 (cond
13391 ((eq data nil) "")
13392 ((equal data "") "")
13393 ((stringp data)
13394 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13395 ":"))
13396 ((listp data)
13397 (concat ":" (mapconcat 'identity data ":") ":"))
13398 (t nil)))
13399 (when data
13400 (save-excursion
13401 (org-back-to-heading t)
13402 (when (looking-at org-complex-heading-regexp)
13403 (if (match-end 5)
13404 (progn
13405 (goto-char (match-beginning 5))
13406 (insert data)
13407 (delete-region (point) (point-at-eol))
13408 (org-set-tags nil 'align))
13409 (goto-char (point-at-eol))
13410 (insert " " data)
13411 (org-set-tags nil 'align)))
13412 (beginning-of-line 1)
13413 (if (looking-at ".*?\\([ \t]+\\)$")
13414 (delete-region (match-beginning 1) (match-end 1))))))
13416 (defun org-align-all-tags ()
13417 "Align the tags i all headings."
13418 (interactive)
13419 (save-excursion
13420 (or (ignore-errors (org-back-to-heading t))
13421 (outline-next-heading))
13422 (if (org-at-heading-p)
13423 (org-set-tags t)
13424 (message "No headings"))))
13426 (defvar org-indent-indentation-per-level)
13427 (defun org-set-tags (&optional arg just-align)
13428 "Set the tags for the current headline.
13429 With prefix ARG, realign all tags in headings in the current buffer."
13430 (interactive "P")
13431 (let* ((re org-outline-regexp-bol)
13432 (current (unless arg (org-get-tags-string)))
13433 (col (current-column))
13434 (org-setting-tags t)
13435 table current-tags inherited-tags ; computed below when needed
13436 tags p0 c0 c1 rpl di tc level)
13437 (if arg
13438 (save-excursion
13439 (goto-char (point-min))
13440 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13441 (while (re-search-forward re nil t)
13442 (org-set-tags nil t)
13443 (end-of-line 1)))
13444 (message "All tags realigned to column %d" org-tags-column))
13445 (if just-align
13446 (setq tags current)
13447 ;; Get a new set of tags from the user
13448 (save-excursion
13449 (setq table (append org-tag-persistent-alist
13450 org-tag-alist
13451 (org-get-buffer-tags)
13452 (and
13453 org-complete-tags-always-offer-all-agenda-tags
13454 (org-global-tags-completion-table
13455 (org-agenda-files))))
13456 org-last-tags-completion-table table
13457 current-tags (org-split-string current ":")
13458 inherited-tags (nreverse
13459 (nthcdr (length current-tags)
13460 (nreverse (org-get-tags-at))))
13461 tags
13462 (if (or (eq t org-use-fast-tag-selection)
13463 (and org-use-fast-tag-selection
13464 (delq nil (mapcar 'cdr table))))
13465 (org-fast-tag-selection
13466 current-tags inherited-tags table
13467 (if org-fast-tag-selection-include-todo
13468 org-todo-key-alist))
13469 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13470 (org-trim
13471 (org-icompleting-read "Tags: "
13472 'org-tags-completion-function
13473 nil nil current 'org-tags-history))))))
13474 (while (string-match "[-+&]+" tags)
13475 ;; No boolean logic, just a list
13476 (setq tags (replace-match ":" t t tags))))
13478 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13480 (if org-tags-sort-function
13481 (setq tags (mapconcat 'identity
13482 (sort (org-split-string
13483 tags (org-re "[^[:alnum:]_@#%]+"))
13484 org-tags-sort-function) ":")))
13486 (if (string-match "\\`[\t ]*\\'" tags)
13487 (setq tags "")
13488 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13489 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13491 ;; Insert new tags at the correct column
13492 (beginning-of-line 1)
13493 (setq level (or (and (looking-at org-outline-regexp)
13494 (- (match-end 0) (point) 1))
13496 (cond
13497 ((and (equal current "") (equal tags "")))
13498 ((re-search-forward
13499 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13500 (point-at-eol) t)
13501 (if (equal tags "")
13502 (setq rpl "")
13503 (goto-char (match-beginning 0))
13504 (setq c0 (current-column)
13505 ;; compute offset for the case of org-indent-mode active
13506 di (if org-indent-mode
13507 (* (1- org-indent-indentation-per-level) (1- level))
13509 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13510 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13511 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13512 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13513 (replace-match rpl t t)
13514 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13515 tags)
13516 (t (error "Tags alignment failed")))
13517 (org-move-to-column col)
13518 (unless just-align
13519 (run-hooks 'org-after-tags-change-hook)))))
13521 (defun org-change-tag-in-region (beg end tag off)
13522 "Add or remove TAG for each entry in the region.
13523 This works in the agenda, and also in an org-mode buffer."
13524 (interactive
13525 (list (region-beginning) (region-end)
13526 (let ((org-last-tags-completion-table
13527 (if (eq major-mode 'org-mode)
13528 (org-get-buffer-tags)
13529 (org-global-tags-completion-table))))
13530 (org-icompleting-read
13531 "Tag: " 'org-tags-completion-function nil nil nil
13532 'org-tags-history))
13533 (progn
13534 (message "[s]et or [r]emove? ")
13535 (equal (read-char-exclusive) ?r))))
13536 (if (fboundp 'deactivate-mark) (deactivate-mark))
13537 (let ((agendap (equal major-mode 'org-agenda-mode))
13538 l1 l2 m buf pos newhead (cnt 0))
13539 (goto-char end)
13540 (setq l2 (1- (org-current-line)))
13541 (goto-char beg)
13542 (setq l1 (org-current-line))
13543 (loop for l from l1 to l2 do
13544 (org-goto-line l)
13545 (setq m (get-text-property (point) 'org-hd-marker))
13546 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13547 (and agendap m))
13548 (setq buf (if agendap (marker-buffer m) (current-buffer))
13549 pos (if agendap m (point)))
13550 (with-current-buffer buf
13551 (save-excursion
13552 (save-restriction
13553 (goto-char pos)
13554 (setq cnt (1+ cnt))
13555 (org-toggle-tag tag (if off 'off 'on))
13556 (setq newhead (org-get-heading)))))
13557 (and agendap (org-agenda-change-all-lines newhead m))))
13558 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13560 (defun org-tags-completion-function (string predicate &optional flag)
13561 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13562 (confirm (lambda (x) (stringp (car x)))))
13563 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13564 (setq s1 (match-string 1 string)
13565 s2 (match-string 2 string))
13566 (setq s1 "" s2 string))
13567 (cond
13568 ((eq flag nil)
13569 ;; try completion
13570 (setq rtn (try-completion s2 ctable confirm))
13571 (if (stringp rtn)
13572 (setq rtn
13573 (concat s1 s2 (substring rtn (length s2))
13574 (if (and org-add-colon-after-tag-completion
13575 (assoc rtn ctable))
13576 ":" ""))))
13577 rtn)
13578 ((eq flag t)
13579 ;; all-completions
13580 (all-completions s2 ctable confirm)
13582 ((eq flag 'lambda)
13583 ;; exact match?
13584 (assoc s2 ctable)))
13587 (defun org-fast-tag-insert (kwd tags face &optional end)
13588 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13589 (insert (format "%-12s" (concat kwd ":"))
13590 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13591 (or end "")))
13593 (defun org-fast-tag-show-exit (flag)
13594 (save-excursion
13595 (org-goto-line 3)
13596 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13597 (replace-match ""))
13598 (when flag
13599 (end-of-line 1)
13600 (org-move-to-column (- (window-width) 19) t)
13601 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13603 (defun org-set-current-tags-overlay (current prefix)
13604 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13605 (if (featurep 'xemacs)
13606 (org-overlay-display org-tags-overlay (concat prefix s)
13607 'secondary-selection)
13608 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13609 (org-overlay-display org-tags-overlay (concat prefix s)))))
13611 (defvar org-last-tag-selection-key nil)
13612 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13613 "Fast tag selection with single keys.
13614 CURRENT is the current list of tags in the headline, INHERITED is the
13615 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13616 possibly with grouping information. TODO-TABLE is a similar table with
13617 TODO keywords, should these have keys assigned to them.
13618 If the keys are nil, a-z are automatically assigned.
13619 Returns the new tags string, or nil to not change the current settings."
13620 (let* ((fulltable (append table todo-table))
13621 (maxlen (apply 'max (mapcar
13622 (lambda (x)
13623 (if (stringp (car x)) (string-width (car x)) 0))
13624 fulltable)))
13625 (buf (current-buffer))
13626 (expert (eq org-fast-tag-selection-single-key 'expert))
13627 (buffer-tags nil)
13628 (fwidth (+ maxlen 3 1 3))
13629 (ncol (/ (- (window-width) 4) fwidth))
13630 (i-face 'org-done)
13631 (c-face 'org-todo)
13632 tg cnt e c char c1 c2 ntable tbl rtn
13633 ov-start ov-end ov-prefix
13634 (exit-after-next org-fast-tag-selection-single-key)
13635 (done-keywords org-done-keywords)
13636 groups ingroup)
13637 (save-excursion
13638 (beginning-of-line 1)
13639 (if (looking-at
13640 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13641 (setq ov-start (match-beginning 1)
13642 ov-end (match-end 1)
13643 ov-prefix "")
13644 (setq ov-start (1- (point-at-eol))
13645 ov-end (1+ ov-start))
13646 (skip-chars-forward "^\n\r")
13647 (setq ov-prefix
13648 (concat
13649 (buffer-substring (1- (point)) (point))
13650 (if (> (current-column) org-tags-column)
13652 (make-string (- org-tags-column (current-column)) ?\ ))))))
13653 (move-overlay org-tags-overlay ov-start ov-end)
13654 (save-window-excursion
13655 (if expert
13656 (set-buffer (get-buffer-create " *Org tags*"))
13657 (delete-other-windows)
13658 (split-window-vertically)
13659 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13660 (erase-buffer)
13661 (org-set-local 'org-done-keywords done-keywords)
13662 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13663 (org-fast-tag-insert "Current" current c-face "\n\n")
13664 (org-fast-tag-show-exit exit-after-next)
13665 (org-set-current-tags-overlay current ov-prefix)
13666 (setq tbl fulltable char ?a cnt 0)
13667 (while (setq e (pop tbl))
13668 (cond
13669 ((equal (car e) :startgroup)
13670 (push '() groups) (setq ingroup t)
13671 (when (not (= cnt 0))
13672 (setq cnt 0)
13673 (insert "\n"))
13674 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13675 ((equal (car e) :endgroup)
13676 (setq ingroup nil cnt 0)
13677 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13678 ((equal e '(:newline))
13679 (when (not (= cnt 0))
13680 (setq cnt 0)
13681 (insert "\n")
13682 (setq e (car tbl))
13683 (while (equal (car tbl) '(:newline))
13684 (insert "\n")
13685 (setq tbl (cdr tbl)))))
13687 (setq tg (copy-sequence (car e)) c2 nil)
13688 (if (cdr e)
13689 (setq c (cdr e))
13690 ;; automatically assign a character.
13691 (setq c1 (string-to-char
13692 (downcase (substring
13693 tg (if (= (string-to-char tg) ?@) 1 0)))))
13694 (if (or (rassoc c1 ntable) (rassoc c1 table))
13695 (while (or (rassoc char ntable) (rassoc char table))
13696 (setq char (1+ char)))
13697 (setq c2 c1))
13698 (setq c (or c2 char)))
13699 (if ingroup (push tg (car groups)))
13700 (setq tg (org-add-props tg nil 'face
13701 (cond
13702 ((not (assoc tg table))
13703 (org-get-todo-face tg))
13704 ((member tg current) c-face)
13705 ((member tg inherited) i-face)
13706 (t nil))))
13707 (if (and (= cnt 0) (not ingroup)) (insert " "))
13708 (insert "[" c "] " tg (make-string
13709 (- fwidth 4 (length tg)) ?\ ))
13710 (push (cons tg c) ntable)
13711 (when (= (setq cnt (1+ cnt)) ncol)
13712 (insert "\n")
13713 (if ingroup (insert " "))
13714 (setq cnt 0)))))
13715 (setq ntable (nreverse ntable))
13716 (insert "\n")
13717 (goto-char (point-min))
13718 (if (not expert) (org-fit-window-to-buffer))
13719 (setq rtn
13720 (catch 'exit
13721 (while t
13722 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13723 (if (not groups) "no " "")
13724 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13725 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13726 (setq org-last-tag-selection-key c)
13727 (cond
13728 ((= c ?\r) (throw 'exit t))
13729 ((= c ?!)
13730 (setq groups (not groups))
13731 (goto-char (point-min))
13732 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13733 ((= c ?\C-c)
13734 (if (not expert)
13735 (org-fast-tag-show-exit
13736 (setq exit-after-next (not exit-after-next)))
13737 (setq expert nil)
13738 (delete-other-windows)
13739 (set-window-buffer (split-window-vertically) " *Org tags*")
13740 (org-switch-to-buffer-other-window " *Org tags*")
13741 (org-fit-window-to-buffer)))
13742 ((or (= c ?\C-g)
13743 (and (= c ?q) (not (rassoc c ntable))))
13744 (org-detach-overlay org-tags-overlay)
13745 (setq quit-flag t))
13746 ((= c ?\ )
13747 (setq current nil)
13748 (if exit-after-next (setq exit-after-next 'now)))
13749 ((= c ?\t)
13750 (condition-case nil
13751 (setq tg (org-icompleting-read
13752 "Tag: "
13753 (append (or buffer-tags
13754 (with-current-buffer buf
13755 (org-get-buffer-tags)))
13756 (mapcar 'car table))))
13757 (quit (setq tg "")))
13758 (when (string-match "\\S-" tg)
13759 (add-to-list 'buffer-tags (list tg))
13760 (if (member tg current)
13761 (setq current (delete tg current))
13762 (push tg current)))
13763 (if exit-after-next (setq exit-after-next 'now)))
13764 ((setq e (rassoc c todo-table) tg (car e))
13765 (with-current-buffer buf
13766 (save-excursion (org-todo tg)))
13767 (if exit-after-next (setq exit-after-next 'now)))
13768 ((setq e (rassoc c ntable) tg (car e))
13769 (if (member tg current)
13770 (setq current (delete tg current))
13771 (loop for g in groups do
13772 (if (member tg g)
13773 (mapc (lambda (x)
13774 (setq current (delete x current)))
13775 g)))
13776 (push tg current))
13777 (if exit-after-next (setq exit-after-next 'now))))
13779 ;; Create a sorted list
13780 (setq current
13781 (sort current
13782 (lambda (a b)
13783 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13784 (if (eq exit-after-next 'now) (throw 'exit t))
13785 (goto-char (point-min))
13786 (beginning-of-line 2)
13787 (delete-region (point) (point-at-eol))
13788 (org-fast-tag-insert "Current" current c-face)
13789 (org-set-current-tags-overlay current ov-prefix)
13790 (while (re-search-forward
13791 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13792 (setq tg (match-string 1))
13793 (add-text-properties
13794 (match-beginning 1) (match-end 1)
13795 (list 'face
13796 (cond
13797 ((member tg current) c-face)
13798 ((member tg inherited) i-face)
13799 (t (get-text-property (match-beginning 1) 'face))))))
13800 (goto-char (point-min)))))
13801 (org-detach-overlay org-tags-overlay)
13802 (if rtn
13803 (mapconcat 'identity current ":")
13804 nil))))
13806 (defun org-get-tags-string ()
13807 "Get the TAGS string in the current headline."
13808 (unless (org-at-heading-p t)
13809 (error "Not on a heading"))
13810 (save-excursion
13811 (beginning-of-line 1)
13812 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13813 (org-match-string-no-properties 1)
13814 "")))
13816 (defun org-get-tags ()
13817 "Get the list of tags specified in the current headline."
13818 (org-split-string (org-get-tags-string) ":"))
13820 (defun org-get-buffer-tags ()
13821 "Get a table of all tags used in the buffer, for completion."
13822 (let (tags)
13823 (save-excursion
13824 (goto-char (point-min))
13825 (while (re-search-forward
13826 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13827 (when (equal (char-after (point-at-bol 0)) ?*)
13828 (mapc (lambda (x) (add-to-list 'tags x))
13829 (org-split-string (org-match-string-no-properties 1) ":")))))
13830 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13831 (mapcar 'list tags)))
13833 ;;;; The mapping API
13835 ;;;###autoload
13836 (defun org-map-entries (func &optional match scope &rest skip)
13837 "Call FUNC at each headline selected by MATCH in SCOPE.
13839 FUNC is a function or a lisp form. The function will be called without
13840 arguments, with the cursor positioned at the beginning of the headline.
13841 The return values of all calls to the function will be collected and
13842 returned as a list.
13844 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13845 does not need to preserve point. After evaluation, the cursor will be
13846 moved to the end of the line (presumably of the headline of the
13847 processed entry) and search continues from there. Under some
13848 circumstances, this may not produce the wanted results. For example,
13849 if you have removed (e.g. archived) the current (sub)tree it could
13850 mean that the next entry will be skipped entirely. In such cases, you
13851 can specify the position from where search should continue by making
13852 FUNC set the variable `org-map-continue-from' to the desired buffer
13853 position.
13855 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13856 Only headlines that are matched by this query will be considered during
13857 the iteration. When MATCH is nil or t, all headlines will be
13858 visited by the iteration.
13860 SCOPE determines the scope of this command. It can be any of:
13862 nil The current buffer, respecting the restriction if any
13863 tree The subtree started with the entry at point
13864 region The entries within the active region, if any
13865 region-start-level
13866 The entries within the active region, but only those at
13867 the same level than the first one.
13868 file The current buffer, without restriction
13869 file-with-archives
13870 The current buffer, and any archives associated with it
13871 agenda All agenda files
13872 agenda-with-archives
13873 All agenda files with any archive files associated with them
13874 \(file1 file2 ...)
13875 If this is a list, all files in the list will be scanned
13877 The remaining args are treated as settings for the skipping facilities of
13878 the scanner. The following items can be given here:
13880 archive skip trees with the archive tag.
13881 comment skip trees with the COMMENT keyword
13882 function or Emacs Lisp form:
13883 will be used as value for `org-agenda-skip-function', so whenever
13884 the function returns t, FUNC will not be called for that
13885 entry and search will continue from the point where the
13886 function leaves it.
13888 If your function needs to retrieve the tags including inherited tags
13889 at the *current* entry, you can use the value of the variable
13890 `org-scanner-tags' which will be much faster than getting the value
13891 with `org-get-tags-at'. If your function gets properties with
13892 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13893 to t around the call to `org-entry-properties' to get the same speedup.
13894 Note that if your function moves around to retrieve tags and properties at
13895 a *different* entry, you cannot use these techniques."
13896 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13897 (not (org-region-active-p)))
13898 (let* ((org-agenda-archives-mode nil) ; just to make sure
13899 (org-agenda-skip-archived-trees (memq 'archive skip))
13900 (org-agenda-skip-comment-trees (memq 'comment skip))
13901 (org-agenda-skip-function
13902 (car (org-delete-all '(comment archive) skip)))
13903 (org-tags-match-list-sublevels t)
13904 (start-level (eq scope 'region-start-level))
13905 matcher file res
13906 org-todo-keywords-for-agenda
13907 org-done-keywords-for-agenda
13908 org-todo-keyword-alist-for-agenda
13909 org-drawers-for-agenda
13910 org-tag-alist-for-agenda
13911 todo-only)
13913 (cond
13914 ((eq match t) (setq matcher t))
13915 ((eq match nil) (setq matcher t))
13916 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13918 (save-excursion
13919 (save-restriction
13920 (cond ((eq scope 'tree)
13921 (org-back-to-heading t)
13922 (org-narrow-to-subtree)
13923 (setq scope nil))
13924 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13925 (org-region-active-p))
13926 ;; If needed, set start-level to a string like "2"
13927 (when start-level
13928 (save-excursion
13929 (goto-char (region-beginning))
13930 (unless (org-at-heading-p) (outline-next-heading))
13931 (setq start-level (org-current-level))))
13932 (narrow-to-region (region-beginning)
13933 (save-excursion
13934 (goto-char (region-end))
13935 (unless (and (bolp) (org-at-heading-p))
13936 (outline-next-heading))
13937 (point)))
13938 (setq scope nil)))
13940 (if (not scope)
13941 (progn
13942 (org-prepare-agenda-buffers
13943 (list (buffer-file-name (current-buffer))))
13944 (setq res (org-scan-tags func matcher todo-only start-level)))
13945 ;; Get the right scope
13946 (cond
13947 ((and scope (listp scope) (symbolp (car scope)))
13948 (setq scope (eval scope)))
13949 ((eq scope 'agenda)
13950 (setq scope (org-agenda-files t)))
13951 ((eq scope 'agenda-with-archives)
13952 (setq scope (org-agenda-files t))
13953 (setq scope (org-add-archive-files scope)))
13954 ((eq scope 'file)
13955 (setq scope (list (buffer-file-name))))
13956 ((eq scope 'file-with-archives)
13957 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13958 (org-prepare-agenda-buffers scope)
13959 (while (setq file (pop scope))
13960 (with-current-buffer (org-find-base-buffer-visiting file)
13961 (save-excursion
13962 (save-restriction
13963 (widen)
13964 (goto-char (point-min))
13965 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
13966 res)))
13968 ;;;; Properties
13970 ;;; Setting and retrieving properties
13972 (defconst org-special-properties
13973 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13974 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13975 "The special properties valid in Org-mode.
13977 These are properties that are not defined in the property drawer,
13978 but in some other way.")
13980 (defconst org-default-properties
13981 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13982 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13983 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13984 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13985 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13986 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13987 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13988 "Some properties that are used by Org-mode for various purposes.
13989 Being in this list makes sure that they are offered for completion.")
13991 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13992 "Regular expression matching the first line of a property drawer.")
13994 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13995 "Regular expression matching the last line of a property drawer.")
13997 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13998 "Regular expression matching the first line of a property drawer.")
14000 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14001 "Regular expression matching the first line of a property drawer.")
14003 (defconst org-property-drawer-re
14004 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14005 org-property-end-re "\\)\n?")
14006 "Matches an entire property drawer.")
14008 (defconst org-clock-drawer-re
14009 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14010 org-property-end-re "\\)\n?")
14011 "Matches an entire clock drawer.")
14013 (defsubst org-re-property (property)
14014 "Return a regexp matching PROPERTY.
14015 Match group 1 will be set to the value "
14016 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14018 (defun org-property-action ()
14019 "Do an action on properties."
14020 (interactive)
14021 (let (c)
14022 (org-at-property-p)
14023 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14024 (setq c (read-char-exclusive))
14025 (cond
14026 ((equal c ?s)
14027 (call-interactively 'org-set-property))
14028 ((equal c ?d)
14029 (call-interactively 'org-delete-property))
14030 ((equal c ?D)
14031 (call-interactively 'org-delete-property-globally))
14032 ((equal c ?c)
14033 (call-interactively 'org-compute-property-at-point))
14034 (t (error "No such property action %c" c)))))
14036 (defun org-set-effort (&optional value)
14037 "Set the effort property of the current entry.
14038 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14039 allowed value."
14040 (interactive "P")
14041 (if (equal value 0) (setq value 10))
14042 (let* ((completion-ignore-case t)
14043 (prop org-effort-property)
14044 (cur (org-entry-get nil prop))
14045 (allowed (org-property-get-allowed-values nil prop 'table))
14046 (existing (mapcar 'list (org-property-values prop)))
14048 (val (cond
14049 ((stringp value) value)
14050 ((and allowed (integerp value))
14051 (or (car (nth (1- value) allowed))
14052 (car (org-last allowed))))
14053 (allowed
14054 (message "Select 1-9,0, [RET%s]: %s"
14055 (if cur (concat "=" cur) "")
14056 (mapconcat 'car allowed " "))
14057 (setq rpl (read-char-exclusive))
14058 (if (equal rpl ?\r)
14060 (setq rpl (- rpl ?0))
14061 (if (equal rpl 0) (setq rpl 10))
14062 (if (and (> rpl 0) (<= rpl (length allowed)))
14063 (car (nth (1- rpl) allowed))
14064 (org-completing-read "Effort: " allowed nil))))
14066 (let (org-completion-use-ido org-completion-use-iswitchb)
14067 (org-completing-read
14068 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14069 (concat "[" cur "]") "")
14070 ": ")
14071 existing nil nil "" nil cur))))))
14072 (unless (equal (org-entry-get nil prop) val)
14073 (org-entry-put nil prop val))
14074 (message "%s is now %s" prop val)))
14076 (defun org-at-property-p ()
14077 "Is cursor inside a property drawer?"
14078 (save-excursion
14079 (beginning-of-line 1)
14080 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14081 (save-match-data ;; Used by calling procedures
14082 (let ((p (point))
14083 (range (unless (org-before-first-heading-p)
14084 (org-get-property-block))))
14085 (and range (<= (car range) p) (< p (cdr range))))))))
14087 (defun org-get-property-block (&optional beg end force)
14088 "Return the (beg . end) range of the body of the property drawer.
14089 BEG and END can be beginning and end of subtree, if not given
14090 they will be found.
14091 If the drawer does not exist and FORCE is non-nil, create the drawer."
14092 (catch 'exit
14093 (save-excursion
14094 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14095 (end (or end (progn (outline-next-heading) (point)))))
14096 (goto-char beg)
14097 (if (re-search-forward org-property-start-re end t)
14098 (setq beg (1+ (match-end 0)))
14099 (if force
14100 (save-excursion
14101 (org-insert-property-drawer)
14102 (setq end (progn (outline-next-heading) (point))))
14103 (throw 'exit nil))
14104 (goto-char beg)
14105 (if (re-search-forward org-property-start-re end t)
14106 (setq beg (1+ (match-end 0)))))
14107 (if (re-search-forward org-property-end-re end t)
14108 (setq end (match-beginning 0))
14109 (or force (throw 'exit nil))
14110 (goto-char beg)
14111 (setq end beg)
14112 (org-indent-line-function)
14113 (insert ":END:\n"))
14114 (cons beg end)))))
14116 (defun org-entry-properties (&optional pom which specific)
14117 "Get all properties of the entry at point-or-marker POM.
14118 This includes the TODO keyword, the tags, time strings for deadline,
14119 scheduled, and clocking, and any additional properties defined in the
14120 entry. The return value is an alist, keys may occur multiple times
14121 if the property key was used several times.
14122 POM may also be nil, in which case the current entry is used.
14123 If WHICH is nil or `all', get all properties. If WHICH is
14124 `special' or `standard', only get that subclass. If WHICH
14125 is a string only get exactly this property. SPECIFIC can be a string, the
14126 specific property we are interested in. Specifying it can speed
14127 things up because then unnecessary parsing is avoided."
14128 (setq which (or which 'all))
14129 (org-with-point-at pom
14130 (let ((clockstr (substring org-clock-string 0 -1))
14131 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14132 (case-fold-search nil)
14133 beg end range props sum-props key key1 value string clocksum)
14134 (save-excursion
14135 (when (condition-case nil
14136 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14137 (error nil))
14138 (setq beg (point))
14139 (setq sum-props (get-text-property (point) 'org-summaries))
14140 (setq clocksum (get-text-property (point) :org-clock-minutes))
14141 (outline-next-heading)
14142 (setq end (point))
14143 (when (memq which '(all special))
14144 ;; Get the special properties, like TODO and tags
14145 (goto-char beg)
14146 (when (and (or (not specific) (string= specific "TODO"))
14147 (looking-at org-todo-line-regexp) (match-end 2))
14148 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14149 (when (and (or (not specific) (string= specific "PRIORITY"))
14150 (looking-at org-priority-regexp))
14151 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14152 (when (or (not specific) (string= specific "FILE"))
14153 (push (cons "FILE" buffer-file-name) props))
14154 (when (and (or (not specific) (string= specific "TAGS"))
14155 (setq value (org-get-tags-string))
14156 (string-match "\\S-" value))
14157 (push (cons "TAGS" value) props))
14158 (when (and (or (not specific) (string= specific "ALLTAGS"))
14159 (setq value (org-get-tags-at)))
14160 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14161 ":"))
14162 props))
14163 (when (or (not specific) (string= specific "BLOCKED"))
14164 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14165 (when (or (not specific)
14166 (member specific
14167 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14168 "TIMESTAMP" "TIMESTAMP_IA")))
14169 (catch 'match
14170 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14171 (setq key (if (match-end 1)
14172 (substring (org-match-string-no-properties 1)
14173 0 -1))
14174 string (if (equal key clockstr)
14175 (org-no-properties
14176 (org-trim
14177 (buffer-substring
14178 (match-beginning 3) (goto-char
14179 (point-at-eol)))))
14180 (substring (org-match-string-no-properties 3)
14181 1 -1)))
14182 ;; Get the correct property name from the key. This is
14183 ;; necessary if the user has configured time keywords.
14184 (setq key1 (concat key ":"))
14185 (cond
14186 ((not key)
14187 (setq key
14188 (if (= (char-after (match-beginning 3)) ?\[)
14189 "TIMESTAMP_IA" "TIMESTAMP")))
14190 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14191 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14192 ((equal key1 org-closed-string) (setq key "CLOSED"))
14193 ((equal key1 org-clock-string) (setq key "CLOCK")))
14194 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14195 (progn
14196 (push (cons key string) props)
14197 ;; no need to search further if match is found
14198 (throw 'match t))
14199 (when (or (equal key "CLOCK") (not (assoc key props)))
14200 (push (cons key string) props))))))
14203 (when (memq which '(all standard))
14204 ;; Get the standard properties, like :PROP: ...
14205 (setq range (org-get-property-block beg end))
14206 (when range
14207 (goto-char (car range))
14208 (while (re-search-forward
14209 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14210 (cdr range) t)
14211 (setq key (org-match-string-no-properties 1)
14212 value (org-trim (or (org-match-string-no-properties 2) "")))
14213 (unless (member key excluded)
14214 (push (cons key (or value "")) props)))))
14215 (if clocksum
14216 (push (cons "CLOCKSUM"
14217 (org-columns-number-to-string (/ (float clocksum) 60.)
14218 'add_times))
14219 props))
14220 (unless (assoc "CATEGORY" props)
14221 (push (cons "CATEGORY" (org-get-category)) props))
14222 (append sum-props (nreverse props)))))))
14224 (defun org-entry-get (pom property &optional inherit literal-nil)
14225 "Get value of PROPERTY for entry at point-or-marker POM.
14226 If INHERIT is non-nil and the entry does not have the property,
14227 then also check higher levels of the hierarchy.
14228 If INHERIT is the symbol `selective', use inheritance only if the setting
14229 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14230 If the property is present but empty, the return value is the empty string.
14231 If the property is not present at all, nil is returned.
14233 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14234 do not interpret it as the list atom nil. This is used for inheritance
14235 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14236 (org-with-point-at pom
14237 (if (and inherit (if (eq inherit 'selective)
14238 (org-property-inherit-p property)
14240 (org-entry-get-with-inheritance property literal-nil)
14241 (if (member property org-special-properties)
14242 ;; We need a special property. Use `org-entry-properties' to
14243 ;; retrieve it, but specify the wanted property
14244 (cdr (assoc property (org-entry-properties nil 'special property)))
14245 (let ((range (unless (org-before-first-heading-p)
14246 (org-get-property-block)))
14247 (props (list (or (assoc property org-file-properties)
14248 (assoc property org-global-properties)
14249 (assoc property org-global-properties-fixed))))
14250 val)
14251 (flet ((ap (key)
14252 (when (re-search-forward
14253 (org-re-property key) (cdr range) t)
14254 (setq props
14255 (org-update-property-plist
14257 (if (match-end 1)
14258 (org-match-string-no-properties 1) "")
14259 props)))))
14260 (when (and range (goto-char (car range)))
14261 (ap property)
14262 (goto-char (car range))
14263 (while (ap (concat property "+")))
14264 (setq val (cdr (assoc property props)))
14265 (when val (if literal-nil val (org-not-nil val))))))))))
14267 (defun org-property-or-variable-value (var &optional inherit)
14268 "Check if there is a property fixing the value of VAR.
14269 If yes, return this value. If not, return the current value of the variable."
14270 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14271 (if (and prop (stringp prop) (string-match "\\S-" prop))
14272 (read prop)
14273 (symbol-value var))))
14275 (defun org-entry-delete (pom property)
14276 "Delete the property PROPERTY from entry at point-or-marker POM."
14277 (org-with-point-at pom
14278 (if (member property org-special-properties)
14279 nil ; cannot delete these properties.
14280 (let ((range (org-get-property-block)))
14281 (if (and range
14282 (goto-char (car range))
14283 (re-search-forward
14284 (org-re-property property)
14285 (cdr range) t))
14286 (progn
14287 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14289 nil)))))
14291 ;; Multi-values properties are properties that contain multiple values
14292 ;; These values are assumed to be single words, separated by whitespace.
14293 (defun org-entry-add-to-multivalued-property (pom property value)
14294 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14295 (let* ((old (org-entry-get pom property))
14296 (values (and old (org-split-string old "[ \t]"))))
14297 (setq value (org-entry-protect-space value))
14298 (unless (member value values)
14299 (setq values (cons value values))
14300 (org-entry-put pom property
14301 (mapconcat 'identity values " ")))))
14303 (defun org-entry-remove-from-multivalued-property (pom property value)
14304 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14305 (let* ((old (org-entry-get pom property))
14306 (values (and old (org-split-string old "[ \t]"))))
14307 (setq value (org-entry-protect-space value))
14308 (when (member value values)
14309 (setq values (delete value values))
14310 (org-entry-put pom property
14311 (mapconcat 'identity values " ")))))
14313 (defun org-entry-member-in-multivalued-property (pom property value)
14314 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14315 (let* ((old (org-entry-get pom property))
14316 (values (and old (org-split-string old "[ \t]"))))
14317 (setq value (org-entry-protect-space value))
14318 (member value values)))
14320 (defun org-entry-get-multivalued-property (pom property)
14321 "Return a list of values in a multivalued property."
14322 (let* ((value (org-entry-get pom property))
14323 (values (and value (org-split-string value "[ \t]"))))
14324 (mapcar 'org-entry-restore-space values)))
14326 (defun org-entry-put-multivalued-property (pom property &rest values)
14327 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14328 VALUES should be a list of strings. Spaces will be protected."
14329 (org-entry-put pom property
14330 (mapconcat 'org-entry-protect-space values " "))
14331 (let* ((value (org-entry-get pom property))
14332 (values (and value (org-split-string value "[ \t]"))))
14333 (mapcar 'org-entry-restore-space values)))
14335 (defun org-entry-protect-space (s)
14336 "Protect spaces and newline in string S."
14337 (while (string-match " " s)
14338 (setq s (replace-match "%20" t t s)))
14339 (while (string-match "\n" s)
14340 (setq s (replace-match "%0A" t t s)))
14343 (defun org-entry-restore-space (s)
14344 "Restore spaces and newline in string S."
14345 (while (string-match "%20" s)
14346 (setq s (replace-match " " t t s)))
14347 (while (string-match "%0A" s)
14348 (setq s (replace-match "\n" t t s)))
14351 (defvar org-entry-property-inherited-from (make-marker)
14352 "Marker pointing to the entry from where a property was inherited.
14353 Each call to `org-entry-get-with-inheritance' will set this marker to the
14354 location of the entry where the inheritance search matched. If there was
14355 no match, the marker will point nowhere.
14356 Note that also `org-entry-get' calls this function, if the INHERIT flag
14357 is set.")
14359 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14360 "Get entry property, and search higher levels if not present.
14361 The search will stop at the first ancestor which has the property defined.
14362 If the value found is \"nil\", return nil to show that the property
14363 should be considered as undefined (this is the meaning of nil here).
14364 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14365 (move-marker org-entry-property-inherited-from nil)
14366 (let (tmp)
14367 (unless (org-before-first-heading-p)
14368 (save-excursion
14369 (save-restriction
14370 (widen)
14371 (catch 'ex
14372 (while t
14373 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14374 (org-back-to-heading t)
14375 (move-marker org-entry-property-inherited-from (point))
14376 (throw 'ex tmp))
14377 (or (org-up-heading-safe) (throw 'ex nil)))))))
14378 (setq tmp (or tmp
14379 (cdr (assoc property org-file-properties))
14380 (cdr (assoc property org-global-properties))
14381 (cdr (assoc property org-global-properties-fixed))))
14382 (if literal-nil tmp (org-not-nil tmp))))
14384 (defvar org-property-changed-functions nil
14385 "Hook called when the value of a property has changed.
14386 Each hook function should accept two arguments, the name of the property
14387 and the new value.")
14389 (defun org-entry-put (pom property value)
14390 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14391 (org-with-point-at pom
14392 (org-back-to-heading t)
14393 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14394 range)
14395 (cond
14396 ((equal property "TODO")
14397 (when (and (stringp value) (string-match "\\S-" value)
14398 (not (member value org-todo-keywords-1)))
14399 (error "\"%s\" is not a valid TODO state" value))
14400 (if (or (not value)
14401 (not (string-match "\\S-" value)))
14402 (setq value 'none))
14403 (org-todo value)
14404 (org-set-tags nil 'align))
14405 ((equal property "PRIORITY")
14406 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14407 (string-to-char value) ?\ ))
14408 (org-set-tags nil 'align))
14409 ((equal property "SCHEDULED")
14410 (if (re-search-forward org-scheduled-time-regexp end t)
14411 (cond
14412 ((eq value 'earlier) (org-timestamp-change -1 'day))
14413 ((eq value 'later) (org-timestamp-change 1 'day))
14414 (t (call-interactively 'org-schedule)))
14415 (call-interactively 'org-schedule)))
14416 ((equal property "DEADLINE")
14417 (if (re-search-forward org-deadline-time-regexp end t)
14418 (cond
14419 ((eq value 'earlier) (org-timestamp-change -1 'day))
14420 ((eq value 'later) (org-timestamp-change 1 'day))
14421 (t (call-interactively 'org-deadline)))
14422 (call-interactively 'org-deadline)))
14423 ((member property org-special-properties)
14424 (error "The %s property can not yet be set with `org-entry-put'"
14425 property))
14426 (t ; a non-special property
14427 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14428 (setq range (org-get-property-block beg end 'force))
14429 (goto-char (car range))
14430 (if (re-search-forward
14431 (org-re-property property) (cdr range) t)
14432 (progn
14433 (delete-region (match-beginning 0) (match-end 0))
14434 (goto-char (match-beginning 0)))
14435 (goto-char (cdr range))
14436 (insert "\n")
14437 (backward-char 1)
14438 (org-indent-line-function))
14439 (insert ":" property ":")
14440 (and value (insert " " value))
14441 (org-indent-line-function)))))
14442 (run-hook-with-args 'org-property-changed-functions property value)))
14444 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14445 "Get all property keys in the current buffer.
14446 With INCLUDE-SPECIALS, also list the special properties that reflect things
14447 like tags and TODO state.
14448 With INCLUDE-DEFAULTS, also include properties that has special meaning
14449 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14450 and others.
14451 With INCLUDE-COLUMNS, also include property names given in COLUMN
14452 formats in the current buffer."
14453 (let (rtn range cfmt s p)
14454 (save-excursion
14455 (save-restriction
14456 (widen)
14457 (goto-char (point-min))
14458 (while (re-search-forward org-property-start-re nil t)
14459 (setq range (org-get-property-block))
14460 (goto-char (car range))
14461 (while (re-search-forward
14462 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14463 (cdr range) t)
14464 (add-to-list 'rtn (org-match-string-no-properties 1)))
14465 (outline-next-heading))))
14467 (when include-specials
14468 (setq rtn (append org-special-properties rtn)))
14470 (when include-defaults
14471 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14472 (add-to-list 'rtn org-effort-property))
14474 (when include-columns
14475 (save-excursion
14476 (save-restriction
14477 (widen)
14478 (goto-char (point-min))
14479 (while (re-search-forward
14480 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14481 nil t)
14482 (setq cfmt (match-string 2) s 0)
14483 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14484 cfmt s)
14485 (setq s (match-end 0)
14486 p (match-string 1 cfmt))
14487 (unless (or (equal p "ITEM")
14488 (member p org-special-properties))
14489 (add-to-list 'rtn (match-string 1 cfmt))))))))
14491 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14493 (defun org-property-values (key)
14494 "Return a list of all values of property KEY in the current buffer."
14495 (save-excursion
14496 (save-restriction
14497 (widen)
14498 (goto-char (point-min))
14499 (let ((re (org-re-property key))
14500 values)
14501 (while (re-search-forward re nil t)
14502 (add-to-list 'values (org-trim (match-string 1))))
14503 (delete "" values)))))
14505 (defun org-insert-property-drawer ()
14506 "Insert a property drawer into the current entry."
14507 (org-back-to-heading t)
14508 (looking-at org-outline-regexp)
14509 (let ((indent (if org-adapt-indentation
14510 (- (match-end 0) (match-beginning 0))
14512 (beg (point))
14513 (re (concat "^[ \t]*" org-keyword-time-regexp))
14514 end hiddenp)
14515 (outline-next-heading)
14516 (setq end (point))
14517 (goto-char beg)
14518 (while (re-search-forward re end t))
14519 (setq hiddenp (outline-invisible-p))
14520 (end-of-line 1)
14521 (and (equal (char-after) ?\n) (forward-char 1))
14522 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14523 (if (member (match-string 1) '("CLOCK:" ":END:"))
14524 ;; just skip this line
14525 (beginning-of-line 2)
14526 ;; Drawer start, find the end
14527 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14528 (beginning-of-line 1)))
14529 (org-skip-over-state-notes)
14530 (skip-chars-backward " \t\n\r")
14531 (if (eq (char-before) ?*) (forward-char 1))
14532 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14533 (beginning-of-line 0)
14534 (org-indent-to-column indent)
14535 (beginning-of-line 2)
14536 (org-indent-to-column indent)
14537 (beginning-of-line 0)
14538 (if hiddenp
14539 (save-excursion
14540 (org-back-to-heading t)
14541 (hide-entry))
14542 (org-flag-drawer t))))
14544 (defun org-insert-drawer (&optional arg drawer)
14545 "Insert a drawer at point.
14547 Optional argument DRAWER, when non-nil, is a string representing
14548 drawer's name. Otherwise, the user is prompted for a name.
14550 If a region is active, insert the drawer around that region
14551 instead.
14553 Point is left between drawer's boundaries."
14554 (interactive "P")
14555 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14556 "LOGBOOK"))
14557 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14558 ;; internally by Org. They are meant to be inserted
14559 ;; automatically.
14560 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14561 ;; Remove system drawers from list. Note: For some reason,
14562 ;; `org-completing-read' ignores the predicate while
14563 ;; `completing-read' handles it fine.
14564 (drawer (if arg "PROPERTIES"
14565 (or drawer
14566 (completing-read
14567 "Drawer: " org-drawers
14568 (lambda (d) (not (member d system-drawers))))))))
14569 (cond
14570 ;; With C-u, fall back on `org-insert-property-drawer'
14571 (arg (org-insert-property-drawer))
14572 ;; With an active region, insert a drawer at point.
14573 ((not (org-region-active-p))
14574 (progn
14575 (unless (bolp) (insert "\n"))
14576 (insert (format ":%s:\n\n:END:\n" drawer))
14577 (forward-line -2)))
14578 ;; Otherwise, insert the drawer at point
14580 (let ((rbeg (region-beginning))
14581 (rend (copy-marker (region-end))))
14582 (unwind-protect
14583 (progn
14584 (goto-char rbeg)
14585 (beginning-of-line)
14586 (when (save-excursion
14587 (re-search-forward org-outline-regexp-bol rend t))
14588 (error "Drawers cannot contain headlines"))
14589 ;; Position point at the beginning of the first
14590 ;; non-blank line in region. Insert drawer's opening
14591 ;; there, then indent it.
14592 (org-skip-whitespace)
14593 (beginning-of-line)
14594 (insert ":" drawer ":\n")
14595 (forward-line -1)
14596 (indent-for-tab-command)
14597 ;; Move point to the beginning of the first blank line
14598 ;; after the last non-blank line in region. Insert
14599 ;; drawer's closing, then indent it.
14600 (goto-char rend)
14601 (skip-chars-backward " \r\t\n")
14602 (insert "\n:END:")
14603 (indent-for-tab-command)
14604 (unless (eolp) (insert "\n")))
14605 ;; Clear marker, whatever the outcome of insertion is.
14606 (set-marker rend nil)))))))
14608 (defvar org-property-set-functions-alist nil
14609 "Property set function alist.
14610 Each entry should have the following format:
14612 (PROPERTY . READ-FUNCTION)
14614 The read function will be called with the same argument as
14615 `org-completing-read'.")
14617 (defun org-set-property-function (property)
14618 "Get the function that should be used to set PROPERTY.
14619 This is computed according to `org-property-set-functions-alist'."
14620 (or (cdr (assoc property org-property-set-functions-alist))
14621 'org-completing-read))
14623 (defun org-read-property-value (property)
14624 "Read PROPERTY value from user."
14625 (let* ((completion-ignore-case t)
14626 (allowed (org-property-get-allowed-values nil property 'table))
14627 (cur (org-entry-get nil property))
14628 (prompt (concat property " value"
14629 (if (and cur (string-match "\\S-" cur))
14630 (concat " [" cur "]") "") ": "))
14631 (set-function (org-set-property-function property))
14632 (val (if allowed
14633 (funcall set-function prompt allowed nil
14634 (not (get-text-property 0 'org-unrestricted
14635 (caar allowed))))
14636 (let (org-completion-use-ido org-completion-use-iswitchb)
14637 (funcall set-function prompt
14638 (mapcar 'list (org-property-values property))
14639 nil nil "" nil cur)))))
14640 (if (equal val "")
14642 val)))
14644 (defvar org-last-set-property nil)
14645 (defun org-read-property-name ()
14646 "Read a property name."
14647 (let* ((completion-ignore-case t)
14648 (keys (org-buffer-property-keys nil t t))
14649 (default-prop (or (save-excursion
14650 (save-match-data
14651 (beginning-of-line)
14652 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14653 (null (string= (match-string 1) "END"))
14654 (match-string 1))))
14655 org-last-set-property))
14656 (property (org-icompleting-read
14657 (concat "Property"
14658 (if default-prop (concat " [" default-prop "]") "")
14659 ": ")
14660 (mapcar 'list keys)
14661 nil nil nil nil
14662 default-prop
14664 (if (member property keys)
14665 property
14666 (or (cdr (assoc (downcase property)
14667 (mapcar (lambda (x) (cons (downcase x) x))
14668 keys)))
14669 property))))
14671 (defun org-set-property (property value)
14672 "In the current entry, set PROPERTY to VALUE.
14673 When called interactively, this will prompt for a property name, offering
14674 completion on existing and default properties. And then it will prompt
14675 for a value, offering completion either on allowed values (via an inherited
14676 xxx_ALL property) or on existing values in other instances of this property
14677 in the current file."
14678 (interactive (list nil nil))
14679 (let* ((property (or property (org-read-property-name)))
14680 (value (or value (org-read-property-value property)))
14681 (fn (assoc property org-properties-postprocess-alist)))
14682 (setq org-last-set-property property)
14683 ;; Possibly postprocess the inserted value:
14684 (when fn (setq value (funcall (cadr fn) value)))
14685 (unless (equal (org-entry-get nil property) value)
14686 (org-entry-put nil property value))))
14688 (defun org-delete-property (property)
14689 "In the current entry, delete PROPERTY."
14690 (interactive
14691 (let* ((completion-ignore-case t)
14692 (prop (org-icompleting-read "Property: "
14693 (org-entry-properties nil 'standard))))
14694 (list prop)))
14695 (message "Property %s %s" property
14696 (if (org-entry-delete nil property)
14697 "deleted"
14698 "was not present in the entry")))
14700 (defun org-delete-property-globally (property)
14701 "Remove PROPERTY globally, from all entries."
14702 (interactive
14703 (let* ((completion-ignore-case t)
14704 (prop (org-icompleting-read
14705 "Globally remove property: "
14706 (mapcar 'list (org-buffer-property-keys)))))
14707 (list prop)))
14708 (save-excursion
14709 (save-restriction
14710 (widen)
14711 (goto-char (point-min))
14712 (let ((cnt 0))
14713 (while (re-search-forward
14714 (org-re-property property)
14715 nil t)
14716 (setq cnt (1+ cnt))
14717 (replace-match ""))
14718 (message "Property \"%s\" removed from %d entries" property cnt)))))
14720 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14722 (defun org-compute-property-at-point ()
14723 "Compute the property at point.
14724 This looks for an enclosing column format, extracts the operator and
14725 then applies it to the property in the column format's scope."
14726 (interactive)
14727 (unless (org-at-property-p)
14728 (error "Not at a property"))
14729 (let ((prop (org-match-string-no-properties 2)))
14730 (org-columns-get-format-and-top-level)
14731 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14732 (error "No operator defined for property %s" prop))
14733 (org-columns-compute prop)))
14735 (defvar org-property-allowed-value-functions nil
14736 "Hook for functions supplying allowed values for a specific property.
14737 The functions must take a single argument, the name of the property, and
14738 return a flat list of allowed values. If \":ETC\" is one of
14739 the values, this means that these values are intended as defaults for
14740 completion, but that other values should be allowed too.
14741 The functions must return nil if they are not responsible for this
14742 property.")
14744 (defun org-property-get-allowed-values (pom property &optional table)
14745 "Get allowed values for the property PROPERTY.
14746 When TABLE is non-nil, return an alist that can directly be used for
14747 completion."
14748 (let (vals)
14749 (cond
14750 ((equal property "TODO")
14751 (setq vals (org-with-point-at pom
14752 (append org-todo-keywords-1 '("")))))
14753 ((equal property "PRIORITY")
14754 (let ((n org-lowest-priority))
14755 (while (>= n org-highest-priority)
14756 (push (char-to-string n) vals)
14757 (setq n (1- n)))))
14758 ((member property org-special-properties))
14759 ((setq vals (run-hook-with-args-until-success
14760 'org-property-allowed-value-functions property)))
14762 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14763 (when (and vals (string-match "\\S-" vals))
14764 (setq vals (car (read-from-string (concat "(" vals ")"))))
14765 (setq vals (mapcar (lambda (x)
14766 (cond ((stringp x) x)
14767 ((numberp x) (number-to-string x))
14768 ((symbolp x) (symbol-name x))
14769 (t "???")))
14770 vals)))))
14771 (when (member ":ETC" vals)
14772 (setq vals (remove ":ETC" vals))
14773 (org-add-props (car vals) '(org-unrestricted t)))
14774 (if table (mapcar 'list vals) vals)))
14776 (defun org-property-previous-allowed-value (&optional previous)
14777 "Switch to the next allowed value for this property."
14778 (interactive)
14779 (org-property-next-allowed-value t))
14781 (defun org-property-next-allowed-value (&optional previous)
14782 "Switch to the next allowed value for this property."
14783 (interactive)
14784 (unless (org-at-property-p)
14785 (error "Not at a property"))
14786 (let* ((key (match-string 2))
14787 (value (match-string 3))
14788 (allowed (or (org-property-get-allowed-values (point) key)
14789 (and (member value '("[ ]" "[-]" "[X]"))
14790 '("[ ]" "[X]"))))
14791 nval)
14792 (unless allowed
14793 (error "Allowed values for this property have not been defined"))
14794 (if previous (setq allowed (reverse allowed)))
14795 (if (member value allowed)
14796 (setq nval (car (cdr (member value allowed)))))
14797 (setq nval (or nval (car allowed)))
14798 (if (equal nval value)
14799 (error "Only one allowed value for this property"))
14800 (org-at-property-p)
14801 (replace-match (concat " :" key ": " nval) t t)
14802 (org-indent-line-function)
14803 (beginning-of-line 1)
14804 (skip-chars-forward " \t")
14805 (run-hook-with-args 'org-property-changed-functions key nval)))
14807 (defun org-find-olp (path &optional this-buffer)
14808 "Return a marker pointing to the entry at outline path OLP.
14809 If anything goes wrong, throw an error.
14810 You can wrap this call to catch the error like this:
14812 (condition-case msg
14813 (org-mobile-locate-entry (match-string 4))
14814 (error (nth 1 msg)))
14816 The return value will then be either a string with the error message,
14817 or a marker if everything is OK.
14819 If THIS-BUFFER is set, the outline path does not contain a file,
14820 only headings."
14821 (let* ((file (if this-buffer buffer-file-name (pop path)))
14822 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14823 (level 1)
14824 (lmin 1)
14825 (lmax 1)
14826 limit re end found pos heading cnt flevel)
14827 (unless buffer (error "File not found :%s" file))
14828 (with-current-buffer buffer
14829 (save-excursion
14830 (save-restriction
14831 (widen)
14832 (setq limit (point-max))
14833 (goto-char (point-min))
14834 (while (setq heading (pop path))
14835 (setq re (format org-complex-heading-regexp-format
14836 (regexp-quote heading)))
14837 (setq cnt 0 pos (point))
14838 (while (re-search-forward re end t)
14839 (setq level (- (match-end 1) (match-beginning 1)))
14840 (if (and (>= level lmin) (<= level lmax))
14841 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14842 (when (= cnt 0) (error "Heading not found on level %d: %s"
14843 lmax heading))
14844 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14845 lmax heading))
14846 (goto-char found)
14847 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14848 (setq end (save-excursion (org-end-of-subtree t t))))
14849 (when (org-at-heading-p)
14850 (move-marker (make-marker) (point))))))))
14852 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14853 "Find node HEADING in BUFFER.
14854 Return a marker to the heading if it was found, or nil if not.
14855 If POS-ONLY is set, return just the position instead of a marker.
14857 The heading text must match exact, but it may have a TODO keyword,
14858 a priority cookie and tags in the standard locations."
14859 (with-current-buffer (or buffer (current-buffer))
14860 (save-excursion
14861 (save-restriction
14862 (widen)
14863 (goto-char (point-min))
14864 (let (case-fold-search)
14865 (if (re-search-forward
14866 (format org-complex-heading-regexp-format
14867 (regexp-quote heading)) nil t)
14868 (if pos-only
14869 (match-beginning 0)
14870 (move-marker (make-marker) (match-beginning 0)))))))))
14872 (defun org-find-exact-heading-in-directory (heading &optional dir)
14873 "Find Org node headline HEADING in all .org files in directory DIR.
14874 When the target headline is found, return a marker to this location."
14875 (let ((files (directory-files (or dir default-directory)
14876 nil "\\`[^.#].*\\.org\\'"))
14877 file visiting m buffer)
14878 (catch 'found
14879 (while (setq file (pop files))
14880 (message "trying %s" file)
14881 (setq visiting (org-find-base-buffer-visiting file))
14882 (setq buffer (or visiting (find-file-noselect file)))
14883 (setq m (org-find-exact-headline-in-buffer
14884 heading buffer))
14885 (when (and (not m) (not visiting)) (kill-buffer buffer))
14886 (and m (throw 'found m))))))
14888 (defun org-find-entry-with-id (ident)
14889 "Locate the entry that contains the ID property with exact value IDENT.
14890 IDENT can be a string, a symbol or a number, this function will search for
14891 the string representation of it.
14892 Return the position where this entry starts, or nil if there is no such entry."
14893 (interactive "sID: ")
14894 (let ((id (cond
14895 ((stringp ident) ident)
14896 ((symbol-name ident) (symbol-name ident))
14897 ((numberp ident) (number-to-string ident))
14898 (t (error "IDENT %s must be a string, symbol or number" ident))))
14899 (case-fold-search nil))
14900 (save-excursion
14901 (save-restriction
14902 (widen)
14903 (goto-char (point-min))
14904 (when (re-search-forward
14905 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14906 nil t)
14907 (org-back-to-heading t)
14908 (point))))))
14910 ;;;; Timestamps
14912 (defvar org-last-changed-timestamp nil)
14913 (defvar org-last-inserted-timestamp nil
14914 "The last time stamp inserted with `org-insert-time-stamp'.")
14915 (defvar org-time-was-given) ; dynamically scoped parameter
14916 (defvar org-end-time-was-given) ; dynamically scoped parameter
14917 (defvar org-ts-what) ; dynamically scoped parameter
14919 (defun org-time-stamp (arg &optional inactive)
14920 "Prompt for a date/time and insert a time stamp.
14921 If the user specifies a time like HH:MM, or if this command is called
14922 with a prefix argument, the time stamp will contain date and time.
14923 Otherwise, only the date will be included. All parts of a date not
14924 specified by the user will be filled in from the current date/time.
14925 So if you press just return without typing anything, the time stamp
14926 will represent the current date/time. If there is already a timestamp
14927 at the cursor, it will be modified."
14928 (interactive "P")
14929 (let* ((ts nil)
14930 (default-time
14931 ;; Default time is either today, or, when entering a range,
14932 ;; the range start.
14933 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14934 (save-excursion
14935 (re-search-backward
14936 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14937 (- (point) 20) t)))
14938 (apply 'encode-time (org-parse-time-string (match-string 1)))
14939 (current-time)))
14940 (default-input (and ts (org-get-compact-tod ts)))
14941 (repeater (save-excursion
14942 (save-match-data
14943 (beginning-of-line)
14944 (when (re-search-forward
14945 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14946 (save-excursion (progn (end-of-line) (point))) t)
14947 (match-string 0)))))
14948 org-time-was-given org-end-time-was-given time)
14949 (cond
14950 ((and (org-at-timestamp-p t)
14951 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14952 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14953 (insert "--")
14954 (setq time (let ((this-command this-command))
14955 (org-read-date arg 'totime nil nil
14956 default-time default-input inactive)))
14957 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14958 ((org-at-timestamp-p t)
14959 (setq time (let ((this-command this-command))
14960 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14961 (when (org-at-timestamp-p t) ; just to get the match data
14962 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14963 (replace-match "")
14964 (setq org-last-changed-timestamp
14965 (org-insert-time-stamp
14966 time (or org-time-was-given arg)
14967 inactive nil nil (list org-end-time-was-given)))
14968 (when repeater (goto-char (1- (point))) (insert " " repeater)
14969 (setq org-last-changed-timestamp
14970 (concat (substring org-last-inserted-timestamp 0 -1)
14971 " " repeater ">"))))
14972 (message "Timestamp updated"))
14974 (setq time (let ((this-command this-command))
14975 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14976 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14977 nil nil (list org-end-time-was-given))))))
14979 ;; FIXME: can we use this for something else, like computing time differences?
14980 (defun org-get-compact-tod (s)
14981 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14982 (let* ((t1 (match-string 1 s))
14983 (h1 (string-to-number (match-string 2 s)))
14984 (m1 (string-to-number (match-string 3 s)))
14985 (t2 (and (match-end 4) (match-string 5 s)))
14986 (h2 (and t2 (string-to-number (match-string 6 s))))
14987 (m2 (and t2 (string-to-number (match-string 7 s))))
14988 dh dm)
14989 (if (not t2)
14991 (setq dh (- h2 h1) dm (- m2 m1))
14992 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14993 (concat t1 "+" (number-to-string dh)
14994 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14996 (defun org-time-stamp-inactive (&optional arg)
14997 "Insert an inactive time stamp.
14998 An inactive time stamp is enclosed in square brackets instead of angle
14999 brackets. It is inactive in the sense that it does not trigger agenda entries,
15000 does not link to the calendar and cannot be changed with the S-cursor keys.
15001 So these are more for recording a certain time/date."
15002 (interactive "P")
15003 (org-time-stamp arg 'inactive))
15005 (defvar org-date-ovl (make-overlay 1 1))
15006 (overlay-put org-date-ovl 'face 'org-warning)
15007 (org-detach-overlay org-date-ovl)
15009 (defvar org-ans1) ; dynamically scoped parameter
15010 (defvar org-ans2) ; dynamically scoped parameter
15012 (defvar org-plain-time-of-day-regexp) ; defined below
15014 (defvar org-overriding-default-time nil) ; dynamically scoped
15015 (defvar org-read-date-overlay nil)
15016 (defvar org-dcst nil) ; dynamically scoped
15017 (defvar org-read-date-history nil)
15018 (defvar org-read-date-final-answer nil)
15019 (defvar org-read-date-analyze-futurep nil)
15020 (defvar org-read-date-analyze-forced-year nil)
15021 (defvar org-read-date-inactive)
15023 (defun org-read-date (&optional with-time to-time from-string prompt
15024 default-time default-input inactive)
15025 "Read a date, possibly a time, and make things smooth for the user.
15026 The prompt will suggest to enter an ISO date, but you can also enter anything
15027 which will at least partially be understood by `parse-time-string'.
15028 Unrecognized parts of the date will default to the current day, month, year,
15029 hour and minute. If this command is called to replace a timestamp at point,
15030 or to enter the second timestamp of a range, the default time is taken
15031 from the existing stamp. Furthermore, the command prefers the future,
15032 so if you are giving a date where the year is not given, and the day-month
15033 combination is already past in the current year, it will assume you
15034 mean next year. For details, see the manual. A few examples:
15036 3-2-5 --> 2003-02-05
15037 feb 15 --> currentyear-02-15
15038 2/15 --> currentyear-02-15
15039 sep 12 9 --> 2009-09-12
15040 12:45 --> today 12:45
15041 22 sept 0:34 --> currentyear-09-22 0:34
15042 12 --> currentyear-currentmonth-12
15043 Fri --> nearest Friday (today or later)
15044 etc.
15046 Furthermore you can specify a relative date by giving, as the *first* thing
15047 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
15048 change in days weeks, months, years.
15049 With a single plus or minus, the date is relative to today. With a double
15050 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15051 +4d --> four days from today
15052 +4 --> same as above
15053 +2w --> two weeks from today
15054 ++5 --> five days from default date
15056 The function understands only English month and weekday abbreviations.
15058 While prompting, a calendar is popped up - you can also select the
15059 date with the mouse (button 1). The calendar shows a period of three
15060 months. To scroll it to other months, use the keys `>' and `<'.
15061 If you don't like the calendar, turn it off with
15062 \(setq org-read-date-popup-calendar nil)
15064 With optional argument TO-TIME, the date will immediately be converted
15065 to an internal time.
15066 With an optional argument WITH-TIME, the prompt will suggest to also
15067 insert a time. Note that when WITH-TIME is not set, you can still
15068 enter a time, and this function will inform the calling routine about
15069 this change. The calling routine may then choose to change the format
15070 used to insert the time stamp into the buffer to include the time.
15071 With optional argument FROM-STRING, read from this string instead from
15072 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15073 the time/date that is used for everything that is not specified by the
15074 user."
15075 (require 'parse-time)
15076 (let* ((org-time-stamp-rounding-minutes
15077 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15078 (org-dcst org-display-custom-times)
15079 (ct (org-current-time))
15080 (def (or org-overriding-default-time default-time ct))
15081 (defdecode (decode-time def))
15082 (dummy (progn
15083 (when (< (nth 2 defdecode) org-extend-today-until)
15084 (setcar (nthcdr 2 defdecode) -1)
15085 (setcar (nthcdr 1 defdecode) 59)
15086 (setq def (apply 'encode-time defdecode)
15087 defdecode (decode-time def)))))
15088 (calendar-frame-setup nil)
15089 (calendar-setup nil)
15090 (calendar-move-hook nil)
15091 (calendar-view-diary-initially-flag nil)
15092 (calendar-view-holidays-initially-flag nil)
15093 (timestr (format-time-string
15094 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
15095 (prompt (concat (if prompt (concat prompt " ") "")
15096 (format "Date+time [%s]: " timestr)))
15097 ans (org-ans0 "") org-ans1 org-ans2 final)
15099 (cond
15100 (from-string (setq ans from-string))
15101 (org-read-date-popup-calendar
15102 (save-excursion
15103 (save-window-excursion
15104 (calendar)
15105 (unwind-protect
15106 (progn
15107 (calendar-forward-day (- (time-to-days def)
15108 (calendar-absolute-from-gregorian
15109 (calendar-current-date))))
15110 (org-eval-in-calendar nil t)
15111 (let* ((old-map (current-local-map))
15112 (map (copy-keymap calendar-mode-map))
15113 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15114 (org-defkey map (kbd "RET") 'org-calendar-select)
15115 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15116 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15117 (org-defkey minibuffer-local-map [(meta shift left)]
15118 (lambda () (interactive)
15119 (org-eval-in-calendar '(calendar-backward-month 1))))
15120 (org-defkey minibuffer-local-map [(meta shift right)]
15121 (lambda () (interactive)
15122 (org-eval-in-calendar '(calendar-forward-month 1))))
15123 (org-defkey minibuffer-local-map [(meta shift up)]
15124 (lambda () (interactive)
15125 (org-eval-in-calendar '(calendar-backward-year 1))))
15126 (org-defkey minibuffer-local-map [(meta shift down)]
15127 (lambda () (interactive)
15128 (org-eval-in-calendar '(calendar-forward-year 1))))
15129 (org-defkey minibuffer-local-map [?\e (shift left)]
15130 (lambda () (interactive)
15131 (org-eval-in-calendar '(calendar-backward-month 1))))
15132 (org-defkey minibuffer-local-map [?\e (shift right)]
15133 (lambda () (interactive)
15134 (org-eval-in-calendar '(calendar-forward-month 1))))
15135 (org-defkey minibuffer-local-map [?\e (shift up)]
15136 (lambda () (interactive)
15137 (org-eval-in-calendar '(calendar-backward-year 1))))
15138 (org-defkey minibuffer-local-map [?\e (shift down)]
15139 (lambda () (interactive)
15140 (org-eval-in-calendar '(calendar-forward-year 1))))
15141 (org-defkey minibuffer-local-map [(shift up)]
15142 (lambda () (interactive)
15143 (org-eval-in-calendar '(calendar-backward-week 1))))
15144 (org-defkey minibuffer-local-map [(shift down)]
15145 (lambda () (interactive)
15146 (org-eval-in-calendar '(calendar-forward-week 1))))
15147 (org-defkey minibuffer-local-map [(shift left)]
15148 (lambda () (interactive)
15149 (org-eval-in-calendar '(calendar-backward-day 1))))
15150 (org-defkey minibuffer-local-map [(shift right)]
15151 (lambda () (interactive)
15152 (org-eval-in-calendar '(calendar-forward-day 1))))
15153 (org-defkey minibuffer-local-map ">"
15154 (lambda () (interactive)
15155 (org-eval-in-calendar '(scroll-calendar-left 1))))
15156 (org-defkey minibuffer-local-map "<"
15157 (lambda () (interactive)
15158 (org-eval-in-calendar '(scroll-calendar-right 1))))
15159 (org-defkey minibuffer-local-map "\C-v"
15160 (lambda () (interactive)
15161 (org-eval-in-calendar
15162 '(calendar-scroll-left-three-months 1))))
15163 (org-defkey minibuffer-local-map "\M-v"
15164 (lambda () (interactive)
15165 (org-eval-in-calendar
15166 '(calendar-scroll-right-three-months 1))))
15167 (run-hooks 'org-read-date-minibuffer-setup-hook)
15168 (unwind-protect
15169 (progn
15170 (use-local-map map)
15171 (setq org-read-date-inactive inactive)
15172 (add-hook 'post-command-hook 'org-read-date-display)
15173 (setq org-ans0 (read-string prompt default-input
15174 'org-read-date-history nil))
15175 ;; org-ans0: from prompt
15176 ;; org-ans1: from mouse click
15177 ;; org-ans2: from calendar motion
15178 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15179 (remove-hook 'post-command-hook 'org-read-date-display)
15180 (use-local-map old-map)
15181 (when org-read-date-overlay
15182 (delete-overlay org-read-date-overlay)
15183 (setq org-read-date-overlay nil)))))
15184 (bury-buffer "*Calendar*")))))
15186 (t ; Naked prompt only
15187 (unwind-protect
15188 (setq ans (read-string prompt default-input
15189 'org-read-date-history timestr))
15190 (when org-read-date-overlay
15191 (delete-overlay org-read-date-overlay)
15192 (setq org-read-date-overlay nil)))))
15194 (setq final (org-read-date-analyze ans def defdecode))
15196 (when org-read-date-analyze-forced-year
15197 (message "Year was forced into %s"
15198 (if org-read-date-force-compatible-dates
15199 "compatible range (1970-2037)"
15200 "range representable on this machine"))
15201 (ding))
15203 ;; One round trip to get rid of 34th of August and stuff like that....
15204 (setq final (decode-time (apply 'encode-time final)))
15206 (setq org-read-date-final-answer ans)
15208 (if to-time
15209 (apply 'encode-time final)
15210 (if (and (boundp 'org-time-was-given) org-time-was-given)
15211 (format "%04d-%02d-%02d %02d:%02d"
15212 (nth 5 final) (nth 4 final) (nth 3 final)
15213 (nth 2 final) (nth 1 final))
15214 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15216 (defvar def)
15217 (defvar defdecode)
15218 (defvar with-time)
15219 (defun org-read-date-display ()
15220 "Display the current date prompt interpretation in the minibuffer."
15221 (when org-read-date-display-live
15222 (when org-read-date-overlay
15223 (delete-overlay org-read-date-overlay))
15224 (let ((p (point)))
15225 (end-of-line 1)
15226 (while (not (equal (buffer-substring
15227 (max (point-min) (- (point) 4)) (point))
15228 " "))
15229 (insert " "))
15230 (goto-char p))
15231 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15232 " " (or org-ans1 org-ans2)))
15233 (org-end-time-was-given nil)
15234 (f (org-read-date-analyze ans def defdecode))
15235 (fmts (if org-dcst
15236 org-time-stamp-custom-formats
15237 org-time-stamp-formats))
15238 (fmt (if (or with-time
15239 (and (boundp 'org-time-was-given) org-time-was-given))
15240 (cdr fmts)
15241 (car fmts)))
15242 (txt (format-time-string fmt (apply 'encode-time f)))
15243 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15244 (txt (concat "=> " txt)))
15245 (when (and org-end-time-was-given
15246 (string-match org-plain-time-of-day-regexp txt))
15247 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15248 org-end-time-was-given
15249 (substring txt (match-end 0)))))
15250 (when org-read-date-analyze-futurep
15251 (setq txt (concat txt " (=>F)")))
15252 (setq org-read-date-overlay
15253 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15254 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15256 (defun org-read-date-analyze (ans def defdecode)
15257 "Analyze the combined answer of the date prompt."
15258 ;; FIXME: cleanup and comment
15259 (let ((nowdecode (decode-time (current-time)))
15260 delta deltan deltaw deltadef year month day
15261 hour minute second wday pm h2 m2 tl wday1
15262 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15263 (setq org-read-date-analyze-futurep nil
15264 org-read-date-analyze-forced-year nil)
15265 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15266 (setq ans "+0"))
15268 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15269 (setq ans (replace-match "" t t ans)
15270 deltan (car delta)
15271 deltaw (nth 1 delta)
15272 deltadef (nth 2 delta)))
15274 ;; Check if there is an iso week date in there
15275 ;; If yes, store the info and postpone interpreting it until the rest
15276 ;; of the parsing is done
15277 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15278 (setq iso-year (if (match-end 1)
15279 (org-small-year-to-year
15280 (string-to-number (match-string 1 ans))))
15281 iso-weekday (if (match-end 3)
15282 (string-to-number (match-string 3 ans)))
15283 iso-week (string-to-number (match-string 2 ans)))
15284 (setq ans (replace-match "" t t ans)))
15286 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15287 (when (string-match
15288 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15289 (setq year (if (match-end 2)
15290 (string-to-number (match-string 2 ans))
15291 (progn (setq kill-year t)
15292 (string-to-number (format-time-string "%Y"))))
15293 month (string-to-number (match-string 3 ans))
15294 day (string-to-number (match-string 4 ans)))
15295 (if (< year 100) (setq year (+ 2000 year)))
15296 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15297 t nil ans)))
15299 ;; Help matching dotted european dates
15300 (when (string-match
15301 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15302 (setq year (if (match-end 3)
15303 (string-to-number (match-string 3 ans))
15304 (progn (setq kill-year t)
15305 (string-to-number (format-time-string "%Y"))))
15306 day (string-to-number (match-string 1 ans))
15307 month (string-to-number (match-string 2 ans))
15308 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15309 t nil ans)))
15311 ;; Help matching american dates, like 5/30 or 5/30/7
15312 (when (string-match
15313 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15314 (setq year (if (match-end 4)
15315 (string-to-number (match-string 4 ans))
15316 (progn (setq kill-year t)
15317 (string-to-number (format-time-string "%Y"))))
15318 month (string-to-number (match-string 1 ans))
15319 day (string-to-number (match-string 2 ans)))
15320 (if (< year 100) (setq year (+ 2000 year)))
15321 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15322 t nil ans)))
15323 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15324 ;; If there is a time with am/pm, and *no* time without it, we convert
15325 ;; so that matching will be successful.
15326 (loop for i from 1 to 2 do ; twice, for end time as well
15327 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15328 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15329 (setq hour (string-to-number (match-string 1 ans))
15330 minute (if (match-end 3)
15331 (string-to-number (match-string 3 ans))
15333 pm (equal ?p
15334 (string-to-char (downcase (match-string 4 ans)))))
15335 (if (and (= hour 12) (not pm))
15336 (setq hour 0)
15337 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15338 (setq ans (replace-match (format "%02d:%02d" hour minute)
15339 t t ans))))
15341 ;; Check if a time range is given as a duration
15342 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15343 (setq hour (string-to-number (match-string 1 ans))
15344 h2 (+ hour (string-to-number (match-string 3 ans)))
15345 minute (string-to-number (match-string 2 ans))
15346 m2 (+ minute (if (match-end 5) (string-to-number
15347 (match-string 5 ans))0)))
15348 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15349 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15350 t t ans)))
15352 ;; Check if there is a time range
15353 (when (boundp 'org-end-time-was-given)
15354 (setq org-time-was-given nil)
15355 (when (and (string-match org-plain-time-of-day-regexp ans)
15356 (match-end 8))
15357 (setq org-end-time-was-given (match-string 8 ans))
15358 (setq ans (concat (substring ans 0 (match-beginning 7))
15359 (substring ans (match-end 7))))))
15361 (setq tl (parse-time-string ans)
15362 day (or (nth 3 tl) (nth 3 defdecode))
15363 month (or (nth 4 tl)
15364 (if (and org-read-date-prefer-future
15365 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15366 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15367 (nth 4 defdecode)))
15368 year (or (and (not kill-year) (nth 5 tl))
15369 (if (and org-read-date-prefer-future
15370 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15371 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15372 (nth 5 defdecode)))
15373 hour (or (nth 2 tl) (nth 2 defdecode))
15374 minute (or (nth 1 tl) (nth 1 defdecode))
15375 second (or (nth 0 tl) 0)
15376 wday (nth 6 tl))
15378 (when (and (eq org-read-date-prefer-future 'time)
15379 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15380 (equal day (nth 3 nowdecode))
15381 (equal month (nth 4 nowdecode))
15382 (equal year (nth 5 nowdecode))
15383 (nth 2 tl)
15384 (or (< (nth 2 tl) (nth 2 nowdecode))
15385 (and (= (nth 2 tl) (nth 2 nowdecode))
15386 (nth 1 tl)
15387 (< (nth 1 tl) (nth 1 nowdecode)))))
15388 (setq day (1+ day)
15389 futurep t))
15391 ;; Special date definitions below
15392 (cond
15393 (iso-week
15394 ;; There was an iso week
15395 (require 'cal-iso)
15396 (setq futurep nil)
15397 (setq year (or iso-year year)
15398 day (or iso-weekday wday 1)
15399 wday nil ; to make sure that the trigger below does not match
15400 iso-date (calendar-gregorian-from-absolute
15401 (calendar-absolute-from-iso
15402 (list iso-week day year))))
15403 ; FIXME: Should we also push ISO weeks into the future?
15404 ; (when (and org-read-date-prefer-future
15405 ; (not iso-year)
15406 ; (< (calendar-absolute-from-gregorian iso-date)
15407 ; (time-to-days (current-time))))
15408 ; (setq year (1+ year)
15409 ; iso-date (calendar-gregorian-from-absolute
15410 ; (calendar-absolute-from-iso
15411 ; (list iso-week day year)))))
15412 (setq month (car iso-date)
15413 year (nth 2 iso-date)
15414 day (nth 1 iso-date)))
15415 (deltan
15416 (setq futurep nil)
15417 (unless deltadef
15418 (let ((now (decode-time (current-time))))
15419 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15420 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15421 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15422 ((equal deltaw "m") (setq month (+ month deltan)))
15423 ((equal deltaw "y") (setq year (+ year deltan)))))
15424 ((and wday (not (nth 3 tl)))
15425 (setq futurep nil)
15426 ;; Weekday was given, but no day, so pick that day in the week
15427 ;; on or after the derived date.
15428 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15429 (unless (equal wday wday1)
15430 (setq day (+ day (% (- wday wday1 -7) 7))))))
15431 (if (and (boundp 'org-time-was-given)
15432 (nth 2 tl))
15433 (setq org-time-was-given t))
15434 (if (< year 100) (setq year (+ 2000 year)))
15435 ;; Check of the date is representable
15436 (if org-read-date-force-compatible-dates
15437 (progn
15438 (if (< year 1970)
15439 (setq year 1970 org-read-date-analyze-forced-year t))
15440 (if (> year 2037)
15441 (setq year 2037 org-read-date-analyze-forced-year t)))
15442 (condition-case nil
15443 (ignore (encode-time second minute hour day month year))
15444 (error
15445 (setq year (nth 5 defdecode))
15446 (setq org-read-date-analyze-forced-year t))))
15447 (setq org-read-date-analyze-futurep futurep)
15448 (list second minute hour day month year)))
15450 (defvar parse-time-weekdays)
15451 (defun org-read-date-get-relative (s today default)
15452 "Check string S for special relative date string.
15453 TODAY and DEFAULT are internal times, for today and for a default.
15454 Return shift list (N what def-flag)
15455 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15456 N is the number of WHATs to shift.
15457 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15458 the DEFAULT date rather than TODAY."
15459 (require 'parse-time)
15460 (when (and
15461 (string-match
15462 (concat
15463 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15464 "\\([0-9]+\\)?"
15465 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15466 "\\([ \t]\\|$\\)") s)
15467 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15468 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15469 (string-to-char (substring (match-string 1 s) -1))
15470 ?+))
15471 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15472 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15473 (what (if (match-end 3) (match-string 3 s) "d"))
15474 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15475 (date (if rel default today))
15476 (wday (nth 6 (decode-time date)))
15477 delta)
15478 (if wday1
15479 (progn
15480 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15481 (if (= dir ?-) (setq delta (- delta 7)))
15482 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15483 (list delta "d" rel))
15484 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15486 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15487 "Turn a user-specified date into the internal representation.
15488 The internal representation needed by the calendar is (month day year).
15489 This is a wrapper to handle the brain-dead convention in calendar that
15490 user function argument order change dependent on argument order."
15491 (if (boundp 'calendar-date-style)
15492 (cond
15493 ((eq calendar-date-style 'american)
15494 (list arg1 arg2 arg3))
15495 ((eq calendar-date-style 'european)
15496 (list arg2 arg1 arg3))
15497 ((eq calendar-date-style 'iso)
15498 (list arg2 arg3 arg1)))
15499 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15500 (if (org-bound-and-true-p european-calendar-style)
15501 (list arg2 arg1 arg3)
15502 (list arg1 arg2 arg3)))))
15504 (defun org-eval-in-calendar (form &optional keepdate)
15505 "Eval FORM in the calendar window and return to current window.
15506 Also, store the cursor date in variable org-ans2."
15507 (let ((sf (selected-frame))
15508 (sw (selected-window)))
15509 (select-window (get-buffer-window "*Calendar*" t))
15510 (eval form)
15511 (when (and (not keepdate) (calendar-cursor-to-date))
15512 (let* ((date (calendar-cursor-to-date))
15513 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15514 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15515 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15516 (select-window sw)
15517 (org-select-frame-set-input-focus sf)))
15519 (defun org-calendar-select ()
15520 "Return to `org-read-date' with the date currently selected.
15521 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15522 (interactive)
15523 (when (calendar-cursor-to-date)
15524 (let* ((date (calendar-cursor-to-date))
15525 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15526 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15527 (if (active-minibuffer-window) (exit-minibuffer))))
15529 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15530 "Insert a date stamp for the date given by the internal TIME.
15531 WITH-HM means use the stamp format that includes the time of the day.
15532 INACTIVE means use square brackets instead of angular ones, so that the
15533 stamp will not contribute to the agenda.
15534 PRE and POST are optional strings to be inserted before and after the
15535 stamp.
15536 The command returns the inserted time stamp."
15537 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15538 stamp)
15539 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15540 (insert-before-markers (or pre ""))
15541 (when (listp extra)
15542 (setq extra (car extra))
15543 (if (and (stringp extra)
15544 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15545 (setq extra (format "-%02d:%02d"
15546 (string-to-number (match-string 1 extra))
15547 (string-to-number (match-string 2 extra))))
15548 (setq extra nil)))
15549 (when extra
15550 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15551 (insert-before-markers (setq stamp (format-time-string fmt time)))
15552 (insert-before-markers (or post ""))
15553 (setq org-last-inserted-timestamp stamp)))
15555 (defun org-toggle-time-stamp-overlays ()
15556 "Toggle the use of custom time stamp formats."
15557 (interactive)
15558 (setq org-display-custom-times (not org-display-custom-times))
15559 (unless org-display-custom-times
15560 (let ((p (point-min)) (bmp (buffer-modified-p)))
15561 (while (setq p (next-single-property-change p 'display))
15562 (if (and (get-text-property p 'display)
15563 (eq (get-text-property p 'face) 'org-date))
15564 (remove-text-properties
15565 p (setq p (next-single-property-change p 'display))
15566 '(display t))))
15567 (set-buffer-modified-p bmp)))
15568 (if (featurep 'xemacs)
15569 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15570 (org-restart-font-lock)
15571 (setq org-table-may-need-update t)
15572 (if org-display-custom-times
15573 (message "Time stamps are overlaid with custom format")
15574 (message "Time stamp overlays removed")))
15576 (defun org-display-custom-time (beg end)
15577 "Overlay modified time stamp format over timestamp between BEG and END."
15578 (let* ((ts (buffer-substring beg end))
15579 t1 w1 with-hm tf time str w2 (off 0))
15580 (save-match-data
15581 (setq t1 (org-parse-time-string ts t))
15582 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15583 (setq off (- (match-end 0) (match-beginning 0)))))
15584 (setq end (- end off))
15585 (setq w1 (- end beg)
15586 with-hm (and (nth 1 t1) (nth 2 t1))
15587 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15588 time (org-fix-decoded-time t1)
15589 str (org-add-props
15590 (format-time-string
15591 (substring tf 1 -1) (apply 'encode-time time))
15592 nil 'mouse-face 'highlight)
15593 w2 (length str))
15594 (if (not (= w2 w1))
15595 (add-text-properties (1+ beg) (+ 2 beg)
15596 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15597 (if (featurep 'xemacs)
15598 (progn
15599 (put-text-property beg end 'invisible t)
15600 (put-text-property beg end 'end-glyph (make-glyph str)))
15601 (put-text-property beg end 'display str))))
15603 (defun org-translate-time (string)
15604 "Translate all timestamps in STRING to custom format.
15605 But do this only if the variable `org-display-custom-times' is set."
15606 (when org-display-custom-times
15607 (save-match-data
15608 (let* ((start 0)
15609 (re org-ts-regexp-both)
15610 t1 with-hm inactive tf time str beg end)
15611 (while (setq start (string-match re string start))
15612 (setq beg (match-beginning 0)
15613 end (match-end 0)
15614 t1 (save-match-data
15615 (org-parse-time-string (substring string beg end) t))
15616 with-hm (and (nth 1 t1) (nth 2 t1))
15617 inactive (equal (substring string beg (1+ beg)) "[")
15618 tf (funcall (if with-hm 'cdr 'car)
15619 org-time-stamp-custom-formats)
15620 time (org-fix-decoded-time t1)
15621 str (format-time-string
15622 (concat
15623 (if inactive "[" "<") (substring tf 1 -1)
15624 (if inactive "]" ">"))
15625 (apply 'encode-time time))
15626 string (replace-match str t t string)
15627 start (+ start (length str)))))))
15628 string)
15630 (defun org-fix-decoded-time (time)
15631 "Set 0 instead of nil for the first 6 elements of time.
15632 Don't touch the rest."
15633 (let ((n 0))
15634 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15636 (defun org-days-to-time (timestamp-string)
15637 "Difference between TIMESTAMP-STRING and now in days."
15638 (- (time-to-days (org-time-string-to-time timestamp-string))
15639 (time-to-days (current-time))))
15641 (defun org-deadline-close (timestamp-string &optional ndays)
15642 "Is the time in TIMESTAMP-STRING close to the current date?"
15643 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15644 (and (< (org-days-to-time timestamp-string) ndays)
15645 (not (org-entry-is-done-p))))
15647 (defun org-get-wdays (ts)
15648 "Get the deadline lead time appropriate for timestring TS."
15649 (cond
15650 ((<= org-deadline-warning-days 0)
15651 ;; 0 or negative, enforce this value no matter what
15652 (- org-deadline-warning-days))
15653 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15654 ;; lead time is specified.
15655 (floor (* (string-to-number (match-string 1 ts))
15656 (cdr (assoc (match-string 2 ts)
15657 '(("d" . 1) ("w" . 7)
15658 ("m" . 30.4) ("y" . 365.25)))))))
15659 ;; go for the default.
15660 (t org-deadline-warning-days)))
15662 (defun org-calendar-select-mouse (ev)
15663 "Return to `org-read-date' with the date currently selected.
15664 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15665 (interactive "e")
15666 (mouse-set-point ev)
15667 (when (calendar-cursor-to-date)
15668 (let* ((date (calendar-cursor-to-date))
15669 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15670 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15671 (if (active-minibuffer-window) (exit-minibuffer))))
15673 (defun org-check-deadlines (ndays)
15674 "Check if there are any deadlines due or past due.
15675 A deadline is considered due if it happens within `org-deadline-warning-days'
15676 days from today's date. If the deadline appears in an entry marked DONE,
15677 it is not shown. The prefix arg NDAYS can be used to test that many
15678 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15679 (interactive "P")
15680 (let* ((org-warn-days
15681 (cond
15682 ((equal ndays '(4)) 100000)
15683 (ndays (prefix-numeric-value ndays))
15684 (t (abs org-deadline-warning-days))))
15685 (case-fold-search nil)
15686 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15687 (callback
15688 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15690 (message "%d deadlines past-due or due within %d days"
15691 (org-occur regexp nil callback)
15692 org-warn-days)))
15694 (defun org-check-before-date (date)
15695 "Check if there are deadlines or scheduled entries before DATE."
15696 (interactive (list (org-read-date)))
15697 (let ((case-fold-search nil)
15698 (regexp (concat "\\<\\(" org-deadline-string
15699 "\\|" org-scheduled-string
15700 "\\) *<\\([^>]+\\)>"))
15701 (callback
15702 (lambda () (time-less-p
15703 (org-time-string-to-time (match-string 2))
15704 (org-time-string-to-time date)))))
15705 (message "%d entries before %s"
15706 (org-occur regexp nil callback) date)))
15708 (defun org-check-after-date (date)
15709 "Check if there are deadlines or scheduled entries after DATE."
15710 (interactive (list (org-read-date)))
15711 (let ((case-fold-search nil)
15712 (regexp (concat "\\<\\(" org-deadline-string
15713 "\\|" org-scheduled-string
15714 "\\) *<\\([^>]+\\)>"))
15715 (callback
15716 (lambda () (not
15717 (time-less-p
15718 (org-time-string-to-time (match-string 2))
15719 (org-time-string-to-time date))))))
15720 (message "%d entries after %s"
15721 (org-occur regexp nil callback) date)))
15723 (defun org-check-dates-range (start-date end-date)
15724 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15725 (interactive (list (org-read-date nil nil nil "Range starts")
15726 (org-read-date nil nil nil "Range end")))
15727 (let ((case-fold-search nil)
15728 (regexp (concat "\\<\\(" org-deadline-string
15729 "\\|" org-scheduled-string
15730 "\\) *<\\([^>]+\\)>"))
15731 (callback
15732 (lambda ()
15733 (let ((match (match-string 2)))
15734 (and
15735 (not (time-less-p
15736 (org-time-string-to-time match)
15737 (org-time-string-to-time start-date)))
15738 (time-less-p
15739 (org-time-string-to-time match)
15740 (org-time-string-to-time end-date)))))))
15741 (message "%d entries between %s and %s"
15742 (org-occur regexp nil callback) start-date end-date)))
15744 (defun org-evaluate-time-range (&optional to-buffer)
15745 "Evaluate a time range by computing the difference between start and end.
15746 Normally the result is just printed in the echo area, but with prefix arg
15747 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15748 If the time range is actually in a table, the result is inserted into the
15749 next column.
15750 For time difference computation, a year is assumed to be exactly 365
15751 days in order to avoid rounding problems."
15752 (interactive "P")
15754 (org-clock-update-time-maybe)
15755 (save-excursion
15756 (unless (org-at-date-range-p t)
15757 (goto-char (point-at-bol))
15758 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15759 (if (not (org-at-date-range-p t))
15760 (error "Not at a time-stamp range, and none found in current line")))
15761 (let* ((ts1 (match-string 1))
15762 (ts2 (match-string 2))
15763 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15764 (match-end (match-end 0))
15765 (time1 (org-time-string-to-time ts1))
15766 (time2 (org-time-string-to-time ts2))
15767 (t1 (org-float-time time1))
15768 (t2 (org-float-time time2))
15769 (diff (abs (- t2 t1)))
15770 (negative (< (- t2 t1) 0))
15771 ;; (ys (floor (* 365 24 60 60)))
15772 (ds (* 24 60 60))
15773 (hs (* 60 60))
15774 (fy "%dy %dd %02d:%02d")
15775 (fy1 "%dy %dd")
15776 (fd "%dd %02d:%02d")
15777 (fd1 "%dd")
15778 (fh "%02d:%02d")
15779 y d h m align)
15780 (if havetime
15781 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15783 d (floor (/ diff ds)) diff (mod diff ds)
15784 h (floor (/ diff hs)) diff (mod diff hs)
15785 m (floor (/ diff 60)))
15786 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15788 d (floor (+ (/ diff ds) 0.5))
15789 h 0 m 0))
15790 (if (not to-buffer)
15791 (message "%s" (org-make-tdiff-string y d h m))
15792 (if (org-at-table-p)
15793 (progn
15794 (goto-char match-end)
15795 (setq align t)
15796 (and (looking-at " *|") (goto-char (match-end 0))))
15797 (goto-char match-end))
15798 (if (looking-at
15799 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15800 (replace-match ""))
15801 (if negative (insert " -"))
15802 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15803 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15804 (insert " " (format fh h m))))
15805 (if align (org-table-align))
15806 (message "Time difference inserted")))))
15808 (defun org-make-tdiff-string (y d h m)
15809 (let ((fmt "")
15810 (l nil))
15811 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15812 l (push y l)))
15813 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15814 l (push d l)))
15815 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15816 l (push h l)))
15817 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15818 l (push m l)))
15819 (apply 'format fmt (nreverse l))))
15821 (defun org-time-string-to-time (s &optional buffer pos)
15822 (condition-case errdata
15823 (apply 'encode-time (org-parse-time-string s))
15824 (error (error "Bad timestamp `%s'%s\nError was: %s"
15825 s (if (not (and buffer pos))
15827 (format " at %d in buffer `%s'" pos buffer))
15828 (cdr errdata)))))
15830 (defun org-time-string-to-seconds (s)
15831 (org-float-time (org-time-string-to-time s)))
15833 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15834 "Convert a time stamp to an absolute day number.
15835 If there is a specifier for a cyclic time stamp, get the closest date to
15836 DAYNR.
15837 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15838 The variable date is bound by the calendar when this is called."
15839 (cond
15840 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15841 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15842 daynr
15843 (+ daynr 1000)))
15844 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15845 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15846 (time-to-days (current-time))) (match-string 0 s)
15847 prefer show-all))
15848 (t (time-to-days
15849 (condition-case errdata
15850 (apply 'encode-time (org-parse-time-string s))
15851 (error (error "Bad timestamp `%s'%s\nError was: %s"
15852 s (if (not (and buffer pos))
15854 (format " at %d in buffer `%s'" pos buffer))
15855 (cdr errdata))))))))
15857 (defun org-days-to-iso-week (days)
15858 "Return the iso week number."
15859 (require 'cal-iso)
15860 (car (calendar-iso-from-absolute days)))
15862 (defun org-small-year-to-year (year)
15863 "Convert 2-digit years into 4-digit years.
15864 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15865 The year 2000 cannot be abbreviated. Any year larger than 99
15866 is returned unchanged."
15867 (if (< year 38)
15868 (setq year (+ 2000 year))
15869 (if (< year 100)
15870 (setq year (+ 1900 year))))
15871 year)
15873 (defun org-time-from-absolute (d)
15874 "Return the time corresponding to date D.
15875 D may be an absolute day number, or a calendar-type list (month day year)."
15876 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15877 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15879 (defun org-calendar-holiday ()
15880 "List of holidays, for Diary display in Org-mode."
15881 (require 'holidays)
15882 (let ((hl (funcall
15883 (if (fboundp 'calendar-check-holidays)
15884 'calendar-check-holidays 'check-calendar-holidays) date)))
15885 (if hl (mapconcat 'identity hl "; "))))
15887 (defun org-diary-sexp-entry (sexp entry date)
15888 "Process a SEXP diary ENTRY for DATE."
15889 (require 'diary-lib)
15890 (let ((result (if calendar-debug-sexp
15891 (let ((stack-trace-on-error t))
15892 (eval (car (read-from-string sexp))))
15893 (condition-case nil
15894 (eval (car (read-from-string sexp)))
15895 (error
15896 (beep)
15897 (message "Bad sexp at line %d in %s: %s"
15898 (org-current-line)
15899 (buffer-file-name) sexp)
15900 (sleep-for 2))))))
15901 (cond ((stringp result) (split-string result "; "))
15902 ((and (consp result)
15903 (not (consp (cdr result)))
15904 (stringp (cdr result))) (cdr result))
15905 ((and (consp result)
15906 (stringp (car result))) result)
15907 (result entry)
15908 (t nil))))
15910 (defun org-diary-to-ical-string (frombuf)
15911 "Get iCalendar entries from diary entries in buffer FROMBUF.
15912 This uses the icalendar.el library."
15913 (let* ((tmpdir (if (featurep 'xemacs)
15914 (temp-directory)
15915 temporary-file-directory))
15916 (tmpfile (make-temp-name
15917 (expand-file-name "orgics" tmpdir)))
15918 buf rtn b e)
15919 (with-current-buffer frombuf
15920 (icalendar-export-region (point-min) (point-max) tmpfile)
15921 (setq buf (find-buffer-visiting tmpfile))
15922 (set-buffer buf)
15923 (goto-char (point-min))
15924 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15925 (setq b (match-beginning 0)))
15926 (goto-char (point-max))
15927 (if (re-search-backward "^END:VEVENT" nil t)
15928 (setq e (match-end 0)))
15929 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15930 (kill-buffer buf)
15931 (delete-file tmpfile)
15932 rtn))
15934 (defun org-closest-date (start current change prefer show-all)
15935 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15936 When PREFER is `past', return a date that is either CURRENT or past.
15937 When PREFER is `future', return a date that is either CURRENT or future.
15938 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15939 ;; Make the proper lists from the dates
15940 (catch 'exit
15941 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15942 dn dw sday cday n1 n2 n0
15943 d m y y1 y2 date1 date2 nmonths nm ny m2)
15945 (setq start (org-date-to-gregorian start)
15946 current (org-date-to-gregorian
15947 (if show-all
15948 current
15949 (time-to-days (current-time))))
15950 sday (calendar-absolute-from-gregorian start)
15951 cday (calendar-absolute-from-gregorian current))
15953 (if (<= cday sday) (throw 'exit sday))
15955 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15956 (setq dn (string-to-number (match-string 1 change))
15957 dw (cdr (assoc (match-string 2 change) a1)))
15958 (error "Invalid change specifier: %s" change))
15959 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15960 (cond
15961 ((eq dw 'day)
15962 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15963 n2 (+ n1 dn)))
15964 ((eq dw 'year)
15965 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15966 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15967 (setq date1 (list m d y1)
15968 n1 (calendar-absolute-from-gregorian date1)
15969 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15970 n2 (calendar-absolute-from-gregorian date2)))
15971 ((eq dw 'month)
15972 ;; approx number of month between the two dates
15973 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15974 ;; How often does dn fit in there?
15975 (setq d (nth 1 start) m (car start) y (nth 2 start)
15976 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15977 m (+ m nm)
15978 ny (floor (/ m 12))
15979 y (+ y ny)
15980 m (- m (* ny 12)))
15981 (while (> m 12) (setq m (- m 12) y (1+ y)))
15982 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15983 (setq m2 (+ m dn) y2 y)
15984 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15985 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15986 (while (<= n2 cday)
15987 (setq n1 n2 m m2 y y2)
15988 (setq m2 (+ m dn) y2 y)
15989 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15990 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15991 ;; Make sure n1 is the earlier date
15992 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15993 (if show-all
15994 (cond
15995 ((eq prefer 'past) (if (= cday n2) n2 n1))
15996 ((eq prefer 'future) (if (= cday n1) n1 n2))
15997 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15998 (cond
15999 ((eq prefer 'past) (if (= cday n2) n2 n1))
16000 ((eq prefer 'future) (if (= cday n1) n1 n2))
16001 (t (if (= cday n1) n1 n2)))))))
16003 (defun org-date-to-gregorian (date)
16004 "Turn any specification of DATE into a Gregorian date for the calendar."
16005 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16006 ((and (listp date) (= (length date) 3)) date)
16007 ((stringp date)
16008 (setq date (org-parse-time-string date))
16009 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16010 ((listp date)
16011 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16013 (defun org-parse-time-string (s &optional nodefault)
16014 "Parse the standard Org-mode time string.
16015 This should be a lot faster than the normal `parse-time-string'.
16016 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16017 hour and minute fields will be nil if not given."
16018 (if (string-match org-ts-regexp0 s)
16019 (list 0
16020 (if (or (match-beginning 8) (not nodefault))
16021 (string-to-number (or (match-string 8 s) "0")))
16022 (if (or (match-beginning 7) (not nodefault))
16023 (string-to-number (or (match-string 7 s) "0")))
16024 (string-to-number (match-string 4 s))
16025 (string-to-number (match-string 3 s))
16026 (string-to-number (match-string 2 s))
16027 nil nil nil)
16028 (error "Not a standard Org-mode time string: %s" s)))
16030 (defun org-timestamp-up (&optional arg)
16031 "Increase the date item at the cursor by one.
16032 If the cursor is on the year, change the year. If it is on the month,
16033 the day or the time, change that.
16034 With prefix ARG, change by that many units."
16035 (interactive "p")
16036 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16038 (defun org-timestamp-down (&optional arg)
16039 "Decrease the date item at the cursor by one.
16040 If the cursor is on the year, change the year. If it is on the month,
16041 the day or the time, change that.
16042 With prefix ARG, change by that many units."
16043 (interactive "p")
16044 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16046 (defun org-timestamp-up-day (&optional arg)
16047 "Increase the date in the time stamp by one day.
16048 With prefix ARG, change that many days."
16049 (interactive "p")
16050 (if (and (not (org-at-timestamp-p t))
16051 (org-at-heading-p))
16052 (org-todo 'up)
16053 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16055 (defun org-timestamp-down-day (&optional arg)
16056 "Decrease the date in the time stamp by one day.
16057 With prefix ARG, change that many days."
16058 (interactive "p")
16059 (if (and (not (org-at-timestamp-p t))
16060 (org-at-heading-p))
16061 (org-todo 'down)
16062 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16064 (defun org-at-timestamp-p (&optional inactive-ok)
16065 "Determine if the cursor is in or at a timestamp."
16066 (interactive)
16067 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16068 (pos (point))
16069 (ans (or (looking-at tsr)
16070 (save-excursion
16071 (skip-chars-backward "^[<\n\r\t")
16072 (if (> (point) (point-min)) (backward-char 1))
16073 (and (looking-at tsr)
16074 (> (- (match-end 0) pos) -1))))))
16075 (and ans
16076 (boundp 'org-ts-what)
16077 (setq org-ts-what
16078 (cond
16079 ((= pos (match-beginning 0)) 'bracket)
16080 ;; Point is considered to be "on the bracket" whether
16081 ;; it's really on it or right after it.
16082 ((or (= pos (1- (match-end 0)))
16083 (= pos (match-end 0))) 'bracket)
16084 ((org-pos-in-match-range pos 2) 'year)
16085 ((org-pos-in-match-range pos 3) 'month)
16086 ((org-pos-in-match-range pos 7) 'hour)
16087 ((org-pos-in-match-range pos 8) 'minute)
16088 ((or (org-pos-in-match-range pos 4)
16089 (org-pos-in-match-range pos 5)) 'day)
16090 ((and (> pos (or (match-end 8) (match-end 5)))
16091 (< pos (match-end 0)))
16092 (- pos (or (match-end 8) (match-end 5))))
16093 (t 'day))))
16094 ans))
16096 (defun org-toggle-timestamp-type ()
16097 "Toggle the type (<active> or [inactive]) of a time stamp."
16098 (interactive)
16099 (when (org-at-timestamp-p t)
16100 (let ((beg (match-beginning 0)) (end (match-end 0))
16101 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16102 (save-excursion
16103 (goto-char beg)
16104 (while (re-search-forward "[][<>]" end t)
16105 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16106 t t)))
16107 (message "Timestamp is now %sactive"
16108 (if (equal (char-after beg) ?<) "" "in")))))
16110 (defun org-timestamp-change (n &optional what updown)
16111 "Change the date in the time stamp at point.
16112 The date will be changed by N times WHAT. WHAT can be `day', `month',
16113 `year', `minute', `second'. If WHAT is not given, the cursor position
16114 in the timestamp determines what will be changed."
16115 (let ((origin (point)) origin-cat
16116 with-hm inactive
16117 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16118 org-ts-what
16119 extra rem
16120 ts time time0)
16121 (if (not (org-at-timestamp-p t))
16122 (error "Not at a timestamp"))
16123 (if (and (not what) (eq org-ts-what 'bracket))
16124 (org-toggle-timestamp-type)
16125 ;; Point isn't on brackets. Remember the part of the time-stamp
16126 ;; the point was in. Indeed, size of time-stamps may change,
16127 ;; but point must be kept in the same category nonetheless.
16128 (setq origin-cat org-ts-what)
16129 (if (and (not what) (not (eq org-ts-what 'day))
16130 org-display-custom-times
16131 (get-text-property (point) 'display)
16132 (not (get-text-property (1- (point)) 'display)))
16133 (setq org-ts-what 'day))
16134 (setq org-ts-what (or what org-ts-what)
16135 inactive (= (char-after (match-beginning 0)) ?\[)
16136 ts (match-string 0))
16137 (replace-match "")
16138 (if (string-match
16139 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16141 (setq extra (match-string 1 ts)))
16142 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16143 (setq with-hm t))
16144 (setq time0 (org-parse-time-string ts))
16145 (when (and updown
16146 (eq org-ts-what 'minute)
16147 (not current-prefix-arg))
16148 ;; This looks like s-up and s-down. Change by one rounding step.
16149 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16150 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16151 (setcar (cdr time0) (+ (nth 1 time0)
16152 (if (> n 0) (- rem) (- dm rem))))))
16153 (setq time
16154 (encode-time (or (car time0) 0)
16155 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16156 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16157 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16158 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16159 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16160 (nthcdr 6 time0)))
16161 (when (and (member org-ts-what '(hour minute))
16162 extra
16163 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16164 (setq extra (org-modify-ts-extra
16165 extra
16166 (if (eq org-ts-what 'hour) 2 5)
16167 n dm)))
16168 (when (integerp org-ts-what)
16169 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16170 (if (eq what 'calendar)
16171 (let ((cal-date (org-get-date-from-calendar)))
16172 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16173 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16174 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16175 (setcar time0 (or (car time0) 0))
16176 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16177 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16178 (setq time (apply 'encode-time time0))))
16179 ;; Insert the new time-stamp, and ensure point stays in the same
16180 ;; category as before (i.e. not after the last position in that
16181 ;; category).
16182 (let ((pos (point)))
16183 ;; Stay before inserted string. `save-excursion' is of no use.
16184 (setq org-last-changed-timestamp
16185 (org-insert-time-stamp time with-hm inactive nil nil extra))
16186 (goto-char pos))
16187 (save-match-data
16188 (looking-at org-ts-regexp3)
16189 (goto-char (cond
16190 ;; `day' category ends before `hour' if any, or at
16191 ;; the end of the day name.
16192 ((eq origin-cat 'day)
16193 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16194 ((eq origin-cat 'hour) (min (match-end 7) origin))
16195 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16196 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16197 ;; `year' and `month' have both fixed size: point
16198 ;; couldn't have moved into another part.
16199 (t origin))))
16200 ;; Update clock if on a CLOCK line.
16201 (org-clock-update-time-maybe)
16202 ;; Try to recenter the calendar window, if any.
16203 (if (and org-calendar-follow-timestamp-change
16204 (get-buffer-window "*Calendar*" t)
16205 (memq org-ts-what '(day month year)))
16206 (org-recenter-calendar (time-to-days time))))))
16208 (defun org-modify-ts-extra (s pos n dm)
16209 "Change the different parts of the lead-time and repeat fields in timestamp."
16210 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16211 ng h m new rem)
16212 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16213 (cond
16214 ((or (org-pos-in-match-range pos 2)
16215 (org-pos-in-match-range pos 3))
16216 (setq m (string-to-number (match-string 3 s))
16217 h (string-to-number (match-string 2 s)))
16218 (if (org-pos-in-match-range pos 2)
16219 (setq h (+ h n))
16220 (setq n (* dm (org-no-warnings (signum n))))
16221 (when (not (= 0 (setq rem (% m dm))))
16222 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16223 (setq m (+ m n)))
16224 (if (< m 0) (setq m (+ m 60) h (1- h)))
16225 (if (> m 59) (setq m (- m 60) h (1+ h)))
16226 (setq h (min 24 (max 0 h)))
16227 (setq ng 1 new (format "-%02d:%02d" h m)))
16228 ((org-pos-in-match-range pos 6)
16229 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16230 ((org-pos-in-match-range pos 5)
16231 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16233 ((org-pos-in-match-range pos 9)
16234 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16235 ((org-pos-in-match-range pos 8)
16236 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16238 (when ng
16239 (setq s (concat
16240 (substring s 0 (match-beginning ng))
16242 (substring s (match-end ng))))))
16245 (defun org-recenter-calendar (date)
16246 "If the calendar is visible, recenter it to DATE."
16247 (let ((cwin (get-buffer-window "*Calendar*" t)))
16248 (when cwin
16249 (let ((calendar-move-hook nil))
16250 (with-selected-window cwin
16251 (calendar-goto-date (if (listp date) date
16252 (calendar-gregorian-from-absolute date))))))))
16254 (defun org-goto-calendar (&optional arg)
16255 "Go to the Emacs calendar at the current date.
16256 If there is a time stamp in the current line, go to that date.
16257 A prefix ARG can be used to force the current date."
16258 (interactive "P")
16259 (let ((tsr org-ts-regexp) diff
16260 (calendar-move-hook nil)
16261 (calendar-view-holidays-initially-flag nil)
16262 (calendar-view-diary-initially-flag nil))
16263 (if (or (org-at-timestamp-p)
16264 (save-excursion
16265 (beginning-of-line 1)
16266 (looking-at (concat ".*" tsr))))
16267 (let ((d1 (time-to-days (current-time)))
16268 (d2 (time-to-days
16269 (org-time-string-to-time (match-string 1)))))
16270 (setq diff (- d2 d1))))
16271 (calendar)
16272 (calendar-goto-today)
16273 (if (and diff (not arg)) (calendar-forward-day diff))))
16275 (defun org-get-date-from-calendar ()
16276 "Return a list (month day year) of date at point in calendar."
16277 (with-current-buffer "*Calendar*"
16278 (save-match-data
16279 (calendar-cursor-to-date))))
16281 (defun org-date-from-calendar ()
16282 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16283 If there is already a time stamp at the cursor position, update it."
16284 (interactive)
16285 (if (org-at-timestamp-p t)
16286 (org-timestamp-change 0 'calendar)
16287 (let ((cal-date (org-get-date-from-calendar)))
16288 (org-insert-time-stamp
16289 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16291 (defun org-minutes-to-hh:mm-string (m)
16292 "Compute H:MM from a number of minutes."
16293 (let ((h (/ m 60)))
16294 (setq m (- m (* 60 h)))
16295 (format org-time-clocksum-format h m)))
16297 (defun org-hh:mm-string-to-minutes (s)
16298 "Convert a string H:MM to a number of minutes.
16299 If the string is just a number, interpret it as minutes.
16300 In fact, the first hh:mm or number in the string will be taken,
16301 there can be extra stuff in the string.
16302 If no number is found, the return value is 0."
16303 (cond
16304 ((integerp s) s)
16305 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16306 (+ (* (string-to-number (match-string 1 s)) 60)
16307 (string-to-number (match-string 2 s))))
16308 ((string-match "\\([0-9]+\\)" s)
16309 (string-to-number (match-string 1 s)))
16310 (t 0)))
16312 (defcustom org-effort-durations
16313 `(("h" . 60)
16314 ("d" . ,(* 60 8))
16315 ("w" . ,(* 60 8 5))
16316 ("m" . ,(* 60 8 5 4))
16317 ("y" . ,(* 60 8 5 40)))
16318 "Conversion factor to minutes for an effort modifier.
16320 Each entry has the form (MODIFIER . MINUTES).
16322 In an effort string, a number followed by MODIFIER is multiplied
16323 by the specified number of MINUTES to obtain an effort in
16324 minutes.
16326 For example, if the value of this variable is ((\"hours\" . 60)), then an
16327 effort string \"2hours\" is equivalent to 120 minutes."
16328 :group 'org-agenda
16329 :version "24.1"
16330 :type '(alist :key-type (string :tag "Modifier")
16331 :value-type (number :tag "Minutes")))
16333 (defun org-duration-string-to-minutes (s)
16334 "Convert a duration string S to minutes.
16336 A bare number is interpreted as minutes, modifiers can be set by
16337 customizing `org-effort-durations' (which see).
16339 Entries containing a colon are interpreted as H:MM by
16340 `org-hh:mm-string-to-minutes'."
16341 (let ((result 0)
16342 (re (concat "\\([0-9]+\\) *\\("
16343 (regexp-opt (mapcar 'car org-effort-durations))
16344 "\\)")))
16345 (while (string-match re s)
16346 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16347 (string-to-number (match-string 1 s))))
16348 (setq s (replace-match "" nil t s)))
16349 (incf result (org-hh:mm-string-to-minutes s))
16350 result))
16352 ;;;; Files
16354 (defun org-save-all-org-buffers ()
16355 "Save all Org-mode buffers without user confirmation."
16356 (interactive)
16357 (message "Saving all Org-mode buffers...")
16358 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16359 (when (featurep 'org-id) (org-id-locations-save))
16360 (message "Saving all Org-mode buffers... done"))
16362 (defun org-revert-all-org-buffers ()
16363 "Revert all Org-mode buffers.
16364 Prompt for confirmation when there are unsaved changes.
16365 Be sure you know what you are doing before letting this function
16366 overwrite your changes.
16368 This function is useful in a setup where one tracks org files
16369 with a version control system, to revert on one machine after pulling
16370 changes from another. I believe the procedure must be like this:
16372 1. M-x org-save-all-org-buffers
16373 2. Pull changes from the other machine, resolve conflicts
16374 3. M-x org-revert-all-org-buffers"
16375 (interactive)
16376 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16377 (error "Abort"))
16378 (save-excursion
16379 (save-window-excursion
16380 (mapc
16381 (lambda (b)
16382 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16383 (with-current-buffer b buffer-file-name))
16384 (org-pop-to-buffer-same-window b)
16385 (revert-buffer t 'no-confirm)))
16386 (buffer-list))
16387 (when (and (featurep 'org-id) org-id-track-globally)
16388 (org-id-locations-load)))))
16390 ;;;; Agenda files
16392 ;;;###autoload
16393 (defun org-switchb (&optional arg)
16394 "Switch between Org buffers.
16395 With one prefix argument, restrict available buffers to files.
16396 With two prefix arguments, restrict available buffers to agenda files.
16398 Defaults to `iswitchb' for buffer name completion.
16399 Set `org-completion-use-ido' to make it use ido instead."
16400 (interactive "P")
16401 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16402 ((equal arg '(16)) (org-buffer-list 'agenda))
16403 (t (org-buffer-list))))
16404 (org-completion-use-iswitchb org-completion-use-iswitchb)
16405 (org-completion-use-ido org-completion-use-ido))
16406 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16407 (setq org-completion-use-iswitchb t))
16408 (org-pop-to-buffer-same-window
16409 (org-icompleting-read "Org buffer: "
16410 (mapcar 'list (mapcar 'buffer-name blist))
16411 nil t))))
16413 ;;; Define some older names previously used for this functionality
16414 ;;;###autoload
16415 (defalias 'org-ido-switchb 'org-switchb)
16416 ;;;###autoload
16417 (defalias 'org-iswitchb 'org-switchb)
16419 (defun org-buffer-list (&optional predicate exclude-tmp)
16420 "Return a list of Org buffers.
16421 PREDICATE can be `export', `files' or `agenda'.
16423 export restrict the list to Export buffers.
16424 files restrict the list to buffers visiting Org files.
16425 agenda restrict the list to buffers visiting agenda files.
16427 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16428 (let* ((bfn nil)
16429 (agenda-files (and (eq predicate 'agenda)
16430 (mapcar 'file-truename (org-agenda-files t))))
16431 (filter
16432 (cond
16433 ((eq predicate 'files)
16434 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16435 ((eq predicate 'export)
16436 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16437 ((eq predicate 'agenda)
16438 (lambda (b)
16439 (with-current-buffer b
16440 (and (eq major-mode 'org-mode)
16441 (setq bfn (buffer-file-name b))
16442 (member (file-truename bfn) agenda-files)))))
16443 (t (lambda (b) (with-current-buffer b
16444 (or (eq major-mode 'org-mode)
16445 (string-match "\*Org .*Export"
16446 (buffer-name b)))))))))
16447 (delq nil
16448 (mapcar
16449 (lambda(b)
16450 (if (and (funcall filter b)
16451 (or (not exclude-tmp)
16452 (not (string-match "tmp" (buffer-name b)))))
16454 nil))
16455 (buffer-list)))))
16457 (defun org-agenda-files (&optional unrestricted archives)
16458 "Get the list of agenda files.
16459 Optional UNRESTRICTED means return the full list even if a restriction
16460 is currently in place.
16461 When ARCHIVES is t, include all archive files that are really being
16462 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16463 `org-agenda-archives-mode' is t."
16464 (let ((files
16465 (cond
16466 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16467 ((stringp org-agenda-files) (org-read-agenda-file-list))
16468 ((listp org-agenda-files) org-agenda-files)
16469 (t (error "Invalid value of `org-agenda-files'")))))
16470 (setq files (apply 'append
16471 (mapcar (lambda (f)
16472 (if (file-directory-p f)
16473 (directory-files
16474 f t org-agenda-file-regexp)
16475 (list f)))
16476 files)))
16477 (when org-agenda-skip-unavailable-files
16478 (setq files (delq nil
16479 (mapcar (function
16480 (lambda (file)
16481 (and (file-readable-p file) file)))
16482 files))))
16483 (when (or (eq archives t)
16484 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16485 (setq files (org-add-archive-files files)))
16486 files))
16488 (defun org-agenda-file-p (&optional file)
16489 "Return non-nil, if FILE is an agenda file.
16490 If FILE is omitted, use the file associated with the current
16491 buffer."
16492 (member (or file (buffer-file-name))
16493 (org-agenda-files t)))
16495 (defun org-edit-agenda-file-list ()
16496 "Edit the list of agenda files.
16497 Depending on setup, this either uses customize to edit the variable
16498 `org-agenda-files', or it visits the file that is holding the list. In the
16499 latter case, the buffer is set up in a way that saving it automatically kills
16500 the buffer and restores the previous window configuration."
16501 (interactive)
16502 (if (stringp org-agenda-files)
16503 (let ((cw (current-window-configuration)))
16504 (find-file org-agenda-files)
16505 (org-set-local 'org-window-configuration cw)
16506 (org-add-hook 'after-save-hook
16507 (lambda ()
16508 (set-window-configuration
16509 (prog1 org-window-configuration
16510 (kill-buffer (current-buffer))))
16511 (org-install-agenda-files-menu)
16512 (message "New agenda file list installed"))
16513 nil 'local)
16514 (message "%s" (substitute-command-keys
16515 "Edit list and finish with \\[save-buffer]")))
16516 (customize-variable 'org-agenda-files)))
16518 (defun org-store-new-agenda-file-list (list)
16519 "Set new value for the agenda file list and save it correctly."
16520 (if (stringp org-agenda-files)
16521 (let ((fe (org-read-agenda-file-list t)) b u)
16522 (while (setq b (find-buffer-visiting org-agenda-files))
16523 (kill-buffer b))
16524 (with-temp-file org-agenda-files
16525 (insert
16526 (mapconcat
16527 (lambda (f) ;; Keep un-expanded entries.
16528 (if (setq u (assoc f fe))
16529 (cdr u)
16531 list "\n")
16532 "\n")))
16533 (let ((org-mode-hook nil) (org-inhibit-startup t)
16534 (org-insert-mode-line-in-empty-file nil))
16535 (setq org-agenda-files list)
16536 (customize-save-variable 'org-agenda-files org-agenda-files))))
16538 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16539 "Read the list of agenda files from a file.
16540 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16541 filenames, used by `org-store-new-agenda-file-list' to write back
16542 un-expanded file names."
16543 (when (file-directory-p org-agenda-files)
16544 (error "`org-agenda-files' cannot be a single directory"))
16545 (when (stringp org-agenda-files)
16546 (with-temp-buffer
16547 (insert-file-contents org-agenda-files)
16548 (mapcar
16549 (lambda (f)
16550 (let ((e (expand-file-name (substitute-in-file-name f)
16551 org-directory)))
16552 (if pair-with-expansion
16553 (cons e f)
16554 e)))
16555 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16557 ;;;###autoload
16558 (defun org-cycle-agenda-files ()
16559 "Cycle through the files in `org-agenda-files'.
16560 If the current buffer visits an agenda file, find the next one in the list.
16561 If the current buffer does not, find the first agenda file."
16562 (interactive)
16563 (let* ((fs (org-agenda-files t))
16564 (files (append fs (list (car fs))))
16565 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16566 file)
16567 (unless files (error "No agenda files"))
16568 (catch 'exit
16569 (while (setq file (pop files))
16570 (if (equal (file-truename file) tcf)
16571 (when (car files)
16572 (find-file (car files))
16573 (throw 'exit t))))
16574 (find-file (car fs)))
16575 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16577 (defun org-agenda-file-to-front (&optional to-end)
16578 "Move/add the current file to the top of the agenda file list.
16579 If the file is not present in the list, it is added to the front. If it is
16580 present, it is moved there. With optional argument TO-END, add/move to the
16581 end of the list."
16582 (interactive "P")
16583 (let ((org-agenda-skip-unavailable-files nil)
16584 (file-alist (mapcar (lambda (x)
16585 (cons (file-truename x) x))
16586 (org-agenda-files t)))
16587 (ctf (file-truename buffer-file-name))
16588 x had)
16589 (setq x (assoc ctf file-alist) had x)
16591 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16592 (if to-end
16593 (setq file-alist (append (delq x file-alist) (list x)))
16594 (setq file-alist (cons x (delq x file-alist))))
16595 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16596 (org-install-agenda-files-menu)
16597 (message "File %s to %s of agenda file list"
16598 (if had "moved" "added") (if to-end "end" "front"))))
16600 (defun org-remove-file (&optional file)
16601 "Remove current file from the list of files in variable `org-agenda-files'.
16602 These are the files which are being checked for agenda entries.
16603 Optional argument FILE means use this file instead of the current."
16604 (interactive)
16605 (let* ((org-agenda-skip-unavailable-files nil)
16606 (file (or file buffer-file-name))
16607 (true-file (file-truename file))
16608 (afile (abbreviate-file-name file))
16609 (files (delq nil (mapcar
16610 (lambda (x)
16611 (if (equal true-file
16612 (file-truename x))
16613 nil x))
16614 (org-agenda-files t)))))
16615 (if (not (= (length files) (length (org-agenda-files t))))
16616 (progn
16617 (org-store-new-agenda-file-list files)
16618 (org-install-agenda-files-menu)
16619 (message "Removed file: %s" afile))
16620 (message "File was not in list: %s (not removed)" afile))))
16622 (defun org-file-menu-entry (file)
16623 (vector file (list 'find-file file) t))
16625 (defun org-check-agenda-file (file)
16626 "Make sure FILE exists. If not, ask user what to do."
16627 (when (not (file-exists-p file))
16628 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16629 (abbreviate-file-name file))
16630 (let ((r (downcase (read-char-exclusive))))
16631 (cond
16632 ((equal r ?r)
16633 (org-remove-file file)
16634 (throw 'nextfile t))
16635 (t (error "Abort"))))))
16637 (defun org-get-agenda-file-buffer (file)
16638 "Get a buffer visiting FILE. If the buffer needs to be created, add
16639 it to the list of buffers which might be released later."
16640 (let ((buf (org-find-base-buffer-visiting file)))
16641 (if buf
16642 buf ; just return it
16643 ;; Make a new buffer and remember it
16644 (setq buf (find-file-noselect file))
16645 (if buf (push buf org-agenda-new-buffers))
16646 buf)))
16648 (defun org-release-buffers (blist)
16649 "Release all buffers in list, asking the user for confirmation when needed.
16650 When a buffer is unmodified, it is just killed. When modified, it is saved
16651 \(if the user agrees) and then killed."
16652 (let (buf file)
16653 (while (setq buf (pop blist))
16654 (setq file (buffer-file-name buf))
16655 (when (and (buffer-modified-p buf)
16656 file
16657 (y-or-n-p (format "Save file %s? " file)))
16658 (with-current-buffer buf (save-buffer)))
16659 (kill-buffer buf))))
16661 (defun org-prepare-agenda-buffers (files)
16662 "Create buffers for all agenda files, protect archived trees and comments."
16663 (interactive)
16664 (let ((pa '(:org-archived t))
16665 (pc '(:org-comment t))
16666 (pall '(:org-archived t :org-comment t))
16667 (inhibit-read-only t)
16668 (rea (concat ":" org-archive-tag ":"))
16669 bmp file re)
16670 (save-excursion
16671 (save-restriction
16672 (while (setq file (pop files))
16673 (catch 'nextfile
16674 (if (bufferp file)
16675 (set-buffer file)
16676 (org-check-agenda-file file)
16677 (set-buffer (org-get-agenda-file-buffer file)))
16678 (widen)
16679 (setq bmp (buffer-modified-p))
16680 (org-refresh-category-properties)
16681 (setq org-todo-keywords-for-agenda
16682 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16683 (setq org-done-keywords-for-agenda
16684 (append org-done-keywords-for-agenda org-done-keywords))
16685 (setq org-todo-keyword-alist-for-agenda
16686 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16687 (setq org-drawers-for-agenda
16688 (append org-drawers-for-agenda org-drawers))
16689 (setq org-tag-alist-for-agenda
16690 (append org-tag-alist-for-agenda org-tag-alist))
16692 (save-excursion
16693 (remove-text-properties (point-min) (point-max) pall)
16694 (when org-agenda-skip-archived-trees
16695 (goto-char (point-min))
16696 (while (re-search-forward rea nil t)
16697 (if (org-at-heading-p t)
16698 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16699 (goto-char (point-min))
16700 (setq re (format org-heading-keyword-regexp-format
16701 org-comment-string))
16702 (while (re-search-forward re nil t)
16703 (add-text-properties
16704 (match-beginning 0) (org-end-of-subtree t) pc)))
16705 (set-buffer-modified-p bmp)))))
16706 (setq org-todo-keywords-for-agenda
16707 (org-uniquify org-todo-keywords-for-agenda))
16708 (setq org-todo-keyword-alist-for-agenda
16709 (org-uniquify org-todo-keyword-alist-for-agenda)
16710 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16712 ;;;; Embedded LaTeX
16714 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16715 "Keymap for the minor `org-cdlatex-mode'.")
16717 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16718 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16719 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16720 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16721 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16723 (defvar org-cdlatex-texmathp-advice-is-done nil
16724 "Flag remembering if we have applied the advice to texmathp already.")
16726 (define-minor-mode org-cdlatex-mode
16727 "Toggle the minor `org-cdlatex-mode'.
16728 This mode supports entering LaTeX environment and math in LaTeX fragments
16729 in Org-mode.
16730 \\{org-cdlatex-mode-map}"
16731 nil " OCDL" nil
16732 (when org-cdlatex-mode
16733 (require 'cdlatex)
16734 (run-hooks 'cdlatex-mode-hook)
16735 (cdlatex-compute-tables))
16736 (unless org-cdlatex-texmathp-advice-is-done
16737 (setq org-cdlatex-texmathp-advice-is-done t)
16738 (defadvice texmathp (around org-math-always-on activate)
16739 "Always return t in org-mode buffers.
16740 This is because we want to insert math symbols without dollars even outside
16741 the LaTeX math segments. If Orgmode thinks that point is actually inside
16742 an embedded LaTeX fragment, let texmathp do its job.
16743 \\[org-cdlatex-mode-map]"
16744 (interactive)
16745 (let (p)
16746 (cond
16747 ((not (eq major-mode 'org-mode)) ad-do-it)
16748 ((eq this-command 'cdlatex-math-symbol)
16749 (setq ad-return-value t
16750 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16752 (let ((p (org-inside-LaTeX-fragment-p)))
16753 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16754 (setq ad-return-value t
16755 texmathp-why '("Org-mode embedded math" . 0))
16756 (if p ad-do-it)))))))))
16758 (defun turn-on-org-cdlatex ()
16759 "Unconditionally turn on `org-cdlatex-mode'."
16760 (org-cdlatex-mode 1))
16762 (defun org-inside-LaTeX-fragment-p ()
16763 "Test if point is inside a LaTeX fragment.
16764 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16765 sequence appearing also before point.
16766 Even though the matchers for math are configurable, this function assumes
16767 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16768 delimiters are skipped when they have been removed by customization.
16769 The return value is nil, or a cons cell with the delimiter and the
16770 position of this delimiter.
16772 This function does a reasonably good job, but can locally be fooled by
16773 for example currency specifications. For example it will assume being in
16774 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16775 fragments that are properly closed, but during editing, we have to live
16776 with the uncertainty caused by missing closing delimiters. This function
16777 looks only before point, not after."
16778 (catch 'exit
16779 (let ((pos (point))
16780 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16781 (lim (progn
16782 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16783 (point)))
16784 dd-on str (start 0) m re)
16785 (goto-char pos)
16786 (when dodollar
16787 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16788 re (nth 1 (assoc "$" org-latex-regexps)))
16789 (while (string-match re str start)
16790 (cond
16791 ((= (match-end 0) (length str))
16792 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16793 ((= (match-end 0) (- (length str) 5))
16794 (throw 'exit nil))
16795 (t (setq start (match-end 0))))))
16796 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16797 (goto-char pos)
16798 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16799 (and (match-beginning 2) (throw 'exit nil))
16800 ;; count $$
16801 (while (re-search-backward "\\$\\$" lim t)
16802 (setq dd-on (not dd-on)))
16803 (goto-char pos)
16804 (if dd-on (cons "$$" m))))))
16806 (defun org-inside-latex-macro-p ()
16807 "Is point inside a LaTeX macro or its arguments?"
16808 (save-match-data
16809 (org-in-regexp
16810 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16812 (defun org-try-cdlatex-tab ()
16813 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16814 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16815 - inside a LaTeX fragment, or
16816 - after the first word in a line, where an abbreviation expansion could
16817 insert a LaTeX environment."
16818 (when org-cdlatex-mode
16819 (cond
16820 ;; Before any word on the line: No expansion possible.
16821 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16822 ;; Just after first word on the line: Expand it. Make sure it
16823 ;; cannot happen on headlines, though.
16824 ((save-excursion
16825 (skip-chars-backward "a-zA-Z0-9*")
16826 (skip-chars-backward " \t")
16827 (and (bolp) (not (org-at-heading-p))))
16828 (cdlatex-tab) t)
16829 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16831 (defun org-cdlatex-underscore-caret (&optional arg)
16832 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16833 Revert to the normal definition outside of these fragments."
16834 (interactive "P")
16835 (if (org-inside-LaTeX-fragment-p)
16836 (call-interactively 'cdlatex-sub-superscript)
16837 (let (org-cdlatex-mode)
16838 (call-interactively (key-binding (vector last-input-event))))))
16840 (defun org-cdlatex-math-modify (&optional arg)
16841 "Execute `cdlatex-math-modify' in LaTeX fragments.
16842 Revert to the normal definition outside of these fragments."
16843 (interactive "P")
16844 (if (org-inside-LaTeX-fragment-p)
16845 (call-interactively 'cdlatex-math-modify)
16846 (let (org-cdlatex-mode)
16847 (call-interactively (key-binding (vector last-input-event))))))
16849 (defvar org-latex-fragment-image-overlays nil
16850 "List of overlays carrying the images of latex fragments.")
16851 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16853 (defun org-remove-latex-fragment-image-overlays ()
16854 "Remove all overlays with LaTeX fragment images in current buffer."
16855 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16856 (setq org-latex-fragment-image-overlays nil))
16858 (defun org-preview-latex-fragment (&optional subtree)
16859 "Preview the LaTeX fragment at point, or all locally or globally.
16860 If the cursor is in a LaTeX fragment, create the image and overlay
16861 it over the source code. If there is no fragment at point, display
16862 all fragments in the current text, from one headline to the next. With
16863 prefix SUBTREE, display all fragments in the current subtree. With a
16864 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16865 the cursor is before the first headline,
16866 display all fragments in the buffer.
16867 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16868 (interactive "P")
16869 (unless buffer-file-name
16870 (error "Can't preview LaTeX fragment in a non-file buffer"))
16871 (org-remove-latex-fragment-image-overlays)
16872 (save-excursion
16873 (save-restriction
16874 (let (beg end at msg)
16875 (cond
16876 ((or (equal subtree '(16))
16877 (not (save-excursion
16878 (re-search-backward org-outline-regexp-bol nil t))))
16879 (setq beg (point-min) end (point-max)
16880 msg "Creating images for buffer...%s"))
16881 ((equal subtree '(4))
16882 (org-back-to-heading)
16883 (setq beg (point) end (org-end-of-subtree t)
16884 msg "Creating images for subtree...%s"))
16886 (if (setq at (org-inside-LaTeX-fragment-p))
16887 (goto-char (max (point-min) (- (cdr at) 2)))
16888 (org-back-to-heading))
16889 (setq beg (point) end (progn (outline-next-heading) (point))
16890 msg (if at "Creating image...%s"
16891 "Creating images for entry...%s"))))
16892 (message msg "")
16893 (narrow-to-region beg end)
16894 (goto-char beg)
16895 (org-format-latex
16896 (concat "ltxpng/" (file-name-sans-extension
16897 (file-name-nondirectory
16898 buffer-file-name)))
16899 default-directory 'overlays msg at 'forbuffer 'dvipng)
16900 (message msg "done. Use `C-c C-c' to remove images.")))))
16902 (defvar org-latex-regexps
16903 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16904 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16905 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16906 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16907 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16908 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16909 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16910 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16911 "Regular expressions for matching embedded LaTeX.")
16913 (defvar org-export-have-math nil) ;; dynamic scoping
16914 (defun org-format-latex (prefix &optional dir overlays msg at
16915 forbuffer processing-type)
16916 "Replace LaTeX fragments with links to an image, and produce images.
16917 Some of the options can be changed using the variable
16918 `org-format-latex-options'."
16919 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16920 (let* ((prefixnodir (file-name-nondirectory prefix))
16921 (absprefix (expand-file-name prefix dir))
16922 (todir (file-name-directory absprefix))
16923 (opt org-format-latex-options)
16924 (matchers (plist-get opt :matchers))
16925 (re-list org-latex-regexps)
16926 (org-format-latex-header-extra
16927 (plist-get (org-infile-export-plist) :latex-header-extra))
16928 (cnt 0) txt hash link beg end re e checkdir
16929 executables-checked string
16930 m n block-type block linkfile movefile ov)
16931 ;; Check the different regular expressions
16932 (while (setq e (pop re-list))
16933 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16934 block (if block-type "\n\n" ""))
16935 (when (member m matchers)
16936 (goto-char (point-min))
16937 (while (re-search-forward re nil t)
16938 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16939 (not (get-text-property (match-beginning n)
16940 'org-protected))
16941 (or (not overlays)
16942 (not (eq (get-char-property (match-beginning n)
16943 'org-overlay-type)
16944 'org-latex-overlay))))
16945 (setq org-export-have-math t)
16946 (cond
16947 ((eq processing-type 'verbatim)
16948 ;; Leave the text verbatim, just protect it
16949 (add-text-properties (match-beginning n) (match-end n)
16950 '(org-protected t)))
16951 ((eq processing-type 'mathjax)
16952 ;; Prepare for MathJax processing
16953 (setq string (match-string n))
16954 (if (member m '("$" "$1"))
16955 (save-excursion
16956 (delete-region (match-beginning n) (match-end n))
16957 (goto-char (match-beginning n))
16958 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16959 "\\)")
16960 '(org-protected t))))
16961 (add-text-properties (match-beginning n) (match-end n)
16962 '(org-protected t))))
16963 ((eq processing-type 'dvipng)
16964 ;; Process to an image
16965 (setq txt (match-string n)
16966 beg (match-beginning n) end (match-end n)
16967 cnt (1+ cnt))
16968 (let (print-length print-level) ; make sure full list is printed
16969 (setq hash (sha1 (prin1-to-string
16970 (list org-format-latex-header
16971 org-format-latex-header-extra
16972 org-export-latex-default-packages-alist
16973 org-export-latex-packages-alist
16974 org-format-latex-options
16975 forbuffer txt)))
16976 linkfile (format "%s_%s.png" prefix hash)
16977 movefile (format "%s_%s.png" absprefix hash)))
16978 (setq link (concat block "[[file:" linkfile "]]" block))
16979 (if msg (message msg cnt))
16980 (goto-char beg)
16981 (unless checkdir ; make sure the directory exists
16982 (setq checkdir t)
16983 (or (file-directory-p todir) (make-directory todir t)))
16985 (unless executables-checked
16986 (org-check-external-command
16987 "latex" "needed to convert LaTeX fragments to images")
16988 (org-check-external-command
16989 "dvipng" "needed to convert LaTeX fragments to images")
16990 (setq executables-checked t))
16992 (unless (file-exists-p movefile)
16993 (org-create-formula-image
16994 txt movefile opt forbuffer))
16995 (if overlays
16996 (progn
16997 (mapc (lambda (o)
16998 (if (eq (overlay-get o 'org-overlay-type)
16999 'org-latex-overlay)
17000 (delete-overlay o)))
17001 (overlays-in beg end))
17002 (setq ov (make-overlay beg end))
17003 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17004 (if (featurep 'xemacs)
17005 (progn
17006 (overlay-put ov 'invisible t)
17007 (overlay-put
17008 ov 'end-glyph
17009 (make-glyph (vector 'png :file movefile))))
17010 (overlay-put
17011 ov 'display
17012 (list 'image :type 'png :file movefile :ascent 'center)))
17013 (push ov org-latex-fragment-image-overlays)
17014 (goto-char end))
17015 (delete-region beg end)
17016 (insert (org-add-props link
17017 (list 'org-latex-src
17018 (replace-regexp-in-string
17019 "\"" "" txt)
17020 'org-latex-src-embed-type
17021 (if block-type 'paragraph 'character))))))
17022 ((eq processing-type 'mathml)
17023 ;; Process to MathML
17024 (unless executables-checked
17025 (unless (save-match-data (org-format-latex-mathml-available-p))
17026 (error "LaTeX to MathML converter not configured"))
17027 (setq executables-checked t))
17028 (setq txt (match-string n)
17029 beg (match-beginning n) end (match-end n)
17030 cnt (1+ cnt))
17031 (if msg (message msg cnt))
17032 (goto-char beg)
17033 (delete-region beg end)
17034 (insert (org-format-latex-as-mathml
17035 txt block-type prefix dir)))
17037 (error "Unknown conversion type %s for latex fragments"
17038 processing-type)))))))))
17040 (defun org-create-math-formula (latex-frag &optional mathml-file)
17041 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17042 Use `org-latex-to-mathml-convert-command'. If the conversion is
17043 sucessful, return the portion between \"<math...> </math>\"
17044 elements otherwise return nil. When MATHML-FILE is specified,
17045 write the results in to that file. When invoked as an
17046 interactive command, prompt for LATEX-FRAG, with initial value
17047 set to the current active region and echo the results for user
17048 inspection."
17049 (interactive (list (let ((frag (when (region-active-p)
17050 (buffer-substring-no-properties
17051 (region-beginning) (region-end)))))
17052 (read-string "LaTeX Fragment: " frag nil frag))))
17053 (unless latex-frag (error "Invalid latex-frag"))
17054 (let* ((tmp-in-file (file-relative-name
17055 (make-temp-name (expand-file-name "ltxmathml-in"))))
17056 (ignore (write-region latex-frag nil tmp-in-file))
17057 (tmp-out-file (file-relative-name
17058 (make-temp-name (expand-file-name "ltxmathml-out"))))
17059 (cmd (format-spec
17060 org-latex-to-mathml-convert-command
17061 `((?j . ,(shell-quote-argument
17062 (expand-file-name org-latex-to-mathml-jar-file)))
17063 (?I . ,(shell-quote-argument tmp-in-file))
17064 (?o . ,(shell-quote-argument tmp-out-file)))))
17065 mathml shell-command-output)
17066 (when (org-called-interactively-p 'any)
17067 (unless (org-format-latex-mathml-available-p)
17068 (error "LaTeX to MathML converter not configured")))
17069 (message "Running %s" cmd)
17070 (setq shell-command-output (shell-command-to-string cmd))
17071 (setq mathml
17072 (when (file-readable-p tmp-out-file)
17073 (with-current-buffer (find-file-noselect tmp-out-file t)
17074 (goto-char (point-min))
17075 (when (re-search-forward
17076 (concat
17077 (regexp-quote
17078 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17079 "\\(.\\|\n\\)*"
17080 (regexp-quote "</math>")) nil t)
17081 (prog1 (match-string 0) (kill-buffer))))))
17082 (cond
17083 (mathml
17084 (setq mathml
17085 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17086 (when mathml-file
17087 (write-region mathml nil mathml-file))
17088 (when (org-called-interactively-p 'any)
17089 (message mathml)))
17090 ((message "LaTeX to MathML conversion failed")
17091 (message shell-command-output)))
17092 (delete-file tmp-in-file)
17093 (when (file-exists-p tmp-out-file)
17094 (delete-file tmp-out-file))
17095 mathml))
17097 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17098 prefix &optional dir)
17099 "Use `org-create-math-formula' but check local cache first."
17100 (let* ((absprefix (expand-file-name prefix dir))
17101 (print-length nil) (print-level nil)
17102 (formula-id (concat
17103 "formula-"
17104 (sha1
17105 (prin1-to-string
17106 (list latex-frag
17107 org-latex-to-mathml-convert-command)))))
17108 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17109 (formula-cache-dir (file-name-directory formula-cache)))
17111 (unless (file-directory-p formula-cache-dir)
17112 (make-directory formula-cache-dir t))
17114 (unless (file-exists-p formula-cache)
17115 (org-create-math-formula latex-frag formula-cache))
17117 (if (file-exists-p formula-cache)
17118 ;; Successful conversion. Return the link to MathML file.
17119 (org-add-props
17120 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17121 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17122 'org-latex-src-embed-type (if latex-frag-type
17123 'paragraph 'character)))
17124 ;; Failed conversion. Return the LaTeX fragment verbatim
17125 (add-text-properties
17126 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17127 latex-frag)))
17129 ;; This function borrows from Ganesh Swami's latex2png.el
17130 (defun org-create-formula-image (string tofile options buffer)
17131 "This calls dvipng."
17132 (require 'org-latex)
17133 (let* ((tmpdir (if (featurep 'xemacs)
17134 (temp-directory)
17135 temporary-file-directory))
17136 (texfilebase (make-temp-name
17137 (expand-file-name "orgtex" tmpdir)))
17138 (texfile (concat texfilebase ".tex"))
17139 (dvifile (concat texfilebase ".dvi"))
17140 (pngfile (concat texfilebase ".png"))
17141 (fnh (if (featurep 'xemacs)
17142 (font-height (face-font 'default))
17143 (face-attribute 'default :height nil)))
17144 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17145 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17146 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17147 "Black"))
17148 (bg (or (plist-get options (if buffer :background :html-background))
17149 "Transparent")))
17150 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17151 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17152 (with-temp-file texfile
17153 (insert (org-splice-latex-header
17154 org-format-latex-header
17155 org-export-latex-default-packages-alist
17156 org-export-latex-packages-alist t
17157 org-format-latex-header-extra))
17158 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17159 (require 'org-latex)
17160 (org-export-latex-fix-inputenc))
17161 (let ((dir default-directory))
17162 (condition-case nil
17163 (progn
17164 (cd tmpdir)
17165 (call-process "latex" nil nil nil texfile))
17166 (error nil))
17167 (cd dir))
17168 (if (not (file-exists-p dvifile))
17169 (progn (message "Failed to create dvi file from %s" texfile) nil)
17170 (condition-case nil
17171 (if (featurep 'xemacs)
17172 (call-process "dvipng" nil nil nil
17173 "-fg" fg "-bg" bg
17174 "-T" "tight"
17175 "-o" pngfile
17176 dvifile)
17177 (call-process "dvipng" nil nil nil
17178 "-fg" fg "-bg" bg
17179 "-D" dpi
17180 ;;"-x" scale "-y" scale
17181 "-T" "tight"
17182 "-o" pngfile
17183 dvifile))
17184 (error nil))
17185 (if (not (file-exists-p pngfile))
17186 (if org-format-latex-signal-error
17187 (error "Failed to create png file from %s" texfile)
17188 (message "Failed to create png file from %s" texfile)
17189 nil)
17190 ;; Use the requested file name and clean up
17191 (copy-file pngfile tofile 'replace)
17192 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17193 (delete-file (concat texfilebase e)))
17194 pngfile))))
17196 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17197 "Fill a LaTeX header template TPL.
17198 In the template, the following place holders will be recognized:
17200 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17201 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17202 [PACKAGES] \\usepackage statements for PKG
17203 [NO-PACKAGES] do not include PKG
17204 [EXTRA] the string EXTRA
17205 [NO-EXTRA] do not include EXTRA
17207 For backward compatibility, if both the positive and the negative place
17208 holder is missing, the positive one (without the \"NO-\") will be
17209 assumed to be present at the end of the template.
17210 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17211 EXTRA is a string.
17212 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17213 (let (rpl (end ""))
17214 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17215 (setq rpl (if (or (match-end 1) (not def-pkg))
17216 "" (org-latex-packages-to-string def-pkg snippets-p t))
17217 tpl (replace-match rpl t t tpl))
17218 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17220 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17221 (setq rpl (if (or (match-end 1) (not pkg))
17222 "" (org-latex-packages-to-string pkg snippets-p t))
17223 tpl (replace-match rpl t t tpl))
17224 (if pkg (setq end
17225 (concat end "\n"
17226 (org-latex-packages-to-string pkg snippets-p)))))
17228 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17229 (setq rpl (if (or (match-end 1) (not extra))
17230 "" (concat extra "\n"))
17231 tpl (replace-match rpl t t tpl))
17232 (if (and extra (string-match "\\S-" extra))
17233 (setq end (concat end "\n" extra))))
17235 (if (string-match "\\S-" end)
17236 (concat tpl "\n" end)
17237 tpl)))
17239 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17240 "Turn an alist of packages into a string with the \\usepackage macros."
17241 (setq pkg (mapconcat (lambda(p)
17242 (cond
17243 ((stringp p) p)
17244 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17245 (format "%% Package %s omitted" (cadr p)))
17246 ((equal "" (car p))
17247 (format "\\usepackage{%s}" (cadr p)))
17249 (format "\\usepackage[%s]{%s}"
17250 (car p) (cadr p)))))
17252 "\n"))
17253 (if newline (concat pkg "\n") pkg))
17255 (defun org-dvipng-color (attr)
17256 "Return an rgb color specification for dvipng."
17257 (apply 'format "rgb %s %s %s"
17258 (mapcar 'org-normalize-color
17259 (if (featurep 'xemacs)
17260 (color-rgb-components
17261 (face-property 'default
17262 (cond ((eq attr :foreground) 'foreground)
17263 ((eq attr :background) 'background))))
17264 (color-values (face-attribute 'default attr nil))))))
17266 (defun org-normalize-color (value)
17267 "Return string to be used as color value for an RGB component."
17268 (format "%g" (/ value 65535.0)))
17270 ;; Image display
17273 (defvar org-inline-image-overlays nil)
17274 (make-variable-buffer-local 'org-inline-image-overlays)
17276 (defun org-toggle-inline-images (&optional include-linked)
17277 "Toggle the display of inline images.
17278 INCLUDE-LINKED is passed to `org-display-inline-images'."
17279 (interactive "P")
17280 (if org-inline-image-overlays
17281 (progn
17282 (org-remove-inline-images)
17283 (message "Inline image display turned off"))
17284 (org-display-inline-images include-linked)
17285 (if org-inline-image-overlays
17286 (message "%d images displayed inline"
17287 (length org-inline-image-overlays))
17288 (message "No images to display inline"))))
17290 (defun org-display-inline-images (&optional include-linked refresh beg end)
17291 "Display inline images.
17292 Normally only links without a description part are inlined, because this
17293 is how it will work for export. When INCLUDE-LINKED is set, also links
17294 with a description part will be inlined. This can be nice for a quick
17295 look at those images, but it does not reflect what exported files will look
17296 like.
17297 When REFRESH is set, refresh existing images between BEG and END.
17298 This will create new image displays only if necessary.
17299 BEG and END default to the buffer boundaries."
17300 (interactive "P")
17301 (unless refresh
17302 (org-remove-inline-images)
17303 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17304 (save-excursion
17305 (save-restriction
17306 (widen)
17307 (setq beg (or beg (point-min)) end (or end (point-max)))
17308 (goto-char beg)
17309 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17310 (substring (org-image-file-name-regexp) 0 -2)
17311 "\\)\\]" (if include-linked "" "\\]")))
17312 old file ov img)
17313 (while (re-search-forward re end t)
17314 (setq old (get-char-property-and-overlay (match-beginning 1)
17315 'org-image-overlay))
17316 (setq file (expand-file-name
17317 (concat (or (match-string 3) "") (match-string 4))))
17318 (when (file-exists-p file)
17319 (if (and (car-safe old) refresh)
17320 (image-refresh (overlay-get (cdr old) 'display))
17321 (setq img (save-match-data (create-image file)))
17322 (when img
17323 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17324 (overlay-put ov 'display img)
17325 (overlay-put ov 'face 'default)
17326 (overlay-put ov 'org-image-overlay t)
17327 (overlay-put ov 'modification-hooks
17328 (list 'org-display-inline-modification-hook))
17329 (push ov org-inline-image-overlays)))))))))
17331 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17332 "Remove inline-display overlay if a corresponding region is modified."
17333 (let ((inhibit-modification-hooks t))
17334 (when (and ov after)
17335 (delete ov org-inline-image-overlays)
17336 (delete-overlay ov))))
17338 (defun org-remove-inline-images ()
17339 "Remove inline display of images."
17340 (interactive)
17341 (mapc 'delete-overlay org-inline-image-overlays)
17342 (setq org-inline-image-overlays nil))
17344 ;;;; Key bindings
17346 ;; Outline functions from `outline-mode-prefix-map'
17347 ;; that can be remapped in Org:
17348 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17349 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17350 (define-key org-mode-map [remap outline-forward-same-level]
17351 'org-forward-same-level)
17352 (define-key org-mode-map [remap outline-backward-same-level]
17353 'org-backward-same-level)
17354 (define-key org-mode-map [remap show-branches]
17355 'org-kill-note-or-show-branches)
17356 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17357 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17358 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17360 ;; Outline functions from `outline-mode-prefix-map'
17361 ;; that can not be remapped in Org:
17362 ;; - the column "key binding" shows whether the Outline function is still
17363 ;; available in Org mode on the same key that it has been bound to in
17364 ;; Outline mode:
17365 ;; - "overridden": key used for a different functionality in Org mode
17366 ;; - else: key still bound to the same Outline function in Org mode
17367 ;; | Outline function | key binding | Org replacement |
17368 ;; |------------------------------------+-------------+-----------------------|
17369 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17370 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17371 ;; | `show-children' | `C-c C-i' | visibility cycling |
17372 ;; | `hide-subtree' | overridden | visibility cycling |
17373 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17374 ;; | `hide-body' | overridden | no replacement |
17375 ;; | `show-all' | overridden | no replacement |
17376 ;; | `hide-entry' | overridden | visibility cycling |
17377 ;; | `show-entry' | overridden | no replacement |
17378 ;; | `hide-leaves' | overridden | no replacement |
17379 ;; | `hide-sublevels' | overridden | no replacement |
17380 ;; | `hide-other' | overridden | no replacement |
17381 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17382 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17384 ;; Make `C-c C-x' a prefix key
17385 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17387 ;; TAB key with modifiers
17388 (org-defkey org-mode-map "\C-i" 'org-cycle)
17389 (org-defkey org-mode-map [(tab)] 'org-cycle)
17390 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17391 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17392 ;; The following line is necessary under Suse GNU/Linux
17393 (unless (featurep 'xemacs)
17394 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17395 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17396 (define-key org-mode-map [backtab] 'org-shifttab)
17398 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17399 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17400 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17402 ;; Cursor keys with modifiers
17403 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17404 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17405 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17406 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17408 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17409 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17410 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17411 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17413 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17414 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17415 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17416 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17418 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17419 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17420 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17421 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17423 ;; Babel keys
17424 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17425 (mapc (lambda (pair)
17426 (define-key org-babel-map (car pair) (cdr pair)))
17427 org-babel-key-bindings)
17429 ;;; Extra keys for tty access.
17430 ;; We only set them when really needed because otherwise the
17431 ;; menus don't show the simple keys
17433 (when (or org-use-extra-keys
17434 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17435 (not window-system))
17436 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17437 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17438 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17439 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17440 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17441 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17442 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17443 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17444 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17445 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17446 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17447 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17448 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17449 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17450 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17451 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17452 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17453 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17454 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17455 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17456 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17457 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17458 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17459 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17460 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17461 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17462 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17463 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17465 ;; All the other keys
17467 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17468 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17469 (if (boundp 'narrow-map)
17470 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17471 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17472 (if (boundp 'narrow-map)
17473 (org-defkey narrow-map "b" 'org-narrow-to-block)
17474 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17475 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17476 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17477 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17478 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17479 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17480 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17481 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17482 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17483 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17484 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17485 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17486 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17487 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17488 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17489 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17490 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17491 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17492 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17493 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17494 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17495 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17496 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17497 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17498 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17499 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17500 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17501 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17502 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17503 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17504 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17505 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17506 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17507 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17508 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17509 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17510 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17511 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17512 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17513 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17514 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17515 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17516 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17517 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17518 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17519 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17520 (org-defkey org-mode-map "\C-c^" 'org-sort)
17521 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17522 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17523 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17524 (org-defkey org-mode-map "\C-m" 'org-return)
17525 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17526 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17527 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17528 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17529 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17530 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17531 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17532 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17533 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17534 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17535 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17536 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17537 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17538 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17539 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17540 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17541 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17542 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17543 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17544 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17545 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17546 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17547 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17549 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17550 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17551 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17552 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17554 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17555 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17556 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17557 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17558 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17559 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17560 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17561 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17562 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17563 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17564 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17565 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17566 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17567 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17568 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17569 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17570 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17571 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17573 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17574 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17575 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17576 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17577 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17579 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17581 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17583 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17584 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17586 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17589 (when (featurep 'xemacs)
17590 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17593 (defconst org-speed-commands-default
17595 ("Outline Navigation")
17596 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17597 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17598 ("f" . (org-speed-move-safe 'org-forward-same-level))
17599 ("b" . (org-speed-move-safe 'org-backward-same-level))
17600 ("u" . (org-speed-move-safe 'outline-up-heading))
17601 ("j" . org-goto)
17602 ("g" . (org-refile t))
17603 ("Outline Visibility")
17604 ("c" . org-cycle)
17605 ("C" . org-shifttab)
17606 (" " . org-display-outline-path)
17607 ("Outline Structure Editing")
17608 ("U" . org-shiftmetaup)
17609 ("D" . org-shiftmetadown)
17610 ("r" . org-metaright)
17611 ("l" . org-metaleft)
17612 ("R" . org-shiftmetaright)
17613 ("L" . org-shiftmetaleft)
17614 ("i" . (progn (forward-char 1) (call-interactively
17615 'org-insert-heading-respect-content)))
17616 ("^" . org-sort)
17617 ("w" . org-refile)
17618 ("a" . org-archive-subtree-default-with-confirmation)
17619 ("." . org-mark-subtree)
17620 ("Clock Commands")
17621 ("I" . org-clock-in)
17622 ("O" . org-clock-out)
17623 ("Meta Data Editing")
17624 ("t" . org-todo)
17625 ("0" . (org-priority ?\ ))
17626 ("1" . (org-priority ?A))
17627 ("2" . (org-priority ?B))
17628 ("3" . (org-priority ?C))
17629 (";" . org-set-tags-command)
17630 ("e" . org-set-effort)
17631 ("Agenda Views etc")
17632 ("v" . org-agenda)
17633 ("/" . org-sparse-tree)
17634 ("Misc")
17635 ("o" . org-open-at-point)
17636 ("?" . org-speed-command-help)
17637 ("<" . (org-agenda-set-restriction-lock 'subtree))
17638 (">" . (org-agenda-remove-restriction-lock))
17640 "The default speed commands.")
17642 (defun org-print-speed-command (e)
17643 (if (> (length (car e)) 1)
17644 (progn
17645 (princ "\n")
17646 (princ (car e))
17647 (princ "\n")
17648 (princ (make-string (length (car e)) ?-))
17649 (princ "\n"))
17650 (princ (car e))
17651 (princ " ")
17652 (if (symbolp (cdr e))
17653 (princ (symbol-name (cdr e)))
17654 (prin1 (cdr e)))
17655 (princ "\n")))
17657 (defun org-speed-command-help ()
17658 "Show the available speed commands."
17659 (interactive)
17660 (if (not org-use-speed-commands)
17661 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17662 (with-output-to-temp-buffer "*Help*"
17663 (princ "User-defined Speed commands\n===========================\n")
17664 (mapc 'org-print-speed-command org-speed-commands-user)
17665 (princ "\n")
17666 (princ "Built-in Speed commands\n=======================\n")
17667 (mapc 'org-print-speed-command org-speed-commands-default))
17668 (with-current-buffer "*Help*"
17669 (setq truncate-lines t))))
17671 (defun org-speed-move-safe (cmd)
17672 "Execute CMD, but make sure that the cursor always ends up in a headline.
17673 If not, return to the original position and throw an error."
17674 (interactive)
17675 (let ((pos (point)))
17676 (call-interactively cmd)
17677 (unless (and (bolp) (org-at-heading-p))
17678 (goto-char pos)
17679 (error "Boundary reached while executing %s" cmd))))
17681 (defvar org-self-insert-command-undo-counter 0)
17683 (defvar org-table-auto-blank-field) ; defined in org-table.el
17684 (defvar org-speed-command nil)
17686 (defun org-speed-command-default-hook (keys)
17687 "Hook for activating single-letter speed commands.
17688 `org-speed-commands-default' specifies a minimal command set.
17689 Use `org-speed-commands-user' for further customization."
17690 (when (or (and (bolp) (looking-at org-outline-regexp))
17691 (and (functionp org-use-speed-commands)
17692 (funcall org-use-speed-commands)))
17693 (cdr (assoc keys (append org-speed-commands-user
17694 org-speed-commands-default)))))
17696 (defun org-babel-speed-command-hook (keys)
17697 "Hook for activating single-letter code block commands."
17698 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17699 (cdr (assoc keys org-babel-key-bindings))))
17701 (defcustom org-speed-command-hook
17702 '(org-speed-command-default-hook org-babel-speed-command-hook)
17703 "Hook for activating speed commands at strategic locations.
17704 Hook functions are called in sequence until a valid handler is
17705 found.
17707 Each hook takes a single argument, a user-pressed command key
17708 which is also a `self-insert-command' from the global map.
17710 Within the hook, examine the cursor position and the command key
17711 and return nil or a valid handler as appropriate. Handler could
17712 be one of an interactive command, a function, or a form.
17714 Set `org-use-speed-commands' to non-nil value to enable this
17715 hook. The default setting is `org-speed-command-default-hook'."
17716 :group 'org-structure
17717 :version "24.1"
17718 :type 'hook)
17720 (defun org-self-insert-command (N)
17721 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17722 If the cursor is in a table looking at whitespace, the whitespace is
17723 overwritten, and the table is not marked as requiring realignment."
17724 (interactive "p")
17725 (org-check-before-invisible-edit 'insert)
17726 (cond
17727 ((and org-use-speed-commands
17728 (setq org-speed-command
17729 (run-hook-with-args-until-success
17730 'org-speed-command-hook (this-command-keys))))
17731 (cond
17732 ((commandp org-speed-command)
17733 (setq this-command org-speed-command)
17734 (call-interactively org-speed-command))
17735 ((functionp org-speed-command)
17736 (funcall org-speed-command))
17737 ((and org-speed-command (listp org-speed-command))
17738 (eval org-speed-command))
17739 (t (let (org-use-speed-commands)
17740 (call-interactively 'org-self-insert-command)))))
17741 ((and
17742 (org-table-p)
17743 (progn
17744 ;; check if we blank the field, and if that triggers align
17745 (and (featurep 'org-table) org-table-auto-blank-field
17746 (member last-command
17747 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17748 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17749 ;; got extra space, this field does not determine column width
17750 (let (org-table-may-need-update) (org-table-blank-field))
17751 ;; no extra space, this field may determine column width
17752 (org-table-blank-field)))
17754 (eq N 1)
17755 (looking-at "[^|\n]* |"))
17756 (let (org-table-may-need-update)
17757 (goto-char (1- (match-end 0)))
17758 (backward-delete-char 1)
17759 (goto-char (match-beginning 0))
17760 (self-insert-command N)))
17762 (setq org-table-may-need-update t)
17763 (self-insert-command N)
17764 (org-fix-tags-on-the-fly)
17765 (if org-self-insert-cluster-for-undo
17766 (if (not (eq last-command 'org-self-insert-command))
17767 (setq org-self-insert-command-undo-counter 1)
17768 (if (>= org-self-insert-command-undo-counter 20)
17769 (setq org-self-insert-command-undo-counter 1)
17770 (and (> org-self-insert-command-undo-counter 0)
17771 buffer-undo-list (listp buffer-undo-list)
17772 (not (cadr buffer-undo-list)) ; remove nil entry
17773 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17774 (setq org-self-insert-command-undo-counter
17775 (1+ org-self-insert-command-undo-counter))))))))
17777 (defun org-check-before-invisible-edit (kind)
17778 "Check is editing if kind KIND would be dangerous with invisible text around.
17779 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17780 ;; First, try to get out of here as quickly as possible, to reduce overhead
17781 (if (and org-catch-invisible-edits
17782 (or (not (boundp 'visible-mode)) (not visible-mode))
17783 (or (get-char-property (point) 'invisible)
17784 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17785 ;; OK, we need to take a closer look
17786 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17787 (invisible-before-point (if (bobp) nil (get-char-property
17788 (1- (point)) 'invisible)))
17789 (border-and-ok-direction
17791 ;; Check if we are acting predictably before invisible text
17792 (and invisible-at-point (not invisible-before-point)
17793 (memq kind '(insert delete-backward)))
17794 ;; Check if we are acting predictably after invisible text
17795 ;; This works not well, and I have turned it off. It seems
17796 ;; better to always show and stop after invisible text.
17797 ;; (and (not invisible-at-point) invisible-before-point
17798 ;; (memq kind '(insert delete)))
17801 (when (or (memq invisible-at-point '(outline org-hide-block))
17802 (memq invisible-before-point '(outline org-hide-block)))
17803 (if (eq org-catch-invisible-edits 'error)
17804 (error "Editing in invisible areas is prohibited - make visible first"))
17805 ;; Make the area visible
17806 (save-excursion
17807 (if invisible-before-point
17808 (goto-char (previous-single-char-property-change
17809 (point) 'invisible)))
17810 (org-cycle))
17811 (cond
17812 ((eq org-catch-invisible-edits 'show)
17813 ;; That's it, we do the edit after showing
17814 (message
17815 "Unfolding invisible region around point before editing")
17816 (sit-for 1))
17817 ((and (eq org-catch-invisible-edits 'smart)
17818 border-and-ok-direction)
17819 (message "Unfolding invisible region around point before editing"))
17821 ;; Don't do the edit, make the user repeat it in full visibility
17822 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17824 (defun org-fix-tags-on-the-fly ()
17825 (when (and (equal (char-after (point-at-bol)) ?*)
17826 (org-at-heading-p))
17827 (org-align-tags-here org-tags-column)))
17829 (defun org-delete-backward-char (N)
17830 "Like `delete-backward-char', insert whitespace at field end in tables.
17831 When deleting backwards, in tables this function will insert whitespace in
17832 front of the next \"|\" separator, to keep the table aligned. The table will
17833 still be marked for re-alignment if the field did fill the entire column,
17834 because, in this case the deletion might narrow the column."
17835 (interactive "p")
17836 (org-check-before-invisible-edit 'delete-backward)
17837 (if (and (org-table-p)
17838 (eq N 1)
17839 (string-match "|" (buffer-substring (point-at-bol) (point)))
17840 (looking-at ".*?|"))
17841 (let ((pos (point))
17842 (noalign (looking-at "[^|\n\r]* |"))
17843 (c org-table-may-need-update))
17844 (backward-delete-char N)
17845 (if (not overwrite-mode)
17846 (progn
17847 (skip-chars-forward "^|")
17848 (insert " ")
17849 (goto-char (1- pos))))
17850 ;; noalign: if there were two spaces at the end, this field
17851 ;; does not determine the width of the column.
17852 (if noalign (setq org-table-may-need-update c)))
17853 (backward-delete-char N)
17854 (org-fix-tags-on-the-fly)))
17856 (defun org-delete-char (N)
17857 "Like `delete-char', but insert whitespace at field end in tables.
17858 When deleting characters, in tables this function will insert whitespace in
17859 front of the next \"|\" separator, to keep the table aligned. The table will
17860 still be marked for re-alignment if the field did fill the entire column,
17861 because, in this case the deletion might narrow the column."
17862 (interactive "p")
17863 (org-check-before-invisible-edit 'delete)
17864 (if (and (org-table-p)
17865 (not (bolp))
17866 (not (= (char-after) ?|))
17867 (eq N 1))
17868 (if (looking-at ".*?|")
17869 (let ((pos (point))
17870 (noalign (looking-at "[^|\n\r]* |"))
17871 (c org-table-may-need-update))
17872 (replace-match (concat
17873 (substring (match-string 0) 1 -1)
17874 " |"))
17875 (goto-char pos)
17876 ;; noalign: if there were two spaces at the end, this field
17877 ;; does not determine the width of the column.
17878 (if noalign (setq org-table-may-need-update c)))
17879 (delete-char N))
17880 (delete-char N)
17881 (org-fix-tags-on-the-fly)))
17883 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17884 (put 'org-self-insert-command 'delete-selection t)
17885 (put 'orgtbl-self-insert-command 'delete-selection t)
17886 (put 'org-delete-char 'delete-selection 'supersede)
17887 (put 'org-delete-backward-char 'delete-selection 'supersede)
17888 (put 'org-yank 'delete-selection 'yank)
17890 ;; Make `flyspell-mode' delay after some commands
17891 (put 'org-self-insert-command 'flyspell-delayed t)
17892 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17893 (put 'org-delete-char 'flyspell-delayed t)
17894 (put 'org-delete-backward-char 'flyspell-delayed t)
17896 ;; Make pabbrev-mode expand after org-mode commands
17897 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17898 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17900 ;; How to do this: Measure non-white length of current string
17901 ;; If equal to column width, we should realign.
17903 (defun org-remap (map &rest commands)
17904 "In MAP, remap the functions given in COMMANDS.
17905 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17906 (let (new old)
17907 (while commands
17908 (setq old (pop commands) new (pop commands))
17909 (if (fboundp 'command-remapping)
17910 (org-defkey map (vector 'remap old) new)
17911 (substitute-key-definition old new map global-map)))))
17913 (when (eq org-enable-table-editor 'optimized)
17914 ;; If the user wants maximum table support, we need to hijack
17915 ;; some standard editing functions
17916 (org-remap org-mode-map
17917 'self-insert-command 'org-self-insert-command
17918 'delete-char 'org-delete-char
17919 'delete-backward-char 'org-delete-backward-char)
17920 (org-defkey org-mode-map "|" 'org-force-self-insert))
17922 (defvar org-ctrl-c-ctrl-c-hook nil
17923 "Hook for functions attaching themselves to `C-c C-c'.
17925 This can be used to add additional functionality to the C-c C-c
17926 key which executes context-dependent commands. This hook is run
17927 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17928 run after the last test.
17930 Each function will be called with no arguments. The function
17931 must check if the context is appropriate for it to act. If yes,
17932 it should do its thing and then return a non-nil value. If the
17933 context is wrong, just do nothing and return nil.")
17935 (defvar org-ctrl-c-ctrl-c-final-hook nil
17936 "Hook for functions attaching themselves to `C-c C-c'.
17938 This can be used to add additional functionality to the C-c C-c
17939 key which executes context-dependent commands. This hook is run
17940 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17941 before the first test.
17943 Each function will be called with no arguments. The function
17944 must check if the context is appropriate for it to act. If yes,
17945 it should do its thing and then return a non-nil value. If the
17946 context is wrong, just do nothing and return nil.")
17948 (defvar org-tab-first-hook nil
17949 "Hook for functions to attach themselves to TAB.
17950 See `org-ctrl-c-ctrl-c-hook' for more information.
17951 This hook runs as the first action when TAB is pressed, even before
17952 `org-cycle' messes around with the `outline-regexp' to cater for
17953 inline tasks and plain list item folding.
17954 If any function in this hook returns t, any other actions that
17955 would have been caused by TAB (such as table field motion or visibility
17956 cycling) will not occur.")
17958 (defvar org-tab-after-check-for-table-hook nil
17959 "Hook for functions to attach themselves to TAB.
17960 See `org-ctrl-c-ctrl-c-hook' for more information.
17961 This hook runs after it has been established that the cursor is not in a
17962 table, but before checking if the cursor is in a headline or if global cycling
17963 should be done.
17964 If any function in this hook returns t, not other actions like visibility
17965 cycling will be done.")
17967 (defvar org-tab-after-check-for-cycling-hook nil
17968 "Hook for functions to attach themselves to TAB.
17969 See `org-ctrl-c-ctrl-c-hook' for more information.
17970 This hook runs after it has been established that not table field motion and
17971 not visibility should be done because of current context. This is probably
17972 the place where a package like yasnippets can hook in.")
17974 (defvar org-tab-before-tab-emulation-hook nil
17975 "Hook for functions to attach themselves to TAB.
17976 See `org-ctrl-c-ctrl-c-hook' for more information.
17977 This hook runs after every other options for TAB have been exhausted, but
17978 before indentation and \t insertion takes place.")
17980 (defvar org-metaleft-hook nil
17981 "Hook for functions attaching themselves to `M-left'.
17982 See `org-ctrl-c-ctrl-c-hook' for more information.")
17983 (defvar org-metaright-hook nil
17984 "Hook for functions attaching themselves to `M-right'.
17985 See `org-ctrl-c-ctrl-c-hook' for more information.")
17986 (defvar org-metaup-hook nil
17987 "Hook for functions attaching themselves to `M-up'.
17988 See `org-ctrl-c-ctrl-c-hook' for more information.")
17989 (defvar org-metadown-hook nil
17990 "Hook for functions attaching themselves to `M-down'.
17991 See `org-ctrl-c-ctrl-c-hook' for more information.")
17992 (defvar org-shiftmetaleft-hook nil
17993 "Hook for functions attaching themselves to `M-S-left'.
17994 See `org-ctrl-c-ctrl-c-hook' for more information.")
17995 (defvar org-shiftmetaright-hook nil
17996 "Hook for functions attaching themselves to `M-S-right'.
17997 See `org-ctrl-c-ctrl-c-hook' for more information.")
17998 (defvar org-shiftmetaup-hook nil
17999 "Hook for functions attaching themselves to `M-S-up'.
18000 See `org-ctrl-c-ctrl-c-hook' for more information.")
18001 (defvar org-shiftmetadown-hook nil
18002 "Hook for functions attaching themselves to `M-S-down'.
18003 See `org-ctrl-c-ctrl-c-hook' for more information.")
18004 (defvar org-metareturn-hook nil
18005 "Hook for functions attaching themselves to `M-RET'.
18006 See `org-ctrl-c-ctrl-c-hook' for more information.")
18007 (defvar org-shiftup-hook nil
18008 "Hook for functions attaching themselves to `S-up'.
18009 See `org-ctrl-c-ctrl-c-hook' for more information.")
18010 (defvar org-shiftup-final-hook nil
18011 "Hook for functions attaching themselves to `S-up'.
18012 This one runs after all other options except shift-select have been excluded.
18013 See `org-ctrl-c-ctrl-c-hook' for more information.")
18014 (defvar org-shiftdown-hook nil
18015 "Hook for functions attaching themselves to `S-down'.
18016 See `org-ctrl-c-ctrl-c-hook' for more information.")
18017 (defvar org-shiftdown-final-hook nil
18018 "Hook for functions attaching themselves to `S-down'.
18019 This one runs after all other options except shift-select have been excluded.
18020 See `org-ctrl-c-ctrl-c-hook' for more information.")
18021 (defvar org-shiftleft-hook nil
18022 "Hook for functions attaching themselves to `S-left'.
18023 See `org-ctrl-c-ctrl-c-hook' for more information.")
18024 (defvar org-shiftleft-final-hook nil
18025 "Hook for functions attaching themselves to `S-left'.
18026 This one runs after all other options except shift-select have been excluded.
18027 See `org-ctrl-c-ctrl-c-hook' for more information.")
18028 (defvar org-shiftright-hook nil
18029 "Hook for functions attaching themselves to `S-right'.
18030 See `org-ctrl-c-ctrl-c-hook' for more information.")
18031 (defvar org-shiftright-final-hook nil
18032 "Hook for functions attaching themselves to `S-right'.
18033 This one runs after all other options except shift-select have been excluded.
18034 See `org-ctrl-c-ctrl-c-hook' for more information.")
18036 (defun org-modifier-cursor-error ()
18037 "Throw an error, a modified cursor command was applied in wrong context."
18038 (error "This command is active in special context like tables, headlines or items"))
18040 (defun org-shiftselect-error ()
18041 "Throw an error because Shift-Cursor command was applied in wrong context."
18042 (if (and (boundp 'shift-select-mode) shift-select-mode)
18043 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18044 (error "This command works only in special context like headlines or timestamps")))
18046 (defun org-call-for-shift-select (cmd)
18047 (let ((this-command-keys-shift-translated t))
18048 (call-interactively cmd)))
18050 (defun org-shifttab (&optional arg)
18051 "Global visibility cycling or move to previous table field.
18052 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18053 on context.
18054 See the individual commands for more information."
18055 (interactive "P")
18056 (cond
18057 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18058 ((integerp arg)
18059 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18060 (message "Content view to level: %d" arg)
18061 (org-content (prefix-numeric-value arg2))
18062 (setq org-cycle-global-status 'overview)))
18063 (t (call-interactively 'org-global-cycle))))
18065 (defun org-shiftmetaleft ()
18066 "Promote subtree or delete table column.
18067 Calls `org-promote-subtree', `org-outdent-item',
18068 or `org-table-delete-column', depending on context.
18069 See the individual commands for more information."
18070 (interactive)
18071 (cond
18072 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18073 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18074 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18075 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
18076 (t (org-modifier-cursor-error))))
18078 (defun org-shiftmetaright ()
18079 "Demote subtree or insert table column.
18080 Calls `org-demote-subtree', `org-indent-item',
18081 or `org-table-insert-column', depending on context.
18082 See the individual commands for more information."
18083 (interactive)
18084 (cond
18085 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18086 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18087 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18088 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
18089 (t (org-modifier-cursor-error))))
18091 (defun org-shiftmetaup (&optional arg)
18092 "Move subtree up or kill table row.
18093 Calls `org-move-subtree-up' or `org-table-kill-row' or
18094 `org-move-item-up' depending on context. See the individual commands
18095 for more information."
18096 (interactive "P")
18097 (cond
18098 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18099 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18100 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18101 ((org-at-item-p) (call-interactively 'org-move-item-up))
18102 (t (org-modifier-cursor-error))))
18104 (defun org-shiftmetadown (&optional arg)
18105 "Move subtree down or insert table row.
18106 Calls `org-move-subtree-down' or `org-table-insert-row' or
18107 `org-move-item-down', depending on context. See the individual
18108 commands for more information."
18109 (interactive "P")
18110 (cond
18111 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18112 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18113 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18114 ((org-at-item-p) (call-interactively 'org-move-item-down))
18115 (t (org-modifier-cursor-error))))
18117 (defsubst org-hidden-tree-error ()
18118 (error
18119 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18121 (defun org-metaleft (&optional arg)
18122 "Promote heading or move table column to left.
18123 Calls `org-do-promote' or `org-table-move-column', depending on context.
18124 With no specific context, calls the Emacs default `backward-word'.
18125 See the individual commands for more information."
18126 (interactive "P")
18127 (cond
18128 ((run-hook-with-args-until-success 'org-metaleft-hook))
18129 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18130 ((org-with-limited-levels
18131 (or (org-at-heading-p)
18132 (and (org-region-active-p)
18133 (save-excursion
18134 (goto-char (region-beginning))
18135 (org-at-heading-p)))))
18136 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18137 (call-interactively 'org-do-promote))
18138 ;; At an inline task.
18139 ((org-at-heading-p)
18140 (call-interactively 'org-inlinetask-promote))
18141 ((or (org-at-item-p)
18142 (and (org-region-active-p)
18143 (save-excursion
18144 (goto-char (region-beginning))
18145 (org-at-item-p))))
18146 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18147 (call-interactively 'org-outdent-item))
18148 (t (call-interactively 'backward-word))))
18150 (defun org-metaright (&optional arg)
18151 "Demote a subtree, a list item or move table column to right.
18152 In front of a drawer or a block keyword, indent it correctly.
18153 With no specific context, calls the Emacs default `forward-word'.
18154 See the individual commands for more information."
18155 (interactive "P")
18156 (cond
18157 ((run-hook-with-args-until-success 'org-metaright-hook))
18158 ((org-at-table-p) (call-interactively 'org-table-move-column))
18159 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18160 ((org-at-block-p) (call-interactively 'org-indent-block))
18161 ((org-with-limited-levels
18162 (or (org-at-heading-p)
18163 (and (org-region-active-p)
18164 (save-excursion
18165 (goto-char (region-beginning))
18166 (org-at-heading-p)))))
18167 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18168 (call-interactively 'org-do-demote))
18169 ;; At an inline task.
18170 ((org-at-heading-p)
18171 (call-interactively 'org-inlinetask-demote))
18172 ((or (org-at-item-p)
18173 (and (org-region-active-p)
18174 (save-excursion
18175 (goto-char (region-beginning))
18176 (org-at-item-p))))
18177 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18178 (call-interactively 'org-indent-item))
18179 (t (call-interactively 'forward-word))))
18181 (defun org-check-for-hidden (what)
18182 "Check if there are hidden headlines/items in the current visual line.
18183 WHAT can be either `headlines' or `items'. If the current line is
18184 an outline or item heading and it has a folded subtree below it,
18185 this function returns t, nil otherwise."
18186 (let ((re (cond
18187 ((eq what 'headlines) org-outline-regexp-bol)
18188 ((eq what 'items) (org-item-beginning-re))
18189 (t (error "This should not happen"))))
18190 beg end)
18191 (save-excursion
18192 (catch 'exit
18193 (unless (org-region-active-p)
18194 (setq beg (point-at-bol))
18195 (beginning-of-line 2)
18196 (while (and (not (eobp)) ;; this is like `next-line'
18197 (get-char-property (1- (point)) 'invisible))
18198 (beginning-of-line 2))
18199 (setq end (point))
18200 (goto-char beg)
18201 (goto-char (point-at-eol))
18202 (setq end (max end (point)))
18203 (while (re-search-forward re end t)
18204 (if (get-char-property (match-beginning 0) 'invisible)
18205 (throw 'exit t))))
18206 nil))))
18208 (defun org-metaup (&optional arg)
18209 "Move subtree up or move table row up.
18210 Calls `org-move-subtree-up' or `org-table-move-row' or
18211 `org-move-item-up', depending on context. See the individual commands
18212 for more information."
18213 (interactive "P")
18214 (cond
18215 ((run-hook-with-args-until-success 'org-metaup-hook))
18216 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18217 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18218 ((org-at-item-p) (call-interactively 'org-move-item-up))
18219 (t (transpose-lines 1) (beginning-of-line -1))))
18221 (defun org-metadown (&optional arg)
18222 "Move subtree down or move table row down.
18223 Calls `org-move-subtree-down' or `org-table-move-row' or
18224 `org-move-item-down', depending on context. See the individual
18225 commands for more information."
18226 (interactive "P")
18227 (cond
18228 ((run-hook-with-args-until-success 'org-metadown-hook))
18229 ((org-at-table-p) (call-interactively 'org-table-move-row))
18230 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18231 ((org-at-item-p) (call-interactively 'org-move-item-down))
18232 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18234 (defun org-shiftup (&optional arg)
18235 "Increase item in timestamp or increase priority of current headline.
18236 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18237 depending on context. See the individual commands for more information."
18238 (interactive "P")
18239 (cond
18240 ((run-hook-with-args-until-success 'org-shiftup-hook))
18241 ((and org-support-shift-select (org-region-active-p))
18242 (org-call-for-shift-select 'previous-line))
18243 ((org-at-timestamp-p t)
18244 (call-interactively (if org-edit-timestamp-down-means-later
18245 'org-timestamp-down 'org-timestamp-up)))
18246 ((and (not (eq org-support-shift-select 'always))
18247 org-enable-priority-commands
18248 (org-at-heading-p))
18249 (call-interactively 'org-priority-up))
18250 ((and (not org-support-shift-select) (org-at-item-p))
18251 (call-interactively 'org-previous-item))
18252 ((org-clocktable-try-shift 'up arg))
18253 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18254 (org-support-shift-select
18255 (org-call-for-shift-select 'previous-line))
18256 (t (org-shiftselect-error))))
18258 (defun org-shiftdown (&optional arg)
18259 "Decrease item in timestamp or decrease priority of current headline.
18260 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18261 depending on context. See the individual commands for more information."
18262 (interactive "P")
18263 (cond
18264 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18265 ((and org-support-shift-select (org-region-active-p))
18266 (org-call-for-shift-select 'next-line))
18267 ((org-at-timestamp-p t)
18268 (call-interactively (if org-edit-timestamp-down-means-later
18269 'org-timestamp-up 'org-timestamp-down)))
18270 ((and (not (eq org-support-shift-select 'always))
18271 org-enable-priority-commands
18272 (org-at-heading-p))
18273 (call-interactively 'org-priority-down))
18274 ((and (not org-support-shift-select) (org-at-item-p))
18275 (call-interactively 'org-next-item))
18276 ((org-clocktable-try-shift 'down arg))
18277 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18278 (org-support-shift-select
18279 (org-call-for-shift-select 'next-line))
18280 (t (org-shiftselect-error))))
18282 (defun org-shiftright (&optional arg)
18283 "Cycle the thing at point or in the current line, depending on context.
18284 Depending on context, this does one of the following:
18286 - switch a timestamp at point one day into the future
18287 - on a headline, switch to the next TODO keyword.
18288 - on an item, switch entire list to the next bullet type
18289 - on a property line, switch to the next allowed value
18290 - on a clocktable definition line, move time block into the future"
18291 (interactive "P")
18292 (cond
18293 ((run-hook-with-args-until-success 'org-shiftright-hook))
18294 ((and org-support-shift-select (org-region-active-p))
18295 (org-call-for-shift-select 'forward-char))
18296 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18297 ((and (not (eq org-support-shift-select 'always))
18298 (org-at-heading-p))
18299 (let ((org-inhibit-logging
18300 (not org-treat-S-cursor-todo-selection-as-state-change))
18301 (org-inhibit-blocking
18302 (not org-treat-S-cursor-todo-selection-as-state-change)))
18303 (org-call-with-arg 'org-todo 'right)))
18304 ((or (and org-support-shift-select
18305 (not (eq org-support-shift-select 'always))
18306 (org-at-item-bullet-p))
18307 (and (not org-support-shift-select) (org-at-item-p)))
18308 (org-call-with-arg 'org-cycle-list-bullet nil))
18309 ((and (not (eq org-support-shift-select 'always))
18310 (org-at-property-p))
18311 (call-interactively 'org-property-next-allowed-value))
18312 ((org-clocktable-try-shift 'right arg))
18313 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18314 (org-support-shift-select
18315 (org-call-for-shift-select 'forward-char))
18316 (t (org-shiftselect-error))))
18318 (defun org-shiftleft (&optional arg)
18319 "Cycle the thing at point or in the current line, depending on context.
18320 Depending on context, this does one of the following:
18322 - switch a timestamp at point one day into the past
18323 - on a headline, switch to the previous TODO keyword.
18324 - on an item, switch entire list to the previous bullet type
18325 - on a property line, switch to the previous allowed value
18326 - on a clocktable definition line, move time block into the past"
18327 (interactive "P")
18328 (cond
18329 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18330 ((and org-support-shift-select (org-region-active-p))
18331 (org-call-for-shift-select 'backward-char))
18332 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18333 ((and (not (eq org-support-shift-select 'always))
18334 (org-at-heading-p))
18335 (let ((org-inhibit-logging
18336 (not org-treat-S-cursor-todo-selection-as-state-change))
18337 (org-inhibit-blocking
18338 (not org-treat-S-cursor-todo-selection-as-state-change)))
18339 (org-call-with-arg 'org-todo 'left)))
18340 ((or (and org-support-shift-select
18341 (not (eq org-support-shift-select 'always))
18342 (org-at-item-bullet-p))
18343 (and (not org-support-shift-select) (org-at-item-p)))
18344 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18345 ((and (not (eq org-support-shift-select 'always))
18346 (org-at-property-p))
18347 (call-interactively 'org-property-previous-allowed-value))
18348 ((org-clocktable-try-shift 'left arg))
18349 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18350 (org-support-shift-select
18351 (org-call-for-shift-select 'backward-char))
18352 (t (org-shiftselect-error))))
18354 (defun org-shiftcontrolright ()
18355 "Switch to next TODO set."
18356 (interactive)
18357 (cond
18358 ((and org-support-shift-select (org-region-active-p))
18359 (org-call-for-shift-select 'forward-word))
18360 ((and (not (eq org-support-shift-select 'always))
18361 (org-at-heading-p))
18362 (org-call-with-arg 'org-todo 'nextset))
18363 (org-support-shift-select
18364 (org-call-for-shift-select 'forward-word))
18365 (t (org-shiftselect-error))))
18367 (defun org-shiftcontrolleft ()
18368 "Switch to previous TODO set."
18369 (interactive)
18370 (cond
18371 ((and org-support-shift-select (org-region-active-p))
18372 (org-call-for-shift-select 'backward-word))
18373 ((and (not (eq org-support-shift-select 'always))
18374 (org-at-heading-p))
18375 (org-call-with-arg 'org-todo 'previousset))
18376 (org-support-shift-select
18377 (org-call-for-shift-select 'backward-word))
18378 (t (org-shiftselect-error))))
18380 (defun org-shiftcontrolup ()
18381 "Change timestamps synchronously up in CLOCK log lines."
18382 (interactive)
18383 (cond ((and (not org-support-shift-select)
18384 (org-at-clock-log-p)
18385 (org-at-timestamp-p t))
18386 (org-clock-timestamps-up))
18387 (t (org-shiftselect-error))))
18389 (defun org-shiftcontroldown ()
18390 "Change timestamps synchronously down in CLOCK log lines."
18391 (interactive)
18392 (cond ((and (not org-support-shift-select)
18393 (org-at-clock-log-p)
18394 (org-at-timestamp-p t))
18395 (org-clock-timestamps-down))
18396 (t (org-shiftselect-error))))
18398 (defun org-ctrl-c-ret ()
18399 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18400 (interactive)
18401 (cond
18402 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18403 (t (call-interactively 'org-insert-heading))))
18405 (defun org-find-visible ()
18406 (let ((s (point)))
18407 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18408 (get-char-property s 'invisible)))
18410 (defun org-find-invisible ()
18411 (let ((s (point)))
18412 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18413 (not (get-char-property s 'invisible))))
18416 (defun org-copy-visible (beg end)
18417 "Copy the visible parts of the region."
18418 (interactive "r")
18419 (let (snippets s)
18420 (save-excursion
18421 (save-restriction
18422 (narrow-to-region beg end)
18423 (setq s (goto-char (point-min)))
18424 (while (not (= (point) (point-max)))
18425 (goto-char (org-find-invisible))
18426 (push (buffer-substring s (point)) snippets)
18427 (setq s (goto-char (org-find-visible))))))
18428 (kill-new (apply 'concat (nreverse snippets)))))
18430 (defun org-copy-special ()
18431 "Copy region in table or copy current subtree.
18432 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18433 See the individual commands for more information."
18434 (interactive)
18435 (call-interactively
18436 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18438 (defun org-cut-special ()
18439 "Cut region in table or cut current subtree.
18440 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18441 See the individual commands for more information."
18442 (interactive)
18443 (call-interactively
18444 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18446 (defun org-paste-special (arg)
18447 "Paste rectangular region into table, or past subtree relative to level.
18448 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18449 See the individual commands for more information."
18450 (interactive "P")
18451 (if (org-at-table-p)
18452 (org-table-paste-rectangle)
18453 (org-paste-subtree arg)))
18455 (defun org-edit-special (&optional arg)
18456 "Call a special editor for the stuff at point.
18457 When at a table, call the formula editor with `org-table-edit-formulas'.
18458 When at the first line of an src example, call `org-edit-src-code'.
18459 When in an #+include line, visit the include file. Otherwise call
18460 `ffap' to visit the file at point."
18461 (interactive)
18462 ;; possibly prep session before editing source
18463 (when arg
18464 (let* ((info (org-babel-get-src-block-info))
18465 (lang (nth 0 info))
18466 (params (nth 2 info))
18467 (session (cdr (assoc :session params))))
18468 (when (and info session) ;; we are in a source-code block with a session
18469 (funcall
18470 (intern (concat "org-babel-prep-session:" lang)) session params))))
18471 (cond ;; proceed with `org-edit-special'
18472 ((save-excursion
18473 (beginning-of-line 1)
18474 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18475 (find-file (org-trim (match-string 1))))
18476 ((org-edit-src-code))
18477 ((org-edit-fixed-width-region))
18478 ((org-at-table.el-p)
18479 (org-edit-src-code))
18480 ((or (org-at-table-p)
18481 (save-excursion
18482 (beginning-of-line 1)
18483 (looking-at "[ \t]*#\\+TBLFM:")))
18484 (call-interactively 'org-table-edit-formulas))
18485 (t (call-interactively 'ffap))))
18487 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18488 (defun org-ctrl-c-ctrl-c (&optional arg)
18489 "Set tags in headline, or update according to changed information at point.
18491 This command does many different things, depending on context:
18493 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18494 this is what we do.
18496 - If the cursor is on a statistics cookie, update it.
18498 - If the cursor is in a headline, prompt for tags and insert them
18499 into the current line, aligned to `org-tags-column'. When called
18500 with prefix arg, realign all tags in the current buffer.
18502 - If the cursor is in one of the special #+KEYWORD lines, this
18503 triggers scanning the buffer for these lines and updating the
18504 information.
18506 - If the cursor is inside a table, realign the table. This command
18507 works even if the automatic table editor has been turned off.
18509 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18510 the entire table.
18512 - If the cursor is at a footnote reference or definition, jump to
18513 the corresponding definition or references, respectively.
18515 - If the cursor is a the beginning of a dynamic block, update it.
18517 - If the current buffer is a capture buffer, close note and file it.
18519 - If the cursor is on a <<<target>>>, update radio targets and
18520 corresponding links in this buffer.
18522 - If the cursor is on a numbered item in a plain list, renumber the
18523 ordered list.
18525 - If the cursor is on a checkbox, toggle it.
18527 - If the cursor is on a code block, evaluate it. The variable
18528 `org-confirm-babel-evaluate' can be used to control prompting
18529 before code block evaluation, by default every code block
18530 evaluation requires confirmation. Code block evaluation can be
18531 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18532 (interactive "P")
18533 (let ((org-enable-table-editor t))
18534 (cond
18535 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18536 org-occur-highlights
18537 org-latex-fragment-image-overlays)
18538 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18539 (org-remove-occur-highlights)
18540 (org-remove-latex-fragment-image-overlays)
18541 (message "Temporary highlights/overlays removed from current buffer"))
18542 ((and (local-variable-p 'org-finish-function (current-buffer))
18543 (fboundp org-finish-function))
18544 (funcall org-finish-function))
18545 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18546 ((org-in-regexp org-ts-regexp-both)
18547 (org-timestamp-change 0 'day))
18548 ((or (looking-at org-property-start-re)
18549 (org-at-property-p))
18550 (call-interactively 'org-property-action))
18551 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18552 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18553 (or (org-at-heading-p) (org-at-item-p)))
18554 (call-interactively 'org-update-statistics-cookies))
18555 ((org-at-heading-p) (call-interactively 'org-set-tags))
18556 ((org-at-table.el-p)
18557 (message "Use C-c ' to edit table.el tables"))
18558 ((org-at-table-p)
18559 (org-table-maybe-eval-formula)
18560 (if arg
18561 (call-interactively 'org-table-recalculate)
18562 (org-table-maybe-recalculate-line))
18563 (call-interactively 'org-table-align)
18564 (orgtbl-send-table 'maybe))
18565 ((or (org-footnote-at-reference-p)
18566 (org-footnote-at-definition-p))
18567 (call-interactively 'org-footnote-action))
18568 ((org-at-item-checkbox-p)
18569 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18570 ;; list only if at top item.
18571 (let* ((cbox (match-string 1))
18572 (struct (org-list-struct))
18573 (old-struct (copy-tree struct))
18574 (parents (org-list-parents-alist struct))
18575 (orderedp (org-entry-get nil "ORDERED"))
18576 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18577 block-item)
18578 ;; Use a light version of `org-toggle-checkbox' to avoid
18579 ;; computing list structure twice.
18580 (let ((new-box (cond
18581 ((equal arg '(16)) "[-]")
18582 ((equal arg '(4)) nil)
18583 ((equal "[X]" cbox) "[ ]")
18584 (t "[X]"))))
18585 (if (and firstp arg)
18586 ;; If at first item of sub-list, remove check-box from
18587 ;; every item at the same level.
18588 (mapc
18589 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18590 (org-list-get-all-items
18591 (point-at-bol) struct (org-list-prevs-alist struct)))
18592 (org-list-set-checkbox (point-at-bol) struct new-box)))
18593 ;; Replicate `org-list-write-struct', while grabbing a return
18594 ;; value from `org-list-struct-fix-box'.
18595 (org-list-struct-fix-ind struct parents 2)
18596 (org-list-struct-fix-item-end struct)
18597 (let ((prevs (org-list-prevs-alist struct)))
18598 (org-list-struct-fix-bul struct prevs)
18599 (org-list-struct-fix-ind struct parents)
18600 (setq block-item
18601 (org-list-struct-fix-box struct parents prevs orderedp)))
18602 (org-list-struct-apply-struct struct old-struct)
18603 (org-update-checkbox-count-maybe)
18604 (when block-item
18605 (message
18606 "Checkboxes were removed due to unchecked box at line %d"
18607 (org-current-line block-item)))
18608 (when firstp (org-list-send-list 'maybe))))
18609 ((org-at-item-p)
18610 ;; Cursor at an item: repair list. Do checkbox related actions
18611 ;; only if function was called with an argument. Send list only
18612 ;; if at top item.
18613 (let* ((struct (org-list-struct))
18614 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18615 old-struct)
18616 (when arg
18617 (setq old-struct (copy-tree struct))
18618 (if firstp
18619 ;; If at first item of sub-list, add check-box to every
18620 ;; item at the same level.
18621 (mapc
18622 (lambda (pos)
18623 (unless (org-list-get-checkbox pos struct)
18624 (org-list-set-checkbox pos struct "[ ]")))
18625 (org-list-get-all-items
18626 (point-at-bol) struct (org-list-prevs-alist struct)))
18627 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18628 (org-list-write-struct
18629 struct (org-list-parents-alist struct) old-struct)
18630 (when arg (org-update-checkbox-count-maybe))
18631 (when firstp (org-list-send-list 'maybe))))
18632 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18633 ;; Dynamic block
18634 (beginning-of-line 1)
18635 (save-excursion (org-update-dblock)))
18636 ((save-excursion
18637 (beginning-of-line 1)
18638 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18639 (cond
18640 ((equal (match-string 1) "TBLFM")
18641 ;; Recalculate the table before this line
18642 (save-excursion
18643 (beginning-of-line 1)
18644 (skip-chars-backward " \r\n\t")
18645 (if (org-at-table-p)
18646 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18648 (let ((org-inhibit-startup-visibility-stuff t)
18649 (org-startup-align-all-tables nil))
18650 (when (boundp 'org-table-coordinate-overlays)
18651 (mapc 'delete-overlay org-table-coordinate-overlays)
18652 (setq org-table-coordinate-overlays nil))
18653 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18654 (message "Local setup has been refreshed"))))
18655 ((org-clock-update-time-maybe))
18657 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18658 (error "C-c C-c can do nothing useful at this location"))))))
18660 (defun org-mode-restart ()
18661 "Restart Org-mode, to scan again for special lines.
18662 Also updates the keyword regular expressions."
18663 (interactive)
18664 (org-mode)
18665 (message "Org-mode restarted"))
18667 (defun org-kill-note-or-show-branches ()
18668 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18669 (interactive)
18670 (if (not org-finish-function)
18671 (progn
18672 (hide-subtree)
18673 (call-interactively 'show-branches))
18674 (let ((org-note-abort t))
18675 (funcall org-finish-function))))
18677 (defun org-return (&optional indent)
18678 "Goto next table row or insert a newline.
18679 Calls `org-table-next-row' or `newline', depending on context.
18680 See the individual commands for more information."
18681 (interactive)
18682 (cond
18683 ((or (bobp) (org-in-src-block-p))
18684 (if indent (newline-and-indent) (newline)))
18685 ((org-at-table-p)
18686 (org-table-justify-field-maybe)
18687 (call-interactively 'org-table-next-row))
18688 ;; when `newline-and-indent' is called within a list, make sure
18689 ;; text moved stays inside the item.
18690 ((and (org-in-item-p) indent)
18691 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18692 (progn
18693 (save-match-data (newline))
18694 (org-indent-line-to (length (match-string 0))))
18695 (let ((ind (org-get-indentation)))
18696 (newline)
18697 (if (org-looking-back org-list-end-re)
18698 (org-indent-line-function)
18699 (org-indent-line-to ind)))))
18700 ((and org-return-follows-link
18701 (let ((tprop (get-text-property (point) 'face)))
18702 (or (eq tprop 'org-link)
18703 (and (listp tprop) (memq 'org-link tprop)))))
18704 (call-interactively 'org-open-at-point))
18705 ((and (org-at-heading-p)
18706 (looking-at
18707 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18708 (org-show-entry)
18709 (end-of-line 1)
18710 (newline))
18711 (t (if indent (newline-and-indent) (newline)))))
18713 (defun org-return-indent ()
18714 "Goto next table row or insert a newline and indent.
18715 Calls `org-table-next-row' or `newline-and-indent', depending on
18716 context. See the individual commands for more information."
18717 (interactive)
18718 (org-return t))
18720 (defun org-ctrl-c-star ()
18721 "Compute table, or change heading status of lines.
18722 Calls `org-table-recalculate' or `org-toggle-heading',
18723 depending on context."
18724 (interactive)
18725 (cond
18726 ((org-at-table-p)
18727 (call-interactively 'org-table-recalculate))
18729 ;; Convert all lines in region to list items
18730 (call-interactively 'org-toggle-heading))))
18732 (defun org-ctrl-c-minus ()
18733 "Insert separator line in table or modify bullet status of line.
18734 Also turns a plain line or a region of lines into list items.
18735 Calls `org-table-insert-hline', `org-toggle-item', or
18736 `org-cycle-list-bullet', depending on context."
18737 (interactive)
18738 (cond
18739 ((org-at-table-p)
18740 (call-interactively 'org-table-insert-hline))
18741 ((org-region-active-p)
18742 (call-interactively 'org-toggle-item))
18743 ((org-in-item-p)
18744 (call-interactively 'org-cycle-list-bullet))
18746 (call-interactively 'org-toggle-item))))
18748 (defun org-toggle-item (arg)
18749 "Convert headings or normal lines to items, items to normal lines.
18750 If there is no active region, only the current line is considered.
18752 If the first non blank line in the region is an headline, convert
18753 all headlines to items, shifting text accordingly.
18755 If it is an item, convert all items to normal lines.
18757 If it is normal text, change region into an item. With a prefix
18758 argument ARG, change each line in region into an item."
18759 (interactive "P")
18760 (let ((shift-text
18761 (function
18762 ;; Shift text in current section to IND, from point to END.
18763 ;; The function leaves point to END line.
18764 (lambda (ind end)
18765 (let ((min-i 1000) (end (copy-marker end)))
18766 ;; First determine the minimum indentation (MIN-I) of
18767 ;; the text.
18768 (save-excursion
18769 (catch 'exit
18770 (while (< (point) end)
18771 (let ((i (org-get-indentation)))
18772 (cond
18773 ;; Skip blank lines and inline tasks.
18774 ((looking-at "^[ \t]*$"))
18775 ((looking-at org-outline-regexp-bol))
18776 ;; We can't find less than 0 indentation.
18777 ((zerop i) (throw 'exit (setq min-i 0)))
18778 ((< i min-i) (setq min-i i))))
18779 (forward-line))))
18780 ;; Then indent each line so that a line indented to
18781 ;; MIN-I becomes indented to IND. Ignore blank lines
18782 ;; and inline tasks in the process.
18783 (let ((delta (- ind min-i)))
18784 (while (< (point) end)
18785 (unless (or (looking-at "^[ \t]*$")
18786 (looking-at org-outline-regexp-bol))
18787 (org-indent-line-to (+ (org-get-indentation) delta)))
18788 (forward-line)))))))
18789 (skip-blanks
18790 (function
18791 ;; Return beginning of first non-blank line, starting from
18792 ;; line at POS.
18793 (lambda (pos)
18794 (save-excursion
18795 (goto-char pos)
18796 (skip-chars-forward " \r\t\n")
18797 (point-at-bol)))))
18798 beg end)
18799 ;; Determine boundaries of changes.
18800 (if (org-region-active-p)
18801 (setq beg (funcall skip-blanks (region-beginning))
18802 end (copy-marker (region-end)))
18803 (setq beg (funcall skip-blanks (point-at-bol))
18804 end (copy-marker (point-at-eol))))
18805 ;; Depending on the starting line, choose an action on the text
18806 ;; between BEG and END.
18807 (org-with-limited-levels
18808 (save-excursion
18809 (goto-char beg)
18810 (cond
18811 ;; Case 1. Start at an item: de-itemize. Note that it only
18812 ;; happens when a region is active: `org-ctrl-c-minus'
18813 ;; would call `org-cycle-list-bullet' otherwise.
18814 ((org-at-item-p)
18815 (while (< (point) end)
18816 (when (org-at-item-p)
18817 (skip-chars-forward " \t")
18818 (delete-region (point) (match-end 0)))
18819 (forward-line)))
18820 ;; Case 2. Start at an heading: convert to items.
18821 ((org-at-heading-p)
18822 (let* ((bul (org-list-bullet-string "-"))
18823 (bul-len (length bul))
18824 ;; Indentation of the first heading. It should be
18825 ;; relative to the indentation of its parent, if any.
18826 (start-ind (save-excursion
18827 (cond
18828 ((not org-adapt-indentation) 0)
18829 ((not (outline-previous-heading)) 0)
18830 (t (length (match-string 0))))))
18831 ;; Level of first heading. Further headings will be
18832 ;; compared to it to determine hierarchy in the list.
18833 (ref-level (org-reduced-level (org-outline-level))))
18834 (while (< (point) end)
18835 (let* ((level (org-reduced-level (org-outline-level)))
18836 (delta (max 0 (- level ref-level))))
18837 ;; If current headline is less indented than the first
18838 ;; one, set it as reference, in order to preserve
18839 ;; subtrees.
18840 (when (< level ref-level) (setq ref-level level))
18841 (replace-match bul t t)
18842 (org-indent-line-to (+ start-ind (* delta bul-len)))
18843 ;; Ensure all text down to END (or SECTION-END) belongs
18844 ;; to the newly created item.
18845 (let ((section-end (save-excursion
18846 (or (outline-next-heading) (point)))))
18847 (forward-line)
18848 (funcall shift-text
18849 (+ start-ind (* (1+ delta) bul-len))
18850 (min end section-end)))))))
18851 ;; Case 3. Normal line with ARG: turn each non-item line into
18852 ;; an item.
18853 (arg
18854 (while (< (point) end)
18855 (unless (or (org-at-heading-p) (org-at-item-p))
18856 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18857 (replace-match
18858 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18859 (forward-line)))
18860 ;; Case 4. Normal line without ARG: make the first line of
18861 ;; region an item, and shift indentation of others
18862 ;; lines to set them as item's body.
18863 (t (let* ((bul (org-list-bullet-string "-"))
18864 (bul-len (length bul))
18865 (ref-ind (org-get-indentation)))
18866 (skip-chars-forward " \t")
18867 (insert bul)
18868 (forward-line)
18869 (while (< (point) end)
18870 ;; Ensure that lines less indented than first one
18871 ;; still get included in item body.
18872 (funcall shift-text
18873 (+ ref-ind bul-len)
18874 (min end (save-excursion (or (outline-next-heading)
18875 (point)))))
18876 (forward-line)))))))))
18878 (defun org-toggle-heading (&optional nstars)
18879 "Convert headings to normal text, or items or text to headings.
18880 If there is no active region, only the current line is considered.
18882 If the first non blank line is an headline, remove the stars from
18883 all headlines in the region.
18885 If it is a plain list item, turn all plain list items into headings.
18887 If it is a normal line, turn each and every normal line (i.e. not
18888 an heading or an item) in the region into a heading.
18890 When converting a line into a heading, the number of stars is chosen
18891 such that the lines become children of the current entry. However,
18892 when a prefix argument is given, its value determines the number of
18893 stars to add."
18894 (interactive "P")
18895 (let ((skip-blanks
18896 (function
18897 ;; Return beginning of first non-blank line, starting from
18898 ;; line at POS.
18899 (lambda (pos)
18900 (save-excursion
18901 (goto-char pos)
18902 (skip-chars-forward " \r\t\n")
18903 (point-at-bol)))))
18904 beg end)
18905 ;; Determine boundaries of changes. If region ends at a bol, do
18906 ;; not consider the last line to be in the region.
18907 (if (org-region-active-p)
18908 (setq beg (funcall skip-blanks (region-beginning))
18909 end (copy-marker (save-excursion
18910 (goto-char (region-end))
18911 (if (bolp) (point) (point-at-eol)))))
18912 (setq beg (funcall skip-blanks (point-at-bol))
18913 end (copy-marker (point-at-eol))))
18914 ;; Ensure inline tasks don't count as headings.
18915 (org-with-limited-levels
18916 (save-excursion
18917 (goto-char beg)
18918 (cond
18919 ;; Case 1. Started at an heading: de-star headings.
18920 ((org-at-heading-p)
18921 (while (< (point) end)
18922 (when (org-at-heading-p t)
18923 (looking-at org-outline-regexp) (replace-match ""))
18924 (forward-line)))
18925 ;; Case 2. Started at an item: change items into headlines.
18926 ;; One star will be added by `org-list-to-subtree'.
18927 ((org-at-item-p)
18928 (let* ((stars (make-string
18929 (if nstars
18930 ;; subtract the star that will be added again by
18931 ;; `org-list-to-subtree'
18932 (1- (prefix-numeric-value current-prefix-arg))
18933 (or (org-current-level) 0))
18934 ?*))
18935 (add-stars
18936 (cond (nstars "") ; stars from prefix only
18937 ((equal stars "") "") ; before first heading
18938 (org-odd-levels-only "*") ; inside heading, odd
18939 (t "")))) ; inside heading, oddeven
18940 (while (< (point) end)
18941 (when (org-at-item-p)
18942 ;; Pay attention to cases when region ends before list.
18943 (let* ((struct (org-list-struct))
18944 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18945 (save-restriction
18946 (narrow-to-region (point) list-end)
18947 (insert
18948 (org-list-to-subtree
18949 (org-list-parse-list t)
18950 '(:istart (concat stars add-stars (funcall get-stars depth))
18951 :icount (concat stars add-stars (funcall get-stars depth))))))))
18952 (forward-line))))
18953 ;; Case 3. Started at normal text: make every line an heading,
18954 ;; skipping headlines and items.
18955 (t (let* ((stars (make-string
18956 (if nstars
18957 (prefix-numeric-value current-prefix-arg)
18958 (or (org-current-level) 0))
18959 ?*))
18960 (add-stars
18961 (cond (nstars "") ; stars from prefix only
18962 ((equal stars "") "*") ; before first heading
18963 (org-odd-levels-only "**") ; inside heading, odd
18964 (t "*"))) ; inside heading, oddeven
18965 (rpl (concat stars add-stars " ")))
18966 (while (< (point) end)
18967 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18968 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18969 (replace-match (concat rpl (match-string 2))))
18970 (forward-line)))))))))
18972 (defun org-meta-return (&optional arg)
18973 "Insert a new heading or wrap a region in a table.
18974 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18975 See the individual commands for more information."
18976 (interactive "P")
18977 (cond
18978 ((run-hook-with-args-until-success 'org-metareturn-hook))
18979 ((or (org-at-drawer-p) (org-at-property-p))
18980 (newline-and-indent))
18981 ((org-at-table-p)
18982 (call-interactively 'org-table-wrap-region))
18983 (t (call-interactively 'org-insert-heading))))
18985 ;;; Menu entries
18987 ;; Define the Org-mode menus
18988 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18989 '("Tbl"
18990 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18991 ["Next Field" org-cycle (org-at-table-p)]
18992 ["Previous Field" org-shifttab (org-at-table-p)]
18993 ["Next Row" org-return (org-at-table-p)]
18994 "--"
18995 ["Blank Field" org-table-blank-field (org-at-table-p)]
18996 ["Edit Field" org-table-edit-field (org-at-table-p)]
18997 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18998 "--"
18999 ("Column"
19000 ["Move Column Left" org-metaleft (org-at-table-p)]
19001 ["Move Column Right" org-metaright (org-at-table-p)]
19002 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19003 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19004 ("Row"
19005 ["Move Row Up" org-metaup (org-at-table-p)]
19006 ["Move Row Down" org-metadown (org-at-table-p)]
19007 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19008 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19009 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19010 "--"
19011 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19012 ("Rectangle"
19013 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19014 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19015 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19016 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19017 "--"
19018 ("Calculate"
19019 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19020 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19021 ["Edit Formulas" org-edit-special (org-at-table-p)]
19022 "--"
19023 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19024 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19025 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19026 "--"
19027 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19028 "--"
19029 ["Sum Column/Rectangle" org-table-sum
19030 (or (org-at-table-p) (org-region-active-p))]
19031 ["Which Column?" org-table-current-column (org-at-table-p)])
19032 ["Debug Formulas"
19033 org-table-toggle-formula-debugger
19034 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19035 ["Show Col/Row Numbers"
19036 org-table-toggle-coordinate-overlays
19037 :style toggle
19038 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19039 "--"
19040 ["Create" org-table-create (and (not (org-at-table-p))
19041 org-enable-table-editor)]
19042 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19043 ["Import from File" org-table-import (not (org-at-table-p))]
19044 ["Export to File" org-table-export (org-at-table-p)]
19045 "--"
19046 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19048 (easy-menu-define org-org-menu org-mode-map "Org menu"
19049 '("Org"
19050 ("Show/Hide"
19051 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19052 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19053 ["Sparse Tree..." org-sparse-tree t]
19054 ["Reveal Context" org-reveal t]
19055 ["Show All" show-all t]
19056 "--"
19057 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19058 "--"
19059 ["New Heading" org-insert-heading t]
19060 ("Navigate Headings"
19061 ["Up" outline-up-heading t]
19062 ["Next" outline-next-visible-heading t]
19063 ["Previous" outline-previous-visible-heading t]
19064 ["Next Same Level" outline-forward-same-level t]
19065 ["Previous Same Level" outline-backward-same-level t]
19066 "--"
19067 ["Jump" org-goto t])
19068 ("Edit Structure"
19069 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19070 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19071 "--"
19072 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19073 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19074 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19075 "--"
19076 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19077 "--"
19078 ["Copy visible text" org-copy-visible t]
19079 "--"
19080 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19081 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19082 ["Demote Heading" org-metaright (not (org-at-table-p))]
19083 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19084 "--"
19085 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19086 "--"
19087 ["Convert to odd levels" org-convert-to-odd-levels t]
19088 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19089 ("Editing"
19090 ["Emphasis..." org-emphasize t]
19091 ["Edit Source Example" org-edit-special t]
19092 "--"
19093 ["Footnote new/jump" org-footnote-action t]
19094 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19095 ("Archive"
19096 ["Archive (default method)" org-archive-subtree-default t]
19097 "--"
19098 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19099 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19100 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19102 "--"
19103 ("Hyperlinks"
19104 ["Store Link (Global)" org-store-link t]
19105 ["Find existing link to here" org-occur-link-in-agenda-files t]
19106 ["Insert Link" org-insert-link t]
19107 ["Follow Link" org-open-at-point t]
19108 "--"
19109 ["Next link" org-next-link t]
19110 ["Previous link" org-previous-link t]
19111 "--"
19112 ["Descriptive Links"
19113 org-toggle-link-display
19114 :style radio
19115 :selected org-descriptive-links
19117 ["Literal Links"
19118 org-toggle-link-display
19119 :style radio
19120 :selected (not org-descriptive-links)])
19121 "--"
19122 ("TODO Lists"
19123 ["TODO/DONE/-" org-todo t]
19124 ("Select keyword"
19125 ["Next keyword" org-shiftright (org-at-heading-p)]
19126 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19127 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19128 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19129 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19130 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19131 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19132 "--"
19133 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19134 :selected org-enforce-todo-dependencies :style toggle :active t]
19135 "Settings for tree at point"
19136 ["Do Children sequentially" org-toggle-ordered-property :style radio
19137 :selected (org-entry-get nil "ORDERED")
19138 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19139 ["Do Children parallel" org-toggle-ordered-property :style radio
19140 :selected (not (org-entry-get nil "ORDERED"))
19141 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19142 "--"
19143 ["Set Priority" org-priority t]
19144 ["Priority Up" org-shiftup t]
19145 ["Priority Down" org-shiftdown t]
19146 "--"
19147 ["Get news from all feeds" org-feed-update-all t]
19148 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19149 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19150 ("TAGS and Properties"
19151 ["Set Tags" org-set-tags-command t]
19152 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19153 "--"
19154 ["Set property" org-set-property t]
19155 ["Column view of properties" org-columns t]
19156 ["Insert Column View DBlock" org-insert-columns-dblock t])
19157 ("Dates and Scheduling"
19158 ["Timestamp" org-time-stamp t]
19159 ["Timestamp (inactive)" org-time-stamp-inactive t]
19160 ("Change Date"
19161 ["1 Day Later" org-shiftright t]
19162 ["1 Day Earlier" org-shiftleft t]
19163 ["1 ... Later" org-shiftup t]
19164 ["1 ... Earlier" org-shiftdown t])
19165 ["Compute Time Range" org-evaluate-time-range t]
19166 ["Schedule Item" org-schedule t]
19167 ["Deadline" org-deadline t]
19168 "--"
19169 ["Custom time format" org-toggle-time-stamp-overlays
19170 :style radio :selected org-display-custom-times]
19171 "--"
19172 ["Goto Calendar" org-goto-calendar t]
19173 ["Date from Calendar" org-date-from-calendar t]
19174 "--"
19175 ["Start/Restart Timer" org-timer-start t]
19176 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19177 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19178 ["Insert Timer String" org-timer t]
19179 ["Insert Timer Item" org-timer-item t])
19180 ("Logging work"
19181 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19182 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19183 ["Clock out" org-clock-out t]
19184 ["Clock cancel" org-clock-cancel t]
19185 "--"
19186 ["Mark as default task" org-clock-mark-default-task t]
19187 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19188 ["Goto running clock" org-clock-goto t]
19189 "--"
19190 ["Display times" org-clock-display t]
19191 ["Create clock table" org-clock-report t]
19192 "--"
19193 ["Record DONE time"
19194 (progn (setq org-log-done (not org-log-done))
19195 (message "Switching to %s will %s record a timestamp"
19196 (car org-done-keywords)
19197 (if org-log-done "automatically" "not")))
19198 :style toggle :selected org-log-done])
19199 "--"
19200 ["Agenda Command..." org-agenda t]
19201 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19202 ("File List for Agenda")
19203 ("Special views current file"
19204 ["TODO Tree" org-show-todo-tree t]
19205 ["Check Deadlines" org-check-deadlines t]
19206 ["Timeline" org-timeline t]
19207 ["Tags/Property tree" org-match-sparse-tree t])
19208 "--"
19209 ["Export/Publish..." org-export t]
19210 ("LaTeX"
19211 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19212 :selected org-cdlatex-mode]
19213 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19214 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19215 ["Modify math symbol" org-cdlatex-math-modify
19216 (org-inside-LaTeX-fragment-p)]
19217 ["Insert citation" org-reftex-citation t]
19218 "--"
19219 ["Template for BEAMER" (progn (require 'org-beamer)
19220 (org-insert-beamer-options-template)) t])
19221 "--"
19222 ("MobileOrg"
19223 ["Push Files and Views" org-mobile-push t]
19224 ["Get Captured and Flagged" org-mobile-pull t]
19225 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19226 "--"
19227 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19228 "--"
19229 ("Documentation"
19230 ["Show Version" org-version t]
19231 ["Info Documentation" org-info t])
19232 ("Customize"
19233 ["Browse Org Group" org-customize t]
19234 "--"
19235 ["Expand This Menu" org-create-customize-menu
19236 (fboundp 'customize-menu-create)])
19237 ["Send bug report" org-submit-bug-report t]
19238 "--"
19239 ("Refresh/Reload"
19240 ["Refresh setup current buffer" org-mode-restart t]
19241 ["Reload Org (after update)" org-reload t]
19242 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19245 (defun org-info (&optional node)
19246 "Read documentation for Org-mode in the info system.
19247 With optional NODE, go directly to that node."
19248 (interactive)
19249 (info (format "(org)%s" (or node ""))))
19251 ;;;###autoload
19252 (defun org-submit-bug-report ()
19253 "Submit a bug report on Org-mode via mail.
19255 Don't hesitate to report any problems or inaccurate documentation.
19257 If you don't have setup sending mail from (X)Emacs, please copy the
19258 output buffer into your mail program, as it gives us important
19259 information about your Org-mode version and configuration."
19260 (interactive)
19261 (require 'reporter)
19262 (org-load-modules-maybe)
19263 (org-require-autoloaded-modules)
19264 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19265 (reporter-submit-bug-report
19266 "emacs-orgmode@gnu.org"
19267 (org-version)
19268 (let (list)
19269 (save-window-excursion
19270 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19271 (delete-other-windows)
19272 (erase-buffer)
19273 (insert "You are about to submit a bug report to the Org-mode mailing list.
19275 We would like to add your full Org-mode and Outline configuration to the
19276 bug report. This greatly simplifies the work of the maintainer and
19277 other experts on the mailing list.
19279 HOWEVER, some variables you have customized may contain private
19280 information. The names of customers, colleagues, or friends, might
19281 appear in the form of file names, tags, todo states, or search strings.
19282 If you answer yes to the prompt, you might want to check and remove
19283 such private information before sending the email.")
19284 (add-text-properties (point-min) (point-max) '(face org-warning))
19285 (when (yes-or-no-p "Include your Org-mode configuration ")
19286 (mapatoms
19287 (lambda (v)
19288 (and (boundp v)
19289 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19290 (or (and (symbol-value v)
19291 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19292 (and
19293 (get v 'custom-type) (get v 'standard-value)
19294 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19295 (push v list)))))
19296 (kill-buffer (get-buffer "*Warn about privacy*"))
19297 list))
19298 nil nil
19299 "Remember to cover the basics, that is, what you expected to happen and
19300 what in fact did happen. You don't know how to make a good report? See
19302 http://orgmode.org/manual/Feedback.html#Feedback
19304 Your bug report will be posted to the Org-mode mailing list.
19305 ------------------------------------------------------------------------")
19306 (save-excursion
19307 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19308 (replace-match "\\1Bug: \\3 [\\2]")))))
19311 (defun org-install-agenda-files-menu ()
19312 (let ((bl (buffer-list)))
19313 (save-excursion
19314 (while bl
19315 (set-buffer (pop bl))
19316 (if (eq major-mode 'org-mode) (setq bl nil)))
19317 (when (eq major-mode 'org-mode)
19318 (easy-menu-change
19319 '("Org") "File List for Agenda"
19320 (append
19321 (list
19322 ["Edit File List" (org-edit-agenda-file-list) t]
19323 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19324 ["Remove Current File from List" org-remove-file t]
19325 ["Cycle through agenda files" org-cycle-agenda-files t]
19326 ["Occur in all agenda files" org-occur-in-agenda-files t]
19327 "--")
19328 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19330 ;;;; Documentation
19332 ;;;###autoload
19333 (defun org-require-autoloaded-modules ()
19334 (interactive)
19335 (mapc 'require
19336 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19337 org-docbook org-exp org-html org-icalendar
19338 org-id org-latex
19339 org-publish org-remember org-table
19340 org-timer org-xoxo)))
19342 ;;;###autoload
19343 (defun org-reload (&optional uncompiled)
19344 "Reload all org lisp files.
19345 With prefix arg UNCOMPILED, load the uncompiled versions."
19346 (interactive "P")
19347 (require 'find-func)
19348 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19349 (dir-org (file-name-directory (org-find-library-name "org")))
19350 (dir-org-contrib (ignore-errors
19351 (file-name-directory
19352 (org-find-library-name "org-contribdir"))))
19353 (babel-files
19354 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19355 (append (list nil "comint" "eval" "exp" "keys"
19356 "lob" "ref" "table" "tangle")
19357 (delq nil
19358 (mapcar
19359 (lambda (lang)
19360 (when (cdr lang) (symbol-name (car lang))))
19361 org-babel-load-languages)))))
19362 (files
19363 (append (directory-files dir-org t file-re)
19364 babel-files
19365 (and dir-org-contrib
19366 (directory-files dir-org-contrib t file-re))))
19367 (remove-re (concat (if (featurep 'xemacs)
19368 "org-colview" "org-colview-xemacs")
19369 "\\'")))
19370 (setq files (mapcar 'file-name-sans-extension files))
19371 (setq files (mapcar
19372 (lambda (x) (if (string-match remove-re x) nil x))
19373 files))
19374 (setq files (delq nil files))
19375 (mapc
19376 (lambda (f)
19377 (when (featurep (intern (file-name-nondirectory f)))
19378 (if (and (not uncompiled)
19379 (file-exists-p (concat f ".elc")))
19380 (load (concat f ".elc") nil nil t)
19381 (load (concat f ".el") nil nil t))))
19382 files))
19383 (org-version))
19385 ;;;###autoload
19386 (defun org-customize ()
19387 "Call the customize function with org as argument."
19388 (interactive)
19389 (org-load-modules-maybe)
19390 (org-require-autoloaded-modules)
19391 (customize-browse 'org))
19393 (defun org-create-customize-menu ()
19394 "Create a full customization menu for Org-mode, insert it into the menu."
19395 (interactive)
19396 (org-load-modules-maybe)
19397 (org-require-autoloaded-modules)
19398 (if (fboundp 'customize-menu-create)
19399 (progn
19400 (easy-menu-change
19401 '("Org") "Customize"
19402 `(["Browse Org group" org-customize t]
19403 "--"
19404 ,(customize-menu-create 'org)
19405 ["Set" Custom-set t]
19406 ["Save" Custom-save t]
19407 ["Reset to Current" Custom-reset-current t]
19408 ["Reset to Saved" Custom-reset-saved t]
19409 ["Reset to Standard Settings" Custom-reset-standard t]))
19410 (message "\"Org\"-menu now contains full customization menu"))
19411 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19413 ;;;; Miscellaneous stuff
19415 ;;; Generally useful functions
19417 (defun org-get-at-bol (property)
19418 "Get text property PROPERTY at beginning of line."
19419 (get-text-property (point-at-bol) property))
19421 (defun org-find-text-property-in-string (prop s)
19422 "Return the first non-nil value of property PROP in string S."
19423 (or (get-text-property 0 prop s)
19424 (get-text-property (or (next-single-property-change 0 prop s) 0)
19425 prop s)))
19427 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19428 "Display the given MESSAGE as a warning."
19429 (if (fboundp 'display-warning)
19430 (display-warning 'org message
19431 (if (featurep 'xemacs) 'warning :warning))
19432 (let ((buf (get-buffer-create "*Org warnings*")))
19433 (with-current-buffer buf
19434 (goto-char (point-max))
19435 (insert "Warning (Org): " message)
19436 (unless (bolp)
19437 (newline)))
19438 (display-buffer buf)
19439 (sit-for 0))))
19441 (defun org-eval (form)
19442 "Eval FORM and return result."
19443 (condition-case error
19444 (eval form)
19445 (error (format "%%![Error: %s]" error))))
19447 (defun org-in-clocktable-p ()
19448 "Check if the cursor is in a clocktable."
19449 (let ((pos (point)) start)
19450 (save-excursion
19451 (end-of-line 1)
19452 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19453 (setq start (match-beginning 0))
19454 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19455 (>= (match-end 0) pos)
19456 start))))
19458 (defun org-in-commented-line ()
19459 "Is point in a line starting with `#'?"
19460 (equal (char-after (point-at-bol)) ?#))
19462 (defun org-in-indented-comment-line ()
19463 "Is point in a line starting with `#' after some white space?"
19464 (save-excursion
19465 (save-match-data
19466 (goto-char (point-at-bol))
19467 (looking-at "[ \t]*#"))))
19469 (defun org-in-verbatim-emphasis ()
19470 (save-match-data
19471 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19473 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19474 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19475 (if (and marker (marker-buffer marker)
19476 (buffer-live-p (marker-buffer marker)))
19477 (progn
19478 (org-pop-to-buffer-same-window (marker-buffer marker))
19479 (if (or (> marker (point-max)) (< marker (point-min)))
19480 (widen))
19481 (goto-char marker)
19482 (org-show-context 'org-goto))
19483 (if bookmark
19484 (bookmark-jump bookmark)
19485 (error "Cannot find location"))))
19487 (defun org-quote-csv-field (s)
19488 "Quote field for inclusion in CSV material."
19489 (if (string-match "[\",]" s)
19490 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19493 (defun org-force-self-insert (N)
19494 "Needed to enforce self-insert under remapping."
19495 (interactive "p")
19496 (self-insert-command N))
19498 (defun org-string-width (s)
19499 "Compute width of string, ignoring invisible characters.
19500 This ignores character with invisibility property `org-link', and also
19501 characters with property `org-cwidth', because these will become invisible
19502 upon the next fontification round."
19503 (let (b l)
19504 (when (or (eq t buffer-invisibility-spec)
19505 (assq 'org-link buffer-invisibility-spec))
19506 (while (setq b (text-property-any 0 (length s)
19507 'invisible 'org-link s))
19508 (setq s (concat (substring s 0 b)
19509 (substring s (or (next-single-property-change
19510 b 'invisible s) (length s)))))))
19511 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19512 (setq s (concat (substring s 0 b)
19513 (substring s (or (next-single-property-change
19514 b 'org-cwidth s) (length s))))))
19515 (setq l (string-width s) b -1)
19516 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19517 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19520 (defun org-shorten-string (s maxlength)
19521 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19522 If the string is shorter or has length MAXLENGTH, just return the
19523 original string. If it is longer, the functions finds a space in the
19524 string, breaks this string off at that locations and adds three dots
19525 as ellipsis. Including the ellipsis, the string will not be longer
19526 than MAXLENGTH. If finding a good breaking point in the string does
19527 not work, the string is just chopped off in the middle of a word
19528 if necessary."
19529 (if (<= (length s) maxlength)
19531 (let* ((n (max (- maxlength 4) 1))
19532 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19533 (if (string-match re s)
19534 (concat (match-string 1 s) "...")
19535 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19537 (defun org-get-indentation (&optional line)
19538 "Get the indentation of the current line, interpreting tabs.
19539 When LINE is given, assume it represents a line and compute its indentation."
19540 (if line
19541 (if (string-match "^ *" (org-remove-tabs line))
19542 (match-end 0))
19543 (save-excursion
19544 (beginning-of-line 1)
19545 (skip-chars-forward " \t")
19546 (current-column))))
19548 (defun org-get-string-indentation (s)
19549 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19550 (let ((n -1) (i 0) (w tab-width) c)
19551 (catch 'exit
19552 (while (< (setq n (1+ n)) (length s))
19553 (setq c (aref s n))
19554 (cond ((= c ?\ ) (setq i (1+ i)))
19555 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19556 (t (throw 'exit t)))))
19559 (defun org-remove-tabs (s &optional width)
19560 "Replace tabulators in S with spaces.
19561 Assumes that s is a single line, starting in column 0."
19562 (setq width (or width tab-width))
19563 (while (string-match "\t" s)
19564 (setq s (replace-match
19565 (make-string
19566 (- (* width (/ (+ (match-beginning 0) width) width))
19567 (match-beginning 0)) ?\ )
19568 t t s)))
19571 (defun org-fix-indentation (line ind)
19572 "Fix indentation in LINE.
19573 IND is a cons cell with target and minimum indentation.
19574 If the current indentation in LINE is smaller than the minimum,
19575 leave it alone. If it is larger than ind, set it to the target."
19576 (let* ((l (org-remove-tabs line))
19577 (i (org-get-indentation l))
19578 (i1 (car ind)) (i2 (cdr ind)))
19579 (if (>= i i2) (setq l (substring line i2)))
19580 (if (> i1 0)
19581 (concat (make-string i1 ?\ ) l)
19582 l)))
19584 (defun org-remove-indentation (code &optional n)
19585 "Remove the maximum common indentation from the lines in CODE.
19586 N may optionally be the number of spaces to remove."
19587 (with-temp-buffer
19588 (insert code)
19589 (org-do-remove-indentation n)
19590 (buffer-string)))
19592 (defun org-do-remove-indentation (&optional n)
19593 "Remove the maximum common indentation from the buffer."
19594 (untabify (point-min) (point-max))
19595 (let ((min 10000) re)
19596 (if n
19597 (setq min n)
19598 (goto-char (point-min))
19599 (while (re-search-forward "^ *[^ \n]" nil t)
19600 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19601 (unless (or (= min 0) (= min 10000))
19602 (setq re (format "^ \\{%d\\}" min))
19603 (goto-char (point-min))
19604 (while (re-search-forward re nil t)
19605 (replace-match "")
19606 (end-of-line 1))
19607 min)))
19609 (defun org-fill-template (template alist)
19610 "Find each %key of ALIST in TEMPLATE and replace it."
19611 (let ((case-fold-search nil)
19612 entry key value)
19613 (setq alist (sort (copy-sequence alist)
19614 (lambda (a b) (< (length (car a)) (length (car b))))))
19615 (while (setq entry (pop alist))
19616 (setq template
19617 (replace-regexp-in-string
19618 (concat "%" (regexp-quote (car entry)))
19619 (cdr entry) template t t)))
19620 template))
19622 (defun org-base-buffer (buffer)
19623 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19624 (if (not buffer)
19625 buffer
19626 (or (buffer-base-buffer buffer)
19627 buffer)))
19629 (defun org-trim (s)
19630 "Remove whitespace at beginning and end of string."
19631 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19632 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19635 (defun org-wrap (string &optional width lines)
19636 "Wrap string to either a number of lines, or a width in characters.
19637 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19638 that costs. If there is a word longer than WIDTH, the text is actually
19639 wrapped to the length of that word.
19640 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19641 many lines, whatever width that takes.
19642 The return value is a list of lines, without newlines at the end."
19643 (let* ((words (org-split-string string "[ \t\n]+"))
19644 (maxword (apply 'max (mapcar 'org-string-width words)))
19645 w ll)
19646 (cond (width
19647 (org-do-wrap words (max maxword width)))
19648 (lines
19649 (setq w maxword)
19650 (setq ll (org-do-wrap words maxword))
19651 (if (<= (length ll) lines)
19653 (setq ll words)
19654 (while (> (length ll) lines)
19655 (setq w (1+ w))
19656 (setq ll (org-do-wrap words w)))
19657 ll))
19658 (t (error "Cannot wrap this")))))
19660 (defun org-do-wrap (words width)
19661 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19662 (let (lines line)
19663 (while words
19664 (setq line (pop words))
19665 (while (and words (< (+ (length line) (length (car words))) width))
19666 (setq line (concat line " " (pop words))))
19667 (setq lines (push line lines)))
19668 (nreverse lines)))
19670 (defun org-split-string (string &optional separators)
19671 "Splits STRING into substrings at SEPARATORS.
19672 No empty strings are returned if there are matches at the beginning
19673 and end of string."
19674 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19675 (start 0)
19676 notfirst
19677 (list nil))
19678 (while (and (string-match rexp string
19679 (if (and notfirst
19680 (= start (match-beginning 0))
19681 (< start (length string)))
19682 (1+ start) start))
19683 (< (match-beginning 0) (length string)))
19684 (setq notfirst t)
19685 (or (eq (match-beginning 0) 0)
19686 (and (eq (match-beginning 0) (match-end 0))
19687 (eq (match-beginning 0) start))
19688 (setq list
19689 (cons (substring string start (match-beginning 0))
19690 list)))
19691 (setq start (match-end 0)))
19692 (or (eq start (length string))
19693 (setq list
19694 (cons (substring string start)
19695 list)))
19696 (nreverse list)))
19698 (defun org-quote-vert (s)
19699 "Replace \"|\" with \"\\vert\"."
19700 (while (string-match "|" s)
19701 (setq s (replace-match "\\vert" t t s)))
19704 (defun org-uuidgen-p (s)
19705 "Is S an ID created by UUIDGEN?"
19706 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19708 (defun org-in-src-block-p nil
19709 "Whether point is in a code source block."
19710 (let (ov)
19711 (when (setq ov (overlays-at (point)))
19712 (memq 'org-block-background
19713 (overlay-properties
19714 (car ov))))))
19716 (defun org-context ()
19717 "Return a list of contexts of the current cursor position.
19718 If several contexts apply, all are returned.
19719 Each context entry is a list with a symbol naming the context, and
19720 two positions indicating start and end of the context. Possible
19721 contexts are:
19723 :headline anywhere in a headline
19724 :headline-stars on the leading stars in a headline
19725 :todo-keyword on a TODO keyword (including DONE) in a headline
19726 :tags on the TAGS in a headline
19727 :priority on the priority cookie in a headline
19728 :item on the first line of a plain list item
19729 :item-bullet on the bullet/number of a plain list item
19730 :checkbox on the checkbox in a plain list item
19731 :table in an org-mode table
19732 :table-special on a special filed in a table
19733 :table-table in a table.el table
19734 :clocktable in a clocktable
19735 :src-block in a source block
19736 :link on a hyperlink
19737 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19738 :target on a <<target>>
19739 :radio-target on a <<<radio-target>>>
19740 :latex-fragment on a LaTeX fragment
19741 :latex-preview on a LaTeX fragment with overlaid preview image
19743 This function expects the position to be visible because it uses font-lock
19744 faces as a help to recognize the following contexts: :table-special, :link,
19745 and :keyword."
19746 (let* ((f (get-text-property (point) 'face))
19747 (faces (if (listp f) f (list f)))
19748 (case-fold-search t)
19749 (p (point)) clist o)
19750 ;; First the large context
19751 (cond
19752 ((org-at-heading-p t)
19753 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19754 (when (progn
19755 (beginning-of-line 1)
19756 (looking-at org-todo-line-tags-regexp))
19757 (push (org-point-in-group p 1 :headline-stars) clist)
19758 (push (org-point-in-group p 2 :todo-keyword) clist)
19759 (push (org-point-in-group p 4 :tags) clist))
19760 (goto-char p)
19761 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19762 (if (looking-at "\\[#[A-Z0-9]\\]")
19763 (push (org-point-in-group p 0 :priority) clist)))
19765 ((org-at-item-p)
19766 (push (org-point-in-group p 2 :item-bullet) clist)
19767 (push (list :item (point-at-bol)
19768 (save-excursion (org-end-of-item) (point)))
19769 clist)
19770 (and (org-at-item-checkbox-p)
19771 (push (org-point-in-group p 0 :checkbox) clist)))
19773 ((org-at-table-p)
19774 (push (list :table (org-table-begin) (org-table-end)) clist)
19775 (if (memq 'org-formula faces)
19776 (push (list :table-special
19777 (previous-single-property-change p 'face)
19778 (next-single-property-change p 'face)) clist)))
19779 ((org-at-table-p 'any)
19780 (push (list :table-table) clist)))
19781 (goto-char p)
19783 ;; New the "medium" contexts: clocktables, source blocks
19784 (cond ((org-in-clocktable-p)
19785 (push (list :clocktable
19786 (and (or (looking-at "#\\+BEGIN: clocktable")
19787 (search-backward "#+BEGIN: clocktable" nil t))
19788 (match-beginning 0))
19789 (and (re-search-forward "#\\+END:?" nil t)
19790 (match-end 0))) clist))
19791 ((org-in-src-block-p)
19792 (push (list :src-block
19793 (and (or (looking-at "#\\+BEGIN_SRC")
19794 (search-backward "#+BEGIN_SRC" nil t))
19795 (match-beginning 0))
19796 (and (search-forward "#+END_SRC" nil t)
19797 (match-beginning 0))) clist)))
19798 (goto-char p)
19800 ;; Now the small context
19801 (cond
19802 ((org-at-timestamp-p)
19803 (push (org-point-in-group p 0 :timestamp) clist))
19804 ((memq 'org-link faces)
19805 (push (list :link
19806 (previous-single-property-change p 'face)
19807 (next-single-property-change p 'face)) clist))
19808 ((memq 'org-special-keyword faces)
19809 (push (list :keyword
19810 (previous-single-property-change p 'face)
19811 (next-single-property-change p 'face)) clist))
19812 ((org-at-target-p)
19813 (push (org-point-in-group p 0 :target) clist)
19814 (goto-char (1- (match-beginning 0)))
19815 (if (looking-at org-radio-target-regexp)
19816 (push (org-point-in-group p 0 :radio-target) clist))
19817 (goto-char p))
19818 ((setq o (car (delq nil
19819 (mapcar
19820 (lambda (x)
19821 (if (memq x org-latex-fragment-image-overlays) x))
19822 (overlays-at (point))))))
19823 (push (list :latex-fragment
19824 (overlay-start o) (overlay-end o)) clist)
19825 (push (list :latex-preview
19826 (overlay-start o) (overlay-end o)) clist))
19827 ((org-inside-LaTeX-fragment-p)
19828 ;; FIXME: positions wrong.
19829 (push (list :latex-fragment (point) (point)) clist)))
19831 (setq clist (nreverse (delq nil clist)))
19832 clist))
19834 ;; FIXME: Compare with at-regexp-p Do we need both?
19835 (defun org-in-regexp (re &optional nlines visually)
19836 "Check if point is inside a match of regexp.
19837 Normally only the current line is checked, but you can include NLINES extra
19838 lines both before and after point into the search.
19839 If VISUALLY is set, require that the cursor is not after the match but
19840 really on, so that the block visually is on the match."
19841 (catch 'exit
19842 (let ((pos (point))
19843 (eol (point-at-eol (+ 1 (or nlines 0))))
19844 (inc (if visually 1 0)))
19845 (save-excursion
19846 (beginning-of-line (- 1 (or nlines 0)))
19847 (while (re-search-forward re eol t)
19848 (if (and (<= (match-beginning 0) pos)
19849 (>= (+ inc (match-end 0)) pos))
19850 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19852 (defun org-at-regexp-p (regexp)
19853 "Is point inside a match of REGEXP in the current line?"
19854 (catch 'exit
19855 (save-excursion
19856 (let ((pos (point)) (end (point-at-eol)))
19857 (beginning-of-line 1)
19858 (while (re-search-forward regexp end t)
19859 (if (and (<= (match-beginning 0) pos)
19860 (>= (match-end 0) pos))
19861 (throw 'exit t)))
19862 nil))))
19864 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19865 "Non-nil when point is between matches of START-RE and END-RE.
19867 Also return a non-nil value when point is on one of the matches.
19869 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19870 buffer positions. Default values are the positions of headlines
19871 surrounding the point.
19873 The functions returns a cons cell whose car (resp. cdr) is the
19874 position before START-RE (resp. after END-RE)."
19875 (save-match-data
19876 (let ((pos (point))
19877 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19878 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19879 beg end)
19880 (save-excursion
19881 ;; Point is on a block when on START-RE or if START-RE can be
19882 ;; found before it...
19883 (and (or (org-at-regexp-p start-re)
19884 (re-search-backward start-re limit-up t))
19885 (setq beg (match-beginning 0))
19886 ;; ... and END-RE after it...
19887 (goto-char (match-end 0))
19888 (re-search-forward end-re limit-down t)
19889 (> (setq end (match-end 0)) pos)
19890 ;; ... without another START-RE in-between.
19891 (goto-char (match-beginning 0))
19892 (not (re-search-backward start-re (1+ beg) t))
19893 ;; Return value.
19894 (cons beg end))))))
19896 (defun org-in-block-p (names)
19897 "Non-nil when point belongs to a block whose name belongs to NAMES.
19899 NAMES is a list of strings containing names of blocks.
19901 Return first block name matched, or nil. Beware that in case of
19902 nested blocks, the returned name may not belong to the closest
19903 block from point."
19904 (save-match-data
19905 (catch 'exit
19906 (let ((case-fold-search t)
19907 (lim-up (save-excursion (outline-previous-heading)))
19908 (lim-down (save-excursion (outline-next-heading))))
19909 (mapc (lambda (name)
19910 (let ((n (regexp-quote name)))
19911 (when (org-between-regexps-p
19912 (concat "^[ \t]*#\\+begin_" n)
19913 (concat "^[ \t]*#\\+end_" n)
19914 lim-up lim-down)
19915 (throw 'exit n))))
19916 names))
19917 nil)))
19919 (defun org-occur-in-agenda-files (regexp &optional nlines)
19920 "Call `multi-occur' with buffers for all agenda files."
19921 (interactive "sOrg-files matching: \np")
19922 (let* ((files (org-agenda-files))
19923 (tnames (mapcar 'file-truename files))
19924 (extra org-agenda-text-search-extra-files)
19926 (when (eq (car extra) 'agenda-archives)
19927 (setq extra (cdr extra))
19928 (setq files (org-add-archive-files files)))
19929 (while (setq f (pop extra))
19930 (unless (member (file-truename f) tnames)
19931 (add-to-list 'files f 'append)
19932 (add-to-list 'tnames (file-truename f) 'append)))
19933 (multi-occur
19934 (mapcar (lambda (x)
19935 (with-current-buffer
19936 (or (get-file-buffer x) (find-file-noselect x))
19937 (widen)
19938 (current-buffer)))
19939 files)
19940 regexp)))
19942 (if (boundp 'occur-mode-find-occurrence-hook)
19943 ;; Emacs 23
19944 (add-hook 'occur-mode-find-occurrence-hook
19945 (lambda ()
19946 (when (eq major-mode 'org-mode)
19947 (org-reveal))))
19948 ;; Emacs 22
19949 (defadvice occur-mode-goto-occurrence
19950 (after org-occur-reveal activate)
19951 (and (eq major-mode 'org-mode) (org-reveal)))
19952 (defadvice occur-mode-goto-occurrence-other-window
19953 (after org-occur-reveal activate)
19954 (and (eq major-mode 'org-mode) (org-reveal)))
19955 (defadvice occur-mode-display-occurrence
19956 (after org-occur-reveal activate)
19957 (when (eq major-mode 'org-mode)
19958 (let ((pos (occur-mode-find-occurrence)))
19959 (with-current-buffer (marker-buffer pos)
19960 (save-excursion
19961 (goto-char pos)
19962 (org-reveal)))))))
19964 (defun org-occur-link-in-agenda-files ()
19965 "Create a link and search for it in the agendas.
19966 The link is not stored in `org-stored-links', it is just created
19967 for the search purpose."
19968 (interactive)
19969 (let ((link (condition-case nil
19970 (org-store-link nil)
19971 (error "Unable to create a link to here"))))
19972 (org-occur-in-agenda-files (regexp-quote link))))
19974 (defun org-uniquify (list)
19975 "Remove duplicate elements from LIST."
19976 (let (res)
19977 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19978 res))
19980 (defun org-delete-all (elts list)
19981 "Remove all elements in ELTS from LIST."
19982 (while elts
19983 (setq list (delete (pop elts) list)))
19984 list)
19986 (defun org-count (cl-item cl-seq)
19987 "Count the number of occurrences of ITEM in SEQ.
19988 Taken from `count' in cl-seq.el with all keyword arguments removed."
19989 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19990 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19991 (while (< cl-start cl-end)
19992 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19993 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19994 (setq cl-start (1+ cl-start)))
19995 cl-count))
19997 (defun org-remove-if (predicate seq)
19998 "Remove everything from SEQ that fulfills PREDICATE."
19999 (let (res e)
20000 (while seq
20001 (setq e (pop seq))
20002 (if (not (funcall predicate e)) (push e res)))
20003 (nreverse res)))
20005 (defun org-remove-if-not (predicate seq)
20006 "Remove everything from SEQ that does not fulfill PREDICATE."
20007 (let (res e)
20008 (while seq
20009 (setq e (pop seq))
20010 (if (funcall predicate e) (push e res)))
20011 (nreverse res)))
20013 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20014 "Reduce two-argument FUNCTION across SEQ.
20015 Taken from `reduce' in cl-seq.el with all keyword arguments but
20016 \":initial-value\" removed."
20017 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20018 (cadr (memq :initial-value cl-keys)))
20019 (cl-seq (pop cl-seq))
20020 (t (funcall cl-func)))))
20021 (while cl-seq
20022 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20023 cl-accum))
20025 (defun org-back-over-empty-lines ()
20026 "Move backwards over whitespace, to the beginning of the first empty line.
20027 Returns the number of empty lines passed."
20028 (let ((pos (point)))
20029 (if (cdr (assoc 'heading org-blank-before-new-entry))
20030 (skip-chars-backward " \t\n\r")
20031 (unless (eobp)
20032 (forward-line -1)))
20033 (beginning-of-line 2)
20034 (goto-char (min (point) pos))
20035 (count-lines (point) pos)))
20037 (defun org-skip-whitespace ()
20038 (skip-chars-forward " \t\n\r"))
20040 (defun org-point-in-group (point group &optional context)
20041 "Check if POINT is in match-group GROUP.
20042 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20043 match. If the match group does not exist or point is not inside it,
20044 return nil."
20045 (and (match-beginning group)
20046 (>= point (match-beginning group))
20047 (<= point (match-end group))
20048 (if context
20049 (list context (match-beginning group) (match-end group))
20050 t)))
20052 (defun org-switch-to-buffer-other-window (&rest args)
20053 "Switch to buffer in a second window on the current frame.
20054 In particular, do not allow pop-up frames.
20055 Returns the newly created buffer."
20056 (let (pop-up-frames special-display-buffer-names special-display-regexps
20057 special-display-function)
20058 (apply 'switch-to-buffer-other-window args)))
20060 (defun org-combine-plists (&rest plists)
20061 "Create a single property list from all plists in PLISTS.
20062 The process starts by copying the first list, and then setting properties
20063 from the other lists. Settings in the last list are the most significant
20064 ones and overrule settings in the other lists."
20065 (let ((rtn (copy-sequence (pop plists)))
20066 p v ls)
20067 (while plists
20068 (setq ls (pop plists))
20069 (while ls
20070 (setq p (pop ls) v (pop ls))
20071 (setq rtn (plist-put rtn p v))))
20072 rtn))
20074 (defun org-move-line-down (arg)
20075 "Move the current line down. With prefix argument, move it past ARG lines."
20076 (interactive "p")
20077 (let ((col (current-column))
20078 beg end pos)
20079 (beginning-of-line 1) (setq beg (point))
20080 (beginning-of-line 2) (setq end (point))
20081 (beginning-of-line (+ 1 arg))
20082 (setq pos (move-marker (make-marker) (point)))
20083 (insert (delete-and-extract-region beg end))
20084 (goto-char pos)
20085 (org-move-to-column col)))
20087 (defun org-move-line-up (arg)
20088 "Move the current line up. With prefix argument, move it past ARG lines."
20089 (interactive "p")
20090 (let ((col (current-column))
20091 beg end pos)
20092 (beginning-of-line 1) (setq beg (point))
20093 (beginning-of-line 2) (setq end (point))
20094 (beginning-of-line (- arg))
20095 (setq pos (move-marker (make-marker) (point)))
20096 (insert (delete-and-extract-region beg end))
20097 (goto-char pos)
20098 (org-move-to-column col)))
20100 (defun org-replace-escapes (string table)
20101 "Replace %-escapes in STRING with values in TABLE.
20102 TABLE is an association list with keys like \"%a\" and string values.
20103 The sequences in STRING may contain normal field width and padding information,
20104 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20105 so values can contain further %-escapes if they are define later in TABLE."
20106 (let ((tbl (copy-alist table))
20107 (case-fold-search nil)
20108 (pchg 0)
20109 e re rpl)
20110 (while (setq e (pop tbl))
20111 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20112 (when (and (cdr e) (string-match re (cdr e)))
20113 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20114 (safe "SREF"))
20115 (add-text-properties 0 3 (list 'sref sref) safe)
20116 (setcdr e (replace-match safe t t (cdr e)))))
20117 (while (string-match re string)
20118 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20119 (cdr e)))
20120 (setq string (replace-match rpl t t string))))
20121 (while (setq pchg (next-property-change pchg string))
20122 (let ((sref (get-text-property pchg 'sref string)))
20123 (when (and sref (string-match "SREF" string pchg))
20124 (setq string (replace-match sref t t string)))))
20125 string))
20127 (defun org-sublist (list start end)
20128 "Return a section of LIST, from START to END.
20129 Counting starts at 1."
20130 (let (rtn (c start))
20131 (setq list (nthcdr (1- start) list))
20132 (while (and list (<= c end))
20133 (push (pop list) rtn)
20134 (setq c (1+ c)))
20135 (nreverse rtn)))
20137 (defun org-find-base-buffer-visiting (file)
20138 "Like `find-buffer-visiting' but always return the base buffer and
20139 not an indirect buffer."
20140 (let ((buf (or (get-file-buffer file)
20141 (find-buffer-visiting file))))
20142 (if buf
20143 (or (buffer-base-buffer buf) buf)
20144 nil)))
20146 (defun org-image-file-name-regexp (&optional extensions)
20147 "Return regexp matching the file names of images.
20148 If EXTENSIONS is given, only match these."
20149 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20150 (image-file-name-regexp)
20151 (let ((image-file-name-extensions
20152 (or extensions
20153 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20154 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20155 (concat "\\."
20156 (regexp-opt (nconc (mapcar 'upcase
20157 image-file-name-extensions)
20158 image-file-name-extensions)
20160 "\\'"))))
20162 (defun org-file-image-p (file &optional extensions)
20163 "Return non-nil if FILE is an image."
20164 (save-match-data
20165 (string-match (org-image-file-name-regexp extensions) file)))
20167 (defun org-get-cursor-date ()
20168 "Return the date at cursor in as a time.
20169 This works in the calendar and in the agenda, anywhere else it just
20170 returns the current time."
20171 (let (date day defd)
20172 (cond
20173 ((eq major-mode 'calendar-mode)
20174 (setq date (calendar-cursor-to-date)
20175 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20176 ((eq major-mode 'org-agenda-mode)
20177 (setq day (get-text-property (point) 'day))
20178 (if day
20179 (setq date (calendar-gregorian-from-absolute day)
20180 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20181 (nth 2 date))))))
20182 (or defd (current-time))))
20184 (defvar org-agenda-action-marker (make-marker)
20185 "Marker pointing to the entry for the next agenda action.")
20187 (defun org-mark-entry-for-agenda-action ()
20188 "Mark the current entry as target of an agenda action.
20189 Agenda actions are actions executed from the agenda with the key `k',
20190 which make use of the date at the cursor."
20191 (interactive)
20192 (move-marker org-agenda-action-marker
20193 (save-excursion (org-back-to-heading t) (point))
20194 (current-buffer))
20195 (message
20196 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20198 (defun org-mark-subtree ()
20199 "Mark the current subtree.
20200 This puts point at the start of the current subtree, and mark at the end.
20202 If point is in an inline task, mark that task instead."
20203 (interactive)
20204 (let ((inline-task-p
20205 (and (featurep 'org-inlinetask)
20206 (org-inlinetask-in-task-p)))
20207 (beg))
20208 ;; Get beginning of subtree
20209 (cond
20210 (inline-task-p (org-inlinetask-goto-beginning))
20211 ((org-at-heading-p) (beginning-of-line))
20212 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20213 (setq beg (point))
20214 ;; Get end of it
20215 (if inline-task-p
20216 (org-inlinetask-goto-end)
20217 (org-end-of-subtree))
20218 ;; Mark zone
20219 (push-mark (point) nil t)
20220 (goto-char beg)))
20222 ;;; Paragraph filling stuff.
20223 ;; We want this to be just right, so use the full arsenal.
20225 (defun org-indent-line-function ()
20226 "Indent line depending on context."
20227 (interactive)
20228 (let* ((pos (point))
20229 (itemp (org-at-item-p))
20230 (case-fold-search t)
20231 (org-drawer-regexp (or org-drawer-regexp "\000"))
20232 (inline-task-p (and (featurep 'org-inlinetask)
20233 (org-inlinetask-in-task-p)))
20234 (inline-re (and inline-task-p
20235 (org-inlinetask-outline-regexp)))
20236 column)
20237 (beginning-of-line 1)
20238 (cond
20239 ;; Comments
20240 ((looking-at "# ") (setq column 0))
20241 ;; Headings
20242 ((looking-at org-outline-regexp) (setq column 0))
20243 ;; Included files
20244 ((looking-at "#\\+include:") (setq column 0))
20245 ;; Footnote definition
20246 ((looking-at org-footnote-definition-re) (setq column 0))
20247 ;; Literal examples
20248 ((looking-at "[ \t]*:\\( \\|$\\)")
20249 (setq column (org-get-indentation))) ; do nothing
20250 ;; Lists
20251 ((ignore-errors (goto-char (org-in-item-p)))
20252 (setq column (if itemp
20253 (org-get-indentation)
20254 (org-list-item-body-column (point))))
20255 (goto-char pos))
20256 ;; Drawers
20257 ((and (looking-at "[ \t]*:END:")
20258 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20259 (save-excursion
20260 (goto-char (1- (match-beginning 1)))
20261 (setq column (current-column))))
20262 ;; Special blocks
20263 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20264 (save-excursion
20265 (re-search-backward
20266 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20267 (setq column (org-get-indentation (match-string 0))))
20268 ((and (not (looking-at "[ \t]*#\\+begin_"))
20269 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20270 (save-excursion
20271 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20272 (setq column
20273 (cond ((equal (downcase (match-string 1)) "src")
20274 ;; src blocks: let `org-edit-src-exit' handle them
20275 (org-get-indentation))
20276 ((equal (downcase (match-string 1)) "example")
20277 (max (org-get-indentation)
20278 (org-get-indentation (match-string 0))))
20280 (org-get-indentation (match-string 0))))))
20281 ;; This line has nothing special, look at the previous relevant
20282 ;; line to compute indentation
20284 (beginning-of-line 0)
20285 (while (and (not (bobp))
20286 (not (looking-at org-drawer-regexp))
20287 ;; When point started in an inline task, do not move
20288 ;; above task starting line.
20289 (not (and inline-task-p (looking-at inline-re)))
20290 ;; Skip drawers, blocks, empty lines, verbatim,
20291 ;; comments, tables, footnotes definitions, lists,
20292 ;; inline tasks.
20293 (or (and (looking-at "[ \t]*:END:")
20294 (re-search-backward org-drawer-regexp nil t))
20295 (and (looking-at "[ \t]*#\\+end_")
20296 (re-search-backward "[ \t]*#\\+begin_"nil t))
20297 (looking-at "[ \t]*[\n:#|]")
20298 (looking-at org-footnote-definition-re)
20299 (and (ignore-errors (goto-char (org-in-item-p)))
20300 (goto-char
20301 (org-list-get-top-point (org-list-struct))))
20302 (and (not inline-task-p)
20303 (featurep 'org-inlinetask)
20304 (org-inlinetask-in-task-p)
20305 (or (org-inlinetask-goto-beginning) t))))
20306 (beginning-of-line 0))
20307 (cond
20308 ;; There was an heading above.
20309 ((looking-at "\\*+[ \t]+")
20310 (if (not org-adapt-indentation)
20311 (setq column 0)
20312 (goto-char (match-end 0))
20313 (setq column (current-column))))
20314 ;; A drawer had started and is unfinished
20315 ((looking-at org-drawer-regexp)
20316 (goto-char (1- (match-beginning 1)))
20317 (setq column (current-column)))
20318 ;; Else, nothing noticeable found: get indentation and go on.
20319 (t (setq column (org-get-indentation))))))
20320 ;; Now apply indentation and move cursor accordingly
20321 (goto-char pos)
20322 (if (<= (current-column) (current-indentation))
20323 (org-indent-line-to column)
20324 (save-excursion (org-indent-line-to column)))
20325 ;; Special polishing for properties, see `org-property-format'
20326 (setq column (current-column))
20327 (beginning-of-line 1)
20328 (if (looking-at
20329 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20330 (replace-match (concat (match-string 1)
20331 (format org-property-format
20332 (match-string 2) (match-string 3)))
20333 t t))
20334 (org-move-to-column column)))
20336 (defun org-indent-drawer ()
20337 "Indent the drawer at point."
20338 (interactive)
20339 (let ((p (point))
20340 (e (and (save-excursion (re-search-forward ":END:" nil t))
20341 (match-end 0)))
20342 (folded
20343 (save-excursion
20344 (end-of-line)
20345 (when (overlays-at (point))
20346 (member 'invisible (overlay-properties
20347 (car (overlays-at (point)))))))))
20348 (when folded (org-cycle))
20349 (indent-for-tab-command)
20350 (while (and (move-beginning-of-line 2) (< (point) e))
20351 (indent-for-tab-command))
20352 (goto-char p)
20353 (when folded (org-cycle)))
20354 (message "Drawer at point indented"))
20356 (defun org-indent-block ()
20357 "Indent the block at point."
20358 (interactive)
20359 (let ((p (point))
20360 (case-fold-search t)
20361 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20362 (match-end 0)))
20363 (folded
20364 (save-excursion
20365 (end-of-line)
20366 (when (overlays-at (point))
20367 (member 'invisible (overlay-properties
20368 (car (overlays-at (point)))))))))
20369 (when folded (org-cycle))
20370 (indent-for-tab-command)
20371 (while (and (move-beginning-of-line 2) (< (point) e))
20372 (indent-for-tab-command))
20373 (goto-char p)
20374 (when folded (org-cycle)))
20375 (message "Block at point indented"))
20377 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20378 "Variable to store copy of `adaptive-fill-regexp'.
20379 Since `adaptive-fill-regexp' is set to never match, we need to
20380 store a backup of its value before entering `org-mode' so that
20381 the functionality can be provided as a fall-back.")
20383 (defun org-set-autofill-regexps ()
20384 (interactive)
20385 ;; In the paragraph separator we include headlines, because filling
20386 ;; text in a line directly attached to a headline would otherwise
20387 ;; fill the headline as well.
20388 (org-set-local 'comment-start-skip "^#+[ \t]*")
20389 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20390 ;; The paragraph starter includes hand-formatted lists.
20391 (org-set-local
20392 'paragraph-start
20393 (concat
20394 "\f" "\\|"
20395 "[ ]*$" "\\|"
20396 org-outline-regexp "\\|"
20397 "[ \t]*#" "\\|"
20398 (org-item-re) "\\|"
20399 "[ \t]*[:|]" "\\|"
20400 "\\$\\$" "\\|"
20401 "\\\\\\(begin\\|end\\|[][]\\)"))
20402 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20403 ;; But only if the user has not turned off tables or fixed-width regions
20404 (org-set-local
20405 'auto-fill-inhibit-regexp
20406 (concat org-outline-regexp
20407 "\\|#\\+"
20408 "\\|[ \t]*" org-keyword-time-regexp
20409 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20410 (concat
20411 "\\|[ \t]*["
20412 (if org-enable-table-editor "|" "")
20413 (if org-enable-fixed-width-editor ":" "")
20414 "]"))))
20415 ;; We use our own fill-paragraph function, to make sure that tables
20416 ;; and fixed-width regions are not wrapped. That function will pass
20417 ;; through to `fill-paragraph' when appropriate.
20418 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20419 ;; Prevent auto-fill from inserting unwanted new items.
20420 (if (boundp 'fill-nobreak-predicate)
20421 (org-set-local
20422 'fill-nobreak-predicate
20423 (org-uniquify
20424 (append fill-nobreak-predicate
20425 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20426 ;; Adaptive filling: To get full control, first make sure that
20427 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20428 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20429 (org-set-local 'org-adaptive-fill-regexp-backup
20430 adaptive-fill-regexp))
20431 (org-set-local 'adaptive-fill-regexp "\000")
20432 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20433 (org-set-local 'adaptive-fill-function
20434 'org-adaptive-fill-function)
20435 (org-set-local
20436 'align-mode-rules-list
20437 '((org-in-buffer-settings
20438 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20439 (modes . '(org-mode))))))
20441 (defun org-fill-item-nobreak-p ()
20442 "Non-nil when a line break at point would insert a new item."
20443 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20445 (defun org-fill-line-break-nobreak-p ()
20446 "Non-nil when a line break at point would create an Org line break."
20447 (save-excursion
20448 (skip-chars-backward "[ \t]")
20449 (skip-chars-backward "\\\\")
20450 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20452 (defun org-fill-paragraph (&optional justify)
20453 "Re-align a table, pass through to fill-paragraph if no table."
20454 (let ((table-p (org-at-table-p))
20455 (table.el-p (org-at-table.el-p))
20456 (itemp (org-in-item-p)))
20457 (cond ((and (equal (char-after (point-at-bol)) ?*)
20458 (save-excursion (goto-char (point-at-bol))
20459 (looking-at org-outline-regexp)))
20460 t) ; skip headlines
20461 (table.el-p t) ; skip table.el tables
20462 (table-p (org-table-align) t) ; align Org tables
20463 (itemp ; align text in items
20464 (let* ((struct (save-excursion (goto-char itemp)
20465 (org-list-struct)))
20466 (parents (org-list-parents-alist struct))
20467 (children (org-list-get-children itemp struct parents))
20468 beg end prev next prefix)
20469 ;; Determine in which part of item point is: before
20470 ;; first child, after last child, between two
20471 ;; sub-lists, or simply in item if there's no child.
20472 (cond
20473 ((not children)
20474 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20475 beg itemp
20476 end (org-list-get-item-end itemp struct)))
20477 ((< (point) (setq next (car children)))
20478 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20479 beg itemp
20480 end next))
20481 ((> (point) (setq prev (car (last children))))
20482 (setq beg (org-list-get-item-end prev struct)
20483 end (org-list-get-item-end itemp struct)
20484 prefix (save-excursion
20485 (goto-char beg)
20486 (skip-chars-forward " \t")
20487 (make-string (current-column) ?\ ))))
20488 (t (catch 'exit
20489 (while (setq next (pop children))
20490 (if (> (point) next)
20491 (setq prev next)
20492 (setq beg (org-list-get-item-end prev struct)
20493 end next
20494 prefix (save-excursion
20495 (goto-char beg)
20496 (skip-chars-forward " \t")
20497 (make-string (current-column) ?\ )))
20498 (throw 'exit nil))))))
20499 ;; Use `fill-paragraph' with buffer narrowed to item
20500 ;; without any child, and with our computed PREFIX.
20501 (flet ((fill-context-prefix (from to &optional flr) prefix))
20502 (save-restriction
20503 (narrow-to-region beg end)
20504 (save-excursion (fill-paragraph justify)))) t))
20505 ;; Special case where point is not in a list but is on
20506 ;; a paragraph adjacent to a list: make sure this paragraph
20507 ;; doesn't get merged with the end of the list by narrowing
20508 ;; buffer first.
20509 ((save-excursion (forward-paragraph -1)
20510 (setq itemp (org-in-item-p)))
20511 (let ((struct (save-excursion (goto-char itemp)
20512 (org-list-struct))))
20513 (save-restriction
20514 (narrow-to-region (org-list-get-bottom-point struct)
20515 (save-excursion (forward-paragraph 1)
20516 (point)))
20517 (fill-paragraph justify) t)))
20518 ;; Else simply call `fill-paragraph'.
20519 (t nil))))
20521 ;; For reference, this is the default value of adaptive-fill-regexp
20522 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20524 (defun org-adaptive-fill-function ()
20525 "Return a fill prefix for org-mode files."
20526 (let (itemp)
20527 (save-excursion
20528 (cond
20529 ;; Comment line
20530 ((looking-at "#[ \t]+")
20531 (match-string-no-properties 0))
20532 ;; Plain list item
20533 ((org-at-item-p)
20534 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20535 ;; Point is in a list after `backward-paragraph': original
20536 ;; point wasn't in the list, or filling would have been taken
20537 ;; care of by `org-auto-fill-function', but the list and the
20538 ;; real paragraph are not separated by a blank line. Thus, move
20539 ;; point after the list to go back to real paragraph and
20540 ;; determine fill-prefix.
20541 ((setq itemp (org-in-item-p))
20542 (goto-char itemp)
20543 (let* ((struct (org-list-struct))
20544 (bottom (org-list-get-bottom-point struct)))
20545 (goto-char bottom)
20546 (make-string (org-get-indentation) ?\ )))
20547 ;; Other text
20548 ((looking-at org-adaptive-fill-regexp-backup)
20549 (match-string-no-properties 0))))))
20551 (defun org-auto-fill-function ()
20552 "Auto-fill function."
20553 (let (itemp prefix)
20554 ;; When in a list, compute an appropriate fill-prefix and make
20555 ;; sure it will be used by `do-auto-fill'.
20556 (if (setq itemp (org-in-item-p))
20557 (progn
20558 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20559 (flet ((fill-context-prefix (from to &optional flr) prefix))
20560 (do-auto-fill)))
20561 ;; Else just use `do-auto-fill'.
20562 (do-auto-fill))))
20564 ;;; Other stuff.
20566 (defun org-toggle-fixed-width-section (arg)
20567 "Toggle the fixed-width export.
20568 If there is no active region, the QUOTE keyword at the current headline is
20569 inserted or removed. When present, it causes the text between this headline
20570 and the next to be exported as fixed-width text, and unmodified.
20571 If there is an active region, this command adds or removes a colon as the
20572 first character of this line. If the first character of a line is a colon,
20573 this line is also exported in fixed-width font."
20574 (interactive "P")
20575 (let* ((cc 0)
20576 (regionp (org-region-active-p))
20577 (beg (if regionp (region-beginning) (point)))
20578 (end (if regionp (region-end)))
20579 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20580 (case-fold-search nil)
20581 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20582 off)
20583 (if regionp
20584 (save-excursion
20585 (goto-char beg)
20586 (setq cc (current-column))
20587 (beginning-of-line 1)
20588 (setq off (looking-at re))
20589 (while (> nlines 0)
20590 (setq nlines (1- nlines))
20591 (beginning-of-line 1)
20592 (cond
20593 (arg
20594 (org-move-to-column cc t)
20595 (insert ": \n")
20596 (forward-line -1))
20597 ((and off (looking-at re))
20598 (replace-match "" t t nil 1))
20599 ((not off) (org-move-to-column cc t) (insert ": ")))
20600 (forward-line 1)))
20601 (save-excursion
20602 (org-back-to-heading)
20603 (cond
20604 ((looking-at (format org-heading-keyword-regexp-format
20605 org-quote-string))
20606 (goto-char (match-end 1))
20607 (looking-at (concat " +" org-quote-string))
20608 (replace-match "" t t)
20609 (when (eolp) (insert " ")))
20610 ((looking-at org-outline-regexp)
20611 (goto-char (match-end 0))
20612 (insert org-quote-string " ")))))))
20614 (defun org-reftex-citation ()
20615 "Use reftex-citation to insert a citation into the buffer.
20616 This looks for a line like
20618 #+BIBLIOGRAPHY: foo plain option:-d
20620 and derives from it that foo.bib is the bibliography file relevant
20621 for this document. It then installs the necessary environment for RefTeX
20622 to work in this buffer and calls `reftex-citation' to insert a citation
20623 into the buffer.
20625 Export of such citations to both LaTeX and HTML is handled by the contributed
20626 package org-exp-bibtex by Taru Karttunen."
20627 (interactive)
20628 (let ((reftex-docstruct-symbol 'rds)
20629 (reftex-cite-format "\\cite{%l}")
20630 rds bib)
20631 (save-excursion
20632 (save-restriction
20633 (widen)
20634 (let ((case-fold-search t)
20635 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20636 (if (not (save-excursion
20637 (or (re-search-forward re nil t)
20638 (re-search-backward re nil t))))
20639 (error "No bibliography defined in file")
20640 (setq bib (concat (match-string 1) ".bib")
20641 rds (list (list 'bib bib)))))))
20642 (call-interactively 'reftex-citation)))
20644 ;;;; Functions extending outline functionality
20646 (defun org-beginning-of-line (&optional arg)
20647 "Go to the beginning of the current line. If that is invisible, continue
20648 to a visible line beginning. This makes the function of C-a more intuitive.
20649 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20650 first attempt, and only move to after the tags when the cursor is already
20651 beyond the end of the headline."
20652 (interactive "P")
20653 (let ((pos (point))
20654 (special (if (consp org-special-ctrl-a/e)
20655 (car org-special-ctrl-a/e)
20656 org-special-ctrl-a/e))
20657 refpos)
20658 (if (org-bound-and-true-p line-move-visual)
20659 (beginning-of-visual-line 1)
20660 (beginning-of-line 1))
20661 (if (and arg (fboundp 'move-beginning-of-line))
20662 (call-interactively 'move-beginning-of-line)
20663 (if (bobp)
20665 (backward-char 1)
20666 (if (org-truely-invisible-p)
20667 (while (and (not (bobp)) (org-truely-invisible-p))
20668 (backward-char 1)
20669 (beginning-of-line 1))
20670 (forward-char 1))))
20671 (when special
20672 (cond
20673 ((and (looking-at org-complex-heading-regexp)
20674 (= (char-after (match-end 1)) ?\ ))
20675 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20676 (point-at-eol)))
20677 (goto-char
20678 (if (eq special t)
20679 (cond ((> pos refpos) refpos)
20680 ((= pos (point)) refpos)
20681 (t (point)))
20682 (cond ((> pos (point)) (point))
20683 ((not (eq last-command this-command)) (point))
20684 (t refpos)))))
20685 ((org-at-item-p)
20686 ;; Being at an item and not looking at an the item means point
20687 ;; was previously moved to beginning of a visual line, whiche
20688 ;; doesn't contain the item. Therefore, do nothing special,
20689 ;; just stay here.
20690 (when (looking-at org-list-full-item-re)
20691 ;; Set special position at first white space character after
20692 ;; bullet, and check-box, if any.
20693 (let ((after-bullet
20694 (let ((box (match-end 3)))
20695 (if (not box) (match-end 1)
20696 (let ((after (char-after box)))
20697 (if (and after (= after ? )) (1+ box) box))))))
20698 ;; Special case: Move point to special position when
20699 ;; currently after it or at beginning of line.
20700 (if (eq special t)
20701 (when (or (> pos after-bullet) (= (point) pos))
20702 (goto-char after-bullet))
20703 ;; Reversed case: Move point to special position when
20704 ;; point was already at beginning of line and command is
20705 ;; repeated.
20706 (when (and (= (point) pos) (eq last-command this-command))
20707 (goto-char after-bullet))))))))
20708 (org-no-warnings
20709 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20711 (defun org-end-of-line (&optional arg)
20712 "Go to the end of the line.
20713 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20714 first attempt, and only move to after the tags when the cursor is already
20715 beyond the end of the headline."
20716 (interactive "P")
20717 (let ((special (if (consp org-special-ctrl-a/e)
20718 (cdr org-special-ctrl-a/e)
20719 org-special-ctrl-a/e)))
20720 (cond
20721 ((or (not special) arg
20722 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20723 (call-interactively
20724 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20725 ((fboundp 'move-end-of-line) 'move-end-of-line)
20726 (t 'end-of-line))))
20727 ((org-at-heading-p)
20728 (let ((pos (point)))
20729 (beginning-of-line 1)
20730 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20731 (if (eq special t)
20732 (if (or (< pos (match-beginning 1))
20733 (= pos (match-end 0)))
20734 (goto-char (match-beginning 1))
20735 (goto-char (match-end 0)))
20736 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20737 (goto-char (match-end 0))
20738 (goto-char (match-beginning 1))))
20739 (call-interactively (if (fboundp 'move-end-of-line)
20740 'move-end-of-line
20741 'end-of-line)))))
20742 ((org-at-drawer-p)
20743 (move-end-of-line 1)
20744 (when (overlays-at (1- (point))) (backward-char 1)))
20745 ;; At an item: Move before any hidden text.
20746 (t (call-interactively
20747 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20748 ((fboundp 'move-end-of-line) 'move-end-of-line)
20749 (t 'end-of-line)))))
20750 (org-no-warnings
20751 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20753 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20754 (define-key org-mode-map "\C-e" 'org-end-of-line)
20756 (defun org-backward-sentence (&optional arg)
20757 "Go to beginning of sentence, or beginning of table field.
20758 This will call `backward-sentence' or `org-table-beginning-of-field',
20759 depending on context."
20760 (interactive "P")
20761 (cond
20762 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20763 (t (call-interactively 'backward-sentence))))
20765 (defun org-forward-sentence (&optional arg)
20766 "Go to end of sentence, or end of table field.
20767 This will call `forward-sentence' or `org-table-end-of-field',
20768 depending on context."
20769 (interactive "P")
20770 (cond
20771 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20772 (t (call-interactively 'forward-sentence))))
20774 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20775 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20777 (defun org-kill-line (&optional arg)
20778 "Kill line, to tags or end of line."
20779 (interactive "P")
20780 (cond
20781 ((or (not org-special-ctrl-k)
20782 (bolp)
20783 (not (org-at-heading-p)))
20784 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20785 org-ctrl-k-protect-subtree)
20786 (if (or (eq org-ctrl-k-protect-subtree 'error)
20787 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20788 (error "C-k aborted - would kill hidden subtree")))
20789 (call-interactively
20790 (if visual-line-mode 'kill-visual-line 'kill-line)))
20791 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20792 (kill-region (point) (match-beginning 1))
20793 (org-set-tags nil t))
20794 (t (kill-region (point) (point-at-eol)))))
20796 (define-key org-mode-map "\C-k" 'org-kill-line)
20798 (defun org-yank (&optional arg)
20799 "Yank. If the kill is a subtree, treat it specially.
20800 This command will look at the current kill and check if is a single
20801 subtree, or a series of subtrees[1]. If it passes the test, and if the
20802 cursor is at the beginning of a line or after the stars of a currently
20803 empty headline, then the yank is handled specially. How exactly depends
20804 on the value of the following variables, both set by default.
20806 org-yank-folded-subtrees
20807 When set, the subtree(s) will be folded after insertion, but only
20808 if doing so would now swallow text after the yanked text.
20810 org-yank-adjusted-subtrees
20811 When set, the subtree will be promoted or demoted in order to
20812 fit into the local outline tree structure, which means that the level
20813 will be adjusted so that it becomes the smaller one of the two
20814 *visible* surrounding headings.
20816 Any prefix to this command will cause `yank' to be called directly with
20817 no special treatment. In particular, a simple \\[universal-argument] prefix \
20818 will just
20819 plainly yank the text as it is.
20821 \[1] The test checks if the first non-white line is a heading
20822 and if there are no other headings with fewer stars."
20823 (interactive "P")
20824 (org-yank-generic 'yank arg))
20826 (defun org-yank-generic (command arg)
20827 "Perform some yank-like command.
20829 This function implements the behavior described in the `org-yank'
20830 documentation. However, it has been generalized to work for any
20831 interactive command with similar behavior."
20833 ;; pretend to be command COMMAND
20834 (setq this-command command)
20836 (if arg
20837 (call-interactively command)
20839 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20840 (and (org-kill-is-subtree-p)
20841 (or (bolp)
20842 (and (looking-at "[ \t]*$")
20843 (string-match
20844 "\\`\\*+\\'"
20845 (buffer-substring (point-at-bol) (point)))))))
20846 swallowp)
20847 (cond
20848 ((and subtreep org-yank-folded-subtrees)
20849 (let ((beg (point))
20850 end)
20851 (if (and subtreep org-yank-adjusted-subtrees)
20852 (org-paste-subtree nil nil 'for-yank)
20853 (call-interactively command))
20855 (setq end (point))
20856 (goto-char beg)
20857 (when (and (bolp) subtreep
20858 (not (setq swallowp
20859 (org-yank-folding-would-swallow-text beg end))))
20860 (org-with-limited-levels
20861 (or (looking-at org-outline-regexp)
20862 (re-search-forward org-outline-regexp-bol end t))
20863 (while (and (< (point) end) (looking-at org-outline-regexp))
20864 (hide-subtree)
20865 (org-cycle-show-empty-lines 'folded)
20866 (condition-case nil
20867 (outline-forward-same-level 1)
20868 (error (goto-char end))))))
20869 (when swallowp
20870 (message
20871 "Inserted text not folded because that would swallow text"))
20873 (goto-char end)
20874 (skip-chars-forward " \t\n\r")
20875 (beginning-of-line 1)
20876 (push-mark beg 'nomsg)))
20877 ((and subtreep org-yank-adjusted-subtrees)
20878 (let ((beg (point-at-bol)))
20879 (org-paste-subtree nil nil 'for-yank)
20880 (push-mark beg 'nomsg)))
20882 (call-interactively command))))))
20884 (defun org-yank-folding-would-swallow-text (beg end)
20885 "Would hide-subtree at BEG swallow any text after END?"
20886 (let (level)
20887 (org-with-limited-levels
20888 (save-excursion
20889 (goto-char beg)
20890 (when (or (looking-at org-outline-regexp)
20891 (re-search-forward org-outline-regexp-bol end t))
20892 (setq level (org-outline-level)))
20893 (goto-char end)
20894 (skip-chars-forward " \t\r\n\v\f")
20895 (if (or (eobp)
20896 (and (bolp) (looking-at org-outline-regexp)
20897 (<= (org-outline-level) level)))
20898 nil ; Nothing would be swallowed
20899 t))))) ; something would swallow
20901 (define-key org-mode-map "\C-y" 'org-yank)
20903 (defun org-truely-invisible-p ()
20904 "Check if point is at a character currently not visible.
20905 This version does not only check the character property, but also
20906 `visible-mode'."
20907 ;; Early versions of noutline don't have `outline-invisible-p'.
20908 (if (org-bound-and-true-p visible-mode)
20910 (outline-invisible-p)))
20912 (defun org-invisible-p2 ()
20913 "Check if point is at a character currently not visible."
20914 (save-excursion
20915 (if (and (eolp) (not (bobp))) (backward-char 1))
20916 ;; Early versions of noutline don't have `outline-invisible-p'.
20917 (outline-invisible-p)))
20919 (defun org-back-to-heading (&optional invisible-ok)
20920 "Call `outline-back-to-heading', but provide a better error message."
20921 (condition-case nil
20922 (outline-back-to-heading invisible-ok)
20923 (error (error "Before first headline at position %d in buffer %s"
20924 (point) (current-buffer)))))
20926 (defun org-beginning-of-defun ()
20927 "Go to the beginning of the subtree, i.e. back to the heading."
20928 (org-back-to-heading))
20929 (defun org-end-of-defun ()
20930 "Go to the end of the subtree."
20931 (org-end-of-subtree nil t))
20933 (defun org-before-first-heading-p ()
20934 "Before first heading?"
20935 (save-excursion
20936 (end-of-line)
20937 (null (re-search-backward org-outline-regexp-bol nil t))))
20939 (defun org-at-heading-p (&optional ignored)
20940 (outline-on-heading-p t))
20941 ;; Compatibility alias with Org versions < 7.8.03
20942 (defalias 'org-on-heading-p 'org-at-heading-p)
20944 (defun org-at-drawer-p nil
20945 "Is cursor at a drawer keyword?"
20946 (save-excursion
20947 (move-beginning-of-line 1)
20948 (looking-at org-drawer-regexp)))
20950 (defun org-at-block-p nil
20951 "Is cursor at a block keyword?"
20952 (save-excursion
20953 (move-beginning-of-line 1)
20954 (looking-at org-block-regexp)))
20956 (defun org-point-at-end-of-empty-headline ()
20957 "If point is at the end of an empty headline, return t, else nil.
20958 If the heading only contains a TODO keyword, it is still still considered
20959 empty."
20960 (and (looking-at "[ \t]*$")
20961 (save-excursion
20962 (beginning-of-line 1)
20963 (let ((case-fold-search nil))
20964 (looking-at org-todo-line-regexp)))
20965 (string= (match-string 3) "")))
20967 (defun org-at-heading-or-item-p ()
20968 (or (org-at-heading-p) (org-at-item-p)))
20970 (defun org-at-target-p ()
20971 (or (org-in-regexp org-radio-target-regexp)
20972 (org-in-regexp org-target-regexp)))
20973 ;; Compatibility alias with Org versions < 7.8.03
20974 (defalias 'org-on-target-p 'org-at-target-p)
20976 (defun org-up-heading-all (arg)
20977 "Move to the heading line of which the present line is a subheading.
20978 This function considers both visible and invisible heading lines.
20979 With argument, move up ARG levels."
20980 (if (fboundp 'outline-up-heading-all)
20981 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20982 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20984 (defun org-up-heading-safe ()
20985 "Move to the heading line of which the present line is a subheading.
20986 This version will not throw an error. It will return the level of the
20987 headline found, or nil if no higher level is found.
20989 Also, this function will be a lot faster than `outline-up-heading',
20990 because it relies on stars being the outline starters. This can really
20991 make a significant difference in outlines with very many siblings."
20992 (let (start-level re)
20993 (org-back-to-heading t)
20994 (setq start-level (funcall outline-level))
20995 (if (equal start-level 1)
20997 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20998 (if (re-search-backward re nil t)
20999 (funcall outline-level)))))
21001 (defun org-first-sibling-p ()
21002 "Is this heading the first child of its parents?"
21003 (interactive)
21004 (let ((re org-outline-regexp-bol)
21005 level l)
21006 (unless (org-at-heading-p t)
21007 (error "Not at a heading"))
21008 (setq level (funcall outline-level))
21009 (save-excursion
21010 (if (not (re-search-backward re nil t))
21012 (setq l (funcall outline-level))
21013 (< l level)))))
21015 (defun org-goto-sibling (&optional previous)
21016 "Goto the next sibling, even if it is invisible.
21017 When PREVIOUS is set, go to the previous sibling instead. Returns t
21018 when a sibling was found. When none is found, return nil and don't
21019 move point."
21020 (let ((fun (if previous 're-search-backward 're-search-forward))
21021 (pos (point))
21022 (re org-outline-regexp-bol)
21023 level l)
21024 (when (condition-case nil (org-back-to-heading t) (error nil))
21025 (setq level (funcall outline-level))
21026 (catch 'exit
21027 (or previous (forward-char 1))
21028 (while (funcall fun re nil t)
21029 (setq l (funcall outline-level))
21030 (when (< l level) (goto-char pos) (throw 'exit nil))
21031 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21032 (goto-char pos)
21033 nil))))
21035 (defun org-show-siblings ()
21036 "Show all siblings of the current headline."
21037 (save-excursion
21038 (while (org-goto-sibling) (org-flag-heading nil)))
21039 (save-excursion
21040 (while (org-goto-sibling 'previous)
21041 (org-flag-heading nil))))
21043 (defun org-goto-first-child ()
21044 "Goto the first child, even if it is invisible.
21045 Return t when a child was found. Otherwise don't move point and
21046 return nil."
21047 (let (level (pos (point)) (re org-outline-regexp-bol))
21048 (when (condition-case nil (org-back-to-heading t) (error nil))
21049 (setq level (outline-level))
21050 (forward-char 1)
21051 (if (and (re-search-forward re nil t) (> (outline-level) level))
21052 (progn (goto-char (match-beginning 0)) t)
21053 (goto-char pos) nil))))
21055 (defun org-show-hidden-entry ()
21056 "Show an entry where even the heading is hidden."
21057 (save-excursion
21058 (org-show-entry)))
21060 (defun org-flag-heading (flag &optional entry)
21061 "Flag the current heading. FLAG non-nil means make invisible.
21062 When ENTRY is non-nil, show the entire entry."
21063 (save-excursion
21064 (org-back-to-heading t)
21065 ;; Check if we should show the entire entry
21066 (if entry
21067 (progn
21068 (org-show-entry)
21069 (save-excursion
21070 (and (outline-next-heading)
21071 (org-flag-heading nil))))
21072 (outline-flag-region (max (point-min) (1- (point)))
21073 (save-excursion (outline-end-of-heading) (point))
21074 flag))))
21076 (defun org-get-next-sibling ()
21077 "Move to next heading of the same level, and return point.
21078 If there is no such heading, return nil.
21079 This is like outline-next-sibling, but invisible headings are ok."
21080 (let ((level (funcall outline-level)))
21081 (outline-next-heading)
21082 (while (and (not (eobp)) (> (funcall outline-level) level))
21083 (outline-next-heading))
21084 (if (or (eobp) (< (funcall outline-level) level))
21086 (point))))
21088 (defun org-get-last-sibling ()
21089 "Move to previous heading of the same level, and return point.
21090 If there is no such heading, return nil."
21091 (let ((opoint (point))
21092 (level (funcall outline-level)))
21093 (outline-previous-heading)
21094 (when (and (/= (point) opoint) (outline-on-heading-p t))
21095 (while (and (> (funcall outline-level) level)
21096 (not (bobp)))
21097 (outline-previous-heading))
21098 (if (< (funcall outline-level) level)
21100 (point)))))
21102 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21103 ;; This contains an exact copy of the original function, but it uses
21104 ;; `org-back-to-heading', to make it work also in invisible
21105 ;; trees. And is uses an invisible-OK argument.
21106 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21107 ;; Furthermore, when used inside Org, finding the end of a large subtree
21108 ;; with many children and grandchildren etc, this can be much faster
21109 ;; than the outline version.
21110 (org-back-to-heading invisible-OK)
21111 (let ((first t)
21112 (level (funcall outline-level)))
21113 (if (and (eq major-mode 'org-mode) (< level 1000))
21114 ;; A true heading (not a plain list item), in Org-mode
21115 ;; This means we can easily find the end by looking
21116 ;; only for the right number of stars. Using a regexp to do
21117 ;; this is so much faster than using a Lisp loop.
21118 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21119 (forward-char 1)
21120 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21121 ;; something else, do it the slow way
21122 (while (and (not (eobp))
21123 (or first (> (funcall outline-level) level)))
21124 (setq first nil)
21125 (outline-next-heading)))
21126 (unless to-heading
21127 (if (memq (preceding-char) '(?\n ?\^M))
21128 (progn
21129 ;; Go to end of line before heading
21130 (forward-char -1)
21131 (if (memq (preceding-char) '(?\n ?\^M))
21132 ;; leave blank line before heading
21133 (forward-char -1))))))
21134 (point))
21136 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21137 "Use Org version in org-mode, for dramatic speed-up."
21138 (if (eq major-mode 'org-mode)
21139 (progn
21140 (org-end-of-subtree nil t)
21141 (unless (eobp) (backward-char 1)))
21142 ad-do-it))
21144 (defun org-end-of-meta-data-and-drawers ()
21145 "Jump to the first text after meta data and drawers in the current entry.
21146 This will move over empty lines, lines with planning time stamps,
21147 clocking lines, and drawers."
21148 (org-back-to-heading t)
21149 (let ((end (save-excursion (outline-next-heading) (point)))
21150 (re (concat "\\(" org-drawer-regexp "\\)"
21151 "\\|" "[ \t]*" org-keyword-time-regexp)))
21152 (forward-line 1)
21153 (while (re-search-forward re end t)
21154 (if (not (match-end 1))
21155 ;; empty or planning line
21156 (forward-line 1)
21157 ;; a drawer, find the end
21158 (re-search-forward "^[ \t]*:END:" end 'move)
21159 (forward-line 1)))
21160 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21161 (point)))
21163 (defun org-forward-same-level (arg &optional invisible-ok)
21164 "Move forward to the arg'th subheading at same level as this one.
21165 Stop at the first and last subheadings of a superior heading.
21166 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21167 it wil also look at invisible ones."
21168 (interactive "p")
21169 (org-back-to-heading invisible-ok)
21170 (org-at-heading-p)
21171 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21172 (re (format "^\\*\\{1,%d\\} " level))
21174 (forward-char 1)
21175 (while (> arg 0)
21176 (while (and (re-search-forward re nil 'move)
21177 (setq l (- (match-end 0) (match-beginning 0) 1))
21178 (= l level)
21179 (not invisible-ok)
21180 (progn (backward-char 1) (outline-invisible-p)))
21181 (if (< l level) (setq arg 1)))
21182 (setq arg (1- arg)))
21183 (beginning-of-line 1)))
21185 (defun org-backward-same-level (arg &optional invisible-ok)
21186 "Move backward to the arg'th subheading at same level as this one.
21187 Stop at the first and last subheadings of a superior heading."
21188 (interactive "p")
21189 (org-back-to-heading)
21190 (org-at-heading-p)
21191 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21192 (re (format "^\\*\\{1,%d\\} " level))
21194 (while (> arg 0)
21195 (while (and (re-search-backward re nil 'move)
21196 (setq l (- (match-end 0) (match-beginning 0) 1))
21197 (= l level)
21198 (not invisible-ok)
21199 (outline-invisible-p))
21200 (if (< l level) (setq arg 1)))
21201 (setq arg (1- arg)))))
21203 (defun org-show-subtree ()
21204 "Show everything after this heading at deeper levels."
21205 (interactive)
21206 (outline-flag-region
21207 (point)
21208 (save-excursion
21209 (org-end-of-subtree t t))
21210 nil))
21212 (defun org-show-entry ()
21213 "Show the body directly following this heading.
21214 Show the heading too, if it is currently invisible."
21215 (interactive)
21216 (save-excursion
21217 (condition-case nil
21218 (progn
21219 (org-back-to-heading t)
21220 (outline-flag-region
21221 (max (point-min) (1- (point)))
21222 (save-excursion
21223 (if (re-search-forward
21224 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21225 (match-beginning 1)
21226 (point-max)))
21227 nil)
21228 (org-cycle-hide-drawers 'children))
21229 (error nil))))
21231 (defun org-make-options-regexp (kwds &optional extra)
21232 "Make a regular expression for keyword lines."
21233 (concat
21235 "#?[ \t]*\\+\\("
21236 (mapconcat 'regexp-quote kwds "\\|")
21237 (if extra (concat "\\|" extra))
21238 "\\):[ \t]*"
21239 "\\(.*\\)"))
21241 ;; Make isearch reveal the necessary context
21242 (defun org-isearch-end ()
21243 "Reveal context after isearch exits."
21244 (when isearch-success ; only if search was successful
21245 (if (featurep 'xemacs)
21246 ;; Under XEmacs, the hook is run in the correct place,
21247 ;; we directly show the context.
21248 (org-show-context 'isearch)
21249 ;; In Emacs the hook runs *before* restoring the overlays.
21250 ;; So we have to use a one-time post-command-hook to do this.
21251 ;; (Emacs 22 has a special variable, see function `org-mode')
21252 (unless (and (boundp 'isearch-mode-end-hook-quit)
21253 isearch-mode-end-hook-quit)
21254 ;; Only when the isearch was not quitted.
21255 (org-add-hook 'post-command-hook 'org-isearch-post-command
21256 'append 'local)))))
21258 (defun org-isearch-post-command ()
21259 "Remove self from hook, and show context."
21260 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21261 (org-show-context 'isearch))
21264 ;;;; Integration with and fixes for other packages
21266 ;;; Imenu support
21268 (defvar org-imenu-markers nil
21269 "All markers currently used by Imenu.")
21270 (make-variable-buffer-local 'org-imenu-markers)
21272 (defun org-imenu-new-marker (&optional pos)
21273 "Return a new marker for use by Imenu, and remember the marker."
21274 (let ((m (make-marker)))
21275 (move-marker m (or pos (point)))
21276 (push m org-imenu-markers)
21279 (defun org-imenu-get-tree ()
21280 "Produce the index for Imenu."
21281 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21282 (setq org-imenu-markers nil)
21283 (let* ((n org-imenu-depth)
21284 (re (concat "^" (org-get-limited-outline-regexp)))
21285 (subs (make-vector (1+ n) nil))
21286 (last-level 0)
21287 m level head)
21288 (save-excursion
21289 (save-restriction
21290 (widen)
21291 (goto-char (point-max))
21292 (while (re-search-backward re nil t)
21293 (setq level (org-reduced-level (funcall outline-level)))
21294 (when (and (<= level n)
21295 (looking-at org-complex-heading-regexp))
21296 (setq head (org-link-display-format
21297 (org-match-string-no-properties 4))
21298 m (org-imenu-new-marker))
21299 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21300 (if (>= level last-level)
21301 (push (cons head m) (aref subs level))
21302 (push (cons head (aref subs (1+ level))) (aref subs level))
21303 (loop for i from (1+ level) to n do (aset subs i nil)))
21304 (setq last-level level)))))
21305 (aref subs 1)))
21307 (eval-after-load "imenu"
21308 '(progn
21309 (add-hook 'imenu-after-jump-hook
21310 (lambda ()
21311 (if (eq major-mode 'org-mode)
21312 (org-show-context 'org-goto))))))
21314 (defun org-link-display-format (link)
21315 "Replace a link with either the description, or the link target
21316 if no description is present"
21317 (save-match-data
21318 (if (string-match org-bracket-link-analytic-regexp link)
21319 (replace-match (if (match-end 5)
21320 (match-string 5 link)
21321 (concat (match-string 1 link)
21322 (match-string 3 link)))
21323 nil t link)
21324 link)))
21326 (defun org-toggle-link-display ()
21327 "Toggle the literal or descriptive display of links."
21328 (interactive)
21329 (if org-descriptive-links
21330 (progn (org-remove-from-invisibility-spec '(org-link))
21331 (org-restart-font-lock)
21332 (setq org-descriptive-links nil))
21333 (progn (add-to-invisibility-spec '(org-link))
21334 (org-restart-font-lock)
21335 (setq org-descriptive-links t))))
21337 ;; Speedbar support
21339 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21340 "Overlay marking the agenda restriction line in speedbar.")
21341 (overlay-put org-speedbar-restriction-lock-overlay
21342 'face 'org-agenda-restriction-lock)
21343 (overlay-put org-speedbar-restriction-lock-overlay
21344 'help-echo "Agendas are currently limited to this item.")
21345 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21347 (defun org-speedbar-set-agenda-restriction ()
21348 "Restrict future agenda commands to the location at point in speedbar.
21349 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21350 (interactive)
21351 (require 'org-agenda)
21352 (let (p m tp np dir txt)
21353 (cond
21354 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21355 'org-imenu t))
21356 (setq m (get-text-property p 'org-imenu-marker))
21357 (with-current-buffer (marker-buffer m)
21358 (goto-char m)
21359 (org-agenda-set-restriction-lock 'subtree)))
21360 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21361 'speedbar-function 'speedbar-find-file))
21362 (setq tp (previous-single-property-change
21363 (1+ p) 'speedbar-function)
21364 np (next-single-property-change
21365 tp 'speedbar-function)
21366 dir (speedbar-line-directory)
21367 txt (buffer-substring-no-properties (or tp (point-min))
21368 (or np (point-max))))
21369 (with-current-buffer (find-file-noselect
21370 (let ((default-directory dir))
21371 (expand-file-name txt)))
21372 (unless (eq major-mode 'org-mode)
21373 (error "Cannot restrict to non-Org-mode file"))
21374 (org-agenda-set-restriction-lock 'file)))
21375 (t (error "Don't know how to restrict Org-mode's agenda")))
21376 (move-overlay org-speedbar-restriction-lock-overlay
21377 (point-at-bol) (point-at-eol))
21378 (setq current-prefix-arg nil)
21379 (org-agenda-maybe-redo)))
21381 (eval-after-load "speedbar"
21382 '(progn
21383 (speedbar-add-supported-extension ".org")
21384 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21385 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21386 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21387 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21388 (add-hook 'speedbar-visiting-tag-hook
21389 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21391 ;;; Fixes and Hacks for problems with other packages
21393 ;; Make flyspell not check words in links, to not mess up our keymap
21394 (defun org-mode-flyspell-verify ()
21395 "Don't let flyspell put overlays at active buttons, or on
21396 {todo,all-time,additional-option-like}-keywords."
21397 (let ((pos (max (1- (point)) (point-min)))
21398 (word (thing-at-point 'word)))
21399 (and (not (get-text-property pos 'keymap))
21400 (not (get-text-property pos 'org-no-flyspell))
21401 (not (member word org-todo-keywords-1))
21402 (not (member word org-all-time-keywords))
21403 (not (member word org-additional-option-like-keywords)))))
21405 (defun org-remove-flyspell-overlays-in (beg end)
21406 "Remove flyspell overlays in region."
21407 (and (org-bound-and-true-p flyspell-mode)
21408 (fboundp 'flyspell-delete-region-overlays)
21409 (flyspell-delete-region-overlays beg end))
21410 (add-text-properties beg end '(org-no-flyspell t)))
21412 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21413 (eval-after-load "bookmark"
21414 '(if (boundp 'bookmark-after-jump-hook)
21415 ;; We can use the hook
21416 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21417 ;; Hook not available, use advice
21418 (defadvice bookmark-jump (after org-make-visible activate)
21419 "Make the position visible."
21420 (org-bookmark-jump-unhide))))
21422 ;; Make sure saveplace shows the location if it was hidden
21423 (eval-after-load "saveplace"
21424 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21425 "Make the position visible."
21426 (org-bookmark-jump-unhide)))
21428 ;; Make sure ecb shows the location if it was hidden
21429 (eval-after-load "ecb"
21430 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21431 "Make hierarchy visible when jumping into location from ECB tree buffer."
21432 (if (eq major-mode 'org-mode)
21433 (org-show-context))))
21435 (defun org-bookmark-jump-unhide ()
21436 "Unhide the current position, to show the bookmark location."
21437 (and (eq major-mode 'org-mode)
21438 (or (outline-invisible-p)
21439 (save-excursion (goto-char (max (point-min) (1- (point))))
21440 (outline-invisible-p)))
21441 (org-show-context 'bookmark-jump)))
21443 ;; Make session.el ignore our circular variable
21444 (eval-after-load "session"
21445 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21447 ;;;; Experimental code
21449 (defun org-closed-in-range ()
21450 "Sparse tree of items closed in a certain time range.
21451 Still experimental, may disappear in the future."
21452 (interactive)
21453 ;; Get the time interval from the user.
21454 (let* ((time1 (org-float-time
21455 (org-read-date nil 'to-time nil "Starting date: ")))
21456 (time2 (org-float-time
21457 (org-read-date nil 'to-time nil "End date:")))
21458 ;; callback function
21459 (callback (lambda ()
21460 (let ((time
21461 (org-float-time
21462 (apply 'encode-time
21463 (org-parse-time-string
21464 (match-string 1))))))
21465 ;; check if time in interval
21466 (and (>= time time1) (<= time time2))))))
21467 ;; make tree, check each match with the callback
21468 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21470 ;;;; Finish up
21472 (provide 'org)
21474 (run-hooks 'org-load-hook)
21476 ;;; org.el ends here