Manually revert to the Release 7.8.04 tag.
[org-mode.git] / lisp / org.el
blob55565fe5e27fed09b16b3dab2d58ce40fb737a97
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.04
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.04"
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 This variable needs to be set before org.el is loaded, and you need to
2274 restart Emacs after a change to make the change effective. The only way
2275 to change is while Emacs is running is through the customize interface."
2276 :set (lambda (var val)
2277 (set var val)
2278 (if val
2279 (add-hook 'org-blocker-hook
2280 'org-block-todo-from-children-or-siblings-or-parent)
2281 (remove-hook 'org-blocker-hook
2282 'org-block-todo-from-children-or-siblings-or-parent)))
2283 :group 'org-todo
2284 :type 'boolean)
2286 (defcustom org-enforce-todo-checkbox-dependencies nil
2287 "Non-nil means unchecked boxes will block switching the parent to DONE.
2288 When this is nil, checkboxes have no influence on switching TODO states.
2289 When non-nil, you first need to check off all check boxes before the TODO
2290 entry can be switched to DONE.
2291 This variable needs to be set before org.el is loaded, and you need to
2292 restart Emacs after a change to make the change effective. The only way
2293 to change is while Emacs is running is through the customize interface."
2294 :set (lambda (var val)
2295 (set var val)
2296 (if val
2297 (add-hook 'org-blocker-hook
2298 'org-block-todo-from-checkboxes)
2299 (remove-hook 'org-blocker-hook
2300 'org-block-todo-from-checkboxes)))
2301 :group 'org-todo
2302 :type 'boolean)
2304 (defcustom org-treat-insert-todo-heading-as-state-change nil
2305 "Non-nil means inserting a TODO heading is treated as state change.
2306 So when the command \\[org-insert-todo-heading] is used, state change
2307 logging will apply if appropriate. When nil, the new TODO item will
2308 be inserted directly, and no logging will take place."
2309 :group 'org-todo
2310 :type 'boolean)
2312 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2313 "Non-nil means switching TODO states with S-cursor counts as state change.
2314 This is the default behavior. However, setting this to nil allows a
2315 convenient way to select a TODO state and bypass any logging associated
2316 with that."
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-todo-state-tags-triggers nil
2321 "Tag changes that should be triggered by TODO state changes.
2322 This is a list. Each entry is
2324 (state-change (tag . flag) .......)
2326 State-change can be a string with a state, and empty string to indicate the
2327 state that has no TODO keyword, or it can be one of the symbols `todo'
2328 or `done', meaning any not-done or done state, respectively."
2329 :group 'org-todo
2330 :group 'org-tags
2331 :type '(repeat
2332 (cons (choice :tag "When changing to"
2333 (const :tag "Not-done state" todo)
2334 (const :tag "Done state" done)
2335 (string :tag "State"))
2336 (repeat
2337 (cons :tag "Tag action"
2338 (string :tag "Tag")
2339 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2341 (defcustom org-log-done nil
2342 "Information to record when a task moves to the DONE state.
2344 Possible values are:
2346 nil Don't add anything, just change the keyword
2347 time Add a time stamp to the task
2348 note Prompt for a note and add it with template `org-log-note-headings'
2350 This option can also be set with on a per-file-basis with
2352 #+STARTUP: nologdone
2353 #+STARTUP: logdone
2354 #+STARTUP: lognotedone
2356 You can have local logging settings for a subtree by setting the LOGGING
2357 property to one or more of these keywords."
2358 :group 'org-todo
2359 :group 'org-progress
2360 :type '(choice
2361 (const :tag "No logging" nil)
2362 (const :tag "Record CLOSED timestamp" time)
2363 (const :tag "Record CLOSED timestamp with note." note)))
2365 ;; Normalize old uses of org-log-done.
2366 (cond
2367 ((eq org-log-done t) (setq org-log-done 'time))
2368 ((and (listp org-log-done) (memq 'done org-log-done))
2369 (setq org-log-done 'note)))
2371 (defcustom org-log-reschedule nil
2372 "Information to record when the scheduling date of a tasks is modified.
2374 Possible values are:
2376 nil Don't add anything, just change the date
2377 time Add a time stamp to the task
2378 note Prompt for a note and add it with template `org-log-note-headings'
2380 This option can also be set with on a per-file-basis with
2382 #+STARTUP: nologreschedule
2383 #+STARTUP: logreschedule
2384 #+STARTUP: lognotereschedule"
2385 :group 'org-todo
2386 :group 'org-progress
2387 :type '(choice
2388 (const :tag "No logging" nil)
2389 (const :tag "Record timestamp" time)
2390 (const :tag "Record timestamp with note." note)))
2392 (defcustom org-log-redeadline nil
2393 "Information to record when the deadline date of a tasks is modified.
2395 Possible values are:
2397 nil Don't add anything, just change the date
2398 time Add a time stamp to the task
2399 note Prompt for a note and add it with template `org-log-note-headings'
2401 This option can also be set with on a per-file-basis with
2403 #+STARTUP: nologredeadline
2404 #+STARTUP: logredeadline
2405 #+STARTUP: lognoteredeadline
2407 You can have local logging settings for a subtree by setting the LOGGING
2408 property to one or more of these keywords."
2409 :group 'org-todo
2410 :group 'org-progress
2411 :type '(choice
2412 (const :tag "No logging" nil)
2413 (const :tag "Record timestamp" time)
2414 (const :tag "Record timestamp with note." note)))
2416 (defcustom org-log-note-clock-out nil
2417 "Non-nil means record a note when clocking out of an item.
2418 This can also be configured on a per-file basis by adding one of
2419 the following lines anywhere in the buffer:
2421 #+STARTUP: lognoteclock-out
2422 #+STARTUP: nolognoteclock-out"
2423 :group 'org-todo
2424 :group 'org-progress
2425 :type 'boolean)
2427 (defcustom org-log-done-with-time t
2428 "Non-nil means the CLOSED time stamp will contain date and time.
2429 When nil, only the date will be recorded."
2430 :group 'org-progress
2431 :type 'boolean)
2433 (defcustom org-log-note-headings
2434 '((done . "CLOSING NOTE %t")
2435 (state . "State %-12s from %-12S %t")
2436 (note . "Note taken on %t")
2437 (reschedule . "Rescheduled from %S on %t")
2438 (delschedule . "Not scheduled, was %S on %t")
2439 (redeadline . "New deadline from %S on %t")
2440 (deldeadline . "Removed deadline, was %S on %t")
2441 (refile . "Refiled on %t")
2442 (clock-out . ""))
2443 "Headings for notes added to entries.
2444 The value is an alist, with the car being a symbol indicating the note
2445 context, and the cdr is the heading to be used. The heading may also be the
2446 empty string.
2447 %t in the heading will be replaced by a time stamp.
2448 %T will be an active time stamp instead the default inactive one
2449 %d will be replaced by a short-format time stamp.
2450 %D will be replaced by an active short-format time stamp.
2451 %s will be replaced by the new TODO state, in double quotes.
2452 %S will be replaced by the old TODO state, in double quotes.
2453 %u will be replaced by the user name.
2454 %U will be replaced by the full user name.
2456 In fact, it is not a good idea to change the `state' entry, because
2457 agenda log mode depends on the format of these entries."
2458 :group 'org-todo
2459 :group 'org-progress
2460 :type '(list :greedy t
2461 (cons (const :tag "Heading when closing an item" done) string)
2462 (cons (const :tag
2463 "Heading when changing todo state (todo sequence only)"
2464 state) string)
2465 (cons (const :tag "Heading when just taking a note" note) string)
2466 (cons (const :tag "Heading when clocking out" clock-out) string)
2467 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2468 (cons (const :tag "Heading when rescheduling" reschedule) string)
2469 (cons (const :tag "Heading when changing deadline" redeadline) string)
2470 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2471 (cons (const :tag "Heading when refiling" refile) string)))
2473 (unless (assq 'note org-log-note-headings)
2474 (push '(note . "%t") org-log-note-headings))
2476 (defcustom org-log-into-drawer nil
2477 "Non-nil means insert state change notes and time stamps into a drawer.
2478 When nil, state changes notes will be inserted after the headline and
2479 any scheduling and clock lines, but not inside a drawer.
2481 The value of this variable should be the name of the drawer to use.
2482 LOGBOOK is proposed as the default drawer for this purpose, you can
2483 also set this to a string to define the drawer of your choice.
2485 A value of t is also allowed, representing \"LOGBOOK\".
2487 If this variable is set, `org-log-state-notes-insert-after-drawers'
2488 will be ignored.
2490 You can set the property LOG_INTO_DRAWER to overrule this setting for
2491 a subtree."
2492 :group 'org-todo
2493 :group 'org-progress
2494 :type '(choice
2495 (const :tag "Not into a drawer" nil)
2496 (const :tag "LOGBOOK" t)
2497 (string :tag "Other")))
2499 (if (fboundp 'defvaralias)
2500 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2502 (defun org-log-into-drawer ()
2503 "Return the value of `org-log-into-drawer', but let properties overrule.
2504 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2505 used instead of the default value."
2506 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2507 (cond
2508 ((or (not p) (equal p "nil")) org-log-into-drawer)
2509 ((equal p "t") "LOGBOOK")
2510 (t p))))
2512 (defcustom org-log-state-notes-insert-after-drawers nil
2513 "Non-nil means insert state change notes after any drawers in entry.
2514 Only the drawers that *immediately* follow the headline and the
2515 deadline/scheduled line are skipped.
2516 When nil, insert notes right after the heading and perhaps the line
2517 with deadline/scheduling if present.
2519 This variable will have no effect if `org-log-into-drawer' is
2520 set."
2521 :group 'org-todo
2522 :group 'org-progress
2523 :type 'boolean)
2525 (defcustom org-log-states-order-reversed t
2526 "Non-nil means the latest state note will be directly after heading.
2527 When nil, the state change notes will be ordered according to time."
2528 :group 'org-todo
2529 :group 'org-progress
2530 :type 'boolean)
2532 (defcustom org-todo-repeat-to-state nil
2533 "The TODO state to which a repeater should return the repeating task.
2534 By default this is the first task in a TODO sequence, or the previous state
2535 in a TODO_TYP set. But you can specify another task here.
2536 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2537 :group 'org-todo
2538 :version "24.1"
2539 :type '(choice (const :tag "Head of sequence" nil)
2540 (string :tag "Specific state")))
2542 (defcustom org-log-repeat 'time
2543 "Non-nil means record moving through the DONE state when triggering repeat.
2544 An auto-repeating task is immediately switched back to TODO when
2545 marked DONE. If you are not logging state changes (by adding \"@\"
2546 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2547 record a closing note, there will be no record of the task moving
2548 through DONE. This variable forces taking a note anyway.
2550 nil Don't force a record
2551 time Record a time stamp
2552 note Record a note
2554 This option can also be set with on a per-file-basis with
2556 #+STARTUP: logrepeat
2557 #+STARTUP: lognoterepeat
2558 #+STARTUP: nologrepeat
2560 You can have local logging settings for a subtree by setting the LOGGING
2561 property to one or more of these keywords."
2562 :group 'org-todo
2563 :group 'org-progress
2564 :type '(choice
2565 (const :tag "Don't force a record" nil)
2566 (const :tag "Force recording the DONE state" time)
2567 (const :tag "Force recording a note with the DONE state" note)))
2570 (defgroup org-priorities nil
2571 "Priorities in Org-mode."
2572 :tag "Org Priorities"
2573 :group 'org-todo)
2575 (defcustom org-enable-priority-commands t
2576 "Non-nil means priority commands are active.
2577 When nil, these commands will be disabled, so that you never accidentally
2578 set a priority."
2579 :group 'org-priorities
2580 :type 'boolean)
2582 (defcustom org-highest-priority ?A
2583 "The highest priority of TODO items. A character like ?A, ?B etc.
2584 Must have a smaller ASCII number than `org-lowest-priority'."
2585 :group 'org-priorities
2586 :type 'character)
2588 (defcustom org-lowest-priority ?C
2589 "The lowest priority of TODO items. A character like ?A, ?B etc.
2590 Must have a larger ASCII number than `org-highest-priority'."
2591 :group 'org-priorities
2592 :type 'character)
2594 (defcustom org-default-priority ?B
2595 "The default priority of TODO items.
2596 This is the priority an item gets if no explicit priority is given.
2597 When starting to cycle on an empty priority the first step in the cycle
2598 depends on `org-priority-start-cycle-with-default'. The resulting first
2599 step priority must not exceed the range from `org-highest-priority' to
2600 `org-lowest-priority' which means that `org-default-priority' has to be
2601 in this range exclusive or inclusive the range boundaries. Else the
2602 first step refuses to set the default and the second will fall back
2603 to (depending on the command used) the highest or lowest priority."
2604 :group 'org-priorities
2605 :type 'character)
2607 (defcustom org-priority-start-cycle-with-default t
2608 "Non-nil means start with default priority when starting to cycle.
2609 When this is nil, the first step in the cycle will be (depending on the
2610 command used) one higher or lower than the default priority.
2611 See also `org-default-priority'."
2612 :group 'org-priorities
2613 :type 'boolean)
2615 (defcustom org-get-priority-function nil
2616 "Function to extract the priority from a string.
2617 The string is normally the headline. If this is nil Org computes the
2618 priority from the priority cookie like [#A] in the headline. It returns
2619 an integer, increasing by 1000 for each priority level.
2620 The user can set a different function here, which should take a string
2621 as an argument and return the numeric priority."
2622 :group 'org-priorities
2623 :version "24.1"
2624 :type 'function)
2626 (defgroup org-time nil
2627 "Options concerning time stamps and deadlines in Org-mode."
2628 :tag "Org Time"
2629 :group 'org)
2631 (defcustom org-insert-labeled-timestamps-at-point nil
2632 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2633 When nil, these labeled time stamps are forces into the second line of an
2634 entry, just after the headline. When scheduling from the global TODO list,
2635 the time stamp will always be forced into the second line."
2636 :group 'org-time
2637 :type 'boolean)
2639 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2640 "Formats for `format-time-string' which are used for time stamps.
2641 It is not recommended to change this constant.")
2643 (defcustom org-time-stamp-rounding-minutes '(0 5)
2644 "Number of minutes to round time stamps to.
2645 These are two values, the first applies when first creating a time stamp.
2646 The second applies when changing it with the commands `S-up' and `S-down'.
2647 When changing the time stamp, this means that it will change in steps
2648 of N minutes, as given by the second value.
2650 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2651 numbers should be factors of 60, so for example 5, 10, 15.
2653 When this is larger than 1, you can still force an exact time stamp by using
2654 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2655 and by using a prefix arg to `S-up/down' to specify the exact number
2656 of minutes to shift."
2657 :group 'org-time
2658 :get #'(lambda (var) ; Make sure both elements are there
2659 (if (integerp (default-value var))
2660 (list (default-value var) 5)
2661 (default-value var)))
2662 :type '(list
2663 (integer :tag "when inserting times")
2664 (integer :tag "when modifying times")))
2666 ;; Normalize old customizations of this variable.
2667 (when (integerp org-time-stamp-rounding-minutes)
2668 (setq org-time-stamp-rounding-minutes
2669 (list org-time-stamp-rounding-minutes
2670 org-time-stamp-rounding-minutes)))
2672 (defcustom org-display-custom-times nil
2673 "Non-nil means overlay custom formats over all time stamps.
2674 The formats are defined through the variable `org-time-stamp-custom-formats'.
2675 To turn this on on a per-file basis, insert anywhere in the file:
2676 #+STARTUP: customtime"
2677 :group 'org-time
2678 :set 'set-default
2679 :type 'sexp)
2680 (make-variable-buffer-local 'org-display-custom-times)
2682 (defcustom org-time-stamp-custom-formats
2683 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2684 "Custom formats for time stamps. See `format-time-string' for the syntax.
2685 These are overlaid over the default ISO format if the variable
2686 `org-display-custom-times' is set. Time like %H:%M should be at the
2687 end of the second format. The custom formats are also honored by export
2688 commands, if custom time display is turned on at the time of export."
2689 :group 'org-time
2690 :type 'sexp)
2692 (defun org-time-stamp-format (&optional long inactive)
2693 "Get the right format for a time string."
2694 (let ((f (if long (cdr org-time-stamp-formats)
2695 (car org-time-stamp-formats))))
2696 (if inactive
2697 (concat "[" (substring f 1 -1) "]")
2698 f)))
2700 (defcustom org-time-clocksum-format "%d:%02d"
2701 "The format string used when creating CLOCKSUM lines.
2702 This is also used when org-mode generates a time duration."
2703 :group 'org-time
2704 :type 'string)
2706 (defcustom org-time-clocksum-use-fractional nil
2707 "If non-nil, \\[org-clock-display] uses fractional times.
2708 org-mode generates a time duration."
2709 :group 'org-time
2710 :type 'boolean)
2712 (defcustom org-time-clocksum-fractional-format "%.2f"
2713 "The format string used when creating CLOCKSUM lines, or when
2714 org-mode generates a time duration."
2715 :group 'org-time
2716 :type 'string)
2718 (defcustom org-deadline-warning-days 14
2719 "No. of days before expiration during which a deadline becomes active.
2720 This variable governs the display in sparse trees and in the agenda.
2721 When 0 or negative, it means use this number (the absolute value of it)
2722 even if a deadline has a different individual lead time specified.
2724 Custom commands can set this variable in the options section."
2725 :group 'org-time
2726 :group 'org-agenda-daily/weekly
2727 :type 'integer)
2729 (defcustom org-read-date-prefer-future t
2730 "Non-nil means assume future for incomplete date input from user.
2731 This affects the following situations:
2732 1. The user gives a month but not a year.
2733 For example, if it is April and you enter \"feb 2\", this will be read
2734 as Feb 2, *next* year. \"May 5\", however, will be this year.
2735 2. The user gives a day, but no month.
2736 For example, if today is the 15th, and you enter \"3\", Org-mode will
2737 read this as the third of *next* month. However, if you enter \"17\",
2738 it will be considered as *this* month.
2740 If you set this variable to the symbol `time', then also the following
2741 will work:
2743 3. If the user gives a time, but no day. If the time is before now,
2744 to will be interpreted as tomorrow.
2746 Currently none of this works for ISO week specifications.
2748 When this option is nil, the current day, month and year will always be
2749 used as defaults.
2751 See also `org-agenda-jump-prefer-future'."
2752 :group 'org-time
2753 :type '(choice
2754 (const :tag "Never" nil)
2755 (const :tag "Check month and day" t)
2756 (const :tag "Check month, day, and time" time)))
2758 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2759 "Should the agenda jump command prefer the future for incomplete dates?
2760 The default is to do the same as configured in `org-read-date-prefer-future'.
2761 But you can also set a deviating value here.
2762 This may t or nil, or the symbol `org-read-date-prefer-future'."
2763 :group 'org-agenda
2764 :group 'org-time
2765 :version "24.1"
2766 :type '(choice
2767 (const :tag "Use org-read-date-prefer-future"
2768 org-read-date-prefer-future)
2769 (const :tag "Never" nil)
2770 (const :tag "Always" t)))
2772 (defcustom org-read-date-force-compatible-dates t
2773 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2775 Depending on the system Emacs is running on, certain dates cannot
2776 be represented with the type used internally to represent time.
2777 Dates between 1970-1-1 and 2038-1-1 can always be represented
2778 correctly. Some systems allow for earlier dates, some for later,
2779 some for both. One way to find out it to insert any date into an
2780 Org buffer, putting the cursor on the year and hitting S-up and
2781 S-down to test the range.
2783 When this variable is set to t, the date/time prompt will not let
2784 you specify dates outside the 1970-2037 range, so it is certain that
2785 these dates will work in whatever version of Emacs you are
2786 running, and also that you can move a file from one Emacs implementation
2787 to another. WHenever Org is forcing the year for you, it will display
2788 a message and beep.
2790 When this variable is nil, Org will check if the date is
2791 representable in the specific Emacs implementation you are using.
2792 If not, it will force a year, usually the current year, and beep
2793 to remind you. Currently this setting is not recommended because
2794 the likelihood that you will open your Org files in an Emacs that
2795 has limited date range is not negligible.
2797 A workaround for this problem is to use diary sexp dates for time
2798 stamps outside of this range."
2799 :group 'org-time
2800 :version "24.1"
2801 :type 'boolean)
2803 (defcustom org-read-date-display-live t
2804 "Non-nil means display current interpretation of date prompt live.
2805 This display will be in an overlay, in the minibuffer."
2806 :group 'org-time
2807 :type 'boolean)
2809 (defcustom org-read-date-popup-calendar t
2810 "Non-nil means pop up a calendar when prompting for a date.
2811 In the calendar, the date can be selected with mouse-1. However, the
2812 minibuffer will also be active, and you can simply enter the date as well.
2813 When nil, only the minibuffer will be available."
2814 :group 'org-time
2815 :type 'boolean)
2816 (if (fboundp 'defvaralias)
2817 (defvaralias 'org-popup-calendar-for-date-prompt
2818 'org-read-date-popup-calendar))
2820 (defcustom org-read-date-minibuffer-setup-hook nil
2821 "Hook to be used to set up keys for the date/time interface.
2822 Add key definitions to `minibuffer-local-map', which will be a temporary
2823 copy."
2824 :group 'org-time
2825 :type 'hook)
2827 (defcustom org-extend-today-until 0
2828 "The hour when your day really ends. Must be an integer.
2829 This has influence for the following applications:
2830 - When switching the agenda to \"today\". It it is still earlier than
2831 the time given here, the day recognized as TODAY is actually yesterday.
2832 - When a date is read from the user and it is still before the time given
2833 here, the current date and time will be assumed to be yesterday, 23:59.
2834 Also, timestamps inserted in remember templates follow this rule.
2836 IMPORTANT: This is a feature whose implementation is and likely will
2837 remain incomplete. Really, it is only here because past midnight seems to
2838 be the favorite working time of John Wiegley :-)"
2839 :group 'org-time
2840 :type 'integer)
2842 (defcustom org-use-effective-time nil
2843 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2844 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2845 \"effective time\" of any timestamps between midnight and 8am will be
2846 23:59 of the previous day."
2847 :group 'boolean
2848 :version "24.1"
2849 :type 'integer)
2851 (defcustom org-edit-timestamp-down-means-later nil
2852 "Non-nil means S-down will increase the time in a time stamp.
2853 When nil, S-up will increase."
2854 :group 'org-time
2855 :type 'boolean)
2857 (defcustom org-calendar-follow-timestamp-change t
2858 "Non-nil means make the calendar window follow timestamp changes.
2859 When a timestamp is modified and the calendar window is visible, it will be
2860 moved to the new date."
2861 :group 'org-time
2862 :type 'boolean)
2864 (defgroup org-tags nil
2865 "Options concerning tags in Org-mode."
2866 :tag "Org Tags"
2867 :group 'org)
2869 (defcustom org-tag-alist nil
2870 "List of tags allowed in Org-mode files.
2871 When this list is nil, Org-mode will base TAG input on what is already in the
2872 buffer.
2873 The value of this variable is an alist, the car of each entry must be a
2874 keyword as a string, the cdr may be a character that is used to select
2875 that tag through the fast-tag-selection interface.
2876 See the manual for details."
2877 :group 'org-tags
2878 :type '(repeat
2879 (choice
2880 (cons (string :tag "Tag name")
2881 (character :tag "Access char"))
2882 (list :tag "Start radio group"
2883 (const :startgroup)
2884 (option (string :tag "Group description")))
2885 (list :tag "End radio group"
2886 (const :endgroup)
2887 (option (string :tag "Group description")))
2888 (const :tag "New line" (:newline)))))
2890 (defcustom org-tag-persistent-alist nil
2891 "List of tags that will always appear in all Org-mode files.
2892 This is in addition to any in buffer settings or customizations
2893 of `org-tag-alist'.
2894 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2895 The value of this variable is an alist, the car of each entry must be a
2896 keyword as a string, the cdr may be a character that is used to select
2897 that tag through the fast-tag-selection interface.
2898 See the manual for details.
2899 To disable these tags on a per-file basis, insert anywhere in the file:
2900 #+STARTUP: noptag"
2901 :group 'org-tags
2902 :type '(repeat
2903 (choice
2904 (cons (string :tag "Tag name")
2905 (character :tag "Access char"))
2906 (const :tag "Start radio group" (:startgroup))
2907 (const :tag "End radio group" (:endgroup))
2908 (const :tag "New line" (:newline)))))
2910 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2911 "If non-nil, always offer completion for all tags of all agenda files.
2912 Instead of customizing this variable directly, you might want to
2913 set it locally for capture buffers, because there no list of
2914 tags in that file can be created dynamically (there are none).
2916 (add-hook 'org-capture-mode-hook
2917 (lambda ()
2918 (set (make-local-variable
2919 'org-complete-tags-always-offer-all-agenda-tags)
2920 t)))"
2921 :group 'org-tags
2922 :version "24.1"
2923 :type 'boolean)
2925 (defvar org-file-tags nil
2926 "List of tags that can be inherited by all entries in the file.
2927 The tags will be inherited if the variable `org-use-tag-inheritance'
2928 says they should be.
2929 This variable is populated from #+FILETAGS lines.")
2931 (defcustom org-use-fast-tag-selection 'auto
2932 "Non-nil means use fast tag selection scheme.
2933 This is a special interface to select and deselect tags with single keys.
2934 When nil, fast selection is never used.
2935 When the symbol `auto', fast selection is used if and only if selection
2936 characters for tags have been configured, either through the variable
2937 `org-tag-alist' or through a #+TAGS line in the buffer.
2938 When t, fast selection is always used and selection keys are assigned
2939 automatically if necessary."
2940 :group 'org-tags
2941 :type '(choice
2942 (const :tag "Always" t)
2943 (const :tag "Never" nil)
2944 (const :tag "When selection characters are configured" 'auto)))
2946 (defcustom org-fast-tag-selection-single-key nil
2947 "Non-nil means fast tag selection exits after first change.
2948 When nil, you have to press RET to exit it.
2949 During fast tag selection, you can toggle this flag with `C-c'.
2950 This variable can also have the value `expert'. In this case, the window
2951 displaying the tags menu is not even shown, until you press C-c again."
2952 :group 'org-tags
2953 :type '(choice
2954 (const :tag "No" nil)
2955 (const :tag "Yes" t)
2956 (const :tag "Expert" expert)))
2958 (defvar org-fast-tag-selection-include-todo nil
2959 "Non-nil means fast tags selection interface will also offer TODO states.
2960 This is an undocumented feature, you should not rely on it.")
2962 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2963 "The column to which tags should be indented in a headline.
2964 If this number is positive, it specifies the column. If it is negative,
2965 it means that the tags should be flushright to that column. For example,
2966 -80 works well for a normal 80 character screen.
2967 When 0, place tags directly after headline text, with only one space in
2968 between."
2969 :group 'org-tags
2970 :type 'integer)
2972 (defcustom org-auto-align-tags t
2973 "Non-nil keeps tags aligned when modifying headlines.
2974 Some operations (i.e. demoting) change the length of a headline and
2975 therefore shift the tags around. With this option turned on, after
2976 each such operation the tags are again aligned to `org-tags-column'."
2977 :group 'org-tags
2978 :type 'boolean)
2980 (defcustom org-use-tag-inheritance t
2981 "Non-nil means tags in levels apply also for sublevels.
2982 When nil, only the tags directly given in a specific line apply there.
2983 This may also be a list of tags that should be inherited, or a regexp that
2984 matches tags that should be inherited. Additional control is possible
2985 with the variable `org-tags-exclude-from-inheritance' which gives an
2986 explicit list of tags to be excluded from inheritance., even if the value of
2987 `org-use-tag-inheritance' would select it for inheritance.
2989 If this option is t, a match early-on in a tree can lead to a large
2990 number of matches in the subtree when constructing the agenda or creating
2991 a sparse tree. If you only want to see the first match in a tree during
2992 a search, check out the variable `org-tags-match-list-sublevels'."
2993 :group 'org-tags
2994 :type '(choice
2995 (const :tag "Not" nil)
2996 (const :tag "Always" t)
2997 (repeat :tag "Specific tags" (string :tag "Tag"))
2998 (regexp :tag "Tags matched by regexp")))
3000 (defcustom org-tags-exclude-from-inheritance nil
3001 "List of tags that should never be inherited.
3002 This is a way to exclude a few tags from inheritance. For way to do
3003 the opposite, to actively allow inheritance for selected tags,
3004 see the variable `org-use-tag-inheritance'."
3005 :group 'org-tags
3006 :type '(repeat (string :tag "Tag")))
3008 (defun org-tag-inherit-p (tag)
3009 "Check if TAG is one that should be inherited."
3010 (cond
3011 ((member tag org-tags-exclude-from-inheritance) nil)
3012 ((eq org-use-tag-inheritance t) t)
3013 ((not org-use-tag-inheritance) nil)
3014 ((stringp org-use-tag-inheritance)
3015 (string-match org-use-tag-inheritance tag))
3016 ((listp org-use-tag-inheritance)
3017 (member tag org-use-tag-inheritance))
3018 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3020 (defcustom org-tags-match-list-sublevels t
3021 "Non-nil means list also sublevels of headlines matching a search.
3022 This variable applies to tags/property searches, and also to stuck
3023 projects because this search is based on a tags match as well.
3025 When set to the symbol `indented', sublevels are indented with
3026 leading dots.
3028 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3029 the sublevels of a headline matching a tag search often also match
3030 the same search. Listing all of them can create very long lists.
3031 Setting this variable to nil causes subtrees of a match to be skipped.
3033 This variable is semi-obsolete and probably should always be true. It
3034 is better to limit inheritance to certain tags using the variables
3035 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3036 :group 'org-tags
3037 :type '(choice
3038 (const :tag "No, don't list them" nil)
3039 (const :tag "Yes, do list them" t)
3040 (const :tag "List them, indented with leading dots" indented)))
3042 (defcustom org-tags-sort-function nil
3043 "When set, tags are sorted using this function as a comparator."
3044 :group 'org-tags
3045 :type '(choice
3046 (const :tag "No sorting" nil)
3047 (const :tag "Alphabetical" string<)
3048 (const :tag "Reverse alphabetical" string>)
3049 (function :tag "Custom function" nil)))
3051 (defvar org-tags-history nil
3052 "History of minibuffer reads for tags.")
3053 (defvar org-last-tags-completion-table nil
3054 "The last used completion table for tags.")
3055 (defvar org-after-tags-change-hook nil
3056 "Hook that is run after the tags in a line have changed.")
3058 (defgroup org-properties nil
3059 "Options concerning properties in Org-mode."
3060 :tag "Org Properties"
3061 :group 'org)
3063 (defcustom org-property-format "%-10s %s"
3064 "How property key/value pairs should be formatted by `indent-line'.
3065 When `indent-line' hits a property definition, it will format the line
3066 according to this format, mainly to make sure that the values are
3067 lined-up with respect to each other."
3068 :group 'org-properties
3069 :type 'string)
3071 (defcustom org-properties-postprocess-alist nil
3072 "Alist of properties and functions to adjust inserted values.
3073 Elements of this alist must be of the form
3075 ([string] [function])
3077 where [string] must be a property name and [function] must be a
3078 lambda expression: this lambda expression must take one argument,
3079 the value to adjust, and return the new value as a string.
3081 For example, this element will allow the property \"Remaining\"
3082 to be updated wrt the relation between the \"Effort\" property
3083 and the clock summary:
3085 ((\"Remaining\" (lambda(value)
3086 (let ((clocksum (org-clock-sum-current-item))
3087 (effort (org-duration-string-to-minutes
3088 (org-entry-get (point) \"Effort\"))))
3089 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3090 :group 'org-properties
3091 :version "24.1"
3092 :type 'alist)
3094 (defcustom org-use-property-inheritance nil
3095 "Non-nil means properties apply also for sublevels.
3097 This setting is chiefly used during property searches. Turning it on can
3098 cause significant overhead when doing a search, which is why it is not
3099 on by default.
3101 When nil, only the properties directly given in the current entry count.
3102 When t, every property is inherited. The value may also be a list of
3103 properties that should have inheritance, or a regular expression matching
3104 properties that should be inherited.
3106 However, note that some special properties use inheritance under special
3107 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3108 and the properties ending in \"_ALL\" when they are used as descriptor
3109 for valid values of a property.
3111 Note for programmers:
3112 When querying an entry with `org-entry-get', you can control if inheritance
3113 should be used. By default, `org-entry-get' looks only at the local
3114 properties. You can request inheritance by setting the inherit argument
3115 to t (to force inheritance) or to `selective' (to respect the setting
3116 in this variable)."
3117 :group 'org-properties
3118 :type '(choice
3119 (const :tag "Not" nil)
3120 (const :tag "Always" t)
3121 (repeat :tag "Specific properties" (string :tag "Property"))
3122 (regexp :tag "Properties matched by regexp")))
3124 (defun org-property-inherit-p (property)
3125 "Check if PROPERTY is one that should be inherited."
3126 (cond
3127 ((eq org-use-property-inheritance t) t)
3128 ((not org-use-property-inheritance) nil)
3129 ((stringp org-use-property-inheritance)
3130 (string-match org-use-property-inheritance property))
3131 ((listp org-use-property-inheritance)
3132 (member property org-use-property-inheritance))
3133 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3135 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3136 "The default column format, if no other format has been defined.
3137 This variable can be set on the per-file basis by inserting a line
3139 #+COLUMNS: %25ITEM ....."
3140 :group 'org-properties
3141 :type 'string)
3143 (defcustom org-columns-ellipses ".."
3144 "The ellipses to be used when a field in column view is truncated.
3145 When this is the empty string, as many characters as possible are shown,
3146 but then there will be no visual indication that the field has been truncated.
3147 When this is a string of length N, the last N characters of a truncated
3148 field are replaced by this string. If the column is narrower than the
3149 ellipses string, only part of the ellipses string will be shown."
3150 :group 'org-properties
3151 :type 'string)
3153 (defcustom org-columns-modify-value-for-display-function nil
3154 "Function that modifies values for display in column view.
3155 For example, it can be used to cut out a certain part from a time stamp.
3156 The function must take 2 arguments:
3158 column-title The title of the column (*not* the property name)
3159 value The value that should be modified.
3161 The function should return the value that should be displayed,
3162 or nil if the normal value should be used."
3163 :group 'org-properties
3164 :type 'function)
3166 (defcustom org-effort-property "Effort"
3167 "The property that is being used to keep track of effort estimates.
3168 Effort estimates given in this property need to have the format H:MM."
3169 :group 'org-properties
3170 :group 'org-progress
3171 :type '(string :tag "Property"))
3173 (defconst org-global-properties-fixed
3174 '(("VISIBILITY_ALL" . "folded children content all")
3175 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3176 "List of property/value pairs that can be inherited by any entry.
3178 These are fixed values, for the preset properties. The user variable
3179 that can be used to add to this list is `org-global-properties'.
3181 The entries in this list are cons cells where the car is a property
3182 name and cdr is a string with the value. If the value represents
3183 multiple items like an \"_ALL\" property, separate the items by
3184 spaces.")
3186 (defcustom org-global-properties nil
3187 "List of property/value pairs that can be inherited by any entry.
3189 This list will be combined with the constant `org-global-properties-fixed'.
3191 The entries in this list are cons cells where the car is a property
3192 name and cdr is a string with the value.
3194 You can set buffer-local values for the same purpose in the variable
3195 `org-file-properties' this by adding lines like
3197 #+PROPERTY: NAME VALUE"
3198 :group 'org-properties
3199 :type '(repeat
3200 (cons (string :tag "Property")
3201 (string :tag "Value"))))
3203 (defvar org-file-properties nil
3204 "List of property/value pairs that can be inherited by any entry.
3205 Valid for the current buffer.
3206 This variable is populated from #+PROPERTY lines.")
3207 (make-variable-buffer-local 'org-file-properties)
3209 (defgroup org-agenda nil
3210 "Options concerning agenda views in Org-mode."
3211 :tag "Org Agenda"
3212 :group 'org)
3214 (defvar org-category nil
3215 "Variable used by org files to set a category for agenda display.
3216 Such files should use a file variable to set it, for example
3218 # -*- mode: org; org-category: \"ELisp\"
3220 or contain a special line
3222 #+CATEGORY: ELisp
3224 If the file does not specify a category, then file's base name
3225 is used instead.")
3226 (make-variable-buffer-local 'org-category)
3227 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3229 (defcustom org-agenda-files nil
3230 "The files to be used for agenda display.
3231 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3232 \\[org-remove-file]. You can also use customize to edit the list.
3234 If an entry is a directory, all files in that directory that are matched by
3235 `org-agenda-file-regexp' will be part of the file list.
3237 If the value of the variable is not a list but a single file name, then
3238 the list of agenda files is actually stored and maintained in that file, one
3239 agenda file per line. In this file paths can be given relative to
3240 `org-directory'. Tilde expansion and environment variable substitution
3241 are also made."
3242 :group 'org-agenda
3243 :type '(choice
3244 (repeat :tag "List of files and directories" file)
3245 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3247 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3248 "Regular expression to match files for `org-agenda-files'.
3249 If any element in the list in that variable contains a directory instead
3250 of a normal file, all files in that directory that are matched by this
3251 regular expression will be included."
3252 :group 'org-agenda
3253 :type 'regexp)
3255 (defcustom org-agenda-text-search-extra-files nil
3256 "List of extra files to be searched by text search commands.
3257 These files will be search in addition to the agenda files by the
3258 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3259 Note that these files will only be searched for text search commands,
3260 not for the other agenda views like todo lists, tag searches or the weekly
3261 agenda. This variable is intended to list notes and possibly archive files
3262 that should also be searched by these two commands.
3263 In fact, if the first element in the list is the symbol `agenda-archives',
3264 than all archive files of all agenda files will be added to the search
3265 scope."
3266 :group 'org-agenda
3267 :type '(set :greedy t
3268 (const :tag "Agenda Archives" agenda-archives)
3269 (repeat :inline t (file))))
3271 (if (fboundp 'defvaralias)
3272 (defvaralias 'org-agenda-multi-occur-extra-files
3273 'org-agenda-text-search-extra-files))
3275 (defcustom org-agenda-skip-unavailable-files nil
3276 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3277 A nil value means to remove them, after a query, from the list."
3278 :group 'org-agenda
3279 :type 'boolean)
3281 (defcustom org-calendar-to-agenda-key [?c]
3282 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3283 The command `org-calendar-goto-agenda' will be bound to this key. The
3284 default is the character `c' because then `c' can be used to switch back and
3285 forth between agenda and calendar."
3286 :group 'org-agenda
3287 :type 'sexp)
3289 (defcustom org-calendar-agenda-action-key [?k]
3290 "The key to be installed in `calendar-mode-map' for agenda-action.
3291 The command `org-agenda-action' will be bound to this key. The
3292 default is the character `k' because we use the same key in the agenda."
3293 :group 'org-agenda
3294 :type 'sexp)
3296 (defcustom org-calendar-insert-diary-entry-key [?i]
3297 "The key to be installed in `calendar-mode-map' for adding diary entries.
3298 This option is irrelevant until `org-agenda-diary-file' has been configured
3299 to point to an Org-mode file. When that is the case, the command
3300 `org-agenda-diary-entry' will be bound to the key given here, by default
3301 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3302 if you want to continue doing this, you need to change this to a different
3303 key."
3304 :group 'org-agenda
3305 :type 'sexp)
3307 (defcustom org-agenda-diary-file 'diary-file
3308 "File to which to add new entries with the `i' key in agenda and calendar.
3309 When this is the symbol `diary-file', the functionality in the Emacs
3310 calendar will be used to add entries to the `diary-file'. But when this
3311 points to a file, `org-agenda-diary-entry' will be used instead."
3312 :group 'org-agenda
3313 :type '(choice
3314 (const :tag "The standard Emacs diary file" diary-file)
3315 (file :tag "Special Org file diary entries")))
3317 (eval-after-load "calendar"
3318 '(progn
3319 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3320 'org-calendar-goto-agenda)
3321 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3322 'org-agenda-action)
3323 (add-hook 'calendar-mode-hook
3324 (lambda ()
3325 (unless (eq org-agenda-diary-file 'diary-file)
3326 (define-key calendar-mode-map
3327 org-calendar-insert-diary-entry-key
3328 'org-agenda-diary-entry))))))
3330 (defgroup org-latex nil
3331 "Options for embedding LaTeX code into Org-mode."
3332 :tag "Org LaTeX"
3333 :group 'org)
3335 (defcustom org-format-latex-options
3336 '(:foreground default :background default :scale 1.0
3337 :html-foreground "Black" :html-background "Transparent"
3338 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3339 "Options for creating images from LaTeX fragments.
3340 This is a property list with the following properties:
3341 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3342 `default' means use the foreground of the default face.
3343 :background the background color, or \"Transparent\".
3344 `default' means use the background of the default face.
3345 :scale a scaling factor for the size of the images, to get more pixels
3346 :html-foreground, :html-background, :html-scale
3347 the same numbers for HTML export.
3348 :matchers a list indicating which matchers should be used to
3349 find LaTeX fragments. Valid members of this list are:
3350 \"begin\" find environments
3351 \"$1\" find single characters surrounded by $.$
3352 \"$\" find math expressions surrounded by $...$
3353 \"$$\" find math expressions surrounded by $$....$$
3354 \"\\(\" find math expressions surrounded by \\(...\\)
3355 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3356 :group 'org-latex
3357 :type 'plist)
3359 (defcustom org-format-latex-signal-error t
3360 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3361 When nil, just push out a message."
3362 :group 'org-latex
3363 :version "24.1"
3364 :type 'boolean)
3366 (defcustom org-latex-to-mathml-jar-file nil
3367 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3368 Use this to specify additional executable file say a jar file.
3370 When using MathToWeb as the converter, specify the full-path to
3371 your mathtoweb.jar file."
3372 :group 'org-latex
3373 :version "24.1"
3374 :type '(choice
3375 (const :tag "None" nil)
3376 (file :tag "JAR file" :must-match t)))
3378 (defcustom org-latex-to-mathml-convert-command nil
3379 "Command to convert LaTeX fragments to MathML.
3380 Replace format-specifiers in the command as noted below and use
3381 `shell-command' to convert LaTeX to MathML.
3382 %j: Executable file in fully expanded form as specified by
3383 `org-latex-to-mathml-jar-file'.
3384 %I: Input LaTeX file in fully expanded form
3385 %o: Output MathML file
3386 This command is used by `org-create-math-formula'.
3388 When using MathToWeb as the converter, set this to
3389 \"java -jar %j -unicode -force -df %o %I\"."
3390 :group 'org-latex
3391 :version "24.1"
3392 :type '(choice
3393 (const :tag "None" nil)
3394 (string :tag "\nShell command")))
3396 (defun org-format-latex-mathml-available-p ()
3397 "Return t if `org-latex-to-mathml-convert-command' is usable."
3398 (save-match-data
3399 (when (and (boundp 'org-latex-to-mathml-convert-command)
3400 org-latex-to-mathml-convert-command)
3401 (let ((executable (car (split-string
3402 org-latex-to-mathml-convert-command))))
3403 (when (executable-find executable)
3404 (if (string-match
3405 "%j" org-latex-to-mathml-convert-command)
3406 (file-readable-p org-latex-to-mathml-jar-file)
3407 t))))))
3409 (defcustom org-format-latex-header "\\documentclass{article}
3410 \\usepackage[usenames]{color}
3411 \\usepackage{amsmath}
3412 \\usepackage[mathscr]{eucal}
3413 \\pagestyle{empty} % do not remove
3414 \[PACKAGES]
3415 \[DEFAULT-PACKAGES]
3416 % The settings below are copied from fullpage.sty
3417 \\setlength{\\textwidth}{\\paperwidth}
3418 \\addtolength{\\textwidth}{-3cm}
3419 \\setlength{\\oddsidemargin}{1.5cm}
3420 \\addtolength{\\oddsidemargin}{-2.54cm}
3421 \\setlength{\\evensidemargin}{\\oddsidemargin}
3422 \\setlength{\\textheight}{\\paperheight}
3423 \\addtolength{\\textheight}{-\\headheight}
3424 \\addtolength{\\textheight}{-\\headsep}
3425 \\addtolength{\\textheight}{-\\footskip}
3426 \\addtolength{\\textheight}{-3cm}
3427 \\setlength{\\topmargin}{1.5cm}
3428 \\addtolength{\\topmargin}{-2.54cm}"
3429 "The document header used for processing LaTeX fragments.
3430 It is imperative that this header make sure that no page number
3431 appears on the page. The package defined in the variables
3432 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3433 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3434 will be appended."
3435 :group 'org-latex
3436 :type 'string)
3438 (defvar org-format-latex-header-extra nil)
3440 (defun org-set-packages-alist (var val)
3441 "Set the packages alist and make sure it has 3 elements per entry."
3442 (set var (mapcar (lambda (x)
3443 (if (and (consp x) (= (length x) 2))
3444 (list (car x) (nth 1 x) t)
3446 val)))
3448 (defun org-get-packages-alist (var)
3450 "Get the packages alist and make sure it has 3 elements per entry."
3451 (mapcar (lambda (x)
3452 (if (and (consp x) (= (length x) 2))
3453 (list (car x) (nth 1 x) t)
3455 (default-value var)))
3457 ;; The following variables are defined here because is it also used
3458 ;; when formatting latex fragments. Originally it was part of the
3459 ;; LaTeX exporter, which is why the name includes "export".
3460 (defcustom org-export-latex-default-packages-alist
3461 '(("AUTO" "inputenc" t)
3462 ("T1" "fontenc" t)
3463 ("" "fixltx2e" nil)
3464 ("" "graphicx" t)
3465 ("" "longtable" nil)
3466 ("" "float" nil)
3467 ("" "wrapfig" nil)
3468 ("" "soul" t)
3469 ("" "textcomp" t)
3470 ("" "marvosym" t)
3471 ("" "wasysym" t)
3472 ("" "latexsym" t)
3473 ("" "amssymb" t)
3474 ("" "hyperref" nil)
3475 "\\tolerance=1000"
3477 "Alist of default packages to be inserted in the header.
3478 Change this only if one of the packages here causes an incompatibility
3479 with another package you are using.
3480 The packages in this list are needed by one part or another of Org-mode
3481 to function properly.
3483 - inputenc, fontenc: for basic font and character selection
3484 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3485 for interpreting the entities in `org-entities'. You can skip some of these
3486 packages if you don't use any of the symbols in it.
3487 - graphicx: for including images
3488 - float, wrapfig: for figure placement
3489 - longtable: for long tables
3490 - hyperref: for cross references
3492 Therefore you should not modify this variable unless you know what you
3493 are doing. The one reason to change it anyway is that you might be loading
3494 some other package that conflicts with one of the default packages.
3495 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3496 If SNIPPET-FLAG is t, the package also needs to be included when
3497 compiling LaTeX snippets into images for inclusion into HTML."
3498 :group 'org-export-latex
3499 :set 'org-set-packages-alist
3500 :get 'org-get-packages-alist
3501 :version "24.1"
3502 :type '(repeat
3503 (choice
3504 (list :tag "options/package pair"
3505 (string :tag "options")
3506 (string :tag "package")
3507 (boolean :tag "Snippet"))
3508 (string :tag "A line of LaTeX"))))
3510 (defcustom org-export-latex-packages-alist nil
3511 "Alist of packages to be inserted in every LaTeX header.
3512 These will be inserted after `org-export-latex-default-packages-alist'.
3513 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3514 SNIPPET-FLAG, when t, indicates that this package is also needed when
3515 turning LaTeX snippets into images for inclusion into HTML.
3516 Make sure that you only list packages here which:
3517 - you want in every file
3518 - do not conflict with the default packages in
3519 `org-export-latex-default-packages-alist'
3520 - do not conflict with the setup in `org-format-latex-header'."
3521 :group 'org-export-latex
3522 :set 'org-set-packages-alist
3523 :get 'org-get-packages-alist
3524 :type '(repeat
3525 (choice
3526 (list :tag "options/package pair"
3527 (string :tag "options")
3528 (string :tag "package")
3529 (boolean :tag "Snippet"))
3530 (string :tag "A line of LaTeX"))))
3533 (defgroup org-appearance nil
3534 "Settings for Org-mode appearance."
3535 :tag "Org Appearance"
3536 :group 'org)
3538 (defcustom org-level-color-stars-only nil
3539 "Non-nil means fontify only the stars in each headline.
3540 When nil, the entire headline is fontified.
3541 Changing it requires restart of `font-lock-mode' to become effective
3542 also in regions already fontified."
3543 :group 'org-appearance
3544 :type 'boolean)
3546 (defcustom org-hide-leading-stars nil
3547 "Non-nil means hide the first N-1 stars in a headline.
3548 This works by using the face `org-hide' for these stars. This
3549 face is white for a light background, and black for a dark
3550 background. You may have to customize the face `org-hide' to
3551 make this work.
3552 Changing it requires restart of `font-lock-mode' to become effective
3553 also in regions already fontified.
3554 You may also set this on a per-file basis by adding one of the following
3555 lines to the buffer:
3557 #+STARTUP: hidestars
3558 #+STARTUP: showstars"
3559 :group 'org-appearance
3560 :type 'boolean)
3562 (defcustom org-hidden-keywords nil
3563 "List of symbols corresponding to keywords to be hidden the org buffer.
3564 For example, a value '(title) for this list will make the document's title
3565 appear in the buffer without the initial #+TITLE: keyword."
3566 :group 'org-appearance
3567 :version "24.1"
3568 :type '(set (const :tag "#+AUTHOR" author)
3569 (const :tag "#+DATE" date)
3570 (const :tag "#+EMAIL" email)
3571 (const :tag "#+TITLE" title)))
3573 (defcustom org-fontify-done-headline nil
3574 "Non-nil means change the face of a headline if it is marked DONE.
3575 Normally, only the TODO/DONE keyword indicates the state of a headline.
3576 When this is non-nil, the headline after the keyword is set to the
3577 `org-headline-done' as an additional indication."
3578 :group 'org-appearance
3579 :type 'boolean)
3581 (defcustom org-fontify-emphasized-text t
3582 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3583 Changing this variable requires a restart of Emacs to take effect."
3584 :group 'org-appearance
3585 :type 'boolean)
3587 (defcustom org-fontify-whole-heading-line nil
3588 "Non-nil means fontify the whole line for headings.
3589 This is useful when setting a background color for the
3590 org-level-* faces."
3591 :group 'org-appearance
3592 :type 'boolean)
3594 (defcustom org-highlight-latex-fragments-and-specials nil
3595 "Non-nil means fontify what is treated specially by the exporters."
3596 :group 'org-appearance
3597 :type 'boolean)
3599 (defcustom org-hide-emphasis-markers nil
3600 "Non-nil mean font-lock should hide the emphasis marker characters."
3601 :group 'org-appearance
3602 :type 'boolean)
3604 (defcustom org-pretty-entities nil
3605 "Non-nil means show entities as UTF8 characters.
3606 When nil, the \\name form remains in the buffer."
3607 :group 'org-appearance
3608 :version "24.1"
3609 :type 'boolean)
3611 (defcustom org-pretty-entities-include-sub-superscripts t
3612 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3613 :group 'org-appearance
3614 :version "24.1"
3615 :type 'boolean)
3617 (defvar org-emph-re nil
3618 "Regular expression for matching emphasis.
3619 After a match, the match groups contain these elements:
3620 0 The match of the full regular expression, including the characters
3621 before and after the proper match
3622 1 The character before the proper match, or empty at beginning of line
3623 2 The proper match, including the leading and trailing markers
3624 3 The leading marker like * or /, indicating the type of highlighting
3625 4 The text between the emphasis markers, not including the markers
3626 5 The character after the match, empty at the end of a line")
3627 (defvar org-verbatim-re nil
3628 "Regular expression for matching verbatim text.")
3629 (defvar org-emphasis-regexp-components) ; defined just below
3630 (defvar org-emphasis-alist) ; defined just below
3631 (defun org-set-emph-re (var val)
3632 "Set variable and compute the emphasis regular expression."
3633 (set var val)
3634 (when (and (boundp 'org-emphasis-alist)
3635 (boundp 'org-emphasis-regexp-components)
3636 org-emphasis-alist org-emphasis-regexp-components)
3637 (let* ((e org-emphasis-regexp-components)
3638 (pre (car e))
3639 (post (nth 1 e))
3640 (border (nth 2 e))
3641 (body (nth 3 e))
3642 (nl (nth 4 e))
3643 (body1 (concat body "*?"))
3644 (markers (mapconcat 'car org-emphasis-alist ""))
3645 (vmarkers (mapconcat
3646 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3647 org-emphasis-alist "")))
3648 ;; make sure special characters appear at the right position in the class
3649 (if (string-match "\\^" markers)
3650 (setq markers (concat (replace-match "" t t markers) "^")))
3651 (if (string-match "-" markers)
3652 (setq markers (concat (replace-match "" t t markers) "-")))
3653 (if (string-match "\\^" vmarkers)
3654 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3655 (if (string-match "-" vmarkers)
3656 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3657 (if (> nl 0)
3658 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3659 (int-to-string nl) "\\}")))
3660 ;; Make the regexp
3661 (setq org-emph-re
3662 (concat "\\([" pre "]\\|^\\)"
3663 "\\("
3664 "\\([" markers "]\\)"
3665 "\\("
3666 "[^" border "]\\|"
3667 "[^" border "]"
3668 body1
3669 "[^" border "]"
3670 "\\)"
3671 "\\3\\)"
3672 "\\([" post "]\\|$\\)"))
3673 (setq org-verbatim-re
3674 (concat "\\([" pre "]\\|^\\)"
3675 "\\("
3676 "\\([" vmarkers "]\\)"
3677 "\\("
3678 "[^" border "]\\|"
3679 "[^" border "]"
3680 body1
3681 "[^" border "]"
3682 "\\)"
3683 "\\3\\)"
3684 "\\([" post "]\\|$\\)")))))
3686 (defcustom org-emphasis-regexp-components
3687 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3688 "Components used to build the regular expression for emphasis.
3689 This is a list with five entries. Terminology: In an emphasis string
3690 like \" *strong word* \", we call the initial space PREMATCH, the final
3691 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3692 and \"trong wor\" is the body. The different components in this variable
3693 specify what is allowed/forbidden in each part:
3695 pre Chars allowed as prematch. Beginning of line will be allowed too.
3696 post Chars allowed as postmatch. End of line will be allowed too.
3697 border The chars *forbidden* as border characters.
3698 body-regexp A regexp like \".\" to match a body character. Don't use
3699 non-shy groups here, and don't allow newline here.
3700 newline The maximum number of newlines allowed in an emphasis exp.
3702 Use customize to modify this, or restart Emacs after changing it."
3703 :group 'org-appearance
3704 :set 'org-set-emph-re
3705 :type '(list
3706 (sexp :tag "Allowed chars in pre ")
3707 (sexp :tag "Allowed chars in post ")
3708 (sexp :tag "Forbidden chars in border ")
3709 (sexp :tag "Regexp for body ")
3710 (integer :tag "number of newlines allowed")
3711 (option (boolean :tag "Please ignore this button"))))
3713 (defcustom org-emphasis-alist
3714 `(("*" bold "<b>" "</b>")
3715 ("/" italic "<i>" "</i>")
3716 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3717 ("=" org-code "<code>" "</code>" verbatim)
3718 ("~" org-verbatim "<code>" "</code>" verbatim)
3719 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3720 "<del>" "</del>")
3722 "Special syntax for emphasized text.
3723 Text starting and ending with a special character will be emphasized, for
3724 example *bold*, _underlined_ and /italic/. This variable sets the marker
3725 characters, the face to be used by font-lock for highlighting in Org-mode
3726 Emacs buffers, and the HTML tags to be used for this.
3727 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3728 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3729 Use customize to modify this, or restart Emacs after changing it."
3730 :group 'org-appearance
3731 :set 'org-set-emph-re
3732 :type '(repeat
3733 (list
3734 (string :tag "Marker character")
3735 (choice
3736 (face :tag "Font-lock-face")
3737 (plist :tag "Face property list"))
3738 (string :tag "HTML start tag")
3739 (string :tag "HTML end tag")
3740 (option (const verbatim)))))
3742 (defvar org-protecting-blocks
3743 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3744 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3745 This is needed for font-lock setup.")
3747 ;;; Miscellaneous options
3749 (defgroup org-completion nil
3750 "Completion in Org-mode."
3751 :tag "Org Completion"
3752 :group 'org)
3754 (defcustom org-completion-use-ido nil
3755 "Non-nil means use ido completion wherever possible.
3756 Note that `ido-mode' must be active for this variable to be relevant.
3757 If you decide to turn this variable on, you might well want to turn off
3758 `org-outline-path-complete-in-steps'.
3759 See also `org-completion-use-iswitchb'."
3760 :group 'org-completion
3761 :type 'boolean)
3763 (defcustom org-completion-use-iswitchb nil
3764 "Non-nil means use iswitchb completion wherever possible.
3765 Note that `iswitchb-mode' must be active for this variable to be relevant.
3766 If you decide to turn this variable on, you might well want to turn off
3767 `org-outline-path-complete-in-steps'.
3768 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3769 :group 'org-completion
3770 :type 'boolean)
3772 (defcustom org-completion-fallback-command 'hippie-expand
3773 "The expansion command called by \\[pcomplete] in normal context.
3774 Normal means, no org-mode-specific context."
3775 :group 'org-completion
3776 :type 'function)
3778 ;;; Functions and variables from their packages
3779 ;; Declared here to avoid compiler warnings
3781 ;; XEmacs only
3782 (defvar outline-mode-menu-heading)
3783 (defvar outline-mode-menu-show)
3784 (defvar outline-mode-menu-hide)
3785 (defvar zmacs-regions) ; XEmacs regions
3787 ;; Emacs only
3788 (defvar mark-active)
3790 ;; Various packages
3791 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3792 (declare-function calendar-forward-day "cal-move" (arg))
3793 (declare-function calendar-goto-date "cal-move" (date))
3794 (declare-function calendar-goto-today "cal-move" ())
3795 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3796 (defvar calc-embedded-close-formula)
3797 (defvar calc-embedded-open-formula)
3798 (declare-function cdlatex-tab "ext:cdlatex" ())
3799 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3800 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3801 (defvar font-lock-unfontify-region-function)
3802 (declare-function iswitchb-read-buffer "iswitchb"
3803 (prompt &optional default require-match start matches-set))
3804 (defvar iswitchb-temp-buflist)
3805 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3806 (defvar org-agenda-tags-todo-honor-ignore-options)
3807 (declare-function org-agenda-skip "org-agenda" ())
3808 (declare-function
3809 org-agenda-format-item "org-agenda"
3810 (extra txt &optional category tags dotime noprefix remove-re habitp))
3811 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3812 (declare-function org-agenda-change-all-lines "org-agenda"
3813 (newhead hdmarker &optional fixface just-this))
3814 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3815 (declare-function org-agenda-maybe-redo "org-agenda" ())
3816 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3817 (beg end))
3818 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3819 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3820 "org-agenda" (&optional end))
3821 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3822 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3823 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3824 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3825 (declare-function org-indent-mode "org-indent" (&optional arg))
3826 (declare-function parse-time-string "parse-time" (string))
3827 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3828 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3829 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3830 (defvar remember-data-file)
3831 (defvar texmathp-why)
3832 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3833 (declare-function table--at-cell-p "table" (position &optional object at-column))
3835 (defvar w3m-current-url)
3836 (defvar w3m-current-title)
3838 (defvar org-latex-regexps)
3840 ;;; Autoload and prepare some org modules
3842 ;; Some table stuff that needs to be defined here, because it is used
3843 ;; by the functions setting up org-mode or checking for table context.
3845 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3846 "Detect an org-type or table-type table.")
3847 (defconst org-table-line-regexp "^[ \t]*|"
3848 "Detect an org-type table line.")
3849 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3850 "Detect an org-type table line.")
3851 (defconst org-table-hline-regexp "^[ \t]*|-"
3852 "Detect an org-type table hline.")
3853 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3854 "Detect a table-type table hline.")
3855 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3856 "Detect the first line outside a table when searching from within it.
3857 This works for both table types.")
3859 ;; Autoload the functions in org-table.el that are needed by functions here.
3861 (eval-and-compile
3862 (org-autoload "org-table"
3863 '(org-table-align org-table-begin org-table-blank-field
3864 org-table-convert org-table-convert-region org-table-copy-down
3865 org-table-copy-region org-table-create
3866 org-table-create-or-convert-from-region
3867 org-table-create-with-table.el org-table-current-dline
3868 org-table-cut-region org-table-delete-column org-table-edit-field
3869 org-table-edit-formulas org-table-end org-table-eval-formula
3870 org-table-export org-table-field-info
3871 org-table-get-stored-formulas org-table-goto-column
3872 org-table-hline-and-move org-table-import org-table-insert-column
3873 org-table-insert-hline org-table-insert-row org-table-iterate
3874 org-table-justify-field-maybe org-table-kill-row
3875 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3876 org-table-move-column org-table-move-column-left
3877 org-table-move-column-right org-table-move-row
3878 org-table-move-row-down org-table-move-row-up
3879 org-table-next-field org-table-next-row org-table-paste-rectangle
3880 org-table-previous-field org-table-recalculate
3881 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3882 org-table-toggle-coordinate-overlays
3883 org-table-toggle-formula-debugger org-table-wrap-region
3884 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3885 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3886 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3888 (defun org-at-table-p (&optional table-type)
3889 "Return t if the cursor is inside an org-type table.
3890 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3891 (if org-enable-table-editor
3892 (save-excursion
3893 (beginning-of-line 1)
3894 (looking-at (if table-type org-table-any-line-regexp
3895 org-table-line-regexp)))
3896 nil))
3897 (defsubst org-table-p () (org-at-table-p))
3899 (defun org-at-table.el-p ()
3900 "Return t if and only if we are at a table.el table."
3901 (and (org-at-table-p 'any)
3902 (save-excursion
3903 (goto-char (org-table-begin 'any))
3904 (looking-at org-table1-hline-regexp))))
3905 (defun org-table-recognize-table.el ()
3906 "If there is a table.el table nearby, recognize it and move into it."
3907 (if org-table-tab-recognizes-table.el
3908 (if (org-at-table.el-p)
3909 (progn
3910 (beginning-of-line 1)
3911 (if (looking-at org-table-dataline-regexp)
3913 (if (looking-at org-table1-hline-regexp)
3914 (progn
3915 (beginning-of-line 2)
3916 (if (looking-at org-table-any-border-regexp)
3917 (beginning-of-line -1)))))
3918 (if (re-search-forward "|" (org-table-end t) t)
3919 (progn
3920 (require 'table)
3921 (if (table--at-cell-p (point))
3923 (message "recognizing table.el table...")
3924 (table-recognize-table)
3925 (message "recognizing table.el table...done")))
3926 (error "This should not happen"))
3928 nil)
3929 nil))
3931 (defun org-at-table-hline-p ()
3932 "Return t if the cursor is inside a hline in a table."
3933 (if org-enable-table-editor
3934 (save-excursion
3935 (beginning-of-line 1)
3936 (looking-at org-table-hline-regexp))
3937 nil))
3939 (defvar org-table-clean-did-remove-column nil)
3941 (defun org-table-map-tables (function &optional quietly)
3942 "Apply FUNCTION to the start of all tables in the buffer."
3943 (save-excursion
3944 (save-restriction
3945 (widen)
3946 (goto-char (point-min))
3947 (while (re-search-forward org-table-any-line-regexp nil t)
3948 (unless quietly
3949 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3950 (beginning-of-line 1)
3951 (when (looking-at org-table-line-regexp)
3952 (save-excursion (funcall function))
3953 (or (looking-at org-table-line-regexp)
3954 (forward-char 1)))
3955 (re-search-forward org-table-any-border-regexp nil 1))))
3956 (unless quietly (message "Mapping tables: done")))
3958 ;; Declare and autoload functions from org-exp.el & Co
3960 (declare-function org-default-export-plist "org-exp")
3961 (declare-function org-infile-export-plist "org-exp")
3962 (declare-function org-get-current-options "org-exp")
3963 (eval-and-compile
3964 (org-autoload "org-exp"
3965 '(org-export org-export-visible
3966 org-insert-export-options-template
3967 org-table-clean-before-export))
3968 (org-autoload "org-ascii"
3969 '(org-export-as-ascii org-export-ascii-preprocess
3970 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3971 org-export-region-as-ascii))
3972 (org-autoload "org-latex"
3973 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3974 org-replace-region-by-latex org-export-region-as-latex
3975 org-export-as-latex org-export-as-pdf
3976 org-export-as-pdf-and-open))
3977 (org-autoload "org-html"
3978 '(org-export-as-html-and-open
3979 org-export-as-html-batch org-export-as-html-to-buffer
3980 org-replace-region-by-html org-export-region-as-html
3981 org-export-as-html))
3982 (org-autoload "org-docbook"
3983 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3984 org-replace-region-by-docbook org-export-region-as-docbook
3985 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3986 org-export-as-docbook))
3987 (org-autoload "org-icalendar"
3988 '(org-export-icalendar-this-file
3989 org-export-icalendar-all-agenda-files
3990 org-export-icalendar-combine-agenda-files))
3991 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3992 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3994 ;; Declare and autoload functions from org-agenda.el
3996 (eval-and-compile
3997 (org-autoload "org-agenda"
3998 '(org-agenda org-agenda-list org-search-view
3999 org-todo-list org-tags-view org-agenda-list-stuck-projects
4000 org-diary org-agenda-to-appt
4001 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4003 ;; Autoload org-remember
4005 (eval-and-compile
4006 (org-autoload "org-remember"
4007 '(org-remember-insinuate org-remember-annotation
4008 org-remember-apply-template org-remember org-remember-handler)))
4010 (eval-and-compile
4011 (org-autoload "org-capture"
4012 '(org-capture org-capture-insert-template-here
4013 org-capture-import-remember-templates)))
4015 ;; Autoload org-clock.el
4017 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4018 (beg end))
4019 (declare-function org-clock-update-mode-line "org-clock" ())
4020 (declare-function org-resolve-clocks "org-clock"
4021 (&optional also-non-dangling-p prompt last-valid))
4022 (defvar org-clock-start-time)
4023 (defvar org-clock-marker (make-marker)
4024 "Marker recording the last clock-in.")
4025 (defvar org-clock-hd-marker (make-marker)
4026 "Marker recording the last clock-in, but the headline position.")
4027 (defvar org-clock-heading ""
4028 "The heading of the current clock entry.")
4029 (defun org-clock-is-active ()
4030 "Return non-nil if clock is currently running.
4031 The return value is actually the clock marker."
4032 (marker-buffer org-clock-marker))
4034 (eval-and-compile
4035 (org-autoload
4036 "org-clock"
4037 '(org-clock-in org-clock-out org-clock-cancel
4038 org-clock-goto org-clock-sum org-clock-display
4039 org-clock-remove-overlays org-clock-report
4040 org-clocktable-shift org-dblock-write:clocktable
4041 org-get-clocktable org-resolve-clocks)))
4043 (defun org-clock-update-time-maybe ()
4044 "If this is a CLOCK line, update it and return t.
4045 Otherwise, return nil."
4046 (interactive)
4047 (save-excursion
4048 (beginning-of-line 1)
4049 (skip-chars-forward " \t")
4050 (when (looking-at org-clock-string)
4051 (let ((re (concat "[ \t]*" org-clock-string
4052 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4053 "\\([ \t]*=>.*\\)?\\)?"))
4054 ts te h m s neg)
4055 (cond
4056 ((not (looking-at re))
4057 nil)
4058 ((not (match-end 2))
4059 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4060 (> org-clock-marker (point))
4061 (<= org-clock-marker (point-at-eol)))
4062 ;; The clock is running here
4063 (setq org-clock-start-time
4064 (apply 'encode-time
4065 (org-parse-time-string (match-string 1))))
4066 (org-clock-update-mode-line)))
4068 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4069 (end-of-line 1)
4070 (setq ts (match-string 1)
4071 te (match-string 3))
4072 (setq s (- (org-float-time
4073 (apply 'encode-time (org-parse-time-string te)))
4074 (org-float-time
4075 (apply 'encode-time (org-parse-time-string ts))))
4076 neg (< s 0)
4077 s (abs s)
4078 h (floor (/ s 3600))
4079 s (- s (* 3600 h))
4080 m (floor (/ s 60))
4081 s (- s (* 60 s)))
4082 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4083 t))))))
4085 (defun org-check-running-clock ()
4086 "Check if the current buffer contains the running clock.
4087 If yes, offer to stop it and to save the buffer with the changes."
4088 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4089 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4090 (buffer-name))))
4091 (org-clock-out)
4092 (when (y-or-n-p "Save changed buffer?")
4093 (save-buffer))))
4095 (defun org-clocktable-try-shift (dir n)
4096 "Check if this line starts a clock table, if yes, shift the time block."
4097 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4098 (org-clocktable-shift dir n)))
4100 ;; Autoload org-timer.el
4102 (eval-and-compile
4103 (org-autoload
4104 "org-timer"
4105 '(org-timer-start org-timer org-timer-item
4106 org-timer-change-times-in-region
4107 org-timer-set-timer
4108 org-timer-reset-timers
4109 org-timer-show-remaining-time)))
4111 ;; Autoload org-feed.el
4113 (eval-and-compile
4114 (org-autoload
4115 "org-feed"
4116 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4119 ;; Autoload org-indent.el
4121 ;; Define the variable already here, to make sure we have it.
4122 (defvar org-indent-mode nil
4123 "Non-nil if Org-Indent mode is enabled.
4124 Use the command `org-indent-mode' to change this variable.")
4126 (eval-and-compile
4127 (org-autoload
4128 "org-indent"
4129 '(org-indent-mode)))
4131 ;; Autoload org-mobile.el
4133 (eval-and-compile
4134 (org-autoload
4135 "org-mobile"
4136 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4138 ;; Autoload archiving code
4139 ;; The stuff that is needed for cycling and tags has to be defined here.
4141 (defgroup org-archive nil
4142 "Options concerning archiving in Org-mode."
4143 :tag "Org Archive"
4144 :group 'org-structure)
4146 (defcustom org-archive-location "%s_archive::"
4147 "The location where subtrees should be archived.
4149 The value of this variable is a string, consisting of two parts,
4150 separated by a double-colon. The first part is a filename and
4151 the second part is a headline.
4153 When the filename is omitted, archiving happens in the same file.
4154 %s in the filename will be replaced by the current file
4155 name (without the directory part). Archiving to a different file
4156 is useful to keep archived entries from contributing to the
4157 Org-mode Agenda.
4159 The archived entries will be filed as subtrees of the specified
4160 headline. When the headline is omitted, the subtrees are simply
4161 filed away at the end of the file, as top-level entries. Also in
4162 the heading you can use %s to represent the file name, this can be
4163 useful when using the same archive for a number of different files.
4165 Here are a few examples:
4166 \"%s_archive::\"
4167 If the current file is Projects.org, archive in file
4168 Projects.org_archive, as top-level trees. This is the default.
4170 \"::* Archived Tasks\"
4171 Archive in the current file, under the top-level headline
4172 \"* Archived Tasks\".
4174 \"~/org/archive.org::\"
4175 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4177 \"~/org/archive.org::* From %s\"
4178 Archive in file ~/org/archive.org (absolute path), under headlines
4179 \"From FILENAME\" where file name is the current file name.
4181 \"basement::** Finished Tasks\"
4182 Archive in file ./basement (relative path), as level 3 trees
4183 below the level 2 heading \"** Finished Tasks\".
4185 You may set this option on a per-file basis by adding to the buffer a
4186 line like
4188 #+ARCHIVE: basement::** Finished Tasks
4190 You may also define it locally for a subtree by setting an ARCHIVE property
4191 in the entry. If such a property is found in an entry, or anywhere up
4192 the hierarchy, it will be used."
4193 :group 'org-archive
4194 :type 'string)
4196 (defcustom org-archive-tag "ARCHIVE"
4197 "The tag that marks a subtree as archived.
4198 An archived subtree does not open during visibility cycling, and does
4199 not contribute to the agenda listings.
4200 After changing this, font-lock must be restarted in the relevant buffers to
4201 get the proper fontification."
4202 :group 'org-archive
4203 :group 'org-keywords
4204 :type 'string)
4206 (defcustom org-agenda-skip-archived-trees t
4207 "Non-nil means the agenda will skip any items located in archived trees.
4208 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4209 variable is no longer recommended, you should leave it at the value t.
4210 Instead, use the key `v' to cycle the archives-mode in the agenda."
4211 :group 'org-archive
4212 :group 'org-agenda-skip
4213 :type 'boolean)
4215 (defcustom org-columns-skip-archived-trees t
4216 "Non-nil means ignore archived trees when creating column view."
4217 :group 'org-archive
4218 :group 'org-properties
4219 :type 'boolean)
4221 (defcustom org-cycle-open-archived-trees nil
4222 "Non-nil means `org-cycle' will open archived trees.
4223 An archived tree is a tree marked with the tag ARCHIVE.
4224 When nil, archived trees will stay folded. You can still open them with
4225 normal outline commands like `show-all', but not with the cycling commands."
4226 :group 'org-archive
4227 :group 'org-cycle
4228 :type 'boolean)
4230 (defcustom org-sparse-tree-open-archived-trees nil
4231 "Non-nil means sparse tree construction shows matches in archived trees.
4232 When nil, matches in these trees are highlighted, but the trees are kept in
4233 collapsed state."
4234 :group 'org-archive
4235 :group 'org-sparse-trees
4236 :type 'boolean)
4238 (defun org-cycle-hide-archived-subtrees (state)
4239 "Re-hide all archived subtrees after a visibility state change."
4240 (when (and (not org-cycle-open-archived-trees)
4241 (not (memq state '(overview folded))))
4242 (save-excursion
4243 (let* ((globalp (memq state '(contents all)))
4244 (beg (if globalp (point-min) (point)))
4245 (end (if globalp (point-max) (org-end-of-subtree t))))
4246 (org-hide-archived-subtrees beg end)
4247 (goto-char beg)
4248 (if (looking-at (concat ".*:" org-archive-tag ":"))
4249 (message "%s" (substitute-command-keys
4250 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4252 (defun org-force-cycle-archived ()
4253 "Cycle subtree even if it is archived."
4254 (interactive)
4255 (setq this-command 'org-cycle)
4256 (let ((org-cycle-open-archived-trees t))
4257 (call-interactively 'org-cycle)))
4259 (defun org-hide-archived-subtrees (beg end)
4260 "Re-hide all archived subtrees after a visibility state change."
4261 (save-excursion
4262 (let* ((re (concat ":" org-archive-tag ":")))
4263 (goto-char beg)
4264 (while (re-search-forward re end t)
4265 (when (org-at-heading-p)
4266 (org-flag-subtree t)
4267 (org-end-of-subtree t))))))
4269 (defun org-flag-subtree (flag)
4270 (save-excursion
4271 (org-back-to-heading t)
4272 (outline-end-of-heading)
4273 (outline-flag-region (point)
4274 (progn (org-end-of-subtree t) (point))
4275 flag)))
4277 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4279 (eval-and-compile
4280 (org-autoload "org-archive"
4281 '(org-add-archive-files org-archive-subtree
4282 org-archive-to-archive-sibling org-toggle-archive-tag
4283 org-archive-subtree-default
4284 org-archive-subtree-default-with-confirmation)))
4286 ;; Autoload Column View Code
4288 (declare-function org-columns-number-to-string "org-colview")
4289 (declare-function org-columns-get-format-and-top-level "org-colview")
4290 (declare-function org-columns-compute "org-colview")
4292 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4293 '(org-columns-number-to-string org-columns-get-format-and-top-level
4294 org-columns-compute org-agenda-columns org-columns-remove-overlays
4295 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4297 ;; Autoload ID code
4299 (declare-function org-id-store-link "org-id")
4300 (declare-function org-id-locations-load "org-id")
4301 (declare-function org-id-locations-save "org-id")
4302 (defvar org-id-track-globally)
4303 (org-autoload "org-id"
4304 '(org-id-get-create org-id-new org-id-copy org-id-get
4305 org-id-get-with-outline-path-completion
4306 org-id-get-with-outline-drilling org-id-store-link
4307 org-id-goto org-id-find org-id-store-link))
4309 ;; Autoload Plotting Code
4311 (org-autoload "org-plot"
4312 '(org-plot/gnuplot))
4314 ;;; Variables for pre-computed regular expressions, all buffer local
4316 (defvar org-drawer-regexp nil
4317 "Matches first line of a hidden block.")
4318 (make-variable-buffer-local 'org-drawer-regexp)
4319 (defvar org-todo-regexp nil
4320 "Matches any of the TODO state keywords.")
4321 (make-variable-buffer-local 'org-todo-regexp)
4322 (defvar org-not-done-regexp nil
4323 "Matches any of the TODO state keywords except the last one.")
4324 (make-variable-buffer-local 'org-not-done-regexp)
4325 (defvar org-not-done-heading-regexp nil
4326 "Matches a TODO headline that is not done.")
4327 (make-variable-buffer-local 'org-not-done-regexp)
4328 (defvar org-todo-line-regexp nil
4329 "Matches a headline and puts TODO state into group 2 if present.")
4330 (make-variable-buffer-local 'org-todo-line-regexp)
4331 (defvar org-complex-heading-regexp nil
4332 "Matches a headline and puts everything into groups:
4333 group 1: the stars
4334 group 2: The todo keyword, maybe
4335 group 3: Priority cookie
4336 group 4: True headline
4337 group 5: Tags")
4338 (make-variable-buffer-local 'org-complex-heading-regexp)
4339 (defvar org-complex-heading-regexp-format nil
4340 "Printf format to make regexp to match an exact headline.
4341 This regexp will match the headline of any node which has the
4342 exact headline text that is put into the format, but may have any
4343 TODO state, priority and tags.")
4344 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4345 (defvar org-todo-line-tags-regexp nil
4346 "Matches a headline and puts TODO state into group 2 if present.
4347 Also put tags into group 4 if tags are present.")
4348 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4349 (defvar org-ds-keyword-length 12
4350 "Maximum length of the Deadline and SCHEDULED keywords.")
4351 (make-variable-buffer-local 'org-ds-keyword-length)
4352 (defvar org-deadline-regexp nil
4353 "Matches the DEADLINE keyword.")
4354 (make-variable-buffer-local 'org-deadline-regexp)
4355 (defvar org-deadline-time-regexp nil
4356 "Matches the DEADLINE keyword together with a time stamp.")
4357 (make-variable-buffer-local 'org-deadline-time-regexp)
4358 (defvar org-deadline-line-regexp nil
4359 "Matches the DEADLINE keyword and the rest of the line.")
4360 (make-variable-buffer-local 'org-deadline-line-regexp)
4361 (defvar org-scheduled-regexp nil
4362 "Matches the SCHEDULED keyword.")
4363 (make-variable-buffer-local 'org-scheduled-regexp)
4364 (defvar org-scheduled-time-regexp nil
4365 "Matches the SCHEDULED keyword together with a time stamp.")
4366 (make-variable-buffer-local 'org-scheduled-time-regexp)
4367 (defvar org-closed-time-regexp nil
4368 "Matches the CLOSED keyword together with a time stamp.")
4369 (make-variable-buffer-local 'org-closed-time-regexp)
4371 (defvar org-keyword-time-regexp nil
4372 "Matches any of the 4 keywords, together with the time stamp.")
4373 (make-variable-buffer-local 'org-keyword-time-regexp)
4374 (defvar org-keyword-time-not-clock-regexp nil
4375 "Matches any of the 3 keywords, together with the time stamp.")
4376 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4377 (defvar org-maybe-keyword-time-regexp nil
4378 "Matches a timestamp, possibly preceded by a keyword.")
4379 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4380 (defvar org-planning-or-clock-line-re nil
4381 "Matches a line with planning or clock info.")
4382 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4383 (defvar org-all-time-keywords nil
4384 "List of time keywords.")
4385 (make-variable-buffer-local 'org-all-time-keywords)
4387 (defconst org-plain-time-of-day-regexp
4388 (concat
4389 "\\(\\<[012]?[0-9]"
4390 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4391 "\\(--?"
4392 "\\(\\<[012]?[0-9]"
4393 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4394 "\\)?")
4395 "Regular expression to match a plain time or time range.
4396 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4397 groups carry important information:
4398 0 the full match
4399 1 the first time, range or not
4400 8 the second time, if it is a range.")
4402 (defconst org-plain-time-extension-regexp
4403 (concat
4404 "\\(\\<[012]?[0-9]"
4405 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4406 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4407 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4408 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4409 groups carry important information:
4410 0 the full match
4411 7 hours of duration
4412 9 minutes of duration")
4414 (defconst org-stamp-time-of-day-regexp
4415 (concat
4416 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4417 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4418 "\\(--?"
4419 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4420 "Regular expression to match a timestamp time or time range.
4421 After a match, the following groups carry important information:
4422 0 the full match
4423 1 date plus weekday, for back referencing to make sure both times are on the same day
4424 2 the first time, range or not
4425 4 the second time, if it is a range.")
4427 (defconst org-startup-options
4428 '(("fold" org-startup-folded t)
4429 ("overview" org-startup-folded t)
4430 ("nofold" org-startup-folded nil)
4431 ("showall" org-startup-folded nil)
4432 ("showeverything" org-startup-folded showeverything)
4433 ("content" org-startup-folded content)
4434 ("indent" org-startup-indented t)
4435 ("noindent" org-startup-indented nil)
4436 ("hidestars" org-hide-leading-stars t)
4437 ("showstars" org-hide-leading-stars nil)
4438 ("odd" org-odd-levels-only t)
4439 ("oddeven" org-odd-levels-only nil)
4440 ("align" org-startup-align-all-tables t)
4441 ("noalign" org-startup-align-all-tables nil)
4442 ("inlineimages" org-startup-with-inline-images t)
4443 ("noinlineimages" org-startup-with-inline-images nil)
4444 ("customtime" org-display-custom-times t)
4445 ("logdone" org-log-done time)
4446 ("lognotedone" org-log-done note)
4447 ("nologdone" org-log-done nil)
4448 ("lognoteclock-out" org-log-note-clock-out t)
4449 ("nolognoteclock-out" org-log-note-clock-out nil)
4450 ("logrepeat" org-log-repeat state)
4451 ("lognoterepeat" org-log-repeat note)
4452 ("nologrepeat" org-log-repeat nil)
4453 ("logreschedule" org-log-reschedule time)
4454 ("lognotereschedule" org-log-reschedule note)
4455 ("nologreschedule" org-log-reschedule nil)
4456 ("logredeadline" org-log-redeadline time)
4457 ("lognoteredeadline" org-log-redeadline note)
4458 ("nologredeadline" org-log-redeadline nil)
4459 ("logrefile" org-log-refile time)
4460 ("lognoterefile" org-log-refile note)
4461 ("nologrefile" org-log-refile nil)
4462 ("fninline" org-footnote-define-inline t)
4463 ("nofninline" org-footnote-define-inline nil)
4464 ("fnlocal" org-footnote-section nil)
4465 ("fnauto" org-footnote-auto-label t)
4466 ("fnprompt" org-footnote-auto-label nil)
4467 ("fnconfirm" org-footnote-auto-label confirm)
4468 ("fnplain" org-footnote-auto-label plain)
4469 ("fnadjust" org-footnote-auto-adjust t)
4470 ("nofnadjust" org-footnote-auto-adjust nil)
4471 ("constcgs" constants-unit-system cgs)
4472 ("constSI" constants-unit-system SI)
4473 ("noptag" org-tag-persistent-alist nil)
4474 ("hideblocks" org-hide-block-startup t)
4475 ("nohideblocks" org-hide-block-startup nil)
4476 ("beamer" org-startup-with-beamer-mode t)
4477 ("entitiespretty" org-pretty-entities t)
4478 ("entitiesplain" org-pretty-entities nil))
4479 "Variable associated with STARTUP options for org-mode.
4480 Each element is a list of three items: The startup options as written
4481 in the #+STARTUP line, the corresponding variable, and the value to
4482 set this variable to if the option is found. An optional forth element PUSH
4483 means to push this value onto the list in the variable.")
4485 (defun org-update-property-plist (key val props)
4486 "Update PROPS with KEY and VAL."
4487 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4488 (key (if appending (substring key 0 (- (length key) 1)) key))
4489 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4490 (previous (cdr (assoc key props))))
4491 (if appending
4492 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4493 (cons (cons key val) remainder))))
4495 (defconst org-block-regexp
4496 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4497 "Regular expression for hiding blocks.")
4498 (defconst org-heading-keyword-regexp-format
4499 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4500 "Printf format for a regexp matching an headline with some keyword.
4501 This regexp will match the headline of any node which has the
4502 exact keyword that is put into the format. The keyword isn't in
4503 any group by default, but the stars and the body are.")
4504 (defconst org-heading-keyword-maybe-regexp-format
4505 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4506 "Printf format for a regexp matching an headline, possibly with some keyword.
4507 This regexp can match any headline with the specified keyword, or
4508 without a keyword. The keyword isn't in any group by default,
4509 but the stars and the body are.")
4511 (defun org-set-regexps-and-options ()
4512 "Precompute regular expressions for current buffer."
4513 (when (eq major-mode 'org-mode)
4514 (org-set-local 'org-todo-kwd-alist nil)
4515 (org-set-local 'org-todo-key-alist nil)
4516 (org-set-local 'org-todo-key-trigger nil)
4517 (org-set-local 'org-todo-keywords-1 nil)
4518 (org-set-local 'org-done-keywords nil)
4519 (org-set-local 'org-todo-heads nil)
4520 (org-set-local 'org-todo-sets nil)
4521 (org-set-local 'org-todo-log-states nil)
4522 (org-set-local 'org-file-properties nil)
4523 (org-set-local 'org-file-tags nil)
4524 (let ((re (org-make-options-regexp
4525 '("CATEGORY" "TODO" "COLUMNS"
4526 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4527 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4528 "OPTIONS")
4529 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4530 (splitre "[ \t]+")
4531 (scripts org-use-sub-superscripts)
4532 kwds kws0 kwsa key log value cat arch tags const links hw dws
4533 tail sep kws1 prio props ftags drawers beamer-p
4534 ext-setup-or-nil setup-contents (start 0))
4535 (save-excursion
4536 (save-restriction
4537 (widen)
4538 (goto-char (point-min))
4539 (while (or (and ext-setup-or-nil
4540 (string-match re ext-setup-or-nil start)
4541 (setq start (match-end 0)))
4542 (and (setq ext-setup-or-nil nil start 0)
4543 (re-search-forward re nil t)))
4544 (setq key (upcase (match-string 1 ext-setup-or-nil))
4545 value (org-match-string-no-properties 2 ext-setup-or-nil))
4546 (if (stringp value) (setq value (org-trim value)))
4547 (cond
4548 ((equal key "CATEGORY")
4549 (setq cat value))
4550 ((member key '("SEQ_TODO" "TODO"))
4551 (push (cons 'sequence (org-split-string value splitre)) kwds))
4552 ((equal key "TYP_TODO")
4553 (push (cons 'type (org-split-string value splitre)) kwds))
4554 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4555 ;; general TODO-like setup
4556 (push (cons (intern (downcase (match-string 1 key)))
4557 (org-split-string value splitre)) kwds))
4558 ((equal key "TAGS")
4559 (setq tags (append tags (if tags '("\\n") nil)
4560 (org-split-string value splitre))))
4561 ((equal key "COLUMNS")
4562 (org-set-local 'org-columns-default-format value))
4563 ((equal key "LINK")
4564 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4565 (push (cons (match-string 1 value)
4566 (org-trim (match-string 2 value)))
4567 links)))
4568 ((equal key "PRIORITIES")
4569 (setq prio (org-split-string value " +")))
4570 ((equal key "PROPERTY")
4571 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4572 (setq props (org-update-property-plist (match-string 1 value)
4573 (match-string 2 value)
4574 props))))
4575 ((equal key "FILETAGS")
4576 (when (string-match "\\S-" value)
4577 (setq ftags
4578 (append
4579 ftags
4580 (apply 'append
4581 (mapcar (lambda (x) (org-split-string x ":"))
4582 (org-split-string value)))))))
4583 ((equal key "DRAWERS")
4584 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4585 ((equal key "CONSTANTS")
4586 (setq const (append const (org-split-string value splitre))))
4587 ((equal key "STARTUP")
4588 (let ((opts (org-split-string value splitre))
4589 l var val)
4590 (while (setq l (pop opts))
4591 (when (setq l (assoc l org-startup-options))
4592 (setq var (nth 1 l) val (nth 2 l))
4593 (if (not (nth 3 l))
4594 (set (make-local-variable var) val)
4595 (if (not (listp (symbol-value var)))
4596 (set (make-local-variable var) nil))
4597 (set (make-local-variable var) (symbol-value var))
4598 (add-to-list var val))))))
4599 ((equal key "ARCHIVE")
4600 (setq arch value)
4601 (remove-text-properties 0 (length arch)
4602 '(face t fontified t) arch))
4603 ((equal key "LATEX_CLASS")
4604 (setq beamer-p (equal value "beamer")))
4605 ((equal key "OPTIONS")
4606 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4607 (setq scripts (read (match-string 2 value)))))
4608 ((equal key "SETUPFILE")
4609 (setq setup-contents (org-file-contents
4610 (expand-file-name
4611 (org-remove-double-quotes value))
4612 'noerror))
4613 (if (not ext-setup-or-nil)
4614 (setq ext-setup-or-nil setup-contents start 0)
4615 (setq ext-setup-or-nil
4616 (concat (substring ext-setup-or-nil 0 start)
4617 "\n" setup-contents "\n"
4618 (substring ext-setup-or-nil start)))))))
4619 ;; search for property blocks
4620 (goto-char (point-min))
4621 (while (re-search-forward org-block-regexp nil t)
4622 (when (equal "PROPERTY" (upcase (match-string 1)))
4623 (setq value (replace-regexp-in-string
4624 "[\n\r]" " " (match-string 4)))
4625 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4626 (setq props (org-update-property-plist (match-string 1 value)
4627 (match-string 2 value)
4628 props)))))))
4629 (org-set-local 'org-use-sub-superscripts scripts)
4630 (when cat
4631 (org-set-local 'org-category (intern cat))
4632 (push (cons "CATEGORY" cat) props))
4633 (when prio
4634 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4635 (setq prio (mapcar 'string-to-char prio))
4636 (org-set-local 'org-highest-priority (nth 0 prio))
4637 (org-set-local 'org-lowest-priority (nth 1 prio))
4638 (org-set-local 'org-default-priority (nth 2 prio)))
4639 (and props (org-set-local 'org-file-properties (nreverse props)))
4640 (and ftags (org-set-local 'org-file-tags
4641 (mapcar 'org-add-prop-inherited ftags)))
4642 (and drawers (org-set-local 'org-drawers drawers))
4643 (and arch (org-set-local 'org-archive-location arch))
4644 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4645 ;; Process the TODO keywords
4646 (unless kwds
4647 ;; Use the global values as if they had been given locally.
4648 (setq kwds (default-value 'org-todo-keywords))
4649 (if (stringp (car kwds))
4650 (setq kwds (list (cons org-todo-interpretation
4651 (default-value 'org-todo-keywords)))))
4652 (setq kwds (reverse kwds)))
4653 (setq kwds (nreverse kwds))
4654 (let (inter kws kw)
4655 (while (setq kws (pop kwds))
4656 (let ((kws (or
4657 (run-hook-with-args-until-success
4658 'org-todo-setup-filter-hook kws)
4659 kws)))
4660 (setq inter (pop kws) sep (member "|" kws)
4661 kws0 (delete "|" (copy-sequence kws))
4662 kwsa nil
4663 kws1 (mapcar
4664 (lambda (x)
4665 ;; 1 2
4666 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4667 (progn
4668 (setq kw (match-string 1 x)
4669 key (and (match-end 2) (match-string 2 x))
4670 log (org-extract-log-state-settings x))
4671 (push (cons kw (and key (string-to-char key))) kwsa)
4672 (and log (push log org-todo-log-states))
4674 (error "Invalid TODO keyword %s" x)))
4675 kws0)
4676 kwsa (if kwsa (append '((:startgroup))
4677 (nreverse kwsa)
4678 '((:endgroup))))
4679 hw (car kws1)
4680 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4681 tail (list inter hw (car dws) (org-last dws))))
4682 (add-to-list 'org-todo-heads hw 'append)
4683 (push kws1 org-todo-sets)
4684 (setq org-done-keywords (append org-done-keywords dws nil))
4685 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4686 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4687 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4688 (setq org-todo-sets (nreverse org-todo-sets)
4689 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4690 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4691 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4692 ;; Process the constants
4693 (when const
4694 (let (e cst)
4695 (while (setq e (pop const))
4696 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4697 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4698 (setq org-table-formula-constants-local cst)))
4700 ;; Process the tags.
4701 (when tags
4702 (let (e tgs)
4703 (while (setq e (pop tags))
4704 (cond
4705 ((equal e "{") (push '(:startgroup) tgs))
4706 ((equal e "}") (push '(:endgroup) tgs))
4707 ((equal e "\\n") (push '(:newline) tgs))
4708 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4709 (push (cons (match-string 1 e)
4710 (string-to-char (match-string 2 e)))
4711 tgs))
4712 (t (push (list e) tgs))))
4713 (org-set-local 'org-tag-alist nil)
4714 (while (setq e (pop tgs))
4715 (or (and (stringp (car e))
4716 (assoc (car e) org-tag-alist))
4717 (push e org-tag-alist)))))
4719 ;; Compute the regular expressions and other local variables.
4720 ;; Using `org-outline-regexp-bol' would complicate them much,
4721 ;; because of the fixed white space at the end of that string.
4722 (if (not org-done-keywords)
4723 (setq org-done-keywords (and org-todo-keywords-1
4724 (list (org-last org-todo-keywords-1)))))
4725 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4726 (length org-scheduled-string)
4727 (length org-clock-string)
4728 (length org-closed-string)))
4729 org-drawer-regexp
4730 (concat "^[ \t]*:\\("
4731 (mapconcat 'regexp-quote org-drawers "\\|")
4732 "\\):[ \t]*$")
4733 org-not-done-keywords
4734 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4735 org-todo-regexp
4736 (concat "\\("
4737 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4738 "\\)")
4739 org-not-done-regexp
4740 (concat "\\("
4741 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4742 "\\)")
4743 org-not-done-heading-regexp
4744 (format org-heading-keyword-regexp-format org-not-done-regexp)
4745 org-todo-line-regexp
4746 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4747 org-complex-heading-regexp
4748 (concat "^\\(\\*+\\)"
4749 "\\(?: +" org-todo-regexp "\\)?"
4750 "\\(?: +\\(\\[#.\\]\\)\\)?"
4751 "\\(?: +\\(.*?\\)\\)?"
4752 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4753 "[ \t]*$")
4754 org-complex-heading-regexp-format
4755 (concat "^\\(\\*+\\)"
4756 "\\(?: +" org-todo-regexp "\\)?"
4757 "\\(?: +\\(\\[#.\\]\\)\\)?"
4758 "\\(?: +"
4759 ;; Stats cookies can be stuck to body.
4760 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4761 "\\(%s\\)"
4762 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4763 "\\)"
4764 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4765 "[ \t]*$")
4766 org-todo-line-tags-regexp
4767 (concat "^\\(\\*+\\)"
4768 "\\(?: +" org-todo-regexp "\\)?"
4769 "\\(?: +\\(.*?\\)\\)?"
4770 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4771 "[ \t]*$")
4772 org-deadline-regexp (concat "\\<" org-deadline-string)
4773 org-deadline-time-regexp
4774 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4775 org-deadline-line-regexp
4776 (concat "\\<\\(" org-deadline-string "\\).*")
4777 org-scheduled-regexp
4778 (concat "\\<" org-scheduled-string)
4779 org-scheduled-time-regexp
4780 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4781 org-closed-time-regexp
4782 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4783 org-keyword-time-regexp
4784 (concat "\\<\\(" org-scheduled-string
4785 "\\|" org-deadline-string
4786 "\\|" org-closed-string
4787 "\\|" org-clock-string "\\)"
4788 " *[[<]\\([^]>]+\\)[]>]")
4789 org-keyword-time-not-clock-regexp
4790 (concat "\\<\\(" org-scheduled-string
4791 "\\|" org-deadline-string
4792 "\\|" org-closed-string
4793 "\\)"
4794 " *[[<]\\([^]>]+\\)[]>]")
4795 org-maybe-keyword-time-regexp
4796 (concat "\\(\\<\\(" org-scheduled-string
4797 "\\|" org-deadline-string
4798 "\\|" org-closed-string
4799 "\\|" org-clock-string "\\)\\)?"
4800 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4801 org-planning-or-clock-line-re
4802 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4803 "\\|" org-deadline-string
4804 "\\|" org-closed-string "\\|" org-clock-string
4805 "\\)\\>\\)")
4806 org-all-time-keywords
4807 (mapcar (lambda (w) (substring w 0 -1))
4808 (list org-scheduled-string org-deadline-string
4809 org-clock-string org-closed-string))
4811 (org-compute-latex-and-specials-regexp)
4812 (org-set-font-lock-defaults))))
4814 (defun org-file-contents (file &optional noerror)
4815 "Return the contents of FILE, as a string."
4816 (if (or (not file)
4817 (not (file-readable-p file)))
4818 (if noerror
4819 (progn
4820 (message "Cannot read file \"%s\"" file)
4821 (ding) (sit-for 2)
4823 (error "Cannot read file \"%s\"" file))
4824 (with-temp-buffer
4825 (insert-file-contents file)
4826 (buffer-string))))
4828 (defun org-extract-log-state-settings (x)
4829 "Extract the log state setting from a TODO keyword string.
4830 This will extract info from a string like \"WAIT(w@/!)\"."
4831 (let (kw key log1 log2)
4832 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4833 (setq kw (match-string 1 x)
4834 key (and (match-end 2) (match-string 2 x))
4835 log1 (and (match-end 3) (match-string 3 x))
4836 log2 (and (match-end 4) (match-string 4 x)))
4837 (and (or log1 log2)
4838 (list kw
4839 (and log1 (if (equal log1 "!") 'time 'note))
4840 (and log2 (if (equal log2 "!") 'time 'note)))))))
4842 (defun org-remove-keyword-keys (list)
4843 "Remove a pair of parenthesis at the end of each string in LIST."
4844 (mapcar (lambda (x)
4845 (if (string-match "(.*)$" x)
4846 (substring x 0 (match-beginning 0))
4848 list))
4850 (defun org-assign-fast-keys (alist)
4851 "Assign fast keys to a keyword-key alist.
4852 Respect keys that are already there."
4853 (let (new e (alt ?0))
4854 (while (setq e (pop alist))
4855 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4856 (cdr e)) ;; Key already assigned.
4857 (push e new)
4858 (let ((clist (string-to-list (downcase (car e))))
4859 (used (append new alist)))
4860 (when (= (car clist) ?@)
4861 (pop clist))
4862 (while (and clist (rassoc (car clist) used))
4863 (pop clist))
4864 (unless clist
4865 (while (rassoc alt used)
4866 (incf alt)))
4867 (push (cons (car e) (or (car clist) alt)) new))))
4868 (nreverse new)))
4870 ;;; Some variables used in various places
4872 (defvar org-window-configuration nil
4873 "Used in various places to store a window configuration.")
4874 (defvar org-selected-window nil
4875 "Used in various places to store a window configuration.")
4876 (defvar org-finish-function nil
4877 "Function to be called when `C-c C-c' is used.
4878 This is for getting out of special buffers like remember.")
4881 ;; FIXME: Occasionally check by commenting these, to make sure
4882 ;; no other functions uses these, forgetting to let-bind them.
4883 (defvar entry)
4884 (defvar last-state)
4885 (defvar date)
4887 ;; Defined somewhere in this file, but used before definition.
4888 (defvar org-entities) ;; defined in org-entities.el
4889 (defvar org-struct-menu)
4890 (defvar org-org-menu)
4891 (defvar org-tbl-menu)
4893 ;;;; Define the Org-mode
4895 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4896 (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"))
4899 ;; We use a before-change function to check if a table might need
4900 ;; an update.
4901 (defvar org-table-may-need-update t
4902 "Indicates that a table might need an update.
4903 This variable is set by `org-before-change-function'.
4904 `org-table-align' sets it back to nil.")
4905 (defun org-before-change-function (beg end)
4906 "Every change indicates that a table might need an update."
4907 (setq org-table-may-need-update t))
4908 (defvar org-mode-map)
4909 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4910 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4911 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4912 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4913 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4914 (defvar org-table-buffer-is-an nil)
4916 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4917 ;; some places -- e.g. see the macro org-with-limited-levels.
4919 ;; In Org buffers, the value of `outline-regexp' is that of
4920 ;; `org-outline-regexp'. The only function still directly relying on
4921 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4922 ;; job when `orgstruct-mode' is active.
4923 (defvar org-outline-regexp "\\*+ "
4924 "Regexp to match Org headlines.")
4925 (defconst org-outline-regexp-bol "^\\*+ "
4926 "Regexp to match Org headlines.
4927 This is similar to `org-outline-regexp' but additionally makes
4928 sure that we are at the beginning of the line.")
4930 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4931 "Matches an headline, putting stars and text into groups.
4932 Stars are put in group 1 and the trimmed body in group 2.")
4934 (defvar bidi-paragraph-direction)
4936 ;;;###autoload
4937 (define-derived-mode org-mode outline-mode "Org"
4938 "Outline-based notes management and organizer, alias
4939 \"Carsten's outline-mode for keeping track of everything.\"
4941 Org-mode develops organizational tasks around a NOTES file which
4942 contains information about projects as plain text. Org-mode is
4943 implemented on top of outline-mode, which is ideal to keep the content
4944 of large files well structured. It supports ToDo items, deadlines and
4945 time stamps, which magically appear in the diary listing of the Emacs
4946 calendar. Tables are easily created with a built-in table editor.
4947 Plain text URL-like links connect to websites, emails (VM), Usenet
4948 messages (Gnus), BBDB entries, and any files related to the project.
4949 For printing and sharing of notes, an Org-mode file (or a part of it)
4950 can be exported as a structured ASCII or HTML file.
4952 The following commands are available:
4954 \\{org-mode-map}"
4956 ;; Get rid of Outline menus, they are not needed
4957 ;; Need to do this here because define-derived-mode sets up
4958 ;; the keymap so late. Still, it is a waste to call this each time
4959 ;; we switch another buffer into org-mode.
4960 (if (featurep 'xemacs)
4961 (when (boundp 'outline-mode-menu-heading)
4962 ;; Assume this is Greg's port, it uses easymenu
4963 (easy-menu-remove outline-mode-menu-heading)
4964 (easy-menu-remove outline-mode-menu-show)
4965 (easy-menu-remove outline-mode-menu-hide))
4966 (define-key org-mode-map [menu-bar headings] 'undefined)
4967 (define-key org-mode-map [menu-bar hide] 'undefined)
4968 (define-key org-mode-map [menu-bar show] 'undefined))
4970 (org-load-modules-maybe)
4971 (easy-menu-add org-org-menu)
4972 (easy-menu-add org-tbl-menu)
4973 (org-install-agenda-files-menu)
4974 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4975 (add-to-invisibility-spec '(org-cwidth))
4976 (add-to-invisibility-spec '(org-hide-block . t))
4977 (when (featurep 'xemacs)
4978 (org-set-local 'line-move-ignore-invisible t))
4979 (org-set-local 'outline-regexp org-outline-regexp)
4980 (org-set-local 'outline-level 'org-outline-level)
4981 (setq bidi-paragraph-direction 'left-to-right)
4982 (when (and org-ellipsis
4983 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4984 (fboundp 'make-glyph-code))
4985 (unless org-display-table
4986 (setq org-display-table (make-display-table)))
4987 (set-display-table-slot
4988 org-display-table 4
4989 (vconcat (mapcar
4990 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4991 org-ellipsis)))
4992 (if (stringp org-ellipsis) org-ellipsis "..."))))
4993 (setq buffer-display-table org-display-table))
4994 (org-set-regexps-and-options)
4995 (when (and org-tag-faces (not org-tags-special-faces-re))
4996 ;; tag faces set outside customize.... force initialization.
4997 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4998 ;; Calc embedded
4999 (org-set-local 'calc-embedded-open-mode "# ")
5000 (modify-syntax-entry ?@ "w")
5001 (if org-startup-truncated (setq truncate-lines t))
5002 (org-set-local 'font-lock-unfontify-region-function
5003 'org-unfontify-region)
5004 ;; Activate before-change-function
5005 (org-set-local 'org-table-may-need-update t)
5006 (org-add-hook 'before-change-functions 'org-before-change-function nil
5007 'local)
5008 ;; Check for running clock before killing a buffer
5009 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5010 ;; Paragraphs and auto-filling
5011 (org-set-autofill-regexps)
5012 (setq indent-line-function 'org-indent-line-function)
5013 (org-update-radio-target-regexp)
5014 ;; Beginning/end of defun
5015 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5016 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5017 ;; Next error for sparse trees
5018 (org-set-local 'next-error-function 'org-occur-next-match)
5019 ;; Make sure dependence stuff works reliably, even for users who set it
5020 ;; too late :-(
5021 (if org-enforce-todo-dependencies
5022 (add-hook 'org-blocker-hook
5023 'org-block-todo-from-children-or-siblings-or-parent)
5024 (remove-hook 'org-blocker-hook
5025 'org-block-todo-from-children-or-siblings-or-parent))
5026 (if org-enforce-todo-checkbox-dependencies
5027 (add-hook 'org-blocker-hook
5028 'org-block-todo-from-checkboxes)
5029 (remove-hook 'org-blocker-hook
5030 'org-block-todo-from-checkboxes))
5032 ;; Comment characters
5033 (org-set-local 'comment-start "#")
5034 (org-set-local 'comment-padding " ")
5036 ;; Align options lines
5037 (org-set-local
5038 'align-mode-rules-list
5039 '((org-in-buffer-settings
5040 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5041 (modes . '(org-mode)))))
5043 ;; Imenu
5044 (org-set-local 'imenu-create-index-function
5045 'org-imenu-get-tree)
5047 ;; Make isearch reveal context
5048 (if (or (featurep 'xemacs)
5049 (not (boundp 'outline-isearch-open-invisible-function)))
5050 ;; Emacs 21 and XEmacs make use of the hook
5051 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5052 ;; Emacs 22 deals with this through a special variable
5053 (org-set-local 'outline-isearch-open-invisible-function
5054 (lambda (&rest ignore) (org-show-context 'isearch))))
5056 ;; Turn on org-beamer-mode?
5057 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5059 ;; Setup the pcomplete hooks
5060 (set (make-local-variable 'pcomplete-command-completion-function)
5061 'org-pcomplete-initial)
5062 (set (make-local-variable 'pcomplete-command-name-function)
5063 'org-command-at-point)
5064 (set (make-local-variable 'pcomplete-default-completion-function)
5065 'ignore)
5066 (set (make-local-variable 'pcomplete-parse-arguments-function)
5067 'org-parse-arguments)
5068 (set (make-local-variable 'pcomplete-termination-string) "")
5069 (set (make-local-variable 'face-remapping-alist)
5070 '((default org-default)))
5072 ;; If empty file that did not turn on org-mode automatically, make it to.
5073 (if (and org-insert-mode-line-in-empty-file
5074 (org-called-interactively-p 'any)
5075 (= (point-min) (point-max)))
5076 (insert "# -*- mode: org -*-\n\n"))
5077 (unless org-inhibit-startup
5078 (when org-startup-align-all-tables
5079 (let ((bmp (buffer-modified-p)))
5080 (org-table-map-tables 'org-table-align 'quietly)
5081 (set-buffer-modified-p bmp)))
5082 (when org-startup-with-inline-images
5083 (org-display-inline-images))
5084 (when org-startup-indented
5085 (require 'org-indent)
5086 (org-indent-mode 1))
5087 (unless org-inhibit-startup-visibility-stuff
5088 (org-set-startup-visibility))))
5090 (when (fboundp 'abbrev-table-put)
5091 (abbrev-table-put org-mode-abbrev-table
5092 :parents (list text-mode-abbrev-table)))
5094 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5096 (defun org-current-time ()
5097 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5098 (if (> (car org-time-stamp-rounding-minutes) 1)
5099 (let ((r (car org-time-stamp-rounding-minutes))
5100 (time (decode-time)))
5101 (apply 'encode-time
5102 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5103 (nthcdr 2 time))))
5104 (current-time)))
5106 (defun org-today ()
5107 "Return today date, considering `org-extend-today-until'."
5108 (time-to-days
5109 (time-subtract (current-time)
5110 (list 0 (* 3600 org-extend-today-until) 0))))
5112 ;;;; Font-Lock stuff, including the activators
5114 (defvar org-mouse-map (make-sparse-keymap))
5115 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5116 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5117 (when org-mouse-1-follows-link
5118 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5119 (when org-tab-follows-link
5120 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5121 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5123 (require 'font-lock)
5125 (defconst org-non-link-chars "]\t\n\r<>")
5126 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5127 "shell" "elisp" "doi" "message"))
5128 (defvar org-link-types-re nil
5129 "Matches a link that has a url-like prefix like \"http:\"")
5130 (defvar org-link-re-with-space nil
5131 "Matches a link with spaces, optional angular brackets around it.")
5132 (defvar org-link-re-with-space2 nil
5133 "Matches a link with spaces, optional angular brackets around it.")
5134 (defvar org-link-re-with-space3 nil
5135 "Matches a link with spaces, only for internal part in bracket links.")
5136 (defvar org-angle-link-re nil
5137 "Matches link with angular brackets, spaces are allowed.")
5138 (defvar org-plain-link-re nil
5139 "Matches plain link, without spaces.")
5140 (defvar org-bracket-link-regexp nil
5141 "Matches a link in double brackets.")
5142 (defvar org-bracket-link-analytic-regexp nil
5143 "Regular expression used to analyze links.
5144 Here is what the match groups contain after a match:
5145 1: http:
5146 2: http
5147 3: path
5148 4: [desc]
5149 5: desc")
5150 (defvar org-bracket-link-analytic-regexp++ nil
5151 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5152 (defvar org-any-link-re nil
5153 "Regular expression matching any link.")
5155 (defcustom org-match-sexp-depth 3
5156 "Number of stacked braces for sub/superscript matching.
5157 This has to be set before loading org.el to be effective."
5158 :group 'org-export-translation ; ??????????????????????????/
5159 :type 'integer)
5161 (defun org-create-multibrace-regexp (left right n)
5162 "Create a regular expression which will match a balanced sexp.
5163 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5164 as single character strings.
5165 The regexp returned will match the entire expression including the
5166 delimiters. It will also define a single group which contains the
5167 match except for the outermost delimiters. The maximum depth of
5168 stacked delimiters is N. Escaping delimiters is not possible."
5169 (let* ((nothing (concat "[^" left right "]*?"))
5170 (or "\\|")
5171 (re nothing)
5172 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5173 (while (> n 1)
5174 (setq n (1- n)
5175 re (concat re or next)
5176 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5177 (concat left "\\(" re "\\)" right)))
5179 (defvar org-match-substring-regexp
5180 (concat
5181 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5182 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5183 "\\|"
5184 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5185 "\\|"
5186 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5187 "The regular expression matching a sub- or superscript.")
5189 (defvar org-match-substring-with-braces-regexp
5190 (concat
5191 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5192 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5193 "\\)")
5194 "The regular expression matching a sub- or superscript, forcing braces.")
5196 (defun org-make-link-regexps ()
5197 "Update the link regular expressions.
5198 This should be called after the variable `org-link-types' has changed."
5199 (setq org-link-types-re
5200 (concat
5201 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5202 org-link-re-with-space
5203 (concat
5204 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5205 "\\([^" org-non-link-chars " ]"
5206 "[^" org-non-link-chars "]*"
5207 "[^" org-non-link-chars " ]\\)>?")
5208 org-link-re-with-space2
5209 (concat
5210 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5211 "\\([^" org-non-link-chars " ]"
5212 "[^\t\n\r]*"
5213 "[^" org-non-link-chars " ]\\)>?")
5214 org-link-re-with-space3
5215 (concat
5216 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5217 "\\([^" org-non-link-chars " ]"
5218 "[^\t\n\r]*\\)")
5219 org-angle-link-re
5220 (concat
5221 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5222 "\\([^" org-non-link-chars " ]"
5223 "[^" org-non-link-chars "]*"
5224 "\\)>")
5225 org-plain-link-re
5226 (concat
5227 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5228 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5229 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5230 org-bracket-link-regexp
5231 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5232 org-bracket-link-analytic-regexp
5233 (concat
5234 "\\[\\["
5235 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5236 "\\([^]]+\\)"
5237 "\\]"
5238 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5239 "\\]")
5240 org-bracket-link-analytic-regexp++
5241 (concat
5242 "\\[\\["
5243 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5244 "\\([^]]+\\)"
5245 "\\]"
5246 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5247 "\\]")
5248 org-any-link-re
5249 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5250 org-angle-link-re "\\)\\|\\("
5251 org-plain-link-re "\\)")))
5253 (org-make-link-regexps)
5255 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5256 "Regular expression for fast time stamp matching.")
5257 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5258 "Regular expression for fast time stamp matching.")
5259 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5260 "Regular expression matching time strings for analysis.
5261 This one does not require the space after the date, so it can be used
5262 on a string that terminates immediately after the date.")
5263 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5264 "Regular expression matching time strings for analysis.")
5265 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5266 "Regular expression matching time stamps, with groups.")
5267 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5268 "Regular expression matching time stamps (also [..]), with groups.")
5269 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5270 "Regular expression matching a time stamp range.")
5271 (defconst org-tr-regexp-both
5272 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5273 "Regular expression matching a time stamp range.")
5274 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5275 org-ts-regexp "\\)?")
5276 "Regular expression matching a time stamp or time stamp range.")
5277 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5278 org-ts-regexp-both "\\)?")
5279 "Regular expression matching a time stamp or time stamp range.
5280 The time stamps may be either active or inactive.")
5282 (defvar org-emph-face nil)
5284 (defun org-do-emphasis-faces (limit)
5285 "Run through the buffer and add overlays to emphasized strings."
5286 (let (rtn a)
5287 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5288 (if (not (= (char-after (match-beginning 3))
5289 (char-after (match-beginning 4))))
5290 (progn
5291 (setq rtn t)
5292 (setq a (assoc (match-string 3) org-emphasis-alist))
5293 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5294 'face
5295 (nth 1 a))
5296 (and (nth 4 a)
5297 (org-remove-flyspell-overlays-in
5298 (match-beginning 0) (match-end 0)))
5299 (add-text-properties (match-beginning 2) (match-end 2)
5300 '(font-lock-multiline t org-emphasis t))
5301 (when org-hide-emphasis-markers
5302 (add-text-properties (match-end 4) (match-beginning 5)
5303 '(invisible org-link))
5304 (add-text-properties (match-beginning 3) (match-end 3)
5305 '(invisible org-link)))))
5306 (backward-char 1))
5307 rtn))
5309 (defun org-emphasize (&optional char)
5310 "Insert or change an emphasis, i.e. a font like bold or italic.
5311 If there is an active region, change that region to a new emphasis.
5312 If there is no region, just insert the marker characters and position
5313 the cursor between them.
5314 CHAR should be either the marker character, or the first character of the
5315 HTML tag associated with that emphasis. If CHAR is a space, the means
5316 to remove the emphasis of the selected region.
5317 If char is not given (for example in an interactive call) it
5318 will be prompted for."
5319 (interactive)
5320 (let ((eal org-emphasis-alist) e det
5321 (erc org-emphasis-regexp-components)
5322 (prompt "")
5323 (string "") beg end move tag c s)
5324 (if (org-region-active-p)
5325 (setq beg (region-beginning) end (region-end)
5326 string (buffer-substring beg end))
5327 (setq move t))
5329 (while (setq e (pop eal))
5330 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5331 c (aref tag 0))
5332 (push (cons c (string-to-char (car e))) det)
5333 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5334 (substring tag 1)))))
5335 (setq det (nreverse det))
5336 (unless char
5337 (message "%s" (concat "Emphasis marker or tag:" prompt))
5338 (setq char (read-char-exclusive)))
5339 (setq char (or (cdr (assoc char det)) char))
5340 (if (equal char ?\ )
5341 (setq s "" move nil)
5342 (unless (assoc (char-to-string char) org-emphasis-alist)
5343 (error "No such emphasis marker: \"%c\"" char))
5344 (setq s (char-to-string char)))
5345 (while (and (> (length string) 1)
5346 (equal (substring string 0 1) (substring string -1))
5347 (assoc (substring string 0 1) org-emphasis-alist))
5348 (setq string (substring string 1 -1)))
5349 (setq string (concat s string s))
5350 (if beg (delete-region beg end))
5351 (unless (or (bolp)
5352 (string-match (concat "[" (nth 0 erc) "\n]")
5353 (char-to-string (char-before (point)))))
5354 (insert " "))
5355 (unless (or (eobp)
5356 (string-match (concat "[" (nth 1 erc) "\n]")
5357 (char-to-string (char-after (point)))))
5358 (insert " ") (backward-char 1))
5359 (insert string)
5360 (and move (backward-char 1))))
5362 (defconst org-nonsticky-props
5363 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5365 (defsubst org-rear-nonsticky-at (pos)
5366 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5368 (defun org-activate-plain-links (limit)
5369 "Run through the buffer and add overlays to links."
5370 (catch 'exit
5371 (let (f)
5372 (if (re-search-forward org-plain-link-re limit t)
5373 (progn
5374 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5375 (setq f (get-text-property (match-beginning 0) 'face))
5376 (if (or (eq f 'org-tag)
5377 (and (listp f) (memq 'org-tag f)))
5379 (add-text-properties (match-beginning 0) (match-end 0)
5380 (list 'mouse-face 'highlight
5381 'face 'org-link
5382 'keymap org-mouse-map))
5383 (org-rear-nonsticky-at (match-end 0)))
5384 t)))))
5386 (defun org-activate-code (limit)
5387 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5388 (progn
5389 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5390 (remove-text-properties (match-beginning 0) (match-end 0)
5391 '(display t invisible t intangible t))
5392 t)))
5394 (defcustom org-src-fontify-natively nil
5395 "When non-nil, fontify code in code blocks."
5396 :type 'boolean
5397 :version "24.1"
5398 :group 'org-appearance
5399 :group 'org-babel)
5401 (defun org-fontify-meta-lines-and-blocks (limit)
5402 (condition-case nil
5403 (org-fontify-meta-lines-and-blocks-1 limit)
5404 (error (message "org-mode fontification error"))))
5406 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5407 "Fontify #+ lines and blocks, in the correct ways."
5408 (let ((case-fold-search t))
5409 (if (re-search-forward
5410 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5411 limit t)
5412 (let ((beg (match-beginning 0))
5413 (block-start (match-end 0))
5414 (block-end nil)
5415 (lang (match-string 7))
5416 (beg1 (line-beginning-position 2))
5417 (dc1 (downcase (match-string 2)))
5418 (dc3 (downcase (match-string 3)))
5419 end end1 quoting block-type ovl)
5420 (cond
5421 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5422 ;; a single line of backend-specific content
5423 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5424 (remove-text-properties (match-beginning 0) (match-end 0)
5425 '(display t invisible t intangible t))
5426 (add-text-properties (match-beginning 1) (match-end 3)
5427 '(font-lock-fontified t face org-meta-line))
5428 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5429 '(font-lock-fontified t face org-block))
5430 ; for backend-specific code
5432 ((and (match-end 4) (equal dc3 "begin"))
5433 ;; Truly a block
5434 (setq block-type (downcase (match-string 5))
5435 quoting (member block-type org-protecting-blocks))
5436 (when (re-search-forward
5437 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5438 nil t) ;; on purpose, we look further than LIMIT
5439 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5440 (setq block-end (match-beginning 0))
5441 (when quoting
5442 (remove-text-properties beg end
5443 '(display t invisible t intangible t)))
5444 (add-text-properties
5445 beg end
5446 '(font-lock-fontified t font-lock-multiline t))
5447 (add-text-properties beg beg1 '(face org-meta-line))
5448 (add-text-properties end1 (min (point-max) (1+ end))
5449 '(face org-meta-line)) ; for end_src
5450 (cond
5451 ((and lang (not (string= lang "")) org-src-fontify-natively)
5452 (org-src-font-lock-fontify-block lang block-start block-end)
5453 ;; remove old background overlays
5454 (mapc (lambda (ov)
5455 (if (eq (overlay-get ov 'face) 'org-block-background)
5456 (delete-overlay ov)))
5457 (overlays-at (/ (+ beg1 block-end) 2)))
5458 ;; add a background overlay
5459 (setq ovl (make-overlay beg1 block-end))
5460 (overlay-put ovl 'face 'org-block-background)
5461 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5462 (quoting
5463 (add-text-properties beg1 (min (point-max) (1+ end1))
5464 '(face org-block))) ; end of source block
5465 ((not org-fontify-quote-and-verse-blocks))
5466 ((string= block-type "quote")
5467 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5468 ((string= block-type "verse")
5469 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5470 (add-text-properties beg beg1 '(face org-block-begin-line))
5471 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5473 ((member dc1 '("title:" "author:" "email:" "date:"))
5474 (add-text-properties
5475 beg (match-end 3)
5476 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5477 '(font-lock-fontified t invisible t)
5478 '(font-lock-fontified t face org-document-info-keyword)))
5479 (add-text-properties
5480 (match-beginning 6) (match-end 6)
5481 (if (string-equal dc1 "title:")
5482 '(font-lock-fontified t face org-document-title)
5483 '(font-lock-fontified t face org-document-info))))
5484 ((not (member (char-after beg) '(?\ ?\t)))
5485 ;; just any other in-buffer setting, but not indented
5486 (add-text-properties
5487 beg (1+ (match-end 0))
5488 '(font-lock-fontified t face org-meta-line))
5490 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5491 "orgtbl:" "tblfm:" "tblname:" "results:"
5492 "call:" "header:" "headers:" "name:"))
5493 (and (match-end 4) (equal dc3 "attr")))
5494 (add-text-properties
5495 beg (match-end 0)
5496 '(font-lock-fontified t face org-meta-line))
5498 ((member dc3 '(" " ""))
5499 (add-text-properties
5500 beg (match-end 0)
5501 '(font-lock-fontified t face font-lock-comment-face)))
5502 (t nil))))))
5504 (defun org-strip-protective-commas (beg end)
5505 "Strip protective commas between BEG and END in the current buffer."
5506 (interactive "r")
5507 (save-excursion
5508 (save-match-data
5509 (goto-char beg)
5510 (let ((front-line (save-excursion
5511 (re-search-forward
5512 "[^[:space:]]" end t)
5513 (goto-char (match-beginning 0))
5514 (current-column))))
5515 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5516 (goto-char (match-beginning 1))
5517 (when (= (current-column) front-line)
5518 (replace-match "" nil nil nil 1)))))))
5520 (defun org-activate-angle-links (limit)
5521 "Run through the buffer and add overlays to links."
5522 (if (re-search-forward org-angle-link-re limit t)
5523 (progn
5524 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5525 (add-text-properties (match-beginning 0) (match-end 0)
5526 (list 'mouse-face 'highlight
5527 'keymap org-mouse-map))
5528 (org-rear-nonsticky-at (match-end 0))
5529 t)))
5531 (defun org-activate-footnote-links (limit)
5532 "Run through the buffer and add overlays to footnotes."
5533 (let ((fn (org-footnote-next-reference-or-definition limit)))
5534 (when fn
5535 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5536 (org-remove-flyspell-overlays-in beg end)
5537 (add-text-properties beg end
5538 (list 'mouse-face 'highlight
5539 'keymap org-mouse-map
5540 'help-echo
5541 (if (= (point-at-bol) beg)
5542 "Footnote definition"
5543 "Footnote reference")
5544 'font-lock-fontified t
5545 'font-lock-multiline t
5546 'face 'org-footnote))))))
5548 (defun org-activate-bracket-links (limit)
5549 "Run through the buffer and add overlays to bracketed links."
5550 (if (re-search-forward org-bracket-link-regexp limit t)
5551 (let* ((help (concat "LINK: "
5552 (org-match-string-no-properties 1)))
5553 ;; FIXME: above we should remove the escapes.
5554 ;; but that requires another match, protecting match data,
5555 ;; a lot of overhead for font-lock.
5556 (ip (org-maybe-intangible
5557 (list 'invisible 'org-link
5558 'keymap org-mouse-map 'mouse-face 'highlight
5559 'font-lock-multiline t 'help-echo help)))
5560 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5561 'font-lock-multiline t 'help-echo help)))
5562 ;; We need to remove the invisible property here. Table narrowing
5563 ;; may have made some of this invisible.
5564 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5565 (remove-text-properties (match-beginning 0) (match-end 0)
5566 '(invisible nil))
5567 (if (match-end 3)
5568 (progn
5569 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5570 (org-rear-nonsticky-at (match-beginning 3))
5571 (add-text-properties (match-beginning 3) (match-end 3) vp)
5572 (org-rear-nonsticky-at (match-end 3))
5573 (add-text-properties (match-end 3) (match-end 0) ip)
5574 (org-rear-nonsticky-at (match-end 0)))
5575 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5576 (org-rear-nonsticky-at (match-beginning 1))
5577 (add-text-properties (match-beginning 1) (match-end 1) vp)
5578 (org-rear-nonsticky-at (match-end 1))
5579 (add-text-properties (match-end 1) (match-end 0) ip)
5580 (org-rear-nonsticky-at (match-end 0)))
5581 t)))
5583 (defun org-activate-dates (limit)
5584 "Run through the buffer and add overlays to dates."
5585 (if (re-search-forward org-tsr-regexp-both limit t)
5586 (progn
5587 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5588 (add-text-properties (match-beginning 0) (match-end 0)
5589 (list 'mouse-face 'highlight
5590 'keymap org-mouse-map))
5591 (org-rear-nonsticky-at (match-end 0))
5592 (when org-display-custom-times
5593 (if (match-end 3)
5594 (org-display-custom-time (match-beginning 3) (match-end 3)))
5595 (org-display-custom-time (match-beginning 1) (match-end 1)))
5596 t)))
5598 (defvar org-target-link-regexp nil
5599 "Regular expression matching radio targets in plain text.")
5600 (make-variable-buffer-local 'org-target-link-regexp)
5601 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5602 "Regular expression matching a link target.")
5603 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5604 "Regular expression matching a radio target.")
5605 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5606 "Regular expression matching any target.")
5608 (defun org-activate-target-links (limit)
5609 "Run through the buffer and add overlays to target matches."
5610 (when org-target-link-regexp
5611 (let ((case-fold-search t))
5612 (if (re-search-forward org-target-link-regexp limit t)
5613 (progn
5614 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5615 (add-text-properties (match-beginning 0) (match-end 0)
5616 (list 'mouse-face 'highlight
5617 'keymap org-mouse-map
5618 'help-echo "Radio target link"
5619 'org-linked-text t))
5620 (org-rear-nonsticky-at (match-end 0))
5621 t)))))
5623 (defun org-update-radio-target-regexp ()
5624 "Find all radio targets in this file and update the regular expression."
5625 (interactive)
5626 (when (memq 'radio org-activate-links)
5627 (setq org-target-link-regexp
5628 (org-make-target-link-regexp (org-all-targets 'radio)))
5629 (org-restart-font-lock)))
5631 (defun org-hide-wide-columns (limit)
5632 (let (s e)
5633 (setq s (text-property-any (point) (or limit (point-max))
5634 'org-cwidth t))
5635 (when s
5636 (setq e (next-single-property-change s 'org-cwidth))
5637 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5638 (goto-char e)
5639 t)))
5641 (defvar org-latex-and-specials-regexp nil
5642 "Regular expression for highlighting export special stuff.")
5643 (defvar org-match-substring-regexp)
5644 (defvar org-match-substring-with-braces-regexp)
5646 ;; This should be with the exporter code, but we also use if for font-locking
5647 (defconst org-export-html-special-string-regexps
5648 '(("\\\\-" . "&shy;")
5649 ("---\\([^-]\\)" . "&mdash;\\1")
5650 ("--\\([^-]\\)" . "&ndash;\\1")
5651 ("\\.\\.\\." . "&hellip;"))
5652 "Regular expressions for special string conversion.")
5655 (defun org-compute-latex-and-specials-regexp ()
5656 "Compute regular expression for stuff treated specially by exporters."
5657 (if (not org-highlight-latex-fragments-and-specials)
5658 (org-set-local 'org-latex-and-specials-regexp nil)
5659 (require 'org-exp)
5660 (let*
5661 ((matchers (plist-get org-format-latex-options :matchers))
5662 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5663 org-latex-regexps)))
5664 (org-export-allow-BIND nil)
5665 (options (org-combine-plists (org-default-export-plist)
5666 (org-infile-export-plist)))
5667 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5668 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5669 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5670 (org-export-html-expand (plist-get options :expand-quoted-html))
5671 (org-export-with-special-strings (plist-get options :special-strings))
5672 (re-sub
5673 (cond
5674 ((equal org-export-with-sub-superscripts '{})
5675 (list org-match-substring-with-braces-regexp))
5676 (org-export-with-sub-superscripts
5677 (list org-match-substring-regexp))
5678 (t nil)))
5679 (re-latex
5680 (if org-export-with-LaTeX-fragments
5681 (mapcar (lambda (x) (nth 1 x)) latexs)))
5682 (re-macros
5683 (if org-export-with-TeX-macros
5684 (list (concat "\\\\"
5685 (regexp-opt
5686 (append
5688 (delq nil
5689 (mapcar 'car-safe
5690 (append org-entities-user
5691 org-entities)))
5692 (if (boundp 'org-latex-entities)
5693 (mapcar (lambda (x)
5694 (or (car-safe x) x))
5695 org-latex-entities)
5696 nil))
5697 'words))) ; FIXME
5699 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5700 (re-special (if org-export-with-special-strings
5701 (mapcar (lambda (x) (car x))
5702 org-export-html-special-string-regexps)))
5703 (re-rest
5704 (delq nil
5705 (list
5706 (if org-export-html-expand "@<[^>\n]+>")
5707 ))))
5708 (org-set-local
5709 'org-latex-and-specials-regexp
5710 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5711 re-rest) "\\|")))))
5713 (defun org-do-latex-and-special-faces (limit)
5714 "Run through the buffer and add overlays to links."
5715 (when org-latex-and-specials-regexp
5716 (let (rtn d)
5717 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5718 limit t))
5719 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5720 'face))
5721 '(org-code org-verbatim underline)))
5722 (progn
5723 (setq rtn t
5724 d (cond ((member (char-after (1+ (match-beginning 0)))
5725 '(?_ ?^)) 1)
5726 (t 0)))
5727 (font-lock-prepend-text-property
5728 (+ d (match-beginning 0)) (match-end 0)
5729 'face 'org-latex-and-export-specials)
5730 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5731 '(font-lock-multiline t)))))
5732 rtn)))
5734 (defun org-restart-font-lock ()
5735 "Restart `font-lock-mode', to force refontification."
5736 (when (and (boundp 'font-lock-mode) font-lock-mode)
5737 (font-lock-mode -1)
5738 (font-lock-mode 1)))
5740 (defun org-all-targets (&optional radio)
5741 "Return a list of all targets in this file.
5742 With optional argument RADIO, only find radio targets."
5743 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5744 rtn)
5745 (save-excursion
5746 (goto-char (point-min))
5747 (while (re-search-forward re nil t)
5748 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5749 rtn)))
5751 (defun org-make-target-link-regexp (targets)
5752 "Make regular expression matching all strings in TARGETS.
5753 The regular expression finds the targets also if there is a line break
5754 between words."
5755 (and targets
5756 (concat
5757 "\\<\\("
5758 (mapconcat
5759 (lambda (x)
5760 (setq x (regexp-quote x))
5761 (while (string-match " +" x)
5762 (setq x (replace-match "\\s-+" t t x)))
5764 targets
5765 "\\|")
5766 "\\)\\>")))
5768 (defun org-activate-tags (limit)
5769 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5770 (progn
5771 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5772 (add-text-properties (match-beginning 1) (match-end 1)
5773 (list 'mouse-face 'highlight
5774 'keymap org-mouse-map))
5775 (org-rear-nonsticky-at (match-end 1))
5776 t)))
5778 (defun org-outline-level ()
5779 "Compute the outline level of the heading at point.
5780 This function assumes that the cursor is at the beginning of a line matched
5781 by `outline-regexp'. Otherwise it returns garbage.
5782 If this is called at a normal headline, the level is the number of stars.
5783 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5784 (save-excursion
5785 (looking-at org-outline-regexp)
5786 (1- (- (match-end 0) (match-beginning 0)))))
5788 (defvar org-font-lock-keywords nil)
5790 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5791 "Regular expression matching a property line.")
5793 (defvar org-font-lock-hook nil
5794 "Functions to be called for special font lock stuff.")
5796 (defvar org-font-lock-set-keywords-hook nil
5797 "Functions that can manipulate `org-font-lock-extra-keywords'.
5798 This is called after `org-font-lock-extra-keywords' is defined, but before
5799 it is installed to be used by font lock. This can be useful if something
5800 needs to be inserted at a specific position in the font-lock sequence.")
5802 (defun org-font-lock-hook (limit)
5803 (run-hook-with-args 'org-font-lock-hook limit))
5805 (defun org-set-font-lock-defaults ()
5806 (let* ((em org-fontify-emphasized-text)
5807 (lk org-activate-links)
5808 (org-font-lock-extra-keywords
5809 (list
5810 ;; Call the hook
5811 '(org-font-lock-hook)
5812 ;; Headlines
5813 `(,(if org-fontify-whole-heading-line
5814 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5815 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5816 (1 (org-get-level-face 1))
5817 (2 (org-get-level-face 2))
5818 (3 (org-get-level-face 3)))
5819 ;; Table lines
5820 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5821 (1 'org-table t))
5822 ;; Table internals
5823 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5824 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5825 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5826 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5827 ;; Drawers
5828 (list org-drawer-regexp '(0 'org-special-keyword t))
5829 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5830 ;; Properties
5831 (list org-property-re
5832 '(1 'org-special-keyword t)
5833 '(3 'org-property-value t))
5834 ;; Links
5835 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5836 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5837 (if (memq 'plain lk) '(org-activate-plain-links))
5838 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5839 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5840 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5841 (if (memq 'footnote lk) '(org-activate-footnote-links))
5842 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5843 '(org-hide-wide-columns (0 nil append))
5844 ;; TODO keyword
5845 (list (format org-heading-keyword-regexp-format
5846 org-todo-regexp)
5847 '(2 (org-get-todo-face 2) t))
5848 ;; DONE
5849 (if org-fontify-done-headline
5850 (list (format org-heading-keyword-regexp-format
5851 (concat
5852 "\\(?:"
5853 (mapconcat 'regexp-quote org-done-keywords "\\|")
5854 "\\)"))
5855 '(2 'org-headline-done t))
5856 nil)
5857 ;; Priorities
5858 '(org-font-lock-add-priority-faces)
5859 ;; Tags
5860 '(org-font-lock-add-tag-faces)
5861 ;; Special keywords
5862 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5863 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5864 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5865 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5866 ;; Emphasis
5867 (if em
5868 (if (featurep 'xemacs)
5869 '(org-do-emphasis-faces (0 nil append))
5870 '(org-do-emphasis-faces)))
5871 ;; Checkboxes
5872 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5873 1 'org-checkbox prepend)
5874 (if (cdr (assq 'checkbox org-list-automatic-rules))
5875 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5876 (0 (org-get-checkbox-statistics-face) t)))
5877 ;; Description list items
5878 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5879 1 'bold prepend)
5880 ;; ARCHIVEd headings
5881 (list (concat
5882 org-outline-regexp-bol
5883 "\\(.*:" org-archive-tag ":.*\\)")
5884 '(1 'org-archived prepend))
5885 ;; Specials
5886 '(org-do-latex-and-special-faces)
5887 '(org-fontify-entities)
5888 '(org-raise-scripts)
5889 ;; Code
5890 '(org-activate-code (1 'org-code t))
5891 ;; COMMENT
5892 (list (format org-heading-keyword-regexp-format
5893 (concat "\\("
5894 org-comment-string "\\|" org-quote-string
5895 "\\)"))
5896 '(2 'org-special-keyword t))
5897 '("^#.*" (0 'font-lock-comment-face t))
5898 ;; Blocks and meta lines
5899 '(org-fontify-meta-lines-and-blocks)
5901 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5902 (run-hooks 'org-font-lock-set-keywords-hook)
5903 ;; Now set the full font-lock-keywords
5904 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5905 (org-set-local 'font-lock-defaults
5906 '(org-font-lock-keywords t nil nil backward-paragraph))
5907 (kill-local-variable 'font-lock-keywords) nil))
5909 (defun org-toggle-pretty-entities ()
5910 "Toggle the composition display of entities as UTF8 characters."
5911 (interactive)
5912 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5913 (org-restart-font-lock)
5914 (if org-pretty-entities
5915 (message "Entities are displayed as UTF8 characters")
5916 (save-restriction
5917 (widen)
5918 (org-decompose-region (point-min) (point-max))
5919 (message "Entities are displayed plain"))))
5921 (defun org-fontify-entities (limit)
5922 "Find an entity to fontify."
5923 (let (ee)
5924 (when org-pretty-entities
5925 (catch 'match
5926 (while (re-search-forward
5927 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5928 limit t)
5929 (if (and (not (org-in-indented-comment-line))
5930 (setq ee (org-entity-get (match-string 1)))
5931 (= (length (nth 6 ee)) 1))
5932 (progn
5933 (add-text-properties
5934 (match-beginning 0) (match-end 1)
5935 (list 'font-lock-fontified t))
5936 (compose-region (match-beginning 0) (match-end 1)
5937 (nth 6 ee) nil)
5938 (backward-char 1)
5939 (throw 'match t))))
5940 nil))))
5942 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5943 "Fontify string S like in Org-mode."
5944 (with-temp-buffer
5945 (insert s)
5946 (let ((org-odd-levels-only odd-levels))
5947 (org-mode)
5948 (font-lock-fontify-buffer)
5949 (buffer-string))))
5951 (defvar org-m nil)
5952 (defvar org-l nil)
5953 (defvar org-f nil)
5954 (defun org-get-level-face (n)
5955 "Get the right face for match N in font-lock matching of headlines."
5956 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5957 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5958 (if org-cycle-level-faces
5959 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5960 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5961 (cond
5962 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5963 ((eq n 2) org-f)
5964 (t (if org-level-color-stars-only nil org-f))))
5967 (defun org-get-todo-face (kwd)
5968 "Get the right face for a TODO keyword KWD.
5969 If KWD is a number, get the corresponding match group."
5970 (if (numberp kwd) (setq kwd (match-string kwd)))
5971 (or (org-face-from-face-or-color
5972 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5973 (and (member kwd org-done-keywords) 'org-done)
5974 'org-todo))
5976 (defun org-face-from-face-or-color (context inherit face-or-color)
5977 "Create a face list that inherits INHERIT, but sets the foreground color.
5978 When FACE-OR-COLOR is not a string, just return it."
5979 (if (stringp face-or-color)
5980 (list :inherit inherit
5981 (cdr (assoc context org-faces-easy-properties))
5982 face-or-color)
5983 face-or-color))
5985 (defun org-font-lock-add-tag-faces (limit)
5986 "Add the special tag faces."
5987 (when (and org-tag-faces org-tags-special-faces-re)
5988 (while (re-search-forward org-tags-special-faces-re limit t)
5989 (add-text-properties (match-beginning 1) (match-end 1)
5990 (list 'face (org-get-tag-face 1)
5991 'font-lock-fontified t))
5992 (backward-char 1))))
5994 (defun org-font-lock-add-priority-faces (limit)
5995 "Add the special priority faces."
5996 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5997 (add-text-properties
5998 (match-beginning 0) (match-end 0)
5999 (list 'face (or (org-face-from-face-or-color
6000 'priority 'org-special-keyword
6001 (cdr (assoc (char-after (match-beginning 1))
6002 org-priority-faces)))
6003 'org-special-keyword)
6004 'font-lock-fontified t))))
6006 (defun org-get-tag-face (kwd)
6007 "Get the right face for a TODO keyword KWD.
6008 If KWD is a number, get the corresponding match group."
6009 (if (numberp kwd) (setq kwd (match-string kwd)))
6010 (or (org-face-from-face-or-color
6011 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6012 'org-tag))
6014 (defun org-unfontify-region (beg end &optional maybe_loudly)
6015 "Remove fontification and activation overlays from links."
6016 (font-lock-default-unfontify-region beg end)
6017 (let* ((buffer-undo-list t)
6018 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6019 (inhibit-modification-hooks t)
6020 deactivate-mark buffer-file-name buffer-file-truename)
6021 (org-decompose-region beg end)
6022 (remove-text-properties beg end
6023 '(mouse-face t keymap t org-linked-text t
6024 invisible t intangible t
6025 org-no-flyspell t org-emphasis t))
6026 (org-remove-font-lock-display-properties beg end)))
6028 (defconst org-script-display '(((raise -0.3) (height 0.7))
6029 ((raise 0.3) (height 0.7))
6030 ((raise -0.5))
6031 ((raise 0.5)))
6032 "Display properties for showing superscripts and subscripts.")
6034 (defun org-remove-font-lock-display-properties (beg end)
6035 "Remove specific display properties that have been added by font lock.
6036 The will remove the raise properties that are used to show superscripts
6037 and subscripts."
6038 (let (next prop)
6039 (while (< beg end)
6040 (setq next (next-single-property-change beg 'display nil end)
6041 prop (get-text-property beg 'display))
6042 (if (member prop org-script-display)
6043 (put-text-property beg next 'display nil))
6044 (setq beg next))))
6046 (defun org-raise-scripts (limit)
6047 "Add raise properties to sub/superscripts."
6048 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6049 (if (re-search-forward
6050 (if (eq org-use-sub-superscripts t)
6051 org-match-substring-regexp
6052 org-match-substring-with-braces-regexp)
6053 limit t)
6054 (let* ((pos (point)) table-p comment-p
6055 (mpos (match-beginning 3))
6056 (emph-p (get-text-property mpos 'org-emphasis))
6057 (link-p (get-text-property mpos 'mouse-face))
6058 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6059 (goto-char (point-at-bol))
6060 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6061 comment-p (org-looking-at-p "[ \t]*#"))
6062 (goto-char pos)
6063 ;; FIXME: Should we go back one character here, for a_b^c
6064 ;; (goto-char (1- pos)) ;????????????????????
6065 (if (or comment-p emph-p link-p keyw-p)
6067 (put-text-property (match-beginning 3) (match-end 0)
6068 'display
6069 (if (equal (char-after (match-beginning 2)) ?^)
6070 (nth (if table-p 3 1) org-script-display)
6071 (nth (if table-p 2 0) org-script-display)))
6072 (add-text-properties (match-beginning 2) (match-end 2)
6073 (list 'invisible t
6074 'org-dwidth t 'org-dwidth-n 1))
6075 (if (and (eq (char-after (match-beginning 3)) ?{)
6076 (eq (char-before (match-end 3)) ?}))
6077 (progn
6078 (add-text-properties
6079 (match-beginning 3) (1+ (match-beginning 3))
6080 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6081 (add-text-properties
6082 (1- (match-end 3)) (match-end 3)
6083 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6084 t)))))
6086 ;;;; Visibility cycling, including org-goto and indirect buffer
6088 ;;; Cycling
6090 (defvar org-cycle-global-status nil)
6091 (make-variable-buffer-local 'org-cycle-global-status)
6092 (defvar org-cycle-subtree-status nil)
6093 (make-variable-buffer-local 'org-cycle-subtree-status)
6095 ;;;###autoload
6097 (defvar org-inlinetask-min-level)
6099 (defun org-cycle (&optional arg)
6100 "TAB-action and visibility cycling for Org-mode.
6102 This is the command invoked in Org-mode by the TAB key. Its main purpose
6103 is outline visibility cycling, but it also invokes other actions
6104 in special contexts.
6106 - When this function is called with a prefix argument, rotate the entire
6107 buffer through 3 states (global cycling)
6108 1. OVERVIEW: Show only top-level headlines.
6109 2. CONTENTS: Show all headlines of all levels, but no body text.
6110 3. SHOW ALL: Show everything.
6111 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6112 determined by the variable `org-startup-folded', and by any VISIBILITY
6113 properties in the buffer.
6114 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6115 including any drawers.
6117 - When inside a table, re-align the table and move to the next field.
6119 - When point is at the beginning of a headline, rotate the subtree started
6120 by this line through 3 different states (local cycling)
6121 1. FOLDED: Only the main headline is shown.
6122 2. CHILDREN: The main headline and the direct children are shown.
6123 From this state, you can move to one of the children
6124 and zoom in further.
6125 3. SUBTREE: Show the entire subtree, including body text.
6126 If there is no subtree, switch directly from CHILDREN to FOLDED.
6128 - When point is at the beginning of an empty headline and the variable
6129 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6130 of the headline by demoting and promoting it to likely levels. This
6131 speeds up creation document structure by pressing TAB once or several
6132 times right after creating a new headline.
6134 - When there is a numeric prefix, go up to a heading with level ARG, do
6135 a `show-subtree' and return to the previous cursor position. If ARG
6136 is negative, go up that many levels.
6138 - When point is not at the beginning of a headline, execute the global
6139 binding for TAB, which is re-indenting the line. See the option
6140 `org-cycle-emulate-tab' for details.
6142 - Special case: if point is at the beginning of the buffer and there is
6143 no headline in line 1, this function will act as if called with prefix arg
6144 (C-u TAB, same as S-TAB) also when called without prefix arg.
6145 But only if also the variable `org-cycle-global-at-bob' is t."
6146 (interactive "P")
6147 (org-load-modules-maybe)
6148 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6149 (and org-cycle-level-after-item/entry-creation
6150 (or (org-cycle-level)
6151 (org-cycle-item-indentation))))
6152 (let* ((limit-level
6153 (or org-cycle-max-level
6154 (and (boundp 'org-inlinetask-min-level)
6155 org-inlinetask-min-level
6156 (1- org-inlinetask-min-level))))
6157 (nstars (and limit-level
6158 (if org-odd-levels-only
6159 (and limit-level (1- (* limit-level 2)))
6160 limit-level)))
6161 (org-outline-regexp
6162 (if (not (eq major-mode 'org-mode))
6163 outline-regexp
6164 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6165 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6166 (not (looking-at org-outline-regexp))))
6167 (org-cycle-hook
6168 (if bob-special
6169 (delq 'org-optimize-window-after-visibility-change
6170 (copy-sequence org-cycle-hook))
6171 org-cycle-hook))
6172 (pos (point)))
6174 (if (or bob-special (equal arg '(4)))
6175 ;; special case: use global cycling
6176 (setq arg t))
6178 (cond
6180 ((equal arg '(16))
6181 (setq last-command 'dummy)
6182 (org-set-startup-visibility)
6183 (message "Startup visibility, plus VISIBILITY properties"))
6185 ((equal arg '(64))
6186 (show-all)
6187 (message "Entire buffer visible, including drawers"))
6189 ;; Table: enter it or move to the next field.
6190 ((org-at-table-p 'any)
6191 (if (org-at-table.el-p)
6192 (message "Use C-c ' to edit table.el tables")
6193 (if arg (org-table-edit-field t)
6194 (org-table-justify-field-maybe)
6195 (call-interactively 'org-table-next-field))))
6197 ((run-hook-with-args-until-success
6198 'org-tab-after-check-for-table-hook))
6200 ;; Global cycling: delegate to `org-cycle-internal-global'.
6201 ((eq arg t) (org-cycle-internal-global))
6203 ;; Drawers: delegate to `org-flag-drawer'.
6204 ((and org-drawers org-drawer-regexp
6205 (save-excursion
6206 (beginning-of-line 1)
6207 (looking-at org-drawer-regexp)))
6208 (org-flag-drawer ; toggle block visibility
6209 (not (get-char-property (match-end 0) 'invisible))))
6211 ;; Show-subtree, ARG levels up from here.
6212 ((integerp arg)
6213 (save-excursion
6214 (org-back-to-heading)
6215 (outline-up-heading (if (< arg 0) (- arg)
6216 (- (funcall outline-level) arg)))
6217 (org-show-subtree)))
6219 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6220 ((and (featurep 'org-inlinetask)
6221 (org-inlinetask-at-task-p)
6222 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6223 (org-inlinetask-toggle-visibility))
6225 ((org-try-cdlatex-tab))
6227 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6228 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6229 (save-excursion (beginning-of-line 1)
6230 (looking-at org-outline-regexp)))
6231 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6232 (org-cycle-internal-local))
6234 ;; From there: TAB emulation and template completion.
6235 (buffer-read-only (org-back-to-heading))
6237 ((run-hook-with-args-until-success
6238 'org-tab-after-check-for-cycling-hook))
6240 ((org-try-structure-completion))
6242 ((run-hook-with-args-until-success
6243 'org-tab-before-tab-emulation-hook))
6245 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6246 (or (not (bolp))
6247 (not (looking-at org-outline-regexp))))
6248 (call-interactively (global-key-binding "\t")))
6250 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6251 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6252 (or (and (eq org-cycle-emulate-tab 'white)
6253 (= (match-end 0) (point-at-eol)))
6254 (and (eq org-cycle-emulate-tab 'whitestart)
6255 (>= (match-end 0) pos))))
6257 (eq org-cycle-emulate-tab t))
6258 (call-interactively (global-key-binding "\t")))
6260 (t (save-excursion
6261 (org-back-to-heading)
6262 (org-cycle)))))))
6264 (defun org-cycle-internal-global ()
6265 "Do the global cycling action."
6266 ;; Hack to avoid display of messages for .org attachments in Gnus
6267 (let ((ga (string-match "\\*fontification" (buffer-name))))
6268 (cond
6269 ((and (eq last-command this-command)
6270 (eq org-cycle-global-status 'overview))
6271 ;; We just created the overview - now do table of contents
6272 ;; This can be slow in very large buffers, so indicate action
6273 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6274 (unless ga (message "CONTENTS..."))
6275 (org-content)
6276 (unless ga (message "CONTENTS...done"))
6277 (setq org-cycle-global-status 'contents)
6278 (run-hook-with-args 'org-cycle-hook 'contents))
6280 ((and (eq last-command this-command)
6281 (eq org-cycle-global-status 'contents))
6282 ;; We just showed the table of contents - now show everything
6283 (run-hook-with-args 'org-pre-cycle-hook 'all)
6284 (show-all)
6285 (unless ga (message "SHOW ALL"))
6286 (setq org-cycle-global-status 'all)
6287 (run-hook-with-args 'org-cycle-hook 'all))
6290 ;; Default action: go to overview
6291 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6292 (org-overview)
6293 (unless ga (message "OVERVIEW"))
6294 (setq org-cycle-global-status 'overview)
6295 (run-hook-with-args 'org-cycle-hook 'overview)))))
6297 (defun org-cycle-internal-local ()
6298 "Do the local cycling action."
6299 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6300 ;; First, determine end of headline (EOH), end of subtree or item
6301 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6302 (save-excursion
6303 (if (org-at-item-p)
6304 (progn
6305 (beginning-of-line)
6306 (setq struct (org-list-struct))
6307 (setq eoh (point-at-eol))
6308 (setq eos (org-list-get-item-end-before-blank (point) struct))
6309 (setq has-children (org-list-has-child-p (point) struct)))
6310 (org-back-to-heading)
6311 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6312 (setq eos (save-excursion
6313 (org-end-of-subtree t)
6314 (unless (eobp)
6315 (skip-chars-forward " \t\n"))
6316 (if (eobp) (point) (1- (point)))))
6317 (setq has-children
6318 (or (save-excursion
6319 (let ((level (funcall outline-level)))
6320 (outline-next-heading)
6321 (and (org-at-heading-p t)
6322 (> (funcall outline-level) level))))
6323 (save-excursion
6324 (org-list-search-forward (org-item-beginning-re) eos t)))))
6325 ;; Determine end invisible part of buffer (EOL)
6326 (beginning-of-line 2)
6327 ;; XEmacs doesn't have `next-single-char-property-change'
6328 (if (featurep 'xemacs)
6329 (while (and (not (eobp)) ;; this is like `next-line'
6330 (get-char-property (1- (point)) 'invisible))
6331 (beginning-of-line 2))
6332 (while (and (not (eobp)) ;; this is like `next-line'
6333 (get-char-property (1- (point)) 'invisible))
6334 (goto-char (next-single-char-property-change (point) 'invisible))
6335 (and (eolp) (beginning-of-line 2))))
6336 (setq eol (point)))
6337 ;; Find out what to do next and set `this-command'
6338 (cond
6339 ((= eos eoh)
6340 ;; Nothing is hidden behind this heading
6341 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6342 (message "EMPTY ENTRY")
6343 (setq org-cycle-subtree-status nil)
6344 (save-excursion
6345 (goto-char eos)
6346 (outline-next-heading)
6347 (if (outline-invisible-p) (org-flag-heading nil))))
6348 ((and (or (>= eol eos)
6349 (not (string-match "\\S-" (buffer-substring eol eos))))
6350 (or has-children
6351 (not (setq children-skipped
6352 org-cycle-skip-children-state-if-no-children))))
6353 ;; Entire subtree is hidden in one line: children view
6354 (run-hook-with-args 'org-pre-cycle-hook 'children)
6355 (if (org-at-item-p)
6356 (org-list-set-item-visibility (point-at-bol) struct 'children)
6357 (org-show-entry)
6358 (org-with-limited-levels (show-children))
6359 (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6360 (org-cycle-hide-drawers 'subtree))
6361 ;; Fold every list in subtree to top-level items.
6362 (when (eq org-cycle-include-plain-lists 'integrate)
6363 (save-excursion
6364 (org-back-to-heading)
6365 (while (org-list-search-forward (org-item-beginning-re) eos t)
6366 (beginning-of-line 1)
6367 (let* ((struct (org-list-struct))
6368 (prevs (org-list-prevs-alist struct))
6369 (end (org-list-get-bottom-point struct)))
6370 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6371 (org-list-get-all-items (point) struct prevs))
6372 (goto-char end))))))
6373 (message "CHILDREN")
6374 (save-excursion
6375 (goto-char eos)
6376 (outline-next-heading)
6377 (if (outline-invisible-p) (org-flag-heading nil)))
6378 (setq org-cycle-subtree-status 'children)
6379 (run-hook-with-args 'org-cycle-hook 'children))
6380 ((or children-skipped
6381 (and (eq last-command this-command)
6382 (eq org-cycle-subtree-status 'children)))
6383 ;; We just showed the children, or no children are there,
6384 ;; now show everything.
6385 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6386 (outline-flag-region eoh eos nil)
6387 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6388 (setq org-cycle-subtree-status 'subtree)
6389 (run-hook-with-args 'org-cycle-hook 'subtree))
6391 ;; Default action: hide the subtree.
6392 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6393 (outline-flag-region eoh eos t)
6394 (message "FOLDED")
6395 (setq org-cycle-subtree-status 'folded)
6396 (run-hook-with-args 'org-cycle-hook 'folded)))))
6398 ;;;###autoload
6399 (defun org-global-cycle (&optional arg)
6400 "Cycle the global visibility. For details see `org-cycle'.
6401 With \\[universal-argument] prefix arg, switch to startup visibility.
6402 With a numeric prefix, show all headlines up to that level."
6403 (interactive "P")
6404 (let ((org-cycle-include-plain-lists
6405 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6406 (cond
6407 ((integerp arg)
6408 (show-all)
6409 (hide-sublevels arg)
6410 (setq org-cycle-global-status 'contents))
6411 ((equal arg '(4))
6412 (org-set-startup-visibility)
6413 (message "Startup visibility, plus VISIBILITY properties."))
6415 (org-cycle '(4))))))
6417 (defun org-set-startup-visibility ()
6418 "Set the visibility required by startup options and properties."
6419 (cond
6420 ((eq org-startup-folded t)
6421 (org-cycle '(4)))
6422 ((eq org-startup-folded 'content)
6423 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6424 (org-cycle '(4)) (org-cycle '(4)))))
6425 (unless (eq org-startup-folded 'showeverything)
6426 (if org-hide-block-startup (org-hide-block-all))
6427 (org-set-visibility-according-to-property 'no-cleanup)
6428 (org-cycle-hide-archived-subtrees 'all)
6429 (org-cycle-hide-drawers 'all)
6430 (org-cycle-show-empty-lines t)))
6432 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6433 "Switch subtree visibilities according to :VISIBILITY: property."
6434 (interactive)
6435 (let (org-show-entry-below state)
6436 (save-excursion
6437 (goto-char (point-min))
6438 (while (re-search-forward
6439 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6440 nil t)
6441 (setq state (match-string 1))
6442 (save-excursion
6443 (org-back-to-heading t)
6444 (hide-subtree)
6445 (org-reveal)
6446 (cond
6447 ((equal state '("fold" "folded"))
6448 (hide-subtree))
6449 ((equal state "children")
6450 (org-show-hidden-entry)
6451 (show-children))
6452 ((equal state "content")
6453 (save-excursion
6454 (save-restriction
6455 (org-narrow-to-subtree)
6456 (org-content))))
6457 ((member state '("all" "showall"))
6458 (show-subtree)))))
6459 (unless no-cleanup
6460 (org-cycle-hide-archived-subtrees 'all)
6461 (org-cycle-hide-drawers 'all)
6462 (org-cycle-show-empty-lines 'all)))))
6464 ;; This function uses outline-regexp instead of the more fundamental
6465 ;; org-outline-regexp so that org-cycle-global works outside of Org
6466 ;; buffers, where outline-regexp is needed.
6467 (defun org-overview ()
6468 "Switch to overview mode, showing only top-level headlines.
6469 Really, this shows all headlines with level equal or greater than the level
6470 of the first headline in the buffer. This is important, because if the
6471 first headline is not level one, then (hide-sublevels 1) gives confusing
6472 results."
6473 (interactive)
6474 (let ((level (save-excursion
6475 (goto-char (point-min))
6476 (if (re-search-forward (concat "^" outline-regexp) nil t)
6477 (progn
6478 (goto-char (match-beginning 0))
6479 (funcall outline-level))))))
6480 (and level (hide-sublevels level))))
6482 (defun org-content (&optional arg)
6483 "Show all headlines in the buffer, like a table of contents.
6484 With numerical argument N, show content up to level N."
6485 (interactive "P")
6486 (save-excursion
6487 ;; Visit all headings and show their offspring
6488 (and (integerp arg) (org-overview))
6489 (goto-char (point-max))
6490 (catch 'exit
6491 (while (and (progn (condition-case nil
6492 (outline-previous-visible-heading 1)
6493 (error (goto-char (point-min))))
6495 (looking-at org-outline-regexp))
6496 (if (integerp arg)
6497 (show-children (1- arg))
6498 (show-branches))
6499 (if (bobp) (throw 'exit nil))))))
6502 (defun org-optimize-window-after-visibility-change (state)
6503 "Adjust the window after a change in outline visibility.
6504 This function is the default value of the hook `org-cycle-hook'."
6505 (when (get-buffer-window (current-buffer))
6506 (cond
6507 ((eq state 'content) nil)
6508 ((eq state 'all) nil)
6509 ((eq state 'folded) nil)
6510 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6511 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6513 (defun org-remove-empty-overlays-at (pos)
6514 "Remove outline overlays that do not contain non-white stuff."
6515 (mapc
6516 (lambda (o)
6517 (and (eq 'outline (overlay-get o 'invisible))
6518 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6519 (overlay-end o))))
6520 (delete-overlay o)))
6521 (overlays-at pos)))
6523 (defun org-clean-visibility-after-subtree-move ()
6524 "Fix visibility issues after moving a subtree."
6525 ;; First, find a reasonable region to look at:
6526 ;; Start two siblings above, end three below
6527 (let* ((beg (save-excursion
6528 (and (org-get-last-sibling)
6529 (org-get-last-sibling))
6530 (point)))
6531 (end (save-excursion
6532 (and (org-get-next-sibling)
6533 (org-get-next-sibling)
6534 (org-get-next-sibling))
6535 (if (org-at-heading-p)
6536 (point-at-eol)
6537 (point))))
6538 (level (looking-at "\\*+"))
6539 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6540 (save-excursion
6541 (save-restriction
6542 (narrow-to-region beg end)
6543 (when re
6544 ;; Properly fold already folded siblings
6545 (goto-char (point-min))
6546 (while (re-search-forward re nil t)
6547 (if (and (not (outline-invisible-p))
6548 (save-excursion
6549 (goto-char (point-at-eol)) (outline-invisible-p)))
6550 (hide-entry))))
6551 (org-cycle-show-empty-lines 'overview)
6552 (org-cycle-hide-drawers 'overview)))))
6554 (defun org-cycle-show-empty-lines (state)
6555 "Show empty lines above all visible headlines.
6556 The region to be covered depends on STATE when called through
6557 `org-cycle-hook'. Lisp program can use t for STATE to get the
6558 entire buffer covered. Note that an empty line is only shown if there
6559 are at least `org-cycle-separator-lines' empty lines before the headline."
6560 (when (not (= org-cycle-separator-lines 0))
6561 (save-excursion
6562 (let* ((n (abs org-cycle-separator-lines))
6563 (re (cond
6564 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6565 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6566 (t (let ((ns (number-to-string (- n 2))))
6567 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6568 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6569 beg end b e)
6570 (cond
6571 ((memq state '(overview contents t))
6572 (setq beg (point-min) end (point-max)))
6573 ((memq state '(children folded))
6574 (setq beg (point) end (progn (org-end-of-subtree t t)
6575 (beginning-of-line 2)
6576 (point)))))
6577 (when beg
6578 (goto-char beg)
6579 (while (re-search-forward re end t)
6580 (unless (get-char-property (match-end 1) 'invisible)
6581 (setq e (match-end 1))
6582 (if (< org-cycle-separator-lines 0)
6583 (setq b (save-excursion
6584 (goto-char (match-beginning 0))
6585 (org-back-over-empty-lines)
6586 (if (save-excursion
6587 (goto-char (max (point-min) (1- (point))))
6588 (org-at-heading-p))
6589 (1- (point))
6590 (point))))
6591 (setq b (match-beginning 1)))
6592 (outline-flag-region b e nil)))))))
6593 ;; Never hide empty lines at the end of the file.
6594 (save-excursion
6595 (goto-char (point-max))
6596 (outline-previous-heading)
6597 (outline-end-of-heading)
6598 (if (and (looking-at "[ \t\n]+")
6599 (= (match-end 0) (point-max)))
6600 (outline-flag-region (point) (match-end 0) nil))))
6602 (defun org-show-empty-lines-in-parent ()
6603 "Move to the parent and re-show empty lines before visible headlines."
6604 (save-excursion
6605 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6606 (org-cycle-show-empty-lines context))))
6608 (defun org-files-list ()
6609 "Return `org-agenda-files' list, plus all open org-mode files.
6610 This is useful for operations that need to scan all of a user's
6611 open and agenda-wise Org files."
6612 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6613 (dolist (buf (buffer-list))
6614 (with-current-buffer buf
6615 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6616 (let ((file (expand-file-name (buffer-file-name))))
6617 (unless (member file files)
6618 (push file files))))))
6619 files))
6621 (defsubst org-entry-beginning-position ()
6622 "Return the beginning position of the current entry."
6623 (save-excursion (outline-back-to-heading t) (point)))
6625 (defsubst org-entry-end-position ()
6626 "Return the end position of the current entry."
6627 (save-excursion (outline-next-heading) (point)))
6629 (defun org-cycle-hide-drawers (state)
6630 "Re-hide all drawers after a visibility state change."
6631 (when (and (eq major-mode 'org-mode)
6632 (not (memq state '(overview folded contents))))
6633 (save-excursion
6634 (let* ((globalp (memq state '(contents all)))
6635 (beg (if globalp (point-min) (point)))
6636 (end (if globalp (point-max)
6637 (if (eq state 'children)
6638 (save-excursion (outline-next-heading) (point))
6639 (org-end-of-subtree t)))))
6640 (goto-char beg)
6641 (while (re-search-forward org-drawer-regexp end t)
6642 (org-flag-drawer t))))))
6644 (defun org-flag-drawer (flag)
6645 (save-excursion
6646 (beginning-of-line 1)
6647 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6648 (let ((b (match-end 0)))
6649 (if (re-search-forward
6650 "^[ \t]*:END:"
6651 (save-excursion (outline-next-heading) (point)) t)
6652 (outline-flag-region b (point-at-eol) flag)
6653 (error ":END: line missing at position %s" b))))))
6655 (defun org-subtree-end-visible-p ()
6656 "Is the end of the current subtree visible?"
6657 (pos-visible-in-window-p
6658 (save-excursion (org-end-of-subtree t) (point))))
6660 (defun org-first-headline-recenter (&optional N)
6661 "Move cursor to the first headline and recenter the headline.
6662 Optional argument N means put the headline into the Nth line of the window."
6663 (goto-char (point-min))
6664 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6665 (beginning-of-line)
6666 (recenter (prefix-numeric-value N))))
6668 ;;; Saving and restoring visibility
6670 (defun org-outline-overlay-data (&optional use-markers)
6671 "Return a list of the locations of all outline overlays.
6672 These are overlays with the `invisible' property value `outline'.
6673 The return value is a list of cons cells, with start and stop
6674 positions for each overlay.
6675 If USE-MARKERS is set, return the positions as markers."
6676 (let (beg end)
6677 (save-excursion
6678 (save-restriction
6679 (widen)
6680 (delq nil
6681 (mapcar (lambda (o)
6682 (when (eq (overlay-get o 'invisible) 'outline)
6683 (setq beg (overlay-start o)
6684 end (overlay-end o))
6685 (and beg end (> end beg)
6686 (if use-markers
6687 (cons (move-marker (make-marker) beg)
6688 (move-marker (make-marker) end))
6689 (cons beg end)))))
6690 (overlays-in (point-min) (point-max))))))))
6692 (defun org-set-outline-overlay-data (data)
6693 "Create visibility overlays for all positions in DATA.
6694 DATA should have been made by `org-outline-overlay-data'."
6695 (let (o)
6696 (save-excursion
6697 (save-restriction
6698 (widen)
6699 (show-all)
6700 (mapc (lambda (c)
6701 (outline-flag-region (car c) (cdr c) t))
6702 data)))))
6704 ;;; Folding of blocks
6706 (defvar org-hide-block-overlays nil
6707 "Overlays hiding blocks.")
6708 (make-variable-buffer-local 'org-hide-block-overlays)
6710 (defun org-block-map (function &optional start end)
6711 "Call FUNCTION at the head of all source blocks in the current buffer.
6712 Optional arguments START and END can be used to limit the range."
6713 (let ((start (or start (point-min)))
6714 (end (or end (point-max))))
6715 (save-excursion
6716 (goto-char start)
6717 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6718 (save-excursion
6719 (save-match-data
6720 (goto-char (match-beginning 0))
6721 (funcall function)))))))
6723 (defun org-hide-block-toggle-all ()
6724 "Toggle the visibility of all blocks in the current buffer."
6725 (org-block-map #'org-hide-block-toggle))
6727 (defun org-hide-block-all ()
6728 "Fold all blocks in the current buffer."
6729 (interactive)
6730 (org-show-block-all)
6731 (org-block-map #'org-hide-block-toggle-maybe))
6733 (defun org-show-block-all ()
6734 "Unfold all blocks in the current buffer."
6735 (interactive)
6736 (mapc 'delete-overlay org-hide-block-overlays)
6737 (setq org-hide-block-overlays nil))
6739 (defun org-hide-block-toggle-maybe ()
6740 "Toggle visibility of block at point."
6741 (interactive)
6742 (let ((case-fold-search t))
6743 (if (save-excursion
6744 (beginning-of-line 1)
6745 (looking-at org-block-regexp))
6746 (progn (org-hide-block-toggle)
6747 t) ;; to signal that we took action
6748 nil))) ;; to signal that we did not
6750 (defun org-hide-block-toggle (&optional force)
6751 "Toggle the visibility of the current block."
6752 (interactive)
6753 (save-excursion
6754 (beginning-of-line)
6755 (if (re-search-forward org-block-regexp nil t)
6756 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6757 (end (match-end 0)) ;; end of entire body
6759 (if (memq t (mapcar (lambda (overlay)
6760 (eq (overlay-get overlay 'invisible)
6761 'org-hide-block))
6762 (overlays-at start)))
6763 (if (or (not force) (eq force 'off))
6764 (mapc (lambda (ov)
6765 (when (member ov org-hide-block-overlays)
6766 (setq org-hide-block-overlays
6767 (delq ov org-hide-block-overlays)))
6768 (when (eq (overlay-get ov 'invisible)
6769 'org-hide-block)
6770 (delete-overlay ov)))
6771 (overlays-at start)))
6772 (setq ov (make-overlay start end))
6773 (overlay-put ov 'invisible 'org-hide-block)
6774 ;; make the block accessible to isearch
6775 (overlay-put
6776 ov 'isearch-open-invisible
6777 (lambda (ov)
6778 (when (member ov org-hide-block-overlays)
6779 (setq org-hide-block-overlays
6780 (delq ov org-hide-block-overlays)))
6781 (when (eq (overlay-get ov 'invisible)
6782 'org-hide-block)
6783 (delete-overlay ov))))
6784 (push ov org-hide-block-overlays)))
6785 (error "Not looking at a source block"))))
6787 ;; org-tab-after-check-for-cycling-hook
6788 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6789 ;; Remove overlays when changing major mode
6790 (add-hook 'org-mode-hook
6791 (lambda () (org-add-hook 'change-major-mode-hook
6792 'org-show-block-all 'append 'local)))
6794 ;;; Org-goto
6796 (defvar org-goto-window-configuration nil)
6797 (defvar org-goto-marker nil)
6798 (defvar org-goto-map
6799 (let ((map (make-sparse-keymap)))
6800 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6801 (while (setq cmd (pop cmds))
6802 (substitute-key-definition cmd cmd map global-map)))
6803 (suppress-keymap map)
6804 (org-defkey map "\C-m" 'org-goto-ret)
6805 (org-defkey map [(return)] 'org-goto-ret)
6806 (org-defkey map [(left)] 'org-goto-left)
6807 (org-defkey map [(right)] 'org-goto-right)
6808 (org-defkey map [(control ?g)] 'org-goto-quit)
6809 (org-defkey map "\C-i" 'org-cycle)
6810 (org-defkey map [(tab)] 'org-cycle)
6811 (org-defkey map [(down)] 'outline-next-visible-heading)
6812 (org-defkey map [(up)] 'outline-previous-visible-heading)
6813 (if org-goto-auto-isearch
6814 (if (fboundp 'define-key-after)
6815 (define-key-after map [t] 'org-goto-local-auto-isearch)
6816 nil)
6817 (org-defkey map "q" 'org-goto-quit)
6818 (org-defkey map "n" 'outline-next-visible-heading)
6819 (org-defkey map "p" 'outline-previous-visible-heading)
6820 (org-defkey map "f" 'outline-forward-same-level)
6821 (org-defkey map "b" 'outline-backward-same-level)
6822 (org-defkey map "u" 'outline-up-heading))
6823 (org-defkey map "/" 'org-occur)
6824 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6825 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6826 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6827 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6828 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6829 map))
6831 (defconst org-goto-help
6832 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6833 RET=jump to location [Q]uit and return to previous location
6834 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6836 (defvar org-goto-start-pos) ; dynamically scoped parameter
6838 ;; FIXME: Docstring does not mention both interfaces
6839 (defun org-goto (&optional alternative-interface)
6840 "Look up a different location in the current file, keeping current visibility.
6842 When you want look-up or go to a different location in a document, the
6843 fastest way is often to fold the entire buffer and then dive into the tree.
6844 This method has the disadvantage, that the previous location will be folded,
6845 which may not be what you want.
6847 This command works around this by showing a copy of the current buffer
6848 in an indirect buffer, in overview mode. You can dive into the tree in
6849 that copy, use org-occur and incremental search to find a location.
6850 When pressing RET or `Q', the command returns to the original buffer in
6851 which the visibility is still unchanged. After RET it will also jump to
6852 the location selected in the indirect buffer and expose the headline
6853 hierarchy above."
6854 (interactive "P")
6855 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6856 (org-refile-use-outline-path t)
6857 (org-refile-target-verify-function nil)
6858 (interface
6859 (if (not alternative-interface)
6860 org-goto-interface
6861 (if (eq org-goto-interface 'outline)
6862 'outline-path-completion
6863 'outline)))
6864 (org-goto-start-pos (point))
6865 (selected-point
6866 (if (eq interface 'outline)
6867 (car (org-get-location (current-buffer) org-goto-help))
6868 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6869 (org-refile-check-position pa)
6870 (nth 3 pa)))))
6871 (if selected-point
6872 (progn
6873 (org-mark-ring-push org-goto-start-pos)
6874 (goto-char selected-point)
6875 (if (or (outline-invisible-p) (org-invisible-p2))
6876 (org-show-context 'org-goto)))
6877 (message "Quit"))))
6879 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6880 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6881 (defvar org-goto-local-auto-isearch-map) ; defined below
6883 (defun org-get-location (buf help)
6884 "Let the user select a location in the Org-mode buffer BUF.
6885 This function uses a recursive edit. It returns the selected position
6886 or nil."
6887 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6888 (isearch-hide-immediately nil)
6889 (isearch-search-fun-function
6890 (lambda () 'org-goto-local-search-headings))
6891 (org-goto-selected-point org-goto-exit-command)
6892 (pop-up-frames nil)
6893 (special-display-buffer-names nil)
6894 (special-display-regexps nil)
6895 (special-display-function nil))
6896 (save-excursion
6897 (save-window-excursion
6898 (delete-other-windows)
6899 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6900 (org-pop-to-buffer-same-window
6901 (condition-case nil
6902 (make-indirect-buffer (current-buffer) "*org-goto*")
6903 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6904 (with-output-to-temp-buffer "*Help*"
6905 (princ help))
6906 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6907 (setq buffer-read-only nil)
6908 (let ((org-startup-truncated t)
6909 (org-startup-folded nil)
6910 (org-startup-align-all-tables nil))
6911 (org-mode)
6912 (org-overview))
6913 (setq buffer-read-only t)
6914 (if (and (boundp 'org-goto-start-pos)
6915 (integer-or-marker-p org-goto-start-pos))
6916 (let ((org-show-hierarchy-above t)
6917 (org-show-siblings t)
6918 (org-show-following-heading t))
6919 (goto-char org-goto-start-pos)
6920 (and (outline-invisible-p) (org-show-context)))
6921 (goto-char (point-min)))
6922 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6923 (message "Select location and press RET")
6924 (use-local-map org-goto-map)
6925 (recursive-edit)
6927 (kill-buffer "*org-goto*")
6928 (cons org-goto-selected-point org-goto-exit-command)))
6930 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6931 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6932 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6933 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6935 (defun org-goto-local-search-headings (string bound noerror)
6936 "Search and make sure that any matches are in headlines."
6937 (catch 'return
6938 (while (if isearch-forward
6939 (search-forward string bound noerror)
6940 (search-backward string bound noerror))
6941 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6942 (and (member :headline context)
6943 (not (member :tags context))))
6944 (throw 'return (point))))))
6946 (defun org-goto-local-auto-isearch ()
6947 "Start isearch."
6948 (interactive)
6949 (goto-char (point-min))
6950 (let ((keys (this-command-keys)))
6951 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6952 (isearch-mode t)
6953 (isearch-process-search-char (string-to-char keys)))))
6955 (defun org-goto-ret (&optional arg)
6956 "Finish `org-goto' by going to the new location."
6957 (interactive "P")
6958 (setq org-goto-selected-point (point)
6959 org-goto-exit-command 'return)
6960 (throw 'exit nil))
6962 (defun org-goto-left ()
6963 "Finish `org-goto' by going to the new location."
6964 (interactive)
6965 (if (org-at-heading-p)
6966 (progn
6967 (beginning-of-line 1)
6968 (setq org-goto-selected-point (point)
6969 org-goto-exit-command 'left)
6970 (throw 'exit nil))
6971 (error "Not on a heading")))
6973 (defun org-goto-right ()
6974 "Finish `org-goto' by going to the new location."
6975 (interactive)
6976 (if (org-at-heading-p)
6977 (progn
6978 (setq org-goto-selected-point (point)
6979 org-goto-exit-command 'right)
6980 (throw 'exit nil))
6981 (error "Not on a heading")))
6983 (defun org-goto-quit ()
6984 "Finish `org-goto' without cursor motion."
6985 (interactive)
6986 (setq org-goto-selected-point nil)
6987 (setq org-goto-exit-command 'quit)
6988 (throw 'exit nil))
6990 ;;; Indirect buffer display of subtrees
6992 (defvar org-indirect-dedicated-frame nil
6993 "This is the frame being used for indirect tree display.")
6994 (defvar org-last-indirect-buffer nil)
6996 (defun org-tree-to-indirect-buffer (&optional arg)
6997 "Create indirect buffer and narrow it to current subtree.
6998 With numerical prefix ARG, go up to this level and then take that tree.
6999 If ARG is negative, go up that many levels.
7000 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7001 indirect buffer previously made with this command, to avoid proliferation of
7002 indirect buffers. However, when you call the command with a \
7003 \\[universal-argument] prefix, or
7004 when `org-indirect-buffer-display' is `new-frame', the last buffer
7005 is kept so that you can work with several indirect buffers at the same time.
7006 If `org-indirect-buffer-display' is `dedicated-frame', the \
7007 \\[universal-argument] prefix also
7008 requests that a new frame be made for the new buffer, so that the dedicated
7009 frame is not changed."
7010 (interactive "P")
7011 (let ((cbuf (current-buffer))
7012 (cwin (selected-window))
7013 (pos (point))
7014 beg end level heading ibuf)
7015 (save-excursion
7016 (org-back-to-heading t)
7017 (when (numberp arg)
7018 (setq level (org-outline-level))
7019 (if (< arg 0) (setq arg (+ level arg)))
7020 (while (> (setq level (org-outline-level)) arg)
7021 (outline-up-heading 1 t)))
7022 (setq beg (point)
7023 heading (org-get-heading))
7024 (org-end-of-subtree t t)
7025 (if (org-at-heading-p) (backward-char 1))
7026 (setq end (point)))
7027 (if (and (buffer-live-p org-last-indirect-buffer)
7028 (not (eq org-indirect-buffer-display 'new-frame))
7029 (not arg))
7030 (kill-buffer org-last-indirect-buffer))
7031 (setq ibuf (org-get-indirect-buffer cbuf)
7032 org-last-indirect-buffer ibuf)
7033 (cond
7034 ((or (eq org-indirect-buffer-display 'new-frame)
7035 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7036 (select-frame (make-frame))
7037 (delete-other-windows)
7038 (org-pop-to-buffer-same-window ibuf)
7039 (org-set-frame-title heading))
7040 ((eq org-indirect-buffer-display 'dedicated-frame)
7041 (raise-frame
7042 (select-frame (or (and org-indirect-dedicated-frame
7043 (frame-live-p org-indirect-dedicated-frame)
7044 org-indirect-dedicated-frame)
7045 (setq org-indirect-dedicated-frame (make-frame)))))
7046 (delete-other-windows)
7047 (org-pop-to-buffer-same-window ibuf)
7048 (org-set-frame-title (concat "Indirect: " heading)))
7049 ((eq org-indirect-buffer-display 'current-window)
7050 (org-pop-to-buffer-same-window ibuf))
7051 ((eq org-indirect-buffer-display 'other-window)
7052 (pop-to-buffer ibuf))
7053 (t (error "Invalid value")))
7054 (if (featurep 'xemacs)
7055 (save-excursion (org-mode) (turn-on-font-lock)))
7056 (narrow-to-region beg end)
7057 (show-all)
7058 (goto-char pos)
7059 (run-hook-with-args 'org-cycle-hook 'all)
7060 (and (window-live-p cwin) (select-window cwin))))
7062 (defun org-get-indirect-buffer (&optional buffer)
7063 (setq buffer (or buffer (current-buffer)))
7064 (let ((n 1) (base (buffer-name buffer)) bname)
7065 (while (buffer-live-p
7066 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7067 (setq n (1+ n)))
7068 (condition-case nil
7069 (make-indirect-buffer buffer bname 'clone)
7070 (error (make-indirect-buffer buffer bname)))))
7072 (defun org-set-frame-title (title)
7073 "Set the title of the current frame to the string TITLE."
7074 ;; FIXME: how to name a single frame in XEmacs???
7075 (unless (featurep 'xemacs)
7076 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7078 ;;;; Structure editing
7080 ;;; Inserting headlines
7082 (defun org-previous-line-empty-p ()
7083 (save-excursion
7084 (and (not (bobp))
7085 (or (beginning-of-line 0) t)
7086 (save-match-data
7087 (looking-at "[ \t]*$")))))
7089 (defun org-insert-heading (&optional force-heading invisible-ok)
7090 "Insert a new heading or item with same depth at point.
7091 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7092 If point is at the beginning of a headline, insert a sibling before the
7093 current headline. If point is not at the beginning, split the line,
7094 create the new headline with the text in the current line after point
7095 \(but see also the variable `org-M-RET-may-split-line').
7097 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7098 This is important for non-interactive uses of the command."
7099 (interactive "P")
7100 (if (or (= (buffer-size) 0)
7101 (and (not (save-excursion
7102 (and (ignore-errors (org-back-to-heading invisible-ok))
7103 (org-at-heading-p))))
7104 (or force-heading (not (org-in-item-p)))))
7105 (progn
7106 (insert "\n* ")
7107 (run-hooks 'org-insert-heading-hook))
7108 (when (or force-heading (not (org-insert-item)))
7109 (let* ((empty-line-p nil)
7110 (level nil)
7111 (on-heading (org-at-heading-p))
7112 (head (save-excursion
7113 (condition-case nil
7114 (progn
7115 (org-back-to-heading invisible-ok)
7116 (when (and (not on-heading)
7117 (featurep 'org-inlinetask)
7118 (integerp org-inlinetask-min-level)
7119 (>= (length (match-string 0))
7120 org-inlinetask-min-level))
7121 ;; Find a heading level before the inline task
7122 (while (and (setq level (org-up-heading-safe))
7123 (>= level org-inlinetask-min-level)))
7124 (if (org-at-heading-p)
7125 (org-back-to-heading invisible-ok)
7126 (error "This should not happen")))
7127 (setq empty-line-p (org-previous-line-empty-p))
7128 (match-string 0))
7129 (error "*"))))
7130 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7131 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7132 pos hide-previous previous-pos)
7133 (cond
7134 ((and (org-at-heading-p) (bolp)
7135 (or (bobp)
7136 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7137 ;; insert before the current line
7138 (open-line (if blank 2 1)))
7139 ((and (bolp)
7140 (not org-insert-heading-respect-content)
7141 (or (bobp)
7142 (save-excursion
7143 (backward-char 1) (not (outline-invisible-p)))))
7144 ;; insert right here
7145 nil)
7147 ;; somewhere in the line
7148 (save-excursion
7149 (setq previous-pos (point-at-bol))
7150 (end-of-line)
7151 (setq hide-previous (outline-invisible-p)))
7152 (and org-insert-heading-respect-content (org-show-subtree))
7153 (let ((split
7154 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7155 (save-excursion
7156 (let ((p (point)))
7157 (goto-char (point-at-bol))
7158 (and (looking-at org-complex-heading-regexp)
7159 (match-beginning 4)
7160 (> p (match-beginning 4)))))))
7161 tags pos)
7162 (cond
7163 (org-insert-heading-respect-content
7164 (org-end-of-subtree nil t)
7165 (when (featurep 'org-inlinetask)
7166 (while (and (not (eobp))
7167 (looking-at "\\(\\*+\\)[ \t]+")
7168 (>= (length (match-string 1))
7169 org-inlinetask-min-level))
7170 (org-end-of-subtree nil t)))
7171 (or (bolp) (newline))
7172 (or (org-previous-line-empty-p)
7173 (and blank (newline)))
7174 (open-line 1))
7175 ((org-at-heading-p)
7176 (when hide-previous
7177 (show-children)
7178 (org-show-entry))
7179 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7180 (setq tags (and (match-end 2) (match-string 2)))
7181 (and (match-end 1)
7182 (delete-region (match-beginning 1) (match-end 1)))
7183 (setq pos (point-at-bol))
7184 (or split (end-of-line 1))
7185 (delete-horizontal-space)
7186 (if (string-match "\\`\\*+\\'"
7187 (buffer-substring (point-at-bol) (point)))
7188 (insert " "))
7189 (newline (if blank 2 1))
7190 (when tags
7191 (save-excursion
7192 (goto-char pos)
7193 (end-of-line 1)
7194 (insert " " tags)
7195 (org-set-tags nil 'align))))
7197 (or split (end-of-line 1))
7198 (newline (if blank 2 1)))))))
7199 (insert head) (just-one-space)
7200 (setq pos (point))
7201 (end-of-line 1)
7202 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7203 (when (and org-insert-heading-respect-content hide-previous)
7204 (save-excursion
7205 (goto-char previous-pos)
7206 (hide-subtree)))
7207 (run-hooks 'org-insert-heading-hook)))))
7209 (defun org-get-heading (&optional no-tags no-todo)
7210 "Return the heading of the current entry, without the stars.
7211 When NO-TAGS is non-nil, don't include tags.
7212 When NO-TODO is non-nil, don't include TODO keywords."
7213 (save-excursion
7214 (org-back-to-heading t)
7215 (cond
7216 ((and no-tags no-todo)
7217 (looking-at org-complex-heading-regexp)
7218 (match-string 4))
7219 (no-tags
7220 (looking-at (concat org-outline-regexp
7221 "\\(.*?\\)"
7222 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7223 (match-string 1))
7224 (no-todo
7225 (looking-at org-todo-line-regexp)
7226 (match-string 3))
7227 (t (looking-at org-heading-regexp)
7228 (match-string 2)))))
7230 (defun org-heading-components ()
7231 "Return the components of the current heading.
7232 This is a list with the following elements:
7233 - the level as an integer
7234 - the reduced level, different if `org-odd-levels-only' is set.
7235 - the TODO keyword, or nil
7236 - the priority character, like ?A, or nil if no priority is given
7237 - the headline text itself, or the tags string if no headline text
7238 - the tags string, or nil."
7239 (save-excursion
7240 (org-back-to-heading t)
7241 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7242 (list (length (match-string 1))
7243 (org-reduced-level (length (match-string 1)))
7244 (org-match-string-no-properties 2)
7245 (and (match-end 3) (aref (match-string 3) 2))
7246 (org-match-string-no-properties 4)
7247 (org-match-string-no-properties 5)))))
7249 (defun org-get-entry ()
7250 "Get the entry text, after heading, entire subtree."
7251 (save-excursion
7252 (org-back-to-heading t)
7253 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7255 (defun org-insert-heading-after-current ()
7256 "Insert a new heading with same level as current, after current subtree."
7257 (interactive)
7258 (org-back-to-heading)
7259 (org-insert-heading)
7260 (org-move-subtree-down)
7261 (end-of-line 1))
7263 (defun org-insert-heading-respect-content ()
7264 (interactive)
7265 (let ((org-insert-heading-respect-content t))
7266 (org-insert-heading t)))
7268 (defun org-insert-todo-heading-respect-content (&optional force-state)
7269 (interactive "P")
7270 (let ((org-insert-heading-respect-content t))
7271 (org-insert-todo-heading force-state t)))
7273 (defun org-insert-todo-heading (arg &optional force-heading)
7274 "Insert a new heading with the same level and TODO state as current heading.
7275 If the heading has no TODO state, or if the state is DONE, use the first
7276 state (TODO by default). Also with prefix arg, force first state."
7277 (interactive "P")
7278 (when (or force-heading (not (org-insert-item 'checkbox)))
7279 (org-insert-heading force-heading)
7280 (save-excursion
7281 (org-back-to-heading)
7282 (outline-previous-heading)
7283 (looking-at org-todo-line-regexp))
7284 (let*
7285 ((new-mark-x
7286 (if (or arg
7287 (not (match-beginning 2))
7288 (member (match-string 2) org-done-keywords))
7289 (car org-todo-keywords-1)
7290 (match-string 2)))
7291 (new-mark
7293 (run-hook-with-args-until-success
7294 'org-todo-get-default-hook new-mark-x nil)
7295 new-mark-x)))
7296 (beginning-of-line 1)
7297 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7298 (if org-treat-insert-todo-heading-as-state-change
7299 (org-todo new-mark)
7300 (insert new-mark " "))))
7301 (when org-provide-todo-statistics
7302 (org-update-parent-todo-statistics))))
7304 (defun org-insert-subheading (arg)
7305 "Insert a new subheading and demote it.
7306 Works for outline headings and for plain lists alike."
7307 (interactive "P")
7308 (org-insert-heading arg)
7309 (cond
7310 ((org-at-heading-p) (org-do-demote))
7311 ((org-at-item-p) (org-indent-item))))
7313 (defun org-insert-todo-subheading (arg)
7314 "Insert a new subheading with TODO keyword or checkbox and demote it.
7315 Works for outline headings and for plain lists alike."
7316 (interactive "P")
7317 (org-insert-todo-heading arg)
7318 (cond
7319 ((org-at-heading-p) (org-do-demote))
7320 ((org-at-item-p) (org-indent-item))))
7322 ;;; Promotion and Demotion
7324 (defvar org-after-demote-entry-hook nil
7325 "Hook run after an entry has been demoted.
7326 The cursor will be at the beginning of the entry.
7327 When a subtree is being demoted, the hook will be called for each node.")
7329 (defvar org-after-promote-entry-hook nil
7330 "Hook run after an entry has been promoted.
7331 The cursor will be at the beginning of the entry.
7332 When a subtree is being promoted, the hook will be called for each node.")
7334 (defun org-promote-subtree ()
7335 "Promote the entire subtree.
7336 See also `org-promote'."
7337 (interactive)
7338 (save-excursion
7339 (org-with-limited-levels (org-map-tree 'org-promote)))
7340 (org-fix-position-after-promote))
7342 (defun org-demote-subtree ()
7343 "Demote the entire subtree. See `org-demote'.
7344 See also `org-promote'."
7345 (interactive)
7346 (save-excursion
7347 (org-with-limited-levels (org-map-tree 'org-demote)))
7348 (org-fix-position-after-promote))
7351 (defun org-do-promote ()
7352 "Promote the current heading higher up the tree.
7353 If the region is active in `transient-mark-mode', promote all headings
7354 in the region."
7355 (interactive)
7356 (save-excursion
7357 (if (org-region-active-p)
7358 (org-map-region 'org-promote (region-beginning) (region-end))
7359 (org-promote)))
7360 (org-fix-position-after-promote))
7362 (defun org-do-demote ()
7363 "Demote the current heading lower down the tree.
7364 If the region is active in `transient-mark-mode', demote all headings
7365 in the region."
7366 (interactive)
7367 (save-excursion
7368 (if (org-region-active-p)
7369 (org-map-region 'org-demote (region-beginning) (region-end))
7370 (org-demote)))
7371 (org-fix-position-after-promote))
7373 (defun org-fix-position-after-promote ()
7374 "Make sure that after pro/demotion cursor position is right."
7375 (let ((pos (point)))
7376 (when (save-excursion
7377 (beginning-of-line 1)
7378 (looking-at org-todo-line-regexp)
7379 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7380 (cond ((eobp) (insert " "))
7381 ((eolp) (insert " "))
7382 ((equal (char-after) ?\ ) (forward-char 1))))))
7384 (defun org-current-level ()
7385 "Return the level of the current entry, or nil if before the first headline.
7386 The level is the number of stars at the beginning of the headline."
7387 (save-excursion
7388 (org-with-limited-levels
7389 (if (ignore-errors (org-back-to-heading t))
7390 (funcall outline-level)))))
7392 (defun org-get-previous-line-level ()
7393 "Return the outline depth of the last headline before the current line.
7394 Returns 0 for the first headline in the buffer, and nil if before the
7395 first headline."
7396 (let ((current-level (org-current-level))
7397 (prev-level (when (> (line-number-at-pos) 1)
7398 (save-excursion
7399 (beginning-of-line 0)
7400 (org-current-level)))))
7401 (cond ((null current-level) nil) ; Before first headline
7402 ((null prev-level) 0) ; At first headline
7403 (prev-level))))
7405 (defun org-reduced-level (l)
7406 "Compute the effective level of a heading.
7407 This takes into account the setting of `org-odd-levels-only'."
7408 (cond
7409 ((zerop l) 0)
7410 (org-odd-levels-only (1+ (floor (/ l 2))))
7411 (t l)))
7413 (defun org-level-increment ()
7414 "Return the number of stars that will be added or removed at a
7415 time to headlines when structure editing, based on the value of
7416 `org-odd-levels-only'."
7417 (if org-odd-levels-only 2 1))
7419 (defun org-get-valid-level (level &optional change)
7420 "Rectify a level change under the influence of `org-odd-levels-only'
7421 LEVEL is a current level, CHANGE is by how much the level should be
7422 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7423 even level numbers will become the next higher odd number."
7424 (if org-odd-levels-only
7425 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7426 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7427 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7428 (max 1 (+ level (or change 0)))))
7430 (if (boundp 'define-obsolete-function-alias)
7431 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7432 (define-obsolete-function-alias 'org-get-legal-level
7433 'org-get-valid-level)
7434 (define-obsolete-function-alias 'org-get-legal-level
7435 'org-get-valid-level "23.1")))
7437 (defun org-promote ()
7438 "Promote the current heading higher up the tree.
7439 If the region is active in `transient-mark-mode', promote all headings
7440 in the region."
7441 (org-back-to-heading t)
7442 (let* ((level (save-match-data (funcall outline-level)))
7443 (after-change-functions (remove 'flyspell-after-change-function
7444 after-change-functions))
7445 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7446 (diff (abs (- level (length up-head) -1))))
7447 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7448 (replace-match up-head nil t)
7449 ;; Fixup tag positioning
7450 (and org-auto-align-tags (org-set-tags nil t))
7451 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7452 (run-hooks 'org-after-promote-entry-hook)))
7454 (defun org-demote ()
7455 "Demote the current heading lower down the tree.
7456 If the region is active in `transient-mark-mode', demote all headings
7457 in the region."
7458 (org-back-to-heading t)
7459 (let* ((level (save-match-data (funcall outline-level)))
7460 (after-change-functions (remove 'flyspell-after-change-function
7461 after-change-functions))
7462 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7463 (diff (abs (- level (length down-head) -1))))
7464 (replace-match down-head nil t)
7465 ;; Fixup tag positioning
7466 (and org-auto-align-tags (org-set-tags nil t))
7467 (if org-adapt-indentation (org-fixup-indentation diff))
7468 (run-hooks 'org-after-demote-entry-hook)))
7470 (defun org-cycle-level ()
7471 "Cycle the level of an empty headline through possible states.
7472 This goes first to child, then to parent, level, then up the hierarchy.
7473 After top level, it switches back to sibling level."
7474 (interactive)
7475 (let ((org-adapt-indentation nil))
7476 (when (org-point-at-end-of-empty-headline)
7477 (setq this-command 'org-cycle-level) ; Only needed for caching
7478 (let ((cur-level (org-current-level))
7479 (prev-level (org-get-previous-line-level)))
7480 (cond
7481 ;; If first headline in file, promote to top-level.
7482 ((= prev-level 0)
7483 (loop repeat (/ (- cur-level 1) (org-level-increment))
7484 do (org-do-promote)))
7485 ;; If same level as prev, demote one.
7486 ((= prev-level cur-level)
7487 (org-do-demote))
7488 ;; If parent is top-level, promote to top level if not already.
7489 ((= prev-level 1)
7490 (loop repeat (/ (- cur-level 1) (org-level-increment))
7491 do (org-do-promote)))
7492 ;; If top-level, return to prev-level.
7493 ((= cur-level 1)
7494 (loop repeat (/ (- prev-level 1) (org-level-increment))
7495 do (org-do-demote)))
7496 ;; If less than prev-level, promote one.
7497 ((< cur-level prev-level)
7498 (org-do-promote))
7499 ;; If deeper than prev-level, promote until higher than
7500 ;; prev-level.
7501 ((> cur-level prev-level)
7502 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7503 do (org-do-promote))))
7504 t))))
7506 (defun org-map-tree (fun)
7507 "Call FUN for every heading underneath the current one."
7508 (org-back-to-heading)
7509 (let ((level (funcall outline-level)))
7510 (save-excursion
7511 (funcall fun)
7512 (while (and (progn
7513 (outline-next-heading)
7514 (> (funcall outline-level) level))
7515 (not (eobp)))
7516 (funcall fun)))))
7518 (defun org-map-region (fun beg end)
7519 "Call FUN for every heading between BEG and END."
7520 (let ((org-ignore-region t))
7521 (save-excursion
7522 (setq end (copy-marker end))
7523 (goto-char beg)
7524 (if (and (re-search-forward org-outline-regexp-bol nil t)
7525 (< (point) end))
7526 (funcall fun))
7527 (while (and (progn
7528 (outline-next-heading)
7529 (< (point) end))
7530 (not (eobp)))
7531 (funcall fun)))))
7533 (defvar org-property-end-re) ; silence byte-compiler
7534 (defun org-fixup-indentation (diff)
7535 "Change the indentation in the current entry by DIFF.
7536 However, if any line in the current entry has no indentation, or if it
7537 would end up with no indentation after the change, nothing at all is done."
7538 (save-excursion
7539 (let ((end (save-excursion (outline-next-heading)
7540 (point-marker)))
7541 (prohibit (if (> diff 0)
7542 "^\\S-"
7543 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7544 col)
7545 (unless (save-excursion (end-of-line 1)
7546 (re-search-forward prohibit end t))
7547 (while (and (< (point) end)
7548 (re-search-forward "^[ \t]+" end t))
7549 (goto-char (match-end 0))
7550 (setq col (current-column))
7551 (if (< diff 0) (replace-match ""))
7552 (org-indent-to-column (+ diff col))))
7553 (move-marker end nil))))
7555 (defun org-convert-to-odd-levels ()
7556 "Convert an org-mode file with all levels allowed to one with odd levels.
7557 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7558 level 5 etc."
7559 (interactive)
7560 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7561 (let ((outline-level 'org-outline-level)
7562 (org-odd-levels-only nil) n)
7563 (save-excursion
7564 (goto-char (point-min))
7565 (while (re-search-forward "^\\*\\*+ " nil t)
7566 (setq n (- (length (match-string 0)) 2))
7567 (while (>= (setq n (1- n)) 0)
7568 (org-demote))
7569 (end-of-line 1))))))
7571 (defun org-convert-to-oddeven-levels ()
7572 "Convert an org-mode file with only odd levels to one with odd/even levels.
7573 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7574 file contains a section with an even level, conversion would
7575 destroy the structure of the file. An error is signaled in this
7576 case."
7577 (interactive)
7578 (goto-char (point-min))
7579 ;; First check if there are no even levels
7580 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7581 (org-show-context t)
7582 (error "Not all levels are odd in this file. Conversion not possible"))
7583 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7584 (let ((outline-regexp org-outline-regexp)
7585 (outline-level 'org-outline-level)
7586 (org-odd-levels-only nil) n)
7587 (save-excursion
7588 (goto-char (point-min))
7589 (while (re-search-forward "^\\*\\*+ " nil t)
7590 (setq n (/ (1- (length (match-string 0))) 2))
7591 (while (>= (setq n (1- n)) 0)
7592 (org-promote))
7593 (end-of-line 1))))))
7595 (defun org-tr-level (n)
7596 "Make N odd if required."
7597 (if org-odd-levels-only (1+ (/ n 2)) n))
7599 ;;; Vertical tree motion, cutting and pasting of subtrees
7601 (defun org-move-subtree-up (&optional arg)
7602 "Move the current subtree up past ARG headlines of the same level."
7603 (interactive "p")
7604 (org-move-subtree-down (- (prefix-numeric-value arg))))
7606 (defun org-move-subtree-down (&optional arg)
7607 "Move the current subtree down past ARG headlines of the same level."
7608 (interactive "p")
7609 (setq arg (prefix-numeric-value arg))
7610 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7611 'org-get-last-sibling))
7612 (ins-point (make-marker))
7613 (cnt (abs arg))
7614 (col (current-column))
7615 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7616 ;; Select the tree
7617 (org-back-to-heading)
7618 (setq beg0 (point))
7619 (save-excursion
7620 (setq ne-beg (org-back-over-empty-lines))
7621 (setq beg (point)))
7622 (save-match-data
7623 (save-excursion (outline-end-of-heading)
7624 (setq folded (outline-invisible-p)))
7625 (outline-end-of-subtree))
7626 (outline-next-heading)
7627 (setq ne-end (org-back-over-empty-lines))
7628 (setq end (point))
7629 (goto-char beg0)
7630 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7631 ;; include less whitespace
7632 (save-excursion
7633 (goto-char beg)
7634 (forward-line (- ne-beg ne-end))
7635 (setq beg (point))))
7636 ;; Find insertion point, with error handling
7637 (while (> cnt 0)
7638 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7639 (progn (goto-char beg0)
7640 (error "Cannot move past superior level or buffer limit")))
7641 (setq cnt (1- cnt)))
7642 (if (> arg 0)
7643 ;; Moving forward - still need to move over subtree
7644 (progn (org-end-of-subtree t t)
7645 (save-excursion
7646 (org-back-over-empty-lines)
7647 (or (bolp) (newline)))))
7648 (setq ne-ins (org-back-over-empty-lines))
7649 (move-marker ins-point (point))
7650 (setq txt (buffer-substring beg end))
7651 (org-save-markers-in-region beg end)
7652 (delete-region beg end)
7653 (org-remove-empty-overlays-at beg)
7654 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7655 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7656 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7657 (let ((bbb (point)))
7658 (insert-before-markers txt)
7659 (org-reinstall-markers-in-region bbb)
7660 (move-marker ins-point bbb))
7661 (or (bolp) (insert "\n"))
7662 (setq ins-end (point))
7663 (goto-char ins-point)
7664 (org-skip-whitespace)
7665 (when (and (< arg 0)
7666 (org-first-sibling-p)
7667 (> ne-ins ne-beg))
7668 ;; Move whitespace back to beginning
7669 (save-excursion
7670 (goto-char ins-end)
7671 (let ((kill-whole-line t))
7672 (kill-line (- ne-ins ne-beg)) (point)))
7673 (insert (make-string (- ne-ins ne-beg) ?\n)))
7674 (move-marker ins-point nil)
7675 (if folded
7676 (hide-subtree)
7677 (org-show-entry)
7678 (show-children)
7679 (org-cycle-hide-drawers 'children))
7680 (org-clean-visibility-after-subtree-move)
7681 ;; move back to the initial column we were at
7682 (move-to-column col)))
7684 (defvar org-subtree-clip ""
7685 "Clipboard for cut and paste of subtrees.
7686 This is actually only a copy of the kill, because we use the normal kill
7687 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7689 (defvar org-subtree-clip-folded nil
7690 "Was the last copied subtree folded?
7691 This is used to fold the tree back after pasting.")
7693 (defun org-cut-subtree (&optional n)
7694 "Cut the current subtree into the clipboard.
7695 With prefix arg N, cut this many sequential subtrees.
7696 This is a short-hand for marking the subtree and then cutting it."
7697 (interactive "p")
7698 (org-copy-subtree n 'cut))
7700 (defun org-copy-subtree (&optional n cut force-store-markers)
7701 "Cut the current subtree into the clipboard.
7702 With prefix arg N, cut this many sequential subtrees.
7703 This is a short-hand for marking the subtree and then copying it.
7704 If CUT is non-nil, actually cut the subtree.
7705 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7706 of some markers in the region, even if CUT is non-nil. This is
7707 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7708 (interactive "p")
7709 (let (beg end folded (beg0 (point)))
7710 (if (org-called-interactively-p 'any)
7711 (org-back-to-heading nil) ; take what looks like a subtree
7712 (org-back-to-heading t)) ; take what is really there
7713 (org-back-over-empty-lines)
7714 (setq beg (point))
7715 (skip-chars-forward " \t\r\n")
7716 (save-match-data
7717 (save-excursion (outline-end-of-heading)
7718 (setq folded (outline-invisible-p)))
7719 (condition-case nil
7720 (org-forward-same-level (1- n) t)
7721 (error nil))
7722 (org-end-of-subtree t t))
7723 (org-back-over-empty-lines)
7724 (setq end (point))
7725 (goto-char beg0)
7726 (when (> end beg)
7727 (setq org-subtree-clip-folded folded)
7728 (when (or cut force-store-markers)
7729 (org-save-markers-in-region beg end))
7730 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7731 (setq org-subtree-clip (current-kill 0))
7732 (message "%s: Subtree(s) with %d characters"
7733 (if cut "Cut" "Copied")
7734 (length org-subtree-clip)))))
7736 (defun org-paste-subtree (&optional level tree for-yank)
7737 "Paste the clipboard as a subtree, with modification of headline level.
7738 The entire subtree is promoted or demoted in order to match a new headline
7739 level.
7741 If the cursor is at the beginning of a headline, the same level as
7742 that headline is used to paste the tree
7744 If not, the new level is derived from the *visible* headings
7745 before and after the insertion point, and taken to be the inferior headline
7746 level of the two. So if the previous visible heading is level 3 and the
7747 next is level 4 (or vice versa), level 4 will be used for insertion.
7748 This makes sure that the subtree remains an independent subtree and does
7749 not swallow low level entries.
7751 You can also force a different level, either by using a numeric prefix
7752 argument, or by inserting the heading marker by hand. For example, if the
7753 cursor is after \"*****\", then the tree will be shifted to level 5.
7755 If optional TREE is given, use this text instead of the kill ring.
7757 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7758 move back over whitespace before inserting, and move point to the end of
7759 the inserted text when done."
7760 (interactive "P")
7761 (setq tree (or tree (and kill-ring (current-kill 0))))
7762 (unless (org-kill-is-subtree-p tree)
7763 (error "%s"
7764 (substitute-command-keys
7765 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7766 (org-with-limited-levels
7767 (let* ((visp (not (outline-invisible-p)))
7768 (txt tree)
7769 (^re_ "\\(\\*+\\)[ \t]*")
7770 (old-level (if (string-match org-outline-regexp-bol txt)
7771 (- (match-end 0) (match-beginning 0) 1)
7772 -1))
7773 (force-level (cond (level (prefix-numeric-value level))
7774 ((and (looking-at "[ \t]*$")
7775 (string-match
7776 "^\\*+$" (buffer-substring
7777 (point-at-bol) (point))))
7778 (- (match-end 1) (match-beginning 1)))
7779 ((and (bolp)
7780 (looking-at org-outline-regexp))
7781 (- (match-end 0) (point) 1))
7782 (t nil)))
7783 (previous-level (save-excursion
7784 (condition-case nil
7785 (progn
7786 (outline-previous-visible-heading 1)
7787 (if (looking-at ^re_)
7788 (- (match-end 0) (match-beginning 0) 1)
7790 (error 1))))
7791 (next-level (save-excursion
7792 (condition-case nil
7793 (progn
7794 (or (looking-at org-outline-regexp)
7795 (outline-next-visible-heading 1))
7796 (if (looking-at ^re_)
7797 (- (match-end 0) (match-beginning 0) 1)
7799 (error 1))))
7800 (new-level (or force-level (max previous-level next-level)))
7801 (shift (if (or (= old-level -1)
7802 (= new-level -1)
7803 (= old-level new-level))
7805 (- new-level old-level)))
7806 (delta (if (> shift 0) -1 1))
7807 (func (if (> shift 0) 'org-demote 'org-promote))
7808 (org-odd-levels-only nil)
7809 beg end newend)
7810 ;; Remove the forced level indicator
7811 (if force-level
7812 (delete-region (point-at-bol) (point)))
7813 ;; Paste
7814 (beginning-of-line (if (bolp) 1 2))
7815 (unless for-yank (org-back-over-empty-lines))
7816 (setq beg (point))
7817 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7818 (insert-before-markers txt)
7819 (unless (string-match "\n\\'" txt) (insert "\n"))
7820 (setq newend (point))
7821 (org-reinstall-markers-in-region beg)
7822 (setq end (point))
7823 (goto-char beg)
7824 (skip-chars-forward " \t\n\r")
7825 (setq beg (point))
7826 (if (and (outline-invisible-p) visp)
7827 (save-excursion (outline-show-heading)))
7828 ;; Shift if necessary
7829 (unless (= shift 0)
7830 (save-restriction
7831 (narrow-to-region beg end)
7832 (while (not (= shift 0))
7833 (org-map-region func (point-min) (point-max))
7834 (setq shift (+ delta shift)))
7835 (goto-char (point-min))
7836 (setq newend (point-max))))
7837 (when (or (org-called-interactively-p 'interactive) for-yank)
7838 (message "Clipboard pasted as level %d subtree" new-level))
7839 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7840 kill-ring
7841 (eq org-subtree-clip (current-kill 0))
7842 org-subtree-clip-folded)
7843 ;; The tree was folded before it was killed/copied
7844 (hide-subtree))
7845 (and for-yank (goto-char newend)))))
7847 (defun org-kill-is-subtree-p (&optional txt)
7848 "Check if the current kill is an outline subtree, or a set of trees.
7849 Returns nil if kill does not start with a headline, or if the first
7850 headline level is not the largest headline level in the tree.
7851 So this will actually accept several entries of equal levels as well,
7852 which is OK for `org-paste-subtree'.
7853 If optional TXT is given, check this string instead of the current kill."
7854 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7855 (re (org-get-limited-outline-regexp))
7856 (^re (concat "^" re))
7857 (start-level (and kill
7858 (string-match
7859 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7860 kill)
7861 (- (match-end 2) (match-beginning 2) 1)))
7862 (start (1+ (or (match-beginning 2) -1))))
7863 (if (not start-level)
7864 (progn
7865 nil) ;; does not even start with a heading
7866 (catch 'exit
7867 (while (setq start (string-match ^re kill (1+ start)))
7868 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7869 (throw 'exit nil)))
7870 t))))
7872 (defvar org-markers-to-move nil
7873 "Markers that should be moved with a cut-and-paste operation.
7874 Those markers are stored together with their positions relative to
7875 the start of the region.")
7877 (defun org-save-markers-in-region (beg end)
7878 "Check markers in region.
7879 If these markers are between BEG and END, record their position relative
7880 to BEG, so that after moving the block of text, we can put the markers back
7881 into place.
7882 This function gets called just before an entry or tree gets cut from the
7883 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7884 called immediately, to move the markers with the entries."
7885 (setq org-markers-to-move nil)
7886 (when (featurep 'org-clock)
7887 (org-clock-save-markers-for-cut-and-paste beg end))
7888 (when (featurep 'org-agenda)
7889 (org-agenda-save-markers-for-cut-and-paste beg end)))
7891 (defun org-check-and-save-marker (marker beg end)
7892 "Check if MARKER is between BEG and END.
7893 If yes, remember the marker and the distance to BEG."
7894 (when (and (marker-buffer marker)
7895 (equal (marker-buffer marker) (current-buffer)))
7896 (if (and (>= marker beg) (< marker end))
7897 (push (cons marker (- marker beg)) org-markers-to-move))))
7899 (defun org-reinstall-markers-in-region (beg)
7900 "Move all remembered markers to their position relative to BEG."
7901 (mapc (lambda (x)
7902 (move-marker (car x) (+ beg (cdr x))))
7903 org-markers-to-move)
7904 (setq org-markers-to-move nil))
7906 (defun org-narrow-to-subtree ()
7907 "Narrow buffer to the current subtree."
7908 (interactive)
7909 (save-excursion
7910 (save-match-data
7911 (org-with-limited-levels
7912 (narrow-to-region
7913 (progn (org-back-to-heading t) (point))
7914 (progn (org-end-of-subtree t t)
7915 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7916 (point)))))))
7918 (defun org-narrow-to-block ()
7919 "Narrow buffer to the current block."
7920 (interactive)
7921 (let* ((case-fold-search t)
7922 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7923 "^[ \t]*#\\+end_.*")))
7924 (if blockp
7925 (narrow-to-region (car blockp) (cdr blockp))
7926 (error "Not in a block"))))
7928 (eval-when-compile
7929 (defvar org-property-drawer-re))
7931 (defvar org-property-start-re) ;; defined below
7932 (defun org-clone-subtree-with-time-shift (n &optional shift)
7933 "Clone the task (subtree) at point N times.
7934 The clones will be inserted as siblings.
7936 In interactive use, the user will be prompted for the number of
7937 clones to be produced, and for a time SHIFT, which may be a
7938 repeater as used in time stamps, for example `+3d'.
7940 When a valid repeater is given and the entry contains any time
7941 stamps, the clones will become a sequence in time, with time
7942 stamps in the subtree shifted for each clone produced. If SHIFT
7943 is nil or the empty string, time stamps will be left alone. The
7944 ID property of the original subtree is removed.
7946 If the original subtree did contain time stamps with a repeater,
7947 the following will happen:
7948 - the repeater will be removed in each clone
7949 - an additional clone will be produced, with the current, unshifted
7950 date(s) in the entry.
7951 - the original entry will be placed *after* all the clones, with
7952 repeater intact.
7953 - the start days in the repeater in the original entry will be shifted
7954 to past the last clone.
7955 In this way you can spell out a number of instances of a repeating task,
7956 and still retain the repeater to cover future instances of the task."
7957 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7958 (let (beg end template task idprop
7959 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7960 (drawer-re org-drawer-regexp))
7961 (if (not (and (integerp n) (> n 0)))
7962 (error "Invalid number of replications %s" n))
7963 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7964 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7965 shift)))
7966 (error "Invalid shift specification %s" shift))
7967 (when doshift
7968 (setq shift-n (string-to-number (match-string 1 shift))
7969 shift-what (cdr (assoc (match-string 2 shift)
7970 '(("d" . day) ("w" . week)
7971 ("m" . month) ("y" . year))))))
7972 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7973 (setq nmin 1 nmax n)
7974 (org-back-to-heading t)
7975 (setq beg (point))
7976 (setq idprop (org-entry-get nil "ID"))
7977 (org-end-of-subtree t t)
7978 (or (bolp) (insert "\n"))
7979 (setq end (point))
7980 (setq template (buffer-substring beg end))
7981 (when (and doshift
7982 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7983 (delete-region beg end)
7984 (setq end beg)
7985 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7986 (goto-char end)
7987 (loop for n from nmin to nmax do
7988 ;; prepare clone
7989 (with-temp-buffer
7990 (insert template)
7991 (org-mode)
7992 (goto-char (point-min))
7993 (org-show-subtree)
7994 (and idprop (if org-clone-delete-id
7995 (org-entry-delete nil "ID")
7996 (org-id-get-create t)))
7997 (unless (= n 0)
7998 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7999 (kill-whole-line))
8000 (goto-char (point-min))
8001 (while (re-search-forward drawer-re nil t)
8002 (mapc (lambda (d)
8003 (org-remove-empty-drawer-at d (point))) org-drawers)))
8004 (goto-char (point-min))
8005 (when doshift
8006 (while (re-search-forward org-ts-regexp-both nil t)
8007 (org-timestamp-change (* n shift-n) shift-what))
8008 (unless (= n n-no-remove)
8009 (goto-char (point-min))
8010 (while (re-search-forward org-ts-regexp nil t)
8011 (save-excursion
8012 (goto-char (match-beginning 0))
8013 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8014 (delete-region (match-beginning 1) (match-end 1)))))))
8015 (setq task (buffer-string)))
8016 (insert task))
8017 (goto-char beg)))
8019 ;;; Outline Sorting
8021 (defun org-sort (with-case)
8022 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8023 Optional argument WITH-CASE means sort case-sensitively."
8024 (interactive "P")
8025 (cond
8026 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8027 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8029 (org-call-with-arg 'org-sort-entries with-case))))
8031 (defun org-sort-remove-invisible (s)
8032 (remove-text-properties 0 (length s) org-rm-props s)
8033 (while (string-match org-bracket-link-regexp s)
8034 (setq s (replace-match (if (match-end 2)
8035 (match-string 3 s)
8036 (match-string 1 s)) t t s)))
8039 (defvar org-priority-regexp) ; defined later in the file
8041 (defvar org-after-sorting-entries-or-items-hook nil
8042 "Hook that is run after a bunch of entries or items have been sorted.
8043 When children are sorted, the cursor is in the parent line when this
8044 hook gets called. When a region or a plain list is sorted, the cursor
8045 will be in the first entry of the sorted region/list.")
8047 (defun org-sort-entries
8048 (&optional with-case sorting-type getkey-func compare-func property)
8049 "Sort entries on a certain level of an outline tree.
8050 If there is an active region, the entries in the region are sorted.
8051 Else, if the cursor is before the first entry, sort the top-level items.
8052 Else, the children of the entry at point are sorted.
8054 Sorting can be alphabetically, numerically, by date/time as given by
8055 a time stamp, by a property or by priority.
8057 The command prompts for the sorting type unless it has been given to the
8058 function through the SORTING-TYPE argument, which needs to be a character,
8059 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8060 precise meaning of each character:
8062 n Numerically, by converting the beginning of the entry/item to a number.
8063 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8064 t By date/time, either the first active time stamp in the entry, or, if
8065 none exist, by the first inactive one.
8066 s By the scheduled date/time.
8067 d By deadline date/time.
8068 c By creation time, which is assumed to be the first inactive time stamp
8069 at the beginning of a line.
8070 p By priority according to the cookie.
8071 r By the value of a property.
8073 Capital letters will reverse the sort order.
8075 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8076 called with point at the beginning of the record. It must return either
8077 a string or a number that should serve as the sorting key for that record.
8079 Comparing entries ignores case by default. However, with an optional argument
8080 WITH-CASE, the sorting considers case as well."
8081 (interactive "P")
8082 (let ((case-func (if with-case 'identity 'downcase))
8083 start beg end stars re re2
8084 txt what tmp)
8085 ;; Find beginning and end of region to sort
8086 (cond
8087 ((org-region-active-p)
8088 ;; we will sort the region
8089 (setq end (region-end)
8090 what "region")
8091 (goto-char (region-beginning))
8092 (if (not (org-at-heading-p)) (outline-next-heading))
8093 (setq start (point)))
8094 ((or (org-at-heading-p)
8095 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8096 ;; we will sort the children of the current headline
8097 (org-back-to-heading)
8098 (setq start (point)
8099 end (progn (org-end-of-subtree t t)
8100 (or (bolp) (insert "\n"))
8101 (org-back-over-empty-lines)
8102 (point))
8103 what "children")
8104 (goto-char start)
8105 (show-subtree)
8106 (outline-next-heading))
8108 ;; we will sort the top-level entries in this file
8109 (goto-char (point-min))
8110 (or (org-at-heading-p) (outline-next-heading))
8111 (setq start (point))
8112 (goto-char (point-max))
8113 (beginning-of-line 1)
8114 (when (looking-at ".*?\\S-")
8115 ;; File ends in a non-white line
8116 (end-of-line 1)
8117 (insert "\n"))
8118 (setq end (point-max))
8119 (setq what "top-level")
8120 (goto-char start)
8121 (show-all)))
8123 (setq beg (point))
8124 (if (>= beg end) (error "Nothing to sort"))
8126 (looking-at "\\(\\*+\\)")
8127 (setq stars (match-string 1)
8128 re (concat "^" (regexp-quote stars) " +")
8129 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8130 txt (buffer-substring beg end))
8131 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8132 (if (and (not (equal stars "*")) (string-match re2 txt))
8133 (error "Region to sort contains a level above the first entry"))
8135 (unless sorting-type
8136 (message
8137 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8138 [t]ime [s]cheduled [d]eadline [c]reated
8139 A/N/T/S/D/C/P/O/F means reversed:"
8140 what)
8141 (setq sorting-type (read-char-exclusive))
8143 (and (= (downcase sorting-type) ?f)
8144 (setq getkey-func
8145 (org-icompleting-read "Sort using function: "
8146 obarray 'fboundp t nil nil))
8147 (setq getkey-func (intern getkey-func)))
8149 (and (= (downcase sorting-type) ?r)
8150 (setq property
8151 (org-icompleting-read "Property: "
8152 (mapcar 'list (org-buffer-property-keys t))
8153 nil t))))
8155 (message "Sorting entries...")
8157 (save-restriction
8158 (narrow-to-region start end)
8159 (let ((dcst (downcase sorting-type))
8160 (case-fold-search nil)
8161 (now (current-time)))
8162 (sort-subr
8163 (/= dcst sorting-type)
8164 ;; This function moves to the beginning character of the "record" to
8165 ;; be sorted.
8166 (lambda nil
8167 (if (re-search-forward re nil t)
8168 (goto-char (match-beginning 0))
8169 (goto-char (point-max))))
8170 ;; This function moves to the last character of the "record" being
8171 ;; sorted.
8172 (lambda nil
8173 (save-match-data
8174 (condition-case nil
8175 (outline-forward-same-level 1)
8176 (error
8177 (goto-char (point-max))))))
8178 ;; This function returns the value that gets sorted against.
8179 (lambda nil
8180 (cond
8181 ((= dcst ?n)
8182 (if (looking-at org-complex-heading-regexp)
8183 (string-to-number (match-string 4))
8184 nil))
8185 ((= dcst ?a)
8186 (if (looking-at org-complex-heading-regexp)
8187 (funcall case-func (match-string 4))
8188 nil))
8189 ((= dcst ?t)
8190 (let ((end (save-excursion (outline-next-heading) (point))))
8191 (if (or (re-search-forward org-ts-regexp end t)
8192 (re-search-forward org-ts-regexp-both end t))
8193 (org-time-string-to-seconds (match-string 0))
8194 (org-float-time now))))
8195 ((= dcst ?c)
8196 (let ((end (save-excursion (outline-next-heading) (point))))
8197 (if (re-search-forward
8198 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8199 end t)
8200 (org-time-string-to-seconds (match-string 0))
8201 (org-float-time now))))
8202 ((= dcst ?s)
8203 (let ((end (save-excursion (outline-next-heading) (point))))
8204 (if (re-search-forward org-scheduled-time-regexp end t)
8205 (org-time-string-to-seconds (match-string 1))
8206 (org-float-time now))))
8207 ((= dcst ?d)
8208 (let ((end (save-excursion (outline-next-heading) (point))))
8209 (if (re-search-forward org-deadline-time-regexp end t)
8210 (org-time-string-to-seconds (match-string 1))
8211 (org-float-time now))))
8212 ((= dcst ?p)
8213 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8214 (string-to-char (match-string 2))
8215 org-default-priority))
8216 ((= dcst ?r)
8217 (or (org-entry-get nil property) ""))
8218 ((= dcst ?o)
8219 (if (looking-at org-complex-heading-regexp)
8220 (- 9999 (length (member (match-string 2)
8221 org-todo-keywords-1)))))
8222 ((= dcst ?f)
8223 (if getkey-func
8224 (progn
8225 (setq tmp (funcall getkey-func))
8226 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8227 tmp)
8228 (error "Invalid key function `%s'" getkey-func)))
8229 (t (error "Invalid sorting type `%c'" sorting-type))))
8231 (cond
8232 ((= dcst ?a) 'string<)
8233 ((= dcst ?f) compare-func)
8234 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8235 (t nil)))))
8236 (run-hooks 'org-after-sorting-entries-or-items-hook)
8237 (message "Sorting entries...done")))
8239 (defun org-do-sort (table what &optional with-case sorting-type)
8240 "Sort TABLE of WHAT according to SORTING-TYPE.
8241 The user will be prompted for the SORTING-TYPE if the call to this
8242 function does not specify it. WHAT is only for the prompt, to indicate
8243 what is being sorted. The sorting key will be extracted from
8244 the car of the elements of the table.
8245 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8246 (unless sorting-type
8247 (message
8248 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8249 what)
8250 (setq sorting-type (read-char-exclusive)))
8251 (let ((dcst (downcase sorting-type))
8252 extractfun comparefun)
8253 ;; Define the appropriate functions
8254 (cond
8255 ((= dcst ?n)
8256 (setq extractfun 'string-to-number
8257 comparefun (if (= dcst sorting-type) '< '>)))
8258 ((= dcst ?a)
8259 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8260 (lambda(x) (downcase (org-sort-remove-invisible x))))
8261 comparefun (if (= dcst sorting-type)
8262 'string<
8263 (lambda (a b) (and (not (string< a b))
8264 (not (string= a b)))))))
8265 ((= dcst ?t)
8266 (setq extractfun
8267 (lambda (x)
8268 (if (or (string-match org-ts-regexp x)
8269 (string-match org-ts-regexp-both x))
8270 (org-float-time
8271 (org-time-string-to-time (match-string 0 x)))
8273 comparefun (if (= dcst sorting-type) '< '>)))
8274 (t (error "Invalid sorting type `%c'" sorting-type)))
8276 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8277 table)
8278 (lambda (a b) (funcall comparefun (car a) (car b))))))
8281 ;;; The orgstruct minor mode
8283 ;; Define a minor mode which can be used in other modes in order to
8284 ;; integrate the org-mode structure editing commands.
8286 ;; This is really a hack, because the org-mode structure commands use
8287 ;; keys which normally belong to the major mode. Here is how it
8288 ;; works: The minor mode defines all the keys necessary to operate the
8289 ;; structure commands, but wraps the commands into a function which
8290 ;; tests if the cursor is currently at a headline or a plain list
8291 ;; item. If that is the case, the structure command is used,
8292 ;; temporarily setting many Org-mode variables like regular
8293 ;; expressions for filling etc. However, when any of those keys is
8294 ;; used at a different location, function uses `key-binding' to look
8295 ;; up if the key has an associated command in another currently active
8296 ;; keymap (minor modes, major mode, global), and executes that
8297 ;; command. There might be problems if any of the keys is otherwise
8298 ;; used as a prefix key.
8300 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8301 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8302 ;; addresses this by checking explicitly for both bindings.
8304 (defvar orgstruct-mode-map (make-sparse-keymap)
8305 "Keymap for the minor `orgstruct-mode'.")
8307 (defvar org-local-vars nil
8308 "List of local variables, for use by `orgstruct-mode'.")
8310 ;;;###autoload
8311 (define-minor-mode orgstruct-mode
8312 "Toggle the minor mode `orgstruct-mode'.
8313 This mode is for using Org-mode structure commands in other
8314 modes. The following keys behave as if Org-mode were active, if
8315 the cursor is on a headline, or on a plain list item (both as
8316 defined by Org-mode).
8318 M-up Move entry/item up
8319 M-down Move entry/item down
8320 M-left Promote
8321 M-right Demote
8322 M-S-up Move entry/item up
8323 M-S-down Move entry/item down
8324 M-S-left Promote subtree
8325 M-S-right Demote subtree
8326 M-q Fill paragraph and items like in Org-mode
8327 C-c ^ Sort entries
8328 C-c - Cycle list bullet
8329 TAB Cycle item visibility
8330 M-RET Insert new heading/item
8331 S-M-RET Insert new TODO heading / Checkbox item
8332 C-c C-c Set tags / toggle checkbox"
8333 nil " OrgStruct" nil
8334 (org-load-modules-maybe)
8335 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8337 ;;;###autoload
8338 (defun turn-on-orgstruct ()
8339 "Unconditionally turn on `orgstruct-mode'."
8340 (orgstruct-mode 1))
8342 (defun orgstruct++-mode (&optional arg)
8343 "Toggle `orgstruct-mode', the enhanced version of it.
8344 In addition to setting orgstruct-mode, this also exports all indentation
8345 and autofilling variables from org-mode into the buffer. It will also
8346 recognize item context in multiline items.
8347 Note that turning off orgstruct-mode will *not* remove the
8348 indentation/paragraph settings. This can only be done by refreshing the
8349 major mode, for example with \\[normal-mode]."
8350 (interactive "P")
8351 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8352 (if (< arg 1)
8353 (orgstruct-mode -1)
8354 (orgstruct-mode 1)
8355 (let (var val)
8356 (mapc
8357 (lambda (x)
8358 (when (string-match
8359 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8360 (symbol-name (car x)))
8361 (setq var (car x) val (nth 1 x))
8362 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8363 org-local-vars)
8364 (org-set-local 'orgstruct-is-++ t))))
8366 (defvar orgstruct-is-++ nil
8367 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8368 (make-variable-buffer-local 'orgstruct-is-++)
8370 ;;;###autoload
8371 (defun turn-on-orgstruct++ ()
8372 "Unconditionally turn on `orgstruct++-mode'."
8373 (orgstruct++-mode 1))
8375 (defun orgstruct-error ()
8376 "Error when there is no default binding for a structure key."
8377 (interactive)
8378 (error "This key has no function outside structure elements"))
8380 (defun orgstruct-setup ()
8381 "Setup orgstruct keymaps."
8382 (let ((nfunc 0)
8383 (bindings
8384 (list
8385 '([(meta up)] org-metaup)
8386 '([(meta down)] org-metadown)
8387 '([(meta left)] org-metaleft)
8388 '([(meta right)] org-metaright)
8389 '([(meta shift up)] org-shiftmetaup)
8390 '([(meta shift down)] org-shiftmetadown)
8391 '([(meta shift left)] org-shiftmetaleft)
8392 '([(meta shift right)] org-shiftmetaright)
8393 '([?\e (up)] org-metaup)
8394 '([?\e (down)] org-metadown)
8395 '([?\e (left)] org-metaleft)
8396 '([?\e (right)] org-metaright)
8397 '([?\e (shift up)] org-shiftmetaup)
8398 '([?\e (shift down)] org-shiftmetadown)
8399 '([?\e (shift left)] org-shiftmetaleft)
8400 '([?\e (shift right)] org-shiftmetaright)
8401 '([(shift up)] org-shiftup)
8402 '([(shift down)] org-shiftdown)
8403 '([(shift left)] org-shiftleft)
8404 '([(shift right)] org-shiftright)
8405 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8406 '("\M-q" fill-paragraph)
8407 '("\C-c^" org-sort)
8408 '("\C-c-" org-cycle-list-bullet)))
8409 elt key fun cmd)
8410 (while (setq elt (pop bindings))
8411 (setq nfunc (1+ nfunc))
8412 (setq key (org-key (car elt))
8413 fun (nth 1 elt)
8414 cmd (orgstruct-make-binding fun nfunc key))
8415 (org-defkey orgstruct-mode-map key cmd))
8417 ;; Special treatment needed for TAB and RET
8418 (org-defkey orgstruct-mode-map [(tab)]
8419 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8420 (org-defkey orgstruct-mode-map "\C-i"
8421 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8423 (org-defkey orgstruct-mode-map "\M-\C-m"
8424 (orgstruct-make-binding 'org-insert-heading 105
8425 "\M-\C-m" [(meta return)]))
8426 (org-defkey orgstruct-mode-map [(meta return)]
8427 (orgstruct-make-binding 'org-insert-heading 106
8428 [(meta return)] "\M-\C-m"))
8430 (org-defkey orgstruct-mode-map [(shift meta return)]
8431 (orgstruct-make-binding 'org-insert-todo-heading 107
8432 [(meta return)] "\M-\C-m"))
8434 (org-defkey orgstruct-mode-map "\e\C-m"
8435 (orgstruct-make-binding 'org-insert-heading 108
8436 "\e\C-m" [?\e (return)]))
8437 (org-defkey orgstruct-mode-map [?\e (return)]
8438 (orgstruct-make-binding 'org-insert-heading 109
8439 [?\e (return)] "\e\C-m"))
8440 (org-defkey orgstruct-mode-map [?\e (shift return)]
8441 (orgstruct-make-binding 'org-insert-todo-heading 110
8442 [?\e (return)] "\e\C-m"))
8444 (unless org-local-vars
8445 (setq org-local-vars (org-get-local-variables)))
8449 (defun orgstruct-make-binding (fun n &rest keys)
8450 "Create a function for binding in the structure minor mode.
8451 FUN is the command to call inside a table. N is used to create a unique
8452 command name. KEYS are keys that should be checked in for a command
8453 to execute outside of tables."
8454 (eval
8455 (list 'defun
8456 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8457 '(arg)
8458 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8459 "Outside of structure, run the binding of `"
8460 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8461 "'.")
8462 '(interactive "p")
8463 (list 'if
8464 `(org-context-p 'headline 'item
8465 (and orgstruct-is-++
8466 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8467 'item-body))
8468 (list 'org-run-like-in-org-mode (list 'quote fun))
8469 (list 'let '(orgstruct-mode)
8470 (list 'call-interactively
8471 (append '(or)
8472 (mapcar (lambda (k)
8473 (list 'key-binding k))
8474 keys)
8475 '('orgstruct-error))))))))
8477 (defun org-context-p (&rest contexts)
8478 "Check if local context is any of CONTEXTS.
8479 Possible values in the list of contexts are `table', `headline', and `item'."
8480 (let ((pos (point)))
8481 (goto-char (point-at-bol))
8482 (prog1 (or (and (memq 'table contexts)
8483 (looking-at "[ \t]*|"))
8484 (and (memq 'headline contexts)
8485 (looking-at org-outline-regexp))
8486 (and (memq 'item contexts)
8487 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8488 (and (memq 'item-body contexts)
8489 (org-in-item-p)))
8490 (goto-char pos))))
8492 (defun org-get-local-variables ()
8493 "Return a list of all local variables in an org-mode buffer."
8494 (let (varlist)
8495 (with-current-buffer (get-buffer-create "*Org tmp*")
8496 (erase-buffer)
8497 (org-mode)
8498 (setq varlist (buffer-local-variables)))
8499 (kill-buffer "*Org tmp*")
8500 (delq nil
8501 (mapcar
8502 (lambda (x)
8503 (setq x
8504 (if (symbolp x)
8505 (list x)
8506 (list (car x) (list 'quote (cdr x)))))
8507 (if (string-match
8508 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8509 (symbol-name (car x)))
8510 x nil))
8511 varlist))))
8513 (defun org-clone-local-variables (from-buffer &optional regexp)
8514 "Clone local variables from FROM-BUFFER.
8515 Optional argument REGEXP selects variables to clone."
8516 (mapc
8517 (lambda (pair)
8518 (and (symbolp (car pair))
8519 (or (null regexp)
8520 (string-match regexp (symbol-name (car pair))))
8521 (set (make-local-variable (car pair))
8522 (cdr pair))))
8523 (buffer-local-variables from-buffer)))
8525 ;;;###autoload
8526 (defun org-run-like-in-org-mode (cmd)
8527 "Run a command, pretending that the current buffer is in Org-mode.
8528 This will temporarily bind local variables that are typically bound in
8529 Org-mode to the values they have in Org-mode, and then interactively
8530 call CMD."
8531 (org-load-modules-maybe)
8532 (unless org-local-vars
8533 (setq org-local-vars (org-get-local-variables)))
8534 (eval (list 'let org-local-vars
8535 (list 'call-interactively (list 'quote cmd)))))
8537 ;;;; Archiving
8539 (defun org-get-category (&optional pos force-refresh)
8540 "Get the category applying to position POS."
8541 (save-match-data
8542 (if force-refresh (org-refresh-category-properties))
8543 (let ((pos (or pos (point))))
8544 (or (get-text-property pos 'org-category)
8545 (progn (org-refresh-category-properties)
8546 (get-text-property pos 'org-category))))))
8548 (defun org-refresh-category-properties ()
8549 "Refresh category text properties in the buffer."
8550 (let ((def-cat (cond
8551 ((null org-category)
8552 (if buffer-file-name
8553 (file-name-sans-extension
8554 (file-name-nondirectory buffer-file-name))
8555 "???"))
8556 ((symbolp org-category) (symbol-name org-category))
8557 (t org-category)))
8558 beg end cat pos optionp)
8559 (org-unmodified
8560 (save-excursion
8561 (save-restriction
8562 (widen)
8563 (goto-char (point-min))
8564 (put-text-property (point) (point-max) 'org-category def-cat)
8565 (while (re-search-forward
8566 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8567 (setq pos (match-end 0)
8568 optionp (equal (char-after (match-beginning 0)) ?#)
8569 cat (org-trim (match-string 2)))
8570 (if optionp
8571 (setq beg (point-at-bol) end (point-max))
8572 (org-back-to-heading t)
8573 (setq beg (point) end (org-end-of-subtree t t)))
8574 (put-text-property beg end 'org-category cat)
8575 (put-text-property beg end 'org-category-position beg)
8576 (goto-char pos)))))))
8579 ;;;; Link Stuff
8581 ;;; Link abbreviations
8583 (defun org-link-expand-abbrev (link)
8584 "Apply replacements as defined in `org-link-abbrev-alist."
8585 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8586 (let* ((key (match-string 1 link))
8587 (as (or (assoc key org-link-abbrev-alist-local)
8588 (assoc key org-link-abbrev-alist)))
8589 (tag (and (match-end 2) (match-string 3 link)))
8590 rpl)
8591 (if (not as)
8592 link
8593 (setq rpl (cdr as))
8594 (cond
8595 ((symbolp rpl) (funcall rpl tag))
8596 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8597 ((string-match "%h" rpl)
8598 (replace-match (url-hexify-string (or tag "")) t t rpl))
8599 (t (concat rpl tag)))))
8600 link))
8602 ;;; Storing and inserting links
8604 (defvar org-insert-link-history nil
8605 "Minibuffer history for links inserted with `org-insert-link'.")
8607 (defvar org-stored-links nil
8608 "Contains the links stored with `org-store-link'.")
8610 (defvar org-store-link-plist nil
8611 "Plist with info about the most recently link created with `org-store-link'.")
8613 (defvar org-link-protocols nil
8614 "Link protocols added to Org-mode using `org-add-link-type'.")
8616 (defvar org-store-link-functions nil
8617 "List of functions that are called to create and store a link.
8618 Each function will be called in turn until one returns a non-nil
8619 value. Each function should check if it is responsible for creating
8620 this link (for example by looking at the major mode).
8621 If not, it must exit and return nil.
8622 If yes, it should return a non-nil value after a calling
8623 `org-store-link-props' with a list of properties and values.
8624 Special properties are:
8626 :type The link prefix, like \"http\". This must be given.
8627 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8628 This is obligatory as well.
8629 :description Optional default description for the second pair
8630 of brackets in an Org-mode link. The user can still change
8631 this when inserting this link into an Org-mode buffer.
8633 In addition to these, any additional properties can be specified
8634 and then used in remember templates.")
8636 (defun org-add-link-type (type &optional follow export)
8637 "Add TYPE to the list of `org-link-types'.
8638 Re-compute all regular expressions depending on `org-link-types'
8640 FOLLOW and EXPORT are two functions.
8642 FOLLOW should take the link path as the single argument and do whatever
8643 is necessary to follow the link, for example find a file or display
8644 a mail message.
8646 EXPORT should format the link path for export to one of the export formats.
8647 It should be a function accepting three arguments:
8649 path the path of the link, the text after the prefix (like \"http:\")
8650 desc the description of the link, if any, or a description added by
8651 org-export-normalize-links if there is none
8652 format the export format, a symbol like `html' or `latex' or `ascii'..
8654 The function may use the FORMAT information to return different values
8655 depending on the format. The return value will be put literally into
8656 the exported file. If the return value is nil, this means Org should
8657 do what it normally does with links which do not have EXPORT defined.
8659 Org-mode has a built-in default for exporting links. If you are happy with
8660 this default, there is no need to define an export function for the link
8661 type. For a simple example of an export function, see `org-bbdb.el'."
8662 (add-to-list 'org-link-types type t)
8663 (org-make-link-regexps)
8664 (if (assoc type org-link-protocols)
8665 (setcdr (assoc type org-link-protocols) (list follow export))
8666 (push (list type follow export) org-link-protocols)))
8668 (defvar org-agenda-buffer-name)
8670 ;;;###autoload
8671 (defun org-store-link (arg)
8672 "\\<org-mode-map>Store an org-link to the current location.
8673 This link is added to `org-stored-links' and can later be inserted
8674 into an org-buffer with \\[org-insert-link].
8676 For some link types, a prefix arg is interpreted:
8677 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8678 For file links, arg negates `org-context-in-file-links'."
8679 (interactive "P")
8680 (org-load-modules-maybe)
8681 (setq org-store-link-plist nil) ; reset
8682 (org-with-limited-levels
8683 (let (link cpltxt desc description search txt custom-id agenda-link)
8684 (cond
8686 ((run-hook-with-args-until-success 'org-store-link-functions)
8687 (setq link (plist-get org-store-link-plist :link)
8688 desc (or (plist-get org-store-link-plist :description) link)))
8690 ((org-src-edit-buffer-p)
8691 (let (label gc)
8692 (while (or (not label)
8693 (save-excursion
8694 (save-restriction
8695 (widen)
8696 (goto-char (point-min))
8697 (re-search-forward
8698 (regexp-quote (format org-coderef-label-format label))
8699 nil t))))
8700 (when label (message "Label exists already") (sit-for 2))
8701 (setq label (read-string "Code line label: " label)))
8702 (end-of-line 1)
8703 (setq link (format org-coderef-label-format label))
8704 (setq gc (- 79 (length link)))
8705 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8706 (insert link)
8707 (setq link (concat "(" label ")") desc nil)))
8709 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8710 ;; We are in the agenda, link to referenced location
8711 (let ((m (or (get-text-property (point) 'org-hd-marker)
8712 (get-text-property (point) 'org-marker))))
8713 (when m
8714 (org-with-point-at m
8715 (setq agenda-link
8716 (if (org-called-interactively-p 'any)
8717 (call-interactively 'org-store-link)
8718 (org-store-link nil)))))))
8720 ((eq major-mode 'calendar-mode)
8721 (let ((cd (calendar-cursor-to-date)))
8722 (setq link
8723 (format-time-string
8724 (car org-time-stamp-formats)
8725 (apply 'encode-time
8726 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8727 nil nil nil))))
8728 (org-store-link-props :type "calendar" :date cd)))
8730 ((eq major-mode 'w3-mode)
8731 (setq cpltxt (if (and (buffer-name)
8732 (not (string-match "Untitled" (buffer-name))))
8733 (buffer-name)
8734 (url-view-url t))
8735 link (org-make-link (url-view-url t)))
8736 (org-store-link-props :type "w3" :url (url-view-url t)))
8738 ((eq major-mode 'w3m-mode)
8739 (setq cpltxt (or w3m-current-title w3m-current-url)
8740 link (org-make-link w3m-current-url))
8741 (org-store-link-props :type "w3m" :url (url-view-url t)))
8743 ((setq search (run-hook-with-args-until-success
8744 'org-create-file-search-functions))
8745 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8746 "::" search))
8747 (setq cpltxt (or description link)))
8749 ((eq major-mode 'image-mode)
8750 (setq cpltxt (concat "file:"
8751 (abbreviate-file-name buffer-file-name))
8752 link (org-make-link cpltxt))
8753 (org-store-link-props :type "image" :file buffer-file-name))
8755 ((eq major-mode 'dired-mode)
8756 ;; link to the file in the current line
8757 (let ((file (dired-get-filename nil t)))
8758 (setq file (if file
8759 (abbreviate-file-name
8760 (expand-file-name (dired-get-filename nil t)))
8761 ;; otherwise, no file so use current directory.
8762 default-directory))
8763 (setq cpltxt (concat "file:" file)
8764 link (org-make-link cpltxt))))
8766 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8767 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8768 (cond
8769 ((org-in-regexp "<<\\(.*?\\)>>")
8770 (setq cpltxt
8771 (concat "file:"
8772 (abbreviate-file-name
8773 (buffer-file-name (buffer-base-buffer)))
8774 "::" (match-string 1))
8775 link (org-make-link cpltxt)))
8776 ((and (featurep 'org-id)
8777 (or (eq org-link-to-org-use-id t)
8778 (and (eq org-link-to-org-use-id 'create-if-interactive)
8779 (org-called-interactively-p 'any))
8780 (and (eq org-link-to-org-use-id
8781 'create-if-interactive-and-no-custom-id)
8782 (org-called-interactively-p 'any)
8783 (not custom-id))
8784 (and org-link-to-org-use-id
8785 (org-entry-get nil "ID"))))
8786 ;; We can make a link using the ID.
8787 (setq link (condition-case nil
8788 (prog1 (org-id-store-link)
8789 (setq desc (plist-get org-store-link-plist
8790 :description)))
8791 (error
8792 ;; probably before first headline, link to file only
8793 (concat "file:"
8794 (abbreviate-file-name
8795 (buffer-file-name (buffer-base-buffer))))))))
8797 ;; Just link to current headline
8798 (setq cpltxt (concat "file:"
8799 (abbreviate-file-name
8800 (buffer-file-name (buffer-base-buffer)))))
8801 ;; Add a context search string
8802 (when (org-xor org-context-in-file-links arg)
8803 (setq txt (cond
8804 ((org-at-heading-p) nil)
8805 ((org-region-active-p)
8806 (buffer-substring (region-beginning) (region-end)))
8807 (t nil)))
8808 (when (or (null txt) (string-match "\\S-" txt))
8809 (setq cpltxt
8810 (concat cpltxt "::"
8811 (condition-case nil
8812 (org-make-org-heading-search-string txt)
8813 (error "")))
8814 desc (or (nth 4 (ignore-errors
8815 (org-heading-components))) "NONE"))))
8816 (if (string-match "::\\'" cpltxt)
8817 (setq cpltxt (substring cpltxt 0 -2)))
8818 (setq link (org-make-link cpltxt)))))
8820 ((buffer-file-name (buffer-base-buffer))
8821 ;; Just link to this file here.
8822 (setq cpltxt (concat "file:"
8823 (abbreviate-file-name
8824 (buffer-file-name (buffer-base-buffer)))))
8825 ;; Add a context string
8826 (when (org-xor org-context-in-file-links arg)
8827 (setq txt (if (org-region-active-p)
8828 (buffer-substring (region-beginning) (region-end))
8829 (buffer-substring (point-at-bol) (point-at-eol))))
8830 ;; Only use search option if there is some text.
8831 (when (string-match "\\S-" txt)
8832 (setq cpltxt
8833 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8834 desc "NONE")))
8835 (setq link (org-make-link cpltxt)))
8837 ((org-called-interactively-p 'interactive)
8838 (error "Cannot link to a buffer which is not visiting a file"))
8840 (t (setq link nil)))
8842 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8843 (setq link (or link cpltxt)
8844 desc (or desc cpltxt))
8845 (if (equal desc "NONE") (setq desc nil))
8847 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8848 (progn
8849 (setq org-stored-links
8850 (cons (list link desc) org-stored-links))
8851 (message "Stored: %s" (or desc link))
8852 (when custom-id
8853 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8854 "::#" custom-id))
8855 (setq org-stored-links
8856 (cons (list link desc) org-stored-links))))
8857 (or agenda-link (and link (org-make-link-string link desc)))))))
8859 (defun org-store-link-props (&rest plist)
8860 "Store link properties, extract names and addresses."
8861 (let (x adr)
8862 (when (setq x (plist-get plist :from))
8863 (setq adr (mail-extract-address-components x))
8864 (setq plist (plist-put plist :fromname (car adr)))
8865 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8866 (when (setq x (plist-get plist :to))
8867 (setq adr (mail-extract-address-components x))
8868 (setq plist (plist-put plist :toname (car adr)))
8869 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8870 (let ((from (plist-get plist :from))
8871 (to (plist-get plist :to)))
8872 (when (and from to org-from-is-user-regexp)
8873 (setq plist
8874 (plist-put plist :fromto
8875 (if (string-match org-from-is-user-regexp from)
8876 (concat "to %t")
8877 (concat "from %f"))))))
8878 (setq org-store-link-plist plist))
8880 (defun org-add-link-props (&rest plist)
8881 "Add these properties to the link property list."
8882 (let (key value)
8883 (while plist
8884 (setq key (pop plist) value (pop plist))
8885 (setq org-store-link-plist
8886 (plist-put org-store-link-plist key value)))))
8888 (defun org-email-link-description (&optional fmt)
8889 "Return the description part of an email link.
8890 This takes information from `org-store-link-plist' and formats it
8891 according to FMT (default from `org-email-link-description-format')."
8892 (setq fmt (or fmt org-email-link-description-format))
8893 (let* ((p org-store-link-plist)
8894 (to (plist-get p :toaddress))
8895 (from (plist-get p :fromaddress))
8896 (table
8897 (list
8898 (cons "%c" (plist-get p :fromto))
8899 (cons "%F" (plist-get p :from))
8900 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8901 (cons "%T" (plist-get p :to))
8902 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8903 (cons "%s" (plist-get p :subject))
8904 (cons "%d" (plist-get p :date))
8905 (cons "%m" (plist-get p :message-id)))))
8906 (when (string-match "%c" fmt)
8907 ;; Check if the user wrote this message
8908 (if (and org-from-is-user-regexp from to
8909 (save-match-data (string-match org-from-is-user-regexp from)))
8910 (setq fmt (replace-match "to %t" t t fmt))
8911 (setq fmt (replace-match "from %f" t t fmt))))
8912 (org-replace-escapes fmt table)))
8914 (defun org-make-org-heading-search-string (&optional string heading)
8915 "Make search string for STRING or current headline."
8916 (interactive)
8917 (let ((s (or string (org-get-heading)))
8918 (lines org-context-in-file-links))
8919 (unless (and string (not heading))
8920 ;; We are using a headline, clean up garbage in there.
8921 (if (string-match org-todo-regexp s)
8922 (setq s (replace-match "" t t s)))
8923 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8924 (setq s (replace-match "" t t s)))
8925 (setq s (org-trim s))
8926 (if (string-match (concat "^\\(" org-quote-string "\\|"
8927 org-comment-string "\\)") s)
8928 (setq s (replace-match "" t t s)))
8929 (while (string-match org-ts-regexp s)
8930 (setq s (replace-match "" t t s))))
8931 (or string (setq s (concat "*" s))) ; Add * for headlines
8932 (when (and string (integerp lines) (> lines 0))
8933 (let ((slines (org-split-string s "\n")))
8934 (when (< lines (length slines))
8935 (setq s (mapconcat
8936 'identity
8937 (reverse (nthcdr (- (length slines) lines)
8938 (reverse slines))) "\n")))))
8939 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8941 (defun org-make-link (&rest strings)
8942 "Concatenate STRINGS."
8943 (apply 'concat strings))
8945 (defun org-make-link-string (link &optional description)
8946 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8947 (unless (string-match "\\S-" link)
8948 (error "Empty link"))
8949 (when (and description
8950 (stringp description)
8951 (not (string-match "\\S-" description)))
8952 (setq description nil))
8953 (when (stringp description)
8954 ;; Remove brackets from the description, they are fatal.
8955 (while (string-match "\\[" description)
8956 (setq description (replace-match "{" t t description)))
8957 (while (string-match "\\]" description)
8958 (setq description (replace-match "}" t t description))))
8959 (when (equal link description)
8960 ;; No description needed, it is identical
8961 (setq description nil))
8962 (when (and (not description)
8963 (not (string-match (org-image-file-name-regexp) link))
8964 (not (equal link (org-link-escape link))))
8965 (setq description (org-extract-attributes link)))
8966 (setq link
8967 (cond ((string-match (org-image-file-name-regexp) link) link)
8968 ((string-match org-link-types-re link)
8969 (concat (match-string 1 link)
8970 (org-link-escape (substring link (match-end 1)))))
8971 (t (org-link-escape link))))
8972 (concat "[[" link "]"
8973 (if description (concat "[" description "]") "")
8974 "]"))
8976 (defconst org-link-escape-chars
8977 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8978 "List of characters that should be escaped in link.
8979 This is the list that is used for internal purposes.")
8981 (defvar org-url-encoding-use-url-hexify nil)
8983 (defconst org-link-escape-chars-browser
8984 '(?\ )
8985 "List of escapes for characters that are problematic in links.
8986 This is the list that is used before handing over to the browser.")
8988 (defun org-link-escape (text &optional table merge)
8989 "Return percent escaped representation of TEXT.
8990 TEXT is a string with the text to escape.
8991 Optional argument TABLE is a list with characters that should be
8992 escaped. When nil, `org-link-escape-chars' is used.
8993 If optional argument MERGE is set, merge TABLE into
8994 `org-link-escape-chars'."
8995 (if (and org-url-encoding-use-url-hexify (not table))
8996 (url-hexify-string text)
8997 (cond
8998 ((and table merge)
8999 (mapc (lambda (defchr)
9000 (unless (member defchr table)
9001 (setq table (cons defchr table)))) org-link-escape-chars))
9002 ((null table)
9003 (setq table org-link-escape-chars)))
9004 (mapconcat
9005 (lambda (char)
9006 (if (or (member char table)
9007 (< char 32) (= char 37) (> char 126))
9008 (mapconcat (lambda (sequence-element)
9009 (format "%%%.2X" sequence-element))
9010 (or (encode-coding-char char 'utf-8)
9011 (error "Unable to percent escape character: %s"
9012 (char-to-string char))) "")
9013 (char-to-string char))) text "")))
9015 (defun org-link-unescape (str)
9016 "Unhex hexified Unicode strings as returned from the JavaScript function
9017 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9018 (unless (and (null str) (string= "" str))
9019 (let ((pos 0) (case-fold-search t) unhexed)
9020 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9021 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9022 (setq str (replace-match unhexed t t str))
9023 (setq pos (+ pos (length unhexed))))))
9024 str)
9026 (defun org-link-unescape-compound (hex)
9027 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9028 Note: this function also decodes single byte encodings like
9029 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9030 (save-match-data
9031 (let* ((bytes (cdr (split-string hex "%")))
9032 (ret "")
9033 (eat 0)
9034 (sum 0))
9035 (while bytes
9036 (let* ((val (string-to-number (pop bytes) 16))
9037 (shift-xor
9038 (if (= 0 eat)
9039 (cond
9040 ((>= val 252) (cons 6 252))
9041 ((>= val 248) (cons 5 248))
9042 ((>= val 240) (cons 4 240))
9043 ((>= val 224) (cons 3 224))
9044 ((>= val 192) (cons 2 192))
9045 (t (cons 0 0)))
9046 (cons 6 128))))
9047 (if (>= val 192) (setq eat (car shift-xor)))
9048 (setq val (logxor val (cdr shift-xor)))
9049 (setq sum (+ (lsh sum (car shift-xor)) val))
9050 (if (> eat 0) (setq eat (- eat 1)))
9051 (cond
9052 ((= 0 eat) ;multi byte
9053 (setq ret (concat ret (org-char-to-string sum)))
9054 (setq sum 0))
9055 ((not bytes) ; single byte(s)
9056 (setq ret (org-link-unescape-single-byte-sequence hex))))
9057 )) ;; end (while bytes
9058 ret )))
9060 (defun org-link-unescape-single-byte-sequence (hex)
9061 "Unhexify hex-encoded single byte character sequences."
9062 (mapconcat (lambda (byte)
9063 (char-to-string (string-to-number byte 16)))
9064 (cdr (split-string hex "%")) ""))
9066 (defun org-xor (a b)
9067 "Exclusive or."
9068 (if a (not b) b))
9070 (defun org-fixup-message-id-for-http (s)
9071 "Replace special characters in a message id, so it can be used in an http query."
9072 (when (string-match "%" s)
9073 (setq s (mapconcat (lambda (c)
9074 (if (eq c ?%)
9075 "%25"
9076 (char-to-string c)))
9077 s "")))
9078 (while (string-match "<" s)
9079 (setq s (replace-match "%3C" t t s)))
9080 (while (string-match ">" s)
9081 (setq s (replace-match "%3E" t t s)))
9082 (while (string-match "@" s)
9083 (setq s (replace-match "%40" t t s)))
9086 ;;;###autoload
9087 (defun org-insert-link-global ()
9088 "Insert a link like Org-mode does.
9089 This command can be called in any mode to insert a link in Org-mode syntax."
9090 (interactive)
9091 (org-load-modules-maybe)
9092 (org-run-like-in-org-mode 'org-insert-link))
9094 (defun org-insert-link (&optional complete-file link-location default-description)
9095 "Insert a link. At the prompt, enter the link.
9097 Completion can be used to insert any of the link protocol prefixes like
9098 http or ftp in use.
9100 The history can be used to select a link previously stored with
9101 `org-store-link'. When the empty string is entered (i.e. if you just
9102 press RET at the prompt), the link defaults to the most recently
9103 stored link. As SPC triggers completion in the minibuffer, you need to
9104 use M-SPC or C-q SPC to force the insertion of a space character.
9106 You will also be prompted for a description, and if one is given, it will
9107 be displayed in the buffer instead of the link.
9109 If there is already a link at point, this command will allow you to edit link
9110 and description parts.
9112 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9113 be selected using completion. The path to the file will be relative to the
9114 current directory if the file is in the current directory or a subdirectory.
9115 Otherwise, the link will be the absolute path as completed in the minibuffer
9116 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9117 option `org-link-file-path-type'.
9119 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9120 the current directory or below.
9122 With three \\[universal-argument] prefixes, negate the meaning of
9123 `org-keep-stored-link-after-insertion'.
9125 If `org-make-link-description-function' is non-nil, this function will be
9126 called with the link target, and the result will be the default
9127 link description.
9129 If the LINK-LOCATION parameter is non-nil, this value will be
9130 used as the link location instead of reading one interactively.
9132 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9133 be used as the default description."
9134 (interactive "P")
9135 (let* ((wcf (current-window-configuration))
9136 (region (if (org-region-active-p)
9137 (buffer-substring (region-beginning) (region-end))))
9138 (remove (and region (list (region-beginning) (region-end))))
9139 (desc region)
9140 tmphist ; byte-compile incorrectly complains about this
9141 (link link-location)
9142 entry file all-prefixes)
9143 (cond
9144 (link-location) ; specified by arg, just use it.
9145 ((org-in-regexp org-bracket-link-regexp 1)
9146 ;; We do have a link at point, and we are going to edit it.
9147 (setq remove (list (match-beginning 0) (match-end 0)))
9148 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9149 (setq link (read-string "Link: "
9150 (org-link-unescape
9151 (org-match-string-no-properties 1)))))
9152 ((or (org-in-regexp org-angle-link-re)
9153 (org-in-regexp org-plain-link-re))
9154 ;; Convert to bracket link
9155 (setq remove (list (match-beginning 0) (match-end 0))
9156 link (read-string "Link: "
9157 (org-remove-angle-brackets (match-string 0)))))
9158 ((member complete-file '((4) (16)))
9159 ;; Completing read for file names.
9160 (setq link (org-file-complete-link complete-file)))
9162 ;; Read link, with completion for stored links.
9163 (with-output-to-temp-buffer "*Org Links*"
9164 (princ "Insert a link.
9165 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9166 (when org-stored-links
9167 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9168 (princ (mapconcat
9169 (lambda (x)
9170 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9171 (reverse org-stored-links) "\n"))))
9172 (let ((cw (selected-window)))
9173 (select-window (get-buffer-window "*Org Links*" 'visible))
9174 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9175 (unless (pos-visible-in-window-p (point-max))
9176 (org-fit-window-to-buffer))
9177 (and (window-live-p cw) (select-window cw)))
9178 ;; Fake a link history, containing the stored links.
9179 (setq tmphist (append (mapcar 'car org-stored-links)
9180 org-insert-link-history))
9181 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9182 (mapcar 'car org-link-abbrev-alist)
9183 org-link-types))
9184 (unwind-protect
9185 (progn
9186 (setq link
9187 (let ((org-completion-use-ido nil)
9188 (org-completion-use-iswitchb nil))
9189 (org-completing-read
9190 "Link: "
9191 (append
9192 (mapcar (lambda (x) (list (concat x ":")))
9193 all-prefixes)
9194 (mapcar 'car org-stored-links))
9195 nil nil nil
9196 'tmphist
9197 (car (car org-stored-links)))))
9198 (if (not (string-match "\\S-" link))
9199 (error "No link selected"))
9200 (if (or (member link all-prefixes)
9201 (and (equal ":" (substring link -1))
9202 (member (substring link 0 -1) all-prefixes)
9203 (setq link (substring link 0 -1))))
9204 (setq link (org-link-try-special-completion link))))
9205 (set-window-configuration wcf)
9206 (kill-buffer "*Org Links*"))
9207 (setq entry (assoc link org-stored-links))
9208 (or entry (push link org-insert-link-history))
9209 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9210 (not org-keep-stored-link-after-insertion))
9211 (setq org-stored-links (delq (assoc link org-stored-links)
9212 org-stored-links)))
9213 (setq desc (or desc (nth 1 entry)))))
9215 (if (string-match org-plain-link-re link)
9216 ;; URL-like link, normalize the use of angular brackets.
9217 (setq link (org-make-link (org-remove-angle-brackets link))))
9219 ;; Check if we are linking to the current file with a search option
9220 ;; If yes, simplify the link by using only the search option.
9221 (when (and buffer-file-name
9222 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9223 (let* ((path (match-string 1 link))
9224 (case-fold-search nil)
9225 (search (match-string 2 link)))
9226 (save-match-data
9227 (if (equal (file-truename buffer-file-name) (file-truename path))
9228 ;; We are linking to this same file, with a search option
9229 (setq link search)))))
9231 ;; Check if we can/should use a relative path. If yes, simplify the link
9232 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9233 (let* ((type (match-string 1 link))
9234 (path (match-string 2 link))
9235 (origpath path)
9236 (case-fold-search nil))
9237 (cond
9238 ((or (eq org-link-file-path-type 'absolute)
9239 (equal complete-file '(16)))
9240 (setq path (abbreviate-file-name (expand-file-name path))))
9241 ((eq org-link-file-path-type 'noabbrev)
9242 (setq path (expand-file-name path)))
9243 ((eq org-link-file-path-type 'relative)
9244 (setq path (file-relative-name path)))
9246 (save-match-data
9247 (if (string-match (concat "^" (regexp-quote
9248 (expand-file-name
9249 (file-name-as-directory
9250 default-directory))))
9251 (expand-file-name path))
9252 ;; We are linking a file with relative path name.
9253 (setq path (substring (expand-file-name path)
9254 (match-end 0)))
9255 (setq path (abbreviate-file-name (expand-file-name path)))))))
9256 (setq link (concat type path))
9257 (if (equal desc origpath)
9258 (setq desc path))))
9260 (if org-make-link-description-function
9261 (setq desc (funcall org-make-link-description-function link desc))
9262 (if default-description (setq desc default-description)))
9264 (setq desc (read-string "Description: " desc))
9265 (unless (string-match "\\S-" desc) (setq desc nil))
9266 (if remove (apply 'delete-region remove))
9267 (insert (org-make-link-string link desc))))
9269 (defun org-link-try-special-completion (type)
9270 "If there is completion support for link type TYPE, offer it."
9271 (let ((fun (intern (concat "org-" type "-complete-link"))))
9272 (if (functionp fun)
9273 (funcall fun)
9274 (read-string "Link (no completion support): " (concat type ":")))))
9276 (defun org-file-complete-link (&optional arg)
9277 "Create a file link using completion."
9278 (let (file link)
9279 (setq file (read-file-name "File: "))
9280 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9281 (pwd1 (file-name-as-directory (abbreviate-file-name
9282 (expand-file-name ".")))))
9283 (cond
9284 ((equal arg '(16))
9285 (setq link (org-make-link
9286 "file:"
9287 (abbreviate-file-name (expand-file-name file)))))
9288 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9289 (setq link (org-make-link "file:" (match-string 1 file))))
9290 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9291 (expand-file-name file))
9292 (setq link (org-make-link
9293 "file:" (match-string 1 (expand-file-name file)))))
9294 (t (setq link (org-make-link "file:" file)))))
9295 link))
9297 (defun org-completing-read (&rest args)
9298 "Completing-read with SPACE being a normal character."
9299 (let ((enable-recursive-minibuffers t)
9300 (minibuffer-local-completion-map
9301 (copy-keymap minibuffer-local-completion-map)))
9302 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9303 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9304 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9305 (apply 'org-icompleting-read args)))
9307 (defun org-completing-read-no-i (&rest args)
9308 (let (org-completion-use-ido org-completion-use-iswitchb)
9309 (apply 'org-completing-read args)))
9311 (defun org-iswitchb-completing-read (prompt choices &rest args)
9312 "Use iswitch as a completing-read replacement to choose from choices.
9313 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9314 from."
9315 (let* ((iswitchb-use-virtual-buffers nil)
9316 (iswitchb-make-buflist-hook
9317 (lambda ()
9318 (setq iswitchb-temp-buflist choices))))
9319 (iswitchb-read-buffer prompt)))
9321 (defun org-icompleting-read (&rest args)
9322 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9323 (org-without-partial-completion
9324 (if (and org-completion-use-ido
9325 (fboundp 'ido-completing-read)
9326 (boundp 'ido-mode) ido-mode
9327 (listp (second args)))
9328 (let ((ido-enter-matching-directory nil))
9329 (apply 'ido-completing-read (concat (car args))
9330 (if (consp (car (nth 1 args)))
9331 (mapcar 'car (nth 1 args))
9332 (nth 1 args))
9333 (cddr args)))
9334 (if (and org-completion-use-iswitchb
9335 (boundp 'iswitchb-mode) iswitchb-mode
9336 (listp (second args)))
9337 (apply 'org-iswitchb-completing-read (concat (car args))
9338 (if (consp (car (nth 1 args)))
9339 (mapcar 'car (nth 1 args))
9340 (nth 1 args))
9341 (cddr args))
9342 (apply 'completing-read args)))))
9344 (defun org-extract-attributes (s)
9345 "Extract the attributes cookie from a string and set as text property."
9346 (let (a attr (start 0) key value)
9347 (save-match-data
9348 (when (string-match "{{\\([^}]+\\)}}$" s)
9349 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9350 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9351 (setq key (match-string 1 a) value (match-string 2 a)
9352 start (match-end 0)
9353 attr (plist-put attr (intern key) value))))
9354 (org-add-props s nil 'org-attr attr))
9357 (defun org-extract-attributes-from-string (tag)
9358 (let (key value attr)
9359 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9360 (setq key (match-string 1 tag) value (match-string 2 tag)
9361 tag (replace-match "" t t tag)
9362 attr (plist-put attr (intern key) value)))
9363 (cons tag attr)))
9365 (defun org-attributes-to-string (plist)
9366 "Format a property list into an HTML attribute list."
9367 (let ((s "") key value)
9368 (while plist
9369 (setq key (pop plist) value (pop plist))
9370 (and value
9371 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9374 ;;; Opening/following a link
9376 (defvar org-link-search-failed nil)
9378 (defvar org-open-link-functions nil
9379 "Hook for functions finding a plain text link.
9380 These functions must take a single argument, the link content.
9381 They will be called for links that look like [[link text][description]]
9382 when LINK TEXT does not have a protocol like \"http:\" and does not look
9383 like a filename (e.g. \"./blue.png\").
9385 These functions will be called *before* Org attempts to resolve the
9386 link by doing text searches in the current buffer - so if you want a
9387 link \"[[target]]\" to still find \"<<target>>\", your function should
9388 handle this as a special case.
9390 When the function does handle the link, it must return a non-nil value.
9391 If it decides that it is not responsible for this link, it must return
9392 nil to indicate that that Org-mode can continue with other options
9393 like exact and fuzzy text search.")
9395 (defun org-next-link ()
9396 "Move forward to the next link.
9397 If the link is in hidden text, expose it."
9398 (interactive)
9399 (when (and org-link-search-failed (eq this-command last-command))
9400 (goto-char (point-min))
9401 (message "Link search wrapped back to beginning of buffer"))
9402 (setq org-link-search-failed nil)
9403 (let* ((pos (point))
9404 (ct (org-context))
9405 (a (assoc :link ct)))
9406 (if a (goto-char (nth 2 a)))
9407 (if (re-search-forward org-any-link-re nil t)
9408 (progn
9409 (goto-char (match-beginning 0))
9410 (if (outline-invisible-p) (org-show-context)))
9411 (goto-char pos)
9412 (setq org-link-search-failed t)
9413 (error "No further link found"))))
9415 (defun org-previous-link ()
9416 "Move backward to the previous link.
9417 If the link is in hidden text, expose it."
9418 (interactive)
9419 (when (and org-link-search-failed (eq this-command last-command))
9420 (goto-char (point-max))
9421 (message "Link search wrapped back to end of buffer"))
9422 (setq org-link-search-failed nil)
9423 (let* ((pos (point))
9424 (ct (org-context))
9425 (a (assoc :link ct)))
9426 (if a (goto-char (nth 1 a)))
9427 (if (re-search-backward org-any-link-re nil t)
9428 (progn
9429 (goto-char (match-beginning 0))
9430 (if (outline-invisible-p) (org-show-context)))
9431 (goto-char pos)
9432 (setq org-link-search-failed t)
9433 (error "No further link found"))))
9435 (defun org-translate-link (s)
9436 "Translate a link string if a translation function has been defined."
9437 (if (and org-link-translation-function
9438 (fboundp org-link-translation-function)
9439 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9440 (progn
9441 (setq s (funcall org-link-translation-function
9442 (match-string 1) (match-string 2)))
9443 (concat (car s) ":" (cdr s)))
9446 (defun org-translate-link-from-planner (type path)
9447 "Translate a link from Emacs Planner syntax so that Org can follow it.
9448 This is still an experimental function, your mileage may vary."
9449 (cond
9450 ((member type '("http" "https" "news" "ftp"))
9451 ;; standard Internet links are the same.
9452 nil)
9453 ((and (equal type "irc") (string-match "^//" path))
9454 ;; Planner has two / at the beginning of an irc link, we have 1.
9455 ;; We should have zero, actually....
9456 (setq path (substring path 1)))
9457 ((and (equal type "lisp") (string-match "^/" path))
9458 ;; Planner has a slash, we do not.
9459 (setq type "elisp" path (substring path 1)))
9460 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9461 ;; A typical message link. Planner has the id after the final slash,
9462 ;; we separate it with a hash mark
9463 (setq path (concat (match-string 1 path) "#"
9464 (org-remove-angle-brackets (match-string 2 path)))))
9466 (cons type path))
9468 (defun org-find-file-at-mouse (ev)
9469 "Open file link or URL at mouse."
9470 (interactive "e")
9471 (mouse-set-point ev)
9472 (org-open-at-point 'in-emacs))
9474 (defun org-open-at-mouse (ev)
9475 "Open file link or URL at mouse.
9476 See the docstring of `org-open-file' for details."
9477 (interactive "e")
9478 (mouse-set-point ev)
9479 (if (eq major-mode 'org-agenda-mode)
9480 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9481 (org-open-at-point))
9483 (defvar org-window-config-before-follow-link nil
9484 "The window configuration before following a link.
9485 This is saved in case the need arises to restore it.")
9487 (defvar org-open-link-marker (make-marker)
9488 "Marker pointing to the location where `org-open-at-point; was called.")
9490 ;;;###autoload
9491 (defun org-open-at-point-global ()
9492 "Follow a link like Org-mode does.
9493 This command can be called in any mode to follow a link that has
9494 Org-mode syntax."
9495 (interactive)
9496 (org-run-like-in-org-mode 'org-open-at-point))
9498 ;;;###autoload
9499 (defun org-open-link-from-string (s &optional arg reference-buffer)
9500 "Open a link in the string S, as if it was in Org-mode."
9501 (interactive "sLink: \nP")
9502 (let ((reference-buffer (or reference-buffer (current-buffer))))
9503 (with-temp-buffer
9504 (let ((org-inhibit-startup (not reference-buffer)))
9505 (org-mode)
9506 (insert s)
9507 (goto-char (point-min))
9508 (when reference-buffer
9509 (setq org-link-abbrev-alist-local
9510 (with-current-buffer reference-buffer
9511 org-link-abbrev-alist-local)))
9512 (org-open-at-point arg reference-buffer)))))
9514 (defvar org-open-at-point-functions nil
9515 "Hook that is run when following a link at point.
9517 Functions in this hook must return t if they identify and follow
9518 a link at point. If they don't find anything interesting at point,
9519 they must return nil.")
9521 (defun org-open-at-point (&optional arg reference-buffer)
9522 "Open link at or after point.
9523 If there is no link at point, this function will search forward up to
9524 the end of the current line.
9525 Normally, files will be opened by an appropriate application. If the
9526 optional prefix argument ARG is non-nil, Emacs will visit the file.
9527 With a double prefix argument, try to open outside of Emacs, in the
9528 application the system uses for this file type."
9529 (interactive "P")
9530 ;; if in a code block, then open the block's results
9531 (unless (call-interactively #'org-babel-open-src-block-result)
9532 (org-load-modules-maybe)
9533 (move-marker org-open-link-marker (point))
9534 (setq org-window-config-before-follow-link (current-window-configuration))
9535 (org-remove-occur-highlights nil nil t)
9536 (cond
9537 ((and (org-at-heading-p)
9538 (not (org-in-regexp
9539 (concat org-plain-link-re "\\|"
9540 org-bracket-link-regexp "\\|"
9541 org-angle-link-re "\\|"
9542 "[ \t]:[^ \t\n]+:[ \t]*$")))
9543 (not (get-text-property (point) 'org-linked-text)))
9544 (or (org-offer-links-in-entry arg)
9545 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9546 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9547 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9548 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9549 (not (org-in-regexp org-bracket-link-regexp)))
9550 (org-footnote-action))
9552 (let (type path link line search (pos (point)))
9553 (catch 'match
9554 (save-excursion
9555 (skip-chars-forward "^]\n\r")
9556 (when (org-in-regexp org-bracket-link-regexp 1)
9557 (setq link (org-extract-attributes
9558 (org-link-unescape (org-match-string-no-properties 1))))
9559 (while (string-match " *\n *" link)
9560 (setq link (replace-match " " t t link)))
9561 (setq link (org-link-expand-abbrev link))
9562 (cond
9563 ((or (file-name-absolute-p link)
9564 (string-match "^\\.\\.?/" link))
9565 (setq type "file" path link))
9566 ((string-match org-link-re-with-space3 link)
9567 (setq type (match-string 1 link) path (match-string 2 link)))
9568 (t (setq type "thisfile" path link)))
9569 (throw 'match t)))
9571 (when (get-text-property (point) 'org-linked-text)
9572 (setq type "thisfile"
9573 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9574 (1+ (point)) (point))
9575 path (buffer-substring
9576 (or (previous-single-property-change pos 'org-linked-text)
9577 (point-min))
9578 (or (next-single-property-change pos 'org-linked-text)
9579 (point-max))))
9580 (throw 'match t))
9582 (save-excursion
9583 (when (or (org-in-regexp org-angle-link-re)
9584 (org-in-regexp org-plain-link-re))
9585 (setq type (match-string 1)
9586 path (org-link-unescape (match-string 2)))
9587 (throw 'match t)))
9588 (save-excursion
9589 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9590 (setq type "tags"
9591 path (match-string 1))
9592 (while (string-match ":" path)
9593 (setq path (replace-match "+" t t path)))
9594 (throw 'match t)))
9595 (when (org-in-regexp "<\\([^><\n]+\\)>")
9596 (setq type "tree-match"
9597 path (match-string 1))
9598 (throw 'match t)))
9599 (unless path
9600 (error "No link found"))
9602 ;; switch back to reference buffer
9603 ;; needed when if called in a temporary buffer through
9604 ;; org-open-link-from-string
9605 (with-current-buffer (or reference-buffer (current-buffer))
9607 ;; Remove any trailing spaces in path
9608 (if (string-match " +\\'" path)
9609 (setq path (replace-match "" t t path)))
9610 (if (and org-link-translation-function
9611 (fboundp org-link-translation-function))
9612 ;; Check if we need to translate the link
9613 (let ((tmp (funcall org-link-translation-function type path)))
9614 (setq type (car tmp) path (cdr tmp))))
9616 (cond
9618 ((assoc type org-link-protocols)
9619 (funcall (nth 1 (assoc type org-link-protocols)) path))
9621 ((equal type "mailto")
9622 (let ((cmd (car org-link-mailto-program))
9623 (args (cdr org-link-mailto-program)) args1
9624 (address path) (subject "") a)
9625 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9626 (setq address (match-string 1 path)
9627 subject (org-link-escape (match-string 2 path))))
9628 (while args
9629 (cond
9630 ((not (stringp (car args))) (push (pop args) args1))
9631 (t (setq a (pop args))
9632 (if (string-match "%a" a)
9633 (setq a (replace-match address t t a)))
9634 (if (string-match "%s" a)
9635 (setq a (replace-match subject t t a)))
9636 (push a args1))))
9637 (apply cmd (nreverse args1))))
9639 ((member type '("http" "https" "ftp" "news"))
9640 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9641 (org-link-escape
9642 path org-link-escape-chars-browser)
9643 path))))
9645 ((string= type "doi")
9646 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9647 (org-link-escape
9648 path org-link-escape-chars-browser)
9649 path))))
9651 ((member type '("message"))
9652 (browse-url (concat type ":" path)))
9654 ((string= type "tags")
9655 (org-tags-view arg path))
9657 ((string= type "tree-match")
9658 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9660 ((string= type "file")
9661 (if (string-match "::\\([0-9]+\\)\\'" path)
9662 (setq line (string-to-number (match-string 1 path))
9663 path (substring path 0 (match-beginning 0)))
9664 (if (string-match "::\\(.+\\)\\'" path)
9665 (setq search (match-string 1 path)
9666 path (substring path 0 (match-beginning 0)))))
9667 (if (string-match "[*?{]" (file-name-nondirectory path))
9668 (dired path)
9669 (org-open-file path arg line search)))
9671 ((string= type "shell")
9672 (let ((cmd path))
9673 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9674 (string-match org-confirm-shell-link-not-regexp cmd))
9675 (not org-confirm-shell-link-function)
9676 (funcall org-confirm-shell-link-function
9677 (format "Execute \"%s\" in shell? "
9678 (org-add-props cmd nil
9679 'face 'org-warning))))
9680 (progn
9681 (message "Executing %s" cmd)
9682 (shell-command cmd))
9683 (error "Abort"))))
9685 ((string= type "elisp")
9686 (let ((cmd path))
9687 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9688 (string-match org-confirm-elisp-link-not-regexp cmd))
9689 (not org-confirm-elisp-link-function)
9690 (funcall org-confirm-elisp-link-function
9691 (format "Execute \"%s\" as elisp? "
9692 (org-add-props cmd nil
9693 'face 'org-warning))))
9694 (message "%s => %s" cmd
9695 (if (equal (string-to-char cmd) ?\()
9696 (eval (read cmd))
9697 (call-interactively (read cmd))))
9698 (error "Abort"))))
9700 ((and (string= type "thisfile")
9701 (run-hook-with-args-until-success
9702 'org-open-link-functions path)))
9704 ((string= type "thisfile")
9705 (if arg
9706 (switch-to-buffer-other-window
9707 (org-get-buffer-for-internal-link (current-buffer)))
9708 (org-mark-ring-push))
9709 (let ((cmd `(org-link-search
9710 ,path
9711 ,(cond ((equal arg '(4)) ''occur)
9712 ((equal arg '(16)) ''org-occur)
9713 (t nil))
9714 ,pos)))
9715 (condition-case nil (let ((org-link-search-inhibit-query t))
9716 (eval cmd))
9717 (error (progn (widen) (eval cmd))))))
9720 (browse-url-at-point)))))))
9721 (move-marker org-open-link-marker nil)
9722 (run-hook-with-args 'org-follow-link-hook)))
9724 (defun org-offer-links-in-entry (&optional nth zero)
9725 "Offer links in the current entry and follow the selected link.
9726 If there is only one link, follow it immediately as well.
9727 If NTH is an integer, immediately pick the NTH link found.
9728 If ZERO is a string, check also this string for a link, and if
9729 there is one, offer it as link number zero."
9730 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9731 "\\(" org-angle-link-re "\\)\\|"
9732 "\\(" org-plain-link-re "\\)"))
9733 (cnt ?0)
9734 (in-emacs (if (integerp nth) nil nth))
9735 have-zero end links link c)
9736 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9737 (push (match-string 0 zero) links)
9738 (setq cnt (1- cnt) have-zero t))
9739 (save-excursion
9740 (org-back-to-heading t)
9741 (setq end (save-excursion (outline-next-heading) (point)))
9742 (while (re-search-forward re end t)
9743 (push (match-string 0) links))
9744 (setq links (org-uniquify (reverse links))))
9746 (cond
9747 ((null links)
9748 (message "No links"))
9749 ((equal (length links) 1)
9750 (setq link (list (car links))))
9751 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9752 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9753 (t ; we have to select a link
9754 (save-excursion
9755 (save-window-excursion
9756 (delete-other-windows)
9757 (with-output-to-temp-buffer "*Select Link*"
9758 (mapc (lambda (l)
9759 (if (not (string-match org-bracket-link-regexp l))
9760 (princ (format "[%c] %s\n" (incf cnt)
9761 (org-remove-angle-brackets l)))
9762 (if (match-end 3)
9763 (princ (format "[%c] %s (%s)\n" (incf cnt)
9764 (match-string 3 l) (match-string 1 l)))
9765 (princ (format "[%c] %s\n" (incf cnt)
9766 (match-string 1 l))))))
9767 links))
9768 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9769 (message "Select link to open, RET to open all:")
9770 (setq c (read-char-exclusive))
9771 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9772 (when (equal c ?q) (error "Abort"))
9773 (if (equal c ?\C-m)
9774 (setq link links)
9775 (setq nth (- c ?0))
9776 (if have-zero (setq nth (1+ nth)))
9777 (unless (and (integerp nth) (>= (length links) nth))
9778 (error "Invalid link selection"))
9779 (setq link (list (nth (1- nth) links))))))
9780 (if link
9781 (let ((buf (current-buffer)))
9782 (dolist (l link)
9783 (org-open-link-from-string l in-emacs buf))
9785 nil)))
9787 ;; Add special file links that specify the way of opening
9789 (org-add-link-type "file+sys" 'org-open-file-with-system)
9790 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9791 (defun org-open-file-with-system (path)
9792 "Open file at PATH using the system way of opening it."
9793 (org-open-file path 'system))
9794 (defun org-open-file-with-emacs (path)
9795 "Open file at PATH in Emacs."
9796 (org-open-file path 'emacs))
9797 (defun org-remove-file-link-modifiers ()
9798 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9799 (goto-char (point-min))
9800 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9801 (org-if-unprotected
9802 (replace-match "file:" t t))))
9803 (eval-after-load "org-exp"
9804 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9805 'org-remove-file-link-modifiers))
9807 ;;;; Time estimates
9809 (defun org-get-effort (&optional pom)
9810 "Get the effort estimate for the current entry."
9811 (org-entry-get pom org-effort-property))
9813 ;;; File search
9815 (defvar org-create-file-search-functions nil
9816 "List of functions to construct the right search string for a file link.
9817 These functions are called in turn with point at the location to
9818 which the link should point.
9820 A function in the hook should first test if it would like to
9821 handle this file type, for example by checking the `major-mode'
9822 or the file extension. If it decides not to handle this file, it
9823 should just return nil to give other functions a chance. If it
9824 does handle the file, it must return the search string to be used
9825 when following the link. The search string will be part of the
9826 file link, given after a double colon, and `org-open-at-point'
9827 will automatically search for it. If special measures must be
9828 taken to make the search successful, another function should be
9829 added to the companion hook `org-execute-file-search-functions',
9830 which see.
9832 A function in this hook may also use `setq' to set the variable
9833 `description' to provide a suggestion for the descriptive text to
9834 be used for this link when it gets inserted into an Org-mode
9835 buffer with \\[org-insert-link].")
9837 (defvar org-execute-file-search-functions nil
9838 "List of functions to execute a file search triggered by a link.
9840 Functions added to this hook must accept a single argument, the
9841 search string that was part of the file link, the part after the
9842 double colon. The function must first check if it would like to
9843 handle this search, for example by checking the `major-mode' or
9844 the file extension. If it decides not to handle this search, it
9845 should just return nil to give other functions a chance. If it
9846 does handle the search, it must return a non-nil value to keep
9847 other functions from trying.
9849 Each function can access the current prefix argument through the
9850 variable `current-prefix-argument'. Note that a single prefix is
9851 used to force opening a link in Emacs, so it may be good to only
9852 use a numeric or double prefix to guide the search function.
9854 In case this is needed, a function in this hook can also restore
9855 the window configuration before `org-open-at-point' was called using:
9857 (set-window-configuration org-window-config-before-follow-link)")
9859 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9860 (defun org-link-search (s &optional type avoid-pos stealth)
9861 "Search for a link search option.
9862 If S is surrounded by forward slashes, it is interpreted as a
9863 regular expression. In org-mode files, this will create an `org-occur'
9864 sparse tree. In ordinary files, `occur' will be used to list matches.
9865 If the current buffer is in `dired-mode', grep will be used to search
9866 in all files. If AVOID-POS is given, ignore matches near that position.
9868 When optional argument STEALTH is non-nil, do not modify
9869 visibility around point, thus ignoring
9870 `org-show-hierarchy-above', `org-show-following-heading' and
9871 `org-show-siblings' variables."
9872 (let ((case-fold-search t)
9873 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9874 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9875 (append '(("") (" ") ("\t") ("\n"))
9876 org-emphasis-alist)
9877 "\\|") "\\)"))
9878 (pos (point))
9879 (pre nil) (post nil)
9880 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9881 (cond
9882 ;; First check if there are any special search functions
9883 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9884 ;; Now try the builtin stuff
9885 ((and (equal (string-to-char s0) ?#)
9886 (> (length s0) 1)
9887 (save-excursion
9888 (goto-char (point-min))
9889 (and
9890 (re-search-forward
9891 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9892 (setq type 'dedicated
9893 pos (match-beginning 0))))
9894 ;; There is an exact target for this
9895 (goto-char pos)
9896 (org-back-to-heading t)))
9897 ((save-excursion
9898 (goto-char (point-min))
9899 (and
9900 (re-search-forward
9901 (concat "<<" (regexp-quote s0) ">>") nil t)
9902 (setq type 'dedicated
9903 pos (match-beginning 0))))
9904 ;; There is an exact target for this
9905 (goto-char pos))
9906 ((save-excursion
9907 (goto-char (point-min))
9908 (and
9909 (re-search-forward
9910 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9911 (setq type 'dedicated pos (match-beginning 0))))
9912 ;; Found an invisible target.
9913 (goto-char pos))
9914 ((save-excursion
9915 (goto-char (point-min))
9916 (and
9917 (re-search-forward
9918 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9919 (setq type 'dedicated pos (match-beginning 0))))
9920 ;; Found an element with a matching #+name affiliated keyword.
9921 (goto-char pos))
9922 ((and (string-match "^(\\(.*\\))$" s0)
9923 (save-excursion
9924 (goto-char (point-min))
9925 (and
9926 (re-search-forward
9927 (concat "[^[]" (regexp-quote
9928 (format org-coderef-label-format
9929 (match-string 1 s0))))
9930 nil t)
9931 (setq type 'dedicated
9932 pos (1+ (match-beginning 0))))))
9933 ;; There is a coderef target for this
9934 (goto-char pos))
9935 ((string-match "^/\\(.*\\)/$" s)
9936 ;; A regular expression
9937 (cond
9938 ((eq major-mode 'org-mode)
9939 (org-occur (match-string 1 s)))
9940 ;;((eq major-mode 'dired-mode)
9941 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9942 (t (org-do-occur (match-string 1 s)))))
9943 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9944 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9945 (goto-char (point-min))
9946 (cond
9947 ((let (case-fold-search)
9948 (re-search-forward (format org-complex-heading-regexp-format
9949 (regexp-quote s))
9950 nil t))
9951 ;; OK, found a match
9952 (setq type 'dedicated)
9953 (goto-char (match-beginning 0)))
9954 ((and (not org-link-search-inhibit-query)
9955 (eq org-link-search-must-match-exact-headline 'query-to-create)
9956 (y-or-n-p "No match - create this as a new heading? "))
9957 (goto-char (point-max))
9958 (or (bolp) (newline))
9959 (insert "* " s "\n")
9960 (beginning-of-line 0))
9962 (goto-char pos)
9963 (error "No match"))))
9965 ;; A normal search string
9966 (when (equal (string-to-char s) ?*)
9967 ;; Anchor on headlines, post may include tags.
9968 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9969 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9970 s (substring s 1)))
9971 (remove-text-properties
9972 0 (length s)
9973 '(face nil mouse-face nil keymap nil fontified nil) s)
9974 ;; Make a series of regular expressions to find a match
9975 (setq words (org-split-string s "[ \n\r\t]+")
9977 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9978 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9979 "\\)" markers)
9980 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9981 re2a (concat "[ \t\r\n]" re2a_)
9982 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9983 re4 (concat "[^a-zA-Z_]" re4_)
9985 re1 (concat pre re2 post)
9986 re3 (concat pre (if pre re4_ re4) post)
9987 re5 (concat pre ".*" re4)
9988 re2 (concat pre re2)
9989 re2a (concat pre (if pre re2a_ re2a))
9990 re4 (concat pre (if pre re4_ re4))
9991 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9992 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9993 re5 "\\)"
9995 (cond
9996 ((eq type 'org-occur) (org-occur reall))
9997 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9998 (t (goto-char (point-min))
9999 (setq type 'fuzzy)
10000 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10001 (org-search-not-self 1 re1 nil t)
10002 (org-search-not-self 1 re2 nil t)
10003 (org-search-not-self 1 re2a nil t)
10004 (org-search-not-self 1 re3 nil t)
10005 (org-search-not-self 1 re4 nil t)
10006 (org-search-not-self 1 re5 nil t)
10008 (goto-char (match-beginning 1))
10009 (goto-char pos)
10010 (error "No match"))))))
10011 (and (eq major-mode 'org-mode)
10012 (not stealth)
10013 (org-show-context 'link-search))
10014 type))
10016 (defun org-search-not-self (group &rest args)
10017 "Execute `re-search-forward', but only accept matches that do not
10018 enclose the position of `org-open-link-marker'."
10019 (let ((m org-open-link-marker))
10020 (catch 'exit
10021 (while (apply 're-search-forward args)
10022 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10023 (goto-char (match-end group))
10024 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10025 (> (match-beginning 0) (marker-position m))
10026 (< (match-end 0) (marker-position m)))
10027 (save-match-data
10028 (or (not (org-in-regexp
10029 org-bracket-link-analytic-regexp 1))
10030 (not (match-end 4)) ; no description
10031 (and (<= (match-beginning 4) (point))
10032 (>= (match-end 4) (point))))))
10033 (throw 'exit (point))))))))
10035 (defun org-get-buffer-for-internal-link (buffer)
10036 "Return a buffer to be used for displaying the link target of internal links."
10037 (cond
10038 ((not org-display-internal-link-with-indirect-buffer)
10039 buffer)
10040 ((string-match "(Clone)$" (buffer-name buffer))
10041 (message "Buffer is already a clone, not making another one")
10042 ;; we also do not modify visibility in this case
10043 buffer)
10044 (t ; make a new indirect buffer for displaying the link
10045 (let* ((bn (buffer-name buffer))
10046 (ibn (concat bn "(Clone)"))
10047 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10048 (with-current-buffer ib (org-overview))
10049 ib))))
10051 (defun org-do-occur (regexp &optional cleanup)
10052 "Call the Emacs command `occur'.
10053 If CLEANUP is non-nil, remove the printout of the regular expression
10054 in the *Occur* buffer. This is useful if the regex is long and not useful
10055 to read."
10056 (occur regexp)
10057 (when cleanup
10058 (let ((cwin (selected-window)) win beg end)
10059 (when (setq win (get-buffer-window "*Occur*"))
10060 (select-window win))
10061 (goto-char (point-min))
10062 (when (re-search-forward "match[a-z]+" nil t)
10063 (setq beg (match-end 0))
10064 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10065 (setq end (1- (match-beginning 0)))))
10066 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10067 (goto-char (point-min))
10068 (select-window cwin))))
10070 ;;; The mark ring for links jumps
10072 (defvar org-mark-ring nil
10073 "Mark ring for positions before jumps in Org-mode.")
10074 (defvar org-mark-ring-last-goto nil
10075 "Last position in the mark ring used to go back.")
10076 ;; Fill and close the ring
10077 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10078 (loop for i from 1 to org-mark-ring-length do
10079 (push (make-marker) org-mark-ring))
10080 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10081 org-mark-ring)
10083 (defun org-mark-ring-push (&optional pos buffer)
10084 "Put the current position or POS into the mark ring and rotate it."
10085 (interactive)
10086 (setq pos (or pos (point)))
10087 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10088 (move-marker (car org-mark-ring)
10089 (or pos (point))
10090 (or buffer (current-buffer)))
10091 (message "%s"
10092 (substitute-command-keys
10093 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10095 (defun org-mark-ring-goto (&optional n)
10096 "Jump to the previous position in the mark ring.
10097 With prefix arg N, jump back that many stored positions. When
10098 called several times in succession, walk through the entire ring.
10099 Org-mode commands jumping to a different position in the current file,
10100 or to another Org-mode file, automatically push the old position
10101 onto the ring."
10102 (interactive "p")
10103 (let (p m)
10104 (if (eq last-command this-command)
10105 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10106 (setq p org-mark-ring))
10107 (setq org-mark-ring-last-goto p)
10108 (setq m (car p))
10109 (org-pop-to-buffer-same-window (marker-buffer m))
10110 (goto-char m)
10111 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10113 (defun org-remove-angle-brackets (s)
10114 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10115 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10117 (defun org-add-angle-brackets (s)
10118 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10119 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10121 (defun org-remove-double-quotes (s)
10122 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10123 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10126 ;;; Following specific links
10128 (defun org-follow-timestamp-link ()
10129 (cond
10130 ((org-at-date-range-p t)
10131 (let ((org-agenda-start-on-weekday)
10132 (t1 (match-string 1))
10133 (t2 (match-string 2)))
10134 (setq t1 (time-to-days (org-time-string-to-time t1))
10135 t2 (time-to-days (org-time-string-to-time t2)))
10136 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10137 ((org-at-timestamp-p t)
10138 (org-agenda-list nil (time-to-days (org-time-string-to-time
10139 (substring (match-string 1) 0 10)))
10141 (t (error "This should not happen"))))
10144 ;;; Following file links
10145 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10146 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10147 (declare-function mailcap-mime-info
10148 "mailcap" (string &optional request no-decode))
10149 (defvar org-wait nil)
10150 (defun org-open-file (path &optional in-emacs line search)
10151 "Open the file at PATH.
10152 First, this expands any special file name abbreviations. Then the
10153 configuration variable `org-file-apps' is checked if it contains an
10154 entry for this file type, and if yes, the corresponding command is launched.
10156 If no application is found, Emacs simply visits the file.
10158 With optional prefix argument IN-EMACS, Emacs will visit the file.
10159 With a double \\[universal-argument] \\[universal-argument] \
10160 prefix arg, Org tries to avoid opening in Emacs
10161 and to use an external application to visit the file.
10163 Optional LINE specifies a line to go to, optional SEARCH a string
10164 to search for. If LINE or SEARCH is given, the file will be
10165 opened in Emacs, unless an entry from org-file-apps that makes
10166 use of groups in a regexp matches.
10168 If you want to change the way frames are used when following a
10169 link, please customize `org-link-frame-setup'.
10171 If the file does not exist, an error is thrown."
10172 (let* ((file (if (equal path "")
10173 buffer-file-name
10174 (substitute-in-file-name (expand-file-name path))))
10175 (file-apps (append org-file-apps (org-default-apps)))
10176 (apps (org-remove-if
10177 'org-file-apps-entry-match-against-dlink-p file-apps))
10178 (apps-dlink (org-remove-if-not
10179 'org-file-apps-entry-match-against-dlink-p file-apps))
10180 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10181 (dirp (if remp nil (file-directory-p file)))
10182 (file (if (and dirp org-open-directory-means-index-dot-org)
10183 (concat (file-name-as-directory file) "index.org")
10184 file))
10185 (a-m-a-p (assq 'auto-mode apps))
10186 (dfile (downcase file))
10187 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10188 (link (cond ((and (eq line nil)
10189 (eq search nil))
10190 file)
10191 (line
10192 (concat file "::" (number-to-string line)))
10193 (search
10194 (concat file "::" search))))
10195 (dlink (downcase link))
10196 (old-buffer (current-buffer))
10197 (old-pos (point))
10198 (old-mode major-mode)
10199 ext cmd link-match-data)
10200 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10201 (setq ext (match-string 1 dfile))
10202 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10203 (setq ext (match-string 1 dfile))))
10204 (cond
10205 ((member in-emacs '((16) system))
10206 (setq cmd (cdr (assoc 'system apps))))
10207 (in-emacs (setq cmd 'emacs))
10209 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10210 (and dirp (cdr (assoc 'directory apps)))
10211 ; first, try matching against apps-dlink
10212 ; if we get a match here, store the match data for later
10213 (let ((match (assoc-default dlink apps-dlink
10214 'string-match)))
10215 (if match
10216 (progn (setq link-match-data (match-data))
10217 match)
10218 (progn (setq in-emacs (or in-emacs line search))
10219 nil))) ; if we have no match in apps-dlink,
10220 ; always open the file in emacs if line or search
10221 ; is given (for backwards compatibility)
10222 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10223 'string-match)
10224 (cdr (assoc ext apps))
10225 (cdr (assoc t apps))))))
10226 (when (eq cmd 'system)
10227 (setq cmd (cdr (assoc 'system apps))))
10228 (when (eq cmd 'default)
10229 (setq cmd (cdr (assoc t apps))))
10230 (when (eq cmd 'mailcap)
10231 (require 'mailcap)
10232 (mailcap-parse-mailcaps)
10233 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10234 (command (mailcap-mime-info mime-type)))
10235 (if (stringp command)
10236 (setq cmd command)
10237 (setq cmd 'emacs))))
10238 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10239 (not (file-exists-p file))
10240 (not org-open-non-existing-files))
10241 (error "No such file: %s" file))
10242 (cond
10243 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10244 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10245 (while (string-match "['\"]%s['\"]" cmd)
10246 (setq cmd (replace-match "%s" t t cmd)))
10247 (while (string-match "%s" cmd)
10248 (setq cmd (replace-match
10249 (save-match-data
10250 (shell-quote-argument
10251 (convert-standard-filename file)))
10252 t t cmd)))
10254 ;; Replace "%1", "%2" etc. in command with group matches from regex
10255 (save-match-data
10256 (let ((match-index 1)
10257 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10258 (set-match-data link-match-data)
10259 (while (<= match-index number-of-groups)
10260 (let ((regex (concat "%" (number-to-string match-index)))
10261 (replace-with (match-string match-index dlink)))
10262 (while (string-match regex cmd)
10263 (setq cmd (replace-match replace-with t t cmd))))
10264 (setq match-index (+ match-index 1)))))
10266 (save-window-excursion
10267 (start-process-shell-command cmd nil cmd)
10268 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10270 ((or (stringp cmd)
10271 (eq cmd 'emacs))
10272 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10273 (widen)
10274 (if line (org-goto-line line)
10275 (if search (org-link-search search))))
10276 ((consp cmd)
10277 (let ((file (convert-standard-filename file)))
10278 (save-match-data
10279 (set-match-data link-match-data)
10280 (eval cmd))))
10281 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10282 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10283 (or (not (equal old-buffer (current-buffer)))
10284 (not (equal old-pos (point))))
10285 (org-mark-ring-push old-pos old-buffer))))
10287 (defun org-file-apps-entry-match-against-dlink-p (entry)
10288 "This function returns non-nil if `entry' uses a regular
10289 expression which should be matched against the whole link by
10290 org-open-file.
10292 It assumes that is the case when the entry uses a regular
10293 expression which has at least one grouping construct and the
10294 action is either a lisp form or a command string containing
10295 '%1', i.e. using at least one subexpression match as a
10296 parameter."
10297 (let ((selector (car entry))
10298 (action (cdr entry)))
10299 (if (stringp selector)
10300 (and (> (regexp-opt-depth selector) 0)
10301 (or (and (stringp action)
10302 (string-match "%[0-9]" action))
10303 (consp action)))
10304 nil)))
10306 (defun org-default-apps ()
10307 "Return the default applications for this operating system."
10308 (cond
10309 ((eq system-type 'darwin)
10310 org-file-apps-defaults-macosx)
10311 ((eq system-type 'windows-nt)
10312 org-file-apps-defaults-windowsnt)
10313 (t org-file-apps-defaults-gnu)))
10315 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10316 "Convert extensions to regular expressions in the cars of LIST.
10317 Also, weed out any non-string entries, because the return value is used
10318 only for regexp matching.
10319 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10320 point to the symbol `emacs', indicating that the file should
10321 be opened in Emacs."
10322 (append
10323 (delq nil
10324 (mapcar (lambda (x)
10325 (if (not (stringp (car x)))
10327 (if (string-match "\\W" (car x))
10329 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10330 list))
10331 (if add-auto-mode
10332 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10334 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10335 (defun org-file-remote-p (file)
10336 "Test whether FILE specifies a location on a remote system.
10337 Return non-nil if the location is indeed remote.
10339 For example, the filename \"/user@host:/foo\" specifies a location
10340 on the system \"/user@host:\"."
10341 (cond ((fboundp 'file-remote-p)
10342 (file-remote-p file))
10343 ((fboundp 'tramp-handle-file-remote-p)
10344 (tramp-handle-file-remote-p file))
10345 ((and (boundp 'ange-ftp-name-format)
10346 (string-match (car ange-ftp-name-format) file))
10348 (t nil)))
10351 ;;;; Refiling
10353 (defun org-get-org-file ()
10354 "Read a filename, with default directory `org-directory'."
10355 (let ((default (or org-default-notes-file remember-data-file)))
10356 (read-file-name (format "File name [%s]: " default)
10357 (file-name-as-directory org-directory)
10358 default)))
10360 (defun org-notes-order-reversed-p ()
10361 "Check if the current file should receive notes in reversed order."
10362 (cond
10363 ((not org-reverse-note-order) nil)
10364 ((eq t org-reverse-note-order) t)
10365 ((not (listp org-reverse-note-order)) nil)
10366 (t (catch 'exit
10367 (let ((all org-reverse-note-order)
10368 entry)
10369 (while (setq entry (pop all))
10370 (if (string-match (car entry) buffer-file-name)
10371 (throw 'exit (cdr entry))))
10372 nil)))))
10374 (defvar org-refile-target-table nil
10375 "The list of refile targets, created by `org-refile'.")
10377 (defvar org-agenda-new-buffers nil
10378 "Buffers created to visit agenda files.")
10380 (defvar org-refile-cache nil
10381 "Cache for refile targets.")
10383 (defvar org-refile-markers nil
10384 "All the markers used for caching refile locations.")
10386 (defun org-refile-marker (pos)
10387 "Get a new refile marker, but only if caching is in use."
10388 (if (not org-refile-use-cache)
10390 (let ((m (make-marker)))
10391 (move-marker m pos)
10392 (push m org-refile-markers)
10393 m)))
10395 (defun org-refile-cache-clear ()
10396 "Clear the refile cache and disable all the markers."
10397 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10398 (setq org-refile-markers nil)
10399 (setq org-refile-cache nil)
10400 (message "Refile cache has been cleared"))
10402 (defun org-refile-cache-check-set (set)
10403 "Check if all the markers in the cache still have live buffers."
10404 (let (marker)
10405 (catch 'exit
10406 (while (and set (setq marker (nth 3 (pop set))))
10407 ;; if org-refile-use-outline-path is 'file, marker may be nil
10408 (when (and marker (null (marker-buffer marker)))
10409 (message "not found") (sit-for 3)
10410 (throw 'exit nil)))
10411 t)))
10413 (defun org-refile-cache-put (set &rest identifiers)
10414 "Push the refile targets SET into the cache, under IDENTIFIERS."
10415 (let* ((key (sha1 (prin1-to-string identifiers)))
10416 (entry (assoc key org-refile-cache)))
10417 (if entry
10418 (setcdr entry set)
10419 (push (cons key set) org-refile-cache))))
10421 (defun org-refile-cache-get (&rest identifiers)
10422 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10423 (cond
10424 ((not org-refile-cache) nil)
10425 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10427 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10428 org-refile-cache))))
10429 (and set (org-refile-cache-check-set set) set)))))
10431 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10432 "Produce a table with refile targets."
10433 (let ((case-fold-search nil)
10434 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10435 (entries (or org-refile-targets '((nil . (:level . 1)))))
10436 targets tgs txt re files f desc descre fast-path-p level pos0)
10437 (message "Getting targets...")
10438 (with-current-buffer (or default-buffer (current-buffer))
10439 (while (setq entry (pop entries))
10440 (setq files (car entry) desc (cdr entry))
10441 (setq fast-path-p nil)
10442 (cond
10443 ((null files) (setq files (list (current-buffer))))
10444 ((eq files 'org-agenda-files)
10445 (setq files (org-agenda-files 'unrestricted)))
10446 ((and (symbolp files) (fboundp files))
10447 (setq files (funcall files)))
10448 ((and (symbolp files) (boundp files))
10449 (setq files (symbol-value files))))
10450 (if (stringp files) (setq files (list files)))
10451 (cond
10452 ((eq (car desc) :tag)
10453 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10454 ((eq (car desc) :todo)
10455 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10456 ((eq (car desc) :regexp)
10457 (setq descre (cdr desc)))
10458 ((eq (car desc) :level)
10459 (setq descre (concat "^\\*\\{" (number-to-string
10460 (if org-odd-levels-only
10461 (1- (* 2 (cdr desc)))
10462 (cdr desc)))
10463 "\\}[ \t]")))
10464 ((eq (car desc) :maxlevel)
10465 (setq fast-path-p t)
10466 (setq descre (concat "^\\*\\{1," (number-to-string
10467 (if org-odd-levels-only
10468 (1- (* 2 (cdr desc)))
10469 (cdr desc)))
10470 "\\}[ \t]")))
10471 (t (error "Bad refiling target description %s" desc)))
10472 (while (setq f (pop files))
10473 (with-current-buffer
10474 (if (bufferp f) f (org-get-agenda-file-buffer f))
10476 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10477 (progn
10478 (if (bufferp f) (setq f (buffer-file-name
10479 (buffer-base-buffer f))))
10480 (setq f (and f (expand-file-name f)))
10481 (if (eq org-refile-use-outline-path 'file)
10482 (push (list (file-name-nondirectory f) f nil nil) tgs))
10483 (save-excursion
10484 (save-restriction
10485 (widen)
10486 (goto-char (point-min))
10487 (while (re-search-forward descre nil t)
10488 (goto-char (setq pos0 (point-at-bol)))
10489 (catch 'next
10490 (when org-refile-target-verify-function
10491 (save-match-data
10492 (or (funcall org-refile-target-verify-function)
10493 (throw 'next t))))
10494 (when (and (looking-at org-complex-heading-regexp)
10495 (not (member (match-string 4) excluded-entries))
10496 (match-string 4))
10497 (setq level (org-reduced-level
10498 (- (match-end 1) (match-beginning 1)))
10499 txt (org-link-display-format (match-string 4))
10500 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10501 re (format org-complex-heading-regexp-format
10502 (regexp-quote (match-string 4))))
10503 (when org-refile-use-outline-path
10504 (setq txt (mapconcat
10505 'org-protect-slash
10506 (append
10507 (if (eq org-refile-use-outline-path
10508 'file)
10509 (list (file-name-nondirectory
10510 (buffer-file-name
10511 (buffer-base-buffer))))
10512 (if (eq org-refile-use-outline-path
10513 'full-file-path)
10514 (list (buffer-file-name
10515 (buffer-base-buffer)))))
10516 (org-get-outline-path fast-path-p
10517 level txt)
10518 (list txt))
10519 "/")))
10520 (push (list txt f re (org-refile-marker (point)))
10521 tgs)))
10522 (when (= (point) pos0)
10523 ;; verification function has not moved point
10524 (goto-char (point-at-eol))))))))
10525 (when org-refile-use-cache
10526 (org-refile-cache-put tgs (buffer-file-name) descre))
10527 (setq targets (append tgs targets))
10528 ))))
10529 (message "Getting targets...done")
10530 (nreverse targets)))
10532 (defun org-protect-slash (s)
10533 (while (string-match "/" s)
10534 (setq s (replace-match "\\" t t s)))
10537 (defvar org-olpa (make-vector 20 nil))
10539 (defun org-get-outline-path (&optional fastp level heading)
10540 "Return the outline path to the current entry, as a list.
10542 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10543 routine which makes outline path derivations for an entire file,
10544 avoiding backtracing. Refile target collection makes use of that."
10545 (if fastp
10546 (progn
10547 (if (> level 19)
10548 (error "Outline path failure, more than 19 levels"))
10549 (loop for i from level upto 19 do
10550 (aset org-olpa i nil))
10551 (prog1
10552 (delq nil (append org-olpa nil))
10553 (aset org-olpa level heading)))
10554 (let (rtn case-fold-search)
10555 (save-excursion
10556 (save-restriction
10557 (widen)
10558 (while (org-up-heading-safe)
10559 (when (looking-at org-complex-heading-regexp)
10560 (push (org-match-string-no-properties 4) rtn)))
10561 rtn)))))
10563 (defun org-format-outline-path (path &optional width prefix)
10564 "Format the outline path PATH for display.
10565 Width is the maximum number of characters that is available.
10566 Prefix is a prefix to be included in the returned string,
10567 such as the file name."
10568 (setq width (or width 79))
10569 (if prefix (setq width (- width (length prefix))))
10570 (if (not path)
10571 (or prefix "")
10572 (let* ((nsteps (length path))
10573 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10574 (maxwidth (if (<= total-width width)
10575 10000 ;; everything fits
10576 ;; we need to shorten the level headings
10577 (/ (- width nsteps) nsteps)))
10578 (org-odd-levels-only nil)
10579 (n 0)
10580 (total (1+ (length prefix))))
10581 (setq maxwidth (max maxwidth 10))
10582 (concat prefix
10583 (mapconcat
10584 (lambda (h)
10585 (setq n (1+ n))
10586 (if (and (= n nsteps) (< maxwidth 10000))
10587 (setq maxwidth (- total-width total)))
10588 (if (< (length h) maxwidth)
10589 (progn (setq total (+ total (length h) 1)) h)
10590 (setq h (substring h 0 (- maxwidth 2))
10591 total (+ total maxwidth 1))
10592 (if (string-match "[ \t]+\\'" h)
10593 (setq h (substring h 0 (match-beginning 0))))
10594 (setq h (concat h "..")))
10595 (org-add-props h nil 'face
10596 (nth (% (1- n) org-n-level-faces)
10597 org-level-faces))
10599 path "/")))))
10601 (defun org-display-outline-path (&optional file current)
10602 "Display the current outline path in the echo area."
10603 (interactive "P")
10604 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10605 (case-fold-search nil)
10606 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10607 (if current (setq path (append path
10608 (save-excursion
10609 (org-back-to-heading t)
10610 (if (looking-at org-complex-heading-regexp)
10611 (list (match-string 4)))))))
10612 (message "%s"
10613 (org-format-outline-path
10614 path
10615 (1- (frame-width))
10616 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10618 (defvar org-refile-history nil
10619 "History for refiling operations.")
10621 (defvar org-after-refile-insert-hook nil
10622 "Hook run after `org-refile' has inserted its stuff at the new location.
10623 Note that this is still *before* the stuff will be removed from
10624 the *old* location.")
10626 (defvar org-capture-last-stored-marker)
10627 (defun org-refile (&optional goto default-buffer rfloc)
10628 "Move the entry or entries at point to another heading.
10629 The list of target headings is compiled using the information in
10630 `org-refile-targets', which see.
10632 At the target location, the entry is filed as a subitem of the target
10633 heading. Depending on `org-reverse-note-order', the new subitem will
10634 either be the first or the last subitem.
10636 If there is an active region, all entries in that region will be moved.
10637 However, the region must fulfill the requirement that the first heading
10638 is the first one sets the top-level of the moved text - at most siblings
10639 below it are allowed.
10641 With prefix arg GOTO, the command will only visit the target location
10642 and not actually move anything.
10644 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10645 go to the location where the last refiling operation has put the subtree.
10646 With a prefix argument of `2', refile to the running clock.
10648 RFLOC can be a refile location obtained in a different way.
10650 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10652 If you are using target caching (see `org-refile-use-cache'),
10653 You have to clear the target cache in order to find new targets.
10654 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10655 prefix argument (`C-u C-u C-u C-c C-w')."
10657 (interactive "P")
10658 (if (member goto '(0 (64)))
10659 (org-refile-cache-clear)
10660 (let* ((cbuf (current-buffer))
10661 (regionp (org-region-active-p))
10662 (region-start (and regionp (region-beginning)))
10663 (region-end (and regionp (region-end)))
10664 (region-length (and regionp (- region-end region-start)))
10665 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10666 pos it nbuf file re level reversed)
10667 (setq last-command nil)
10668 (when regionp
10669 (goto-char region-start)
10670 (or (bolp) (goto-char (point-at-bol)))
10671 (setq region-start (point))
10672 (unless (or (org-kill-is-subtree-p
10673 (buffer-substring region-start region-end))
10674 (prog1 org-refile-active-region-within-subtree
10675 (org-toggle-heading)))
10676 (error "The region is not a (sequence of) subtree(s)")))
10677 (if (equal goto '(16))
10678 (org-refile-goto-last-stored)
10679 (when (or
10680 (and (equal goto 2)
10681 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10682 (prog1
10683 (setq it (list (or org-clock-heading "running clock")
10684 (buffer-file-name
10685 (marker-buffer org-clock-hd-marker))
10687 (marker-position org-clock-hd-marker)))
10688 (setq goto nil)))
10689 (setq it (or rfloc
10690 (let (heading-text)
10691 (save-excursion
10692 (unless goto
10693 (org-back-to-heading t)
10694 (setq heading-text
10695 (nth 4 (org-heading-components))))
10696 (org-refile-get-location
10697 (cond (goto "Goto")
10698 (regionp "Refile region to")
10699 (t (concat "Refile subtree \""
10700 heading-text "\" to")))
10701 default-buffer
10702 org-refile-allow-creating-parent-nodes
10703 goto))))))
10704 (setq file (nth 1 it)
10705 re (nth 2 it)
10706 pos (nth 3 it))
10707 (if (and (not goto)
10709 (equal (buffer-file-name) file)
10710 (if regionp
10711 (and (>= pos region-start)
10712 (<= pos region-end))
10713 (and (>= pos (point))
10714 (< pos (save-excursion
10715 (org-end-of-subtree t t))))))
10716 (error "Cannot refile to position inside the tree or region"))
10718 (setq nbuf (or (find-buffer-visiting file)
10719 (find-file-noselect file)))
10720 (if goto
10721 (progn
10722 (org-pop-to-buffer-same-window nbuf)
10723 (goto-char pos)
10724 (org-show-context 'org-goto))
10725 (if regionp
10726 (progn
10727 (org-kill-new (buffer-substring region-start region-end))
10728 (org-save-markers-in-region region-start region-end))
10729 (org-copy-subtree 1 nil t))
10730 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10731 (find-file-noselect file)))
10732 (setq reversed (org-notes-order-reversed-p))
10733 (save-excursion
10734 (save-restriction
10735 (widen)
10736 (if pos
10737 (progn
10738 (goto-char pos)
10739 (looking-at org-outline-regexp)
10740 (setq level (org-get-valid-level (funcall outline-level) 1))
10741 (goto-char
10742 (if reversed
10743 (or (outline-next-heading) (point-max))
10744 (or (save-excursion (org-get-next-sibling))
10745 (org-end-of-subtree t t)
10746 (point-max)))))
10747 (setq level 1)
10748 (if (not reversed)
10749 (goto-char (point-max))
10750 (goto-char (point-min))
10751 (or (outline-next-heading) (goto-char (point-max)))))
10752 (if (not (bolp)) (newline))
10753 (org-paste-subtree level)
10754 (when org-log-refile
10755 (org-add-log-setup 'refile nil nil 'findpos
10756 org-log-refile)
10757 (unless (eq org-log-refile 'note)
10758 (save-excursion (org-add-log-note))))
10759 (and org-auto-align-tags (org-set-tags nil t))
10760 (bookmark-set "org-refile-last-stored")
10761 ;; If we are refiling for capture, make sure that the
10762 ;; last-capture pointers point here
10763 (when (org-bound-and-true-p org-refile-for-capture)
10764 (bookmark-set "org-capture-last-stored-marker")
10765 (move-marker org-capture-last-stored-marker (point)))
10766 (if (fboundp 'deactivate-mark) (deactivate-mark))
10767 (run-hooks 'org-after-refile-insert-hook))))
10768 (if regionp
10769 (delete-region (point) (+ (point) region-length))
10770 (org-cut-subtree))
10771 (when (featurep 'org-inlinetask)
10772 (org-inlinetask-remove-END-maybe))
10773 (setq org-markers-to-move nil)
10774 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10776 (defun org-refile-goto-last-stored ()
10777 "Go to the location where the last refile was stored."
10778 (interactive)
10779 (bookmark-jump "org-refile-last-stored")
10780 (message "This is the location of the last refile"))
10782 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10783 no-exclude)
10784 "Prompt the user for a refile location, using PROMPT.
10785 PROMPT should not be suffixed with a colon and a space, because
10786 this function appends the default value from
10787 `org-refile-history' automatically, if that is not empty.
10788 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10789 this is used for the GOTO interface."
10790 (let ((org-refile-targets org-refile-targets)
10791 (org-refile-use-outline-path org-refile-use-outline-path)
10792 excluded-entries)
10793 (when (and (eq major-mode 'org-mode)
10794 (not org-refile-use-cache)
10795 (not no-exclude))
10796 (org-map-tree
10797 (lambda()
10798 (setq excluded-entries
10799 (append excluded-entries (list (org-get-heading t t)))))))
10800 (setq org-refile-target-table
10801 (org-refile-get-targets default-buffer excluded-entries)))
10802 (unless org-refile-target-table
10803 (error "No refile targets"))
10804 (let* ((prompt (concat prompt
10805 (and (car org-refile-history)
10806 (concat " (default " (car org-refile-history) ")"))
10807 ": "))
10808 (cbuf (current-buffer))
10809 (partial-completion-mode nil)
10810 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10811 (cfunc (if (and org-refile-use-outline-path
10812 org-outline-path-complete-in-steps)
10813 'org-olpath-completing-read
10814 'org-icompleting-read))
10815 (extra (if org-refile-use-outline-path "/" ""))
10816 (filename (and cfn (expand-file-name cfn)))
10817 (tbl (mapcar
10818 (lambda (x)
10819 (if (and (not (member org-refile-use-outline-path
10820 '(file full-file-path)))
10821 (not (equal filename (nth 1 x))))
10822 (cons (concat (car x) extra " ("
10823 (file-name-nondirectory (nth 1 x)) ")")
10824 (cdr x))
10825 (cons (concat (car x) extra) (cdr x))))
10826 org-refile-target-table))
10827 (completion-ignore-case t)
10828 pa answ parent-target child parent old-hist)
10829 (setq old-hist org-refile-history)
10830 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10831 nil 'org-refile-history (car org-refile-history)))
10832 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10833 (org-refile-check-position pa)
10834 (if pa
10835 (progn
10836 (when (or (not org-refile-history)
10837 (not (eq old-hist org-refile-history))
10838 (not (equal (car pa) (car org-refile-history))))
10839 (setq org-refile-history
10840 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10841 org-refile-history
10842 (cdr org-refile-history))))
10843 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10844 (pop org-refile-history)))
10846 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10847 (progn
10848 (setq parent (match-string 1 answ)
10849 child (match-string 2 answ))
10850 (setq parent-target (or (assoc parent tbl)
10851 (assoc (concat parent "/") tbl)))
10852 (when (and parent-target
10853 (or (eq new-nodes t)
10854 (and (eq new-nodes 'confirm)
10855 (y-or-n-p (format "Create new node \"%s\"? "
10856 child)))))
10857 (org-refile-new-child parent-target child)))
10858 (error "Invalid target location")))))
10860 (defun org-refile-check-position (refile-pointer)
10861 "Check if the refile pointer matches the readline to which it points."
10862 (let* ((file (nth 1 refile-pointer))
10863 (re (nth 2 refile-pointer))
10864 (pos (nth 3 refile-pointer))
10865 buffer)
10866 (when (org-string-nw-p re)
10867 (setq buffer (if (markerp pos)
10868 (marker-buffer pos)
10869 (or (find-buffer-visiting file)
10870 (find-file-noselect file))))
10871 (with-current-buffer buffer
10872 (save-excursion
10873 (save-restriction
10874 (widen)
10875 (goto-char pos)
10876 (beginning-of-line 1)
10877 (unless (org-looking-at-p re)
10878 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10880 (defun org-refile-new-child (parent-target child)
10881 "Use refile target PARENT-TARGET to add new CHILD below it."
10882 (unless parent-target
10883 (error "Cannot find parent for new node"))
10884 (let ((file (nth 1 parent-target))
10885 (pos (nth 3 parent-target))
10886 level)
10887 (with-current-buffer (or (find-buffer-visiting file)
10888 (find-file-noselect file))
10889 (save-excursion
10890 (save-restriction
10891 (widen)
10892 (if pos
10893 (goto-char pos)
10894 (goto-char (point-max))
10895 (if (not (bolp)) (newline)))
10896 (when (looking-at org-outline-regexp)
10897 (setq level (funcall outline-level))
10898 (org-end-of-subtree t t))
10899 (org-back-over-empty-lines)
10900 (insert "\n" (make-string
10901 (if pos (org-get-valid-level level 1) 1) ?*)
10902 " " child "\n")
10903 (beginning-of-line 0)
10904 (list (concat (car parent-target) "/" child) file "" (point)))))))
10906 (defun org-olpath-completing-read (prompt collection &rest args)
10907 "Read an outline path like a file name."
10908 (let ((thetable collection)
10909 (org-completion-use-ido nil) ; does not work with ido.
10910 (org-completion-use-iswitchb nil)) ; or iswitchb
10911 (apply
10912 'org-icompleting-read prompt
10913 (lambda (string predicate &optional flag)
10914 (let (rtn r f (l (length string)))
10915 (cond
10916 ((eq flag nil)
10917 ;; try completion
10918 (try-completion string thetable))
10919 ((eq flag t)
10920 ;; all-completions
10921 (setq rtn (all-completions string thetable predicate))
10922 (mapcar
10923 (lambda (x)
10924 (setq r (substring x l))
10925 (if (string-match " ([^)]*)$" x)
10926 (setq f (match-string 0 x))
10927 (setq f ""))
10928 (if (string-match "/" r)
10929 (concat string (substring r 0 (match-end 0)) f)
10931 rtn))
10932 ((eq flag 'lambda)
10933 ;; exact match?
10934 (assoc string thetable)))
10936 args)))
10938 ;;;; Dynamic blocks
10940 (defun org-find-dblock (name)
10941 "Find the first dynamic block with name NAME in the buffer.
10942 If not found, stay at current position and return nil."
10943 (let (pos)
10944 (save-excursion
10945 (goto-char (point-min))
10946 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10947 nil t)
10948 (match-beginning 0))))
10949 (if pos (goto-char pos))
10950 pos))
10952 (defconst org-dblock-start-re
10953 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10954 "Matches the start line of a dynamic block, with parameters.")
10956 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10957 "Matches the end of a dynamic block.")
10959 (defun org-create-dblock (plist)
10960 "Create a dynamic block section, with parameters taken from PLIST.
10961 PLIST must contain a :name entry which is used as name of the block."
10962 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10963 (end-of-line 1)
10964 (newline))
10965 (let ((col (current-column))
10966 (name (plist-get plist :name)))
10967 (insert "#+BEGIN: " name)
10968 (while plist
10969 (if (eq (car plist) :name)
10970 (setq plist (cddr plist))
10971 (insert " " (prin1-to-string (pop plist)))))
10972 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10973 (beginning-of-line -2)))
10975 (defun org-prepare-dblock ()
10976 "Prepare dynamic block for refresh.
10977 This empties the block, puts the cursor at the insert position and returns
10978 the property list including an extra property :name with the block name."
10979 (unless (looking-at org-dblock-start-re)
10980 (error "Not at a dynamic block"))
10981 (let* ((begdel (1+ (match-end 0)))
10982 (name (org-no-properties (match-string 1)))
10983 (params (append (list :name name)
10984 (read (concat "(" (match-string 3) ")")))))
10985 (save-excursion
10986 (beginning-of-line 1)
10987 (skip-chars-forward " \t")
10988 (setq params (plist-put params :indentation-column (current-column))))
10989 (unless (re-search-forward org-dblock-end-re nil t)
10990 (error "Dynamic block not terminated"))
10991 (setq params
10992 (append params
10993 (list :content (buffer-substring
10994 begdel (match-beginning 0)))))
10995 (delete-region begdel (match-beginning 0))
10996 (goto-char begdel)
10997 (open-line 1)
10998 params))
11000 (defun org-map-dblocks (&optional command)
11001 "Apply COMMAND to all dynamic blocks in the current buffer.
11002 If COMMAND is not given, use `org-update-dblock'."
11003 (let ((cmd (or command 'org-update-dblock)))
11004 (save-excursion
11005 (goto-char (point-min))
11006 (while (re-search-forward org-dblock-start-re nil t)
11007 (goto-char (match-beginning 0))
11008 (save-excursion
11009 (condition-case nil
11010 (funcall cmd)
11011 (error (message "Error during update of dynamic block"))))
11012 (unless (re-search-forward org-dblock-end-re nil t)
11013 (error "Dynamic block not terminated"))))))
11015 (defun org-dblock-update (&optional arg)
11016 "User command for updating dynamic blocks.
11017 Update the dynamic block at point. With prefix ARG, update all dynamic
11018 blocks in the buffer."
11019 (interactive "P")
11020 (if arg
11021 (org-update-all-dblocks)
11022 (or (looking-at org-dblock-start-re)
11023 (org-beginning-of-dblock))
11024 (org-update-dblock)))
11026 (defun org-update-dblock ()
11027 "Update the dynamic block at point.
11028 This means to empty the block, parse for parameters and then call
11029 the correct writing function."
11030 (interactive)
11031 (save-window-excursion
11032 (let* ((pos (point))
11033 (line (org-current-line))
11034 (params (org-prepare-dblock))
11035 (name (plist-get params :name))
11036 (indent (plist-get params :indentation-column))
11037 (cmd (intern (concat "org-dblock-write:" name))))
11038 (message "Updating dynamic block `%s' at line %d..." name line)
11039 (funcall cmd params)
11040 (message "Updating dynamic block `%s' at line %d...done" name line)
11041 (goto-char pos)
11042 (when (and indent (> indent 0))
11043 (setq indent (make-string indent ?\ ))
11044 (save-excursion
11045 (org-beginning-of-dblock)
11046 (forward-line 1)
11047 (while (not (looking-at org-dblock-end-re))
11048 (insert indent)
11049 (beginning-of-line 2))
11050 (when (looking-at org-dblock-end-re)
11051 (and (looking-at "[ \t]+")
11052 (replace-match ""))
11053 (insert indent)))))))
11055 (defun org-beginning-of-dblock ()
11056 "Find the beginning of the dynamic block at point.
11057 Error if there is no such block at point."
11058 (let ((pos (point))
11059 beg)
11060 (end-of-line 1)
11061 (if (and (re-search-backward org-dblock-start-re nil t)
11062 (setq beg (match-beginning 0))
11063 (re-search-forward org-dblock-end-re nil t)
11064 (> (match-end 0) pos))
11065 (goto-char beg)
11066 (goto-char pos)
11067 (error "Not in a dynamic block"))))
11069 (defun org-update-all-dblocks ()
11070 "Update all dynamic blocks in the buffer.
11071 This function can be used in a hook."
11072 (interactive)
11073 (when (eq major-mode 'org-mode)
11074 (org-map-dblocks 'org-update-dblock)))
11077 ;;;; Completion
11079 (defconst org-additional-option-like-keywords
11080 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11081 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11082 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11083 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11084 "BEGIN:" "END:"
11085 "ORGTBL" "TBLFM:" "TBLNAME:"
11086 "BEGIN_EXAMPLE" "END_EXAMPLE"
11087 "BEGIN_QUOTE" "END_QUOTE"
11088 "BEGIN_VERSE" "END_VERSE"
11089 "BEGIN_CENTER" "END_CENTER"
11090 "BEGIN_SRC" "END_SRC"
11091 "BEGIN_RESULT" "END_RESULT"
11092 "NAME:" "RESULTS:"
11093 "HEADER:" "HEADERS:"
11094 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11095 "CAPTION:" "LABEL:"
11096 "SETUPFILE:"
11097 "INCLUDE:"
11098 "BIND:"
11099 "MACRO:"))
11101 (defcustom org-structure-template-alist
11103 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11104 "<src lang=\"?\">\n\n</src>")
11105 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11106 "<example>\n?\n</example>")
11107 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11108 "<quote>\n?\n</quote>")
11109 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11110 "<verse>\n?\n</verse>")
11111 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11112 "<center>\n?\n</center>")
11113 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11114 "<literal style=\"latex\">\n?\n</literal>")
11115 ("L" "#+LaTeX: "
11116 "<literal style=\"latex\">?</literal>")
11117 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11118 "<literal style=\"html\">\n?\n</literal>")
11119 ("H" "#+HTML: "
11120 "<literal style=\"html\">?</literal>")
11121 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11122 ("A" "#+ASCII: ")
11123 ("i" "#+INDEX: ?"
11124 "#+INDEX: ?")
11125 ("I" "#+INCLUDE %file ?"
11126 "<include file=%file markup=\"?\">")
11128 "Structure completion elements.
11129 This is a list of abbreviation keys and values. The value gets inserted
11130 if you type `<' followed by the key and then press the completion key,
11131 usually `M-TAB'. %file will be replaced by a file name after prompting
11132 for the file using completion. The cursor will be placed at the position
11133 of the `?` in the template.
11134 There are two templates for each key, the first uses the original Org syntax,
11135 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11136 the default when the /org-mtags.el/ module has been loaded. See also the
11137 variable `org-mtags-prefer-muse-templates'."
11138 :group 'org-completion
11139 :type '(repeat
11140 (string :tag "Key")
11141 (string :tag "Template")
11142 (string :tag "Muse Template")))
11144 (defun org-try-structure-completion ()
11145 "Try to complete a structure template before point.
11146 This looks for strings like \"<e\" on an otherwise empty line and
11147 expands them."
11148 (let ((l (buffer-substring (point-at-bol) (point)))
11150 (when (and (looking-at "[ \t]*$")
11151 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11152 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11153 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11154 (match-beginning 1)) a)
11155 t)))
11157 (defun org-complete-expand-structure-template (start cell)
11158 "Expand a structure template."
11159 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11160 (rpl (nth (if musep 2 1) cell))
11161 (ind ""))
11162 (delete-region start (point))
11163 (when (string-match "\\`#\\+" rpl)
11164 (cond
11165 ((bolp))
11166 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11167 (setq ind (buffer-substring (point-at-bol) (point))))
11168 (t (newline))))
11169 (setq start (point))
11170 (if (string-match "%file" rpl)
11171 (setq rpl (replace-match
11172 (concat
11173 "\""
11174 (save-match-data
11175 (abbreviate-file-name (read-file-name "Include file: ")))
11176 "\"")
11177 t t rpl)))
11178 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11179 (concat "\n" ind)))
11180 (insert rpl)
11181 (if (re-search-backward "\\?" start t) (delete-char 1))))
11183 ;;;; TODO, DEADLINE, Comments
11185 (defun org-toggle-comment ()
11186 "Change the COMMENT state of an entry."
11187 (interactive)
11188 (save-excursion
11189 (org-back-to-heading)
11190 (let (case-fold-search)
11191 (cond
11192 ((looking-at (format org-heading-keyword-regexp-format
11193 org-comment-string))
11194 (goto-char (match-end 1))
11195 (looking-at (concat " +" org-comment-string))
11196 (replace-match "" t t)
11197 (when (eolp) (insert " ")))
11198 ((looking-at org-outline-regexp)
11199 (goto-char (match-end 0))
11200 (insert org-comment-string " "))))))
11202 (defvar org-last-todo-state-is-todo nil
11203 "This is non-nil when the last TODO state change led to a TODO state.
11204 If the last change removed the TODO tag or switched to DONE, then
11205 this is nil.")
11207 (defvar org-setting-tags nil) ; dynamically skipped
11209 (defvar org-todo-setup-filter-hook nil
11210 "Hook for functions that pre-filter todo specs.
11211 Each function takes a todo spec and returns either nil or the spec
11212 transformed into canonical form." )
11214 (defvar org-todo-get-default-hook nil
11215 "Hook for functions that get a default item for todo.
11216 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11217 nil or a string to be used for the todo mark." )
11219 (defvar org-agenda-headline-snapshot-before-repeat)
11221 (defun org-current-effective-time ()
11222 "Return current time adjusted for `org-extend-today-until' variable"
11223 (let* ((ct (org-current-time))
11224 (dct (decode-time ct))
11225 (ct1
11226 (if (and org-use-effective-time
11227 (< (nth 2 dct) org-extend-today-until))
11228 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11229 ct)))
11230 ct1))
11232 (defun org-todo-yesterday (&optional arg)
11233 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11234 (interactive "P")
11235 (if (eq major-mode 'org-agenda-mode)
11236 (apply 'org-agenda-todo-yesterday arg)
11237 (let* ((hour (third (decode-time
11238 (org-current-time))))
11239 (org-extend-today-until (1+ hour)))
11240 (org-todo arg))))
11242 (defun org-todo (&optional arg)
11243 "Change the TODO state of an item.
11244 The state of an item is given by a keyword at the start of the heading,
11245 like
11246 *** TODO Write paper
11247 *** DONE Call mom
11249 The different keywords are specified in the variable `org-todo-keywords'.
11250 By default the available states are \"TODO\" and \"DONE\".
11251 So for this example: when the item starts with TODO, it is changed to DONE.
11252 When it starts with DONE, the DONE is removed. And when neither TODO nor
11253 DONE are present, add TODO at the beginning of the heading.
11255 With \\[universal-argument] prefix arg, use completion to determine the new \
11256 state.
11257 With numeric prefix arg, switch to that state.
11258 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11259 keywords (nextset).
11260 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11261 With a numeric prefix arg of 0, inhibit note taking for the change.
11263 For calling through lisp, arg is also interpreted in the following way:
11264 'none -> empty state
11265 \"\"(empty string) -> switch to empty state
11266 'done -> switch to DONE
11267 'nextset -> switch to the next set of keywords
11268 'previousset -> switch to the previous set of keywords
11269 \"WAITING\" -> switch to the specified keyword, but only if it
11270 really is a member of `org-todo-keywords'."
11271 (interactive "P")
11272 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11273 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11274 'region-start-level 'region))
11275 org-loop-over-headlines-in-active-region)
11276 (org-map-entries
11277 `(org-todo ,arg)
11278 org-loop-over-headlines-in-active-region
11279 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11280 (if (equal arg '(16)) (setq arg 'nextset))
11281 (let ((org-blocker-hook org-blocker-hook)
11282 (case-fold-search nil))
11283 (when (equal arg '(64))
11284 (setq arg nil org-blocker-hook nil))
11285 (when (and org-blocker-hook
11286 (or org-inhibit-blocking
11287 (org-entry-get nil "NOBLOCKING")))
11288 (setq org-blocker-hook nil))
11289 (save-excursion
11290 (catch 'exit
11291 (org-back-to-heading t)
11292 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11293 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11294 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11295 (let* ((match-data (match-data))
11296 (startpos (point-at-bol))
11297 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11298 (org-log-done org-log-done)
11299 (org-log-repeat org-log-repeat)
11300 (org-todo-log-states org-todo-log-states)
11301 (org-inhibit-logging
11302 (if (equal arg 0)
11303 (progn (setq arg nil) 'note) org-inhibit-logging))
11304 (this (match-string 1))
11305 (hl-pos (match-beginning 0))
11306 (head (org-get-todo-sequence-head this))
11307 (ass (assoc head org-todo-kwd-alist))
11308 (interpret (nth 1 ass))
11309 (done-word (nth 3 ass))
11310 (final-done-word (nth 4 ass))
11311 (last-state (or this ""))
11312 (completion-ignore-case t)
11313 (member (member this org-todo-keywords-1))
11314 (tail (cdr member))
11315 (state (cond
11316 ((and org-todo-key-trigger
11317 (or (and (equal arg '(4))
11318 (eq org-use-fast-todo-selection 'prefix))
11319 (and (not arg) org-use-fast-todo-selection
11320 (not (eq org-use-fast-todo-selection
11321 'prefix)))))
11322 ;; Use fast selection
11323 (org-fast-todo-selection))
11324 ((and (equal arg '(4))
11325 (or (not org-use-fast-todo-selection)
11326 (not org-todo-key-trigger)))
11327 ;; Read a state with completion
11328 (org-icompleting-read
11329 "State: " (mapcar (lambda(x) (list x))
11330 org-todo-keywords-1)
11331 nil t))
11332 ((eq arg 'right)
11333 (if this
11334 (if tail (car tail) nil)
11335 (car org-todo-keywords-1)))
11336 ((eq arg 'left)
11337 (if (equal member org-todo-keywords-1)
11339 (if this
11340 (nth (- (length org-todo-keywords-1)
11341 (length tail) 2)
11342 org-todo-keywords-1)
11343 (org-last org-todo-keywords-1))))
11344 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11345 (setq arg nil))) ; hack to fall back to cycling
11346 (arg
11347 ;; user or caller requests a specific state
11348 (cond
11349 ((equal arg "") nil)
11350 ((eq arg 'none) nil)
11351 ((eq arg 'done) (or done-word (car org-done-keywords)))
11352 ((eq arg 'nextset)
11353 (or (car (cdr (member head org-todo-heads)))
11354 (car org-todo-heads)))
11355 ((eq arg 'previousset)
11356 (let ((org-todo-heads (reverse org-todo-heads)))
11357 (or (car (cdr (member head org-todo-heads)))
11358 (car org-todo-heads))))
11359 ((car (member arg org-todo-keywords-1)))
11360 ((stringp arg)
11361 (error "State `%s' not valid in this file" arg))
11362 ((nth (1- (prefix-numeric-value arg))
11363 org-todo-keywords-1))))
11364 ((null member) (or head (car org-todo-keywords-1)))
11365 ((equal this final-done-word) nil) ;; -> make empty
11366 ((null tail) nil) ;; -> first entry
11367 ((memq interpret '(type priority))
11368 (if (eq this-command last-command)
11369 (car tail)
11370 (if (> (length tail) 0)
11371 (or done-word (car org-done-keywords))
11372 nil)))
11374 (car tail))))
11375 (state (or
11376 (run-hook-with-args-until-success
11377 'org-todo-get-default-hook state last-state)
11378 state))
11379 (next (if state (concat " " state " ") " "))
11380 (change-plist (list :type 'todo-state-change :from this :to state
11381 :position startpos))
11382 dolog now-done-p)
11383 (when org-blocker-hook
11384 (setq org-last-todo-state-is-todo
11385 (not (member this org-done-keywords)))
11386 (unless (save-excursion
11387 (save-match-data
11388 (org-with-wide-buffer
11389 (run-hook-with-args-until-failure
11390 'org-blocker-hook change-plist))))
11391 (if (org-called-interactively-p 'interactive)
11392 (error "TODO state change from %s to %s blocked" this state)
11393 ;; fail silently
11394 (message "TODO state change from %s to %s blocked" this state)
11395 (throw 'exit nil))))
11396 (store-match-data match-data)
11397 (replace-match next t t)
11398 (unless (pos-visible-in-window-p hl-pos)
11399 (message "TODO state changed to %s" (org-trim next)))
11400 (unless head
11401 (setq head (org-get-todo-sequence-head state)
11402 ass (assoc head org-todo-kwd-alist)
11403 interpret (nth 1 ass)
11404 done-word (nth 3 ass)
11405 final-done-word (nth 4 ass)))
11406 (when (memq arg '(nextset previousset))
11407 (message "Keyword-Set %d/%d: %s"
11408 (- (length org-todo-sets) -1
11409 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11410 (length org-todo-sets)
11411 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11412 (setq org-last-todo-state-is-todo
11413 (not (member state org-done-keywords)))
11414 (setq now-done-p (and (member state org-done-keywords)
11415 (not (member this org-done-keywords))))
11416 (and logging (org-local-logging logging))
11417 (when (and (or org-todo-log-states org-log-done)
11418 (not (eq org-inhibit-logging t))
11419 (not (memq arg '(nextset previousset))))
11420 ;; we need to look at recording a time and note
11421 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11422 (nth 2 (assoc this org-todo-log-states))))
11423 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11424 (setq dolog 'time))
11425 (when (and state
11426 (member state org-not-done-keywords)
11427 (not (member this org-not-done-keywords)))
11428 ;; This is now a todo state and was not one before
11429 ;; If there was a CLOSED time stamp, get rid of it.
11430 (org-add-planning-info nil nil 'closed))
11431 (when (and now-done-p org-log-done)
11432 ;; It is now done, and it was not done before
11433 (org-add-planning-info 'closed (org-current-effective-time))
11434 (if (and (not dolog) (eq 'note org-log-done))
11435 (org-add-log-setup 'done state this 'findpos 'note)))
11436 (when (and state dolog)
11437 ;; This is a non-nil state, and we need to log it
11438 (org-add-log-setup 'state state this 'findpos dolog)))
11439 ;; Fixup tag positioning
11440 (org-todo-trigger-tag-changes state)
11441 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11442 (when org-provide-todo-statistics
11443 (org-update-parent-todo-statistics))
11444 (run-hooks 'org-after-todo-state-change-hook)
11445 (if (and arg (not (member state org-done-keywords)))
11446 (setq head (org-get-todo-sequence-head state)))
11447 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11448 ;; Do we need to trigger a repeat?
11449 (when now-done-p
11450 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11451 ;; This is for the agenda, take a snapshot of the headline.
11452 (save-match-data
11453 (setq org-agenda-headline-snapshot-before-repeat
11454 (org-get-heading))))
11455 (org-auto-repeat-maybe state))
11456 ;; Fixup cursor location if close to the keyword
11457 (if (and (outline-on-heading-p)
11458 (not (bolp))
11459 (save-excursion (beginning-of-line 1)
11460 (looking-at org-todo-line-regexp))
11461 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11462 (progn
11463 (goto-char (or (match-end 2) (match-end 1)))
11464 (and (looking-at " ") (just-one-space))))
11465 (when org-trigger-hook
11466 (save-excursion
11467 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11469 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11470 "Block turning an entry into a TODO, using the hierarchy.
11471 This checks whether the current task should be blocked from state
11472 changes. Such blocking occurs when:
11474 1. The task has children which are not all in a completed state.
11476 2. A task has a parent with the property :ORDERED:, and there
11477 are siblings prior to the current task with incomplete
11478 status.
11480 3. The parent of the task is blocked because it has siblings that should
11481 be done first, or is child of a block grandparent TODO entry."
11483 (if (not org-enforce-todo-dependencies)
11484 t ; if locally turned off don't block
11485 (catch 'dont-block
11486 ;; If this is not a todo state change, or if this entry is already DONE,
11487 ;; do not block
11488 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11489 (member (plist-get change-plist :from)
11490 (cons 'done org-done-keywords))
11491 (member (plist-get change-plist :to)
11492 (cons 'todo org-not-done-keywords))
11493 (not (plist-get change-plist :to)))
11494 (throw 'dont-block t))
11495 ;; If this task has children, and any are undone, it's blocked
11496 (save-excursion
11497 (org-back-to-heading t)
11498 (let ((this-level (funcall outline-level)))
11499 (outline-next-heading)
11500 (let ((child-level (funcall outline-level)))
11501 (while (and (not (eobp))
11502 (> child-level this-level))
11503 ;; this todo has children, check whether they are all
11504 ;; completed
11505 (if (and (not (org-entry-is-done-p))
11506 (org-entry-is-todo-p))
11507 (throw 'dont-block nil))
11508 (outline-next-heading)
11509 (setq child-level (funcall outline-level))))))
11510 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11511 ;; any previous siblings are undone, it's blocked
11512 (save-excursion
11513 (org-back-to-heading t)
11514 (let* ((pos (point))
11515 (parent-pos (and (org-up-heading-safe) (point))))
11516 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11517 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11518 (forward-line 1)
11519 (re-search-forward org-not-done-heading-regexp pos t))
11520 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11521 ;; Search further up the hierarchy, to see if an ancestor is blocked
11522 (while t
11523 (goto-char parent-pos)
11524 (if (not (looking-at org-not-done-heading-regexp))
11525 (throw 'dont-block t)) ; do not block, parent is not a TODO
11526 (setq pos (point))
11527 (setq parent-pos (and (org-up-heading-safe) (point)))
11528 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11529 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11530 (forward-line 1)
11531 (re-search-forward org-not-done-heading-regexp pos t))
11532 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11534 (defcustom org-track-ordered-property-with-tag nil
11535 "Should the ORDERED property also be shown as a tag?
11536 The ORDERED property decides if an entry should require subtasks to be
11537 completed in sequence. Since a property is not very visible, setting
11538 this option means that toggling the ORDERED property with the command
11539 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11540 not relevant for the behavior, but it makes things more visible.
11542 Note that toggling the tag with tags commands will not change the property
11543 and therefore not influence behavior!
11545 This can be t, meaning the tag ORDERED should be used, It can also be a
11546 string to select a different tag for this task."
11547 :group 'org-todo
11548 :type '(choice
11549 (const :tag "No tracking" nil)
11550 (const :tag "Track with ORDERED tag" t)
11551 (string :tag "Use other tag")))
11553 (defun org-toggle-ordered-property ()
11554 "Toggle the ORDERED property of the current entry.
11555 For better visibility, you can track the value of this property with a tag.
11556 See variable `org-track-ordered-property-with-tag'."
11557 (interactive)
11558 (let* ((t1 org-track-ordered-property-with-tag)
11559 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11560 (save-excursion
11561 (org-back-to-heading)
11562 (if (org-entry-get nil "ORDERED")
11563 (progn
11564 (org-delete-property "ORDERED")
11565 (and tag (org-toggle-tag tag 'off))
11566 (message "Subtasks can be completed in arbitrary order"))
11567 (org-entry-put nil "ORDERED" "t")
11568 (and tag (org-toggle-tag tag 'on))
11569 (message "Subtasks must be completed in sequence")))))
11571 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11572 (defun org-block-todo-from-checkboxes (change-plist)
11573 "Block turning an entry into a TODO, using checkboxes.
11574 This checks whether the current task should be blocked from state
11575 changes because there are unchecked boxes in this entry."
11576 (if (not org-enforce-todo-checkbox-dependencies)
11577 t ; if locally turned off don't block
11578 (catch 'dont-block
11579 ;; If this is not a todo state change, or if this entry is already DONE,
11580 ;; do not block
11581 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11582 (member (plist-get change-plist :from)
11583 (cons 'done org-done-keywords))
11584 (member (plist-get change-plist :to)
11585 (cons 'todo org-not-done-keywords))
11586 (not (plist-get change-plist :to)))
11587 (throw 'dont-block t))
11588 ;; If this task has checkboxes that are not checked, it's blocked
11589 (save-excursion
11590 (org-back-to-heading t)
11591 (let ((beg (point)) end)
11592 (outline-next-heading)
11593 (setq end (point))
11594 (goto-char beg)
11595 (if (org-list-search-forward
11596 (concat (org-item-beginning-re)
11597 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11598 "\\[[- ]\\]")
11599 end t)
11600 (progn
11601 (if (boundp 'org-blocked-by-checkboxes)
11602 (setq org-blocked-by-checkboxes t))
11603 (throw 'dont-block nil)))))
11604 t))) ; do not block
11606 (defun org-entry-blocked-p ()
11607 "Is the current entry blocked?"
11608 (if (org-entry-get nil "NOBLOCKING")
11609 nil ;; Never block this entry
11610 (not
11611 (run-hook-with-args-until-failure
11612 'org-blocker-hook
11613 (list :type 'todo-state-change
11614 :position (point)
11615 :from 'todo
11616 :to 'done)))))
11618 (defun org-update-statistics-cookies (all)
11619 "Update the statistics cookie, either from TODO or from checkboxes.
11620 This should be called with the cursor in a line with a statistics cookie."
11621 (interactive "P")
11622 (if all
11623 (progn
11624 (org-update-checkbox-count 'all)
11625 (org-map-entries 'org-update-parent-todo-statistics))
11626 (if (not (org-at-heading-p))
11627 (org-update-checkbox-count)
11628 (let ((pos (move-marker (make-marker) (point)))
11629 end l1 l2)
11630 (ignore-errors (org-back-to-heading t))
11631 (if (not (org-at-heading-p))
11632 (org-update-checkbox-count)
11633 (setq l1 (org-outline-level))
11634 (setq end (save-excursion
11635 (outline-next-heading)
11636 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11637 (point)))
11638 (if (and (save-excursion
11639 (re-search-forward
11640 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11641 (not (save-excursion (re-search-forward
11642 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11643 (org-update-checkbox-count)
11644 (if (and l2 (> l2 l1))
11645 (progn
11646 (goto-char end)
11647 (org-update-parent-todo-statistics))
11648 (goto-char pos)
11649 (beginning-of-line 1)
11650 (while (re-search-forward
11651 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11652 (point-at-eol) t)
11653 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11654 (goto-char pos)
11655 (move-marker pos nil)))))
11657 (defvar org-entry-property-inherited-from) ;; defined below
11658 (defun org-update-parent-todo-statistics ()
11659 "Update any statistics cookie in the parent of the current headline.
11660 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11661 the entire subtree and this will travel up the hierarchy and update
11662 statistics everywhere."
11663 (let* ((prop (save-excursion (org-up-heading-safe)
11664 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11665 (recursive (or (not org-hierarchical-todo-statistics)
11666 (and prop (string-match "\\<recursive\\>" prop))))
11667 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11669 (first t)
11670 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11671 level ltoggle l1 new ndel
11672 (cnt-all 0) (cnt-done 0) is-percent kwd
11673 checkbox-beg ov ovs ove cookie-present)
11674 (catch 'exit
11675 (save-excursion
11676 (beginning-of-line 1)
11677 (setq ltoggle (funcall outline-level))
11678 ;; Three situations are to consider:
11680 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11681 ;; to the top-level ancestor on the headline;
11683 ;; 2. If parent has "recursive" property, repeat up to the
11684 ;; headline setting that property, taking inheritance into
11685 ;; account;
11687 ;; 3. Else, move up to direct parent and proceed only once.
11688 (while (and (setq level (org-up-heading-safe))
11689 (or recursive first)
11690 (>= (point) lim))
11691 (setq first nil cookie-present nil)
11692 (unless (and level
11693 (not (string-match
11694 "\\<checkbox\\>"
11695 (downcase (or (org-entry-get nil "COOKIE_DATA")
11696 "")))))
11697 (throw 'exit nil))
11698 (while (re-search-forward box-re (point-at-eol) t)
11699 (setq cnt-all 0 cnt-done 0 cookie-present t)
11700 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11701 (save-match-data
11702 (unless (outline-next-heading) (throw 'exit nil))
11703 (while (and (looking-at org-complex-heading-regexp)
11704 (> (setq l1 (length (match-string 1))) level))
11705 (setq kwd (and (or recursive (= l1 ltoggle))
11706 (match-string 2)))
11707 (if (or (eq org-provide-todo-statistics 'all-headlines)
11708 (and (listp org-provide-todo-statistics)
11709 (or (member kwd org-provide-todo-statistics)
11710 (member kwd org-done-keywords))))
11711 (setq cnt-all (1+ cnt-all))
11712 (if (eq org-provide-todo-statistics t)
11713 (and kwd (setq cnt-all (1+ cnt-all)))))
11714 (and (member kwd org-done-keywords)
11715 (setq cnt-done (1+ cnt-done)))
11716 (outline-next-heading)))
11717 (setq new
11718 (if is-percent
11719 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11720 (format "[%d/%d]" cnt-done cnt-all))
11721 ndel (- (match-end 0) checkbox-beg))
11722 ;; handle overlays when updating cookie from column view
11723 (when (setq ov (car (overlays-at checkbox-beg)))
11724 (setq ovs (overlay-start ov) ove (overlay-end ov))
11725 (delete-overlay ov))
11726 (goto-char checkbox-beg)
11727 (insert new)
11728 (delete-region (point) (+ (point) ndel))
11729 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11730 (when ov (move-overlay ov ovs ove)))
11731 (when cookie-present
11732 (run-hook-with-args 'org-after-todo-statistics-hook
11733 cnt-done (- cnt-all cnt-done))))))
11734 (run-hooks 'org-todo-statistics-hook)))
11736 (defvar org-after-todo-statistics-hook nil
11737 "Hook that is called after a TODO statistics cookie has been updated.
11738 Each function is called with two arguments: the number of not-done entries
11739 and the number of done entries.
11741 For example, the following function, when added to this hook, will switch
11742 an entry to DONE when all children are done, and back to TODO when new
11743 entries are set to a TODO status. Note that this hook is only called
11744 when there is a statistics cookie in the headline!
11746 (defun org-summary-todo (n-done n-not-done)
11747 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11748 (let (org-log-done org-log-states) ; turn off logging
11749 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11752 (defvar org-todo-statistics-hook nil
11753 "Hook that is run whenever Org thinks TODO statistics should be updated.
11754 This hook runs even if there is no statistics cookie present, in which case
11755 `org-after-todo-statistics-hook' would not run.")
11757 (defun org-todo-trigger-tag-changes (state)
11758 "Apply the changes defined in `org-todo-state-tags-triggers'."
11759 (let ((l org-todo-state-tags-triggers)
11760 changes)
11761 (when (or (not state) (equal state ""))
11762 (setq changes (append changes (cdr (assoc "" l)))))
11763 (when (and (stringp state) (> (length state) 0))
11764 (setq changes (append changes (cdr (assoc state l)))))
11765 (when (member state org-not-done-keywords)
11766 (setq changes (append changes (cdr (assoc 'todo l)))))
11767 (when (member state org-done-keywords)
11768 (setq changes (append changes (cdr (assoc 'done l)))))
11769 (dolist (c changes)
11770 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11772 (defun org-local-logging (value)
11773 "Get logging settings from a property VALUE."
11774 (let* (words w a)
11775 ;; directly set the variables, they are already local.
11776 (setq org-log-done nil
11777 org-log-repeat nil
11778 org-todo-log-states nil)
11779 (setq words (org-split-string value))
11780 (while (setq w (pop words))
11781 (cond
11782 ((setq a (assoc w org-startup-options))
11783 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11784 (set (nth 1 a) (nth 2 a))))
11785 ((setq a (org-extract-log-state-settings w))
11786 (and (member (car a) org-todo-keywords-1)
11787 (push a org-todo-log-states)))))))
11789 (defun org-get-todo-sequence-head (kwd)
11790 "Return the head of the TODO sequence to which KWD belongs.
11791 If KWD is not set, check if there is a text property remembering the
11792 right sequence."
11793 (let (p)
11794 (cond
11795 ((not kwd)
11796 (or (get-text-property (point-at-bol) 'org-todo-head)
11797 (progn
11798 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11799 nil (point-at-eol)))
11800 (get-text-property p 'org-todo-head))))
11801 ((not (member kwd org-todo-keywords-1))
11802 (car org-todo-keywords-1))
11803 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11805 (defun org-fast-todo-selection ()
11806 "Fast TODO keyword selection with single keys.
11807 Returns the new TODO keyword, or nil if no state change should occur."
11808 (let* ((fulltable org-todo-key-alist)
11809 (done-keywords org-done-keywords) ;; needed for the faces.
11810 (maxlen (apply 'max (mapcar
11811 (lambda (x)
11812 (if (stringp (car x)) (string-width (car x)) 0))
11813 fulltable)))
11814 (expert nil)
11815 (fwidth (+ maxlen 3 1 3))
11816 (ncol (/ (- (window-width) 4) fwidth))
11817 tg cnt e c tbl
11818 groups ingroup)
11819 (save-excursion
11820 (save-window-excursion
11821 (if expert
11822 (set-buffer (get-buffer-create " *Org todo*"))
11823 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11824 (erase-buffer)
11825 (org-set-local 'org-done-keywords done-keywords)
11826 (setq tbl fulltable cnt 0)
11827 (while (setq e (pop tbl))
11828 (cond
11829 ((equal e '(:startgroup))
11830 (push '() groups) (setq ingroup t)
11831 (when (not (= cnt 0))
11832 (setq cnt 0)
11833 (insert "\n"))
11834 (insert "{ "))
11835 ((equal e '(:endgroup))
11836 (setq ingroup nil cnt 0)
11837 (insert "}\n"))
11838 ((equal e '(:newline))
11839 (when (not (= cnt 0))
11840 (setq cnt 0)
11841 (insert "\n")
11842 (setq e (car tbl))
11843 (while (equal (car tbl) '(:newline))
11844 (insert "\n")
11845 (setq tbl (cdr tbl)))))
11847 (setq tg (car e) c (cdr e))
11848 (if ingroup (push tg (car groups)))
11849 (setq tg (org-add-props tg nil 'face
11850 (org-get-todo-face tg)))
11851 (if (and (= cnt 0) (not ingroup)) (insert " "))
11852 (insert "[" c "] " tg (make-string
11853 (- fwidth 4 (length tg)) ?\ ))
11854 (when (= (setq cnt (1+ cnt)) ncol)
11855 (insert "\n")
11856 (if ingroup (insert " "))
11857 (setq cnt 0)))))
11858 (insert "\n")
11859 (goto-char (point-min))
11860 (if (not expert) (org-fit-window-to-buffer))
11861 (message "[a-z..]:Set [SPC]:clear")
11862 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11863 (cond
11864 ((or (= c ?\C-g)
11865 (and (= c ?q) (not (rassoc c fulltable))))
11866 (setq quit-flag t))
11867 ((= c ?\ ) nil)
11868 ((setq e (rassoc c fulltable) tg (car e))
11870 (t (setq quit-flag t)))))))
11872 (defun org-entry-is-todo-p ()
11873 (member (org-get-todo-state) org-not-done-keywords))
11875 (defun org-entry-is-done-p ()
11876 (member (org-get-todo-state) org-done-keywords))
11878 (defun org-get-todo-state ()
11879 (save-excursion
11880 (org-back-to-heading t)
11881 (and (looking-at org-todo-line-regexp)
11882 (match-end 2)
11883 (match-string 2))))
11885 (defun org-at-date-range-p (&optional inactive-ok)
11886 "Is the cursor inside a date range?"
11887 (interactive)
11888 (save-excursion
11889 (catch 'exit
11890 (let ((pos (point)))
11891 (skip-chars-backward "^[<\r\n")
11892 (skip-chars-backward "<[")
11893 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11894 (>= (match-end 0) pos)
11895 (throw 'exit t))
11896 (skip-chars-backward "^<[\r\n")
11897 (skip-chars-backward "<[")
11898 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11899 (>= (match-end 0) pos)
11900 (throw 'exit t)))
11901 nil)))
11903 (defun org-get-repeat (&optional tagline)
11904 "Check if there is a deadline/schedule with repeater in this entry."
11905 (save-match-data
11906 (save-excursion
11907 (org-back-to-heading t)
11908 (and (re-search-forward (if tagline
11909 (concat tagline "\\s-*" org-repeat-re)
11910 org-repeat-re)
11911 (org-entry-end-position) t)
11912 (match-string-no-properties 1)))))
11914 (defvar org-last-changed-timestamp)
11915 (defvar org-last-inserted-timestamp)
11916 (defvar org-log-post-message)
11917 (defvar org-log-note-purpose)
11918 (defvar org-log-note-how)
11919 (defvar org-log-note-extra)
11920 (defun org-auto-repeat-maybe (done-word)
11921 "Check if the current headline contains a repeated deadline/schedule.
11922 If yes, set TODO state back to what it was and change the base date
11923 of repeating deadline/scheduled time stamps to new date.
11924 This function is run automatically after each state change to a DONE state."
11925 ;; last-state is dynamically scoped into this function
11926 (let* ((repeat (org-get-repeat))
11927 (aa (assoc last-state org-todo-kwd-alist))
11928 (interpret (nth 1 aa))
11929 (head (nth 2 aa))
11930 (whata '(("d" . day) ("m" . month) ("y" . year)))
11931 (msg "Entry repeats: ")
11932 (org-log-done nil)
11933 (org-todo-log-states nil)
11934 re type n what ts time to-state)
11935 (when repeat
11936 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11937 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11938 org-todo-repeat-to-state))
11939 (unless (and to-state (member to-state org-todo-keywords-1))
11940 (setq to-state (if (eq interpret 'type) last-state head)))
11941 (org-todo to-state)
11942 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11943 (org-entry-put nil "LAST_REPEAT" (format-time-string
11944 (org-time-stamp-format t t))))
11945 (when org-log-repeat
11946 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11947 (memq 'org-add-log-note post-command-hook))
11948 ;; OK, we are already setup for some record
11949 (if (eq org-log-repeat 'note)
11950 ;; make sure we take a note, not only a time stamp
11951 (setq org-log-note-how 'note))
11952 ;; Set up for taking a record
11953 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11954 last-state
11955 'findpos org-log-repeat)))
11956 (org-back-to-heading t)
11957 (org-add-planning-info nil nil 'closed)
11958 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11959 org-deadline-time-regexp "\\)\\|\\("
11960 org-ts-regexp "\\)"))
11961 (while (re-search-forward
11962 re (save-excursion (outline-next-heading) (point)) t)
11963 (setq type (if (match-end 1) org-scheduled-string
11964 (if (match-end 3) org-deadline-string "Plain:"))
11965 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11966 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11967 (setq n (string-to-number (match-string 2 ts))
11968 what (match-string 3 ts))
11969 (if (equal what "w") (setq n (* n 7) what "d"))
11970 ;; Preparation, see if we need to modify the start date for the change
11971 (when (match-end 1)
11972 (setq time (save-match-data (org-time-string-to-time ts)))
11973 (cond
11974 ((equal (match-string 1 ts) ".")
11975 ;; Shift starting date to today
11976 (org-timestamp-change
11977 (- (org-today) (time-to-days time))
11978 'day))
11979 ((equal (match-string 1 ts) "+")
11980 (let ((nshiftmax 10) (nshift 0))
11981 (while (or (= nshift 0)
11982 (<= (time-to-days time)
11983 (time-to-days (current-time))))
11984 (when (= (incf nshift) nshiftmax)
11985 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11986 (error "Abort")))
11987 (org-timestamp-change n (cdr (assoc what whata)))
11988 (org-at-timestamp-p t)
11989 (setq ts (match-string 1))
11990 (setq time (save-match-data (org-time-string-to-time ts)))))
11991 (org-timestamp-change (- n) (cdr (assoc what whata)))
11992 ;; rematch, so that we have everything in place for the real shift
11993 (org-at-timestamp-p t)
11994 (setq ts (match-string 1))
11995 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11996 (org-timestamp-change n (cdr (assoc what whata)))
11997 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11998 (setq org-log-post-message msg)
11999 (message "%s" msg))))
12001 (defun org-show-todo-tree (arg)
12002 "Make a compact tree which shows all headlines marked with TODO.
12003 The tree will show the lines where the regexp matches, and all higher
12004 headlines above the match.
12005 With a \\[universal-argument] prefix, prompt for a regexp to match.
12006 With a numeric prefix N, construct a sparse tree for the Nth element
12007 of `org-todo-keywords-1'."
12008 (interactive "P")
12009 (let ((case-fold-search nil)
12010 (kwd-re
12011 (cond ((null arg) org-not-done-regexp)
12012 ((equal arg '(4))
12013 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12014 (mapcar 'list org-todo-keywords-1))))
12015 (concat "\\("
12016 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12017 "\\)\\>")))
12018 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12019 (regexp-quote (nth (1- (prefix-numeric-value arg))
12020 org-todo-keywords-1)))
12021 (t (error "Invalid prefix argument: %s" arg)))))
12022 (message "%d TODO entries found"
12023 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12025 (defun org-deadline (&optional remove time)
12026 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12027 With argument REMOVE, remove any deadline from the item.
12028 With argument TIME, set the deadline at the corresponding date. TIME
12029 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12030 (interactive "P")
12031 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12032 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12033 'region-start-level 'region))
12034 org-loop-over-headlines-in-active-region)
12035 (org-map-entries
12036 `(org-deadline ',remove ,time)
12037 org-loop-over-headlines-in-active-region
12038 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12039 (let* ((old-date (org-entry-get nil "DEADLINE"))
12040 (repeater (and old-date
12041 (string-match
12042 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12043 old-date)
12044 (match-string 1 old-date))))
12045 (if remove
12046 (progn
12047 (when (and old-date org-log-redeadline)
12048 (org-add-log-setup 'deldeadline nil old-date 'findpos
12049 org-log-redeadline))
12050 (org-remove-timestamp-with-keyword org-deadline-string)
12051 (message "Item no longer has a deadline."))
12052 (org-add-planning-info 'deadline time 'closed)
12053 (when (and old-date org-log-redeadline
12054 (not (equal old-date
12055 (substring org-last-inserted-timestamp 1 -1))))
12056 (org-add-log-setup 'redeadline nil old-date 'findpos
12057 org-log-redeadline))
12058 (when repeater
12059 (save-excursion
12060 (org-back-to-heading t)
12061 (when (re-search-forward (concat org-deadline-string " "
12062 org-last-inserted-timestamp)
12063 (save-excursion
12064 (outline-next-heading) (point)) t)
12065 (goto-char (1- (match-end 0)))
12066 (insert " " repeater)
12067 (setq org-last-inserted-timestamp
12068 (concat (substring org-last-inserted-timestamp 0 -1)
12069 " " repeater
12070 (substring org-last-inserted-timestamp -1))))))
12071 (message "Deadline on %s" org-last-inserted-timestamp)))))
12073 (defun org-schedule (&optional remove time)
12074 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12075 With argument REMOVE, remove any scheduling date from the item.
12076 With argument TIME, scheduled at the corresponding date. TIME can
12077 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12078 (interactive "P")
12079 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12080 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12081 'region-start-level 'region))
12082 org-loop-over-headlines-in-active-region)
12083 (org-map-entries
12084 `(org-schedule ',remove ,time)
12085 org-loop-over-headlines-in-active-region
12086 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12087 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12088 (repeater (and old-date
12089 (string-match
12090 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12091 old-date)
12092 (match-string 1 old-date))))
12093 (if remove
12094 (progn
12095 (when (and old-date org-log-reschedule)
12096 (org-add-log-setup 'delschedule nil old-date 'findpos
12097 org-log-reschedule))
12098 (org-remove-timestamp-with-keyword org-scheduled-string)
12099 (message "Item is no longer scheduled."))
12100 (org-add-planning-info 'scheduled time 'closed)
12101 (when (and old-date org-log-reschedule
12102 (not (equal old-date
12103 (substring org-last-inserted-timestamp 1 -1))))
12104 (org-add-log-setup 'reschedule nil old-date 'findpos
12105 org-log-reschedule))
12106 (when repeater
12107 (save-excursion
12108 (org-back-to-heading t)
12109 (when (re-search-forward (concat org-scheduled-string " "
12110 org-last-inserted-timestamp)
12111 (save-excursion
12112 (outline-next-heading) (point)) t)
12113 (goto-char (1- (match-end 0)))
12114 (insert " " repeater)
12115 (setq org-last-inserted-timestamp
12116 (concat (substring org-last-inserted-timestamp 0 -1)
12117 " " repeater
12118 (substring org-last-inserted-timestamp -1))))))
12119 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12121 (defun org-get-scheduled-time (pom &optional inherit)
12122 "Get the scheduled time as a time tuple, of a format suitable
12123 for calling org-schedule with, or if there is no scheduling,
12124 returns nil."
12125 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12126 (when time
12127 (apply 'encode-time (org-parse-time-string time)))))
12129 (defun org-get-deadline-time (pom &optional inherit)
12130 "Get the deadline as a time tuple, of a format suitable for
12131 calling org-deadline with, or if there is no scheduling, returns
12132 nil."
12133 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12134 (when time
12135 (apply 'encode-time (org-parse-time-string time)))))
12137 (defun org-remove-timestamp-with-keyword (keyword)
12138 "Remove all time stamps with KEYWORD in the current entry."
12139 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12140 beg)
12141 (save-excursion
12142 (org-back-to-heading t)
12143 (setq beg (point))
12144 (outline-next-heading)
12145 (while (re-search-backward re beg t)
12146 (replace-match "")
12147 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12148 (equal (char-before) ?\ ))
12149 (backward-delete-char 1)
12150 (if (string-match "^[ \t]*$" (buffer-substring
12151 (point-at-bol) (point-at-eol)))
12152 (delete-region (point-at-bol)
12153 (min (point-max) (1+ (point-at-eol))))))))))
12155 (defun org-add-planning-info (what &optional time &rest remove)
12156 "Insert new timestamp with keyword in the line directly after the headline.
12157 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12158 If non is given, the user is prompted for a date.
12159 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12160 be removed."
12161 (interactive)
12162 (let (org-time-was-given org-end-time-was-given ts
12163 end default-time default-input)
12165 (catch 'exit
12166 (when (and (memq what '(scheduled deadline))
12167 (or (not time)
12168 (and (stringp time)
12169 (string-match "^[-+]+[0-9]" time))))
12170 ;; Try to get a default date/time from existing timestamp
12171 (save-excursion
12172 (org-back-to-heading t)
12173 (setq end (save-excursion (outline-next-heading) (point)))
12174 (when (re-search-forward (if (eq what 'scheduled)
12175 org-scheduled-time-regexp
12176 org-deadline-time-regexp)
12177 end t)
12178 (setq ts (match-string 1)
12179 default-time
12180 (apply 'encode-time (org-parse-time-string ts))
12181 default-input (and ts (org-get-compact-tod ts))))))
12182 (when what
12183 (setq time
12184 (if (stringp time)
12185 ;; This is a string (relative or absolute), set proper date
12186 (apply 'encode-time
12187 (org-read-date-analyze
12188 time default-time (decode-time default-time)))
12189 ;; If necessary, get the time from the user
12190 (or time (org-read-date nil 'to-time nil nil
12191 default-time default-input)))))
12193 (when (and org-insert-labeled-timestamps-at-point
12194 (member what '(scheduled deadline)))
12195 (insert
12196 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12197 (org-insert-time-stamp time org-time-was-given
12198 nil nil nil (list org-end-time-was-given))
12199 (setq what nil))
12200 (save-excursion
12201 (save-restriction
12202 (let (col list elt ts buffer-invisibility-spec)
12203 (org-back-to-heading t)
12204 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12205 (goto-char (match-end 1))
12206 (setq col (current-column))
12207 (goto-char (match-end 0))
12208 (if (eobp) (insert "\n") (forward-char 1))
12209 (when (and (not what)
12210 (not (looking-at
12211 (concat "[ \t]*"
12212 org-keyword-time-not-clock-regexp))))
12213 ;; Nothing to add, nothing to remove...... :-)
12214 (throw 'exit nil))
12215 (if (and (not (looking-at org-outline-regexp))
12216 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12217 "[^\r\n]*"))
12218 (not (equal (match-string 1) org-clock-string)))
12219 (narrow-to-region (match-beginning 0) (match-end 0))
12220 (insert-before-markers "\n")
12221 (backward-char 1)
12222 (narrow-to-region (point) (point))
12223 (and org-adapt-indentation (org-indent-to-column col)))
12224 ;; Check if we have to remove something.
12225 (setq list (cons what remove))
12226 (while list
12227 (setq elt (pop list))
12228 (when (or (and (eq elt 'scheduled)
12229 (re-search-forward org-scheduled-time-regexp nil t))
12230 (and (eq elt 'deadline)
12231 (re-search-forward org-deadline-time-regexp nil t))
12232 (and (eq elt 'closed)
12233 (re-search-forward org-closed-time-regexp nil t)))
12234 (replace-match "")
12235 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12236 (and (looking-at "[ \t]+") (replace-match ""))
12237 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12238 (when what
12239 (insert
12240 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12241 (cond ((eq what 'scheduled) org-scheduled-string)
12242 ((eq what 'deadline) org-deadline-string)
12243 ((eq what 'closed) org-closed-string))
12244 " ")
12245 (setq ts (org-insert-time-stamp
12246 time
12247 (or org-time-was-given
12248 (and (eq what 'closed) org-log-done-with-time))
12249 (eq what 'closed)
12250 nil nil (list org-end-time-was-given)))
12251 (insert
12252 (if (not (or (bolp) (eq (char-before) ?\ )
12253 (memq (char-after) '(32 10))
12254 (eobp))) " " ""))
12255 (end-of-line 1))
12256 (goto-char (point-min))
12257 (widen)
12258 (if (and (looking-at "[ \t]*\n")
12259 (equal (char-before) ?\n))
12260 (delete-region (1- (point)) (point-at-eol)))
12261 ts))))))
12263 (defvar org-log-note-marker (make-marker))
12264 (defvar org-log-note-purpose nil)
12265 (defvar org-log-note-state nil)
12266 (defvar org-log-note-previous-state nil)
12267 (defvar org-log-note-how nil)
12268 (defvar org-log-note-extra nil)
12269 (defvar org-log-note-window-configuration nil)
12270 (defvar org-log-note-return-to (make-marker))
12271 (defvar org-log-note-effective-time nil
12272 "Remembered current time so that dynamically scoped
12273 `org-extend-today-until' affects tha timestamps in state change
12274 log")
12276 (defvar org-log-post-message nil
12277 "Message to be displayed after a log note has been stored.
12278 The auto-repeater uses this.")
12280 (defun org-add-note ()
12281 "Add a note to the current entry.
12282 This is done in the same way as adding a state change note."
12283 (interactive)
12284 (org-add-log-setup 'note nil nil 'findpos nil))
12286 (defvar org-property-end-re)
12287 (defun org-add-log-setup (&optional purpose state prev-state
12288 findpos how extra)
12289 "Set up the post command hook to take a note.
12290 If this is about to TODO state change, the new state is expected in STATE.
12291 When FINDPOS is non-nil, find the correct position for the note in
12292 the current entry. If not, assume that it can be inserted at point.
12293 HOW is an indicator what kind of note should be created.
12294 EXTRA is additional text that will be inserted into the notes buffer."
12295 (let* ((org-log-into-drawer (org-log-into-drawer))
12296 (drawer (cond ((stringp org-log-into-drawer)
12297 org-log-into-drawer)
12298 (org-log-into-drawer "LOGBOOK")
12299 (t nil))))
12300 (save-restriction
12301 (save-excursion
12302 (when findpos
12303 (org-back-to-heading t)
12304 (narrow-to-region (point) (save-excursion
12305 (outline-next-heading) (point)))
12306 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12307 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12308 "[^\r\n]*\\)?"))
12309 (goto-char (match-end 0))
12310 (cond
12311 (drawer
12312 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12313 nil t)
12314 (progn
12315 (goto-char (match-end 0))
12316 (or org-log-states-order-reversed
12317 (and (re-search-forward org-property-end-re nil t)
12318 (goto-char (1- (match-beginning 0))))))
12319 (insert "\n:" drawer ":\n:END:")
12320 (beginning-of-line 0)
12321 (org-indent-line-function)
12322 (beginning-of-line 2)
12323 (org-indent-line-function)
12324 (end-of-line 0)))
12325 ((and org-log-state-notes-insert-after-drawers
12326 (save-excursion
12327 (forward-line) (looking-at org-drawer-regexp)))
12328 (forward-line)
12329 (while (looking-at org-drawer-regexp)
12330 (goto-char (match-end 0))
12331 (re-search-forward org-property-end-re (point-max) t)
12332 (forward-line))
12333 (forward-line -1)))
12334 (unless org-log-states-order-reversed
12335 (and (= (char-after) ?\n) (forward-char 1))
12336 (org-skip-over-state-notes)
12337 (skip-chars-backward " \t\n\r")))
12338 (move-marker org-log-note-marker (point))
12339 (setq org-log-note-purpose purpose
12340 org-log-note-state state
12341 org-log-note-previous-state prev-state
12342 org-log-note-how how
12343 org-log-note-extra extra
12344 org-log-note-effective-time (org-current-effective-time))
12345 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12347 (defun org-skip-over-state-notes ()
12348 "Skip past the list of State notes in an entry."
12349 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12350 (when (ignore-errors (goto-char (org-in-item-p)))
12351 (let* ((struct (org-list-struct))
12352 (prevs (org-list-prevs-alist struct)))
12353 (while (looking-at "[ \t]*- State")
12354 (goto-char (or (org-list-get-next-item (point) struct prevs)
12355 (org-list-get-item-end (point) struct)))))))
12357 (defun org-add-log-note (&optional purpose)
12358 "Pop up a window for taking a note, and add this note later at point."
12359 (remove-hook 'post-command-hook 'org-add-log-note)
12360 (setq org-log-note-window-configuration (current-window-configuration))
12361 (delete-other-windows)
12362 (move-marker org-log-note-return-to (point))
12363 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12364 (goto-char org-log-note-marker)
12365 (org-switch-to-buffer-other-window "*Org Note*")
12366 (erase-buffer)
12367 (if (memq org-log-note-how '(time state))
12368 (let (current-prefix-arg) (org-store-log-note))
12369 (let ((org-inhibit-startup t)) (org-mode))
12370 (insert (format "# Insert note for %s.
12371 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12372 (cond
12373 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12374 ((eq org-log-note-purpose 'done) "closed todo item")
12375 ((eq org-log-note-purpose 'state)
12376 (format "state change from \"%s\" to \"%s\""
12377 (or org-log-note-previous-state "")
12378 (or org-log-note-state "")))
12379 ((eq org-log-note-purpose 'reschedule)
12380 "rescheduling")
12381 ((eq org-log-note-purpose 'delschedule)
12382 "no longer scheduled")
12383 ((eq org-log-note-purpose 'redeadline)
12384 "changing deadline")
12385 ((eq org-log-note-purpose 'deldeadline)
12386 "removing deadline")
12387 ((eq org-log-note-purpose 'refile)
12388 "refiling")
12389 ((eq org-log-note-purpose 'note)
12390 "this entry")
12391 (t (error "This should not happen")))))
12392 (if org-log-note-extra (insert org-log-note-extra))
12393 (org-set-local 'org-finish-function 'org-store-log-note)
12394 (run-hooks 'org-log-buffer-setup-hook)))
12396 (defvar org-note-abort nil) ; dynamically scoped
12397 (defun org-store-log-note ()
12398 "Finish taking a log note, and insert it to where it belongs."
12399 (let ((txt (buffer-string))
12400 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12401 lines ind bul)
12402 (kill-buffer (current-buffer))
12403 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12404 (setq txt (replace-match "" t t txt)))
12405 (if (string-match "\\s-+\\'" txt)
12406 (setq txt (replace-match "" t t txt)))
12407 (setq lines (org-split-string txt "\n"))
12408 (when (and note (string-match "\\S-" note))
12409 (setq note
12410 (org-replace-escapes
12411 note
12412 (list (cons "%u" (user-login-name))
12413 (cons "%U" user-full-name)
12414 (cons "%t" (format-time-string
12415 (org-time-stamp-format 'long 'inactive)
12416 org-log-note-effective-time))
12417 (cons "%T" (format-time-string
12418 (org-time-stamp-format 'long nil)
12419 org-log-note-effective-time))
12420 (cons "%d" (format-time-string
12421 (org-time-stamp-format nil 'inactive)
12422 org-log-note-effective-time))
12423 (cons "%D" (format-time-string
12424 (org-time-stamp-format nil nil)
12425 org-log-note-effective-time))
12426 (cons "%s" (if org-log-note-state
12427 (concat "\"" org-log-note-state "\"")
12428 ""))
12429 (cons "%S" (if org-log-note-previous-state
12430 (concat "\"" org-log-note-previous-state "\"")
12431 "\"\"")))))
12432 (if lines (setq note (concat note " \\\\")))
12433 (push note lines))
12434 (when (or current-prefix-arg org-note-abort)
12435 (when org-log-into-drawer
12436 (org-remove-empty-drawer-at
12437 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12438 org-log-note-marker))
12439 (setq lines nil))
12440 (when lines
12441 (with-current-buffer (marker-buffer org-log-note-marker)
12442 (save-excursion
12443 (goto-char org-log-note-marker)
12444 (move-marker org-log-note-marker nil)
12445 (end-of-line 1)
12446 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12447 (setq ind (save-excursion
12448 (if (ignore-errors (goto-char (org-in-item-p)))
12449 (let ((struct (org-list-struct)))
12450 (org-list-get-ind
12451 (org-list-get-top-point struct) struct))
12452 (skip-chars-backward " \r\t\n")
12453 (cond
12454 ((and (org-at-heading-p)
12455 org-adapt-indentation)
12456 (1+ (org-current-level)))
12457 ((org-at-heading-p) 0)
12458 (t (org-get-indentation))))))
12459 (setq bul (org-list-bullet-string "-"))
12460 (org-indent-line-to ind)
12461 (insert bul (pop lines))
12462 (let ((ind-body (+ (length bul) ind)))
12463 (while lines
12464 (insert "\n")
12465 (org-indent-line-to ind-body)
12466 (insert (pop lines))))
12467 (message "Note stored")
12468 (org-back-to-heading t)
12469 (org-cycle-hide-drawers 'children)))))
12470 (set-window-configuration org-log-note-window-configuration)
12471 (with-current-buffer (marker-buffer org-log-note-return-to)
12472 (goto-char org-log-note-return-to))
12473 (move-marker org-log-note-return-to nil)
12474 (and org-log-post-message (message "%s" org-log-post-message)))
12476 (defun org-remove-empty-drawer-at (drawer pos)
12477 "Remove an empty drawer DRAWER at position POS.
12478 POS may also be a marker."
12479 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12480 (save-excursion
12481 (save-restriction
12482 (widen)
12483 (goto-char pos)
12484 (if (org-in-regexp
12485 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12486 (replace-match ""))))))
12488 (defun org-sparse-tree (&optional arg)
12489 "Create a sparse tree, prompt for the details.
12490 This command can create sparse trees. You first need to select the type
12491 of match used to create the tree:
12493 t Show all TODO entries.
12494 T Show entries with a specific TODO keyword.
12495 m Show entries selected by a tags/property match.
12496 p Enter a property name and its value (both with completion on existing
12497 names/values) and show entries with that property.
12498 r Show entries matching a regular expression (`/' can be used as well)
12499 d Show deadlines due within `org-deadline-warning-days'.
12500 b Show deadlines and scheduled items before a date.
12501 a Show deadlines and scheduled items after a date."
12502 (interactive "P")
12503 (let (ans kwd value)
12504 (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")
12505 (setq ans (read-char-exclusive))
12506 (cond
12507 ((equal ans ?d)
12508 (call-interactively 'org-check-deadlines))
12509 ((equal ans ?b)
12510 (call-interactively 'org-check-before-date))
12511 ((equal ans ?a)
12512 (call-interactively 'org-check-after-date))
12513 ((equal ans ?D)
12514 (call-interactively 'org-check-dates-range))
12515 ((equal ans ?t)
12516 (org-show-todo-tree nil))
12517 ((equal ans ?T)
12518 (org-show-todo-tree '(4)))
12519 ((member ans '(?T ?m))
12520 (call-interactively 'org-match-sparse-tree))
12521 ((member ans '(?p ?P))
12522 (setq kwd (org-icompleting-read "Property: "
12523 (mapcar 'list (org-buffer-property-keys))))
12524 (setq value (org-icompleting-read "Value: "
12525 (mapcar 'list (org-property-values kwd))))
12526 (unless (string-match "\\`{.*}\\'" value)
12527 (setq value (concat "\"" value "\"")))
12528 (org-match-sparse-tree arg (concat kwd "=" value)))
12529 ((member ans '(?r ?R ?/))
12530 (call-interactively 'org-occur))
12531 (t (error "No such sparse tree command \"%c\"" ans)))))
12533 (defvar org-occur-highlights nil
12534 "List of overlays used for occur matches.")
12535 (make-variable-buffer-local 'org-occur-highlights)
12536 (defvar org-occur-parameters nil
12537 "Parameters of the active org-occur calls.
12538 This is a list, each call to org-occur pushes as cons cell,
12539 containing the regular expression and the callback, onto the list.
12540 The list can contain several entries if `org-occur' has been called
12541 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12542 will only contain one set of parameters. When the highlights are
12543 removed (for example with `C-c C-c', or with the next edit (depending
12544 on `org-remove-highlights-with-change'), this variable is emptied
12545 as well.")
12546 (make-variable-buffer-local 'org-occur-parameters)
12548 (defun org-occur (regexp &optional keep-previous callback)
12549 "Make a compact tree which shows all matches of REGEXP.
12550 The tree will show the lines where the regexp matches, and all higher
12551 headlines above the match. It will also show the heading after the match,
12552 to make sure editing the matching entry is easy.
12553 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12554 call to `org-occur' will be kept, to allow stacking of calls to this
12555 command.
12556 If CALLBACK is non-nil, it is a function which is called to confirm
12557 that the match should indeed be shown."
12558 (interactive "sRegexp: \nP")
12559 (when (equal regexp "")
12560 (error "Regexp cannot be empty"))
12561 (unless keep-previous
12562 (org-remove-occur-highlights nil nil t))
12563 (push (cons regexp callback) org-occur-parameters)
12564 (let ((cnt 0))
12565 (save-excursion
12566 (goto-char (point-min))
12567 (if (or (not keep-previous) ; do not want to keep
12568 (not org-occur-highlights)) ; no previous matches
12569 ;; hide everything
12570 (org-overview))
12571 (while (re-search-forward regexp nil t)
12572 (when (or (not callback)
12573 (save-match-data (funcall callback)))
12574 (setq cnt (1+ cnt))
12575 (when org-highlight-sparse-tree-matches
12576 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12577 (org-show-context 'occur-tree))))
12578 (when org-remove-highlights-with-change
12579 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12580 nil 'local))
12581 (unless org-sparse-tree-open-archived-trees
12582 (org-hide-archived-subtrees (point-min) (point-max)))
12583 (run-hooks 'org-occur-hook)
12584 (if (org-called-interactively-p 'interactive)
12585 (message "%d match(es) for regexp %s" cnt regexp))
12586 cnt))
12588 (defun org-occur-next-match (&optional n reset)
12589 "Function for `next-error-function' to find sparse tree matches.
12590 N is the number of matches to move, when negative move backwards.
12591 RESET is entirely ignored - this function always goes back to the
12592 starting point when no match is found."
12593 (let* ((limit (if (< n 0) (point-min) (point-max)))
12594 (search-func (if (< n 0)
12595 'previous-single-char-property-change
12596 'next-single-char-property-change))
12597 (n (abs n))
12598 (pos (point))
12600 (catch 'exit
12601 (while (setq p1 (funcall search-func (point) 'org-type))
12602 (when (equal p1 limit)
12603 (goto-char pos)
12604 (error "No more matches"))
12605 (when (equal (get-char-property p1 'org-type) 'org-occur)
12606 (setq n (1- n))
12607 (when (= n 0)
12608 (goto-char p1)
12609 (throw 'exit (point))))
12610 (goto-char p1))
12611 (goto-char p1)
12612 (error "No more matches"))))
12614 (defun org-show-context (&optional key)
12615 "Make sure point and context are visible.
12616 How much context is shown depends upon the variables
12617 `org-show-hierarchy-above', `org-show-following-heading',
12618 `org-show-entry-below' and `org-show-siblings'."
12619 (let ((heading-p (org-at-heading-p t))
12620 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12621 (following-p (org-get-alist-option org-show-following-heading key))
12622 (entry-p (org-get-alist-option org-show-entry-below key))
12623 (siblings-p (org-get-alist-option org-show-siblings key)))
12624 (catch 'exit
12625 ;; Show heading or entry text
12626 (if (and heading-p (not entry-p))
12627 (org-flag-heading nil) ; only show the heading
12628 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12629 (org-show-hidden-entry))) ; show entire entry
12630 (when following-p
12631 ;; Show next sibling, or heading below text
12632 (save-excursion
12633 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12634 (org-flag-heading nil))))
12635 (when siblings-p (org-show-siblings))
12636 (when hierarchy-p
12637 ;; show all higher headings, possibly with siblings
12638 (save-excursion
12639 (while (and (condition-case nil
12640 (progn (org-up-heading-all 1) t)
12641 (error nil))
12642 (not (bobp)))
12643 (org-flag-heading nil)
12644 (when siblings-p (org-show-siblings))))))))
12646 (defvar org-reveal-start-hook nil
12647 "Hook run before revealing a location.")
12649 (defun org-reveal (&optional siblings)
12650 "Show current entry, hierarchy above it, and the following headline.
12651 This can be used to show a consistent set of context around locations
12652 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12653 not t for the search context.
12655 With optional argument SIBLINGS, on each level of the hierarchy all
12656 siblings are shown. This repairs the tree structure to what it would
12657 look like when opened with hierarchical calls to `org-cycle'.
12658 With double optional argument \\[universal-argument] \\[universal-argument], \
12659 go to the parent and show the
12660 entire tree."
12661 (interactive "P")
12662 (run-hooks 'org-reveal-start-hook)
12663 (let ((org-show-hierarchy-above t)
12664 (org-show-following-heading t)
12665 (org-show-siblings (if siblings t org-show-siblings)))
12666 (org-show-context nil))
12667 (when (equal siblings '(16))
12668 (save-excursion
12669 (when (org-up-heading-safe)
12670 (org-show-subtree)
12671 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12673 (defun org-highlight-new-match (beg end)
12674 "Highlight from BEG to END and mark the highlight is an occur headline."
12675 (let ((ov (make-overlay beg end)))
12676 (overlay-put ov 'face 'secondary-selection)
12677 (overlay-put ov 'org-type 'org-occur)
12678 (push ov org-occur-highlights)))
12680 (defun org-remove-occur-highlights (&optional beg end noremove)
12681 "Remove the occur highlights from the buffer.
12682 BEG and END are ignored. If NOREMOVE is nil, remove this function
12683 from the `before-change-functions' in the current buffer."
12684 (interactive)
12685 (unless org-inhibit-highlight-removal
12686 (mapc 'delete-overlay org-occur-highlights)
12687 (setq org-occur-highlights nil)
12688 (setq org-occur-parameters nil)
12689 (unless noremove
12690 (remove-hook 'before-change-functions
12691 'org-remove-occur-highlights 'local))))
12693 ;;;; Priorities
12695 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12696 "Regular expression matching the priority indicator.")
12698 (defvar org-remove-priority-next-time nil)
12700 (defun org-priority-up ()
12701 "Increase the priority of the current item."
12702 (interactive)
12703 (org-priority 'up))
12705 (defun org-priority-down ()
12706 "Decrease the priority of the current item."
12707 (interactive)
12708 (org-priority 'down))
12710 (defun org-priority (&optional action)
12711 "Change the priority of an item by ARG.
12712 ACTION can be `set', `up', `down', or a character."
12713 (interactive)
12714 (unless org-enable-priority-commands
12715 (error "Priority commands are disabled"))
12716 (setq action (or action 'set))
12717 (let (current new news have remove)
12718 (save-excursion
12719 (org-back-to-heading t)
12720 (if (looking-at org-priority-regexp)
12721 (setq current (string-to-char (match-string 2))
12722 have t))
12723 (cond
12724 ((eq action 'remove)
12725 (setq remove t new ?\ ))
12726 ((or (eq action 'set)
12727 (if (featurep 'xemacs) (characterp action) (integerp action)))
12728 (if (not (eq action 'set))
12729 (setq new action)
12730 (message "Priority %c-%c, SPC to remove: "
12731 org-highest-priority org-lowest-priority)
12732 (save-match-data
12733 (setq new (read-char-exclusive))))
12734 (if (and (= (upcase org-highest-priority) org-highest-priority)
12735 (= (upcase org-lowest-priority) org-lowest-priority))
12736 (setq new (upcase new)))
12737 (cond ((equal new ?\ ) (setq remove t))
12738 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12739 (error "Priority must be between `%c' and `%c'"
12740 org-highest-priority org-lowest-priority))))
12741 ((eq action 'up)
12742 (setq new (if have
12743 (1- current) ; normal cycling
12744 ;; last priority was empty
12745 (if (eq last-command this-command)
12746 org-lowest-priority ; wrap around empty to lowest
12747 ;; default
12748 (if org-priority-start-cycle-with-default
12749 org-default-priority
12750 (1- org-default-priority))))))
12751 ((eq action 'down)
12752 (setq new (if have
12753 (1+ current) ; normal cycling
12754 ;; last priority was empty
12755 (if (eq last-command this-command)
12756 org-highest-priority ; wrap around empty to highest
12757 ;; default
12758 (if org-priority-start-cycle-with-default
12759 org-default-priority
12760 (1+ org-default-priority))))))
12761 (t (error "Invalid action")))
12762 (if (or (< (upcase new) org-highest-priority)
12763 (> (upcase new) org-lowest-priority))
12764 (if (and (memq action '(up down))
12765 (not have) (not (eq last-command this-command)))
12766 ;; `new' is from default priority
12767 (error
12768 "The default can not be set, see `org-default-priority' why")
12769 ;; normal cycling: `new' is beyond highest/lowest priority
12770 ;; and is wrapped around to the empty priority
12771 (setq remove t)))
12772 (setq news (format "%c" new))
12773 (if have
12774 (if remove
12775 (replace-match "" t t nil 1)
12776 (replace-match news t t nil 2))
12777 (if remove
12778 (error "No priority cookie found in line")
12779 (let ((case-fold-search nil))
12780 (looking-at org-todo-line-regexp))
12781 (if (match-end 2)
12782 (progn
12783 (goto-char (match-end 2))
12784 (insert " [#" news "]"))
12785 (goto-char (match-beginning 3))
12786 (insert "[#" news "] "))))
12787 (org-preserve-lc (org-set-tags nil 'align)))
12788 (if remove
12789 (message "Priority removed")
12790 (message "Priority of current item set to %s" news))))
12792 (defun org-get-priority (s)
12793 "Find priority cookie and return priority."
12794 (if (functionp org-get-priority-function)
12795 (funcall org-get-priority-function)
12796 (save-match-data
12797 (if (not (string-match org-priority-regexp s))
12798 (* 1000 (- org-lowest-priority org-default-priority))
12799 (* 1000 (- org-lowest-priority
12800 (string-to-char (match-string 2 s))))))))
12802 ;;;; Tags
12804 (defvar org-agenda-archives-mode)
12805 (defvar org-map-continue-from nil
12806 "Position from where mapping should continue.
12807 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12809 (defvar org-scanner-tags nil
12810 "The current tag list while the tags scanner is running.")
12811 (defvar org-trust-scanner-tags nil
12812 "Should `org-get-tags-at' use the tags for the scanner.
12813 This is for internal dynamical scoping only.
12814 When this is non-nil, the function `org-get-tags-at' will return the value
12815 of `org-scanner-tags' instead of building the list by itself. This
12816 can lead to large speed-ups when the tags scanner is used in a file with
12817 many entries, and when the list of tags is retrieved, for example to
12818 obtain a list of properties. Building the tags list for each entry in such
12819 a file becomes an N^2 operation - but with this variable set, it scales
12820 as N.")
12822 (defun org-scan-tags (action matcher &optional todo-only start-level)
12823 "Scan headline tags with inheritance and produce output ACTION.
12825 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12826 or `agenda' to produce an entry list for an agenda view. It can also be
12827 a Lisp form or a function that should be called at each matched headline, in
12828 this case the return value is a list of all return values from these calls.
12830 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12831 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12832 only lines with a TODO keyword are included in the output.
12834 START-LEVEL can be a string with asterisks, reducing the scope to
12835 headlines matching this string."
12836 (require 'org-agenda)
12837 (let* ((re (concat "^"
12838 (if start-level
12839 ;; Get the correct level to match
12840 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12841 org-outline-regexp)
12842 " *\\(\\<\\("
12843 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12844 (org-re
12845 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12846 (props (list 'face 'default
12847 'done-face 'org-agenda-done
12848 'undone-face 'default
12849 'mouse-face 'highlight
12850 'org-not-done-regexp org-not-done-regexp
12851 'org-todo-regexp org-todo-regexp
12852 'org-complex-heading-regexp org-complex-heading-regexp
12853 'help-echo
12854 (format "mouse-2 or RET jump to org file %s"
12855 (abbreviate-file-name
12856 (or (buffer-file-name (buffer-base-buffer))
12857 (buffer-name (buffer-base-buffer)))))))
12858 (case-fold-search nil)
12859 (org-map-continue-from nil)
12860 lspos tags tags-list
12861 (tags-alist (list (cons 0 org-file-tags)))
12862 (llast 0) rtn rtn1 level category i txt
12863 todo marker entry priority)
12864 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12865 (setq action (list 'lambda nil action)))
12866 (save-excursion
12867 (goto-char (point-min))
12868 (when (eq action 'sparse-tree)
12869 (org-overview)
12870 (org-remove-occur-highlights))
12871 (while (re-search-forward re nil t)
12872 (setq org-map-continue-from nil)
12873 (catch :skip
12874 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12875 tags (if (match-end 4) (org-match-string-no-properties 4)))
12876 (goto-char (setq lspos (match-beginning 0)))
12877 (setq level (org-reduced-level (funcall outline-level))
12878 category (org-get-category))
12879 (setq i llast llast level)
12880 ;; remove tag lists from same and sublevels
12881 (while (>= i level)
12882 (when (setq entry (assoc i tags-alist))
12883 (setq tags-alist (delete entry tags-alist)))
12884 (setq i (1- i)))
12885 ;; add the next tags
12886 (when tags
12887 (setq tags (org-split-string tags ":")
12888 tags-alist
12889 (cons (cons level tags) tags-alist)))
12890 ;; compile tags for current headline
12891 (setq tags-list
12892 (if org-use-tag-inheritance
12893 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12894 tags)
12895 org-scanner-tags tags-list)
12896 (when org-use-tag-inheritance
12897 (setcdr (car tags-alist)
12898 (mapcar (lambda (x)
12899 (setq x (copy-sequence x))
12900 (org-add-prop-inherited x))
12901 (cdar tags-alist))))
12902 (when (and tags org-use-tag-inheritance
12903 (or (not (eq t org-use-tag-inheritance))
12904 org-tags-exclude-from-inheritance))
12905 ;; selective inheritance, remove uninherited ones
12906 (setcdr (car tags-alist)
12907 (org-remove-uninherited-tags (cdar tags-alist))))
12908 (when (and
12910 ;; eval matcher only when the todo condition is OK
12911 (and (or (not todo-only) (member todo org-not-done-keywords))
12912 (let ((case-fold-search t) (org-trust-scanner-tags t))
12913 (eval matcher)))
12915 ;; Call the skipper, but return t if it does not skip,
12916 ;; so that the `and' form continues evaluating
12917 (progn
12918 (unless (eq action 'sparse-tree) (org-agenda-skip))
12921 ;; Check if timestamps are deselecting this entry
12922 (or (not todo-only)
12923 (and (member todo org-not-done-keywords)
12924 (or (not org-agenda-tags-todo-honor-ignore-options)
12925 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12927 ;; Extra check for the archive tag
12928 ;; FIXME: Does the skipper already do this????
12930 (not (member org-archive-tag tags-list))
12931 ;; we have an archive tag, should we use this anyway?
12932 (or (not org-agenda-skip-archived-trees)
12933 (and (eq action 'agenda) org-agenda-archives-mode))))
12935 ;; select this headline
12937 (cond
12938 ((eq action 'sparse-tree)
12939 (and org-highlight-sparse-tree-matches
12940 (org-get-heading) (match-end 0)
12941 (org-highlight-new-match
12942 (match-beginning 1) (match-end 1)))
12943 (org-show-context 'tags-tree))
12944 ((eq action 'agenda)
12945 (setq txt (org-agenda-format-item
12947 (concat
12948 (if (eq org-tags-match-list-sublevels 'indented)
12949 (make-string (1- level) ?.) "")
12950 (org-get-heading))
12951 category
12952 tags-list)
12953 priority (org-get-priority txt))
12954 (goto-char lspos)
12955 (setq marker (org-agenda-new-marker))
12956 (org-add-props txt props
12957 'org-marker marker 'org-hd-marker marker 'org-category category
12958 'todo-state todo
12959 'priority priority 'type "tagsmatch")
12960 (push txt rtn))
12961 ((functionp action)
12962 (setq org-map-continue-from nil)
12963 (save-excursion
12964 (setq rtn1 (funcall action))
12965 (push rtn1 rtn)))
12966 (t (error "Invalid action")))
12968 ;; if we are to skip sublevels, jump to end of subtree
12969 (unless org-tags-match-list-sublevels
12970 (org-end-of-subtree t)
12971 (backward-char 1))))
12972 ;; Get the correct position from where to continue
12973 (if org-map-continue-from
12974 (goto-char org-map-continue-from)
12975 (and (= (point) lspos) (end-of-line 1)))))
12976 (when (and (eq action 'sparse-tree)
12977 (not org-sparse-tree-open-archived-trees))
12978 (org-hide-archived-subtrees (point-min) (point-max)))
12979 (nreverse rtn)))
12981 (defun org-remove-uninherited-tags (tags)
12982 "Remove all tags that are not inherited from the list TAGS."
12983 (cond
12984 ((eq org-use-tag-inheritance t)
12985 (if org-tags-exclude-from-inheritance
12986 (org-delete-all org-tags-exclude-from-inheritance tags)
12987 tags))
12988 ((not org-use-tag-inheritance) nil)
12989 ((stringp org-use-tag-inheritance)
12990 (delq nil (mapcar
12991 (lambda (x)
12992 (if (and (string-match org-use-tag-inheritance x)
12993 (not (member x org-tags-exclude-from-inheritance)))
12994 x nil))
12995 tags)))
12996 ((listp org-use-tag-inheritance)
12997 (delq nil (mapcar
12998 (lambda (x)
12999 (if (member x org-use-tag-inheritance) x nil))
13000 tags)))))
13002 (defvar todo-only) ;; dynamically scoped
13004 (defun org-match-sparse-tree (&optional todo-only match)
13005 "Create a sparse tree according to tags string MATCH.
13006 MATCH can contain positive and negative selection of tags, like
13007 \"+WORK+URGENT-WITHBOSS\".
13008 If optional argument TODO-ONLY is non-nil, only select lines that are
13009 also TODO lines."
13010 (interactive "P")
13011 (org-prepare-agenda-buffers (list (current-buffer)))
13012 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13014 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13016 (defvar org-cached-props nil)
13017 (defun org-cached-entry-get (pom property)
13018 (if (or (eq t org-use-property-inheritance)
13019 (and (stringp org-use-property-inheritance)
13020 (string-match org-use-property-inheritance property))
13021 (and (listp org-use-property-inheritance)
13022 (member property org-use-property-inheritance)))
13023 ;; Caching is not possible, check it directly
13024 (org-entry-get pom property 'inherit)
13025 ;; Get all properties, so that we can do complicated checks easily
13026 (cdr (assoc property (or org-cached-props
13027 (setq org-cached-props
13028 (org-entry-properties pom)))))))
13030 (defun org-global-tags-completion-table (&optional files)
13031 "Return the list of all tags in all agenda buffer/files.
13032 Optional FILES argument is a list of files to which can be used
13033 instead of the agenda files."
13034 (save-excursion
13035 (org-uniquify
13036 (delq nil
13037 (apply 'append
13038 (mapcar
13039 (lambda (file)
13040 (set-buffer (find-file-noselect file))
13041 (append (org-get-buffer-tags)
13042 (mapcar (lambda (x) (if (stringp (car-safe x))
13043 (list (car-safe x)) nil))
13044 org-tag-alist)))
13045 (if (and files (car files))
13046 files
13047 (org-agenda-files))))))))
13049 (defun org-make-tags-matcher (match)
13050 "Create the TAGS/TODO matcher form for the selection string MATCH."
13051 ;; todo-only is scoped dynamically into this function, and the function
13052 ;; may change it if the matcher asks for it.
13053 (unless match
13054 ;; Get a new match request, with completion
13055 (let ((org-last-tags-completion-table
13056 (org-global-tags-completion-table)))
13057 (setq match (org-completing-read-no-i
13058 "Match: " 'org-tags-completion-function nil nil nil
13059 'org-tags-history))))
13061 ;; Parse the string and create a lisp form
13062 (let ((match0 match)
13063 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13064 minus tag mm
13065 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13066 orterms term orlist re-p str-p level-p level-op time-p
13067 prop-p pn pv po gv rest)
13068 (if (string-match "/+" match)
13069 ;; match contains also a todo-matching request
13070 (progn
13071 (setq tagsmatch (substring match 0 (match-beginning 0))
13072 todomatch (substring match (match-end 0)))
13073 (if (string-match "^!" todomatch)
13074 (setq todo-only t todomatch (substring todomatch 1)))
13075 (if (string-match "^\\s-*$" todomatch)
13076 (setq todomatch nil)))
13077 ;; only matching tags
13078 (setq tagsmatch match todomatch nil))
13080 ;; Make the tags matcher
13081 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13082 (setq tagsmatcher t)
13083 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13084 (while (setq term (pop orterms))
13085 (while (and (equal (substring term -1) "\\") orterms)
13086 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13087 (while (string-match re term)
13088 (setq rest (substring term (match-end 0))
13089 minus (and (match-end 1)
13090 (equal (match-string 1 term) "-"))
13091 tag (save-match-data (replace-regexp-in-string
13092 "\\\\-" "-"
13093 (match-string 2 term)))
13094 re-p (equal (string-to-char tag) ?{)
13095 level-p (match-end 4)
13096 prop-p (match-end 5)
13097 mm (cond
13098 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13099 (level-p
13100 (setq level-op (org-op-to-function (match-string 3 term)))
13101 `(,level-op level ,(string-to-number
13102 (match-string 4 term))))
13103 (prop-p
13104 (setq pn (match-string 5 term)
13105 po (match-string 6 term)
13106 pv (match-string 7 term)
13107 re-p (equal (string-to-char pv) ?{)
13108 str-p (equal (string-to-char pv) ?\")
13109 time-p (save-match-data
13110 (string-match "^\"[[<].*[]>]\"$" pv))
13111 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13112 (if time-p (setq pv (org-matcher-time pv)))
13113 (setq po (org-op-to-function po (if time-p 'time str-p)))
13114 (cond
13115 ((equal pn "CATEGORY")
13116 (setq gv '(get-text-property (point) 'org-category)))
13117 ((equal pn "TODO")
13118 (setq gv 'todo))
13120 (setq gv `(org-cached-entry-get nil ,pn))))
13121 (if re-p
13122 (if (eq po 'org<>)
13123 `(not (string-match ,pv (or ,gv "")))
13124 `(string-match ,pv (or ,gv "")))
13125 (if str-p
13126 `(,po (or ,gv "") ,pv)
13127 `(,po (string-to-number (or ,gv ""))
13128 ,(string-to-number pv) ))))
13129 (t `(member ,tag tags-list)))
13130 mm (if minus (list 'not mm) mm)
13131 term rest)
13132 (push mm tagsmatcher))
13133 (push (if (> (length tagsmatcher) 1)
13134 (cons 'and tagsmatcher)
13135 (car tagsmatcher))
13136 orlist)
13137 (setq tagsmatcher nil))
13138 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13139 (setq tagsmatcher
13140 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13141 ;; Make the todo matcher
13142 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13143 (setq todomatcher t)
13144 (setq orterms (org-split-string todomatch "|") orlist nil)
13145 (while (setq term (pop orterms))
13146 (while (string-match re term)
13147 (setq minus (and (match-end 1)
13148 (equal (match-string 1 term) "-"))
13149 kwd (match-string 2 term)
13150 re-p (equal (string-to-char kwd) ?{)
13151 term (substring term (match-end 0))
13152 mm (if re-p
13153 `(string-match ,(substring kwd 1 -1) todo)
13154 (list 'equal 'todo kwd))
13155 mm (if minus (list 'not mm) mm))
13156 (push mm todomatcher))
13157 (push (if (> (length todomatcher) 1)
13158 (cons 'and todomatcher)
13159 (car todomatcher))
13160 orlist)
13161 (setq todomatcher nil))
13162 (setq todomatcher (if (> (length orlist) 1)
13163 (cons 'or orlist) (car orlist))))
13165 ;; Return the string and lisp forms of the matcher
13166 (setq matcher (if todomatcher
13167 (list 'and tagsmatcher todomatcher)
13168 tagsmatcher))
13169 (cons match0 matcher)))
13171 (defun org-op-to-function (op &optional stringp)
13172 "Turn an operator into the appropriate function."
13173 (setq op
13174 (cond
13175 ((equal op "<" ) '(< string< org-time<))
13176 ((equal op ">" ) '(> org-string> org-time>))
13177 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13178 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13179 ((member op '("=" "==")) '(= string= org-time=))
13180 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13181 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13183 (defun org<> (a b) (not (= a b)))
13184 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13185 (defun org-string>= (a b) (not (string< a b)))
13186 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13187 (defun org-string<> (a b) (not (string= a b)))
13188 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13189 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13190 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13191 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13192 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13193 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13194 (defun org-2ft (s)
13195 "Convert S to a floating point time.
13196 If S is already a number, just return it. If it is a string, parse
13197 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13198 (cond
13199 ((numberp s) s)
13200 ((stringp s)
13201 (condition-case nil
13202 (float-time (apply 'encode-time (org-parse-time-string s)))
13203 (error 0.)))
13204 (t 0.)))
13206 (defun org-time-today ()
13207 "Time in seconds today at 0:00.
13208 Returns the float number of seconds since the beginning of the
13209 epoch to the beginning of today (00:00)."
13210 (float-time (apply 'encode-time
13211 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13213 (defun org-matcher-time (s)
13214 "Interpret a time comparison value."
13215 (save-match-data
13216 (cond
13217 ((string= s "<now>") (float-time))
13218 ((string= s "<today>") (org-time-today))
13219 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13220 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13221 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13222 (+ (org-time-today)
13223 (* (string-to-number (match-string 1 s))
13224 (cdr (assoc (match-string 2 s)
13225 '(("d" . 86400.0) ("w" . 604800.0)
13226 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13227 (t (org-2ft s)))))
13229 (defun org-match-any-p (re list)
13230 "Does re match any element of list?"
13231 (setq list (mapcar (lambda (x) (string-match re x)) list))
13232 (delq nil list))
13234 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13235 (defvar org-tags-overlay (make-overlay 1 1))
13236 (org-detach-overlay org-tags-overlay)
13238 (defun org-get-local-tags-at (&optional pos)
13239 "Get a list of tags defined in the current headline."
13240 (org-get-tags-at pos 'local))
13242 (defun org-get-local-tags ()
13243 "Get a list of tags defined in the current headline."
13244 (org-get-tags-at nil 'local))
13246 (defun org-get-tags-at (&optional pos local)
13247 "Get a list of all headline tags applicable at POS.
13248 POS defaults to point. If tags are inherited, the list contains
13249 the targets in the same sequence as the headlines appear, i.e.
13250 the tags of the current headline come last.
13251 When LOCAL is non-nil, only return tags from the current headline,
13252 ignore inherited ones."
13253 (interactive)
13254 (if (and org-trust-scanner-tags
13255 (or (not pos) (equal pos (point)))
13256 (not local))
13257 org-scanner-tags
13258 (let (tags ltags lastpos parent)
13259 (save-excursion
13260 (save-restriction
13261 (widen)
13262 (goto-char (or pos (point)))
13263 (save-match-data
13264 (catch 'done
13265 (condition-case nil
13266 (progn
13267 (org-back-to-heading t)
13268 (while (not (equal lastpos (point)))
13269 (setq lastpos (point))
13270 (when (looking-at
13271 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13272 (setq ltags (org-split-string
13273 (org-match-string-no-properties 1) ":"))
13274 (when parent
13275 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13276 (setq tags (append
13277 (if parent
13278 (org-remove-uninherited-tags ltags)
13279 ltags)
13280 tags)))
13281 (or org-use-tag-inheritance (throw 'done t))
13282 (if local (throw 'done t))
13283 (or (org-up-heading-safe) (error nil))
13284 (setq parent t)))
13285 (error nil)))))
13286 (if local
13287 tags
13288 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13290 (defun org-add-prop-inherited (s)
13291 (add-text-properties 0 (length s) '(inherited t) s)
13294 (defun org-toggle-tag (tag &optional onoff)
13295 "Toggle the tag TAG for the current line.
13296 If ONOFF is `on' or `off', don't toggle but set to this state."
13297 (let (res current)
13298 (save-excursion
13299 (org-back-to-heading t)
13300 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13301 (point-at-eol) t)
13302 (progn
13303 (setq current (match-string 1))
13304 (replace-match ""))
13305 (setq current ""))
13306 (setq current (nreverse (org-split-string current ":")))
13307 (cond
13308 ((eq onoff 'on)
13309 (setq res t)
13310 (or (member tag current) (push tag current)))
13311 ((eq onoff 'off)
13312 (or (not (member tag current)) (setq current (delete tag current))))
13313 (t (if (member tag current)
13314 (setq current (delete tag current))
13315 (setq res t)
13316 (push tag current))))
13317 (end-of-line 1)
13318 (if current
13319 (progn
13320 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13321 (org-set-tags nil t))
13322 (delete-horizontal-space))
13323 (run-hooks 'org-after-tags-change-hook))
13324 res))
13326 (defun org-align-tags-here (to-col)
13327 ;; Assumes that this is a headline
13328 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13329 (beginning-of-line 1)
13330 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13331 (< pos (match-beginning 2)))
13332 (progn
13333 (setq tags-l (- (match-end 2) (match-beginning 2)))
13334 (goto-char (match-beginning 1))
13335 (insert " ")
13336 (delete-region (point) (1+ (match-beginning 2)))
13337 (setq ncol (max (current-column)
13338 (1+ col)
13339 (if (> to-col 0)
13340 to-col
13341 (- (abs to-col) tags-l))))
13342 (setq p (point))
13343 (insert (make-string (- ncol (current-column)) ?\ ))
13344 (setq ncol (current-column))
13345 (when indent-tabs-mode (tabify p (point-at-eol)))
13346 (org-move-to-column (min ncol col) t))
13347 (goto-char pos))))
13349 (defun org-set-tags-command (&optional arg just-align)
13350 "Call the set-tags command for the current entry."
13351 (interactive "P")
13352 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13353 (org-set-tags arg just-align)
13354 (save-excursion
13355 (org-back-to-heading t)
13356 (org-set-tags arg just-align))))
13358 (defun org-set-tags-to (data)
13359 "Set the tags of the current entry to DATA, replacing the current tags.
13360 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13361 If DATA is nil or the empty string, any tags will be removed."
13362 (interactive "sTags: ")
13363 (setq data
13364 (cond
13365 ((eq data nil) "")
13366 ((equal data "") "")
13367 ((stringp data)
13368 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13369 ":"))
13370 ((listp data)
13371 (concat ":" (mapconcat 'identity data ":") ":"))
13372 (t nil)))
13373 (when data
13374 (save-excursion
13375 (org-back-to-heading t)
13376 (when (looking-at org-complex-heading-regexp)
13377 (if (match-end 5)
13378 (progn
13379 (goto-char (match-beginning 5))
13380 (insert data)
13381 (delete-region (point) (point-at-eol))
13382 (org-set-tags nil 'align))
13383 (goto-char (point-at-eol))
13384 (insert " " data)
13385 (org-set-tags nil 'align)))
13386 (beginning-of-line 1)
13387 (if (looking-at ".*?\\([ \t]+\\)$")
13388 (delete-region (match-beginning 1) (match-end 1))))))
13390 (defun org-align-all-tags ()
13391 "Align the tags i all headings."
13392 (interactive)
13393 (save-excursion
13394 (or (ignore-errors (org-back-to-heading t))
13395 (outline-next-heading))
13396 (if (org-at-heading-p)
13397 (org-set-tags t)
13398 (message "No headings"))))
13400 (defvar org-indent-indentation-per-level)
13401 (defun org-set-tags (&optional arg just-align)
13402 "Set the tags for the current headline.
13403 With prefix ARG, realign all tags in headings in the current buffer."
13404 (interactive "P")
13405 (let* ((re org-outline-regexp-bol)
13406 (current (unless arg (org-get-tags-string)))
13407 (col (current-column))
13408 (org-setting-tags t)
13409 table current-tags inherited-tags ; computed below when needed
13410 tags p0 c0 c1 rpl di tc level)
13411 (if arg
13412 (save-excursion
13413 (goto-char (point-min))
13414 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13415 (while (re-search-forward re nil t)
13416 (org-set-tags nil t)
13417 (end-of-line 1)))
13418 (message "All tags realigned to column %d" org-tags-column))
13419 (if just-align
13420 (setq tags current)
13421 ;; Get a new set of tags from the user
13422 (save-excursion
13423 (setq table (append org-tag-persistent-alist
13424 (or org-tag-alist (org-get-buffer-tags))
13425 (and
13426 org-complete-tags-always-offer-all-agenda-tags
13427 (org-global-tags-completion-table
13428 (org-agenda-files))))
13429 org-last-tags-completion-table table
13430 current-tags (org-split-string current ":")
13431 inherited-tags (nreverse
13432 (nthcdr (length current-tags)
13433 (nreverse (org-get-tags-at))))
13434 tags
13435 (if (or (eq t org-use-fast-tag-selection)
13436 (and org-use-fast-tag-selection
13437 (delq nil (mapcar 'cdr table))))
13438 (org-fast-tag-selection
13439 current-tags inherited-tags table
13440 (if org-fast-tag-selection-include-todo
13441 org-todo-key-alist))
13442 (let ((org-add-colon-after-tag-completion t))
13443 (org-trim
13444 (org-icompleting-read "Tags: "
13445 'org-tags-completion-function
13446 nil nil current 'org-tags-history))))))
13447 (while (string-match "[-+&]+" tags)
13448 ;; No boolean logic, just a list
13449 (setq tags (replace-match ":" t t tags))))
13451 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13453 (if org-tags-sort-function
13454 (setq tags (mapconcat 'identity
13455 (sort (org-split-string
13456 tags (org-re "[^[:alnum:]_@#%]+"))
13457 org-tags-sort-function) ":")))
13459 (if (string-match "\\`[\t ]*\\'" tags)
13460 (setq tags "")
13461 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13462 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13464 ;; Insert new tags at the correct column
13465 (beginning-of-line 1)
13466 (setq level (or (and (looking-at org-outline-regexp)
13467 (- (match-end 0) (point) 1))
13469 (cond
13470 ((and (equal current "") (equal tags "")))
13471 ((re-search-forward
13472 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13473 (point-at-eol) t)
13474 (if (equal tags "")
13475 (setq rpl "")
13476 (goto-char (match-beginning 0))
13477 (setq c0 (current-column)
13478 ;; compute offset for the case of org-indent-mode active
13479 di (if org-indent-mode
13480 (* (1- org-indent-indentation-per-level) (1- level))
13482 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13483 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13484 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13485 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13486 (replace-match rpl t t)
13487 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13488 tags)
13489 (t (error "Tags alignment failed")))
13490 (org-move-to-column col)
13491 (unless just-align
13492 (run-hooks 'org-after-tags-change-hook)))))
13494 (defun org-change-tag-in-region (beg end tag off)
13495 "Add or remove TAG for each entry in the region.
13496 This works in the agenda, and also in an org-mode buffer."
13497 (interactive
13498 (list (region-beginning) (region-end)
13499 (let ((org-last-tags-completion-table
13500 (if (eq major-mode 'org-mode)
13501 (org-get-buffer-tags)
13502 (org-global-tags-completion-table))))
13503 (org-icompleting-read
13504 "Tag: " 'org-tags-completion-function nil nil nil
13505 'org-tags-history))
13506 (progn
13507 (message "[s]et or [r]emove? ")
13508 (equal (read-char-exclusive) ?r))))
13509 (if (fboundp 'deactivate-mark) (deactivate-mark))
13510 (let ((agendap (equal major-mode 'org-agenda-mode))
13511 l1 l2 m buf pos newhead (cnt 0))
13512 (goto-char end)
13513 (setq l2 (1- (org-current-line)))
13514 (goto-char beg)
13515 (setq l1 (org-current-line))
13516 (loop for l from l1 to l2 do
13517 (org-goto-line l)
13518 (setq m (get-text-property (point) 'org-hd-marker))
13519 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13520 (and agendap m))
13521 (setq buf (if agendap (marker-buffer m) (current-buffer))
13522 pos (if agendap m (point)))
13523 (with-current-buffer buf
13524 (save-excursion
13525 (save-restriction
13526 (goto-char pos)
13527 (setq cnt (1+ cnt))
13528 (org-toggle-tag tag (if off 'off 'on))
13529 (setq newhead (org-get-heading)))))
13530 (and agendap (org-agenda-change-all-lines newhead m))))
13531 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13533 (defun org-tags-completion-function (string predicate &optional flag)
13534 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13535 (confirm (lambda (x) (stringp (car x)))))
13536 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13537 (setq s1 (match-string 1 string)
13538 s2 (match-string 2 string))
13539 (setq s1 "" s2 string))
13540 (cond
13541 ((eq flag nil)
13542 ;; try completion
13543 (setq rtn (try-completion s2 ctable confirm))
13544 (if (stringp rtn)
13545 (setq rtn
13546 (concat s1 s2 (substring rtn (length s2))
13547 (if (and org-add-colon-after-tag-completion
13548 (assoc rtn ctable))
13549 ":" ""))))
13550 rtn)
13551 ((eq flag t)
13552 ;; all-completions
13553 (all-completions s2 ctable confirm)
13555 ((eq flag 'lambda)
13556 ;; exact match?
13557 (assoc s2 ctable)))
13560 (defun org-fast-tag-insert (kwd tags face &optional end)
13561 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13562 (insert (format "%-12s" (concat kwd ":"))
13563 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13564 (or end "")))
13566 (defun org-fast-tag-show-exit (flag)
13567 (save-excursion
13568 (org-goto-line 3)
13569 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13570 (replace-match ""))
13571 (when flag
13572 (end-of-line 1)
13573 (org-move-to-column (- (window-width) 19) t)
13574 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13576 (defun org-set-current-tags-overlay (current prefix)
13577 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13578 (if (featurep 'xemacs)
13579 (org-overlay-display org-tags-overlay (concat prefix s)
13580 'secondary-selection)
13581 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13582 (org-overlay-display org-tags-overlay (concat prefix s)))))
13584 (defvar org-last-tag-selection-key nil)
13585 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13586 "Fast tag selection with single keys.
13587 CURRENT is the current list of tags in the headline, INHERITED is the
13588 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13589 possibly with grouping information. TODO-TABLE is a similar table with
13590 TODO keywords, should these have keys assigned to them.
13591 If the keys are nil, a-z are automatically assigned.
13592 Returns the new tags string, or nil to not change the current settings."
13593 (let* ((fulltable (append table todo-table))
13594 (maxlen (apply 'max (mapcar
13595 (lambda (x)
13596 (if (stringp (car x)) (string-width (car x)) 0))
13597 fulltable)))
13598 (buf (current-buffer))
13599 (expert (eq org-fast-tag-selection-single-key 'expert))
13600 (buffer-tags nil)
13601 (fwidth (+ maxlen 3 1 3))
13602 (ncol (/ (- (window-width) 4) fwidth))
13603 (i-face 'org-done)
13604 (c-face 'org-todo)
13605 tg cnt e c char c1 c2 ntable tbl rtn
13606 ov-start ov-end ov-prefix
13607 (exit-after-next org-fast-tag-selection-single-key)
13608 (done-keywords org-done-keywords)
13609 groups ingroup)
13610 (save-excursion
13611 (beginning-of-line 1)
13612 (if (looking-at
13613 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13614 (setq ov-start (match-beginning 1)
13615 ov-end (match-end 1)
13616 ov-prefix "")
13617 (setq ov-start (1- (point-at-eol))
13618 ov-end (1+ ov-start))
13619 (skip-chars-forward "^\n\r")
13620 (setq ov-prefix
13621 (concat
13622 (buffer-substring (1- (point)) (point))
13623 (if (> (current-column) org-tags-column)
13625 (make-string (- org-tags-column (current-column)) ?\ ))))))
13626 (move-overlay org-tags-overlay ov-start ov-end)
13627 (save-window-excursion
13628 (if expert
13629 (set-buffer (get-buffer-create " *Org tags*"))
13630 (delete-other-windows)
13631 (split-window-vertically)
13632 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13633 (erase-buffer)
13634 (org-set-local 'org-done-keywords done-keywords)
13635 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13636 (org-fast-tag-insert "Current" current c-face "\n\n")
13637 (org-fast-tag-show-exit exit-after-next)
13638 (org-set-current-tags-overlay current ov-prefix)
13639 (setq tbl fulltable char ?a cnt 0)
13640 (while (setq e (pop tbl))
13641 (cond
13642 ((equal (car e) :startgroup)
13643 (push '() groups) (setq ingroup t)
13644 (when (not (= cnt 0))
13645 (setq cnt 0)
13646 (insert "\n"))
13647 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13648 ((equal (car e) :endgroup)
13649 (setq ingroup nil cnt 0)
13650 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13651 ((equal e '(:newline))
13652 (when (not (= cnt 0))
13653 (setq cnt 0)
13654 (insert "\n")
13655 (setq e (car tbl))
13656 (while (equal (car tbl) '(:newline))
13657 (insert "\n")
13658 (setq tbl (cdr tbl)))))
13660 (setq tg (copy-sequence (car e)) c2 nil)
13661 (if (cdr e)
13662 (setq c (cdr e))
13663 ;; automatically assign a character.
13664 (setq c1 (string-to-char
13665 (downcase (substring
13666 tg (if (= (string-to-char tg) ?@) 1 0)))))
13667 (if (or (rassoc c1 ntable) (rassoc c1 table))
13668 (while (or (rassoc char ntable) (rassoc char table))
13669 (setq char (1+ char)))
13670 (setq c2 c1))
13671 (setq c (or c2 char)))
13672 (if ingroup (push tg (car groups)))
13673 (setq tg (org-add-props tg nil 'face
13674 (cond
13675 ((not (assoc tg table))
13676 (org-get-todo-face tg))
13677 ((member tg current) c-face)
13678 ((member tg inherited) i-face)
13679 (t nil))))
13680 (if (and (= cnt 0) (not ingroup)) (insert " "))
13681 (insert "[" c "] " tg (make-string
13682 (- fwidth 4 (length tg)) ?\ ))
13683 (push (cons tg c) ntable)
13684 (when (= (setq cnt (1+ cnt)) ncol)
13685 (insert "\n")
13686 (if ingroup (insert " "))
13687 (setq cnt 0)))))
13688 (setq ntable (nreverse ntable))
13689 (insert "\n")
13690 (goto-char (point-min))
13691 (if (not expert) (org-fit-window-to-buffer))
13692 (setq rtn
13693 (catch 'exit
13694 (while t
13695 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13696 (if (not groups) "no " "")
13697 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13698 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13699 (setq org-last-tag-selection-key c)
13700 (cond
13701 ((= c ?\r) (throw 'exit t))
13702 ((= c ?!)
13703 (setq groups (not groups))
13704 (goto-char (point-min))
13705 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13706 ((= c ?\C-c)
13707 (if (not expert)
13708 (org-fast-tag-show-exit
13709 (setq exit-after-next (not exit-after-next)))
13710 (setq expert nil)
13711 (delete-other-windows)
13712 (set-window-buffer (split-window-vertically) " *Org tags*")
13713 (org-switch-to-buffer-other-window " *Org tags*")
13714 (org-fit-window-to-buffer)))
13715 ((or (= c ?\C-g)
13716 (and (= c ?q) (not (rassoc c ntable))))
13717 (org-detach-overlay org-tags-overlay)
13718 (setq quit-flag t))
13719 ((= c ?\ )
13720 (setq current nil)
13721 (if exit-after-next (setq exit-after-next 'now)))
13722 ((= c ?\t)
13723 (condition-case nil
13724 (setq tg (org-icompleting-read
13725 "Tag: "
13726 (or buffer-tags
13727 (with-current-buffer buf
13728 (org-get-buffer-tags)))))
13729 (quit (setq tg "")))
13730 (when (string-match "\\S-" tg)
13731 (add-to-list 'buffer-tags (list tg))
13732 (if (member tg current)
13733 (setq current (delete tg current))
13734 (push tg current)))
13735 (if exit-after-next (setq exit-after-next 'now)))
13736 ((setq e (rassoc c todo-table) tg (car e))
13737 (with-current-buffer buf
13738 (save-excursion (org-todo tg)))
13739 (if exit-after-next (setq exit-after-next 'now)))
13740 ((setq e (rassoc c ntable) tg (car e))
13741 (if (member tg current)
13742 (setq current (delete tg current))
13743 (loop for g in groups do
13744 (if (member tg g)
13745 (mapc (lambda (x)
13746 (setq current (delete x current)))
13747 g)))
13748 (push tg current))
13749 (if exit-after-next (setq exit-after-next 'now))))
13751 ;; Create a sorted list
13752 (setq current
13753 (sort current
13754 (lambda (a b)
13755 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13756 (if (eq exit-after-next 'now) (throw 'exit t))
13757 (goto-char (point-min))
13758 (beginning-of-line 2)
13759 (delete-region (point) (point-at-eol))
13760 (org-fast-tag-insert "Current" current c-face)
13761 (org-set-current-tags-overlay current ov-prefix)
13762 (while (re-search-forward
13763 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13764 (setq tg (match-string 1))
13765 (add-text-properties
13766 (match-beginning 1) (match-end 1)
13767 (list 'face
13768 (cond
13769 ((member tg current) c-face)
13770 ((member tg inherited) i-face)
13771 (t (get-text-property (match-beginning 1) 'face))))))
13772 (goto-char (point-min)))))
13773 (org-detach-overlay org-tags-overlay)
13774 (if rtn
13775 (mapconcat 'identity current ":")
13776 nil))))
13778 (defun org-get-tags-string ()
13779 "Get the TAGS string in the current headline."
13780 (unless (org-at-heading-p t)
13781 (error "Not on a heading"))
13782 (save-excursion
13783 (beginning-of-line 1)
13784 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13785 (org-match-string-no-properties 1)
13786 "")))
13788 (defun org-get-tags ()
13789 "Get the list of tags specified in the current headline."
13790 (org-split-string (org-get-tags-string) ":"))
13792 (defun org-get-buffer-tags ()
13793 "Get a table of all tags used in the buffer, for completion."
13794 (let (tags)
13795 (save-excursion
13796 (goto-char (point-min))
13797 (while (re-search-forward
13798 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13799 (when (equal (char-after (point-at-bol 0)) ?*)
13800 (mapc (lambda (x) (add-to-list 'tags x))
13801 (org-split-string (org-match-string-no-properties 1) ":")))))
13802 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13803 (mapcar 'list tags)))
13805 ;;;; The mapping API
13807 ;;;###autoload
13808 (defun org-map-entries (func &optional match scope &rest skip)
13809 "Call FUNC at each headline selected by MATCH in SCOPE.
13811 FUNC is a function or a lisp form. The function will be called without
13812 arguments, with the cursor positioned at the beginning of the headline.
13813 The return values of all calls to the function will be collected and
13814 returned as a list.
13816 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13817 does not need to preserve point. After evaluation, the cursor will be
13818 moved to the end of the line (presumably of the headline of the
13819 processed entry) and search continues from there. Under some
13820 circumstances, this may not produce the wanted results. For example,
13821 if you have removed (e.g. archived) the current (sub)tree it could
13822 mean that the next entry will be skipped entirely. In such cases, you
13823 can specify the position from where search should continue by making
13824 FUNC set the variable `org-map-continue-from' to the desired buffer
13825 position.
13827 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13828 Only headlines that are matched by this query will be considered during
13829 the iteration. When MATCH is nil or t, all headlines will be
13830 visited by the iteration.
13832 SCOPE determines the scope of this command. It can be any of:
13834 nil The current buffer, respecting the restriction if any
13835 tree The subtree started with the entry at point
13836 region The entries within the active region, if any
13837 region-start-level
13838 The entries within the active region, but only those at
13839 the same level than the first one.
13840 file The current buffer, without restriction
13841 file-with-archives
13842 The current buffer, and any archives associated with it
13843 agenda All agenda files
13844 agenda-with-archives
13845 All agenda files with any archive files associated with them
13846 \(file1 file2 ...)
13847 If this is a list, all files in the list will be scanned
13849 The remaining args are treated as settings for the skipping facilities of
13850 the scanner. The following items can be given here:
13852 archive skip trees with the archive tag.
13853 comment skip trees with the COMMENT keyword
13854 function or Emacs Lisp form:
13855 will be used as value for `org-agenda-skip-function', so whenever
13856 the function returns t, FUNC will not be called for that
13857 entry and search will continue from the point where the
13858 function leaves it.
13860 If your function needs to retrieve the tags including inherited tags
13861 at the *current* entry, you can use the value of the variable
13862 `org-scanner-tags' which will be much faster than getting the value
13863 with `org-get-tags-at'. If your function gets properties with
13864 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13865 to t around the call to `org-entry-properties' to get the same speedup.
13866 Note that if your function moves around to retrieve tags and properties at
13867 a *different* entry, you cannot use these techniques."
13868 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13869 (not (org-region-active-p)))
13870 (let* ((org-agenda-archives-mode nil) ; just to make sure
13871 (org-agenda-skip-archived-trees (memq 'archive skip))
13872 (org-agenda-skip-comment-trees (memq 'comment skip))
13873 (org-agenda-skip-function
13874 (car (org-delete-all '(comment archive) skip)))
13875 (org-tags-match-list-sublevels t)
13876 (start-level (eq scope 'region-start-level))
13877 matcher file res
13878 org-todo-keywords-for-agenda
13879 org-done-keywords-for-agenda
13880 org-todo-keyword-alist-for-agenda
13881 org-drawers-for-agenda
13882 org-tag-alist-for-agenda)
13884 (cond
13885 ((eq match t) (setq matcher t))
13886 ((eq match nil) (setq matcher t))
13887 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13889 (save-excursion
13890 (save-restriction
13891 (cond ((eq scope 'tree)
13892 (org-back-to-heading t)
13893 (org-narrow-to-subtree)
13894 (setq scope nil))
13895 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13896 (org-region-active-p))
13897 ;; If needed, set start-level to a string like "2"
13898 (when start-level
13899 (save-excursion
13900 (goto-char (region-beginning))
13901 (unless (org-at-heading-p) (outline-next-heading))
13902 (setq start-level (org-current-level))))
13903 (narrow-to-region (region-beginning)
13904 (save-excursion
13905 (goto-char (region-end))
13906 (unless (and (bolp) (org-at-heading-p))
13907 (outline-next-heading))
13908 (point)))
13909 (setq scope nil)))
13911 (if (not scope)
13912 (progn
13913 (org-prepare-agenda-buffers
13914 (list (buffer-file-name (current-buffer))))
13915 (setq res (org-scan-tags func matcher nil start-level)))
13916 ;; Get the right scope
13917 (cond
13918 ((and scope (listp scope) (symbolp (car scope)))
13919 (setq scope (eval scope)))
13920 ((eq scope 'agenda)
13921 (setq scope (org-agenda-files t)))
13922 ((eq scope 'agenda-with-archives)
13923 (setq scope (org-agenda-files t))
13924 (setq scope (org-add-archive-files scope)))
13925 ((eq scope 'file)
13926 (setq scope (list (buffer-file-name))))
13927 ((eq scope 'file-with-archives)
13928 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13929 (org-prepare-agenda-buffers scope)
13930 (while (setq file (pop scope))
13931 (with-current-buffer (org-find-base-buffer-visiting file)
13932 (save-excursion
13933 (save-restriction
13934 (widen)
13935 (goto-char (point-min))
13936 (setq res (append res (org-scan-tags func matcher))))))))))
13937 res)))
13939 ;;;; Properties
13941 ;;; Setting and retrieving properties
13943 (defconst org-special-properties
13944 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13945 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13946 "The special properties valid in Org-mode.
13948 These are properties that are not defined in the property drawer,
13949 but in some other way.")
13951 (defconst org-default-properties
13952 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13953 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13954 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13955 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13956 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13957 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13958 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13959 "Some properties that are used by Org-mode for various purposes.
13960 Being in this list makes sure that they are offered for completion.")
13962 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13963 "Regular expression matching the first line of a property drawer.")
13965 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13966 "Regular expression matching the last line of a property drawer.")
13968 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13969 "Regular expression matching the first line of a property drawer.")
13971 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13972 "Regular expression matching the first line of a property drawer.")
13974 (defconst org-property-drawer-re
13975 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13976 org-property-end-re "\\)\n?")
13977 "Matches an entire property drawer.")
13979 (defconst org-clock-drawer-re
13980 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13981 org-property-end-re "\\)\n?")
13982 "Matches an entire clock drawer.")
13984 (defsubst org-re-property (property)
13985 "Return a regexp matching PROPERTY.
13986 Match group 1 will be set to the value "
13987 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13989 (defun org-property-action ()
13990 "Do an action on properties."
13991 (interactive)
13992 (let (c)
13993 (org-at-property-p)
13994 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13995 (setq c (read-char-exclusive))
13996 (cond
13997 ((equal c ?s)
13998 (call-interactively 'org-set-property))
13999 ((equal c ?d)
14000 (call-interactively 'org-delete-property))
14001 ((equal c ?D)
14002 (call-interactively 'org-delete-property-globally))
14003 ((equal c ?c)
14004 (call-interactively 'org-compute-property-at-point))
14005 (t (error "No such property action %c" c)))))
14007 (defun org-set-effort (&optional value)
14008 "Set the effort property of the current entry.
14009 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14010 allowed value."
14011 (interactive "P")
14012 (if (equal value 0) (setq value 10))
14013 (let* ((completion-ignore-case t)
14014 (prop org-effort-property)
14015 (cur (org-entry-get nil prop))
14016 (allowed (org-property-get-allowed-values nil prop 'table))
14017 (existing (mapcar 'list (org-property-values prop)))
14019 (val (cond
14020 ((stringp value) value)
14021 ((and allowed (integerp value))
14022 (or (car (nth (1- value) allowed))
14023 (car (org-last allowed))))
14024 (allowed
14025 (message "Select 1-9,0, [RET%s]: %s"
14026 (if cur (concat "=" cur) "")
14027 (mapconcat 'car allowed " "))
14028 (setq rpl (read-char-exclusive))
14029 (if (equal rpl ?\r)
14031 (setq rpl (- rpl ?0))
14032 (if (equal rpl 0) (setq rpl 10))
14033 (if (and (> rpl 0) (<= rpl (length allowed)))
14034 (car (nth (1- rpl) allowed))
14035 (org-completing-read "Effort: " allowed nil))))
14037 (let (org-completion-use-ido org-completion-use-iswitchb)
14038 (org-completing-read
14039 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14040 (concat "[" cur "]") "")
14041 ": ")
14042 existing nil nil "" nil cur))))))
14043 (unless (equal (org-entry-get nil prop) val)
14044 (org-entry-put nil prop val))
14045 (message "%s is now %s" prop val)))
14047 (defun org-at-property-p ()
14048 "Is cursor inside a property drawer?"
14049 (save-excursion
14050 (beginning-of-line 1)
14051 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14052 (save-match-data ;; Used by calling procedures
14053 (let ((p (point))
14054 (range (unless (org-before-first-heading-p)
14055 (org-get-property-block))))
14056 (and range (<= (car range) p) (< p (cdr range))))))))
14058 (defun org-get-property-block (&optional beg end force)
14059 "Return the (beg . end) range of the body of the property drawer.
14060 BEG and END can be beginning and end of subtree, if not given
14061 they will be found.
14062 If the drawer does not exist and FORCE is non-nil, create the drawer."
14063 (catch 'exit
14064 (save-excursion
14065 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14066 (end (or end (progn (outline-next-heading) (point)))))
14067 (goto-char beg)
14068 (if (re-search-forward org-property-start-re end t)
14069 (setq beg (1+ (match-end 0)))
14070 (if force
14071 (save-excursion
14072 (org-insert-property-drawer)
14073 (setq end (progn (outline-next-heading) (point))))
14074 (throw 'exit nil))
14075 (goto-char beg)
14076 (if (re-search-forward org-property-start-re end t)
14077 (setq beg (1+ (match-end 0)))))
14078 (if (re-search-forward org-property-end-re end t)
14079 (setq end (match-beginning 0))
14080 (or force (throw 'exit nil))
14081 (goto-char beg)
14082 (setq end beg)
14083 (org-indent-line-function)
14084 (insert ":END:\n"))
14085 (cons beg end)))))
14087 (defun org-entry-properties (&optional pom which specific)
14088 "Get all properties of the entry at point-or-marker POM.
14089 This includes the TODO keyword, the tags, time strings for deadline,
14090 scheduled, and clocking, and any additional properties defined in the
14091 entry. The return value is an alist, keys may occur multiple times
14092 if the property key was used several times.
14093 POM may also be nil, in which case the current entry is used.
14094 If WHICH is nil or `all', get all properties. If WHICH is
14095 `special' or `standard', only get that subclass. If WHICH
14096 is a string only get exactly this property. SPECIFIC can be a string, the
14097 specific property we are interested in. Specifying it can speed
14098 things up because then unnecessary parsing is avoided."
14099 (setq which (or which 'all))
14100 (org-with-point-at pom
14101 (let ((clockstr (substring org-clock-string 0 -1))
14102 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14103 (case-fold-search nil)
14104 beg end range props sum-props key key1 value string clocksum)
14105 (save-excursion
14106 (when (condition-case nil
14107 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14108 (error nil))
14109 (setq beg (point))
14110 (setq sum-props (get-text-property (point) 'org-summaries))
14111 (setq clocksum (get-text-property (point) :org-clock-minutes))
14112 (outline-next-heading)
14113 (setq end (point))
14114 (when (memq which '(all special))
14115 ;; Get the special properties, like TODO and tags
14116 (goto-char beg)
14117 (when (and (or (not specific) (string= specific "TODO"))
14118 (looking-at org-todo-line-regexp) (match-end 2))
14119 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14120 (when (and (or (not specific) (string= specific "PRIORITY"))
14121 (looking-at org-priority-regexp))
14122 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14123 (when (or (not specific) (string= specific "FILE"))
14124 (push (cons "FILE" buffer-file-name) props))
14125 (when (and (or (not specific) (string= specific "TAGS"))
14126 (setq value (org-get-tags-string))
14127 (string-match "\\S-" value))
14128 (push (cons "TAGS" value) props))
14129 (when (and (or (not specific) (string= specific "ALLTAGS"))
14130 (setq value (org-get-tags-at)))
14131 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14132 ":"))
14133 props))
14134 (when (or (not specific) (string= specific "BLOCKED"))
14135 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14136 (when (or (not specific)
14137 (member specific
14138 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14139 "TIMESTAMP" "TIMESTAMP_IA")))
14140 (catch 'match
14141 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14142 (setq key (if (match-end 1)
14143 (substring (org-match-string-no-properties 1)
14144 0 -1))
14145 string (if (equal key clockstr)
14146 (org-no-properties
14147 (org-trim
14148 (buffer-substring
14149 (match-beginning 3) (goto-char
14150 (point-at-eol)))))
14151 (substring (org-match-string-no-properties 3)
14152 1 -1)))
14153 ;; Get the correct property name from the key. This is
14154 ;; necessary if the user has configured time keywords.
14155 (setq key1 (concat key ":"))
14156 (cond
14157 ((not key)
14158 (setq key
14159 (if (= (char-after (match-beginning 3)) ?\[)
14160 "TIMESTAMP_IA" "TIMESTAMP")))
14161 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14162 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14163 ((equal key1 org-closed-string) (setq key "CLOSED"))
14164 ((equal key1 org-clock-string) (setq key "CLOCK")))
14165 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14166 (progn
14167 (push (cons key string) props)
14168 ;; no need to search further if match is found
14169 (throw 'match t))
14170 (when (or (equal key "CLOCK") (not (assoc key props)))
14171 (push (cons key string) props))))))
14174 (when (memq which '(all standard))
14175 ;; Get the standard properties, like :PROP: ...
14176 (setq range (org-get-property-block beg end))
14177 (when range
14178 (goto-char (car range))
14179 (while (re-search-forward
14180 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14181 (cdr range) t)
14182 (setq key (org-match-string-no-properties 1)
14183 value (org-trim (or (org-match-string-no-properties 2) "")))
14184 (unless (member key excluded)
14185 (push (cons key (or value "")) props)))))
14186 (if clocksum
14187 (push (cons "CLOCKSUM"
14188 (org-columns-number-to-string (/ (float clocksum) 60.)
14189 'add_times))
14190 props))
14191 (unless (assoc "CATEGORY" props)
14192 (push (cons "CATEGORY" (org-get-category)) props))
14193 (append sum-props (nreverse props)))))))
14195 (defun org-entry-get (pom property &optional inherit literal-nil)
14196 "Get value of PROPERTY for entry at point-or-marker POM.
14197 If INHERIT is non-nil and the entry does not have the property,
14198 then also check higher levels of the hierarchy.
14199 If INHERIT is the symbol `selective', use inheritance only if the setting
14200 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14201 If the property is present but empty, the return value is the empty string.
14202 If the property is not present at all, nil is returned.
14204 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14205 do not interpret it as the list atom nil. This is used for inheritance
14206 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14207 (org-with-point-at pom
14208 (if (and inherit (if (eq inherit 'selective)
14209 (org-property-inherit-p property)
14211 (org-entry-get-with-inheritance property literal-nil)
14212 (if (member property org-special-properties)
14213 ;; We need a special property. Use `org-entry-properties' to
14214 ;; retrieve it, but specify the wanted property
14215 (cdr (assoc property (org-entry-properties nil 'special property)))
14216 (let ((range (unless (org-before-first-heading-p)
14217 (org-get-property-block)))
14218 (props (list (or (assoc property org-file-properties)
14219 (assoc property org-global-properties)
14220 (assoc property org-global-properties-fixed))))
14221 val)
14222 (flet ((ap (key)
14223 (when (re-search-forward
14224 (org-re-property key) (cdr range) t)
14225 (setq props
14226 (org-update-property-plist
14228 (if (match-end 1)
14229 (org-match-string-no-properties 1) "")
14230 props)))))
14231 (when (and range (goto-char (car range)))
14232 (ap property)
14233 (goto-char (car range))
14234 (while (ap (concat property "+")))
14235 (setq val (cdr (assoc property props)))
14236 (when val (if literal-nil val (org-not-nil val))))))))))
14238 (defun org-property-or-variable-value (var &optional inherit)
14239 "Check if there is a property fixing the value of VAR.
14240 If yes, return this value. If not, return the current value of the variable."
14241 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14242 (if (and prop (stringp prop) (string-match "\\S-" prop))
14243 (read prop)
14244 (symbol-value var))))
14246 (defun org-entry-delete (pom property)
14247 "Delete the property PROPERTY from entry at point-or-marker POM."
14248 (org-with-point-at pom
14249 (if (member property org-special-properties)
14250 nil ; cannot delete these properties.
14251 (let ((range (org-get-property-block)))
14252 (if (and range
14253 (goto-char (car range))
14254 (re-search-forward
14255 (org-re-property property)
14256 (cdr range) t))
14257 (progn
14258 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14260 nil)))))
14262 ;; Multi-values properties are properties that contain multiple values
14263 ;; These values are assumed to be single words, separated by whitespace.
14264 (defun org-entry-add-to-multivalued-property (pom property value)
14265 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14266 (let* ((old (org-entry-get pom property))
14267 (values (and old (org-split-string old "[ \t]"))))
14268 (setq value (org-entry-protect-space value))
14269 (unless (member value values)
14270 (setq values (cons value values))
14271 (org-entry-put pom property
14272 (mapconcat 'identity values " ")))))
14274 (defun org-entry-remove-from-multivalued-property (pom property value)
14275 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14276 (let* ((old (org-entry-get pom property))
14277 (values (and old (org-split-string old "[ \t]"))))
14278 (setq value (org-entry-protect-space value))
14279 (when (member value values)
14280 (setq values (delete value values))
14281 (org-entry-put pom property
14282 (mapconcat 'identity values " ")))))
14284 (defun org-entry-member-in-multivalued-property (pom property value)
14285 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14286 (let* ((old (org-entry-get pom property))
14287 (values (and old (org-split-string old "[ \t]"))))
14288 (setq value (org-entry-protect-space value))
14289 (member value values)))
14291 (defun org-entry-get-multivalued-property (pom property)
14292 "Return a list of values in a multivalued property."
14293 (let* ((value (org-entry-get pom property))
14294 (values (and value (org-split-string value "[ \t]"))))
14295 (mapcar 'org-entry-restore-space values)))
14297 (defun org-entry-put-multivalued-property (pom property &rest values)
14298 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14299 VALUES should be a list of strings. Spaces will be protected."
14300 (org-entry-put pom property
14301 (mapconcat 'org-entry-protect-space values " "))
14302 (let* ((value (org-entry-get pom property))
14303 (values (and value (org-split-string value "[ \t]"))))
14304 (mapcar 'org-entry-restore-space values)))
14306 (defun org-entry-protect-space (s)
14307 "Protect spaces and newline in string S."
14308 (while (string-match " " s)
14309 (setq s (replace-match "%20" t t s)))
14310 (while (string-match "\n" s)
14311 (setq s (replace-match "%0A" t t s)))
14314 (defun org-entry-restore-space (s)
14315 "Restore spaces and newline in string S."
14316 (while (string-match "%20" s)
14317 (setq s (replace-match " " t t s)))
14318 (while (string-match "%0A" s)
14319 (setq s (replace-match "\n" t t s)))
14322 (defvar org-entry-property-inherited-from (make-marker)
14323 "Marker pointing to the entry from where a property was inherited.
14324 Each call to `org-entry-get-with-inheritance' will set this marker to the
14325 location of the entry where the inheritance search matched. If there was
14326 no match, the marker will point nowhere.
14327 Note that also `org-entry-get' calls this function, if the INHERIT flag
14328 is set.")
14330 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14331 "Get entry property, and search higher levels if not present.
14332 The search will stop at the first ancestor which has the property defined.
14333 If the value found is \"nil\", return nil to show that the property
14334 should be considered as undefined (this is the meaning of nil here).
14335 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14336 (move-marker org-entry-property-inherited-from nil)
14337 (let (tmp)
14338 (unless (org-before-first-heading-p)
14339 (save-excursion
14340 (save-restriction
14341 (widen)
14342 (catch 'ex
14343 (while t
14344 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14345 (org-back-to-heading t)
14346 (move-marker org-entry-property-inherited-from (point))
14347 (throw 'ex tmp))
14348 (or (org-up-heading-safe) (throw 'ex nil)))))))
14349 (setq tmp (or tmp
14350 (cdr (assoc property org-file-properties))
14351 (cdr (assoc property org-global-properties))
14352 (cdr (assoc property org-global-properties-fixed))))
14353 (if literal-nil tmp (org-not-nil tmp))))
14355 (defvar org-property-changed-functions nil
14356 "Hook called when the value of a property has changed.
14357 Each hook function should accept two arguments, the name of the property
14358 and the new value.")
14360 (defun org-entry-put (pom property value)
14361 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14362 (org-with-point-at pom
14363 (org-back-to-heading t)
14364 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14365 range)
14366 (cond
14367 ((equal property "TODO")
14368 (when (and (stringp value) (string-match "\\S-" value)
14369 (not (member value org-todo-keywords-1)))
14370 (error "\"%s\" is not a valid TODO state" value))
14371 (if (or (not value)
14372 (not (string-match "\\S-" value)))
14373 (setq value 'none))
14374 (org-todo value)
14375 (org-set-tags nil 'align))
14376 ((equal property "PRIORITY")
14377 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14378 (string-to-char value) ?\ ))
14379 (org-set-tags nil 'align))
14380 ((equal property "SCHEDULED")
14381 (if (re-search-forward org-scheduled-time-regexp end t)
14382 (cond
14383 ((eq value 'earlier) (org-timestamp-change -1 'day))
14384 ((eq value 'later) (org-timestamp-change 1 'day))
14385 (t (call-interactively 'org-schedule)))
14386 (call-interactively 'org-schedule)))
14387 ((equal property "DEADLINE")
14388 (if (re-search-forward org-deadline-time-regexp end t)
14389 (cond
14390 ((eq value 'earlier) (org-timestamp-change -1 'day))
14391 ((eq value 'later) (org-timestamp-change 1 'day))
14392 (t (call-interactively 'org-deadline)))
14393 (call-interactively 'org-deadline)))
14394 ((member property org-special-properties)
14395 (error "The %s property can not yet be set with `org-entry-put'"
14396 property))
14397 (t ; a non-special property
14398 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14399 (setq range (org-get-property-block beg end 'force))
14400 (goto-char (car range))
14401 (if (re-search-forward
14402 (org-re-property property) (cdr range) t)
14403 (progn
14404 (delete-region (match-beginning 0) (match-end 0))
14405 (goto-char (match-beginning 0)))
14406 (goto-char (cdr range))
14407 (insert "\n")
14408 (backward-char 1)
14409 (org-indent-line-function))
14410 (insert ":" property ":")
14411 (and value (insert " " value))
14412 (org-indent-line-function)))))
14413 (run-hook-with-args 'org-property-changed-functions property value)))
14415 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14416 "Get all property keys in the current buffer.
14417 With INCLUDE-SPECIALS, also list the special properties that reflect things
14418 like tags and TODO state.
14419 With INCLUDE-DEFAULTS, also include properties that has special meaning
14420 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14421 and others.
14422 With INCLUDE-COLUMNS, also include property names given in COLUMN
14423 formats in the current buffer."
14424 (let (rtn range cfmt s p)
14425 (save-excursion
14426 (save-restriction
14427 (widen)
14428 (goto-char (point-min))
14429 (while (re-search-forward org-property-start-re nil t)
14430 (setq range (org-get-property-block))
14431 (goto-char (car range))
14432 (while (re-search-forward
14433 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14434 (cdr range) t)
14435 (add-to-list 'rtn (org-match-string-no-properties 1)))
14436 (outline-next-heading))))
14438 (when include-specials
14439 (setq rtn (append org-special-properties rtn)))
14441 (when include-defaults
14442 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14443 (add-to-list 'rtn org-effort-property))
14445 (when include-columns
14446 (save-excursion
14447 (save-restriction
14448 (widen)
14449 (goto-char (point-min))
14450 (while (re-search-forward
14451 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14452 nil t)
14453 (setq cfmt (match-string 2) s 0)
14454 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14455 cfmt s)
14456 (setq s (match-end 0)
14457 p (match-string 1 cfmt))
14458 (unless (or (equal p "ITEM")
14459 (member p org-special-properties))
14460 (add-to-list 'rtn (match-string 1 cfmt))))))))
14462 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14464 (defun org-property-values (key)
14465 "Return a list of all values of property KEY in the current buffer."
14466 (save-excursion
14467 (save-restriction
14468 (widen)
14469 (goto-char (point-min))
14470 (let ((re (org-re-property key))
14471 values)
14472 (while (re-search-forward re nil t)
14473 (add-to-list 'values (org-trim (match-string 1))))
14474 (delete "" values)))))
14476 (defun org-insert-property-drawer ()
14477 "Insert a property drawer into the current entry."
14478 (org-back-to-heading t)
14479 (looking-at org-outline-regexp)
14480 (let ((indent (if org-adapt-indentation
14481 (- (match-end 0) (match-beginning 0))
14483 (beg (point))
14484 (re (concat "^[ \t]*" org-keyword-time-regexp))
14485 end hiddenp)
14486 (outline-next-heading)
14487 (setq end (point))
14488 (goto-char beg)
14489 (while (re-search-forward re end t))
14490 (setq hiddenp (outline-invisible-p))
14491 (end-of-line 1)
14492 (and (equal (char-after) ?\n) (forward-char 1))
14493 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14494 (if (member (match-string 1) '("CLOCK:" ":END:"))
14495 ;; just skip this line
14496 (beginning-of-line 2)
14497 ;; Drawer start, find the end
14498 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14499 (beginning-of-line 1)))
14500 (org-skip-over-state-notes)
14501 (skip-chars-backward " \t\n\r")
14502 (if (eq (char-before) ?*) (forward-char 1))
14503 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14504 (beginning-of-line 0)
14505 (org-indent-to-column indent)
14506 (beginning-of-line 2)
14507 (org-indent-to-column indent)
14508 (beginning-of-line 0)
14509 (if hiddenp
14510 (save-excursion
14511 (org-back-to-heading t)
14512 (hide-entry))
14513 (org-flag-drawer t))))
14515 (defun org-insert-drawer (&optional arg drawer)
14516 "Insert a drawer at point.
14518 Optional argument DRAWER, when non-nil, is a string representing
14519 drawer's name. Otherwise, the user is prompted for a name.
14521 If a region is active, insert the drawer around that region
14522 instead.
14524 Point is left between drawer's boundaries."
14525 (interactive "P")
14526 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14527 "LOGBOOK"))
14528 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14529 ;; internally by Org. They are meant to be inserted
14530 ;; automatically.
14531 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14532 ;; Remove system drawers from list. Note: For some reason,
14533 ;; `org-completing-read' ignores the predicate while
14534 ;; `completing-read' handles it fine.
14535 (drawer (if arg "PROPERTIES"
14536 (or drawer
14537 (completing-read
14538 "Drawer: " org-drawers
14539 (lambda (d) (not (member d system-drawers))))))))
14540 (cond
14541 ;; With C-u, fall back on `org-insert-property-drawer'
14542 (arg (org-insert-property-drawer))
14543 ;; With an active region, insert a drawer at point.
14544 ((not (org-region-active-p))
14545 (progn
14546 (unless (bolp) (insert "\n"))
14547 (insert (format ":%s:\n\n:END:\n" drawer))
14548 (forward-line -2)))
14549 ;; Otherwise, insert the drawer at point
14551 (let ((rbeg (region-beginning))
14552 (rend (copy-marker (region-end))))
14553 (unwind-protect
14554 (progn
14555 (goto-char rbeg)
14556 (beginning-of-line)
14557 (when (save-excursion
14558 (re-search-forward org-outline-regexp-bol rend t))
14559 (error "Drawers cannot contain headlines"))
14560 ;; Position point at the beginning of the first
14561 ;; non-blank line in region. Insert drawer's opening
14562 ;; there, then indent it.
14563 (org-skip-whitespace)
14564 (beginning-of-line)
14565 (insert ":" drawer ":\n")
14566 (forward-line -1)
14567 (indent-for-tab-command)
14568 ;; Move point to the beginning of the first blank line
14569 ;; after the last non-blank line in region. Insert
14570 ;; drawer's closing, then indent it.
14571 (goto-char rend)
14572 (skip-chars-backward " \r\t\n")
14573 (insert "\n:END:")
14574 (indent-for-tab-command)
14575 (unless (eolp) (insert "\n")))
14576 ;; Clear marker, whatever the outcome of insertion is.
14577 (set-marker rend nil)))))))
14579 (defvar org-property-set-functions-alist nil
14580 "Property set function alist.
14581 Each entry should have the following format:
14583 (PROPERTY . READ-FUNCTION)
14585 The read function will be called with the same argument as
14586 `org-completing-read'.")
14588 (defun org-set-property-function (property)
14589 "Get the function that should be used to set PROPERTY.
14590 This is computed according to `org-property-set-functions-alist'."
14591 (or (cdr (assoc property org-property-set-functions-alist))
14592 'org-completing-read))
14594 (defun org-read-property-value (property)
14595 "Read PROPERTY value from user."
14596 (let* ((completion-ignore-case t)
14597 (allowed (org-property-get-allowed-values nil property 'table))
14598 (cur (org-entry-get nil property))
14599 (prompt (concat property " value"
14600 (if (and cur (string-match "\\S-" cur))
14601 (concat " [" cur "]") "") ": "))
14602 (set-function (org-set-property-function property))
14603 (val (if allowed
14604 (funcall set-function prompt allowed nil
14605 (not (get-text-property 0 'org-unrestricted
14606 (caar allowed))))
14607 (let (org-completion-use-ido org-completion-use-iswitchb)
14608 (funcall set-function prompt
14609 (mapcar 'list (org-property-values property))
14610 nil nil "" nil cur)))))
14611 (if (equal val "")
14613 val)))
14615 (defvar org-last-set-property nil)
14616 (defun org-read-property-name ()
14617 "Read a property name."
14618 (let* ((completion-ignore-case t)
14619 (keys (org-buffer-property-keys nil t t))
14620 (default-prop (or (save-excursion
14621 (save-match-data
14622 (beginning-of-line)
14623 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14624 (null (string= (match-string 1) "END"))
14625 (match-string 1))))
14626 org-last-set-property))
14627 (property (org-icompleting-read
14628 (concat "Property"
14629 (if default-prop (concat " [" default-prop "]") "")
14630 ": ")
14631 (mapcar 'list keys)
14632 nil nil nil nil
14633 default-prop
14635 (if (member property keys)
14636 property
14637 (or (cdr (assoc (downcase property)
14638 (mapcar (lambda (x) (cons (downcase x) x))
14639 keys)))
14640 property))))
14642 (defun org-set-property (property value)
14643 "In the current entry, set PROPERTY to VALUE.
14644 When called interactively, this will prompt for a property name, offering
14645 completion on existing and default properties. And then it will prompt
14646 for a value, offering completion either on allowed values (via an inherited
14647 xxx_ALL property) or on existing values in other instances of this property
14648 in the current file."
14649 (interactive (list nil nil))
14650 (let* ((property (or property (org-read-property-name)))
14651 (value (or value (org-read-property-value property)))
14652 (fn (assoc property org-properties-postprocess-alist)))
14653 (setq org-last-set-property property)
14654 ;; Possibly postprocess the inserted value:
14655 (when fn (setq value (funcall (cadr fn) value)))
14656 (unless (equal (org-entry-get nil property) value)
14657 (org-entry-put nil property value))))
14659 (defun org-delete-property (property)
14660 "In the current entry, delete PROPERTY."
14661 (interactive
14662 (let* ((completion-ignore-case t)
14663 (prop (org-icompleting-read "Property: "
14664 (org-entry-properties nil 'standard))))
14665 (list prop)))
14666 (message "Property %s %s" property
14667 (if (org-entry-delete nil property)
14668 "deleted"
14669 "was not present in the entry")))
14671 (defun org-delete-property-globally (property)
14672 "Remove PROPERTY globally, from all entries."
14673 (interactive
14674 (let* ((completion-ignore-case t)
14675 (prop (org-icompleting-read
14676 "Globally remove property: "
14677 (mapcar 'list (org-buffer-property-keys)))))
14678 (list prop)))
14679 (save-excursion
14680 (save-restriction
14681 (widen)
14682 (goto-char (point-min))
14683 (let ((cnt 0))
14684 (while (re-search-forward
14685 (org-re-property property)
14686 nil t)
14687 (setq cnt (1+ cnt))
14688 (replace-match ""))
14689 (message "Property \"%s\" removed from %d entries" property cnt)))))
14691 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14693 (defun org-compute-property-at-point ()
14694 "Compute the property at point.
14695 This looks for an enclosing column format, extracts the operator and
14696 then applies it to the property in the column format's scope."
14697 (interactive)
14698 (unless (org-at-property-p)
14699 (error "Not at a property"))
14700 (let ((prop (org-match-string-no-properties 2)))
14701 (org-columns-get-format-and-top-level)
14702 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14703 (error "No operator defined for property %s" prop))
14704 (org-columns-compute prop)))
14706 (defvar org-property-allowed-value-functions nil
14707 "Hook for functions supplying allowed values for a specific property.
14708 The functions must take a single argument, the name of the property, and
14709 return a flat list of allowed values. If \":ETC\" is one of
14710 the values, this means that these values are intended as defaults for
14711 completion, but that other values should be allowed too.
14712 The functions must return nil if they are not responsible for this
14713 property.")
14715 (defun org-property-get-allowed-values (pom property &optional table)
14716 "Get allowed values for the property PROPERTY.
14717 When TABLE is non-nil, return an alist that can directly be used for
14718 completion."
14719 (let (vals)
14720 (cond
14721 ((equal property "TODO")
14722 (setq vals (org-with-point-at pom
14723 (append org-todo-keywords-1 '("")))))
14724 ((equal property "PRIORITY")
14725 (let ((n org-lowest-priority))
14726 (while (>= n org-highest-priority)
14727 (push (char-to-string n) vals)
14728 (setq n (1- n)))))
14729 ((member property org-special-properties))
14730 ((setq vals (run-hook-with-args-until-success
14731 'org-property-allowed-value-functions property)))
14733 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14734 (when (and vals (string-match "\\S-" vals))
14735 (setq vals (car (read-from-string (concat "(" vals ")"))))
14736 (setq vals (mapcar (lambda (x)
14737 (cond ((stringp x) x)
14738 ((numberp x) (number-to-string x))
14739 ((symbolp x) (symbol-name x))
14740 (t "???")))
14741 vals)))))
14742 (when (member ":ETC" vals)
14743 (setq vals (remove ":ETC" vals))
14744 (org-add-props (car vals) '(org-unrestricted t)))
14745 (if table (mapcar 'list vals) vals)))
14747 (defun org-property-previous-allowed-value (&optional previous)
14748 "Switch to the next allowed value for this property."
14749 (interactive)
14750 (org-property-next-allowed-value t))
14752 (defun org-property-next-allowed-value (&optional previous)
14753 "Switch to the next allowed value for this property."
14754 (interactive)
14755 (unless (org-at-property-p)
14756 (error "Not at a property"))
14757 (let* ((key (match-string 2))
14758 (value (match-string 3))
14759 (allowed (or (org-property-get-allowed-values (point) key)
14760 (and (member value '("[ ]" "[-]" "[X]"))
14761 '("[ ]" "[X]"))))
14762 nval)
14763 (unless allowed
14764 (error "Allowed values for this property have not been defined"))
14765 (if previous (setq allowed (reverse allowed)))
14766 (if (member value allowed)
14767 (setq nval (car (cdr (member value allowed)))))
14768 (setq nval (or nval (car allowed)))
14769 (if (equal nval value)
14770 (error "Only one allowed value for this property"))
14771 (org-at-property-p)
14772 (replace-match (concat " :" key ": " nval) t t)
14773 (org-indent-line-function)
14774 (beginning-of-line 1)
14775 (skip-chars-forward " \t")
14776 (run-hook-with-args 'org-property-changed-functions key nval)))
14778 (defun org-find-olp (path &optional this-buffer)
14779 "Return a marker pointing to the entry at outline path OLP.
14780 If anything goes wrong, throw an error.
14781 You can wrap this call to catch the error like this:
14783 (condition-case msg
14784 (org-mobile-locate-entry (match-string 4))
14785 (error (nth 1 msg)))
14787 The return value will then be either a string with the error message,
14788 or a marker if everything is OK.
14790 If THIS-BUFFER is set, the outline path does not contain a file,
14791 only headings."
14792 (let* ((file (if this-buffer buffer-file-name (pop path)))
14793 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14794 (level 1)
14795 (lmin 1)
14796 (lmax 1)
14797 limit re end found pos heading cnt flevel)
14798 (unless buffer (error "File not found :%s" file))
14799 (with-current-buffer buffer
14800 (save-excursion
14801 (save-restriction
14802 (widen)
14803 (setq limit (point-max))
14804 (goto-char (point-min))
14805 (while (setq heading (pop path))
14806 (setq re (format org-complex-heading-regexp-format
14807 (regexp-quote heading)))
14808 (setq cnt 0 pos (point))
14809 (while (re-search-forward re end t)
14810 (setq level (- (match-end 1) (match-beginning 1)))
14811 (if (and (>= level lmin) (<= level lmax))
14812 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14813 (when (= cnt 0) (error "Heading not found on level %d: %s"
14814 lmax heading))
14815 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14816 lmax heading))
14817 (goto-char found)
14818 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14819 (setq end (save-excursion (org-end-of-subtree t t))))
14820 (when (org-at-heading-p)
14821 (move-marker (make-marker) (point))))))))
14823 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14824 "Find node HEADING in BUFFER.
14825 Return a marker to the heading if it was found, or nil if not.
14826 If POS-ONLY is set, return just the position instead of a marker.
14828 The heading text must match exact, but it may have a TODO keyword,
14829 a priority cookie and tags in the standard locations."
14830 (with-current-buffer (or buffer (current-buffer))
14831 (save-excursion
14832 (save-restriction
14833 (widen)
14834 (goto-char (point-min))
14835 (let (case-fold-search)
14836 (if (re-search-forward
14837 (format org-complex-heading-regexp-format
14838 (regexp-quote heading)) nil t)
14839 (if pos-only
14840 (match-beginning 0)
14841 (move-marker (make-marker) (match-beginning 0)))))))))
14843 (defun org-find-exact-heading-in-directory (heading &optional dir)
14844 "Find Org node headline HEADING in all .org files in directory DIR.
14845 When the target headline is found, return a marker to this location."
14846 (let ((files (directory-files (or dir default-directory)
14847 nil "\\`[^.#].*\\.org\\'"))
14848 file visiting m buffer)
14849 (catch 'found
14850 (while (setq file (pop files))
14851 (message "trying %s" file)
14852 (setq visiting (org-find-base-buffer-visiting file))
14853 (setq buffer (or visiting (find-file-noselect file)))
14854 (setq m (org-find-exact-headline-in-buffer
14855 heading buffer))
14856 (when (and (not m) (not visiting)) (kill-buffer buffer))
14857 (and m (throw 'found m))))))
14859 (defun org-find-entry-with-id (ident)
14860 "Locate the entry that contains the ID property with exact value IDENT.
14861 IDENT can be a string, a symbol or a number, this function will search for
14862 the string representation of it.
14863 Return the position where this entry starts, or nil if there is no such entry."
14864 (interactive "sID: ")
14865 (let ((id (cond
14866 ((stringp ident) ident)
14867 ((symbol-name ident) (symbol-name ident))
14868 ((numberp ident) (number-to-string ident))
14869 (t (error "IDENT %s must be a string, symbol or number" ident))))
14870 (case-fold-search nil))
14871 (save-excursion
14872 (save-restriction
14873 (widen)
14874 (goto-char (point-min))
14875 (when (re-search-forward
14876 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14877 nil t)
14878 (org-back-to-heading t)
14879 (point))))))
14881 ;;;; Timestamps
14883 (defvar org-last-changed-timestamp nil)
14884 (defvar org-last-inserted-timestamp nil
14885 "The last time stamp inserted with `org-insert-time-stamp'.")
14886 (defvar org-time-was-given) ; dynamically scoped parameter
14887 (defvar org-end-time-was-given) ; dynamically scoped parameter
14888 (defvar org-ts-what) ; dynamically scoped parameter
14890 (defun org-time-stamp (arg &optional inactive)
14891 "Prompt for a date/time and insert a time stamp.
14892 If the user specifies a time like HH:MM, or if this command is called
14893 with a prefix argument, the time stamp will contain date and time.
14894 Otherwise, only the date will be included. All parts of a date not
14895 specified by the user will be filled in from the current date/time.
14896 So if you press just return without typing anything, the time stamp
14897 will represent the current date/time. If there is already a timestamp
14898 at the cursor, it will be modified."
14899 (interactive "P")
14900 (let* ((ts nil)
14901 (default-time
14902 ;; Default time is either today, or, when entering a range,
14903 ;; the range start.
14904 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14905 (save-excursion
14906 (re-search-backward
14907 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14908 (- (point) 20) t)))
14909 (apply 'encode-time (org-parse-time-string (match-string 1)))
14910 (current-time)))
14911 (default-input (and ts (org-get-compact-tod ts)))
14912 (repeater (save-excursion
14913 (save-match-data
14914 (beginning-of-line)
14915 (when (re-search-forward
14916 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14917 (save-excursion (progn (end-of-line) (point))) t)
14918 (match-string 0)))))
14919 org-time-was-given org-end-time-was-given time)
14920 (cond
14921 ((and (org-at-timestamp-p t)
14922 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14923 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14924 (insert "--")
14925 (setq time (let ((this-command this-command))
14926 (org-read-date arg 'totime nil nil
14927 default-time default-input inactive)))
14928 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14929 ((org-at-timestamp-p t)
14930 (setq time (let ((this-command this-command))
14931 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14932 (when (org-at-timestamp-p t) ; just to get the match data
14933 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14934 (replace-match "")
14935 (setq org-last-changed-timestamp
14936 (org-insert-time-stamp
14937 time (or org-time-was-given arg)
14938 inactive nil nil (list org-end-time-was-given)))
14939 (when repeater (goto-char (1- (point))) (insert " " repeater)
14940 (setq org-last-changed-timestamp
14941 (concat (substring org-last-inserted-timestamp 0 -1)
14942 " " repeater ">"))))
14943 (message "Timestamp updated"))
14945 (setq time (let ((this-command this-command))
14946 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14947 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14948 nil nil (list org-end-time-was-given))))))
14950 ;; FIXME: can we use this for something else, like computing time differences?
14951 (defun org-get-compact-tod (s)
14952 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14953 (let* ((t1 (match-string 1 s))
14954 (h1 (string-to-number (match-string 2 s)))
14955 (m1 (string-to-number (match-string 3 s)))
14956 (t2 (and (match-end 4) (match-string 5 s)))
14957 (h2 (and t2 (string-to-number (match-string 6 s))))
14958 (m2 (and t2 (string-to-number (match-string 7 s))))
14959 dh dm)
14960 (if (not t2)
14962 (setq dh (- h2 h1) dm (- m2 m1))
14963 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14964 (concat t1 "+" (number-to-string dh)
14965 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14967 (defun org-time-stamp-inactive (&optional arg)
14968 "Insert an inactive time stamp.
14969 An inactive time stamp is enclosed in square brackets instead of angle
14970 brackets. It is inactive in the sense that it does not trigger agenda entries,
14971 does not link to the calendar and cannot be changed with the S-cursor keys.
14972 So these are more for recording a certain time/date."
14973 (interactive "P")
14974 (org-time-stamp arg 'inactive))
14976 (defvar org-date-ovl (make-overlay 1 1))
14977 (overlay-put org-date-ovl 'face 'org-warning)
14978 (org-detach-overlay org-date-ovl)
14980 (defvar org-ans1) ; dynamically scoped parameter
14981 (defvar org-ans2) ; dynamically scoped parameter
14983 (defvar org-plain-time-of-day-regexp) ; defined below
14985 (defvar org-overriding-default-time nil) ; dynamically scoped
14986 (defvar org-read-date-overlay nil)
14987 (defvar org-dcst nil) ; dynamically scoped
14988 (defvar org-read-date-history nil)
14989 (defvar org-read-date-final-answer nil)
14990 (defvar org-read-date-analyze-futurep nil)
14991 (defvar org-read-date-analyze-forced-year nil)
14992 (defvar org-read-date-inactive)
14994 (defun org-read-date (&optional with-time to-time from-string prompt
14995 default-time default-input inactive)
14996 "Read a date, possibly a time, and make things smooth for the user.
14997 The prompt will suggest to enter an ISO date, but you can also enter anything
14998 which will at least partially be understood by `parse-time-string'.
14999 Unrecognized parts of the date will default to the current day, month, year,
15000 hour and minute. If this command is called to replace a timestamp at point,
15001 or to enter the second timestamp of a range, the default time is taken
15002 from the existing stamp. Furthermore, the command prefers the future,
15003 so if you are giving a date where the year is not given, and the day-month
15004 combination is already past in the current year, it will assume you
15005 mean next year. For details, see the manual. A few examples:
15007 3-2-5 --> 2003-02-05
15008 feb 15 --> currentyear-02-15
15009 2/15 --> currentyear-02-15
15010 sep 12 9 --> 2009-09-12
15011 12:45 --> today 12:45
15012 22 sept 0:34 --> currentyear-09-22 0:34
15013 12 --> currentyear-currentmonth-12
15014 Fri --> nearest Friday (today or later)
15015 etc.
15017 Furthermore you can specify a relative date by giving, as the *first* thing
15018 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
15019 change in days weeks, months, years.
15020 With a single plus or minus, the date is relative to today. With a double
15021 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15022 +4d --> four days from today
15023 +4 --> same as above
15024 +2w --> two weeks from today
15025 ++5 --> five days from default date
15027 The function understands only English month and weekday abbreviations,
15028 but this can be configured with the variables `parse-time-months' and
15029 `parse-time-weekdays'.
15031 While prompting, a calendar is popped up - you can also select the
15032 date with the mouse (button 1). The calendar shows a period of three
15033 months. To scroll it to other months, use the keys `>' and `<'.
15034 If you don't like the calendar, turn it off with
15035 \(setq org-read-date-popup-calendar nil)
15037 With optional argument TO-TIME, the date will immediately be converted
15038 to an internal time.
15039 With an optional argument WITH-TIME, the prompt will suggest to also
15040 insert a time. Note that when WITH-TIME is not set, you can still
15041 enter a time, and this function will inform the calling routine about
15042 this change. The calling routine may then choose to change the format
15043 used to insert the time stamp into the buffer to include the time.
15044 With optional argument FROM-STRING, read from this string instead from
15045 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15046 the time/date that is used for everything that is not specified by the
15047 user."
15048 (require 'parse-time)
15049 (let* ((org-time-stamp-rounding-minutes
15050 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15051 (org-dcst org-display-custom-times)
15052 (ct (org-current-time))
15053 (def (or org-overriding-default-time default-time ct))
15054 (defdecode (decode-time def))
15055 (dummy (progn
15056 (when (< (nth 2 defdecode) org-extend-today-until)
15057 (setcar (nthcdr 2 defdecode) -1)
15058 (setcar (nthcdr 1 defdecode) 59)
15059 (setq def (apply 'encode-time defdecode)
15060 defdecode (decode-time def)))))
15061 (calendar-frame-setup nil)
15062 (calendar-setup nil)
15063 (calendar-move-hook nil)
15064 (calendar-view-diary-initially-flag nil)
15065 (calendar-view-holidays-initially-flag nil)
15066 (timestr (format-time-string
15067 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
15068 (prompt (concat (if prompt (concat prompt " ") "")
15069 (format "Date+time [%s]: " timestr)))
15070 ans (org-ans0 "") org-ans1 org-ans2 final)
15072 (cond
15073 (from-string (setq ans from-string))
15074 (org-read-date-popup-calendar
15075 (save-excursion
15076 (save-window-excursion
15077 (calendar)
15078 (unwind-protect
15079 (progn
15080 (calendar-forward-day (- (time-to-days def)
15081 (calendar-absolute-from-gregorian
15082 (calendar-current-date))))
15083 (org-eval-in-calendar nil t)
15084 (let* ((old-map (current-local-map))
15085 (map (copy-keymap calendar-mode-map))
15086 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15087 (org-defkey map (kbd "RET") 'org-calendar-select)
15088 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15089 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15090 (org-defkey minibuffer-local-map [(meta shift left)]
15091 (lambda () (interactive)
15092 (org-eval-in-calendar '(calendar-backward-month 1))))
15093 (org-defkey minibuffer-local-map [(meta shift right)]
15094 (lambda () (interactive)
15095 (org-eval-in-calendar '(calendar-forward-month 1))))
15096 (org-defkey minibuffer-local-map [(meta shift up)]
15097 (lambda () (interactive)
15098 (org-eval-in-calendar '(calendar-backward-year 1))))
15099 (org-defkey minibuffer-local-map [(meta shift down)]
15100 (lambda () (interactive)
15101 (org-eval-in-calendar '(calendar-forward-year 1))))
15102 (org-defkey minibuffer-local-map [?\e (shift left)]
15103 (lambda () (interactive)
15104 (org-eval-in-calendar '(calendar-backward-month 1))))
15105 (org-defkey minibuffer-local-map [?\e (shift right)]
15106 (lambda () (interactive)
15107 (org-eval-in-calendar '(calendar-forward-month 1))))
15108 (org-defkey minibuffer-local-map [?\e (shift up)]
15109 (lambda () (interactive)
15110 (org-eval-in-calendar '(calendar-backward-year 1))))
15111 (org-defkey minibuffer-local-map [?\e (shift down)]
15112 (lambda () (interactive)
15113 (org-eval-in-calendar '(calendar-forward-year 1))))
15114 (org-defkey minibuffer-local-map [(shift up)]
15115 (lambda () (interactive)
15116 (org-eval-in-calendar '(calendar-backward-week 1))))
15117 (org-defkey minibuffer-local-map [(shift down)]
15118 (lambda () (interactive)
15119 (org-eval-in-calendar '(calendar-forward-week 1))))
15120 (org-defkey minibuffer-local-map [(shift left)]
15121 (lambda () (interactive)
15122 (org-eval-in-calendar '(calendar-backward-day 1))))
15123 (org-defkey minibuffer-local-map [(shift right)]
15124 (lambda () (interactive)
15125 (org-eval-in-calendar '(calendar-forward-day 1))))
15126 (org-defkey minibuffer-local-map ">"
15127 (lambda () (interactive)
15128 (org-eval-in-calendar '(scroll-calendar-left 1))))
15129 (org-defkey minibuffer-local-map "<"
15130 (lambda () (interactive)
15131 (org-eval-in-calendar '(scroll-calendar-right 1))))
15132 (org-defkey minibuffer-local-map "\C-v"
15133 (lambda () (interactive)
15134 (org-eval-in-calendar
15135 '(calendar-scroll-left-three-months 1))))
15136 (org-defkey minibuffer-local-map "\M-v"
15137 (lambda () (interactive)
15138 (org-eval-in-calendar
15139 '(calendar-scroll-right-three-months 1))))
15140 (run-hooks 'org-read-date-minibuffer-setup-hook)
15141 (unwind-protect
15142 (progn
15143 (use-local-map map)
15144 (setq org-read-date-inactive inactive)
15145 (add-hook 'post-command-hook 'org-read-date-display)
15146 (setq org-ans0 (read-string prompt default-input
15147 'org-read-date-history nil))
15148 ;; org-ans0: from prompt
15149 ;; org-ans1: from mouse click
15150 ;; org-ans2: from calendar motion
15151 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15152 (remove-hook 'post-command-hook 'org-read-date-display)
15153 (use-local-map old-map)
15154 (when org-read-date-overlay
15155 (delete-overlay org-read-date-overlay)
15156 (setq org-read-date-overlay nil)))))
15157 (bury-buffer "*Calendar*")))))
15159 (t ; Naked prompt only
15160 (unwind-protect
15161 (setq ans (read-string prompt default-input
15162 'org-read-date-history timestr))
15163 (when org-read-date-overlay
15164 (delete-overlay org-read-date-overlay)
15165 (setq org-read-date-overlay nil)))))
15167 (setq final (org-read-date-analyze ans def defdecode))
15169 (when org-read-date-analyze-forced-year
15170 (message "Year was forced into %s"
15171 (if org-read-date-force-compatible-dates
15172 "compatible range (1970-2037)"
15173 "range representable on this machine"))
15174 (ding))
15176 ;; One round trip to get rid of 34th of August and stuff like that....
15177 (setq final (decode-time (apply 'encode-time final)))
15179 (setq org-read-date-final-answer ans)
15181 (if to-time
15182 (apply 'encode-time final)
15183 (if (and (boundp 'org-time-was-given) org-time-was-given)
15184 (format "%04d-%02d-%02d %02d:%02d"
15185 (nth 5 final) (nth 4 final) (nth 3 final)
15186 (nth 2 final) (nth 1 final))
15187 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15189 (defvar def)
15190 (defvar defdecode)
15191 (defvar with-time)
15192 (defun org-read-date-display ()
15193 "Display the current date prompt interpretation in the minibuffer."
15194 (when org-read-date-display-live
15195 (when org-read-date-overlay
15196 (delete-overlay org-read-date-overlay))
15197 (let ((p (point)))
15198 (end-of-line 1)
15199 (while (not (equal (buffer-substring
15200 (max (point-min) (- (point) 4)) (point))
15201 " "))
15202 (insert " "))
15203 (goto-char p))
15204 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15205 " " (or org-ans1 org-ans2)))
15206 (org-end-time-was-given nil)
15207 (f (org-read-date-analyze ans def defdecode))
15208 (fmts (if org-dcst
15209 org-time-stamp-custom-formats
15210 org-time-stamp-formats))
15211 (fmt (if (or with-time
15212 (and (boundp 'org-time-was-given) org-time-was-given))
15213 (cdr fmts)
15214 (car fmts)))
15215 (txt (format-time-string fmt (apply 'encode-time f)))
15216 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15217 (txt (concat "=> " txt)))
15218 (when (and org-end-time-was-given
15219 (string-match org-plain-time-of-day-regexp txt))
15220 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15221 org-end-time-was-given
15222 (substring txt (match-end 0)))))
15223 (when org-read-date-analyze-futurep
15224 (setq txt (concat txt " (=>F)")))
15225 (setq org-read-date-overlay
15226 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15227 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15229 (defun org-read-date-analyze (ans def defdecode)
15230 "Analyze the combined answer of the date prompt."
15231 ;; FIXME: cleanup and comment
15232 (let ((nowdecode (decode-time (current-time)))
15233 delta deltan deltaw deltadef year month day
15234 hour minute second wday pm h2 m2 tl wday1
15235 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15236 (setq org-read-date-analyze-futurep nil
15237 org-read-date-analyze-forced-year nil)
15238 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15239 (setq ans "+0"))
15241 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15242 (setq ans (replace-match "" t t ans)
15243 deltan (car delta)
15244 deltaw (nth 1 delta)
15245 deltadef (nth 2 delta)))
15247 ;; Check if there is an iso week date in there
15248 ;; If yes, store the info and postpone interpreting it until the rest
15249 ;; of the parsing is done
15250 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15251 (setq iso-year (if (match-end 1)
15252 (org-small-year-to-year
15253 (string-to-number (match-string 1 ans))))
15254 iso-weekday (if (match-end 3)
15255 (string-to-number (match-string 3 ans)))
15256 iso-week (string-to-number (match-string 2 ans)))
15257 (setq ans (replace-match "" t t ans)))
15259 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15260 (when (string-match
15261 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15262 (setq year (if (match-end 2)
15263 (string-to-number (match-string 2 ans))
15264 (progn (setq kill-year t)
15265 (string-to-number (format-time-string "%Y"))))
15266 month (string-to-number (match-string 3 ans))
15267 day (string-to-number (match-string 4 ans)))
15268 (if (< year 100) (setq year (+ 2000 year)))
15269 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15270 t nil ans)))
15272 ;; Help matching dotted european dates
15273 (when (string-match
15274 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15275 (setq year (if (match-end 3)
15276 (string-to-number (match-string 3 ans))
15277 (progn (setq kill-year t)
15278 (string-to-number (format-time-string "%Y"))))
15279 day (string-to-number (match-string 1 ans))
15280 month (string-to-number (match-string 2 ans))
15281 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15282 t nil ans)))
15284 ;; Help matching american dates, like 5/30 or 5/30/7
15285 (when (string-match
15286 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15287 (setq year (if (match-end 4)
15288 (string-to-number (match-string 4 ans))
15289 (progn (setq kill-year t)
15290 (string-to-number (format-time-string "%Y"))))
15291 month (string-to-number (match-string 1 ans))
15292 day (string-to-number (match-string 2 ans)))
15293 (if (< year 100) (setq year (+ 2000 year)))
15294 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15295 t nil ans)))
15296 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15297 ;; If there is a time with am/pm, and *no* time without it, we convert
15298 ;; so that matching will be successful.
15299 (loop for i from 1 to 2 do ; twice, for end time as well
15300 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15301 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15302 (setq hour (string-to-number (match-string 1 ans))
15303 minute (if (match-end 3)
15304 (string-to-number (match-string 3 ans))
15306 pm (equal ?p
15307 (string-to-char (downcase (match-string 4 ans)))))
15308 (if (and (= hour 12) (not pm))
15309 (setq hour 0)
15310 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15311 (setq ans (replace-match (format "%02d:%02d" hour minute)
15312 t t ans))))
15314 ;; Check if a time range is given as a duration
15315 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15316 (setq hour (string-to-number (match-string 1 ans))
15317 h2 (+ hour (string-to-number (match-string 3 ans)))
15318 minute (string-to-number (match-string 2 ans))
15319 m2 (+ minute (if (match-end 5) (string-to-number
15320 (match-string 5 ans))0)))
15321 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15322 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15323 t t ans)))
15325 ;; Check if there is a time range
15326 (when (boundp 'org-end-time-was-given)
15327 (setq org-time-was-given nil)
15328 (when (and (string-match org-plain-time-of-day-regexp ans)
15329 (match-end 8))
15330 (setq org-end-time-was-given (match-string 8 ans))
15331 (setq ans (concat (substring ans 0 (match-beginning 7))
15332 (substring ans (match-end 7))))))
15334 (setq tl (parse-time-string ans)
15335 day (or (nth 3 tl) (nth 3 defdecode))
15336 month (or (nth 4 tl)
15337 (if (and org-read-date-prefer-future
15338 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15339 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15340 (nth 4 defdecode)))
15341 year (or (and (not kill-year) (nth 5 tl))
15342 (if (and org-read-date-prefer-future
15343 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15344 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15345 (nth 5 defdecode)))
15346 hour (or (nth 2 tl) (nth 2 defdecode))
15347 minute (or (nth 1 tl) (nth 1 defdecode))
15348 second (or (nth 0 tl) 0)
15349 wday (nth 6 tl))
15351 (when (and (eq org-read-date-prefer-future 'time)
15352 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15353 (equal day (nth 3 nowdecode))
15354 (equal month (nth 4 nowdecode))
15355 (equal year (nth 5 nowdecode))
15356 (nth 2 tl)
15357 (or (< (nth 2 tl) (nth 2 nowdecode))
15358 (and (= (nth 2 tl) (nth 2 nowdecode))
15359 (nth 1 tl)
15360 (< (nth 1 tl) (nth 1 nowdecode)))))
15361 (setq day (1+ day)
15362 futurep t))
15364 ;; Special date definitions below
15365 (cond
15366 (iso-week
15367 ;; There was an iso week
15368 (require 'cal-iso)
15369 (setq futurep nil)
15370 (setq year (or iso-year year)
15371 day (or iso-weekday wday 1)
15372 wday nil ; to make sure that the trigger below does not match
15373 iso-date (calendar-gregorian-from-absolute
15374 (calendar-absolute-from-iso
15375 (list iso-week day year))))
15376 ; FIXME: Should we also push ISO weeks into the future?
15377 ; (when (and org-read-date-prefer-future
15378 ; (not iso-year)
15379 ; (< (calendar-absolute-from-gregorian iso-date)
15380 ; (time-to-days (current-time))))
15381 ; (setq year (1+ year)
15382 ; iso-date (calendar-gregorian-from-absolute
15383 ; (calendar-absolute-from-iso
15384 ; (list iso-week day year)))))
15385 (setq month (car iso-date)
15386 year (nth 2 iso-date)
15387 day (nth 1 iso-date)))
15388 (deltan
15389 (setq futurep nil)
15390 (unless deltadef
15391 (let ((now (decode-time (current-time))))
15392 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15393 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15394 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15395 ((equal deltaw "m") (setq month (+ month deltan)))
15396 ((equal deltaw "y") (setq year (+ year deltan)))))
15397 ((and wday (not (nth 3 tl)))
15398 (setq futurep nil)
15399 ;; Weekday was given, but no day, so pick that day in the week
15400 ;; on or after the derived date.
15401 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15402 (unless (equal wday wday1)
15403 (setq day (+ day (% (- wday wday1 -7) 7))))))
15404 (if (and (boundp 'org-time-was-given)
15405 (nth 2 tl))
15406 (setq org-time-was-given t))
15407 (if (< year 100) (setq year (+ 2000 year)))
15408 ;; Check of the date is representable
15409 (if org-read-date-force-compatible-dates
15410 (progn
15411 (if (< year 1970)
15412 (setq year 1970 org-read-date-analyze-forced-year t))
15413 (if (> year 2037)
15414 (setq year 2037 org-read-date-analyze-forced-year t)))
15415 (condition-case nil
15416 (ignore (encode-time second minute hour day month year))
15417 (error
15418 (setq year (nth 5 defdecode))
15419 (setq org-read-date-analyze-forced-year t))))
15420 (setq org-read-date-analyze-futurep futurep)
15421 (list second minute hour day month year)))
15423 (defvar parse-time-weekdays)
15425 (defun org-read-date-get-relative (s today default)
15426 "Check string S for special relative date string.
15427 TODAY and DEFAULT are internal times, for today and for a default.
15428 Return shift list (N what def-flag)
15429 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15430 N is the number of WHATs to shift.
15431 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15432 the DEFAULT date rather than TODAY."
15433 (require 'parse-time)
15434 (when (and
15435 (string-match
15436 (concat
15437 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15438 "\\([0-9]+\\)?"
15439 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15440 "\\([ \t]\\|$\\)") s)
15441 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15442 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15443 (string-to-char (substring (match-string 1 s) -1))
15444 ?+))
15445 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15446 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15447 (what (if (match-end 3) (match-string 3 s) "d"))
15448 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15449 (date (if rel default today))
15450 (wday (nth 6 (decode-time date)))
15451 delta)
15452 (if wday1
15453 (progn
15454 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15455 (if (= dir ?-) (setq delta (- delta 7)))
15456 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15457 (list delta "d" rel))
15458 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15460 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15461 "Turn a user-specified date into the internal representation.
15462 The internal representation needed by the calendar is (month day year).
15463 This is a wrapper to handle the brain-dead convention in calendar that
15464 user function argument order change dependent on argument order."
15465 (if (boundp 'calendar-date-style)
15466 (cond
15467 ((eq calendar-date-style 'american)
15468 (list arg1 arg2 arg3))
15469 ((eq calendar-date-style 'european)
15470 (list arg2 arg1 arg3))
15471 ((eq calendar-date-style 'iso)
15472 (list arg2 arg3 arg1)))
15473 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15474 (if (org-bound-and-true-p european-calendar-style)
15475 (list arg2 arg1 arg3)
15476 (list arg1 arg2 arg3)))))
15478 (defun org-eval-in-calendar (form &optional keepdate)
15479 "Eval FORM in the calendar window and return to current window.
15480 Also, store the cursor date in variable org-ans2."
15481 (let ((sf (selected-frame))
15482 (sw (selected-window)))
15483 (select-window (get-buffer-window "*Calendar*" t))
15484 (eval form)
15485 (when (and (not keepdate) (calendar-cursor-to-date))
15486 (let* ((date (calendar-cursor-to-date))
15487 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15488 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15489 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15490 (select-window sw)
15491 (org-select-frame-set-input-focus sf)))
15493 (defun org-calendar-select ()
15494 "Return to `org-read-date' with the date currently selected.
15495 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15496 (interactive)
15497 (when (calendar-cursor-to-date)
15498 (let* ((date (calendar-cursor-to-date))
15499 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15500 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15501 (if (active-minibuffer-window) (exit-minibuffer))))
15503 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15504 "Insert a date stamp for the date given by the internal TIME.
15505 WITH-HM means use the stamp format that includes the time of the day.
15506 INACTIVE means use square brackets instead of angular ones, so that the
15507 stamp will not contribute to the agenda.
15508 PRE and POST are optional strings to be inserted before and after the
15509 stamp.
15510 The command returns the inserted time stamp."
15511 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15512 stamp)
15513 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15514 (insert-before-markers (or pre ""))
15515 (when (listp extra)
15516 (setq extra (car extra))
15517 (if (and (stringp extra)
15518 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15519 (setq extra (format "-%02d:%02d"
15520 (string-to-number (match-string 1 extra))
15521 (string-to-number (match-string 2 extra))))
15522 (setq extra nil)))
15523 (when extra
15524 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15525 (insert-before-markers (setq stamp (format-time-string fmt time)))
15526 (insert-before-markers (or post ""))
15527 (setq org-last-inserted-timestamp stamp)))
15529 (defun org-toggle-time-stamp-overlays ()
15530 "Toggle the use of custom time stamp formats."
15531 (interactive)
15532 (setq org-display-custom-times (not org-display-custom-times))
15533 (unless org-display-custom-times
15534 (let ((p (point-min)) (bmp (buffer-modified-p)))
15535 (while (setq p (next-single-property-change p 'display))
15536 (if (and (get-text-property p 'display)
15537 (eq (get-text-property p 'face) 'org-date))
15538 (remove-text-properties
15539 p (setq p (next-single-property-change p 'display))
15540 '(display t))))
15541 (set-buffer-modified-p bmp)))
15542 (if (featurep 'xemacs)
15543 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15544 (org-restart-font-lock)
15545 (setq org-table-may-need-update t)
15546 (if org-display-custom-times
15547 (message "Time stamps are overlaid with custom format")
15548 (message "Time stamp overlays removed")))
15550 (defun org-display-custom-time (beg end)
15551 "Overlay modified time stamp format over timestamp between BEG and END."
15552 (let* ((ts (buffer-substring beg end))
15553 t1 w1 with-hm tf time str w2 (off 0))
15554 (save-match-data
15555 (setq t1 (org-parse-time-string ts t))
15556 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15557 (setq off (- (match-end 0) (match-beginning 0)))))
15558 (setq end (- end off))
15559 (setq w1 (- end beg)
15560 with-hm (and (nth 1 t1) (nth 2 t1))
15561 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15562 time (org-fix-decoded-time t1)
15563 str (org-add-props
15564 (format-time-string
15565 (substring tf 1 -1) (apply 'encode-time time))
15566 nil 'mouse-face 'highlight)
15567 w2 (length str))
15568 (if (not (= w2 w1))
15569 (add-text-properties (1+ beg) (+ 2 beg)
15570 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15571 (if (featurep 'xemacs)
15572 (progn
15573 (put-text-property beg end 'invisible t)
15574 (put-text-property beg end 'end-glyph (make-glyph str)))
15575 (put-text-property beg end 'display str))))
15577 (defun org-translate-time (string)
15578 "Translate all timestamps in STRING to custom format.
15579 But do this only if the variable `org-display-custom-times' is set."
15580 (when org-display-custom-times
15581 (save-match-data
15582 (let* ((start 0)
15583 (re org-ts-regexp-both)
15584 t1 with-hm inactive tf time str beg end)
15585 (while (setq start (string-match re string start))
15586 (setq beg (match-beginning 0)
15587 end (match-end 0)
15588 t1 (save-match-data
15589 (org-parse-time-string (substring string beg end) t))
15590 with-hm (and (nth 1 t1) (nth 2 t1))
15591 inactive (equal (substring string beg (1+ beg)) "[")
15592 tf (funcall (if with-hm 'cdr 'car)
15593 org-time-stamp-custom-formats)
15594 time (org-fix-decoded-time t1)
15595 str (format-time-string
15596 (concat
15597 (if inactive "[" "<") (substring tf 1 -1)
15598 (if inactive "]" ">"))
15599 (apply 'encode-time time))
15600 string (replace-match str t t string)
15601 start (+ start (length str)))))))
15602 string)
15604 (defun org-fix-decoded-time (time)
15605 "Set 0 instead of nil for the first 6 elements of time.
15606 Don't touch the rest."
15607 (let ((n 0))
15608 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15610 (defun org-days-to-time (timestamp-string)
15611 "Difference between TIMESTAMP-STRING and now in days."
15612 (- (time-to-days (org-time-string-to-time timestamp-string))
15613 (time-to-days (current-time))))
15615 (defun org-deadline-close (timestamp-string &optional ndays)
15616 "Is the time in TIMESTAMP-STRING close to the current date?"
15617 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15618 (and (< (org-days-to-time timestamp-string) ndays)
15619 (not (org-entry-is-done-p))))
15621 (defun org-get-wdays (ts)
15622 "Get the deadline lead time appropriate for timestring TS."
15623 (cond
15624 ((<= org-deadline-warning-days 0)
15625 ;; 0 or negative, enforce this value no matter what
15626 (- org-deadline-warning-days))
15627 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15628 ;; lead time is specified.
15629 (floor (* (string-to-number (match-string 1 ts))
15630 (cdr (assoc (match-string 2 ts)
15631 '(("d" . 1) ("w" . 7)
15632 ("m" . 30.4) ("y" . 365.25)))))))
15633 ;; go for the default.
15634 (t org-deadline-warning-days)))
15636 (defun org-calendar-select-mouse (ev)
15637 "Return to `org-read-date' with the date currently selected.
15638 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15639 (interactive "e")
15640 (mouse-set-point ev)
15641 (when (calendar-cursor-to-date)
15642 (let* ((date (calendar-cursor-to-date))
15643 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15644 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15645 (if (active-minibuffer-window) (exit-minibuffer))))
15647 (defun org-check-deadlines (ndays)
15648 "Check if there are any deadlines due or past due.
15649 A deadline is considered due if it happens within `org-deadline-warning-days'
15650 days from today's date. If the deadline appears in an entry marked DONE,
15651 it is not shown. The prefix arg NDAYS can be used to test that many
15652 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15653 (interactive "P")
15654 (let* ((org-warn-days
15655 (cond
15656 ((equal ndays '(4)) 100000)
15657 (ndays (prefix-numeric-value ndays))
15658 (t (abs org-deadline-warning-days))))
15659 (case-fold-search nil)
15660 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15661 (callback
15662 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15664 (message "%d deadlines past-due or due within %d days"
15665 (org-occur regexp nil callback)
15666 org-warn-days)))
15668 (defun org-check-before-date (date)
15669 "Check if there are deadlines or scheduled entries before DATE."
15670 (interactive (list (org-read-date)))
15671 (let ((case-fold-search nil)
15672 (regexp (concat "\\<\\(" org-deadline-string
15673 "\\|" org-scheduled-string
15674 "\\) *<\\([^>]+\\)>"))
15675 (callback
15676 (lambda () (time-less-p
15677 (org-time-string-to-time (match-string 2))
15678 (org-time-string-to-time date)))))
15679 (message "%d entries before %s"
15680 (org-occur regexp nil callback) date)))
15682 (defun org-check-after-date (date)
15683 "Check if there are deadlines or scheduled entries after DATE."
15684 (interactive (list (org-read-date)))
15685 (let ((case-fold-search nil)
15686 (regexp (concat "\\<\\(" org-deadline-string
15687 "\\|" org-scheduled-string
15688 "\\) *<\\([^>]+\\)>"))
15689 (callback
15690 (lambda () (not
15691 (time-less-p
15692 (org-time-string-to-time (match-string 2))
15693 (org-time-string-to-time date))))))
15694 (message "%d entries after %s"
15695 (org-occur regexp nil callback) date)))
15697 (defun org-check-dates-range (start-date end-date)
15698 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15699 (interactive (list (org-read-date nil nil nil "Range starts")
15700 (org-read-date nil nil nil "Range end")))
15701 (let ((case-fold-search nil)
15702 (regexp (concat "\\<\\(" org-deadline-string
15703 "\\|" org-scheduled-string
15704 "\\) *<\\([^>]+\\)>"))
15705 (callback
15706 (lambda ()
15707 (let ((match (match-string 2)))
15708 (and
15709 (not (time-less-p
15710 (org-time-string-to-time match)
15711 (org-time-string-to-time start-date)))
15712 (time-less-p
15713 (org-time-string-to-time match)
15714 (org-time-string-to-time end-date)))))))
15715 (message "%d entries between %s and %s"
15716 (org-occur regexp nil callback) start-date end-date)))
15718 (defun org-evaluate-time-range (&optional to-buffer)
15719 "Evaluate a time range by computing the difference between start and end.
15720 Normally the result is just printed in the echo area, but with prefix arg
15721 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15722 If the time range is actually in a table, the result is inserted into the
15723 next column.
15724 For time difference computation, a year is assumed to be exactly 365
15725 days in order to avoid rounding problems."
15726 (interactive "P")
15728 (org-clock-update-time-maybe)
15729 (save-excursion
15730 (unless (org-at-date-range-p t)
15731 (goto-char (point-at-bol))
15732 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15733 (if (not (org-at-date-range-p t))
15734 (error "Not at a time-stamp range, and none found in current line")))
15735 (let* ((ts1 (match-string 1))
15736 (ts2 (match-string 2))
15737 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15738 (match-end (match-end 0))
15739 (time1 (org-time-string-to-time ts1))
15740 (time2 (org-time-string-to-time ts2))
15741 (t1 (org-float-time time1))
15742 (t2 (org-float-time time2))
15743 (diff (abs (- t2 t1)))
15744 (negative (< (- t2 t1) 0))
15745 ;; (ys (floor (* 365 24 60 60)))
15746 (ds (* 24 60 60))
15747 (hs (* 60 60))
15748 (fy "%dy %dd %02d:%02d")
15749 (fy1 "%dy %dd")
15750 (fd "%dd %02d:%02d")
15751 (fd1 "%dd")
15752 (fh "%02d:%02d")
15753 y d h m align)
15754 (if havetime
15755 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15757 d (floor (/ diff ds)) diff (mod diff ds)
15758 h (floor (/ diff hs)) diff (mod diff hs)
15759 m (floor (/ diff 60)))
15760 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15762 d (floor (+ (/ diff ds) 0.5))
15763 h 0 m 0))
15764 (if (not to-buffer)
15765 (message "%s" (org-make-tdiff-string y d h m))
15766 (if (org-at-table-p)
15767 (progn
15768 (goto-char match-end)
15769 (setq align t)
15770 (and (looking-at " *|") (goto-char (match-end 0))))
15771 (goto-char match-end))
15772 (if (looking-at
15773 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15774 (replace-match ""))
15775 (if negative (insert " -"))
15776 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15777 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15778 (insert " " (format fh h m))))
15779 (if align (org-table-align))
15780 (message "Time difference inserted")))))
15782 (defun org-make-tdiff-string (y d h m)
15783 (let ((fmt "")
15784 (l nil))
15785 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15786 l (push y l)))
15787 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15788 l (push d l)))
15789 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15790 l (push h l)))
15791 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15792 l (push m l)))
15793 (apply 'format fmt (nreverse l))))
15795 (defun org-time-string-to-time (s &optional buffer pos)
15796 (condition-case errdata
15797 (apply 'encode-time (org-parse-time-string s))
15798 (error (error "Bad timestamp `%s'%s\nError was: %s"
15799 s (if (not (and buffer pos))
15801 (format " at %d in buffer `%s'" pos buffer))
15802 (cdr errdata)))))
15804 (defun org-time-string-to-seconds (s)
15805 (org-float-time (org-time-string-to-time s)))
15807 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15808 "Convert a time stamp to an absolute day number.
15809 If there is a specifier for a cyclic time stamp, get the closest date to
15810 DAYNR.
15811 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15812 The variable date is bound by the calendar when this is called."
15813 (cond
15814 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15815 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15816 daynr
15817 (+ daynr 1000)))
15818 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15819 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15820 (time-to-days (current-time))) (match-string 0 s)
15821 prefer show-all))
15822 (t (time-to-days
15823 (condition-case errdata
15824 (apply 'encode-time (org-parse-time-string s))
15825 (error (error "Bad timestamp `%s'%s\nError was: %s"
15826 s (if (not (and buffer pos))
15828 (format " at %d in buffer `%s'" pos buffer))
15829 (cdr errdata))))))))
15831 (defun org-days-to-iso-week (days)
15832 "Return the iso week number."
15833 (require 'cal-iso)
15834 (car (calendar-iso-from-absolute days)))
15836 (defun org-small-year-to-year (year)
15837 "Convert 2-digit years into 4-digit years.
15838 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15839 The year 2000 cannot be abbreviated. Any year larger than 99
15840 is returned unchanged."
15841 (if (< year 38)
15842 (setq year (+ 2000 year))
15843 (if (< year 100)
15844 (setq year (+ 1900 year))))
15845 year)
15847 (defun org-time-from-absolute (d)
15848 "Return the time corresponding to date D.
15849 D may be an absolute day number, or a calendar-type list (month day year)."
15850 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15851 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15853 (defun org-calendar-holiday ()
15854 "List of holidays, for Diary display in Org-mode."
15855 (require 'holidays)
15856 (let ((hl (funcall
15857 (if (fboundp 'calendar-check-holidays)
15858 'calendar-check-holidays 'check-calendar-holidays) date)))
15859 (if hl (mapconcat 'identity hl "; "))))
15861 (defun org-diary-sexp-entry (sexp entry date)
15862 "Process a SEXP diary ENTRY for DATE."
15863 (require 'diary-lib)
15864 (let ((result (if calendar-debug-sexp
15865 (let ((stack-trace-on-error t))
15866 (eval (car (read-from-string sexp))))
15867 (condition-case nil
15868 (eval (car (read-from-string sexp)))
15869 (error
15870 (beep)
15871 (message "Bad sexp at line %d in %s: %s"
15872 (org-current-line)
15873 (buffer-file-name) sexp)
15874 (sleep-for 2))))))
15875 (cond ((stringp result) (split-string result "; "))
15876 ((and (consp result)
15877 (not (consp (cdr result)))
15878 (stringp (cdr result))) (cdr result))
15879 ((and (consp result)
15880 (stringp (car result))) result)
15881 (result entry)
15882 (t nil))))
15884 (defun org-diary-to-ical-string (frombuf)
15885 "Get iCalendar entries from diary entries in buffer FROMBUF.
15886 This uses the icalendar.el library."
15887 (let* ((tmpdir (if (featurep 'xemacs)
15888 (temp-directory)
15889 temporary-file-directory))
15890 (tmpfile (make-temp-name
15891 (expand-file-name "orgics" tmpdir)))
15892 buf rtn b e)
15893 (with-current-buffer frombuf
15894 (icalendar-export-region (point-min) (point-max) tmpfile)
15895 (setq buf (find-buffer-visiting tmpfile))
15896 (set-buffer buf)
15897 (goto-char (point-min))
15898 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15899 (setq b (match-beginning 0)))
15900 (goto-char (point-max))
15901 (if (re-search-backward "^END:VEVENT" nil t)
15902 (setq e (match-end 0)))
15903 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15904 (kill-buffer buf)
15905 (delete-file tmpfile)
15906 rtn))
15908 (defun org-closest-date (start current change prefer show-all)
15909 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15910 When PREFER is `past', return a date that is either CURRENT or past.
15911 When PREFER is `future', return a date that is either CURRENT or future.
15912 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15913 ;; Make the proper lists from the dates
15914 (catch 'exit
15915 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15916 dn dw sday cday n1 n2 n0
15917 d m y y1 y2 date1 date2 nmonths nm ny m2)
15919 (setq start (org-date-to-gregorian start)
15920 current (org-date-to-gregorian
15921 (if show-all
15922 current
15923 (time-to-days (current-time))))
15924 sday (calendar-absolute-from-gregorian start)
15925 cday (calendar-absolute-from-gregorian current))
15927 (if (<= cday sday) (throw 'exit sday))
15929 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15930 (setq dn (string-to-number (match-string 1 change))
15931 dw (cdr (assoc (match-string 2 change) a1)))
15932 (error "Invalid change specifier: %s" change))
15933 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15934 (cond
15935 ((eq dw 'day)
15936 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15937 n2 (+ n1 dn)))
15938 ((eq dw 'year)
15939 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15940 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15941 (setq date1 (list m d y1)
15942 n1 (calendar-absolute-from-gregorian date1)
15943 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15944 n2 (calendar-absolute-from-gregorian date2)))
15945 ((eq dw 'month)
15946 ;; approx number of month between the two dates
15947 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15948 ;; How often does dn fit in there?
15949 (setq d (nth 1 start) m (car start) y (nth 2 start)
15950 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15951 m (+ m nm)
15952 ny (floor (/ m 12))
15953 y (+ y ny)
15954 m (- m (* ny 12)))
15955 (while (> m 12) (setq m (- m 12) y (1+ y)))
15956 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15957 (setq m2 (+ m dn) y2 y)
15958 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15959 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15960 (while (<= n2 cday)
15961 (setq n1 n2 m m2 y y2)
15962 (setq m2 (+ m dn) y2 y)
15963 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15964 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15965 ;; Make sure n1 is the earlier date
15966 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15967 (if show-all
15968 (cond
15969 ((eq prefer 'past) (if (= cday n2) n2 n1))
15970 ((eq prefer 'future) (if (= cday n1) n1 n2))
15971 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15972 (cond
15973 ((eq prefer 'past) (if (= cday n2) n2 n1))
15974 ((eq prefer 'future) (if (= cday n1) n1 n2))
15975 (t (if (= cday n1) n1 n2)))))))
15977 (defun org-date-to-gregorian (date)
15978 "Turn any specification of DATE into a Gregorian date for the calendar."
15979 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15980 ((and (listp date) (= (length date) 3)) date)
15981 ((stringp date)
15982 (setq date (org-parse-time-string date))
15983 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15984 ((listp date)
15985 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15987 (defun org-parse-time-string (s &optional nodefault)
15988 "Parse the standard Org-mode time string.
15989 This should be a lot faster than the normal `parse-time-string'.
15990 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15991 hour and minute fields will be nil if not given."
15992 (if (string-match org-ts-regexp0 s)
15993 (list 0
15994 (if (or (match-beginning 8) (not nodefault))
15995 (string-to-number (or (match-string 8 s) "0")))
15996 (if (or (match-beginning 7) (not nodefault))
15997 (string-to-number (or (match-string 7 s) "0")))
15998 (string-to-number (match-string 4 s))
15999 (string-to-number (match-string 3 s))
16000 (string-to-number (match-string 2 s))
16001 nil nil nil)
16002 (error "Not a standard Org-mode time string: %s" s)))
16004 (defun org-timestamp-up (&optional arg)
16005 "Increase the date item at the cursor by one.
16006 If the cursor is on the year, change the year. If it is on the month,
16007 the day or the time, change that.
16008 With prefix ARG, change by that many units."
16009 (interactive "p")
16010 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16012 (defun org-timestamp-down (&optional arg)
16013 "Decrease the date item at the cursor by one.
16014 If the cursor is on the year, change the year. If it is on the month,
16015 the day or the time, change that.
16016 With prefix ARG, change by that many units."
16017 (interactive "p")
16018 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16020 (defun org-timestamp-up-day (&optional arg)
16021 "Increase the date in the time stamp by one day.
16022 With prefix ARG, change that many days."
16023 (interactive "p")
16024 (if (and (not (org-at-timestamp-p t))
16025 (org-at-heading-p))
16026 (org-todo 'up)
16027 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16029 (defun org-timestamp-down-day (&optional arg)
16030 "Decrease the date in the time stamp by one day.
16031 With prefix ARG, change that many days."
16032 (interactive "p")
16033 (if (and (not (org-at-timestamp-p t))
16034 (org-at-heading-p))
16035 (org-todo 'down)
16036 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16038 (defun org-at-timestamp-p (&optional inactive-ok)
16039 "Determine if the cursor is in or at a timestamp."
16040 (interactive)
16041 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16042 (pos (point))
16043 (ans (or (looking-at tsr)
16044 (save-excursion
16045 (skip-chars-backward "^[<\n\r\t")
16046 (if (> (point) (point-min)) (backward-char 1))
16047 (and (looking-at tsr)
16048 (> (- (match-end 0) pos) -1))))))
16049 (and ans
16050 (boundp 'org-ts-what)
16051 (setq org-ts-what
16052 (cond
16053 ((= pos (match-beginning 0)) 'bracket)
16054 ;; Point is considered to be "on the bracket" whether
16055 ;; it's really on it or right after it.
16056 ((or (= pos (1- (match-end 0)))
16057 (= pos (match-end 0))) 'bracket)
16058 ((org-pos-in-match-range pos 2) 'year)
16059 ((org-pos-in-match-range pos 3) 'month)
16060 ((org-pos-in-match-range pos 7) 'hour)
16061 ((org-pos-in-match-range pos 8) 'minute)
16062 ((or (org-pos-in-match-range pos 4)
16063 (org-pos-in-match-range pos 5)) 'day)
16064 ((and (> pos (or (match-end 8) (match-end 5)))
16065 (< pos (match-end 0)))
16066 (- pos (or (match-end 8) (match-end 5))))
16067 (t 'day))))
16068 ans))
16070 (defun org-toggle-timestamp-type ()
16071 "Toggle the type (<active> or [inactive]) of a time stamp."
16072 (interactive)
16073 (when (org-at-timestamp-p t)
16074 (let ((beg (match-beginning 0)) (end (match-end 0))
16075 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16076 (save-excursion
16077 (goto-char beg)
16078 (while (re-search-forward "[][<>]" end t)
16079 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16080 t t)))
16081 (message "Timestamp is now %sactive"
16082 (if (equal (char-after beg) ?<) "" "in")))))
16084 (defun org-timestamp-change (n &optional what updown)
16085 "Change the date in the time stamp at point.
16086 The date will be changed by N times WHAT. WHAT can be `day', `month',
16087 `year', `minute', `second'. If WHAT is not given, the cursor position
16088 in the timestamp determines what will be changed."
16089 (let ((origin (point)) origin-cat
16090 with-hm inactive
16091 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16092 org-ts-what
16093 extra rem
16094 ts time time0)
16095 (if (not (org-at-timestamp-p t))
16096 (error "Not at a timestamp"))
16097 (if (and (not what) (eq org-ts-what 'bracket))
16098 (org-toggle-timestamp-type)
16099 ;; Point isn't on brackets. Remember the part of the time-stamp
16100 ;; the point was in. Indeed, size of time-stamps may change,
16101 ;; but point must be kept in the same category nonetheless.
16102 (setq origin-cat org-ts-what)
16103 (if (and (not what) (not (eq org-ts-what 'day))
16104 org-display-custom-times
16105 (get-text-property (point) 'display)
16106 (not (get-text-property (1- (point)) 'display)))
16107 (setq org-ts-what 'day))
16108 (setq org-ts-what (or what org-ts-what)
16109 inactive (= (char-after (match-beginning 0)) ?\[)
16110 ts (match-string 0))
16111 (replace-match "")
16112 (if (string-match
16113 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16115 (setq extra (match-string 1 ts)))
16116 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16117 (setq with-hm t))
16118 (setq time0 (org-parse-time-string ts))
16119 (when (and updown
16120 (eq org-ts-what 'minute)
16121 (not current-prefix-arg))
16122 ;; This looks like s-up and s-down. Change by one rounding step.
16123 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16124 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16125 (setcar (cdr time0) (+ (nth 1 time0)
16126 (if (> n 0) (- rem) (- dm rem))))))
16127 (setq time
16128 (encode-time (or (car time0) 0)
16129 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16130 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16131 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16132 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16133 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16134 (nthcdr 6 time0)))
16135 (when (and (member org-ts-what '(hour minute))
16136 extra
16137 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16138 (setq extra (org-modify-ts-extra
16139 extra
16140 (if (eq org-ts-what 'hour) 2 5)
16141 n dm)))
16142 (when (integerp org-ts-what)
16143 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16144 (if (eq what 'calendar)
16145 (let ((cal-date (org-get-date-from-calendar)))
16146 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16147 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16148 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16149 (setcar time0 (or (car time0) 0))
16150 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16151 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16152 (setq time (apply 'encode-time time0))))
16153 ;; Insert the new time-stamp, and ensure point stays in the same
16154 ;; category as before (i.e. not after the last position in that
16155 ;; category).
16156 (let ((pos (point)))
16157 ;; Stay before inserted string. `save-excursion' is of no use.
16158 (setq org-last-changed-timestamp
16159 (org-insert-time-stamp time with-hm inactive nil nil extra))
16160 (goto-char pos))
16161 (save-match-data
16162 (looking-at org-ts-regexp3)
16163 (goto-char (cond
16164 ;; `day' category ends before `hour' if any, or at
16165 ;; the end of the day name.
16166 ((eq origin-cat 'day)
16167 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16168 ((eq origin-cat 'hour) (min (match-end 7) origin))
16169 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16170 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16171 ;; `year' and `month' have both fixed size: point
16172 ;; couldn't have moved into another part.
16173 (t origin))))
16174 ;; Update clock if on a CLOCK line.
16175 (org-clock-update-time-maybe)
16176 ;; Try to recenter the calendar window, if any.
16177 (if (and org-calendar-follow-timestamp-change
16178 (get-buffer-window "*Calendar*" t)
16179 (memq org-ts-what '(day month year)))
16180 (org-recenter-calendar (time-to-days time))))))
16182 (defun org-modify-ts-extra (s pos n dm)
16183 "Change the different parts of the lead-time and repeat fields in timestamp."
16184 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16185 ng h m new rem)
16186 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16187 (cond
16188 ((or (org-pos-in-match-range pos 2)
16189 (org-pos-in-match-range pos 3))
16190 (setq m (string-to-number (match-string 3 s))
16191 h (string-to-number (match-string 2 s)))
16192 (if (org-pos-in-match-range pos 2)
16193 (setq h (+ h n))
16194 (setq n (* dm (org-no-warnings (signum n))))
16195 (when (not (= 0 (setq rem (% m dm))))
16196 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16197 (setq m (+ m n)))
16198 (if (< m 0) (setq m (+ m 60) h (1- h)))
16199 (if (> m 59) (setq m (- m 60) h (1+ h)))
16200 (setq h (min 24 (max 0 h)))
16201 (setq ng 1 new (format "-%02d:%02d" h m)))
16202 ((org-pos-in-match-range pos 6)
16203 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16204 ((org-pos-in-match-range pos 5)
16205 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16207 ((org-pos-in-match-range pos 9)
16208 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16209 ((org-pos-in-match-range pos 8)
16210 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16212 (when ng
16213 (setq s (concat
16214 (substring s 0 (match-beginning ng))
16216 (substring s (match-end ng))))))
16219 (defun org-recenter-calendar (date)
16220 "If the calendar is visible, recenter it to DATE."
16221 (let ((cwin (get-buffer-window "*Calendar*" t)))
16222 (when cwin
16223 (let ((calendar-move-hook nil))
16224 (with-selected-window cwin
16225 (calendar-goto-date (if (listp date) date
16226 (calendar-gregorian-from-absolute date))))))))
16228 (defun org-goto-calendar (&optional arg)
16229 "Go to the Emacs calendar at the current date.
16230 If there is a time stamp in the current line, go to that date.
16231 A prefix ARG can be used to force the current date."
16232 (interactive "P")
16233 (let ((tsr org-ts-regexp) diff
16234 (calendar-move-hook nil)
16235 (calendar-view-holidays-initially-flag nil)
16236 (calendar-view-diary-initially-flag nil))
16237 (if (or (org-at-timestamp-p)
16238 (save-excursion
16239 (beginning-of-line 1)
16240 (looking-at (concat ".*" tsr))))
16241 (let ((d1 (time-to-days (current-time)))
16242 (d2 (time-to-days
16243 (org-time-string-to-time (match-string 1)))))
16244 (setq diff (- d2 d1))))
16245 (calendar)
16246 (calendar-goto-today)
16247 (if (and diff (not arg)) (calendar-forward-day diff))))
16249 (defun org-get-date-from-calendar ()
16250 "Return a list (month day year) of date at point in calendar."
16251 (with-current-buffer "*Calendar*"
16252 (save-match-data
16253 (calendar-cursor-to-date))))
16255 (defun org-date-from-calendar ()
16256 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16257 If there is already a time stamp at the cursor position, update it."
16258 (interactive)
16259 (if (org-at-timestamp-p t)
16260 (org-timestamp-change 0 'calendar)
16261 (let ((cal-date (org-get-date-from-calendar)))
16262 (org-insert-time-stamp
16263 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16265 (defun org-minutes-to-hh:mm-string (m)
16266 "Compute H:MM from a number of minutes."
16267 (let ((h (/ m 60)))
16268 (setq m (- m (* 60 h)))
16269 (format org-time-clocksum-format h m)))
16271 (defun org-hh:mm-string-to-minutes (s)
16272 "Convert a string H:MM to a number of minutes.
16273 If the string is just a number, interpret it as minutes.
16274 In fact, the first hh:mm or number in the string will be taken,
16275 there can be extra stuff in the string.
16276 If no number is found, the return value is 0."
16277 (cond
16278 ((integerp s) s)
16279 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16280 (+ (* (string-to-number (match-string 1 s)) 60)
16281 (string-to-number (match-string 2 s))))
16282 ((string-match "\\([0-9]+\\)" s)
16283 (string-to-number (match-string 1 s)))
16284 (t 0)))
16286 (defcustom org-effort-durations
16287 `(("h" . 60)
16288 ("d" . ,(* 60 8))
16289 ("w" . ,(* 60 8 5))
16290 ("m" . ,(* 60 8 5 4))
16291 ("y" . ,(* 60 8 5 40)))
16292 "Conversion factor to minutes for an effort modifier.
16294 Each entry has the form (MODIFIER . MINUTES).
16296 In an effort string, a number followed by MODIFIER is multiplied
16297 by the specified number of MINUTES to obtain an effort in
16298 minutes.
16300 For example, if the value of this variable is ((\"hours\" . 60)), then an
16301 effort string \"2hours\" is equivalent to 120 minutes."
16302 :group 'org-agenda
16303 :version "24.1"
16304 :type '(alist :key-type (string :tag "Modifier")
16305 :value-type (number :tag "Minutes")))
16307 (defun org-duration-string-to-minutes (s)
16308 "Convert a duration string S to minutes.
16310 A bare number is interpreted as minutes, modifiers can be set by
16311 customizing `org-effort-durations' (which see).
16313 Entries containing a colon are interpreted as H:MM by
16314 `org-hh:mm-string-to-minutes'."
16315 (let ((result 0)
16316 (re (concat "\\([0-9]+\\) *\\("
16317 (regexp-opt (mapcar 'car org-effort-durations))
16318 "\\)")))
16319 (while (string-match re s)
16320 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16321 (string-to-number (match-string 1 s))))
16322 (setq s (replace-match "" nil t s)))
16323 (incf result (org-hh:mm-string-to-minutes s))
16324 result))
16326 ;;;; Files
16328 (defun org-save-all-org-buffers ()
16329 "Save all Org-mode buffers without user confirmation."
16330 (interactive)
16331 (message "Saving all Org-mode buffers...")
16332 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16333 (when (featurep 'org-id) (org-id-locations-save))
16334 (message "Saving all Org-mode buffers... done"))
16336 (defun org-revert-all-org-buffers ()
16337 "Revert all Org-mode buffers.
16338 Prompt for confirmation when there are unsaved changes.
16339 Be sure you know what you are doing before letting this function
16340 overwrite your changes.
16342 This function is useful in a setup where one tracks org files
16343 with a version control system, to revert on one machine after pulling
16344 changes from another. I believe the procedure must be like this:
16346 1. M-x org-save-all-org-buffers
16347 2. Pull changes from the other machine, resolve conflicts
16348 3. M-x org-revert-all-org-buffers"
16349 (interactive)
16350 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16351 (error "Abort"))
16352 (save-excursion
16353 (save-window-excursion
16354 (mapc
16355 (lambda (b)
16356 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16357 (with-current-buffer b buffer-file-name))
16358 (org-pop-to-buffer-same-window b)
16359 (revert-buffer t 'no-confirm)))
16360 (buffer-list))
16361 (when (and (featurep 'org-id) org-id-track-globally)
16362 (org-id-locations-load)))))
16364 ;;;; Agenda files
16366 ;;;###autoload
16367 (defun org-switchb (&optional arg)
16368 "Switch between Org buffers.
16369 With one prefix argument, restrict available buffers to files.
16370 With two prefix arguments, restrict available buffers to agenda files.
16372 Defaults to `iswitchb' for buffer name completion.
16373 Set `org-completion-use-ido' to make it use ido instead."
16374 (interactive "P")
16375 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16376 ((equal arg '(16)) (org-buffer-list 'agenda))
16377 (t (org-buffer-list))))
16378 (org-completion-use-iswitchb org-completion-use-iswitchb)
16379 (org-completion-use-ido org-completion-use-ido))
16380 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16381 (setq org-completion-use-iswitchb t))
16382 (org-pop-to-buffer-same-window
16383 (org-icompleting-read "Org buffer: "
16384 (mapcar 'list (mapcar 'buffer-name blist))
16385 nil t))))
16387 ;;; Define some older names previously used for this functionality
16388 ;;;###autoload
16389 (defalias 'org-ido-switchb 'org-switchb)
16390 ;;;###autoload
16391 (defalias 'org-iswitchb 'org-switchb)
16393 (defun org-buffer-list (&optional predicate exclude-tmp)
16394 "Return a list of Org buffers.
16395 PREDICATE can be `export', `files' or `agenda'.
16397 export restrict the list to Export buffers.
16398 files restrict the list to buffers visiting Org files.
16399 agenda restrict the list to buffers visiting agenda files.
16401 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16402 (let* ((bfn nil)
16403 (agenda-files (and (eq predicate 'agenda)
16404 (mapcar 'file-truename (org-agenda-files t))))
16405 (filter
16406 (cond
16407 ((eq predicate 'files)
16408 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16409 ((eq predicate 'export)
16410 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16411 ((eq predicate 'agenda)
16412 (lambda (b)
16413 (with-current-buffer b
16414 (and (eq major-mode 'org-mode)
16415 (setq bfn (buffer-file-name b))
16416 (member (file-truename bfn) agenda-files)))))
16417 (t (lambda (b) (with-current-buffer b
16418 (or (eq major-mode 'org-mode)
16419 (string-match "\*Org .*Export"
16420 (buffer-name b)))))))))
16421 (delq nil
16422 (mapcar
16423 (lambda(b)
16424 (if (and (funcall filter b)
16425 (or (not exclude-tmp)
16426 (not (string-match "tmp" (buffer-name b)))))
16428 nil))
16429 (buffer-list)))))
16431 (defun org-agenda-files (&optional unrestricted archives)
16432 "Get the list of agenda files.
16433 Optional UNRESTRICTED means return the full list even if a restriction
16434 is currently in place.
16435 When ARCHIVES is t, include all archive files that are really being
16436 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16437 `org-agenda-archives-mode' is t."
16438 (let ((files
16439 (cond
16440 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16441 ((stringp org-agenda-files) (org-read-agenda-file-list))
16442 ((listp org-agenda-files) org-agenda-files)
16443 (t (error "Invalid value of `org-agenda-files'")))))
16444 (setq files (apply 'append
16445 (mapcar (lambda (f)
16446 (if (file-directory-p f)
16447 (directory-files
16448 f t org-agenda-file-regexp)
16449 (list f)))
16450 files)))
16451 (when org-agenda-skip-unavailable-files
16452 (setq files (delq nil
16453 (mapcar (function
16454 (lambda (file)
16455 (and (file-readable-p file) file)))
16456 files))))
16457 (when (or (eq archives t)
16458 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16459 (setq files (org-add-archive-files files)))
16460 files))
16462 (defun org-agenda-file-p (&optional file)
16463 "Return non-nil, if FILE is an agenda file.
16464 If FILE is omitted, use the file associated with the current
16465 buffer."
16466 (member (or file (buffer-file-name))
16467 (org-agenda-files t)))
16469 (defun org-edit-agenda-file-list ()
16470 "Edit the list of agenda files.
16471 Depending on setup, this either uses customize to edit the variable
16472 `org-agenda-files', or it visits the file that is holding the list. In the
16473 latter case, the buffer is set up in a way that saving it automatically kills
16474 the buffer and restores the previous window configuration."
16475 (interactive)
16476 (if (stringp org-agenda-files)
16477 (let ((cw (current-window-configuration)))
16478 (find-file org-agenda-files)
16479 (org-set-local 'org-window-configuration cw)
16480 (org-add-hook 'after-save-hook
16481 (lambda ()
16482 (set-window-configuration
16483 (prog1 org-window-configuration
16484 (kill-buffer (current-buffer))))
16485 (org-install-agenda-files-menu)
16486 (message "New agenda file list installed"))
16487 nil 'local)
16488 (message "%s" (substitute-command-keys
16489 "Edit list and finish with \\[save-buffer]")))
16490 (customize-variable 'org-agenda-files)))
16492 (defun org-store-new-agenda-file-list (list)
16493 "Set new value for the agenda file list and save it correctly."
16494 (if (stringp org-agenda-files)
16495 (let ((fe (org-read-agenda-file-list t)) b u)
16496 (while (setq b (find-buffer-visiting org-agenda-files))
16497 (kill-buffer b))
16498 (with-temp-file org-agenda-files
16499 (insert
16500 (mapconcat
16501 (lambda (f) ;; Keep un-expanded entries.
16502 (if (setq u (assoc f fe))
16503 (cdr u)
16505 list "\n")
16506 "\n")))
16507 (let ((org-mode-hook nil) (org-inhibit-startup t)
16508 (org-insert-mode-line-in-empty-file nil))
16509 (setq org-agenda-files list)
16510 (customize-save-variable 'org-agenda-files org-agenda-files))))
16512 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16513 "Read the list of agenda files from a file.
16514 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16515 filenames, used by `org-store-new-agenda-file-list' to write back
16516 un-expanded file names."
16517 (when (file-directory-p org-agenda-files)
16518 (error "`org-agenda-files' cannot be a single directory"))
16519 (when (stringp org-agenda-files)
16520 (with-temp-buffer
16521 (insert-file-contents org-agenda-files)
16522 (mapcar
16523 (lambda (f)
16524 (let ((e (expand-file-name (substitute-in-file-name f)
16525 org-directory)))
16526 (if pair-with-expansion
16527 (cons e f)
16528 e)))
16529 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16531 ;;;###autoload
16532 (defun org-cycle-agenda-files ()
16533 "Cycle through the files in `org-agenda-files'.
16534 If the current buffer visits an agenda file, find the next one in the list.
16535 If the current buffer does not, find the first agenda file."
16536 (interactive)
16537 (let* ((fs (org-agenda-files t))
16538 (files (append fs (list (car fs))))
16539 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16540 file)
16541 (unless files (error "No agenda files"))
16542 (catch 'exit
16543 (while (setq file (pop files))
16544 (if (equal (file-truename file) tcf)
16545 (when (car files)
16546 (find-file (car files))
16547 (throw 'exit t))))
16548 (find-file (car fs)))
16549 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16551 (defun org-agenda-file-to-front (&optional to-end)
16552 "Move/add the current file to the top of the agenda file list.
16553 If the file is not present in the list, it is added to the front. If it is
16554 present, it is moved there. With optional argument TO-END, add/move to the
16555 end of the list."
16556 (interactive "P")
16557 (let ((org-agenda-skip-unavailable-files nil)
16558 (file-alist (mapcar (lambda (x)
16559 (cons (file-truename x) x))
16560 (org-agenda-files t)))
16561 (ctf (file-truename buffer-file-name))
16562 x had)
16563 (setq x (assoc ctf file-alist) had x)
16565 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16566 (if to-end
16567 (setq file-alist (append (delq x file-alist) (list x)))
16568 (setq file-alist (cons x (delq x file-alist))))
16569 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16570 (org-install-agenda-files-menu)
16571 (message "File %s to %s of agenda file list"
16572 (if had "moved" "added") (if to-end "end" "front"))))
16574 (defun org-remove-file (&optional file)
16575 "Remove current file from the list of files in variable `org-agenda-files'.
16576 These are the files which are being checked for agenda entries.
16577 Optional argument FILE means use this file instead of the current."
16578 (interactive)
16579 (let* ((org-agenda-skip-unavailable-files nil)
16580 (file (or file buffer-file-name))
16581 (true-file (file-truename file))
16582 (afile (abbreviate-file-name file))
16583 (files (delq nil (mapcar
16584 (lambda (x)
16585 (if (equal true-file
16586 (file-truename x))
16587 nil x))
16588 (org-agenda-files t)))))
16589 (if (not (= (length files) (length (org-agenda-files t))))
16590 (progn
16591 (org-store-new-agenda-file-list files)
16592 (org-install-agenda-files-menu)
16593 (message "Removed file: %s" afile))
16594 (message "File was not in list: %s (not removed)" afile))))
16596 (defun org-file-menu-entry (file)
16597 (vector file (list 'find-file file) t))
16599 (defun org-check-agenda-file (file)
16600 "Make sure FILE exists. If not, ask user what to do."
16601 (when (not (file-exists-p file))
16602 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16603 (abbreviate-file-name file))
16604 (let ((r (downcase (read-char-exclusive))))
16605 (cond
16606 ((equal r ?r)
16607 (org-remove-file file)
16608 (throw 'nextfile t))
16609 (t (error "Abort"))))))
16611 (defun org-get-agenda-file-buffer (file)
16612 "Get a buffer visiting FILE. If the buffer needs to be created, add
16613 it to the list of buffers which might be released later."
16614 (let ((buf (org-find-base-buffer-visiting file)))
16615 (if buf
16616 buf ; just return it
16617 ;; Make a new buffer and remember it
16618 (setq buf (find-file-noselect file))
16619 (if buf (push buf org-agenda-new-buffers))
16620 buf)))
16622 (defun org-release-buffers (blist)
16623 "Release all buffers in list, asking the user for confirmation when needed.
16624 When a buffer is unmodified, it is just killed. When modified, it is saved
16625 \(if the user agrees) and then killed."
16626 (let (buf file)
16627 (while (setq buf (pop blist))
16628 (setq file (buffer-file-name buf))
16629 (when (and (buffer-modified-p buf)
16630 file
16631 (y-or-n-p (format "Save file %s? " file)))
16632 (with-current-buffer buf (save-buffer)))
16633 (kill-buffer buf))))
16635 (defun org-prepare-agenda-buffers (files)
16636 "Create buffers for all agenda files, protect archived trees and comments."
16637 (interactive)
16638 (let ((pa '(:org-archived t))
16639 (pc '(:org-comment t))
16640 (pall '(:org-archived t :org-comment t))
16641 (inhibit-read-only t)
16642 (rea (concat ":" org-archive-tag ":"))
16643 bmp file re)
16644 (save-excursion
16645 (save-restriction
16646 (while (setq file (pop files))
16647 (catch 'nextfile
16648 (if (bufferp file)
16649 (set-buffer file)
16650 (org-check-agenda-file file)
16651 (set-buffer (org-get-agenda-file-buffer file)))
16652 (widen)
16653 (setq bmp (buffer-modified-p))
16654 (org-refresh-category-properties)
16655 (setq org-todo-keywords-for-agenda
16656 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16657 (setq org-done-keywords-for-agenda
16658 (append org-done-keywords-for-agenda org-done-keywords))
16659 (setq org-todo-keyword-alist-for-agenda
16660 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16661 (setq org-drawers-for-agenda
16662 (append org-drawers-for-agenda org-drawers))
16663 (setq org-tag-alist-for-agenda
16664 (append org-tag-alist-for-agenda org-tag-alist))
16666 (save-excursion
16667 (remove-text-properties (point-min) (point-max) pall)
16668 (when org-agenda-skip-archived-trees
16669 (goto-char (point-min))
16670 (while (re-search-forward rea nil t)
16671 (if (org-at-heading-p t)
16672 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16673 (goto-char (point-min))
16674 (setq re (format org-heading-keyword-regexp-format
16675 org-comment-string))
16676 (while (re-search-forward re nil t)
16677 (add-text-properties
16678 (match-beginning 0) (org-end-of-subtree t) pc)))
16679 (set-buffer-modified-p bmp)))))
16680 (setq org-todo-keywords-for-agenda
16681 (org-uniquify org-todo-keywords-for-agenda))
16682 (setq org-todo-keyword-alist-for-agenda
16683 (org-uniquify org-todo-keyword-alist-for-agenda)
16684 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16686 ;;;; Embedded LaTeX
16688 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16689 "Keymap for the minor `org-cdlatex-mode'.")
16691 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16692 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16693 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16694 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16695 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16697 (defvar org-cdlatex-texmathp-advice-is-done nil
16698 "Flag remembering if we have applied the advice to texmathp already.")
16700 (define-minor-mode org-cdlatex-mode
16701 "Toggle the minor `org-cdlatex-mode'.
16702 This mode supports entering LaTeX environment and math in LaTeX fragments
16703 in Org-mode.
16704 \\{org-cdlatex-mode-map}"
16705 nil " OCDL" nil
16706 (when org-cdlatex-mode
16707 (require 'cdlatex)
16708 (run-hooks 'cdlatex-mode-hook)
16709 (cdlatex-compute-tables))
16710 (unless org-cdlatex-texmathp-advice-is-done
16711 (setq org-cdlatex-texmathp-advice-is-done t)
16712 (defadvice texmathp (around org-math-always-on activate)
16713 "Always return t in org-mode buffers.
16714 This is because we want to insert math symbols without dollars even outside
16715 the LaTeX math segments. If Orgmode thinks that point is actually inside
16716 an embedded LaTeX fragment, let texmathp do its job.
16717 \\[org-cdlatex-mode-map]"
16718 (interactive)
16719 (let (p)
16720 (cond
16721 ((not (eq major-mode 'org-mode)) ad-do-it)
16722 ((eq this-command 'cdlatex-math-symbol)
16723 (setq ad-return-value t
16724 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16726 (let ((p (org-inside-LaTeX-fragment-p)))
16727 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16728 (setq ad-return-value t
16729 texmathp-why '("Org-mode embedded math" . 0))
16730 (if p ad-do-it)))))))))
16732 (defun turn-on-org-cdlatex ()
16733 "Unconditionally turn on `org-cdlatex-mode'."
16734 (org-cdlatex-mode 1))
16736 (defun org-inside-LaTeX-fragment-p ()
16737 "Test if point is inside a LaTeX fragment.
16738 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16739 sequence appearing also before point.
16740 Even though the matchers for math are configurable, this function assumes
16741 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16742 delimiters are skipped when they have been removed by customization.
16743 The return value is nil, or a cons cell with the delimiter and the
16744 position of this delimiter.
16746 This function does a reasonably good job, but can locally be fooled by
16747 for example currency specifications. For example it will assume being in
16748 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16749 fragments that are properly closed, but during editing, we have to live
16750 with the uncertainty caused by missing closing delimiters. This function
16751 looks only before point, not after."
16752 (catch 'exit
16753 (let ((pos (point))
16754 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16755 (lim (progn
16756 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16757 (point)))
16758 dd-on str (start 0) m re)
16759 (goto-char pos)
16760 (when dodollar
16761 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16762 re (nth 1 (assoc "$" org-latex-regexps)))
16763 (while (string-match re str start)
16764 (cond
16765 ((= (match-end 0) (length str))
16766 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16767 ((= (match-end 0) (- (length str) 5))
16768 (throw 'exit nil))
16769 (t (setq start (match-end 0))))))
16770 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16771 (goto-char pos)
16772 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16773 (and (match-beginning 2) (throw 'exit nil))
16774 ;; count $$
16775 (while (re-search-backward "\\$\\$" lim t)
16776 (setq dd-on (not dd-on)))
16777 (goto-char pos)
16778 (if dd-on (cons "$$" m))))))
16780 (defun org-inside-latex-macro-p ()
16781 "Is point inside a LaTeX macro or its arguments?"
16782 (save-match-data
16783 (org-in-regexp
16784 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16786 (defun org-try-cdlatex-tab ()
16787 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16788 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16789 - inside a LaTeX fragment, or
16790 - after the first word in a line, where an abbreviation expansion could
16791 insert a LaTeX environment."
16792 (when org-cdlatex-mode
16793 (cond
16794 ;; Before any word on the line: No expansion possible.
16795 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16796 ;; Just after first word on the line: Expand it. Make sure it
16797 ;; cannot happen on headlines, though.
16798 ((save-excursion
16799 (skip-chars-backward "a-zA-Z0-9*")
16800 (skip-chars-backward " \t")
16801 (and (bolp) (not (org-at-heading-p))))
16802 (cdlatex-tab) t)
16803 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16805 (defun org-cdlatex-underscore-caret (&optional arg)
16806 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16807 Revert to the normal definition outside of these fragments."
16808 (interactive "P")
16809 (if (org-inside-LaTeX-fragment-p)
16810 (call-interactively 'cdlatex-sub-superscript)
16811 (let (org-cdlatex-mode)
16812 (call-interactively (key-binding (vector last-input-event))))))
16814 (defun org-cdlatex-math-modify (&optional arg)
16815 "Execute `cdlatex-math-modify' in LaTeX fragments.
16816 Revert to the normal definition outside of these fragments."
16817 (interactive "P")
16818 (if (org-inside-LaTeX-fragment-p)
16819 (call-interactively 'cdlatex-math-modify)
16820 (let (org-cdlatex-mode)
16821 (call-interactively (key-binding (vector last-input-event))))))
16823 (defvar org-latex-fragment-image-overlays nil
16824 "List of overlays carrying the images of latex fragments.")
16825 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16827 (defun org-remove-latex-fragment-image-overlays ()
16828 "Remove all overlays with LaTeX fragment images in current buffer."
16829 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16830 (setq org-latex-fragment-image-overlays nil))
16832 (defun org-preview-latex-fragment (&optional subtree)
16833 "Preview the LaTeX fragment at point, or all locally or globally.
16834 If the cursor is in a LaTeX fragment, create the image and overlay
16835 it over the source code. If there is no fragment at point, display
16836 all fragments in the current text, from one headline to the next. With
16837 prefix SUBTREE, display all fragments in the current subtree. With a
16838 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16839 the cursor is before the first headline,
16840 display all fragments in the buffer.
16841 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16842 (interactive "P")
16843 (unless buffer-file-name
16844 (error "Can't preview LaTeX fragment in a non-file buffer"))
16845 (org-remove-latex-fragment-image-overlays)
16846 (save-excursion
16847 (save-restriction
16848 (let (beg end at msg)
16849 (cond
16850 ((or (equal subtree '(16))
16851 (not (save-excursion
16852 (re-search-backward org-outline-regexp-bol nil t))))
16853 (setq beg (point-min) end (point-max)
16854 msg "Creating images for buffer...%s"))
16855 ((equal subtree '(4))
16856 (org-back-to-heading)
16857 (setq beg (point) end (org-end-of-subtree t)
16858 msg "Creating images for subtree...%s"))
16860 (if (setq at (org-inside-LaTeX-fragment-p))
16861 (goto-char (max (point-min) (- (cdr at) 2)))
16862 (org-back-to-heading))
16863 (setq beg (point) end (progn (outline-next-heading) (point))
16864 msg (if at "Creating image...%s"
16865 "Creating images for entry...%s"))))
16866 (message msg "")
16867 (narrow-to-region beg end)
16868 (goto-char beg)
16869 (org-format-latex
16870 (concat "ltxpng/" (file-name-sans-extension
16871 (file-name-nondirectory
16872 buffer-file-name)))
16873 default-directory 'overlays msg at 'forbuffer 'dvipng)
16874 (message msg "done. Use `C-c C-c' to remove images.")))))
16876 (defvar org-latex-regexps
16877 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16878 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16879 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16880 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16881 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16882 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16883 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16884 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16885 "Regular expressions for matching embedded LaTeX.")
16887 (defvar org-export-have-math nil) ;; dynamic scoping
16888 (defun org-format-latex (prefix &optional dir overlays msg at
16889 forbuffer processing-type)
16890 "Replace LaTeX fragments with links to an image, and produce images.
16891 Some of the options can be changed using the variable
16892 `org-format-latex-options'."
16893 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16894 (let* ((prefixnodir (file-name-nondirectory prefix))
16895 (absprefix (expand-file-name prefix dir))
16896 (todir (file-name-directory absprefix))
16897 (opt org-format-latex-options)
16898 (matchers (plist-get opt :matchers))
16899 (re-list org-latex-regexps)
16900 (org-format-latex-header-extra
16901 (plist-get (org-infile-export-plist) :latex-header-extra))
16902 (cnt 0) txt hash link beg end re e checkdir
16903 executables-checked string
16904 m n block-type block linkfile movefile ov)
16905 ;; Check the different regular expressions
16906 (while (setq e (pop re-list))
16907 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16908 block (if block-type "\n\n" ""))
16909 (when (member m matchers)
16910 (goto-char (point-min))
16911 (while (re-search-forward re nil t)
16912 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16913 (not (get-text-property (match-beginning n)
16914 'org-protected))
16915 (or (not overlays)
16916 (not (eq (get-char-property (match-beginning n)
16917 'org-overlay-type)
16918 'org-latex-overlay))))
16919 (setq org-export-have-math t)
16920 (cond
16921 ((eq processing-type 'verbatim)
16922 ;; Leave the text verbatim, just protect it
16923 (add-text-properties (match-beginning n) (match-end n)
16924 '(org-protected t)))
16925 ((eq processing-type 'mathjax)
16926 ;; Prepare for MathJax processing
16927 (setq string (match-string n))
16928 (if (member m '("$" "$1"))
16929 (save-excursion
16930 (delete-region (match-beginning n) (match-end n))
16931 (goto-char (match-beginning n))
16932 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16933 "\\)")
16934 '(org-protected t))))
16935 (add-text-properties (match-beginning n) (match-end n)
16936 '(org-protected t))))
16937 ((eq processing-type 'dvipng)
16938 ;; Process to an image
16939 (setq txt (match-string n)
16940 beg (match-beginning n) end (match-end n)
16941 cnt (1+ cnt))
16942 (let (print-length print-level) ; make sure full list is printed
16943 (setq hash (sha1 (prin1-to-string
16944 (list org-format-latex-header
16945 org-format-latex-header-extra
16946 org-export-latex-default-packages-alist
16947 org-export-latex-packages-alist
16948 org-format-latex-options
16949 forbuffer txt)))
16950 linkfile (format "%s_%s.png" prefix hash)
16951 movefile (format "%s_%s.png" absprefix hash)))
16952 (setq link (concat block "[[file:" linkfile "]]" block))
16953 (if msg (message msg cnt))
16954 (goto-char beg)
16955 (unless checkdir ; make sure the directory exists
16956 (setq checkdir t)
16957 (or (file-directory-p todir) (make-directory todir t)))
16959 (unless executables-checked
16960 (org-check-external-command
16961 "latex" "needed to convert LaTeX fragments to images")
16962 (org-check-external-command
16963 "dvipng" "needed to convert LaTeX fragments to images")
16964 (setq executables-checked t))
16966 (unless (file-exists-p movefile)
16967 (org-create-formula-image
16968 txt movefile opt forbuffer))
16969 (if overlays
16970 (progn
16971 (mapc (lambda (o)
16972 (if (eq (overlay-get o 'org-overlay-type)
16973 'org-latex-overlay)
16974 (delete-overlay o)))
16975 (overlays-in beg end))
16976 (setq ov (make-overlay beg end))
16977 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16978 (if (featurep 'xemacs)
16979 (progn
16980 (overlay-put ov 'invisible t)
16981 (overlay-put
16982 ov 'end-glyph
16983 (make-glyph (vector 'png :file movefile))))
16984 (overlay-put
16985 ov 'display
16986 (list 'image :type 'png :file movefile :ascent 'center)))
16987 (push ov org-latex-fragment-image-overlays)
16988 (goto-char end))
16989 (delete-region beg end)
16990 (insert (org-add-props link
16991 (list 'org-latex-src
16992 (replace-regexp-in-string
16993 "\"" "" txt)
16994 'org-latex-src-embed-type
16995 (if block-type 'paragraph 'character))))))
16996 ((eq processing-type 'mathml)
16997 ;; Process to MathML
16998 (unless executables-checked
16999 (unless (save-match-data (org-format-latex-mathml-available-p))
17000 (error "LaTeX to MathML converter not configured"))
17001 (setq executables-checked t))
17002 (setq txt (match-string n)
17003 beg (match-beginning n) end (match-end n)
17004 cnt (1+ cnt))
17005 (if msg (message msg cnt))
17006 (goto-char beg)
17007 (delete-region beg end)
17008 (insert (org-format-latex-as-mathml
17009 txt block-type prefix dir)))
17011 (error "Unknown conversion type %s for latex fragments"
17012 processing-type)))))))))
17014 (declare-function format-spec "format-spec" (format specification))
17016 (defun org-create-math-formula (latex-frag &optional mathml-file)
17017 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17018 Use `org-latex-to-mathml-convert-command'. If the conversion is
17019 sucessful, return the portion between \"<math...> </math>\"
17020 elements otherwise return nil. When MATHML-FILE is specified,
17021 write the results in to that file. When invoked as an
17022 interactive command, prompt for LATEX-FRAG, with initial value
17023 set to the current active region and echo the results for user
17024 inspection."
17025 (interactive (list (let ((frag (when (region-active-p)
17026 (buffer-substring-no-properties
17027 (region-beginning) (region-end)))))
17028 (read-string "LaTeX Fragment: " frag nil frag))))
17029 (unless latex-frag (error "Invalid latex-frag"))
17030 (let* ((tmp-in-file (file-relative-name
17031 (make-temp-name (expand-file-name "ltxmathml-in"))))
17032 (ignore (write-region latex-frag nil tmp-in-file))
17033 (tmp-out-file (file-relative-name
17034 (make-temp-name (expand-file-name "ltxmathml-out"))))
17035 (cmd (format-spec
17036 org-latex-to-mathml-convert-command
17037 `((?j . ,(shell-quote-argument
17038 (expand-file-name org-latex-to-mathml-jar-file)))
17039 (?I . ,(shell-quote-argument tmp-in-file))
17040 (?o . ,(shell-quote-argument tmp-out-file)))))
17041 mathml shell-command-output)
17042 (when (org-called-interactively-p 'any)
17043 (unless (org-format-latex-mathml-available-p)
17044 (error "LaTeX to MathML converter not configured")))
17045 (message "Running %s" cmd)
17046 (setq shell-command-output (shell-command-to-string cmd))
17047 (setq mathml
17048 (when (file-readable-p tmp-out-file)
17049 (with-current-buffer (find-file-noselect tmp-out-file t)
17050 (goto-char (point-min))
17051 (when (re-search-forward
17052 (concat
17053 (regexp-quote
17054 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17055 "\\(.\\|\n\\)*"
17056 (regexp-quote "</math>")) nil t)
17057 (prog1 (match-string 0) (kill-buffer))))))
17058 (cond
17059 (mathml
17060 (setq mathml
17061 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17062 (when mathml-file
17063 (write-region mathml nil mathml-file))
17064 (when (org-called-interactively-p 'any)
17065 (message mathml)))
17066 ((message "LaTeX to MathML conversion failed")
17067 (message shell-command-output)))
17068 (delete-file tmp-in-file)
17069 (when (file-exists-p tmp-out-file)
17070 (delete-file tmp-out-file))
17071 mathml))
17073 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17074 prefix &optional dir)
17075 "Use `org-create-math-formula' but check local cache first."
17076 (let* ((absprefix (expand-file-name prefix dir))
17077 (print-length nil) (print-level nil)
17078 (formula-id (concat
17079 "formula-"
17080 (sha1
17081 (prin1-to-string
17082 (list latex-frag
17083 org-latex-to-mathml-convert-command)))))
17084 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17085 (formula-cache-dir (file-name-directory formula-cache)))
17087 (unless (file-directory-p formula-cache-dir)
17088 (make-directory formula-cache-dir t))
17090 (unless (file-exists-p formula-cache)
17091 (org-create-math-formula latex-frag formula-cache))
17093 (if (file-exists-p formula-cache)
17094 ;; Successful conversion. Return the link to MathML file.
17095 (org-add-props
17096 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17097 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17098 'org-latex-src-embed-type (if latex-frag-type
17099 'paragraph 'character)))
17100 ;; Failed conversion. Return the LaTeX fragment verbatim
17101 (add-text-properties
17102 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17103 latex-frag)))
17105 ;; This function borrows from Ganesh Swami's latex2png.el
17106 (defun org-create-formula-image (string tofile options buffer)
17107 "This calls dvipng."
17108 (require 'org-latex)
17109 (let* ((tmpdir (if (featurep 'xemacs)
17110 (temp-directory)
17111 temporary-file-directory))
17112 (texfilebase (make-temp-name
17113 (expand-file-name "orgtex" tmpdir)))
17114 (texfile (concat texfilebase ".tex"))
17115 (dvifile (concat texfilebase ".dvi"))
17116 (pngfile (concat texfilebase ".png"))
17117 (fnh (if (featurep 'xemacs)
17118 (font-height (face-font 'default))
17119 (face-attribute 'default :height nil)))
17120 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17121 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17122 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17123 "Black"))
17124 (bg (or (plist-get options (if buffer :background :html-background))
17125 "Transparent")))
17126 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17127 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17128 (with-temp-file texfile
17129 (insert (org-splice-latex-header
17130 org-format-latex-header
17131 org-export-latex-default-packages-alist
17132 org-export-latex-packages-alist t
17133 org-format-latex-header-extra))
17134 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17135 (require 'org-latex)
17136 (org-export-latex-fix-inputenc))
17137 (let ((dir default-directory))
17138 (condition-case nil
17139 (progn
17140 (cd tmpdir)
17141 (call-process "latex" nil nil nil texfile))
17142 (error nil))
17143 (cd dir))
17144 (if (not (file-exists-p dvifile))
17145 (progn (message "Failed to create dvi file from %s" texfile) nil)
17146 (condition-case nil
17147 (if (featurep 'xemacs)
17148 (call-process "dvipng" nil nil nil
17149 "-fg" fg "-bg" bg
17150 "-T" "tight"
17151 "-o" pngfile
17152 dvifile)
17153 (call-process "dvipng" nil nil nil
17154 "-fg" fg "-bg" bg
17155 "-D" dpi
17156 ;;"-x" scale "-y" scale
17157 "-T" "tight"
17158 "-o" pngfile
17159 dvifile))
17160 (error nil))
17161 (if (not (file-exists-p pngfile))
17162 (if org-format-latex-signal-error
17163 (error "Failed to create png file from %s" texfile)
17164 (message "Failed to create png file from %s" texfile)
17165 nil)
17166 ;; Use the requested file name and clean up
17167 (copy-file pngfile tofile 'replace)
17168 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17169 (delete-file (concat texfilebase e)))
17170 pngfile))))
17172 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17173 "Fill a LaTeX header template TPL.
17174 In the template, the following place holders will be recognized:
17176 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17177 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17178 [PACKAGES] \\usepackage statements for PKG
17179 [NO-PACKAGES] do not include PKG
17180 [EXTRA] the string EXTRA
17181 [NO-EXTRA] do not include EXTRA
17183 For backward compatibility, if both the positive and the negative place
17184 holder is missing, the positive one (without the \"NO-\") will be
17185 assumed to be present at the end of the template.
17186 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17187 EXTRA is a string.
17188 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17189 (let (rpl (end ""))
17190 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17191 (setq rpl (if (or (match-end 1) (not def-pkg))
17192 "" (org-latex-packages-to-string def-pkg snippets-p t))
17193 tpl (replace-match rpl t t tpl))
17194 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17196 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17197 (setq rpl (if (or (match-end 1) (not pkg))
17198 "" (org-latex-packages-to-string pkg snippets-p t))
17199 tpl (replace-match rpl t t tpl))
17200 (if pkg (setq end
17201 (concat end "\n"
17202 (org-latex-packages-to-string pkg snippets-p)))))
17204 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17205 (setq rpl (if (or (match-end 1) (not extra))
17206 "" (concat extra "\n"))
17207 tpl (replace-match rpl t t tpl))
17208 (if (and extra (string-match "\\S-" extra))
17209 (setq end (concat end "\n" extra))))
17211 (if (string-match "\\S-" end)
17212 (concat tpl "\n" end)
17213 tpl)))
17215 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17216 "Turn an alist of packages into a string with the \\usepackage macros."
17217 (setq pkg (mapconcat (lambda(p)
17218 (cond
17219 ((stringp p) p)
17220 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17221 (format "%% Package %s omitted" (cadr p)))
17222 ((equal "" (car p))
17223 (format "\\usepackage{%s}" (cadr p)))
17225 (format "\\usepackage[%s]{%s}"
17226 (car p) (cadr p)))))
17228 "\n"))
17229 (if newline (concat pkg "\n") pkg))
17231 (defun org-dvipng-color (attr)
17232 "Return an rgb color specification for dvipng."
17233 (apply 'format "rgb %s %s %s"
17234 (mapcar 'org-normalize-color
17235 (if (featurep 'xemacs)
17236 (color-rgb-components
17237 (face-property 'default
17238 (cond ((eq attr :foreground) 'foreground)
17239 ((eq attr :background) 'background))))
17240 (color-values (face-attribute 'default attr nil))))))
17242 (defun org-normalize-color (value)
17243 "Return string to be used as color value for an RGB component."
17244 (format "%g" (/ value 65535.0)))
17246 ;; Image display
17249 (defvar org-inline-image-overlays nil)
17250 (make-variable-buffer-local 'org-inline-image-overlays)
17252 (defun org-toggle-inline-images (&optional include-linked)
17253 "Toggle the display of inline images.
17254 INCLUDE-LINKED is passed to `org-display-inline-images'."
17255 (interactive "P")
17256 (if org-inline-image-overlays
17257 (progn
17258 (org-remove-inline-images)
17259 (message "Inline image display turned off"))
17260 (org-display-inline-images include-linked)
17261 (if org-inline-image-overlays
17262 (message "%d images displayed inline"
17263 (length org-inline-image-overlays))
17264 (message "No images to display inline"))))
17266 (defun org-display-inline-images (&optional include-linked refresh beg end)
17267 "Display inline images.
17268 Normally only links without a description part are inlined, because this
17269 is how it will work for export. When INCLUDE-LINKED is set, also links
17270 with a description part will be inlined. This can be nice for a quick
17271 look at those images, but it does not reflect what exported files will look
17272 like.
17273 When REFRESH is set, refresh existing images between BEG and END.
17274 This will create new image displays only if necessary.
17275 BEG and END default to the buffer boundaries."
17276 (interactive "P")
17277 (unless refresh
17278 (org-remove-inline-images)
17279 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17280 (save-excursion
17281 (save-restriction
17282 (widen)
17283 (setq beg (or beg (point-min)) end (or end (point-max)))
17284 (goto-char (point-min))
17285 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17286 (substring (org-image-file-name-regexp) 0 -2)
17287 "\\)\\]" (if include-linked "" "\\]")))
17288 old file ov img)
17289 (while (re-search-forward re end t)
17290 (setq old (get-char-property-and-overlay (match-beginning 1)
17291 'org-image-overlay))
17292 (setq file (expand-file-name
17293 (concat (or (match-string 3) "") (match-string 4))))
17294 (when (file-exists-p file)
17295 (if (and (car-safe old) refresh)
17296 (image-refresh (overlay-get (cdr old) 'display))
17297 (setq img (save-match-data (create-image file)))
17298 (when img
17299 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17300 (overlay-put ov 'display img)
17301 (overlay-put ov 'face 'default)
17302 (overlay-put ov 'org-image-overlay t)
17303 (overlay-put ov 'modification-hooks
17304 (list 'org-display-inline-modification-hook))
17305 (push ov org-inline-image-overlays)))))))))
17307 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17308 "Remove inline-display overlay if a corresponding region is modified."
17309 (let ((inhibit-modification-hooks t))
17310 (when (and ov after)
17311 (delete ov org-inline-image-overlays)
17312 (delete-overlay ov))))
17314 (defun org-remove-inline-images ()
17315 "Remove inline display of images."
17316 (interactive)
17317 (mapc 'delete-overlay org-inline-image-overlays)
17318 (setq org-inline-image-overlays nil))
17320 ;;;; Key bindings
17322 ;; Outline functions from `outline-mode-prefix-map'
17323 ;; that can be remapped in Org:
17324 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17325 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17326 (define-key org-mode-map [remap outline-forward-same-level]
17327 'org-forward-same-level)
17328 (define-key org-mode-map [remap outline-backward-same-level]
17329 'org-backward-same-level)
17330 (define-key org-mode-map [remap show-branches]
17331 'org-kill-note-or-show-branches)
17332 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17333 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17334 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17336 ;; Outline functions from `outline-mode-prefix-map'
17337 ;; that can not be remapped in Org:
17338 ;; - the column "key binding" shows whether the Outline function is still
17339 ;; available in Org mode on the same key that it has been bound to in
17340 ;; Outline mode:
17341 ;; - "overridden": key used for a different functionality in Org mode
17342 ;; - else: key still bound to the same Outline function in Org mode
17343 ;; | Outline function | key binding | Org replacement |
17344 ;; |------------------------------------+-------------+-----------------------|
17345 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17346 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17347 ;; | `show-children' | `C-c C-i' | visibility cycling |
17348 ;; | `hide-subtree' | overridden | visibility cycling |
17349 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17350 ;; | `hide-body' | overridden | no replacement |
17351 ;; | `show-all' | overridden | no replacement |
17352 ;; | `hide-entry' | overridden | visibility cycling |
17353 ;; | `show-entry' | overridden | no replacement |
17354 ;; | `hide-leaves' | overridden | no replacement |
17355 ;; | `hide-sublevels' | overridden | no replacement |
17356 ;; | `hide-other' | overridden | no replacement |
17357 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17358 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17360 ;; Make `C-c C-x' a prefix key
17361 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17363 ;; TAB key with modifiers
17364 (org-defkey org-mode-map "\C-i" 'org-cycle)
17365 (org-defkey org-mode-map [(tab)] 'org-cycle)
17366 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17367 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17368 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17369 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17370 ;; The following line is necessary under Suse GNU/Linux
17371 (unless (featurep 'xemacs)
17372 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17373 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17374 (define-key org-mode-map [backtab] 'org-shifttab)
17376 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17377 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17378 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17380 ;; Cursor keys with modifiers
17381 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17382 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17383 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17384 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17386 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17387 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17388 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17389 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17391 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17392 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17393 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17394 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17396 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17397 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17398 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17399 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17401 ;; Babel keys
17402 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17403 (mapc (lambda (pair)
17404 (define-key org-babel-map (car pair) (cdr pair)))
17405 org-babel-key-bindings)
17407 ;;; Extra keys for tty access.
17408 ;; We only set them when really needed because otherwise the
17409 ;; menus don't show the simple keys
17411 (when (or org-use-extra-keys
17412 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17413 (not window-system))
17414 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17415 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17416 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17417 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17418 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17419 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17420 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17421 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17422 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17423 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17424 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17425 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17426 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17427 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17428 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17429 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17430 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17431 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17432 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17433 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17434 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17435 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17436 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17437 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17438 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17439 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17440 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17441 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17443 ;; All the other keys
17445 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17446 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17447 (if (boundp 'narrow-map)
17448 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17449 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17450 (if (boundp 'narrow-map)
17451 (org-defkey narrow-map "b" 'org-narrow-to-block)
17452 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17453 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17454 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17455 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17456 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17457 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17458 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17459 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17460 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17461 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17462 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17463 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17464 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17465 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17466 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17467 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17468 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17469 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17470 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17471 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17472 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17473 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17474 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17475 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17476 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17477 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17478 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17479 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17480 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17481 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17482 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17483 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17484 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17485 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17486 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17487 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17488 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17489 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17490 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17491 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17492 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17493 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17494 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17495 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17496 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17497 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17498 (org-defkey org-mode-map "\C-c^" 'org-sort)
17499 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17500 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17501 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17502 (org-defkey org-mode-map "\C-m" 'org-return)
17503 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17504 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17505 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17506 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17507 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17508 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17509 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17510 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17511 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17512 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17513 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17514 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17515 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17516 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17517 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17518 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17519 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17520 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17521 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17522 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17523 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17524 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17525 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17527 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17528 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17529 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17530 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17532 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17533 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17534 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17535 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17536 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17537 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17538 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17539 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17540 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17541 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17542 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17543 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17544 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17545 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17546 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17547 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17548 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17549 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17551 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17552 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17553 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17554 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17555 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17557 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17559 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17561 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17562 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17564 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17567 (when (featurep 'xemacs)
17568 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17571 (defconst org-speed-commands-default
17573 ("Outline Navigation")
17574 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17575 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17576 ("f" . (org-speed-move-safe 'org-forward-same-level))
17577 ("b" . (org-speed-move-safe 'org-backward-same-level))
17578 ("u" . (org-speed-move-safe 'outline-up-heading))
17579 ("j" . org-goto)
17580 ("g" . (org-refile t))
17581 ("Outline Visibility")
17582 ("c" . org-cycle)
17583 ("C" . org-shifttab)
17584 (" " . org-display-outline-path)
17585 ("Outline Structure Editing")
17586 ("U" . org-shiftmetaup)
17587 ("D" . org-shiftmetadown)
17588 ("r" . org-metaright)
17589 ("l" . org-metaleft)
17590 ("R" . org-shiftmetaright)
17591 ("L" . org-shiftmetaleft)
17592 ("i" . (progn (forward-char 1) (call-interactively
17593 'org-insert-heading-respect-content)))
17594 ("^" . org-sort)
17595 ("w" . org-refile)
17596 ("a" . org-archive-subtree-default-with-confirmation)
17597 ("." . org-mark-subtree)
17598 ("Clock Commands")
17599 ("I" . org-clock-in)
17600 ("O" . org-clock-out)
17601 ("Meta Data Editing")
17602 ("t" . org-todo)
17603 ("0" . (org-priority ?\ ))
17604 ("1" . (org-priority ?A))
17605 ("2" . (org-priority ?B))
17606 ("3" . (org-priority ?C))
17607 (";" . org-set-tags-command)
17608 ("e" . org-set-effort)
17609 ("Agenda Views etc")
17610 ("v" . org-agenda)
17611 ("/" . org-sparse-tree)
17612 ("Misc")
17613 ("o" . org-open-at-point)
17614 ("?" . org-speed-command-help)
17615 ("<" . (org-agenda-set-restriction-lock 'subtree))
17616 (">" . (org-agenda-remove-restriction-lock))
17618 "The default speed commands.")
17620 (defun org-print-speed-command (e)
17621 (if (> (length (car e)) 1)
17622 (progn
17623 (princ "\n")
17624 (princ (car e))
17625 (princ "\n")
17626 (princ (make-string (length (car e)) ?-))
17627 (princ "\n"))
17628 (princ (car e))
17629 (princ " ")
17630 (if (symbolp (cdr e))
17631 (princ (symbol-name (cdr e)))
17632 (prin1 (cdr e)))
17633 (princ "\n")))
17635 (defun org-speed-command-help ()
17636 "Show the available speed commands."
17637 (interactive)
17638 (if (not org-use-speed-commands)
17639 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17640 (with-output-to-temp-buffer "*Help*"
17641 (princ "User-defined Speed commands\n===========================\n")
17642 (mapc 'org-print-speed-command org-speed-commands-user)
17643 (princ "\n")
17644 (princ "Built-in Speed commands\n=======================\n")
17645 (mapc 'org-print-speed-command org-speed-commands-default))
17646 (with-current-buffer "*Help*"
17647 (setq truncate-lines t))))
17649 (defun org-speed-move-safe (cmd)
17650 "Execute CMD, but make sure that the cursor always ends up in a headline.
17651 If not, return to the original position and throw an error."
17652 (interactive)
17653 (let ((pos (point)))
17654 (call-interactively cmd)
17655 (unless (and (bolp) (org-at-heading-p))
17656 (goto-char pos)
17657 (error "Boundary reached while executing %s" cmd))))
17659 (defvar org-self-insert-command-undo-counter 0)
17661 (defvar org-table-auto-blank-field) ; defined in org-table.el
17662 (defvar org-speed-command nil)
17664 (defun org-speed-command-default-hook (keys)
17665 "Hook for activating single-letter speed commands.
17666 `org-speed-commands-default' specifies a minimal command set.
17667 Use `org-speed-commands-user' for further customization."
17668 (when (or (and (bolp) (looking-at org-outline-regexp))
17669 (and (functionp org-use-speed-commands)
17670 (funcall org-use-speed-commands)))
17671 (cdr (assoc keys (append org-speed-commands-user
17672 org-speed-commands-default)))))
17674 (defun org-babel-speed-command-hook (keys)
17675 "Hook for activating single-letter code block commands."
17676 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17677 (cdr (assoc keys org-babel-key-bindings))))
17679 (defcustom org-speed-command-hook
17680 '(org-speed-command-default-hook org-babel-speed-command-hook)
17681 "Hook for activating speed commands at strategic locations.
17682 Hook functions are called in sequence until a valid handler is
17683 found.
17685 Each hook takes a single argument, a user-pressed command key
17686 which is also a `self-insert-command' from the global map.
17688 Within the hook, examine the cursor position and the command key
17689 and return nil or a valid handler as appropriate. Handler could
17690 be one of an interactive command, a function, or a form.
17692 Set `org-use-speed-commands' to non-nil value to enable this
17693 hook. The default setting is `org-speed-command-default-hook'."
17694 :group 'org-structure
17695 :version "24.1"
17696 :type 'hook)
17698 (defun org-self-insert-command (N)
17699 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17700 If the cursor is in a table looking at whitespace, the whitespace is
17701 overwritten, and the table is not marked as requiring realignment."
17702 (interactive "p")
17703 (org-check-before-invisible-edit 'insert)
17704 (cond
17705 ((and org-use-speed-commands
17706 (setq org-speed-command
17707 (run-hook-with-args-until-success
17708 'org-speed-command-hook (this-command-keys))))
17709 (cond
17710 ((commandp org-speed-command)
17711 (setq this-command org-speed-command)
17712 (call-interactively org-speed-command))
17713 ((functionp org-speed-command)
17714 (funcall org-speed-command))
17715 ((and org-speed-command (listp org-speed-command))
17716 (eval org-speed-command))
17717 (t (let (org-use-speed-commands)
17718 (call-interactively 'org-self-insert-command)))))
17719 ((and
17720 (org-table-p)
17721 (progn
17722 ;; check if we blank the field, and if that triggers align
17723 (and (featurep 'org-table) org-table-auto-blank-field
17724 (member last-command
17725 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17726 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17727 ;; got extra space, this field does not determine column width
17728 (let (org-table-may-need-update) (org-table-blank-field))
17729 ;; no extra space, this field may determine column width
17730 (org-table-blank-field)))
17732 (eq N 1)
17733 (looking-at "[^|\n]* |"))
17734 (let (org-table-may-need-update)
17735 (goto-char (1- (match-end 0)))
17736 (delete-char -1)
17737 (goto-char (match-beginning 0))
17738 (self-insert-command N)))
17740 (setq org-table-may-need-update t)
17741 (self-insert-command N)
17742 (org-fix-tags-on-the-fly)
17743 (if org-self-insert-cluster-for-undo
17744 (if (not (eq last-command 'org-self-insert-command))
17745 (setq org-self-insert-command-undo-counter 1)
17746 (if (>= org-self-insert-command-undo-counter 20)
17747 (setq org-self-insert-command-undo-counter 1)
17748 (and (> org-self-insert-command-undo-counter 0)
17749 buffer-undo-list (listp buffer-undo-list)
17750 (not (cadr buffer-undo-list)) ; remove nil entry
17751 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17752 (setq org-self-insert-command-undo-counter
17753 (1+ org-self-insert-command-undo-counter))))))))
17755 (defun org-check-before-invisible-edit (kind)
17756 "Check is editing if kind KIND would be dangerous with invisible text around.
17757 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17758 ;; First, try to get out of here as quickly as possible, to reduce overhead
17759 (if (and org-catch-invisible-edits
17760 (or (not (boundp 'visible-mode)) (not visible-mode))
17761 (or (get-char-property (point) 'invisible)
17762 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17763 ;; OK, we need to take a closer look
17764 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17765 (invisible-before-point (if (bobp) nil (get-char-property
17766 (1- (point)) 'invisible)))
17767 (border-and-ok-direction
17769 ;; Check if we are acting predictably before invisible text
17770 (and invisible-at-point (not invisible-before-point)
17771 (memq kind '(insert delete-backward)))
17772 ;; Check if we are acting predictably after invisible text
17773 ;; This works not well, and I have turned it off. It seems
17774 ;; better to always show and stop after invisible text.
17775 ;; (and (not invisible-at-point) invisible-before-point
17776 ;; (memq kind '(insert delete)))
17779 (when (or (memq invisible-at-point '(outline org-hide-block))
17780 (memq invisible-before-point '(outline org-hide-block)))
17781 (if (eq org-catch-invisible-edits 'error)
17782 (error "Editing in invisible areas is prohibited - make visible first"))
17783 ;; Make the area visible
17784 (save-excursion
17785 (if invisible-before-point
17786 (goto-char (previous-single-char-property-change
17787 (point) 'invisible)))
17788 (org-cycle))
17789 (cond
17790 ((eq org-catch-invisible-edits 'show)
17791 ;; That's it, we do the edit after showing
17792 (message
17793 "Unfolding invisible region around point before editing")
17794 (sit-for 1))
17795 ((and (eq org-catch-invisible-edits 'smart)
17796 border-and-ok-direction)
17797 (message "Unfolding invisible region around point before editing"))
17799 ;; Don't do the edit, make the user repeat it in full visibility
17800 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17802 (defun org-fix-tags-on-the-fly ()
17803 (when (and (equal (char-after (point-at-bol)) ?*)
17804 (org-at-heading-p))
17805 (org-align-tags-here org-tags-column)))
17807 (defun org-delete-backward-char (N)
17808 "Like `delete-backward-char', insert whitespace at field end in tables.
17809 When deleting backwards, in tables this function will insert whitespace in
17810 front of the next \"|\" separator, to keep the table aligned. The table will
17811 still be marked for re-alignment if the field did fill the entire column,
17812 because, in this case the deletion might narrow the column."
17813 (interactive "p")
17814 (org-check-before-invisible-edit 'delete-backward)
17815 (if (and (org-table-p)
17816 (eq N 1)
17817 (string-match "|" (buffer-substring (point-at-bol) (point)))
17818 (looking-at ".*?|"))
17819 (let ((pos (point))
17820 (noalign (looking-at "[^|\n\r]* |"))
17821 (c org-table-may-need-update))
17822 (backward-delete-char N)
17823 (if (not overwrite-mode)
17824 (progn
17825 (skip-chars-forward "^|")
17826 (insert " ")
17827 (goto-char (1- pos))))
17828 ;; noalign: if there were two spaces at the end, this field
17829 ;; does not determine the width of the column.
17830 (if noalign (setq org-table-may-need-update c)))
17831 (backward-delete-char N)
17832 (org-fix-tags-on-the-fly)))
17834 (defun org-delete-char (N)
17835 "Like `delete-char', but insert whitespace at field end in tables.
17836 When deleting characters, in tables this function will insert whitespace in
17837 front of the next \"|\" separator, to keep the table aligned. The table will
17838 still be marked for re-alignment if the field did fill the entire column,
17839 because, in this case the deletion might narrow the column."
17840 (interactive "p")
17841 (org-check-before-invisible-edit 'delete)
17842 (if (and (org-table-p)
17843 (not (bolp))
17844 (not (= (char-after) ?|))
17845 (eq N 1))
17846 (if (looking-at ".*?|")
17847 (let ((pos (point))
17848 (noalign (looking-at "[^|\n\r]* |"))
17849 (c org-table-may-need-update))
17850 (replace-match (concat
17851 (substring (match-string 0) 1 -1)
17852 " |"))
17853 (goto-char pos)
17854 ;; noalign: if there were two spaces at the end, this field
17855 ;; does not determine the width of the column.
17856 (if noalign (setq org-table-may-need-update c)))
17857 (delete-char N))
17858 (delete-char N)
17859 (org-fix-tags-on-the-fly)))
17861 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17862 (put 'org-self-insert-command 'delete-selection t)
17863 (put 'orgtbl-self-insert-command 'delete-selection t)
17864 (put 'org-delete-char 'delete-selection 'supersede)
17865 (put 'org-delete-backward-char 'delete-selection 'supersede)
17866 (put 'org-yank 'delete-selection 'yank)
17868 ;; Make `flyspell-mode' delay after some commands
17869 (put 'org-self-insert-command 'flyspell-delayed t)
17870 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17871 (put 'org-delete-char 'flyspell-delayed t)
17872 (put 'org-delete-backward-char 'flyspell-delayed t)
17874 ;; Make pabbrev-mode expand after org-mode commands
17875 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17876 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17878 ;; How to do this: Measure non-white length of current string
17879 ;; If equal to column width, we should realign.
17881 (defun org-remap (map &rest commands)
17882 "In MAP, remap the functions given in COMMANDS.
17883 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17884 (let (new old)
17885 (while commands
17886 (setq old (pop commands) new (pop commands))
17887 (if (fboundp 'command-remapping)
17888 (org-defkey map (vector 'remap old) new)
17889 (substitute-key-definition old new map global-map)))))
17891 (when (eq org-enable-table-editor 'optimized)
17892 ;; If the user wants maximum table support, we need to hijack
17893 ;; some standard editing functions
17894 (org-remap org-mode-map
17895 'self-insert-command 'org-self-insert-command
17896 'delete-char 'org-delete-char
17897 'delete-backward-char 'org-delete-backward-char)
17898 (org-defkey org-mode-map "|" 'org-force-self-insert))
17900 (defvar org-ctrl-c-ctrl-c-hook nil
17901 "Hook for functions attaching themselves to `C-c C-c'.
17903 This can be used to add additional functionality to the C-c C-c
17904 key which executes context-dependent commands. This hook is run
17905 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17906 run after the last test.
17908 Each function will be called with no arguments. The function
17909 must check if the context is appropriate for it to act. If yes,
17910 it should do its thing and then return a non-nil value. If the
17911 context is wrong, just do nothing and return nil.")
17913 (defvar org-ctrl-c-ctrl-c-final-hook nil
17914 "Hook for functions attaching themselves to `C-c C-c'.
17916 This can be used to add additional functionality to the C-c C-c
17917 key which executes context-dependent commands. This hook is run
17918 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17919 before the first test.
17921 Each function will be called with no arguments. The function
17922 must check if the context is appropriate for it to act. If yes,
17923 it should do its thing and then return a non-nil value. If the
17924 context is wrong, just do nothing and return nil.")
17926 (defvar org-tab-first-hook nil
17927 "Hook for functions to attach themselves to TAB.
17928 See `org-ctrl-c-ctrl-c-hook' for more information.
17929 This hook runs as the first action when TAB is pressed, even before
17930 `org-cycle' messes around with the `outline-regexp' to cater for
17931 inline tasks and plain list item folding.
17932 If any function in this hook returns t, any other actions that
17933 would have been caused by TAB (such as table field motion or visibility
17934 cycling) will not occur.")
17936 (defvar org-tab-after-check-for-table-hook nil
17937 "Hook for functions to attach themselves to TAB.
17938 See `org-ctrl-c-ctrl-c-hook' for more information.
17939 This hook runs after it has been established that the cursor is not in a
17940 table, but before checking if the cursor is in a headline or if global cycling
17941 should be done.
17942 If any function in this hook returns t, not other actions like visibility
17943 cycling will be done.")
17945 (defvar org-tab-after-check-for-cycling-hook nil
17946 "Hook for functions to attach themselves to TAB.
17947 See `org-ctrl-c-ctrl-c-hook' for more information.
17948 This hook runs after it has been established that not table field motion and
17949 not visibility should be done because of current context. This is probably
17950 the place where a package like yasnippets can hook in.")
17952 (defvar org-tab-before-tab-emulation-hook nil
17953 "Hook for functions to attach themselves to TAB.
17954 See `org-ctrl-c-ctrl-c-hook' for more information.
17955 This hook runs after every other options for TAB have been exhausted, but
17956 before indentation and \t insertion takes place.")
17958 (defvar org-metaleft-hook nil
17959 "Hook for functions attaching themselves to `M-left'.
17960 See `org-ctrl-c-ctrl-c-hook' for more information.")
17961 (defvar org-metaright-hook nil
17962 "Hook for functions attaching themselves to `M-right'.
17963 See `org-ctrl-c-ctrl-c-hook' for more information.")
17964 (defvar org-metaup-hook nil
17965 "Hook for functions attaching themselves to `M-up'.
17966 See `org-ctrl-c-ctrl-c-hook' for more information.")
17967 (defvar org-metadown-hook nil
17968 "Hook for functions attaching themselves to `M-down'.
17969 See `org-ctrl-c-ctrl-c-hook' for more information.")
17970 (defvar org-shiftmetaleft-hook nil
17971 "Hook for functions attaching themselves to `M-S-left'.
17972 See `org-ctrl-c-ctrl-c-hook' for more information.")
17973 (defvar org-shiftmetaright-hook nil
17974 "Hook for functions attaching themselves to `M-S-right'.
17975 See `org-ctrl-c-ctrl-c-hook' for more information.")
17976 (defvar org-shiftmetaup-hook nil
17977 "Hook for functions attaching themselves to `M-S-up'.
17978 See `org-ctrl-c-ctrl-c-hook' for more information.")
17979 (defvar org-shiftmetadown-hook nil
17980 "Hook for functions attaching themselves to `M-S-down'.
17981 See `org-ctrl-c-ctrl-c-hook' for more information.")
17982 (defvar org-metareturn-hook nil
17983 "Hook for functions attaching themselves to `M-RET'.
17984 See `org-ctrl-c-ctrl-c-hook' for more information.")
17985 (defvar org-shiftup-hook nil
17986 "Hook for functions attaching themselves to `S-up'.
17987 See `org-ctrl-c-ctrl-c-hook' for more information.")
17988 (defvar org-shiftup-final-hook nil
17989 "Hook for functions attaching themselves to `S-up'.
17990 This one runs after all other options except shift-select have been excluded.
17991 See `org-ctrl-c-ctrl-c-hook' for more information.")
17992 (defvar org-shiftdown-hook nil
17993 "Hook for functions attaching themselves to `S-down'.
17994 See `org-ctrl-c-ctrl-c-hook' for more information.")
17995 (defvar org-shiftdown-final-hook nil
17996 "Hook for functions attaching themselves to `S-down'.
17997 This one runs after all other options except shift-select have been excluded.
17998 See `org-ctrl-c-ctrl-c-hook' for more information.")
17999 (defvar org-shiftleft-hook nil
18000 "Hook for functions attaching themselves to `S-left'.
18001 See `org-ctrl-c-ctrl-c-hook' for more information.")
18002 (defvar org-shiftleft-final-hook nil
18003 "Hook for functions attaching themselves to `S-left'.
18004 This one runs after all other options except shift-select have been excluded.
18005 See `org-ctrl-c-ctrl-c-hook' for more information.")
18006 (defvar org-shiftright-hook nil
18007 "Hook for functions attaching themselves to `S-right'.
18008 See `org-ctrl-c-ctrl-c-hook' for more information.")
18009 (defvar org-shiftright-final-hook nil
18010 "Hook for functions attaching themselves to `S-right'.
18011 This one runs after all other options except shift-select have been excluded.
18012 See `org-ctrl-c-ctrl-c-hook' for more information.")
18014 (defun org-modifier-cursor-error ()
18015 "Throw an error, a modified cursor command was applied in wrong context."
18016 (error "This command is active in special context like tables, headlines or items"))
18018 (defun org-shiftselect-error ()
18019 "Throw an error because Shift-Cursor command was applied in wrong context."
18020 (if (and (boundp 'shift-select-mode) shift-select-mode)
18021 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18022 (error "This command works only in special context like headlines or timestamps")))
18024 (defun org-call-for-shift-select (cmd)
18025 (let ((this-command-keys-shift-translated t))
18026 (call-interactively cmd)))
18028 (defun org-shifttab (&optional arg)
18029 "Global visibility cycling or move to previous table field.
18030 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18031 on context.
18032 See the individual commands for more information."
18033 (interactive "P")
18034 (cond
18035 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18036 ((integerp arg)
18037 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18038 (message "Content view to level: %d" arg)
18039 (org-content (prefix-numeric-value arg2))
18040 (setq org-cycle-global-status 'overview)))
18041 (t (call-interactively 'org-global-cycle))))
18043 (defun org-shiftmetaleft ()
18044 "Promote subtree or delete table column.
18045 Calls `org-promote-subtree', `org-outdent-item',
18046 or `org-table-delete-column', depending on context.
18047 See the individual commands for more information."
18048 (interactive)
18049 (cond
18050 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18051 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18052 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18053 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
18054 (t (org-modifier-cursor-error))))
18056 (defun org-shiftmetaright ()
18057 "Demote subtree or insert table column.
18058 Calls `org-demote-subtree', `org-indent-item',
18059 or `org-table-insert-column', depending on context.
18060 See the individual commands for more information."
18061 (interactive)
18062 (cond
18063 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18064 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18065 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18066 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
18067 (t (org-modifier-cursor-error))))
18069 (defun org-shiftmetaup (&optional arg)
18070 "Move subtree up or kill table row.
18071 Calls `org-move-subtree-up' or `org-table-kill-row' or
18072 `org-move-item-up' depending on context. See the individual commands
18073 for more information."
18074 (interactive "P")
18075 (cond
18076 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18077 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18078 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18079 ((org-at-item-p) (call-interactively 'org-move-item-up))
18080 (t (org-modifier-cursor-error))))
18082 (defun org-shiftmetadown (&optional arg)
18083 "Move subtree down or insert table row.
18084 Calls `org-move-subtree-down' or `org-table-insert-row' or
18085 `org-move-item-down', depending on context. See the individual
18086 commands for more information."
18087 (interactive "P")
18088 (cond
18089 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18090 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18091 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18092 ((org-at-item-p) (call-interactively 'org-move-item-down))
18093 (t (org-modifier-cursor-error))))
18095 (defsubst org-hidden-tree-error ()
18096 (error
18097 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18099 (defun org-metaleft (&optional arg)
18100 "Promote heading or move table column to left.
18101 Calls `org-do-promote' or `org-table-move-column', depending on context.
18102 With no specific context, calls the Emacs default `backward-word'.
18103 See the individual commands for more information."
18104 (interactive "P")
18105 (cond
18106 ((run-hook-with-args-until-success 'org-metaleft-hook))
18107 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18108 ((org-with-limited-levels
18109 (or (org-at-heading-p)
18110 (and (org-region-active-p)
18111 (save-excursion
18112 (goto-char (region-beginning))
18113 (org-at-heading-p)))))
18114 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18115 (call-interactively 'org-do-promote))
18116 ;; At an inline task.
18117 ((org-at-heading-p)
18118 (call-interactively 'org-inlinetask-promote))
18119 ((or (org-at-item-p)
18120 (and (org-region-active-p)
18121 (save-excursion
18122 (goto-char (region-beginning))
18123 (org-at-item-p))))
18124 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18125 (call-interactively 'org-outdent-item))
18126 (t (call-interactively 'backward-word))))
18128 (defun org-metaright (&optional arg)
18129 "Demote a subtree, a list item or move table column to right.
18130 In front of a drawer or a block keyword, indent it correctly.
18131 With no specific context, calls the Emacs default `forward-word'.
18132 See the individual commands for more information."
18133 (interactive "P")
18134 (cond
18135 ((run-hook-with-args-until-success 'org-metaright-hook))
18136 ((org-at-table-p) (call-interactively 'org-table-move-column))
18137 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18138 ((org-at-block-p) (call-interactively 'org-indent-block))
18139 ((org-with-limited-levels
18140 (or (org-at-heading-p)
18141 (and (org-region-active-p)
18142 (save-excursion
18143 (goto-char (region-beginning))
18144 (org-at-heading-p)))))
18145 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18146 (call-interactively 'org-do-demote))
18147 ;; At an inline task.
18148 ((org-at-heading-p)
18149 (call-interactively 'org-inlinetask-demote))
18150 ((or (org-at-item-p)
18151 (and (org-region-active-p)
18152 (save-excursion
18153 (goto-char (region-beginning))
18154 (org-at-item-p))))
18155 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18156 (call-interactively 'org-indent-item))
18157 (t (call-interactively 'forward-word))))
18159 (defun org-check-for-hidden (what)
18160 "Check if there are hidden headlines/items in the current visual line.
18161 WHAT can be either `headlines' or `items'. If the current line is
18162 an outline or item heading and it has a folded subtree below it,
18163 this function returns t, nil otherwise."
18164 (let ((re (cond
18165 ((eq what 'headlines) org-outline-regexp-bol)
18166 ((eq what 'items) (org-item-beginning-re))
18167 (t (error "This should not happen"))))
18168 beg end)
18169 (save-excursion
18170 (catch 'exit
18171 (unless (org-region-active-p)
18172 (setq beg (point-at-bol))
18173 (beginning-of-line 2)
18174 (while (and (not (eobp)) ;; this is like `next-line'
18175 (get-char-property (1- (point)) 'invisible))
18176 (beginning-of-line 2))
18177 (setq end (point))
18178 (goto-char beg)
18179 (goto-char (point-at-eol))
18180 (setq end (max end (point)))
18181 (while (re-search-forward re end t)
18182 (if (get-char-property (match-beginning 0) 'invisible)
18183 (throw 'exit t))))
18184 nil))))
18186 (defun org-metaup (&optional arg)
18187 "Move subtree up or move table row up.
18188 Calls `org-move-subtree-up' or `org-table-move-row' or
18189 `org-move-item-up', depending on context. See the individual commands
18190 for more information."
18191 (interactive "P")
18192 (cond
18193 ((run-hook-with-args-until-success 'org-metaup-hook))
18194 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18195 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18196 ((org-at-item-p) (call-interactively 'org-move-item-up))
18197 (t (transpose-lines 1) (beginning-of-line -1))))
18199 (defun org-metadown (&optional arg)
18200 "Move subtree down or move table row down.
18201 Calls `org-move-subtree-down' or `org-table-move-row' or
18202 `org-move-item-down', depending on context. See the individual
18203 commands for more information."
18204 (interactive "P")
18205 (cond
18206 ((run-hook-with-args-until-success 'org-metadown-hook))
18207 ((org-at-table-p) (call-interactively 'org-table-move-row))
18208 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18209 ((org-at-item-p) (call-interactively 'org-move-item-down))
18210 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18212 (defun org-shiftup (&optional arg)
18213 "Increase item in timestamp or increase priority of current headline.
18214 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18215 depending on context. See the individual commands for more information."
18216 (interactive "P")
18217 (cond
18218 ((run-hook-with-args-until-success 'org-shiftup-hook))
18219 ((and org-support-shift-select (org-region-active-p))
18220 (org-call-for-shift-select 'previous-line))
18221 ((org-at-timestamp-p t)
18222 (call-interactively (if org-edit-timestamp-down-means-later
18223 'org-timestamp-down 'org-timestamp-up)))
18224 ((and (not (eq org-support-shift-select 'always))
18225 org-enable-priority-commands
18226 (org-at-heading-p))
18227 (call-interactively 'org-priority-up))
18228 ((and (not org-support-shift-select) (org-at-item-p))
18229 (call-interactively 'org-previous-item))
18230 ((org-clocktable-try-shift 'up arg))
18231 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18232 (org-support-shift-select
18233 (org-call-for-shift-select 'previous-line))
18234 (t (org-shiftselect-error))))
18236 (defun org-shiftdown (&optional arg)
18237 "Decrease item in timestamp or decrease priority of current headline.
18238 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18239 depending on context. See the individual commands for more information."
18240 (interactive "P")
18241 (cond
18242 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18243 ((and org-support-shift-select (org-region-active-p))
18244 (org-call-for-shift-select 'next-line))
18245 ((org-at-timestamp-p t)
18246 (call-interactively (if org-edit-timestamp-down-means-later
18247 'org-timestamp-up 'org-timestamp-down)))
18248 ((and (not (eq org-support-shift-select 'always))
18249 org-enable-priority-commands
18250 (org-at-heading-p))
18251 (call-interactively 'org-priority-down))
18252 ((and (not org-support-shift-select) (org-at-item-p))
18253 (call-interactively 'org-next-item))
18254 ((org-clocktable-try-shift 'down arg))
18255 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18256 (org-support-shift-select
18257 (org-call-for-shift-select 'next-line))
18258 (t (org-shiftselect-error))))
18260 (defun org-shiftright (&optional arg)
18261 "Cycle the thing at point or in the current line, depending on context.
18262 Depending on context, this does one of the following:
18264 - switch a timestamp at point one day into the future
18265 - on a headline, switch to the next TODO keyword.
18266 - on an item, switch entire list to the next bullet type
18267 - on a property line, switch to the next allowed value
18268 - on a clocktable definition line, move time block into the future"
18269 (interactive "P")
18270 (cond
18271 ((run-hook-with-args-until-success 'org-shiftright-hook))
18272 ((and org-support-shift-select (org-region-active-p))
18273 (org-call-for-shift-select 'forward-char))
18274 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18275 ((and (not (eq org-support-shift-select 'always))
18276 (org-at-heading-p))
18277 (let ((org-inhibit-logging
18278 (not org-treat-S-cursor-todo-selection-as-state-change))
18279 (org-inhibit-blocking
18280 (not org-treat-S-cursor-todo-selection-as-state-change)))
18281 (org-call-with-arg 'org-todo 'right)))
18282 ((or (and org-support-shift-select
18283 (not (eq org-support-shift-select 'always))
18284 (org-at-item-bullet-p))
18285 (and (not org-support-shift-select) (org-at-item-p)))
18286 (org-call-with-arg 'org-cycle-list-bullet nil))
18287 ((and (not (eq org-support-shift-select 'always))
18288 (org-at-property-p))
18289 (call-interactively 'org-property-next-allowed-value))
18290 ((org-clocktable-try-shift 'right arg))
18291 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18292 (org-support-shift-select
18293 (org-call-for-shift-select 'forward-char))
18294 (t (org-shiftselect-error))))
18296 (defun org-shiftleft (&optional arg)
18297 "Cycle the thing at point or in the current line, depending on context.
18298 Depending on context, this does one of the following:
18300 - switch a timestamp at point one day into the past
18301 - on a headline, switch to the previous TODO keyword.
18302 - on an item, switch entire list to the previous bullet type
18303 - on a property line, switch to the previous allowed value
18304 - on a clocktable definition line, move time block into the past"
18305 (interactive "P")
18306 (cond
18307 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18308 ((and org-support-shift-select (org-region-active-p))
18309 (org-call-for-shift-select 'backward-char))
18310 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18311 ((and (not (eq org-support-shift-select 'always))
18312 (org-at-heading-p))
18313 (let ((org-inhibit-logging
18314 (not org-treat-S-cursor-todo-selection-as-state-change))
18315 (org-inhibit-blocking
18316 (not org-treat-S-cursor-todo-selection-as-state-change)))
18317 (org-call-with-arg 'org-todo 'left)))
18318 ((or (and org-support-shift-select
18319 (not (eq org-support-shift-select 'always))
18320 (org-at-item-bullet-p))
18321 (and (not org-support-shift-select) (org-at-item-p)))
18322 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18323 ((and (not (eq org-support-shift-select 'always))
18324 (org-at-property-p))
18325 (call-interactively 'org-property-previous-allowed-value))
18326 ((org-clocktable-try-shift 'left arg))
18327 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18328 (org-support-shift-select
18329 (org-call-for-shift-select 'backward-char))
18330 (t (org-shiftselect-error))))
18332 (defun org-shiftcontrolright ()
18333 "Switch to next TODO set."
18334 (interactive)
18335 (cond
18336 ((and org-support-shift-select (org-region-active-p))
18337 (org-call-for-shift-select 'forward-word))
18338 ((and (not (eq org-support-shift-select 'always))
18339 (org-at-heading-p))
18340 (org-call-with-arg 'org-todo 'nextset))
18341 (org-support-shift-select
18342 (org-call-for-shift-select 'forward-word))
18343 (t (org-shiftselect-error))))
18345 (defun org-shiftcontrolleft ()
18346 "Switch to previous TODO set."
18347 (interactive)
18348 (cond
18349 ((and org-support-shift-select (org-region-active-p))
18350 (org-call-for-shift-select 'backward-word))
18351 ((and (not (eq org-support-shift-select 'always))
18352 (org-at-heading-p))
18353 (org-call-with-arg 'org-todo 'previousset))
18354 (org-support-shift-select
18355 (org-call-for-shift-select 'backward-word))
18356 (t (org-shiftselect-error))))
18358 (defun org-shiftcontrolup ()
18359 "Change timestamps synchronously up in CLOCK log lines."
18360 (interactive)
18361 (cond ((and (not org-support-shift-select)
18362 (org-at-clock-log-p)
18363 (org-at-timestamp-p t))
18364 (org-clock-timestamps-up))
18365 (t (org-shiftselect-error))))
18367 (defun org-shiftcontroldown ()
18368 "Change timestamps synchronously down in CLOCK log lines."
18369 (interactive)
18370 (cond ((and (not org-support-shift-select)
18371 (org-at-clock-log-p)
18372 (org-at-timestamp-p t))
18373 (org-clock-timestamps-down))
18374 (t (org-shiftselect-error))))
18376 (defun org-ctrl-c-ret ()
18377 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18378 (interactive)
18379 (cond
18380 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18381 (t (call-interactively 'org-insert-heading))))
18383 (defun org-find-visible ()
18384 (let ((s (point)))
18385 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18386 (get-char-property s 'invisible)))
18388 (defun org-find-invisible ()
18389 (let ((s (point)))
18390 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18391 (not (get-char-property s 'invisible))))
18394 (defun org-copy-visible (beg end)
18395 "Copy the visible parts of the region."
18396 (interactive "r")
18397 (let (snippets s)
18398 (save-excursion
18399 (save-restriction
18400 (narrow-to-region beg end)
18401 (setq s (goto-char (point-min)))
18402 (while (not (= (point) (point-max)))
18403 (goto-char (org-find-invisible))
18404 (push (buffer-substring s (point)) snippets)
18405 (setq s (goto-char (org-find-visible))))))
18406 (kill-new (apply 'concat (nreverse snippets)))))
18408 (defun org-copy-special ()
18409 "Copy region in table or copy current subtree.
18410 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18411 See the individual commands for more information."
18412 (interactive)
18413 (call-interactively
18414 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18416 (defun org-cut-special ()
18417 "Cut region in table or cut current subtree.
18418 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18419 See the individual commands for more information."
18420 (interactive)
18421 (call-interactively
18422 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18424 (defun org-paste-special (arg)
18425 "Paste rectangular region into table, or past subtree relative to level.
18426 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18427 See the individual commands for more information."
18428 (interactive "P")
18429 (if (org-at-table-p)
18430 (org-table-paste-rectangle)
18431 (org-paste-subtree arg)))
18433 (defun org-edit-special (&optional arg)
18434 "Call a special editor for the stuff at point.
18435 When at a table, call the formula editor with `org-table-edit-formulas'.
18436 When at the first line of an src example, call `org-edit-src-code'.
18437 When in an #+include line, visit the include file. Otherwise call
18438 `ffap' to visit the file at point."
18439 (interactive)
18440 ;; possibly prep session before editing source
18441 (when arg
18442 (let* ((info (org-babel-get-src-block-info))
18443 (lang (nth 0 info))
18444 (params (nth 2 info))
18445 (session (cdr (assoc :session params))))
18446 (when (and info session) ;; we are in a source-code block with a session
18447 (funcall
18448 (intern (concat "org-babel-prep-session:" lang)) session params))))
18449 (cond ;; proceed with `org-edit-special'
18450 ((save-excursion
18451 (beginning-of-line 1)
18452 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18453 (find-file (org-trim (match-string 1))))
18454 ((org-edit-src-code))
18455 ((org-edit-fixed-width-region))
18456 ((org-at-table.el-p)
18457 (org-edit-src-code))
18458 ((or (org-at-table-p)
18459 (save-excursion
18460 (beginning-of-line 1)
18461 (looking-at "[ \t]*#\\+TBLFM:")))
18462 (call-interactively 'org-table-edit-formulas))
18463 (t (call-interactively 'ffap))))
18465 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18466 (defun org-ctrl-c-ctrl-c (&optional arg)
18467 "Set tags in headline, or update according to changed information at point.
18469 This command does many different things, depending on context:
18471 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18472 this is what we do.
18474 - If the cursor is on a statistics cookie, update it.
18476 - If the cursor is in a headline, prompt for tags and insert them
18477 into the current line, aligned to `org-tags-column'. When called
18478 with prefix arg, realign all tags in the current buffer.
18480 - If the cursor is in one of the special #+KEYWORD lines, this
18481 triggers scanning the buffer for these lines and updating the
18482 information.
18484 - If the cursor is inside a table, realign the table. This command
18485 works even if the automatic table editor has been turned off.
18487 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18488 the entire table.
18490 - If the cursor is at a footnote reference or definition, jump to
18491 the corresponding definition or references, respectively.
18493 - If the cursor is a the beginning of a dynamic block, update it.
18495 - If the current buffer is a capture buffer, close note and file it.
18497 - If the cursor is on a <<<target>>>, update radio targets and
18498 corresponding links in this buffer.
18500 - If the cursor is on a numbered item in a plain list, renumber the
18501 ordered list.
18503 - If the cursor is on a checkbox, toggle it.
18505 - If the cursor is on a code block, evaluate it. The variable
18506 `org-confirm-babel-evaluate' can be used to control prompting
18507 before code block evaluation, by default every code block
18508 evaluation requires confirmation. Code block evaluation can be
18509 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18510 (interactive "P")
18511 (let ((org-enable-table-editor t))
18512 (cond
18513 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18514 org-occur-highlights
18515 org-latex-fragment-image-overlays)
18516 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18517 (org-remove-occur-highlights)
18518 (org-remove-latex-fragment-image-overlays)
18519 (message "Temporary highlights/overlays removed from current buffer"))
18520 ((and (local-variable-p 'org-finish-function (current-buffer))
18521 (fboundp org-finish-function))
18522 (funcall org-finish-function))
18523 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18524 ((org-in-regexp org-ts-regexp-both)
18525 (org-timestamp-change 0 'day))
18526 ((or (looking-at org-property-start-re)
18527 (org-at-property-p))
18528 (call-interactively 'org-property-action))
18529 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18530 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18531 (or (org-at-heading-p) (org-at-item-p)))
18532 (call-interactively 'org-update-statistics-cookies))
18533 ((org-at-heading-p) (call-interactively 'org-set-tags))
18534 ((org-at-table.el-p)
18535 (message "Use C-c ' to edit table.el tables"))
18536 ((org-at-table-p)
18537 (org-table-maybe-eval-formula)
18538 (if arg
18539 (call-interactively 'org-table-recalculate)
18540 (org-table-maybe-recalculate-line))
18541 (call-interactively 'org-table-align)
18542 (orgtbl-send-table 'maybe))
18543 ((or (org-footnote-at-reference-p)
18544 (org-footnote-at-definition-p))
18545 (call-interactively 'org-footnote-action))
18546 ((org-at-item-checkbox-p)
18547 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18548 ;; list only if at top item.
18549 (let* ((cbox (match-string 1))
18550 (struct (org-list-struct))
18551 (old-struct (copy-tree struct))
18552 (parents (org-list-parents-alist struct))
18553 (orderedp (org-entry-get nil "ORDERED"))
18554 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18555 block-item)
18556 ;; Use a light version of `org-toggle-checkbox' to avoid
18557 ;; computing list structure twice.
18558 (let ((new-box (cond
18559 ((equal arg '(16)) "[-]")
18560 ((equal arg '(4)) nil)
18561 ((equal "[X]" cbox) "[ ]")
18562 (t "[X]"))))
18563 (if (and firstp arg)
18564 ;; If at first item of sub-list, remove check-box from
18565 ;; every item at the same level.
18566 (mapc
18567 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18568 (org-list-get-all-items
18569 (point-at-bol) struct (org-list-prevs-alist struct)))
18570 (org-list-set-checkbox (point-at-bol) struct new-box)))
18571 ;; Replicate `org-list-write-struct', while grabbing a return
18572 ;; value from `org-list-struct-fix-box'.
18573 (org-list-struct-fix-ind struct parents 2)
18574 (org-list-struct-fix-item-end struct)
18575 (let ((prevs (org-list-prevs-alist struct)))
18576 (org-list-struct-fix-bul struct prevs)
18577 (org-list-struct-fix-ind struct parents)
18578 (setq block-item
18579 (org-list-struct-fix-box struct parents prevs orderedp)))
18580 (org-list-struct-apply-struct struct old-struct)
18581 (org-update-checkbox-count-maybe)
18582 (when block-item
18583 (message
18584 "Checkboxes were removed due to unchecked box at line %d"
18585 (org-current-line block-item)))
18586 (when firstp (org-list-send-list 'maybe))))
18587 ((org-at-item-p)
18588 ;; Cursor at an item: repair list. Do checkbox related actions
18589 ;; only if function was called with an argument. Send list only
18590 ;; if at top item.
18591 (let* ((struct (org-list-struct))
18592 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18593 old-struct)
18594 (when arg
18595 (setq old-struct (copy-tree struct))
18596 (if firstp
18597 ;; If at first item of sub-list, add check-box to every
18598 ;; item at the same level.
18599 (mapc
18600 (lambda (pos)
18601 (unless (org-list-get-checkbox pos struct)
18602 (org-list-set-checkbox pos struct "[ ]")))
18603 (org-list-get-all-items
18604 (point-at-bol) struct (org-list-prevs-alist struct)))
18605 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18606 (org-list-write-struct
18607 struct (org-list-parents-alist struct) old-struct)
18608 (when arg (org-update-checkbox-count-maybe))
18609 (when firstp (org-list-send-list 'maybe))))
18610 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18611 ;; Dynamic block
18612 (beginning-of-line 1)
18613 (save-excursion (org-update-dblock)))
18614 ((save-excursion
18615 (beginning-of-line 1)
18616 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18617 (cond
18618 ((equal (match-string 1) "TBLFM")
18619 ;; Recalculate the table before this line
18620 (save-excursion
18621 (beginning-of-line 1)
18622 (skip-chars-backward " \r\n\t")
18623 (if (org-at-table-p)
18624 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18626 (let ((org-inhibit-startup-visibility-stuff t)
18627 (org-startup-align-all-tables nil))
18628 (when (boundp 'org-table-coordinate-overlays)
18629 (mapc 'delete-overlay org-table-coordinate-overlays)
18630 (setq org-table-coordinate-overlays nil))
18631 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18632 (message "Local setup has been refreshed"))))
18633 ((org-clock-update-time-maybe))
18635 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18636 (error "C-c C-c can do nothing useful at this location"))))))
18638 (defun org-mode-restart ()
18639 "Restart Org-mode, to scan again for special lines.
18640 Also updates the keyword regular expressions."
18641 (interactive)
18642 (org-mode)
18643 (message "Org-mode restarted"))
18645 (defun org-kill-note-or-show-branches ()
18646 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18647 (interactive)
18648 (if (not org-finish-function)
18649 (progn
18650 (hide-subtree)
18651 (call-interactively 'show-branches))
18652 (let ((org-note-abort t))
18653 (funcall org-finish-function))))
18655 (defun org-return (&optional indent)
18656 "Goto next table row or insert a newline.
18657 Calls `org-table-next-row' or `newline', depending on context.
18658 See the individual commands for more information."
18659 (interactive)
18660 (cond
18661 ((or (bobp) (org-in-src-block-p))
18662 (if indent (newline-and-indent) (newline)))
18663 ((org-at-table-p)
18664 (org-table-justify-field-maybe)
18665 (call-interactively 'org-table-next-row))
18666 ;; when `newline-and-indent' is called within a list, make sure
18667 ;; text moved stays inside the item.
18668 ((and (org-in-item-p) indent)
18669 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18670 (progn
18671 (save-match-data (newline))
18672 (org-indent-line-to (length (match-string 0))))
18673 (let ((ind (org-get-indentation)))
18674 (newline)
18675 (if (org-looking-back org-list-end-re)
18676 (org-indent-line-function)
18677 (org-indent-line-to ind)))))
18678 ((and org-return-follows-link
18679 (let ((tprop (get-text-property (point) 'face)))
18680 (or (eq tprop 'org-link)
18681 (and (listp tprop) (memq 'org-link tprop)))))
18682 (call-interactively 'org-open-at-point))
18683 ((and (org-at-heading-p)
18684 (looking-at
18685 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18686 (org-show-entry)
18687 (end-of-line 1)
18688 (newline))
18689 (t (if indent (newline-and-indent) (newline)))))
18691 (defun org-return-indent ()
18692 "Goto next table row or insert a newline and indent.
18693 Calls `org-table-next-row' or `newline-and-indent', depending on
18694 context. See the individual commands for more information."
18695 (interactive)
18696 (org-return t))
18698 (defun org-ctrl-c-star ()
18699 "Compute table, or change heading status of lines.
18700 Calls `org-table-recalculate' or `org-toggle-heading',
18701 depending on context."
18702 (interactive)
18703 (cond
18704 ((org-at-table-p)
18705 (call-interactively 'org-table-recalculate))
18707 ;; Convert all lines in region to list items
18708 (call-interactively 'org-toggle-heading))))
18710 (defun org-ctrl-c-minus ()
18711 "Insert separator line in table or modify bullet status of line.
18712 Also turns a plain line or a region of lines into list items.
18713 Calls `org-table-insert-hline', `org-toggle-item', or
18714 `org-cycle-list-bullet', depending on context."
18715 (interactive)
18716 (cond
18717 ((org-at-table-p)
18718 (call-interactively 'org-table-insert-hline))
18719 ((org-region-active-p)
18720 (call-interactively 'org-toggle-item))
18721 ((org-in-item-p)
18722 (call-interactively 'org-cycle-list-bullet))
18724 (call-interactively 'org-toggle-item))))
18726 (defun org-toggle-item (arg)
18727 "Convert headings or normal lines to items, items to normal lines.
18728 If there is no active region, only the current line is considered.
18730 If the first non blank line in the region is an headline, convert
18731 all headlines to items, shifting text accordingly.
18733 If it is an item, convert all items to normal lines.
18735 If it is normal text, change region into an item. With a prefix
18736 argument ARG, change each line in region into an item."
18737 (interactive "P")
18738 (let ((shift-text
18739 (function
18740 ;; Shift text in current section to IND, from point to END.
18741 ;; The function leaves point to END line.
18742 (lambda (ind end)
18743 (let ((min-i 1000) (end (copy-marker end)))
18744 ;; First determine the minimum indentation (MIN-I) of
18745 ;; the text.
18746 (save-excursion
18747 (catch 'exit
18748 (while (< (point) end)
18749 (let ((i (org-get-indentation)))
18750 (cond
18751 ;; Skip blank lines and inline tasks.
18752 ((looking-at "^[ \t]*$"))
18753 ((looking-at org-outline-regexp-bol))
18754 ;; We can't find less than 0 indentation.
18755 ((zerop i) (throw 'exit (setq min-i 0)))
18756 ((< i min-i) (setq min-i i))))
18757 (forward-line))))
18758 ;; Then indent each line so that a line indented to
18759 ;; MIN-I becomes indented to IND. Ignore blank lines
18760 ;; and inline tasks in the process.
18761 (let ((delta (- ind min-i)))
18762 (while (< (point) end)
18763 (unless (or (looking-at "^[ \t]*$")
18764 (looking-at org-outline-regexp-bol))
18765 (org-indent-line-to (+ (org-get-indentation) delta)))
18766 (forward-line)))))))
18767 (skip-blanks
18768 (function
18769 ;; Return beginning of first non-blank line, starting from
18770 ;; line at POS.
18771 (lambda (pos)
18772 (save-excursion
18773 (goto-char pos)
18774 (skip-chars-forward " \r\t\n")
18775 (point-at-bol)))))
18776 beg end)
18777 ;; Determine boundaries of changes.
18778 (if (org-region-active-p)
18779 (setq beg (funcall skip-blanks (region-beginning))
18780 end (copy-marker (region-end)))
18781 (setq beg (funcall skip-blanks (point-at-bol))
18782 end (copy-marker (point-at-eol))))
18783 ;; Depending on the starting line, choose an action on the text
18784 ;; between BEG and END.
18785 (org-with-limited-levels
18786 (save-excursion
18787 (goto-char beg)
18788 (cond
18789 ;; Case 1. Start at an item: de-itemize. Note that it only
18790 ;; happens when a region is active: `org-ctrl-c-minus'
18791 ;; would call `org-cycle-list-bullet' otherwise.
18792 ((org-at-item-p)
18793 (while (< (point) end)
18794 (when (org-at-item-p)
18795 (skip-chars-forward " \t")
18796 (delete-region (point) (match-end 0)))
18797 (forward-line)))
18798 ;; Case 2. Start at an heading: convert to items.
18799 ((org-at-heading-p)
18800 (let* ((bul (org-list-bullet-string "-"))
18801 (bul-len (length bul))
18802 ;; Indentation of the first heading. It should be
18803 ;; relative to the indentation of its parent, if any.
18804 (start-ind (save-excursion
18805 (cond
18806 ((not org-adapt-indentation) 0)
18807 ((not (outline-previous-heading)) 0)
18808 (t (length (match-string 0))))))
18809 ;; Level of first heading. Further headings will be
18810 ;; compared to it to determine hierarchy in the list.
18811 (ref-level (org-reduced-level (org-outline-level))))
18812 (while (< (point) end)
18813 (let* ((level (org-reduced-level (org-outline-level)))
18814 (delta (max 0 (- level ref-level))))
18815 ;; If current headline is less indented than the first
18816 ;; one, set it as reference, in order to preserve
18817 ;; subtrees.
18818 (when (< level ref-level) (setq ref-level level))
18819 (replace-match bul t t)
18820 (org-indent-line-to (+ start-ind (* delta bul-len)))
18821 ;; Ensure all text down to END (or SECTION-END) belongs
18822 ;; to the newly created item.
18823 (let ((section-end (save-excursion
18824 (or (outline-next-heading) (point)))))
18825 (forward-line)
18826 (funcall shift-text
18827 (+ start-ind (* (1+ delta) bul-len))
18828 (min end section-end)))))))
18829 ;; Case 3. Normal line with ARG: turn each non-item line into
18830 ;; an item.
18831 (arg
18832 (while (< (point) end)
18833 (unless (or (org-at-heading-p) (org-at-item-p))
18834 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18835 (replace-match
18836 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18837 (forward-line)))
18838 ;; Case 4. Normal line without ARG: make the first line of
18839 ;; region an item, and shift indentation of others
18840 ;; lines to set them as item's body.
18841 (t (let* ((bul (org-list-bullet-string "-"))
18842 (bul-len (length bul))
18843 (ref-ind (org-get-indentation)))
18844 (skip-chars-forward " \t")
18845 (insert bul)
18846 (forward-line)
18847 (while (< (point) end)
18848 ;; Ensure that lines less indented than first one
18849 ;; still get included in item body.
18850 (funcall shift-text
18851 (+ ref-ind bul-len)
18852 (min end (save-excursion (or (outline-next-heading)
18853 (point)))))
18854 (forward-line)))))))))
18856 (defun org-toggle-heading (&optional nstars)
18857 "Convert headings to normal text, or items or text to headings.
18858 If there is no active region, only the current line is considered.
18860 If the first non blank line is an headline, remove the stars from
18861 all headlines in the region.
18863 If it is a plain list item, turn all plain list items into headings.
18865 If it is a normal line, turn each and every normal line (i.e. not
18866 an heading or an item) in the region into a heading.
18868 When converting a line into a heading, the number of stars is chosen
18869 such that the lines become children of the current entry. However,
18870 when a prefix argument is given, its value determines the number of
18871 stars to add."
18872 (interactive "P")
18873 (let ((skip-blanks
18874 (function
18875 ;; Return beginning of first non-blank line, starting from
18876 ;; line at POS.
18877 (lambda (pos)
18878 (save-excursion
18879 (goto-char pos)
18880 (skip-chars-forward " \r\t\n")
18881 (point-at-bol)))))
18882 beg end)
18883 ;; Determine boundaries of changes. If region ends at a bol, do
18884 ;; not consider the last line to be in the region.
18885 (if (org-region-active-p)
18886 (setq beg (funcall skip-blanks (region-beginning))
18887 end (copy-marker (save-excursion
18888 (goto-char (region-end))
18889 (if (bolp) (point) (point-at-eol)))))
18890 (setq beg (funcall skip-blanks (point-at-bol))
18891 end (copy-marker (point-at-eol))))
18892 ;; Ensure inline tasks don't count as headings.
18893 (org-with-limited-levels
18894 (save-excursion
18895 (goto-char beg)
18896 (cond
18897 ;; Case 1. Started at an heading: de-star headings.
18898 ((org-at-heading-p)
18899 (while (< (point) end)
18900 (when (org-at-heading-p t)
18901 (looking-at org-outline-regexp) (replace-match ""))
18902 (forward-line)))
18903 ;; Case 2. Started at an item: change items into headlines.
18904 ;; One star will be added by `org-list-to-subtree'.
18905 ((org-at-item-p)
18906 (let* ((stars (make-string
18907 (if nstars
18908 ;; subtract the star that will be added again by
18909 ;; `org-list-to-subtree'
18910 (1- (prefix-numeric-value current-prefix-arg))
18911 (or (org-current-level) 0))
18912 ?*))
18913 (add-stars
18914 (cond (nstars "") ; stars from prefix only
18915 ((equal stars "") "") ; before first heading
18916 (org-odd-levels-only "*") ; inside heading, odd
18917 (t "")))) ; inside heading, oddeven
18918 (while (< (point) end)
18919 (when (org-at-item-p)
18920 ;; Pay attention to cases when region ends before list.
18921 (let* ((struct (org-list-struct))
18922 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18923 (save-restriction
18924 (narrow-to-region (point) list-end)
18925 (insert
18926 (org-list-to-subtree
18927 (org-list-parse-list t)
18928 '(:istart (concat stars add-stars (funcall get-stars depth))
18929 :icount (concat stars add-stars (funcall get-stars depth))))))))
18930 (forward-line))))
18931 ;; Case 3. Started at normal text: make every line an heading,
18932 ;; skipping headlines and items.
18933 (t (let* ((stars (make-string
18934 (if nstars
18935 (prefix-numeric-value current-prefix-arg)
18936 (or (org-current-level) 0))
18937 ?*))
18938 (add-stars
18939 (cond (nstars "") ; stars from prefix only
18940 ((equal stars "") "*") ; before first heading
18941 (org-odd-levels-only "**") ; inside heading, odd
18942 (t "*"))) ; inside heading, oddeven
18943 (rpl (concat stars add-stars " ")))
18944 (while (< (point) end)
18945 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18946 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18947 (replace-match (concat rpl (match-string 2))))
18948 (forward-line)))))))))
18950 (defun org-meta-return (&optional arg)
18951 "Insert a new heading or wrap a region in a table.
18952 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18953 See the individual commands for more information."
18954 (interactive "P")
18955 (cond
18956 ((run-hook-with-args-until-success 'org-metareturn-hook))
18957 ((or (org-at-drawer-p) (org-at-property-p))
18958 (newline-and-indent))
18959 ((org-at-table-p)
18960 (call-interactively 'org-table-wrap-region))
18961 (t (call-interactively 'org-insert-heading))))
18963 ;;; Menu entries
18965 ;; Define the Org-mode menus
18966 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18967 '("Tbl"
18968 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18969 ["Next Field" org-cycle (org-at-table-p)]
18970 ["Previous Field" org-shifttab (org-at-table-p)]
18971 ["Next Row" org-return (org-at-table-p)]
18972 "--"
18973 ["Blank Field" org-table-blank-field (org-at-table-p)]
18974 ["Edit Field" org-table-edit-field (org-at-table-p)]
18975 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18976 "--"
18977 ("Column"
18978 ["Move Column Left" org-metaleft (org-at-table-p)]
18979 ["Move Column Right" org-metaright (org-at-table-p)]
18980 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18981 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18982 ("Row"
18983 ["Move Row Up" org-metaup (org-at-table-p)]
18984 ["Move Row Down" org-metadown (org-at-table-p)]
18985 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18986 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18987 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18988 "--"
18989 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18990 ("Rectangle"
18991 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18992 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18993 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18994 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18995 "--"
18996 ("Calculate"
18997 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18998 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18999 ["Edit Formulas" org-edit-special (org-at-table-p)]
19000 "--"
19001 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19002 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19003 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19004 "--"
19005 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19006 "--"
19007 ["Sum Column/Rectangle" org-table-sum
19008 (or (org-at-table-p) (org-region-active-p))]
19009 ["Which Column?" org-table-current-column (org-at-table-p)])
19010 ["Debug Formulas"
19011 org-table-toggle-formula-debugger
19012 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19013 ["Show Col/Row Numbers"
19014 org-table-toggle-coordinate-overlays
19015 :style toggle
19016 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19017 "--"
19018 ["Create" org-table-create (and (not (org-at-table-p))
19019 org-enable-table-editor)]
19020 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19021 ["Import from File" org-table-import (not (org-at-table-p))]
19022 ["Export to File" org-table-export (org-at-table-p)]
19023 "--"
19024 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19026 (easy-menu-define org-org-menu org-mode-map "Org menu"
19027 '("Org"
19028 ("Show/Hide"
19029 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19030 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19031 ["Sparse Tree..." org-sparse-tree t]
19032 ["Reveal Context" org-reveal t]
19033 ["Show All" show-all t]
19034 "--"
19035 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19036 "--"
19037 ["New Heading" org-insert-heading t]
19038 ("Navigate Headings"
19039 ["Up" outline-up-heading t]
19040 ["Next" outline-next-visible-heading t]
19041 ["Previous" outline-previous-visible-heading t]
19042 ["Next Same Level" outline-forward-same-level t]
19043 ["Previous Same Level" outline-backward-same-level t]
19044 "--"
19045 ["Jump" org-goto t])
19046 ("Edit Structure"
19047 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19048 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19049 "--"
19050 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19051 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19052 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19053 "--"
19054 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19055 "--"
19056 ["Copy visible text" org-copy-visible t]
19057 "--"
19058 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19059 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19060 ["Demote Heading" org-metaright (not (org-at-table-p))]
19061 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19062 "--"
19063 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19064 "--"
19065 ["Convert to odd levels" org-convert-to-odd-levels t]
19066 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19067 ("Editing"
19068 ["Emphasis..." org-emphasize t]
19069 ["Edit Source Example" org-edit-special t]
19070 "--"
19071 ["Footnote new/jump" org-footnote-action t]
19072 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19073 ("Archive"
19074 ["Archive (default method)" org-archive-subtree-default t]
19075 "--"
19076 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19077 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19078 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19080 "--"
19081 ("Hyperlinks"
19082 ["Store Link (Global)" org-store-link t]
19083 ["Find existing link to here" org-occur-link-in-agenda-files t]
19084 ["Insert Link" org-insert-link t]
19085 ["Follow Link" org-open-at-point t]
19086 "--"
19087 ["Next link" org-next-link t]
19088 ["Previous link" org-previous-link t]
19089 "--"
19090 ["Descriptive Links"
19091 org-toggle-link-display
19092 :style radio
19093 :selected org-descriptive-links
19095 ["Literal Links"
19096 org-toggle-link-display
19097 :style radio
19098 :selected (not org-descriptive-links)])
19099 "--"
19100 ("TODO Lists"
19101 ["TODO/DONE/-" org-todo t]
19102 ("Select keyword"
19103 ["Next keyword" org-shiftright (org-at-heading-p)]
19104 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19105 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19106 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19107 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19108 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19109 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19110 "--"
19111 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19112 :selected org-enforce-todo-dependencies :style toggle :active t]
19113 "Settings for tree at point"
19114 ["Do Children sequentially" org-toggle-ordered-property :style radio
19115 :selected (org-entry-get nil "ORDERED")
19116 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19117 ["Do Children parallel" org-toggle-ordered-property :style radio
19118 :selected (not (org-entry-get nil "ORDERED"))
19119 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19120 "--"
19121 ["Set Priority" org-priority t]
19122 ["Priority Up" org-shiftup t]
19123 ["Priority Down" org-shiftdown t]
19124 "--"
19125 ["Get news from all feeds" org-feed-update-all t]
19126 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19127 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19128 ("TAGS and Properties"
19129 ["Set Tags" org-set-tags-command t]
19130 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19131 "--"
19132 ["Set property" org-set-property t]
19133 ["Column view of properties" org-columns t]
19134 ["Insert Column View DBlock" org-insert-columns-dblock t])
19135 ("Dates and Scheduling"
19136 ["Timestamp" org-time-stamp t]
19137 ["Timestamp (inactive)" org-time-stamp-inactive t]
19138 ("Change Date"
19139 ["1 Day Later" org-shiftright t]
19140 ["1 Day Earlier" org-shiftleft t]
19141 ["1 ... Later" org-shiftup t]
19142 ["1 ... Earlier" org-shiftdown t])
19143 ["Compute Time Range" org-evaluate-time-range t]
19144 ["Schedule Item" org-schedule t]
19145 ["Deadline" org-deadline t]
19146 "--"
19147 ["Custom time format" org-toggle-time-stamp-overlays
19148 :style radio :selected org-display-custom-times]
19149 "--"
19150 ["Goto Calendar" org-goto-calendar t]
19151 ["Date from Calendar" org-date-from-calendar t]
19152 "--"
19153 ["Start/Restart Timer" org-timer-start t]
19154 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19155 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19156 ["Insert Timer String" org-timer t]
19157 ["Insert Timer Item" org-timer-item t])
19158 ("Logging work"
19159 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19160 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19161 ["Clock out" org-clock-out t]
19162 ["Clock cancel" org-clock-cancel t]
19163 "--"
19164 ["Mark as default task" org-clock-mark-default-task t]
19165 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19166 ["Goto running clock" org-clock-goto t]
19167 "--"
19168 ["Display times" org-clock-display t]
19169 ["Create clock table" org-clock-report t]
19170 "--"
19171 ["Record DONE time"
19172 (progn (setq org-log-done (not org-log-done))
19173 (message "Switching to %s will %s record a timestamp"
19174 (car org-done-keywords)
19175 (if org-log-done "automatically" "not")))
19176 :style toggle :selected org-log-done])
19177 "--"
19178 ["Agenda Command..." org-agenda t]
19179 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19180 ("File List for Agenda")
19181 ("Special views current file"
19182 ["TODO Tree" org-show-todo-tree t]
19183 ["Check Deadlines" org-check-deadlines t]
19184 ["Timeline" org-timeline t]
19185 ["Tags/Property tree" org-match-sparse-tree t])
19186 "--"
19187 ["Export/Publish..." org-export t]
19188 ("LaTeX"
19189 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19190 :selected org-cdlatex-mode]
19191 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19192 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19193 ["Modify math symbol" org-cdlatex-math-modify
19194 (org-inside-LaTeX-fragment-p)]
19195 ["Insert citation" org-reftex-citation t]
19196 "--"
19197 ["Template for BEAMER" org-insert-beamer-options-template t])
19198 "--"
19199 ("MobileOrg"
19200 ["Push Files and Views" org-mobile-push t]
19201 ["Get Captured and Flagged" org-mobile-pull t]
19202 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19203 "--"
19204 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19205 "--"
19206 ("Documentation"
19207 ["Show Version" org-version t]
19208 ["Info Documentation" org-info t])
19209 ("Customize"
19210 ["Browse Org Group" org-customize t]
19211 "--"
19212 ["Expand This Menu" org-create-customize-menu
19213 (fboundp 'customize-menu-create)])
19214 ["Send bug report" org-submit-bug-report t]
19215 "--"
19216 ("Refresh/Reload"
19217 ["Refresh setup current buffer" org-mode-restart t]
19218 ["Reload Org (after update)" org-reload t]
19219 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19222 (defun org-info (&optional node)
19223 "Read documentation for Org-mode in the info system.
19224 With optional NODE, go directly to that node."
19225 (interactive)
19226 (info (format "(org)%s" (or node ""))))
19228 ;;;###autoload
19229 (defun org-submit-bug-report ()
19230 "Submit a bug report on Org-mode via mail.
19232 Don't hesitate to report any problems or inaccurate documentation.
19234 If you don't have setup sending mail from (X)Emacs, please copy the
19235 output buffer into your mail program, as it gives us important
19236 information about your Org-mode version and configuration."
19237 (interactive)
19238 (require 'reporter)
19239 (org-load-modules-maybe)
19240 (org-require-autoloaded-modules)
19241 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19242 (reporter-submit-bug-report
19243 "emacs-orgmode@gnu.org"
19244 (org-version)
19245 (let (list)
19246 (save-window-excursion
19247 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19248 (delete-other-windows)
19249 (erase-buffer)
19250 (insert "You are about to submit a bug report to the Org-mode mailing list.
19252 We would like to add your full Org-mode and Outline configuration to the
19253 bug report. This greatly simplifies the work of the maintainer and
19254 other experts on the mailing list.
19256 HOWEVER, some variables you have customized may contain private
19257 information. The names of customers, colleagues, or friends, might
19258 appear in the form of file names, tags, todo states, or search strings.
19259 If you answer yes to the prompt, you might want to check and remove
19260 such private information before sending the email.")
19261 (add-text-properties (point-min) (point-max) '(face org-warning))
19262 (when (yes-or-no-p "Include your Org-mode configuration ")
19263 (mapatoms
19264 (lambda (v)
19265 (and (boundp v)
19266 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19267 (or (and (symbol-value v)
19268 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19269 (and
19270 (get v 'custom-type) (get v 'standard-value)
19271 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19272 (push v list)))))
19273 (kill-buffer (get-buffer "*Warn about privacy*"))
19274 list))
19275 nil nil
19276 "Remember to cover the basics, that is, what you expected to happen and
19277 what in fact did happen. You don't know how to make a good report? See
19279 http://orgmode.org/manual/Feedback.html#Feedback
19281 Your bug report will be posted to the Org-mode mailing list.
19282 ------------------------------------------------------------------------")
19283 (save-excursion
19284 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19285 (replace-match "\\1Bug: \\3 [\\2]")))))
19288 (defun org-install-agenda-files-menu ()
19289 (let ((bl (buffer-list)))
19290 (save-excursion
19291 (while bl
19292 (set-buffer (pop bl))
19293 (if (eq major-mode 'org-mode) (setq bl nil)))
19294 (when (eq major-mode 'org-mode)
19295 (easy-menu-change
19296 '("Org") "File List for Agenda"
19297 (append
19298 (list
19299 ["Edit File List" (org-edit-agenda-file-list) t]
19300 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19301 ["Remove Current File from List" org-remove-file t]
19302 ["Cycle through agenda files" org-cycle-agenda-files t]
19303 ["Occur in all agenda files" org-occur-in-agenda-files t]
19304 "--")
19305 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19307 ;;;; Documentation
19309 ;;;###autoload
19310 (defun org-require-autoloaded-modules ()
19311 (interactive)
19312 (mapc 'require
19313 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19314 org-docbook org-exp org-html org-icalendar
19315 org-id org-latex
19316 org-publish org-remember org-table
19317 org-timer org-xoxo)))
19319 ;;;###autoload
19320 (defun org-reload (&optional uncompiled)
19321 "Reload all org lisp files.
19322 With prefix arg UNCOMPILED, load the uncompiled versions."
19323 (interactive "P")
19324 (require 'find-func)
19325 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19326 (dir-org (file-name-directory (org-find-library-name "org")))
19327 (dir-org-contrib (ignore-errors
19328 (file-name-directory
19329 (org-find-library-name "org-contribdir"))))
19330 (babel-files
19331 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19332 (append (list nil "comint" "eval" "exp" "keys"
19333 "lob" "ref" "table" "tangle")
19334 (delq nil
19335 (mapcar
19336 (lambda (lang)
19337 (when (cdr lang) (symbol-name (car lang))))
19338 org-babel-load-languages)))))
19339 (files
19340 (append (directory-files dir-org t file-re)
19341 babel-files
19342 (and dir-org-contrib
19343 (directory-files dir-org-contrib t file-re))))
19344 (remove-re (concat (if (featurep 'xemacs)
19345 "org-colview" "org-colview-xemacs")
19346 "\\'")))
19347 (setq files (mapcar 'file-name-sans-extension files))
19348 (setq files (mapcar
19349 (lambda (x) (if (string-match remove-re x) nil x))
19350 files))
19351 (setq files (delq nil files))
19352 (mapc
19353 (lambda (f)
19354 (when (featurep (intern (file-name-nondirectory f)))
19355 (if (and (not uncompiled)
19356 (file-exists-p (concat f ".elc")))
19357 (load (concat f ".elc") nil nil t)
19358 (load (concat f ".el") nil nil t))))
19359 files))
19360 (org-version))
19362 ;;;###autoload
19363 (defun org-customize ()
19364 "Call the customize function with org as argument."
19365 (interactive)
19366 (org-load-modules-maybe)
19367 (org-require-autoloaded-modules)
19368 (customize-browse 'org))
19370 (defun org-create-customize-menu ()
19371 "Create a full customization menu for Org-mode, insert it into the menu."
19372 (interactive)
19373 (org-load-modules-maybe)
19374 (org-require-autoloaded-modules)
19375 (if (fboundp 'customize-menu-create)
19376 (progn
19377 (easy-menu-change
19378 '("Org") "Customize"
19379 `(["Browse Org group" org-customize t]
19380 "--"
19381 ,(customize-menu-create 'org)
19382 ["Set" Custom-set t]
19383 ["Save" Custom-save t]
19384 ["Reset to Current" Custom-reset-current t]
19385 ["Reset to Saved" Custom-reset-saved t]
19386 ["Reset to Standard Settings" Custom-reset-standard t]))
19387 (message "\"Org\"-menu now contains full customization menu"))
19388 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19390 ;;;; Miscellaneous stuff
19392 ;;; Generally useful functions
19394 (defun org-get-at-bol (property)
19395 "Get text property PROPERTY at beginning of line."
19396 (get-text-property (point-at-bol) property))
19398 (defun org-find-text-property-in-string (prop s)
19399 "Return the first non-nil value of property PROP in string S."
19400 (or (get-text-property 0 prop s)
19401 (get-text-property (or (next-single-property-change 0 prop s) 0)
19402 prop s)))
19404 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19405 "Display the given MESSAGE as a warning."
19406 (if (fboundp 'display-warning)
19407 (display-warning 'org message
19408 (if (featurep 'xemacs) 'warning :warning))
19409 (let ((buf (get-buffer-create "*Org warnings*")))
19410 (with-current-buffer buf
19411 (goto-char (point-max))
19412 (insert "Warning (Org): " message)
19413 (unless (bolp)
19414 (newline)))
19415 (display-buffer buf)
19416 (sit-for 0))))
19418 (defun org-eval (form)
19419 "Eval FORM and return result."
19420 (condition-case error
19421 (eval form)
19422 (error (format "%%![Error: %s]" error))))
19424 (defun org-in-clocktable-p ()
19425 "Check if the cursor is in a clocktable."
19426 (let ((pos (point)) start)
19427 (save-excursion
19428 (end-of-line 1)
19429 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19430 (setq start (match-beginning 0))
19431 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19432 (>= (match-end 0) pos)
19433 start))))
19435 (defun org-in-commented-line ()
19436 "Is point in a line starting with `#'?"
19437 (equal (char-after (point-at-bol)) ?#))
19439 (defun org-in-indented-comment-line ()
19440 "Is point in a line starting with `#' after some white space?"
19441 (save-excursion
19442 (save-match-data
19443 (goto-char (point-at-bol))
19444 (looking-at "[ \t]*#"))))
19446 (defun org-in-verbatim-emphasis ()
19447 (save-match-data
19448 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19450 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19451 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19452 (if (and marker (marker-buffer marker)
19453 (buffer-live-p (marker-buffer marker)))
19454 (progn
19455 (org-pop-to-buffer-same-window (marker-buffer marker))
19456 (if (or (> marker (point-max)) (< marker (point-min)))
19457 (widen))
19458 (goto-char marker)
19459 (org-show-context 'org-goto))
19460 (if bookmark
19461 (bookmark-jump bookmark)
19462 (error "Cannot find location"))))
19464 (defun org-quote-csv-field (s)
19465 "Quote field for inclusion in CSV material."
19466 (if (string-match "[\",]" s)
19467 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19470 (defun org-force-self-insert (N)
19471 "Needed to enforce self-insert under remapping."
19472 (interactive "p")
19473 (self-insert-command N))
19475 (defun org-string-width (s)
19476 "Compute width of string, ignoring invisible characters.
19477 This ignores character with invisibility property `org-link', and also
19478 characters with property `org-cwidth', because these will become invisible
19479 upon the next fontification round."
19480 (let (b l)
19481 (when (or (eq t buffer-invisibility-spec)
19482 (assq 'org-link buffer-invisibility-spec))
19483 (while (setq b (text-property-any 0 (length s)
19484 'invisible 'org-link s))
19485 (setq s (concat (substring s 0 b)
19486 (substring s (or (next-single-property-change
19487 b 'invisible s) (length s)))))))
19488 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19489 (setq s (concat (substring s 0 b)
19490 (substring s (or (next-single-property-change
19491 b 'org-cwidth s) (length s))))))
19492 (setq l (string-width s) b -1)
19493 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19494 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19497 (defun org-shorten-string (s maxlength)
19498 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19499 If the string is shorter or has length MAXLENGTH, just return the
19500 original string. If it is longer, the functions finds a space in the
19501 string, breaks this string off at that locations and adds three dots
19502 as ellipsis. Including the ellipsis, the string will not be longer
19503 than MAXLENGTH. If finding a good breaking point in the string does
19504 not work, the string is just chopped off in the middle of a word
19505 if necessary."
19506 (if (<= (length s) maxlength)
19508 (let* ((n (max (- maxlength 4) 1))
19509 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19510 (if (string-match re s)
19511 (concat (match-string 1 s) "...")
19512 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19514 (defun org-get-indentation (&optional line)
19515 "Get the indentation of the current line, interpreting tabs.
19516 When LINE is given, assume it represents a line and compute its indentation."
19517 (if line
19518 (if (string-match "^ *" (org-remove-tabs line))
19519 (match-end 0))
19520 (save-excursion
19521 (beginning-of-line 1)
19522 (skip-chars-forward " \t")
19523 (current-column))))
19525 (defun org-get-string-indentation (s)
19526 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19527 (let ((n -1) (i 0) (w tab-width) c)
19528 (catch 'exit
19529 (while (< (setq n (1+ n)) (length s))
19530 (setq c (aref s n))
19531 (cond ((= c ?\ ) (setq i (1+ i)))
19532 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19533 (t (throw 'exit t)))))
19536 (defun org-remove-tabs (s &optional width)
19537 "Replace tabulators in S with spaces.
19538 Assumes that s is a single line, starting in column 0."
19539 (setq width (or width tab-width))
19540 (while (string-match "\t" s)
19541 (setq s (replace-match
19542 (make-string
19543 (- (* width (/ (+ (match-beginning 0) width) width))
19544 (match-beginning 0)) ?\ )
19545 t t s)))
19548 (defun org-fix-indentation (line ind)
19549 "Fix indentation in LINE.
19550 IND is a cons cell with target and minimum indentation.
19551 If the current indentation in LINE is smaller than the minimum,
19552 leave it alone. If it is larger than ind, set it to the target."
19553 (let* ((l (org-remove-tabs line))
19554 (i (org-get-indentation l))
19555 (i1 (car ind)) (i2 (cdr ind)))
19556 (if (>= i i2) (setq l (substring line i2)))
19557 (if (> i1 0)
19558 (concat (make-string i1 ?\ ) l)
19559 l)))
19561 (defun org-remove-indentation (code &optional n)
19562 "Remove the maximum common indentation from the lines in CODE.
19563 N may optionally be the number of spaces to remove."
19564 (with-temp-buffer
19565 (insert code)
19566 (org-do-remove-indentation n)
19567 (buffer-string)))
19569 (defun org-do-remove-indentation (&optional n)
19570 "Remove the maximum common indentation from the buffer."
19571 (untabify (point-min) (point-max))
19572 (let ((min 10000) re)
19573 (if n
19574 (setq min n)
19575 (goto-char (point-min))
19576 (while (re-search-forward "^ *[^ \n]" nil t)
19577 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19578 (unless (or (= min 0) (= min 10000))
19579 (setq re (format "^ \\{%d\\}" min))
19580 (goto-char (point-min))
19581 (while (re-search-forward re nil t)
19582 (replace-match "")
19583 (end-of-line 1))
19584 min)))
19586 (defun org-fill-template (template alist)
19587 "Find each %key of ALIST in TEMPLATE and replace it."
19588 (let ((case-fold-search nil)
19589 entry key value)
19590 (setq alist (sort (copy-sequence alist)
19591 (lambda (a b) (< (length (car a)) (length (car b))))))
19592 (while (setq entry (pop alist))
19593 (setq template
19594 (replace-regexp-in-string
19595 (concat "%" (regexp-quote (car entry)))
19596 (cdr entry) template t t)))
19597 template))
19599 (defun org-base-buffer (buffer)
19600 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19601 (if (not buffer)
19602 buffer
19603 (or (buffer-base-buffer buffer)
19604 buffer)))
19606 (defun org-trim (s)
19607 "Remove whitespace at beginning and end of string."
19608 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19609 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19612 (defun org-wrap (string &optional width lines)
19613 "Wrap string to either a number of lines, or a width in characters.
19614 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19615 that costs. If there is a word longer than WIDTH, the text is actually
19616 wrapped to the length of that word.
19617 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19618 many lines, whatever width that takes.
19619 The return value is a list of lines, without newlines at the end."
19620 (let* ((words (org-split-string string "[ \t\n]+"))
19621 (maxword (apply 'max (mapcar 'org-string-width words)))
19622 w ll)
19623 (cond (width
19624 (org-do-wrap words (max maxword width)))
19625 (lines
19626 (setq w maxword)
19627 (setq ll (org-do-wrap words maxword))
19628 (if (<= (length ll) lines)
19630 (setq ll words)
19631 (while (> (length ll) lines)
19632 (setq w (1+ w))
19633 (setq ll (org-do-wrap words w)))
19634 ll))
19635 (t (error "Cannot wrap this")))))
19637 (defun org-do-wrap (words width)
19638 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19639 (let (lines line)
19640 (while words
19641 (setq line (pop words))
19642 (while (and words (< (+ (length line) (length (car words))) width))
19643 (setq line (concat line " " (pop words))))
19644 (setq lines (push line lines)))
19645 (nreverse lines)))
19647 (defun org-split-string (string &optional separators)
19648 "Splits STRING into substrings at SEPARATORS.
19649 No empty strings are returned if there are matches at the beginning
19650 and end of string."
19651 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19652 (start 0)
19653 notfirst
19654 (list nil))
19655 (while (and (string-match rexp string
19656 (if (and notfirst
19657 (= start (match-beginning 0))
19658 (< start (length string)))
19659 (1+ start) start))
19660 (< (match-beginning 0) (length string)))
19661 (setq notfirst t)
19662 (or (eq (match-beginning 0) 0)
19663 (and (eq (match-beginning 0) (match-end 0))
19664 (eq (match-beginning 0) start))
19665 (setq list
19666 (cons (substring string start (match-beginning 0))
19667 list)))
19668 (setq start (match-end 0)))
19669 (or (eq start (length string))
19670 (setq list
19671 (cons (substring string start)
19672 list)))
19673 (nreverse list)))
19675 (defun org-quote-vert (s)
19676 "Replace \"|\" with \"\\vert\"."
19677 (while (string-match "|" s)
19678 (setq s (replace-match "\\vert" t t s)))
19681 (defun org-uuidgen-p (s)
19682 "Is S an ID created by UUIDGEN?"
19683 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19685 (defun org-in-src-block-p nil
19686 "Whether point is in a code source block."
19687 (let (ov)
19688 (when (setq ov (overlays-at (point)))
19689 (memq 'org-block-background
19690 (overlay-properties
19691 (car ov))))))
19693 (defun org-context ()
19694 "Return a list of contexts of the current cursor position.
19695 If several contexts apply, all are returned.
19696 Each context entry is a list with a symbol naming the context, and
19697 two positions indicating start and end of the context. Possible
19698 contexts are:
19700 :headline anywhere in a headline
19701 :headline-stars on the leading stars in a headline
19702 :todo-keyword on a TODO keyword (including DONE) in a headline
19703 :tags on the TAGS in a headline
19704 :priority on the priority cookie in a headline
19705 :item on the first line of a plain list item
19706 :item-bullet on the bullet/number of a plain list item
19707 :checkbox on the checkbox in a plain list item
19708 :table in an org-mode table
19709 :table-special on a special filed in a table
19710 :table-table in a table.el table
19711 :clocktable in a clocktable
19712 :src-block in a source block
19713 :link on a hyperlink
19714 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19715 :target on a <<target>>
19716 :radio-target on a <<<radio-target>>>
19717 :latex-fragment on a LaTeX fragment
19718 :latex-preview on a LaTeX fragment with overlaid preview image
19720 This function expects the position to be visible because it uses font-lock
19721 faces as a help to recognize the following contexts: :table-special, :link,
19722 and :keyword."
19723 (let* ((f (get-text-property (point) 'face))
19724 (faces (if (listp f) f (list f)))
19725 (case-fold-search t)
19726 (p (point)) clist o)
19727 ;; First the large context
19728 (cond
19729 ((org-at-heading-p t)
19730 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19731 (when (progn
19732 (beginning-of-line 1)
19733 (looking-at org-todo-line-tags-regexp))
19734 (push (org-point-in-group p 1 :headline-stars) clist)
19735 (push (org-point-in-group p 2 :todo-keyword) clist)
19736 (push (org-point-in-group p 4 :tags) clist))
19737 (goto-char p)
19738 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19739 (if (looking-at "\\[#[A-Z0-9]\\]")
19740 (push (org-point-in-group p 0 :priority) clist)))
19742 ((org-at-item-p)
19743 (push (org-point-in-group p 2 :item-bullet) clist)
19744 (push (list :item (point-at-bol)
19745 (save-excursion (org-end-of-item) (point)))
19746 clist)
19747 (and (org-at-item-checkbox-p)
19748 (push (org-point-in-group p 0 :checkbox) clist)))
19750 ((org-at-table-p)
19751 (push (list :table (org-table-begin) (org-table-end)) clist)
19752 (if (memq 'org-formula faces)
19753 (push (list :table-special
19754 (previous-single-property-change p 'face)
19755 (next-single-property-change p 'face)) clist)))
19756 ((org-at-table-p 'any)
19757 (push (list :table-table) clist)))
19758 (goto-char p)
19760 ;; New the "medium" contexts: clocktables, source blocks
19761 (cond ((org-in-clocktable-p)
19762 (push (list :clocktable
19763 (and (or (looking-at "#\\+BEGIN: clocktable")
19764 (search-backward "#+BEGIN: clocktable" nil t))
19765 (match-beginning 0))
19766 (and (re-search-forward "#\\+END:?" nil t)
19767 (match-end 0))) clist))
19768 ((org-in-src-block-p)
19769 (push (list :src-block
19770 (and (or (looking-at "#\\+BEGIN_SRC")
19771 (search-backward "#+BEGIN_SRC" nil t))
19772 (match-beginning 0))
19773 (and (search-forward "#+END_SRC" nil t)
19774 (match-beginning 0))) clist)))
19775 (goto-char p)
19777 ;; Now the small context
19778 (cond
19779 ((org-at-timestamp-p)
19780 (push (org-point-in-group p 0 :timestamp) clist))
19781 ((memq 'org-link faces)
19782 (push (list :link
19783 (previous-single-property-change p 'face)
19784 (next-single-property-change p 'face)) clist))
19785 ((memq 'org-special-keyword faces)
19786 (push (list :keyword
19787 (previous-single-property-change p 'face)
19788 (next-single-property-change p 'face)) clist))
19789 ((org-at-target-p)
19790 (push (org-point-in-group p 0 :target) clist)
19791 (goto-char (1- (match-beginning 0)))
19792 (if (looking-at org-radio-target-regexp)
19793 (push (org-point-in-group p 0 :radio-target) clist))
19794 (goto-char p))
19795 ((setq o (car (delq nil
19796 (mapcar
19797 (lambda (x)
19798 (if (memq x org-latex-fragment-image-overlays) x))
19799 (overlays-at (point))))))
19800 (push (list :latex-fragment
19801 (overlay-start o) (overlay-end o)) clist)
19802 (push (list :latex-preview
19803 (overlay-start o) (overlay-end o)) clist))
19804 ((org-inside-LaTeX-fragment-p)
19805 ;; FIXME: positions wrong.
19806 (push (list :latex-fragment (point) (point)) clist)))
19808 (setq clist (nreverse (delq nil clist)))
19809 clist))
19811 ;; FIXME: Compare with at-regexp-p Do we need both?
19812 (defun org-in-regexp (re &optional nlines visually)
19813 "Check if point is inside a match of regexp.
19814 Normally only the current line is checked, but you can include NLINES extra
19815 lines both before and after point into the search.
19816 If VISUALLY is set, require that the cursor is not after the match but
19817 really on, so that the block visually is on the match."
19818 (catch 'exit
19819 (let ((pos (point))
19820 (eol (point-at-eol (+ 1 (or nlines 0))))
19821 (inc (if visually 1 0)))
19822 (save-excursion
19823 (beginning-of-line (- 1 (or nlines 0)))
19824 (while (re-search-forward re eol t)
19825 (if (and (<= (match-beginning 0) pos)
19826 (>= (+ inc (match-end 0)) pos))
19827 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19829 (defun org-at-regexp-p (regexp)
19830 "Is point inside a match of REGEXP in the current line?"
19831 (catch 'exit
19832 (save-excursion
19833 (let ((pos (point)) (end (point-at-eol)))
19834 (beginning-of-line 1)
19835 (while (re-search-forward regexp end t)
19836 (if (and (<= (match-beginning 0) pos)
19837 (>= (match-end 0) pos))
19838 (throw 'exit t)))
19839 nil))))
19841 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19842 "Non-nil when point is between matches of START-RE and END-RE.
19844 Also return a non-nil value when point is on one of the matches.
19846 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19847 buffer positions. Default values are the positions of headlines
19848 surrounding the point.
19850 The functions returns a cons cell whose car (resp. cdr) is the
19851 position before START-RE (resp. after END-RE)."
19852 (save-match-data
19853 (let ((pos (point))
19854 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19855 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19856 beg end)
19857 (save-excursion
19858 ;; Point is on a block when on START-RE or if START-RE can be
19859 ;; found before it...
19860 (and (or (org-at-regexp-p start-re)
19861 (re-search-backward start-re limit-up t))
19862 (setq beg (match-beginning 0))
19863 ;; ... and END-RE after it...
19864 (goto-char (match-end 0))
19865 (re-search-forward end-re limit-down t)
19866 (> (setq end (match-end 0)) pos)
19867 ;; ... without another START-RE in-between.
19868 (goto-char (match-beginning 0))
19869 (not (re-search-backward start-re (1+ beg) t))
19870 ;; Return value.
19871 (cons beg end))))))
19873 (defun org-in-block-p (names)
19874 "Non-nil when point belongs to a block whose name belongs to NAMES.
19876 NAMES is a list of strings containing names of blocks.
19878 Return first block name matched, or nil. Beware that in case of
19879 nested blocks, the returned name may not belong to the closest
19880 block from point."
19881 (save-match-data
19882 (catch 'exit
19883 (let ((case-fold-search t)
19884 (lim-up (save-excursion (outline-previous-heading)))
19885 (lim-down (save-excursion (outline-next-heading))))
19886 (mapc (lambda (name)
19887 (let ((n (regexp-quote name)))
19888 (when (org-between-regexps-p
19889 (concat "^[ \t]*#\\+begin_" n)
19890 (concat "^[ \t]*#\\+end_" n)
19891 lim-up lim-down)
19892 (throw 'exit n))))
19893 names))
19894 nil)))
19896 (defun org-occur-in-agenda-files (regexp &optional nlines)
19897 "Call `multi-occur' with buffers for all agenda files."
19898 (interactive "sOrg-files matching: \np")
19899 (let* ((files (org-agenda-files))
19900 (tnames (mapcar 'file-truename files))
19901 (extra org-agenda-text-search-extra-files)
19903 (when (eq (car extra) 'agenda-archives)
19904 (setq extra (cdr extra))
19905 (setq files (org-add-archive-files files)))
19906 (while (setq f (pop extra))
19907 (unless (member (file-truename f) tnames)
19908 (add-to-list 'files f 'append)
19909 (add-to-list 'tnames (file-truename f) 'append)))
19910 (multi-occur
19911 (mapcar (lambda (x)
19912 (with-current-buffer
19913 (or (get-file-buffer x) (find-file-noselect x))
19914 (widen)
19915 (current-buffer)))
19916 files)
19917 regexp)))
19919 (if (boundp 'occur-mode-find-occurrence-hook)
19920 ;; Emacs 23
19921 (add-hook 'occur-mode-find-occurrence-hook
19922 (lambda ()
19923 (when (eq major-mode 'org-mode)
19924 (org-reveal))))
19925 ;; Emacs 22
19926 (defadvice occur-mode-goto-occurrence
19927 (after org-occur-reveal activate)
19928 (and (eq major-mode 'org-mode) (org-reveal)))
19929 (defadvice occur-mode-goto-occurrence-other-window
19930 (after org-occur-reveal activate)
19931 (and (eq major-mode 'org-mode) (org-reveal)))
19932 (defadvice occur-mode-display-occurrence
19933 (after org-occur-reveal activate)
19934 (when (eq major-mode 'org-mode)
19935 (let ((pos (occur-mode-find-occurrence)))
19936 (with-current-buffer (marker-buffer pos)
19937 (save-excursion
19938 (goto-char pos)
19939 (org-reveal)))))))
19941 (defun org-occur-link-in-agenda-files ()
19942 "Create a link and search for it in the agendas.
19943 The link is not stored in `org-stored-links', it is just created
19944 for the search purpose."
19945 (interactive)
19946 (let ((link (condition-case nil
19947 (org-store-link nil)
19948 (error "Unable to create a link to here"))))
19949 (org-occur-in-agenda-files (regexp-quote link))))
19951 (defun org-uniquify (list)
19952 "Remove duplicate elements from LIST."
19953 (let (res)
19954 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19955 res))
19957 (defun org-delete-all (elts list)
19958 "Remove all elements in ELTS from LIST."
19959 (while elts
19960 (setq list (delete (pop elts) list)))
19961 list)
19963 (defun org-count (cl-item cl-seq)
19964 "Count the number of occurrences of ITEM in SEQ.
19965 Taken from `count' in cl-seq.el with all keyword arguments removed."
19966 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19967 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19968 (while (< cl-start cl-end)
19969 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19970 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19971 (setq cl-start (1+ cl-start)))
19972 cl-count))
19974 (defun org-remove-if (predicate seq)
19975 "Remove everything from SEQ that fulfills PREDICATE."
19976 (let (res e)
19977 (while seq
19978 (setq e (pop seq))
19979 (if (not (funcall predicate e)) (push e res)))
19980 (nreverse res)))
19982 (defun org-remove-if-not (predicate seq)
19983 "Remove everything from SEQ that does not fulfill PREDICATE."
19984 (let (res e)
19985 (while seq
19986 (setq e (pop seq))
19987 (if (funcall predicate e) (push e res)))
19988 (nreverse res)))
19990 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19991 "Reduce two-argument FUNCTION across SEQ.
19992 Taken from `reduce' in cl-seq.el with all keyword arguments but
19993 \":initial-value\" removed."
19994 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19995 (cadr (memq :initial-value cl-keys)))
19996 (cl-seq (pop cl-seq))
19997 (t (funcall cl-func)))))
19998 (while cl-seq
19999 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20000 cl-accum))
20002 (defun org-back-over-empty-lines ()
20003 "Move backwards over whitespace, to the beginning of the first empty line.
20004 Returns the number of empty lines passed."
20005 (let ((pos (point)))
20006 (if (cdr (assoc 'heading org-blank-before-new-entry))
20007 (skip-chars-backward " \t\n\r")
20008 (unless (eobp)
20009 (forward-line -1)))
20010 (beginning-of-line 2)
20011 (goto-char (min (point) pos))
20012 (count-lines (point) pos)))
20014 (defun org-skip-whitespace ()
20015 (skip-chars-forward " \t\n\r"))
20017 (defun org-point-in-group (point group &optional context)
20018 "Check if POINT is in match-group GROUP.
20019 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20020 match. If the match group does not exist or point is not inside it,
20021 return nil."
20022 (and (match-beginning group)
20023 (>= point (match-beginning group))
20024 (<= point (match-end group))
20025 (if context
20026 (list context (match-beginning group) (match-end group))
20027 t)))
20029 (defun org-switch-to-buffer-other-window (&rest args)
20030 "Switch to buffer in a second window on the current frame.
20031 In particular, do not allow pop-up frames.
20032 Returns the newly created buffer."
20033 (let (pop-up-frames special-display-buffer-names special-display-regexps
20034 special-display-function)
20035 (apply 'switch-to-buffer-other-window args)))
20037 (defun org-combine-plists (&rest plists)
20038 "Create a single property list from all plists in PLISTS.
20039 The process starts by copying the first list, and then setting properties
20040 from the other lists. Settings in the last list are the most significant
20041 ones and overrule settings in the other lists."
20042 (let ((rtn (copy-sequence (pop plists)))
20043 p v ls)
20044 (while plists
20045 (setq ls (pop plists))
20046 (while ls
20047 (setq p (pop ls) v (pop ls))
20048 (setq rtn (plist-put rtn p v))))
20049 rtn))
20051 (defun org-move-line-down (arg)
20052 "Move the current line down. With prefix argument, move it past ARG lines."
20053 (interactive "p")
20054 (let ((col (current-column))
20055 beg end pos)
20056 (beginning-of-line 1) (setq beg (point))
20057 (beginning-of-line 2) (setq end (point))
20058 (beginning-of-line (+ 1 arg))
20059 (setq pos (move-marker (make-marker) (point)))
20060 (insert (delete-and-extract-region beg end))
20061 (goto-char pos)
20062 (org-move-to-column col)))
20064 (defun org-move-line-up (arg)
20065 "Move the current line up. With prefix argument, move it past ARG lines."
20066 (interactive "p")
20067 (let ((col (current-column))
20068 beg end pos)
20069 (beginning-of-line 1) (setq beg (point))
20070 (beginning-of-line 2) (setq end (point))
20071 (beginning-of-line (- arg))
20072 (setq pos (move-marker (make-marker) (point)))
20073 (insert (delete-and-extract-region beg end))
20074 (goto-char pos)
20075 (org-move-to-column col)))
20077 (defun org-replace-escapes (string table)
20078 "Replace %-escapes in STRING with values in TABLE.
20079 TABLE is an association list with keys like \"%a\" and string values.
20080 The sequences in STRING may contain normal field width and padding information,
20081 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20082 so values can contain further %-escapes if they are define later in TABLE."
20083 (let ((tbl (copy-alist table))
20084 (case-fold-search nil)
20085 (pchg 0)
20086 e re rpl)
20087 (while (setq e (pop tbl))
20088 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20089 (when (and (cdr e) (string-match re (cdr e)))
20090 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20091 (safe "SREF"))
20092 (add-text-properties 0 3 (list 'sref sref) safe)
20093 (setcdr e (replace-match safe t t (cdr e)))))
20094 (while (string-match re string)
20095 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20096 (cdr e)))
20097 (setq string (replace-match rpl t t string))))
20098 (while (setq pchg (next-property-change pchg string))
20099 (let ((sref (get-text-property pchg 'sref string)))
20100 (when (and sref (string-match "SREF" string pchg))
20101 (setq string (replace-match sref t t string)))))
20102 string))
20104 (defun org-sublist (list start end)
20105 "Return a section of LIST, from START to END.
20106 Counting starts at 1."
20107 (let (rtn (c start))
20108 (setq list (nthcdr (1- start) list))
20109 (while (and list (<= c end))
20110 (push (pop list) rtn)
20111 (setq c (1+ c)))
20112 (nreverse rtn)))
20114 (defun org-find-base-buffer-visiting (file)
20115 "Like `find-buffer-visiting' but always return the base buffer and
20116 not an indirect buffer."
20117 (let ((buf (or (get-file-buffer file)
20118 (find-buffer-visiting file))))
20119 (if buf
20120 (or (buffer-base-buffer buf) buf)
20121 nil)))
20123 (defun org-image-file-name-regexp (&optional extensions)
20124 "Return regexp matching the file names of images.
20125 If EXTENSIONS is given, only match these."
20126 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20127 (image-file-name-regexp)
20128 (let ((image-file-name-extensions
20129 (or extensions
20130 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20131 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20132 (concat "\\."
20133 (regexp-opt (nconc (mapcar 'upcase
20134 image-file-name-extensions)
20135 image-file-name-extensions)
20137 "\\'"))))
20139 (defun org-file-image-p (file &optional extensions)
20140 "Return non-nil if FILE is an image."
20141 (save-match-data
20142 (string-match (org-image-file-name-regexp extensions) file)))
20144 (defun org-get-cursor-date ()
20145 "Return the date at cursor in as a time.
20146 This works in the calendar and in the agenda, anywhere else it just
20147 returns the current time."
20148 (let (date day defd)
20149 (cond
20150 ((eq major-mode 'calendar-mode)
20151 (setq date (calendar-cursor-to-date)
20152 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20153 ((eq major-mode 'org-agenda-mode)
20154 (setq day (get-text-property (point) 'day))
20155 (if day
20156 (setq date (calendar-gregorian-from-absolute day)
20157 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20158 (nth 2 date))))))
20159 (or defd (current-time))))
20161 (defvar org-agenda-action-marker (make-marker)
20162 "Marker pointing to the entry for the next agenda action.")
20164 (defun org-mark-entry-for-agenda-action ()
20165 "Mark the current entry as target of an agenda action.
20166 Agenda actions are actions executed from the agenda with the key `k',
20167 which make use of the date at the cursor."
20168 (interactive)
20169 (move-marker org-agenda-action-marker
20170 (save-excursion (org-back-to-heading t) (point))
20171 (current-buffer))
20172 (message
20173 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20175 (defun org-mark-subtree ()
20176 "Mark the current subtree.
20177 This puts point at the start of the current subtree, and mark at the end.
20179 If point is in an inline task, mark that task instead."
20180 (interactive)
20181 (let ((inline-task-p
20182 (and (featurep 'org-inlinetask)
20183 (org-inlinetask-in-task-p)))
20184 (beg))
20185 ;; Get beginning of subtree
20186 (cond
20187 (inline-task-p (org-inlinetask-goto-beginning))
20188 ((org-at-heading-p) (beginning-of-line))
20189 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20190 (setq beg (point))
20191 ;; Get end of it
20192 (if inline-task-p
20193 (org-inlinetask-goto-end)
20194 (org-end-of-subtree))
20195 ;; Mark zone
20196 (push-mark (point) nil t)
20197 (goto-char beg)))
20199 ;;; Paragraph filling stuff.
20200 ;; We want this to be just right, so use the full arsenal.
20202 (defun org-indent-line-function ()
20203 "Indent line depending on context."
20204 (interactive)
20205 (let* ((pos (point))
20206 (itemp (org-at-item-p))
20207 (case-fold-search t)
20208 (org-drawer-regexp (or org-drawer-regexp "\000"))
20209 (inline-task-p (and (featurep 'org-inlinetask)
20210 (org-inlinetask-in-task-p)))
20211 (inline-re (and inline-task-p
20212 (org-inlinetask-outline-regexp)))
20213 column)
20214 (beginning-of-line 1)
20215 (cond
20216 ;; Comments
20217 ((looking-at "# ") (setq column 0))
20218 ;; Headings
20219 ((looking-at org-outline-regexp) (setq column 0))
20220 ;; Included files
20221 ((looking-at "#\\+include:") (setq column 0))
20222 ;; Footnote definition
20223 ((looking-at org-footnote-definition-re) (setq column 0))
20224 ;; Literal examples
20225 ((looking-at "[ \t]*:\\( \\|$\\)")
20226 (setq column (org-get-indentation))) ; do nothing
20227 ;; Lists
20228 ((ignore-errors (goto-char (org-in-item-p)))
20229 (setq column (if itemp
20230 (org-get-indentation)
20231 (org-list-item-body-column (point))))
20232 (goto-char pos))
20233 ;; Drawers
20234 ((and (looking-at "[ \t]*:END:")
20235 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20236 (save-excursion
20237 (goto-char (1- (match-beginning 1)))
20238 (setq column (current-column))))
20239 ;; Special blocks
20240 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20241 (save-excursion
20242 (re-search-backward
20243 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20244 (setq column (org-get-indentation (match-string 0))))
20245 ((and (not (looking-at "[ \t]*#\\+begin_"))
20246 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20247 (save-excursion
20248 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20249 (setq column
20250 (cond ((equal (downcase (match-string 1)) "src")
20251 ;; src blocks: let `org-edit-src-exit' handle them
20252 (org-get-indentation))
20253 ((equal (downcase (match-string 1)) "example")
20254 (max (org-get-indentation)
20255 (org-get-indentation (match-string 0))))
20257 (org-get-indentation (match-string 0))))))
20258 ;; This line has nothing special, look at the previous relevant
20259 ;; line to compute indentation
20261 (beginning-of-line 0)
20262 (while (and (not (bobp))
20263 (not (looking-at org-drawer-regexp))
20264 ;; When point started in an inline task, do not move
20265 ;; above task starting line.
20266 (not (and inline-task-p (looking-at inline-re)))
20267 ;; Skip drawers, blocks, empty lines, verbatim,
20268 ;; comments, tables, footnotes definitions, lists,
20269 ;; inline tasks.
20270 (or (and (looking-at "[ \t]*:END:")
20271 (re-search-backward org-drawer-regexp nil t))
20272 (and (looking-at "[ \t]*#\\+end_")
20273 (re-search-backward "[ \t]*#\\+begin_"nil t))
20274 (looking-at "[ \t]*[\n:#|]")
20275 (looking-at org-footnote-definition-re)
20276 (and (ignore-errors (goto-char (org-in-item-p)))
20277 (goto-char
20278 (org-list-get-top-point (org-list-struct))))
20279 (and (not inline-task-p)
20280 (featurep 'org-inlinetask)
20281 (org-inlinetask-in-task-p)
20282 (or (org-inlinetask-goto-beginning) t))))
20283 (beginning-of-line 0))
20284 (cond
20285 ;; There was an heading above.
20286 ((looking-at "\\*+[ \t]+")
20287 (if (not org-adapt-indentation)
20288 (setq column 0)
20289 (goto-char (match-end 0))
20290 (setq column (current-column))))
20291 ;; A drawer had started and is unfinished
20292 ((looking-at org-drawer-regexp)
20293 (goto-char (1- (match-beginning 1)))
20294 (setq column (current-column)))
20295 ;; Else, nothing noticeable found: get indentation and go on.
20296 (t (setq column (org-get-indentation))))))
20297 ;; Now apply indentation and move cursor accordingly
20298 (goto-char pos)
20299 (if (<= (current-column) (current-indentation))
20300 (org-indent-line-to column)
20301 (save-excursion (org-indent-line-to column)))
20302 ;; Special polishing for properties, see `org-property-format'
20303 (setq column (current-column))
20304 (beginning-of-line 1)
20305 (if (looking-at
20306 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20307 (replace-match (concat (match-string 1)
20308 (format org-property-format
20309 (match-string 2) (match-string 3)))
20310 t t))
20311 (org-move-to-column column)))
20313 (defun org-indent-drawer ()
20314 "Indent the drawer at point."
20315 (interactive)
20316 (let ((p (point))
20317 (e (and (save-excursion (re-search-forward ":END:" nil t))
20318 (match-end 0)))
20319 (folded
20320 (save-excursion
20321 (end-of-line)
20322 (when (overlays-at (point))
20323 (member 'invisible (overlay-properties
20324 (car (overlays-at (point)))))))))
20325 (when folded (org-cycle))
20326 (indent-for-tab-command)
20327 (while (and (move-beginning-of-line 2) (< (point) e))
20328 (indent-for-tab-command))
20329 (goto-char p)
20330 (when folded (org-cycle)))
20331 (message "Drawer at point indented"))
20333 (defun org-indent-block ()
20334 "Indent the block at point."
20335 (interactive)
20336 (let ((p (point))
20337 (case-fold-search t)
20338 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20339 (match-end 0)))
20340 (folded
20341 (save-excursion
20342 (end-of-line)
20343 (when (overlays-at (point))
20344 (member 'invisible (overlay-properties
20345 (car (overlays-at (point)))))))))
20346 (when folded (org-cycle))
20347 (indent-for-tab-command)
20348 (while (and (move-beginning-of-line 2) (< (point) e))
20349 (indent-for-tab-command))
20350 (goto-char p)
20351 (when folded (org-cycle)))
20352 (message "Block at point indented"))
20354 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20355 "Variable to store copy of `adaptive-fill-regexp'.
20356 Since `adaptive-fill-regexp' is set to never match, we need to
20357 store a backup of its value before entering `org-mode' so that
20358 the functionality can be provided as a fall-back.")
20360 (defun org-set-autofill-regexps ()
20361 (interactive)
20362 ;; In the paragraph separator we include headlines, because filling
20363 ;; text in a line directly attached to a headline would otherwise
20364 ;; fill the headline as well.
20365 (org-set-local 'comment-start-skip "^#+[ \t]*")
20366 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20367 ;; The paragraph starter includes hand-formatted lists.
20368 (org-set-local
20369 'paragraph-start
20370 (concat
20371 "\f" "\\|"
20372 "[ ]*$" "\\|"
20373 org-outline-regexp "\\|"
20374 "[ \t]*#" "\\|"
20375 (org-item-re) "\\|"
20376 "[ \t]*[:|]" "\\|"
20377 "\\$\\$" "\\|"
20378 "\\\\\\(begin\\|end\\|[][]\\)"))
20379 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20380 ;; But only if the user has not turned off tables or fixed-width regions
20381 (org-set-local
20382 'auto-fill-inhibit-regexp
20383 (concat org-outline-regexp
20384 "\\|#\\+"
20385 "\\|[ \t]*" org-keyword-time-regexp
20386 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20387 (concat
20388 "\\|[ \t]*["
20389 (if org-enable-table-editor "|" "")
20390 (if org-enable-fixed-width-editor ":" "")
20391 "]"))))
20392 ;; We use our own fill-paragraph function, to make sure that tables
20393 ;; and fixed-width regions are not wrapped. That function will pass
20394 ;; through to `fill-paragraph' when appropriate.
20395 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20396 ;; Prevent auto-fill from inserting unwanted new items.
20397 (if (boundp 'fill-nobreak-predicate)
20398 (org-set-local
20399 'fill-nobreak-predicate
20400 (org-uniquify
20401 (append fill-nobreak-predicate
20402 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20403 ;; Adaptive filling: To get full control, first make sure that
20404 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20405 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20406 (org-set-local 'org-adaptive-fill-regexp-backup
20407 adaptive-fill-regexp))
20408 (org-set-local 'adaptive-fill-regexp "\000")
20409 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20410 (org-set-local 'adaptive-fill-function
20411 'org-adaptive-fill-function)
20412 (org-set-local
20413 'align-mode-rules-list
20414 '((org-in-buffer-settings
20415 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20416 (modes . '(org-mode))))))
20418 (defun org-fill-item-nobreak-p ()
20419 "Non-nil when a line break at point would insert a new item."
20420 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20422 (defun org-fill-line-break-nobreak-p ()
20423 "Non-nil when a line break at point would create an Org line break."
20424 (save-excursion
20425 (skip-chars-backward "[ \t]")
20426 (skip-chars-backward "\\\\")
20427 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20429 (defun org-fill-paragraph (&optional justify)
20430 "Re-align a table, pass through to fill-paragraph if no table."
20431 (let ((table-p (org-at-table-p))
20432 (table.el-p (org-at-table.el-p))
20433 (itemp (org-in-item-p)))
20434 (cond ((and (equal (char-after (point-at-bol)) ?*)
20435 (save-excursion (goto-char (point-at-bol))
20436 (looking-at org-outline-regexp)))
20437 t) ; skip headlines
20438 (table.el-p t) ; skip table.el tables
20439 (table-p (org-table-align) t) ; align Org tables
20440 (itemp ; align text in items
20441 (let* ((struct (save-excursion (goto-char itemp)
20442 (org-list-struct)))
20443 (parents (org-list-parents-alist struct))
20444 (children (org-list-get-children itemp struct parents))
20445 beg end prev next prefix)
20446 ;; Determine in which part of item point is: before
20447 ;; first child, after last child, between two
20448 ;; sub-lists, or simply in item if there's no child.
20449 (cond
20450 ((not children)
20451 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20452 beg itemp
20453 end (org-list-get-item-end itemp struct)))
20454 ((< (point) (setq next (car children)))
20455 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20456 beg itemp
20457 end next))
20458 ((> (point) (setq prev (car (last children))))
20459 (setq beg (org-list-get-item-end prev struct)
20460 end (org-list-get-item-end itemp struct)
20461 prefix (save-excursion
20462 (goto-char beg)
20463 (skip-chars-forward " \t")
20464 (make-string (current-column) ?\ ))))
20465 (t (catch 'exit
20466 (while (setq next (pop children))
20467 (if (> (point) next)
20468 (setq prev next)
20469 (setq beg (org-list-get-item-end prev struct)
20470 end next
20471 prefix (save-excursion
20472 (goto-char beg)
20473 (skip-chars-forward " \t")
20474 (make-string (current-column) ?\ )))
20475 (throw 'exit nil))))))
20476 ;; Use `fill-paragraph' with buffer narrowed to item
20477 ;; without any child, and with our computed PREFIX.
20478 (flet ((fill-context-prefix (from to &optional flr) prefix))
20479 (save-restriction
20480 (narrow-to-region beg end)
20481 (save-excursion (fill-paragraph justify)))) t))
20482 ;; Special case where point is not in a list but is on
20483 ;; a paragraph adjacent to a list: make sure this paragraph
20484 ;; doesn't get merged with the end of the list by narrowing
20485 ;; buffer first.
20486 ((save-excursion (forward-paragraph -1)
20487 (setq itemp (org-in-item-p)))
20488 (let ((struct (save-excursion (goto-char itemp)
20489 (org-list-struct))))
20490 (save-restriction
20491 (narrow-to-region (org-list-get-bottom-point struct)
20492 (save-excursion (forward-paragraph 1)
20493 (point)))
20494 (fill-paragraph justify) t)))
20495 ;; Else simply call `fill-paragraph'.
20496 (t nil))))
20498 ;; For reference, this is the default value of adaptive-fill-regexp
20499 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20501 (defun org-adaptive-fill-function ()
20502 "Return a fill prefix for org-mode files."
20503 (let (itemp)
20504 (save-excursion
20505 (cond
20506 ;; Comment line
20507 ((looking-at "#[ \t]+")
20508 (match-string-no-properties 0))
20509 ;; Plain list item
20510 ((org-at-item-p)
20511 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20512 ;; Point is in a list after `backward-paragraph': original
20513 ;; point wasn't in the list, or filling would have been taken
20514 ;; care of by `org-auto-fill-function', but the list and the
20515 ;; real paragraph are not separated by a blank line. Thus, move
20516 ;; point after the list to go back to real paragraph and
20517 ;; determine fill-prefix.
20518 ((setq itemp (org-in-item-p))
20519 (goto-char itemp)
20520 (let* ((struct (org-list-struct))
20521 (bottom (org-list-get-bottom-point struct)))
20522 (goto-char bottom)
20523 (make-string (org-get-indentation) ?\ )))
20524 ;; Other text
20525 ((looking-at org-adaptive-fill-regexp-backup)
20526 (match-string-no-properties 0))))))
20528 (defun org-auto-fill-function ()
20529 "Auto-fill function."
20530 (let (itemp prefix)
20531 ;; When in a list, compute an appropriate fill-prefix and make
20532 ;; sure it will be used by `do-auto-fill'.
20533 (if (setq itemp (org-in-item-p))
20534 (progn
20535 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20536 (flet ((fill-context-prefix (from to &optional flr) prefix))
20537 (do-auto-fill)))
20538 ;; Else just use `do-auto-fill'.
20539 (do-auto-fill))))
20541 ;;; Other stuff.
20543 (defun org-toggle-fixed-width-section (arg)
20544 "Toggle the fixed-width export.
20545 If there is no active region, the QUOTE keyword at the current headline is
20546 inserted or removed. When present, it causes the text between this headline
20547 and the next to be exported as fixed-width text, and unmodified.
20548 If there is an active region, this command adds or removes a colon as the
20549 first character of this line. If the first character of a line is a colon,
20550 this line is also exported in fixed-width font."
20551 (interactive "P")
20552 (let* ((cc 0)
20553 (regionp (org-region-active-p))
20554 (beg (if regionp (region-beginning) (point)))
20555 (end (if regionp (region-end)))
20556 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20557 (case-fold-search nil)
20558 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20559 off)
20560 (if regionp
20561 (save-excursion
20562 (goto-char beg)
20563 (setq cc (current-column))
20564 (beginning-of-line 1)
20565 (setq off (looking-at re))
20566 (while (> nlines 0)
20567 (setq nlines (1- nlines))
20568 (beginning-of-line 1)
20569 (cond
20570 (arg
20571 (org-move-to-column cc t)
20572 (insert ": \n")
20573 (forward-line -1))
20574 ((and off (looking-at re))
20575 (replace-match "" t t nil 1))
20576 ((not off) (org-move-to-column cc t) (insert ": ")))
20577 (forward-line 1)))
20578 (save-excursion
20579 (org-back-to-heading)
20580 (cond
20581 ((looking-at (format org-heading-keyword-regexp-format
20582 org-quote-string))
20583 (goto-char (match-end 1))
20584 (looking-at (concat " +" org-quote-string))
20585 (replace-match "" t t)
20586 (when (eolp) (insert " ")))
20587 ((looking-at org-outline-regexp)
20588 (goto-char (match-end 0))
20589 (insert org-quote-string " ")))))))
20591 (defun org-reftex-citation ()
20592 "Use reftex-citation to insert a citation into the buffer.
20593 This looks for a line like
20595 #+BIBLIOGRAPHY: foo plain option:-d
20597 and derives from it that foo.bib is the bibliography file relevant
20598 for this document. It then installs the necessary environment for RefTeX
20599 to work in this buffer and calls `reftex-citation' to insert a citation
20600 into the buffer.
20602 Export of such citations to both LaTeX and HTML is handled by the contributed
20603 package org-exp-bibtex by Taru Karttunen."
20604 (interactive)
20605 (let ((reftex-docstruct-symbol 'rds)
20606 (reftex-cite-format "\\cite{%l}")
20607 rds bib)
20608 (save-excursion
20609 (save-restriction
20610 (widen)
20611 (let ((case-fold-search t)
20612 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20613 (if (not (save-excursion
20614 (or (re-search-forward re nil t)
20615 (re-search-backward re nil t))))
20616 (error "No bibliography defined in file")
20617 (setq bib (concat (match-string 1) ".bib")
20618 rds (list (list 'bib bib)))))))
20619 (call-interactively 'reftex-citation)))
20621 ;;;; Functions extending outline functionality
20623 (defun org-beginning-of-line (&optional arg)
20624 "Go to the beginning of the current line. If that is invisible, continue
20625 to a visible line beginning. This makes the function of C-a more intuitive.
20626 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20627 first attempt, and only move to after the tags when the cursor is already
20628 beyond the end of the headline."
20629 (interactive "P")
20630 (let ((pos (point))
20631 (special (if (consp org-special-ctrl-a/e)
20632 (car org-special-ctrl-a/e)
20633 org-special-ctrl-a/e))
20634 refpos)
20635 (if (org-bound-and-true-p line-move-visual)
20636 (beginning-of-visual-line 1)
20637 (beginning-of-line 1))
20638 (if (and arg (fboundp 'move-beginning-of-line))
20639 (call-interactively 'move-beginning-of-line)
20640 (if (bobp)
20642 (backward-char 1)
20643 (if (org-truely-invisible-p)
20644 (while (and (not (bobp)) (org-truely-invisible-p))
20645 (backward-char 1)
20646 (beginning-of-line 1))
20647 (forward-char 1))))
20648 (when special
20649 (cond
20650 ((and (looking-at org-complex-heading-regexp)
20651 (= (char-after (match-end 1)) ?\ ))
20652 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20653 (point-at-eol)))
20654 (goto-char
20655 (if (eq special t)
20656 (cond ((> pos refpos) refpos)
20657 ((= pos (point)) refpos)
20658 (t (point)))
20659 (cond ((> pos (point)) (point))
20660 ((not (eq last-command this-command)) (point))
20661 (t refpos)))))
20662 ((org-at-item-p)
20663 ;; Being at an item and not looking at an the item means point
20664 ;; was previously moved to beginning of a visual line, whiche
20665 ;; doesn't contain the item. Therefore, do nothing special,
20666 ;; just stay here.
20667 (when (looking-at org-list-full-item-re)
20668 ;; Set special position at first white space character after
20669 ;; bullet, and check-box, if any.
20670 (let ((after-bullet
20671 (let ((box (match-end 3)))
20672 (if (not box) (match-end 1)
20673 (let ((after (char-after box)))
20674 (if (and after (= after ? )) (1+ box) box))))))
20675 ;; Special case: Move point to special position when
20676 ;; currently after it or at beginning of line.
20677 (if (eq special t)
20678 (when (or (> pos after-bullet) (= (point) pos))
20679 (goto-char after-bullet))
20680 ;; Reversed case: Move point to special position when
20681 ;; point was already at beginning of line and command is
20682 ;; repeated.
20683 (when (and (= (point) pos) (eq last-command this-command))
20684 (goto-char after-bullet))))))))
20685 (org-no-warnings
20686 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20688 (defun org-end-of-line (&optional arg)
20689 "Go to the end of the line.
20690 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20691 first attempt, and only move to after the tags when the cursor is already
20692 beyond the end of the headline."
20693 (interactive "P")
20694 (let ((special (if (consp org-special-ctrl-a/e)
20695 (cdr org-special-ctrl-a/e)
20696 org-special-ctrl-a/e)))
20697 (cond
20698 ((or (not special) arg
20699 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20700 (call-interactively
20701 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20702 ((fboundp 'move-end-of-line) 'move-end-of-line)
20703 (t 'end-of-line))))
20704 ((org-at-heading-p)
20705 (let ((pos (point)))
20706 (beginning-of-line 1)
20707 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20708 (if (eq special t)
20709 (if (or (< pos (match-beginning 1))
20710 (= pos (match-end 0)))
20711 (goto-char (match-beginning 1))
20712 (goto-char (match-end 0)))
20713 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20714 (goto-char (match-end 0))
20715 (goto-char (match-beginning 1))))
20716 (call-interactively (if (fboundp 'move-end-of-line)
20717 'move-end-of-line
20718 'end-of-line)))))
20719 ((org-at-drawer-p)
20720 (move-end-of-line 1)
20721 (when (overlays-at (1- (point))) (backward-char 1)))
20722 ;; At an item: Move before any hidden text.
20723 (t (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-no-warnings
20728 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20730 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20731 (define-key org-mode-map "\C-e" 'org-end-of-line)
20733 (defun org-backward-sentence (&optional arg)
20734 "Go to beginning of sentence, or beginning of table field.
20735 This will call `backward-sentence' or `org-table-beginning-of-field',
20736 depending on context."
20737 (interactive "P")
20738 (cond
20739 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20740 (t (call-interactively 'backward-sentence))))
20742 (defun org-forward-sentence (&optional arg)
20743 "Go to end of sentence, or end of table field.
20744 This will call `forward-sentence' or `org-table-end-of-field',
20745 depending on context."
20746 (interactive "P")
20747 (cond
20748 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20749 (t (call-interactively 'forward-sentence))))
20751 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20752 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20754 (defun org-kill-line (&optional arg)
20755 "Kill line, to tags or end of line."
20756 (interactive "P")
20757 (cond
20758 ((or (not org-special-ctrl-k)
20759 (bolp)
20760 (not (org-at-heading-p)))
20761 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20762 org-ctrl-k-protect-subtree)
20763 (if (or (eq org-ctrl-k-protect-subtree 'error)
20764 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20765 (error "C-k aborted - would kill hidden subtree")))
20766 (call-interactively
20767 (if visual-line-mode 'kill-visual-line 'kill-line)))
20768 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20769 (kill-region (point) (match-beginning 1))
20770 (org-set-tags nil t))
20771 (t (kill-region (point) (point-at-eol)))))
20773 (define-key org-mode-map "\C-k" 'org-kill-line)
20775 (defun org-yank (&optional arg)
20776 "Yank. If the kill is a subtree, treat it specially.
20777 This command will look at the current kill and check if is a single
20778 subtree, or a series of subtrees[1]. If it passes the test, and if the
20779 cursor is at the beginning of a line or after the stars of a currently
20780 empty headline, then the yank is handled specially. How exactly depends
20781 on the value of the following variables, both set by default.
20783 org-yank-folded-subtrees
20784 When set, the subtree(s) will be folded after insertion, but only
20785 if doing so would now swallow text after the yanked text.
20787 org-yank-adjusted-subtrees
20788 When set, the subtree will be promoted or demoted in order to
20789 fit into the local outline tree structure, which means that the level
20790 will be adjusted so that it becomes the smaller one of the two
20791 *visible* surrounding headings.
20793 Any prefix to this command will cause `yank' to be called directly with
20794 no special treatment. In particular, a simple \\[universal-argument] prefix \
20795 will just
20796 plainly yank the text as it is.
20798 \[1] The test checks if the first non-white line is a heading
20799 and if there are no other headings with fewer stars."
20800 (interactive "P")
20801 (org-yank-generic 'yank arg))
20803 (defun org-yank-generic (command arg)
20804 "Perform some yank-like command.
20806 This function implements the behavior described in the `org-yank'
20807 documentation. However, it has been generalized to work for any
20808 interactive command with similar behavior."
20810 ;; pretend to be command COMMAND
20811 (setq this-command command)
20813 (if arg
20814 (call-interactively command)
20816 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20817 (and (org-kill-is-subtree-p)
20818 (or (bolp)
20819 (and (looking-at "[ \t]*$")
20820 (string-match
20821 "\\`\\*+\\'"
20822 (buffer-substring (point-at-bol) (point)))))))
20823 swallowp)
20824 (cond
20825 ((and subtreep org-yank-folded-subtrees)
20826 (let ((beg (point))
20827 end)
20828 (if (and subtreep org-yank-adjusted-subtrees)
20829 (org-paste-subtree nil nil 'for-yank)
20830 (call-interactively command))
20832 (setq end (point))
20833 (goto-char beg)
20834 (when (and (bolp) subtreep
20835 (not (setq swallowp
20836 (org-yank-folding-would-swallow-text beg end))))
20837 (org-with-limited-levels
20838 (or (looking-at org-outline-regexp)
20839 (re-search-forward org-outline-regexp-bol end t))
20840 (while (and (< (point) end) (looking-at org-outline-regexp))
20841 (hide-subtree)
20842 (org-cycle-show-empty-lines 'folded)
20843 (condition-case nil
20844 (outline-forward-same-level 1)
20845 (error (goto-char end))))))
20846 (when swallowp
20847 (message
20848 "Inserted text not folded because that would swallow text"))
20850 (goto-char end)
20851 (skip-chars-forward " \t\n\r")
20852 (beginning-of-line 1)
20853 (push-mark beg 'nomsg)))
20854 ((and subtreep org-yank-adjusted-subtrees)
20855 (let ((beg (point-at-bol)))
20856 (org-paste-subtree nil nil 'for-yank)
20857 (push-mark beg 'nomsg)))
20859 (call-interactively command))))))
20861 (defun org-yank-folding-would-swallow-text (beg end)
20862 "Would hide-subtree at BEG swallow any text after END?"
20863 (let (level)
20864 (org-with-limited-levels
20865 (save-excursion
20866 (goto-char beg)
20867 (when (or (looking-at org-outline-regexp)
20868 (re-search-forward org-outline-regexp-bol end t))
20869 (setq level (org-outline-level)))
20870 (goto-char end)
20871 (skip-chars-forward " \t\r\n\v\f")
20872 (if (or (eobp)
20873 (and (bolp) (looking-at org-outline-regexp)
20874 (<= (org-outline-level) level)))
20875 nil ; Nothing would be swallowed
20876 t))))) ; something would swallow
20878 (define-key org-mode-map "\C-y" 'org-yank)
20880 (defun org-truely-invisible-p ()
20881 "Check if point is at a character currently not visible.
20882 This version does not only check the character property, but also
20883 `visible-mode'."
20884 ;; Early versions of noutline don't have `outline-invisible-p'.
20885 (if (org-bound-and-true-p visible-mode)
20887 (outline-invisible-p)))
20889 (defun org-invisible-p2 ()
20890 "Check if point is at a character currently not visible."
20891 (save-excursion
20892 (if (and (eolp) (not (bobp))) (backward-char 1))
20893 ;; Early versions of noutline don't have `outline-invisible-p'.
20894 (outline-invisible-p)))
20896 (defun org-back-to-heading (&optional invisible-ok)
20897 "Call `outline-back-to-heading', but provide a better error message."
20898 (condition-case nil
20899 (outline-back-to-heading invisible-ok)
20900 (error (error "Before first headline at position %d in buffer %s"
20901 (point) (current-buffer)))))
20903 (defun org-beginning-of-defun ()
20904 "Go to the beginning of the subtree, i.e. back to the heading."
20905 (org-back-to-heading))
20906 (defun org-end-of-defun ()
20907 "Go to the end of the subtree."
20908 (org-end-of-subtree nil t))
20910 (defun org-before-first-heading-p ()
20911 "Before first heading?"
20912 (save-excursion
20913 (end-of-line)
20914 (null (re-search-backward org-outline-regexp-bol nil t))))
20916 (defun org-at-heading-p (&optional ignored)
20917 (outline-on-heading-p t))
20918 ;; Compatibility alias with Org versions < 7.8.03
20919 (defalias 'org-on-heading-p 'org-at-heading-p)
20921 (defun org-at-drawer-p nil
20922 "Is cursor at a drawer keyword?"
20923 (save-excursion
20924 (move-beginning-of-line 1)
20925 (looking-at org-drawer-regexp)))
20927 (defun org-at-block-p nil
20928 "Is cursor at a block keyword?"
20929 (save-excursion
20930 (move-beginning-of-line 1)
20931 (looking-at org-block-regexp)))
20933 (defun org-point-at-end-of-empty-headline ()
20934 "If point is at the end of an empty headline, return t, else nil.
20935 If the heading only contains a TODO keyword, it is still still considered
20936 empty."
20937 (and (looking-at "[ \t]*$")
20938 (save-excursion
20939 (beginning-of-line 1)
20940 (let ((case-fold-search nil))
20941 (looking-at org-todo-line-regexp)))
20942 (string= (match-string 3) "")))
20944 (defun org-at-heading-or-item-p ()
20945 (or (org-at-heading-p) (org-at-item-p)))
20947 (defun org-at-target-p ()
20948 (or (org-in-regexp org-radio-target-regexp)
20949 (org-in-regexp org-target-regexp)))
20950 ;; Compatibility alias with Org versions < 7.8.03
20951 (defalias 'org-on-target-p 'org-at-target-p)
20953 (defun org-up-heading-all (arg)
20954 "Move to the heading line of which the present line is a subheading.
20955 This function considers both visible and invisible heading lines.
20956 With argument, move up ARG levels."
20957 (if (fboundp 'outline-up-heading-all)
20958 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20959 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20961 (defun org-up-heading-safe ()
20962 "Move to the heading line of which the present line is a subheading.
20963 This version will not throw an error. It will return the level of the
20964 headline found, or nil if no higher level is found.
20966 Also, this function will be a lot faster than `outline-up-heading',
20967 because it relies on stars being the outline starters. This can really
20968 make a significant difference in outlines with very many siblings."
20969 (let (start-level re)
20970 (org-back-to-heading t)
20971 (setq start-level (funcall outline-level))
20972 (if (equal start-level 1)
20974 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20975 (if (re-search-backward re nil t)
20976 (funcall outline-level)))))
20978 (defun org-first-sibling-p ()
20979 "Is this heading the first child of its parents?"
20980 (interactive)
20981 (let ((re org-outline-regexp-bol)
20982 level l)
20983 (unless (org-at-heading-p t)
20984 (error "Not at a heading"))
20985 (setq level (funcall outline-level))
20986 (save-excursion
20987 (if (not (re-search-backward re nil t))
20989 (setq l (funcall outline-level))
20990 (< l level)))))
20992 (defun org-goto-sibling (&optional previous)
20993 "Goto the next sibling, even if it is invisible.
20994 When PREVIOUS is set, go to the previous sibling instead. Returns t
20995 when a sibling was found. When none is found, return nil and don't
20996 move point."
20997 (let ((fun (if previous 're-search-backward 're-search-forward))
20998 (pos (point))
20999 (re org-outline-regexp-bol)
21000 level l)
21001 (when (condition-case nil (org-back-to-heading t) (error nil))
21002 (setq level (funcall outline-level))
21003 (catch 'exit
21004 (or previous (forward-char 1))
21005 (while (funcall fun re nil t)
21006 (setq l (funcall outline-level))
21007 (when (< l level) (goto-char pos) (throw 'exit nil))
21008 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21009 (goto-char pos)
21010 nil))))
21012 (defun org-show-siblings ()
21013 "Show all siblings of the current headline."
21014 (save-excursion
21015 (while (org-goto-sibling) (org-flag-heading nil)))
21016 (save-excursion
21017 (while (org-goto-sibling 'previous)
21018 (org-flag-heading nil))))
21020 (defun org-goto-first-child ()
21021 "Goto the first child, even if it is invisible.
21022 Return t when a child was found. Otherwise don't move point and
21023 return nil."
21024 (let (level (pos (point)) (re org-outline-regexp-bol))
21025 (when (condition-case nil (org-back-to-heading t) (error nil))
21026 (setq level (outline-level))
21027 (forward-char 1)
21028 (if (and (re-search-forward re nil t) (> (outline-level) level))
21029 (progn (goto-char (match-beginning 0)) t)
21030 (goto-char pos) nil))))
21032 (defun org-show-hidden-entry ()
21033 "Show an entry where even the heading is hidden."
21034 (save-excursion
21035 (org-show-entry)))
21037 (defun org-flag-heading (flag &optional entry)
21038 "Flag the current heading. FLAG non-nil means make invisible.
21039 When ENTRY is non-nil, show the entire entry."
21040 (save-excursion
21041 (org-back-to-heading t)
21042 ;; Check if we should show the entire entry
21043 (if entry
21044 (progn
21045 (org-show-entry)
21046 (save-excursion
21047 (and (outline-next-heading)
21048 (org-flag-heading nil))))
21049 (outline-flag-region (max (point-min) (1- (point)))
21050 (save-excursion (outline-end-of-heading) (point))
21051 flag))))
21053 (defun org-get-next-sibling ()
21054 "Move to next heading of the same level, and return point.
21055 If there is no such heading, return nil.
21056 This is like outline-next-sibling, but invisible headings are ok."
21057 (let ((level (funcall outline-level)))
21058 (outline-next-heading)
21059 (while (and (not (eobp)) (> (funcall outline-level) level))
21060 (outline-next-heading))
21061 (if (or (eobp) (< (funcall outline-level) level))
21063 (point))))
21065 (defun org-get-last-sibling ()
21066 "Move to previous heading of the same level, and return point.
21067 If there is no such heading, return nil."
21068 (let ((opoint (point))
21069 (level (funcall outline-level)))
21070 (outline-previous-heading)
21071 (when (and (/= (point) opoint) (outline-on-heading-p t))
21072 (while (and (> (funcall outline-level) level)
21073 (not (bobp)))
21074 (outline-previous-heading))
21075 (if (< (funcall outline-level) level)
21077 (point)))))
21079 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21080 ;; This contains an exact copy of the original function, but it uses
21081 ;; `org-back-to-heading', to make it work also in invisible
21082 ;; trees. And is uses an invisible-OK argument.
21083 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21084 ;; Furthermore, when used inside Org, finding the end of a large subtree
21085 ;; with many children and grandchildren etc, this can be much faster
21086 ;; than the outline version.
21087 (org-back-to-heading invisible-OK)
21088 (let ((first t)
21089 (level (funcall outline-level)))
21090 (if (and (eq major-mode 'org-mode) (< level 1000))
21091 ;; A true heading (not a plain list item), in Org-mode
21092 ;; This means we can easily find the end by looking
21093 ;; only for the right number of stars. Using a regexp to do
21094 ;; this is so much faster than using a Lisp loop.
21095 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21096 (forward-char 1)
21097 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21098 ;; something else, do it the slow way
21099 (while (and (not (eobp))
21100 (or first (> (funcall outline-level) level)))
21101 (setq first nil)
21102 (outline-next-heading)))
21103 (unless to-heading
21104 (if (memq (preceding-char) '(?\n ?\^M))
21105 (progn
21106 ;; Go to end of line before heading
21107 (forward-char -1)
21108 (if (memq (preceding-char) '(?\n ?\^M))
21109 ;; leave blank line before heading
21110 (forward-char -1))))))
21111 (point))
21113 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21114 "Use Org version in org-mode, for dramatic speed-up."
21115 (if (eq major-mode 'org-mode)
21116 (progn
21117 (org-end-of-subtree nil t)
21118 (unless (eobp) (backward-char 1)))
21119 ad-do-it))
21121 (defun org-end-of-meta-data-and-drawers ()
21122 "Jump to the first text after meta data and drawers in the current entry.
21123 This will move over empty lines, lines with planning time stamps,
21124 clocking lines, and drawers."
21125 (org-back-to-heading t)
21126 (let ((end (save-excursion (outline-next-heading) (point)))
21127 (re (concat "\\(" org-drawer-regexp "\\)"
21128 "\\|" "[ \t]*" org-keyword-time-regexp)))
21129 (forward-line 1)
21130 (while (re-search-forward re end t)
21131 (if (not (match-end 1))
21132 ;; empty or planning line
21133 (forward-line 1)
21134 ;; a drawer, find the end
21135 (re-search-forward "^[ \t]*:END:" end 'move)
21136 (forward-line 1)))
21137 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21138 (point)))
21140 (defun org-forward-same-level (arg &optional invisible-ok)
21141 "Move forward to the arg'th subheading at same level as this one.
21142 Stop at the first and last subheadings of a superior heading.
21143 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21144 it wil also look at invisible ones."
21145 (interactive "p")
21146 (org-back-to-heading invisible-ok)
21147 (org-at-heading-p)
21148 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21149 (re (format "^\\*\\{1,%d\\} " level))
21151 (forward-char 1)
21152 (while (> arg 0)
21153 (while (and (re-search-forward re nil 'move)
21154 (setq l (- (match-end 0) (match-beginning 0) 1))
21155 (= l level)
21156 (not invisible-ok)
21157 (progn (backward-char 1) (outline-invisible-p)))
21158 (if (< l level) (setq arg 1)))
21159 (setq arg (1- arg)))
21160 (beginning-of-line 1)))
21162 (defun org-backward-same-level (arg &optional invisible-ok)
21163 "Move backward to the arg'th subheading at same level as this one.
21164 Stop at the first and last subheadings of a superior heading."
21165 (interactive "p")
21166 (org-back-to-heading)
21167 (org-at-heading-p)
21168 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21169 (re (format "^\\*\\{1,%d\\} " level))
21171 (while (> arg 0)
21172 (while (and (re-search-backward re nil 'move)
21173 (setq l (- (match-end 0) (match-beginning 0) 1))
21174 (= l level)
21175 (not invisible-ok)
21176 (outline-invisible-p))
21177 (if (< l level) (setq arg 1)))
21178 (setq arg (1- arg)))))
21180 (defun org-show-subtree ()
21181 "Show everything after this heading at deeper levels."
21182 (outline-flag-region
21183 (point)
21184 (save-excursion
21185 (org-end-of-subtree t t))
21186 nil))
21188 (defun org-show-entry ()
21189 "Show the body directly following this heading.
21190 Show the heading too, if it is currently invisible."
21191 (interactive)
21192 (save-excursion
21193 (condition-case nil
21194 (progn
21195 (org-back-to-heading t)
21196 (outline-flag-region
21197 (max (point-min) (1- (point)))
21198 (save-excursion
21199 (if (re-search-forward
21200 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21201 (match-beginning 1)
21202 (point-max)))
21203 nil)
21204 (org-cycle-hide-drawers 'children))
21205 (error nil))))
21207 (defun org-make-options-regexp (kwds &optional extra)
21208 "Make a regular expression for keyword lines."
21209 (concat
21211 "#?[ \t]*\\+\\("
21212 (mapconcat 'regexp-quote kwds "\\|")
21213 (if extra (concat "\\|" extra))
21214 "\\):[ \t]*"
21215 "\\(.*\\)"))
21217 ;; Make isearch reveal the necessary context
21218 (defun org-isearch-end ()
21219 "Reveal context after isearch exits."
21220 (when isearch-success ; only if search was successful
21221 (if (featurep 'xemacs)
21222 ;; Under XEmacs, the hook is run in the correct place,
21223 ;; we directly show the context.
21224 (org-show-context 'isearch)
21225 ;; In Emacs the hook runs *before* restoring the overlays.
21226 ;; So we have to use a one-time post-command-hook to do this.
21227 ;; (Emacs 22 has a special variable, see function `org-mode')
21228 (unless (and (boundp 'isearch-mode-end-hook-quit)
21229 isearch-mode-end-hook-quit)
21230 ;; Only when the isearch was not quitted.
21231 (org-add-hook 'post-command-hook 'org-isearch-post-command
21232 'append 'local)))))
21234 (defun org-isearch-post-command ()
21235 "Remove self from hook, and show context."
21236 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21237 (org-show-context 'isearch))
21240 ;;;; Integration with and fixes for other packages
21242 ;;; Imenu support
21244 (defvar org-imenu-markers nil
21245 "All markers currently used by Imenu.")
21246 (make-variable-buffer-local 'org-imenu-markers)
21248 (defun org-imenu-new-marker (&optional pos)
21249 "Return a new marker for use by Imenu, and remember the marker."
21250 (let ((m (make-marker)))
21251 (move-marker m (or pos (point)))
21252 (push m org-imenu-markers)
21255 (defun org-imenu-get-tree ()
21256 "Produce the index for Imenu."
21257 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21258 (setq org-imenu-markers nil)
21259 (let* ((n org-imenu-depth)
21260 (re (concat "^" (org-get-limited-outline-regexp)))
21261 (subs (make-vector (1+ n) nil))
21262 (last-level 0)
21263 m level head)
21264 (save-excursion
21265 (save-restriction
21266 (widen)
21267 (goto-char (point-max))
21268 (while (re-search-backward re nil t)
21269 (setq level (org-reduced-level (funcall outline-level)))
21270 (when (<= level n)
21271 (looking-at org-complex-heading-regexp)
21272 (setq head (org-link-display-format
21273 (org-match-string-no-properties 4))
21274 m (org-imenu-new-marker))
21275 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21276 (if (>= level last-level)
21277 (push (cons head m) (aref subs level))
21278 (push (cons head (aref subs (1+ level))) (aref subs level))
21279 (loop for i from (1+ level) to n do (aset subs i nil)))
21280 (setq last-level level)))))
21281 (aref subs 1)))
21283 (eval-after-load "imenu"
21284 '(progn
21285 (add-hook 'imenu-after-jump-hook
21286 (lambda ()
21287 (if (eq major-mode 'org-mode)
21288 (org-show-context 'org-goto))))))
21290 (defun org-link-display-format (link)
21291 "Replace a link with either the description, or the link target
21292 if no description is present"
21293 (save-match-data
21294 (if (string-match org-bracket-link-analytic-regexp link)
21295 (replace-match (if (match-end 5)
21296 (match-string 5 link)
21297 (concat (match-string 1 link)
21298 (match-string 3 link)))
21299 nil t link)
21300 link)))
21302 (defun org-toggle-link-display ()
21303 "Toggle the literal or descriptive display of links."
21304 (interactive)
21305 (if org-descriptive-links
21306 (progn (org-remove-from-invisibility-spec '(org-link))
21307 (org-restart-font-lock)
21308 (setq org-descriptive-links nil))
21309 (progn (add-to-invisibility-spec '(org-link))
21310 (org-restart-font-lock)
21311 (setq org-descriptive-links t))))
21313 ;; Speedbar support
21315 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21316 "Overlay marking the agenda restriction line in speedbar.")
21317 (overlay-put org-speedbar-restriction-lock-overlay
21318 'face 'org-agenda-restriction-lock)
21319 (overlay-put org-speedbar-restriction-lock-overlay
21320 'help-echo "Agendas are currently limited to this item.")
21321 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21323 (defun org-speedbar-set-agenda-restriction ()
21324 "Restrict future agenda commands to the location at point in speedbar.
21325 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21326 (interactive)
21327 (require 'org-agenda)
21328 (let (p m tp np dir txt)
21329 (cond
21330 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21331 'org-imenu t))
21332 (setq m (get-text-property p 'org-imenu-marker))
21333 (with-current-buffer (marker-buffer m)
21334 (goto-char m)
21335 (org-agenda-set-restriction-lock 'subtree)))
21336 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21337 'speedbar-function 'speedbar-find-file))
21338 (setq tp (previous-single-property-change
21339 (1+ p) 'speedbar-function)
21340 np (next-single-property-change
21341 tp 'speedbar-function)
21342 dir (speedbar-line-directory)
21343 txt (buffer-substring-no-properties (or tp (point-min))
21344 (or np (point-max))))
21345 (with-current-buffer (find-file-noselect
21346 (let ((default-directory dir))
21347 (expand-file-name txt)))
21348 (unless (eq major-mode 'org-mode)
21349 (error "Cannot restrict to non-Org-mode file"))
21350 (org-agenda-set-restriction-lock 'file)))
21351 (t (error "Don't know how to restrict Org-mode's agenda")))
21352 (move-overlay org-speedbar-restriction-lock-overlay
21353 (point-at-bol) (point-at-eol))
21354 (setq current-prefix-arg nil)
21355 (org-agenda-maybe-redo)))
21357 (eval-after-load "speedbar"
21358 '(progn
21359 (speedbar-add-supported-extension ".org")
21360 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21361 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21362 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21363 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21364 (add-hook 'speedbar-visiting-tag-hook
21365 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21367 ;;; Fixes and Hacks for problems with other packages
21369 ;; Make flyspell not check words in links, to not mess up our keymap
21370 (defun org-mode-flyspell-verify ()
21371 "Don't let flyspell put overlays at active buttons, or on
21372 {todo,all-time,additional-option-like}-keywords."
21373 (let ((pos (max (1- (point)) (point-min)))
21374 (word (thing-at-point 'word)))
21375 (and (not (get-text-property pos 'keymap))
21376 (not (get-text-property pos 'org-no-flyspell))
21377 (not (member word org-todo-keywords-1))
21378 (not (member word org-all-time-keywords))
21379 (not (member word org-additional-option-like-keywords)))))
21381 (defun org-remove-flyspell-overlays-in (beg end)
21382 "Remove flyspell overlays in region."
21383 (and (org-bound-and-true-p flyspell-mode)
21384 (fboundp 'flyspell-delete-region-overlays)
21385 (flyspell-delete-region-overlays beg end))
21386 (add-text-properties beg end '(org-no-flyspell t)))
21388 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21389 (eval-after-load "bookmark"
21390 '(if (boundp 'bookmark-after-jump-hook)
21391 ;; We can use the hook
21392 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21393 ;; Hook not available, use advice
21394 (defadvice bookmark-jump (after org-make-visible activate)
21395 "Make the position visible."
21396 (org-bookmark-jump-unhide))))
21398 ;; Make sure saveplace shows the location if it was hidden
21399 (eval-after-load "saveplace"
21400 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21401 "Make the position visible."
21402 (org-bookmark-jump-unhide)))
21404 ;; Make sure ecb shows the location if it was hidden
21405 (eval-after-load "ecb"
21406 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21407 "Make hierarchy visible when jumping into location from ECB tree buffer."
21408 (if (eq major-mode 'org-mode)
21409 (org-show-context))))
21411 (defun org-bookmark-jump-unhide ()
21412 "Unhide the current position, to show the bookmark location."
21413 (and (eq major-mode 'org-mode)
21414 (or (outline-invisible-p)
21415 (save-excursion (goto-char (max (point-min) (1- (point))))
21416 (outline-invisible-p)))
21417 (org-show-context 'bookmark-jump)))
21419 ;; Make session.el ignore our circular variable
21420 (eval-after-load "session"
21421 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21423 ;;;; Experimental code
21425 (defun org-closed-in-range ()
21426 "Sparse tree of items closed in a certain time range.
21427 Still experimental, may disappear in the future."
21428 (interactive)
21429 ;; Get the time interval from the user.
21430 (let* ((time1 (org-float-time
21431 (org-read-date nil 'to-time nil "Starting date: ")))
21432 (time2 (org-float-time
21433 (org-read-date nil 'to-time nil "End date:")))
21434 ;; callback function
21435 (callback (lambda ()
21436 (let ((time
21437 (org-float-time
21438 (apply 'encode-time
21439 (org-parse-time-string
21440 (match-string 1))))))
21441 ;; check if time in interval
21442 (and (>= time time1) (<= time time2))))))
21443 ;; make tree, check each match with the callback
21444 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21446 ;;;; Finish up
21448 (provide 'org)
21450 (run-hooks 'org-load-hook)
21452 ;;; org.el ends here